1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use gpui::{
74 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
75 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
76 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
77 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
78 ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
79 Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
80 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
81 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
82};
83use highlight_matching_bracket::refresh_matching_bracket_highlights;
84use hover_popover::{hide_hover, HoverState};
85pub(crate) use hunk_diff::HoveredHunk;
86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
87use indent_guides::ActiveIndentGuidesState;
88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
89pub use inline_completion_provider::*;
90pub use items::MAX_TAB_TITLE_LEN;
91use itertools::Itertools;
92use language::{
93 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{
99 point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
100};
101use linked_editing_ranges::refresh_linked_ranges;
102pub use proposed_changes_editor::{
103 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
104};
105use similar::{ChangeTag, TextDiff};
106use std::iter::Peekable;
107use task::{ResolvedTask, TaskTemplate, TaskVariables};
108
109use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
110pub use lsp::CompletionContext;
111use lsp::{
112 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
113 LanguageServerId,
114};
115use mouse_context_menu::MouseContextMenu;
116use movement::TextLayoutDetails;
117pub use multi_buffer::{
118 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
119 ToPoint,
120};
121use multi_buffer::{
122 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
123};
124use ordered_float::OrderedFloat;
125use parking_lot::{Mutex, RwLock};
126use project::{
127 lsp_store::{FormatTarget, FormatTrigger},
128 project_settings::{GitGutterSetting, ProjectSettings},
129 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
130 LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
131};
132use rand::prelude::*;
133use rpc::{proto::*, ErrorExt};
134use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
135use selections_collection::{
136 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
137};
138use serde::{Deserialize, Serialize};
139use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
140use smallvec::SmallVec;
141use snippet::Snippet;
142use std::{
143 any::TypeId,
144 borrow::Cow,
145 cell::RefCell,
146 cmp::{self, Ordering, Reverse},
147 mem,
148 num::NonZeroU32,
149 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
150 path::{Path, PathBuf},
151 rc::Rc,
152 sync::Arc,
153 time::{Duration, Instant},
154};
155pub use sum_tree::Bias;
156use sum_tree::TreeMap;
157use text::{BufferId, OffsetUtf16, Rope};
158use theme::{
159 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
160 ThemeColors, ThemeSettings,
161};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 ListItem, Popover, PopoverMenuHandle, Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::find_url;
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188#[doc(hidden)]
189pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
190
191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
193
194pub fn render_parsed_markdown(
195 element_id: impl Into<ElementId>,
196 parsed: &language::ParsedMarkdown,
197 editor_style: &EditorStyle,
198 workspace: Option<WeakView<Workspace>>,
199 cx: &mut WindowContext,
200) -> InteractiveText {
201 let code_span_background_color = cx
202 .theme()
203 .colors()
204 .editor_document_highlight_read_background;
205
206 let highlights = gpui::combine_highlights(
207 parsed.highlights.iter().filter_map(|(range, highlight)| {
208 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
209 Some((range.clone(), highlight))
210 }),
211 parsed
212 .regions
213 .iter()
214 .zip(&parsed.region_ranges)
215 .filter_map(|(region, range)| {
216 if region.code {
217 Some((
218 range.clone(),
219 HighlightStyle {
220 background_color: Some(code_span_background_color),
221 ..Default::default()
222 },
223 ))
224 } else {
225 None
226 }
227 }),
228 );
229
230 let mut links = Vec::new();
231 let mut link_ranges = Vec::new();
232 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
233 if let Some(link) = region.link.clone() {
234 links.push(link);
235 link_ranges.push(range.clone());
236 }
237 }
238
239 InteractiveText::new(
240 element_id,
241 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
242 )
243 .on_click(link_ranges, move |clicked_range_ix, cx| {
244 match &links[clicked_range_ix] {
245 markdown::Link::Web { url } => cx.open_url(url),
246 markdown::Link::Path { path } => {
247 if let Some(workspace) = &workspace {
248 _ = workspace.update(cx, |workspace, cx| {
249 workspace.open_abs_path(path.clone(), false, cx).detach();
250 });
251 }
252 }
253 }
254 })
255}
256
257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
258pub(crate) enum InlayId {
259 Suggestion(usize),
260 Hint(usize),
261}
262
263impl InlayId {
264 fn id(&self) -> usize {
265 match self {
266 Self::Suggestion(id) => *id,
267 Self::Hint(id) => *id,
268 }
269 }
270}
271
272enum DiffRowHighlight {}
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Copy, Clone, PartialEq, Eq)]
278pub enum Direction {
279 Prev,
280 Next,
281}
282
283#[derive(Debug, Copy, Clone, PartialEq, Eq)]
284pub enum Navigated {
285 Yes,
286 No,
287}
288
289impl Navigated {
290 pub fn from_bool(yes: bool) -> Navigated {
291 if yes {
292 Navigated::Yes
293 } else {
294 Navigated::No
295 }
296 }
297}
298
299pub fn init_settings(cx: &mut AppContext) {
300 EditorSettings::register(cx);
301}
302
303pub fn init(cx: &mut AppContext) {
304 init_settings(cx);
305
306 workspace::register_project_item::<Editor>(cx);
307 workspace::FollowableViewRegistry::register::<Editor>(cx);
308 workspace::register_serializable_item::<Editor>(cx);
309
310 cx.observe_new_views(
311 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
312 workspace.register_action(Editor::new_file);
313 workspace.register_action(Editor::new_file_vertical);
314 workspace.register_action(Editor::new_file_horizontal);
315 },
316 )
317 .detach();
318
319 cx.on_action(move |_: &workspace::NewFile, cx| {
320 let app_state = workspace::AppState::global(cx);
321 if let Some(app_state) = app_state.upgrade() {
322 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
323 Editor::new_file(workspace, &Default::default(), cx)
324 })
325 .detach();
326 }
327 });
328 cx.on_action(move |_: &workspace::NewWindow, cx| {
329 let app_state = workspace::AppState::global(cx);
330 if let Some(app_state) = app_state.upgrade() {
331 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
332 Editor::new_file(workspace, &Default::default(), cx)
333 })
334 .detach();
335 }
336 });
337}
338
339pub struct SearchWithinRange;
340
341trait InvalidationRegion {
342 fn ranges(&self) -> &[Range<Anchor>];
343}
344
345#[derive(Clone, Debug, PartialEq)]
346pub enum SelectPhase {
347 Begin {
348 position: DisplayPoint,
349 add: bool,
350 click_count: usize,
351 },
352 BeginColumnar {
353 position: DisplayPoint,
354 reset: bool,
355 goal_column: u32,
356 },
357 Extend {
358 position: DisplayPoint,
359 click_count: usize,
360 },
361 Update {
362 position: DisplayPoint,
363 goal_column: u32,
364 scroll_delta: gpui::Point<f32>,
365 },
366 End,
367}
368
369#[derive(Clone, Debug)]
370pub enum SelectMode {
371 Character,
372 Word(Range<Anchor>),
373 Line(Range<Anchor>),
374 All,
375}
376
377#[derive(Copy, Clone, PartialEq, Eq, Debug)]
378pub enum EditorMode {
379 SingleLine { auto_width: bool },
380 AutoHeight { max_lines: usize },
381 Full,
382}
383
384#[derive(Copy, Clone, Debug)]
385pub enum SoftWrap {
386 /// Prefer not to wrap at all.
387 ///
388 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
389 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
390 GitDiff,
391 /// Prefer a single line generally, unless an overly long line is encountered.
392 None,
393 /// Soft wrap lines that exceed the editor width.
394 EditorWidth,
395 /// Soft wrap lines at the preferred line length.
396 Column(u32),
397 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
398 Bounded(u32),
399}
400
401#[derive(Clone)]
402pub struct EditorStyle {
403 pub background: Hsla,
404 pub local_player: PlayerColor,
405 pub text: TextStyle,
406 pub scrollbar_width: Pixels,
407 pub syntax: Arc<SyntaxTheme>,
408 pub status: StatusColors,
409 pub inlay_hints_style: HighlightStyle,
410 pub suggestions_style: HighlightStyle,
411 pub unnecessary_code_fade: f32,
412}
413
414impl Default for EditorStyle {
415 fn default() -> Self {
416 Self {
417 background: Hsla::default(),
418 local_player: PlayerColor::default(),
419 text: TextStyle::default(),
420 scrollbar_width: Pixels::default(),
421 syntax: Default::default(),
422 // HACK: Status colors don't have a real default.
423 // We should look into removing the status colors from the editor
424 // style and retrieve them directly from the theme.
425 status: StatusColors::dark(),
426 inlay_hints_style: HighlightStyle::default(),
427 suggestions_style: HighlightStyle::default(),
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
445type CompletionId = usize;
446
447#[derive(Clone, Debug)]
448struct CompletionState {
449 // render_inlay_ids represents the inlay hints that are inserted
450 // for rendering the inline completions. They may be discontinuous
451 // in the event that the completion provider returns some intersection
452 // with the existing content.
453 render_inlay_ids: Vec<InlayId>,
454 // text is the resulting rope that is inserted when the user accepts a completion.
455 text: Rope,
456 // position is the position of the cursor when the completion was triggered.
457 position: multi_buffer::Anchor,
458 // delete_range is the range of text that this completion state covers.
459 // if the completion is accepted, this range should be deleted.
460 delete_range: Option<Range<multi_buffer::Anchor>>,
461}
462
463#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
464struct EditorActionId(usize);
465
466impl EditorActionId {
467 pub fn post_inc(&mut self) -> Self {
468 let answer = self.0;
469
470 *self = Self(answer + 1);
471
472 Self(answer)
473 }
474}
475
476// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
477// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
478
479type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
480type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
481
482#[derive(Default)]
483struct ScrollbarMarkerState {
484 scrollbar_size: Size<Pixels>,
485 dirty: bool,
486 markers: Arc<[PaintQuad]>,
487 pending_refresh: Option<Task<Result<()>>>,
488}
489
490impl ScrollbarMarkerState {
491 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
492 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
493 }
494}
495
496#[derive(Clone, Debug)]
497struct RunnableTasks {
498 templates: Vec<(TaskSourceKind, TaskTemplate)>,
499 offset: MultiBufferOffset,
500 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
501 column: u32,
502 // Values of all named captures, including those starting with '_'
503 extra_variables: HashMap<String, String>,
504 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
505 context_range: Range<BufferOffset>,
506}
507
508impl RunnableTasks {
509 fn resolve<'a>(
510 &'a self,
511 cx: &'a task::TaskContext,
512 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
513 self.templates.iter().filter_map(|(kind, template)| {
514 template
515 .resolve_task(&kind.to_id_base(), cx)
516 .map(|task| (kind.clone(), task))
517 })
518 }
519}
520
521#[derive(Clone)]
522struct ResolvedTasks {
523 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
524 position: Anchor,
525}
526#[derive(Copy, Clone, Debug)]
527struct MultiBufferOffset(usize);
528#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
529struct BufferOffset(usize);
530
531// Addons allow storing per-editor state in other crates (e.g. Vim)
532pub trait Addon: 'static {
533 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
534
535 fn to_any(&self) -> &dyn std::any::Any;
536}
537
538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
539///
540/// See the [module level documentation](self) for more information.
541pub struct Editor {
542 focus_handle: FocusHandle,
543 last_focused_descendant: Option<WeakFocusHandle>,
544 /// The text buffer being edited
545 buffer: Model<MultiBuffer>,
546 /// Map of how text in the buffer should be displayed.
547 /// Handles soft wraps, folds, fake inlay text insertions, etc.
548 pub display_map: Model<DisplayMap>,
549 pub selections: SelectionsCollection,
550 pub scroll_manager: ScrollManager,
551 /// When inline assist editors are linked, they all render cursors because
552 /// typing enters text into each of them, even the ones that aren't focused.
553 pub(crate) show_cursor_when_unfocused: bool,
554 columnar_selection_tail: Option<Anchor>,
555 add_selections_state: Option<AddSelectionsState>,
556 select_next_state: Option<SelectNextState>,
557 select_prev_state: Option<SelectNextState>,
558 selection_history: SelectionHistory,
559 autoclose_regions: Vec<AutocloseRegion>,
560 snippet_stack: InvalidationStack<SnippetState>,
561 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
562 ime_transaction: Option<TransactionId>,
563 active_diagnostics: Option<ActiveDiagnosticGroup>,
564 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
565
566 project: Option<Model<Project>>,
567 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
568 completion_provider: Option<Box<dyn CompletionProvider>>,
569 collaboration_hub: Option<Box<dyn CollaborationHub>>,
570 blink_manager: Model<BlinkManager>,
571 show_cursor_names: bool,
572 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
573 pub show_local_selections: bool,
574 mode: EditorMode,
575 show_breadcrumbs: bool,
576 show_gutter: bool,
577 show_line_numbers: Option<bool>,
578 use_relative_line_numbers: Option<bool>,
579 show_git_diff_gutter: Option<bool>,
580 show_code_actions: Option<bool>,
581 show_runnables: Option<bool>,
582 show_wrap_guides: Option<bool>,
583 show_indent_guides: Option<bool>,
584 placeholder_text: Option<Arc<str>>,
585 highlight_order: usize,
586 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
587 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
588 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
589 scrollbar_marker_state: ScrollbarMarkerState,
590 active_indent_guides_state: ActiveIndentGuidesState,
591 nav_history: Option<ItemNavHistory>,
592 context_menu: RwLock<Option<ContextMenu>>,
593 mouse_context_menu: Option<MouseContextMenu>,
594 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
595 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
596 signature_help_state: SignatureHelpState,
597 auto_signature_help: Option<bool>,
598 find_all_references_task_sources: Vec<Anchor>,
599 next_completion_id: CompletionId,
600 completion_documentation_pre_resolve_debounce: DebouncedDelay,
601 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
602 code_actions_task: Option<Task<Result<()>>>,
603 document_highlights_task: Option<Task<()>>,
604 linked_editing_range_task: Option<Task<Option<()>>>,
605 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
606 pending_rename: Option<RenameState>,
607 searchable: bool,
608 cursor_shape: CursorShape,
609 current_line_highlight: Option<CurrentLineHighlight>,
610 collapse_matches: bool,
611 autoindent_mode: Option<AutoindentMode>,
612 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
613 input_enabled: bool,
614 use_modal_editing: bool,
615 read_only: bool,
616 leader_peer_id: Option<PeerId>,
617 remote_id: Option<ViewId>,
618 hover_state: HoverState,
619 gutter_hovered: bool,
620 hovered_link_state: Option<HoveredLinkState>,
621 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
622 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
623 active_inline_completion: Option<CompletionState>,
624 // enable_inline_completions is a switch that Vim can use to disable
625 // inline completions based on its mode.
626 enable_inline_completions: bool,
627 show_inline_completions_override: Option<bool>,
628 inlay_hint_cache: InlayHintCache,
629 expanded_hunks: ExpandedHunks,
630 next_inlay_id: usize,
631 _subscriptions: Vec<Subscription>,
632 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
633 gutter_dimensions: GutterDimensions,
634 style: Option<EditorStyle>,
635 text_style_refinement: Option<TextStyleRefinement>,
636 next_editor_action_id: EditorActionId,
637 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
638 use_autoclose: bool,
639 use_auto_surround: bool,
640 auto_replace_emoji_shortcode: bool,
641 show_git_blame_gutter: bool,
642 show_git_blame_inline: bool,
643 show_git_blame_inline_delay_task: Option<Task<()>>,
644 git_blame_inline_enabled: bool,
645 serialize_dirty_buffers: bool,
646 show_selection_menu: Option<bool>,
647 blame: Option<Model<GitBlame>>,
648 blame_subscription: Option<Subscription>,
649 custom_context_menu: Option<
650 Box<
651 dyn 'static
652 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
653 >,
654 >,
655 last_bounds: Option<Bounds<Pixels>>,
656 expect_bounds_change: Option<Bounds<Pixels>>,
657 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
658 tasks_update_task: Option<Task<()>>,
659 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
660 breadcrumb_header: Option<String>,
661 focused_block: Option<FocusedBlock>,
662 next_scroll_position: NextScrollCursorCenterTopBottom,
663 addons: HashMap<TypeId, Box<dyn Addon>>,
664 _scroll_cursor_center_top_bottom_task: Task<()>,
665}
666
667#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
668enum NextScrollCursorCenterTopBottom {
669 #[default]
670 Center,
671 Top,
672 Bottom,
673}
674
675impl NextScrollCursorCenterTopBottom {
676 fn next(&self) -> Self {
677 match self {
678 Self::Center => Self::Top,
679 Self::Top => Self::Bottom,
680 Self::Bottom => Self::Center,
681 }
682 }
683}
684
685#[derive(Clone)]
686pub struct EditorSnapshot {
687 pub mode: EditorMode,
688 show_gutter: bool,
689 show_line_numbers: Option<bool>,
690 show_git_diff_gutter: Option<bool>,
691 show_code_actions: Option<bool>,
692 show_runnables: Option<bool>,
693 git_blame_gutter_max_author_length: Option<usize>,
694 pub display_snapshot: DisplaySnapshot,
695 pub placeholder_text: Option<Arc<str>>,
696 is_focused: bool,
697 scroll_anchor: ScrollAnchor,
698 ongoing_scroll: OngoingScroll,
699 current_line_highlight: CurrentLineHighlight,
700 gutter_hovered: bool,
701}
702
703const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
704
705#[derive(Default, Debug, Clone, Copy)]
706pub struct GutterDimensions {
707 pub left_padding: Pixels,
708 pub right_padding: Pixels,
709 pub width: Pixels,
710 pub margin: Pixels,
711 pub git_blame_entries_width: Option<Pixels>,
712}
713
714impl GutterDimensions {
715 /// The full width of the space taken up by the gutter.
716 pub fn full_width(&self) -> Pixels {
717 self.margin + self.width
718 }
719
720 /// The width of the space reserved for the fold indicators,
721 /// use alongside 'justify_end' and `gutter_width` to
722 /// right align content with the line numbers
723 pub fn fold_area_width(&self) -> Pixels {
724 self.margin + self.right_padding
725 }
726}
727
728#[derive(Debug)]
729pub struct RemoteSelection {
730 pub replica_id: ReplicaId,
731 pub selection: Selection<Anchor>,
732 pub cursor_shape: CursorShape,
733 pub peer_id: PeerId,
734 pub line_mode: bool,
735 pub participant_index: Option<ParticipantIndex>,
736 pub user_name: Option<SharedString>,
737}
738
739#[derive(Clone, Debug)]
740struct SelectionHistoryEntry {
741 selections: Arc<[Selection<Anchor>]>,
742 select_next_state: Option<SelectNextState>,
743 select_prev_state: Option<SelectNextState>,
744 add_selections_state: Option<AddSelectionsState>,
745}
746
747enum SelectionHistoryMode {
748 Normal,
749 Undoing,
750 Redoing,
751}
752
753#[derive(Clone, PartialEq, Eq, Hash)]
754struct HoveredCursor {
755 replica_id: u16,
756 selection_id: usize,
757}
758
759impl Default for SelectionHistoryMode {
760 fn default() -> Self {
761 Self::Normal
762 }
763}
764
765#[derive(Default)]
766struct SelectionHistory {
767 #[allow(clippy::type_complexity)]
768 selections_by_transaction:
769 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
770 mode: SelectionHistoryMode,
771 undo_stack: VecDeque<SelectionHistoryEntry>,
772 redo_stack: VecDeque<SelectionHistoryEntry>,
773}
774
775impl SelectionHistory {
776 fn insert_transaction(
777 &mut self,
778 transaction_id: TransactionId,
779 selections: Arc<[Selection<Anchor>]>,
780 ) {
781 self.selections_by_transaction
782 .insert(transaction_id, (selections, None));
783 }
784
785 #[allow(clippy::type_complexity)]
786 fn transaction(
787 &self,
788 transaction_id: TransactionId,
789 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
790 self.selections_by_transaction.get(&transaction_id)
791 }
792
793 #[allow(clippy::type_complexity)]
794 fn transaction_mut(
795 &mut self,
796 transaction_id: TransactionId,
797 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
798 self.selections_by_transaction.get_mut(&transaction_id)
799 }
800
801 fn push(&mut self, entry: SelectionHistoryEntry) {
802 if !entry.selections.is_empty() {
803 match self.mode {
804 SelectionHistoryMode::Normal => {
805 self.push_undo(entry);
806 self.redo_stack.clear();
807 }
808 SelectionHistoryMode::Undoing => self.push_redo(entry),
809 SelectionHistoryMode::Redoing => self.push_undo(entry),
810 }
811 }
812 }
813
814 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
815 if self
816 .undo_stack
817 .back()
818 .map_or(true, |e| e.selections != entry.selections)
819 {
820 self.undo_stack.push_back(entry);
821 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
822 self.undo_stack.pop_front();
823 }
824 }
825 }
826
827 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
828 if self
829 .redo_stack
830 .back()
831 .map_or(true, |e| e.selections != entry.selections)
832 {
833 self.redo_stack.push_back(entry);
834 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
835 self.redo_stack.pop_front();
836 }
837 }
838 }
839}
840
841struct RowHighlight {
842 index: usize,
843 range: Range<Anchor>,
844 color: Hsla,
845 should_autoscroll: bool,
846}
847
848#[derive(Clone, Debug)]
849struct AddSelectionsState {
850 above: bool,
851 stack: Vec<usize>,
852}
853
854#[derive(Clone)]
855struct SelectNextState {
856 query: AhoCorasick,
857 wordwise: bool,
858 done: bool,
859}
860
861impl std::fmt::Debug for SelectNextState {
862 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
863 f.debug_struct(std::any::type_name::<Self>())
864 .field("wordwise", &self.wordwise)
865 .field("done", &self.done)
866 .finish()
867 }
868}
869
870#[derive(Debug)]
871struct AutocloseRegion {
872 selection_id: usize,
873 range: Range<Anchor>,
874 pair: BracketPair,
875}
876
877#[derive(Debug)]
878struct SnippetState {
879 ranges: Vec<Vec<Range<Anchor>>>,
880 active_index: usize,
881}
882
883#[doc(hidden)]
884pub struct RenameState {
885 pub range: Range<Anchor>,
886 pub old_name: Arc<str>,
887 pub editor: View<Editor>,
888 block_id: CustomBlockId,
889}
890
891struct InvalidationStack<T>(Vec<T>);
892
893struct RegisteredInlineCompletionProvider {
894 provider: Arc<dyn InlineCompletionProviderHandle>,
895 _subscription: Subscription,
896}
897
898enum ContextMenu {
899 Completions(CompletionsMenu),
900 CodeActions(CodeActionsMenu),
901}
902
903impl ContextMenu {
904 fn select_first(
905 &mut self,
906 provider: Option<&dyn CompletionProvider>,
907 cx: &mut ViewContext<Editor>,
908 ) -> bool {
909 if self.visible() {
910 match self {
911 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
912 ContextMenu::CodeActions(menu) => menu.select_first(cx),
913 }
914 true
915 } else {
916 false
917 }
918 }
919
920 fn select_prev(
921 &mut self,
922 provider: Option<&dyn CompletionProvider>,
923 cx: &mut ViewContext<Editor>,
924 ) -> bool {
925 if self.visible() {
926 match self {
927 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
928 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
929 }
930 true
931 } else {
932 false
933 }
934 }
935
936 fn select_next(
937 &mut self,
938 provider: Option<&dyn CompletionProvider>,
939 cx: &mut ViewContext<Editor>,
940 ) -> bool {
941 if self.visible() {
942 match self {
943 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
944 ContextMenu::CodeActions(menu) => menu.select_next(cx),
945 }
946 true
947 } else {
948 false
949 }
950 }
951
952 fn select_last(
953 &mut self,
954 provider: Option<&dyn CompletionProvider>,
955 cx: &mut ViewContext<Editor>,
956 ) -> bool {
957 if self.visible() {
958 match self {
959 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
960 ContextMenu::CodeActions(menu) => menu.select_last(cx),
961 }
962 true
963 } else {
964 false
965 }
966 }
967
968 fn visible(&self) -> bool {
969 match self {
970 ContextMenu::Completions(menu) => menu.visible(),
971 ContextMenu::CodeActions(menu) => menu.visible(),
972 }
973 }
974
975 fn render(
976 &self,
977 cursor_position: DisplayPoint,
978 style: &EditorStyle,
979 max_height: Pixels,
980 workspace: Option<WeakView<Workspace>>,
981 cx: &mut ViewContext<Editor>,
982 ) -> (ContextMenuOrigin, AnyElement) {
983 match self {
984 ContextMenu::Completions(menu) => (
985 ContextMenuOrigin::EditorPoint(cursor_position),
986 menu.render(style, max_height, workspace, cx),
987 ),
988 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
989 }
990 }
991}
992
993enum ContextMenuOrigin {
994 EditorPoint(DisplayPoint),
995 GutterIndicator(DisplayRow),
996}
997
998#[derive(Clone)]
999struct CompletionsMenu {
1000 id: CompletionId,
1001 sort_completions: bool,
1002 initial_position: Anchor,
1003 buffer: Model<Buffer>,
1004 completions: Arc<RwLock<Box<[Completion]>>>,
1005 match_candidates: Arc<[StringMatchCandidate]>,
1006 matches: Arc<[StringMatch]>,
1007 selected_item: usize,
1008 scroll_handle: UniformListScrollHandle,
1009 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
1010}
1011
1012impl CompletionsMenu {
1013 fn select_first(
1014 &mut self,
1015 provider: Option<&dyn CompletionProvider>,
1016 cx: &mut ViewContext<Editor>,
1017 ) {
1018 self.selected_item = 0;
1019 self.scroll_handle.scroll_to_item(self.selected_item);
1020 self.attempt_resolve_selected_completion_documentation(provider, cx);
1021 cx.notify();
1022 }
1023
1024 fn select_prev(
1025 &mut self,
1026 provider: Option<&dyn CompletionProvider>,
1027 cx: &mut ViewContext<Editor>,
1028 ) {
1029 if self.selected_item > 0 {
1030 self.selected_item -= 1;
1031 } else {
1032 self.selected_item = self.matches.len() - 1;
1033 }
1034 self.scroll_handle.scroll_to_item(self.selected_item);
1035 self.attempt_resolve_selected_completion_documentation(provider, cx);
1036 cx.notify();
1037 }
1038
1039 fn select_next(
1040 &mut self,
1041 provider: Option<&dyn CompletionProvider>,
1042 cx: &mut ViewContext<Editor>,
1043 ) {
1044 if self.selected_item + 1 < self.matches.len() {
1045 self.selected_item += 1;
1046 } else {
1047 self.selected_item = 0;
1048 }
1049 self.scroll_handle.scroll_to_item(self.selected_item);
1050 self.attempt_resolve_selected_completion_documentation(provider, cx);
1051 cx.notify();
1052 }
1053
1054 fn select_last(
1055 &mut self,
1056 provider: Option<&dyn CompletionProvider>,
1057 cx: &mut ViewContext<Editor>,
1058 ) {
1059 self.selected_item = self.matches.len() - 1;
1060 self.scroll_handle.scroll_to_item(self.selected_item);
1061 self.attempt_resolve_selected_completion_documentation(provider, cx);
1062 cx.notify();
1063 }
1064
1065 fn pre_resolve_completion_documentation(
1066 buffer: Model<Buffer>,
1067 completions: Arc<RwLock<Box<[Completion]>>>,
1068 matches: Arc<[StringMatch]>,
1069 editor: &Editor,
1070 cx: &mut ViewContext<Editor>,
1071 ) -> Task<()> {
1072 let settings = EditorSettings::get_global(cx);
1073 if !settings.show_completion_documentation {
1074 return Task::ready(());
1075 }
1076
1077 let Some(provider) = editor.completion_provider.as_ref() else {
1078 return Task::ready(());
1079 };
1080
1081 let resolve_task = provider.resolve_completions(
1082 buffer,
1083 matches.iter().map(|m| m.candidate_id).collect(),
1084 completions.clone(),
1085 cx,
1086 );
1087
1088 cx.spawn(move |this, mut cx| async move {
1089 if let Some(true) = resolve_task.await.log_err() {
1090 this.update(&mut cx, |_, cx| cx.notify()).ok();
1091 }
1092 })
1093 }
1094
1095 fn attempt_resolve_selected_completion_documentation(
1096 &mut self,
1097 provider: Option<&dyn CompletionProvider>,
1098 cx: &mut ViewContext<Editor>,
1099 ) {
1100 let settings = EditorSettings::get_global(cx);
1101 if !settings.show_completion_documentation {
1102 return;
1103 }
1104
1105 let completion_index = self.matches[self.selected_item].candidate_id;
1106 let Some(provider) = provider else {
1107 return;
1108 };
1109
1110 let resolve_task = provider.resolve_completions(
1111 self.buffer.clone(),
1112 vec![completion_index],
1113 self.completions.clone(),
1114 cx,
1115 );
1116
1117 let delay_ms =
1118 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1119 let delay = Duration::from_millis(delay_ms);
1120
1121 self.selected_completion_documentation_resolve_debounce
1122 .lock()
1123 .fire_new(delay, cx, |_, cx| {
1124 cx.spawn(move |this, mut cx| async move {
1125 if let Some(true) = resolve_task.await.log_err() {
1126 this.update(&mut cx, |_, cx| cx.notify()).ok();
1127 }
1128 })
1129 });
1130 }
1131
1132 fn visible(&self) -> bool {
1133 !self.matches.is_empty()
1134 }
1135
1136 fn render(
1137 &self,
1138 style: &EditorStyle,
1139 max_height: Pixels,
1140 workspace: Option<WeakView<Workspace>>,
1141 cx: &mut ViewContext<Editor>,
1142 ) -> AnyElement {
1143 let settings = EditorSettings::get_global(cx);
1144 let show_completion_documentation = settings.show_completion_documentation;
1145
1146 let widest_completion_ix = self
1147 .matches
1148 .iter()
1149 .enumerate()
1150 .max_by_key(|(_, mat)| {
1151 let completions = self.completions.read();
1152 let completion = &completions[mat.candidate_id];
1153 let documentation = &completion.documentation;
1154
1155 let mut len = completion.label.text.chars().count();
1156 if let Some(Documentation::SingleLine(text)) = documentation {
1157 if show_completion_documentation {
1158 len += text.chars().count();
1159 }
1160 }
1161
1162 len
1163 })
1164 .map(|(ix, _)| ix);
1165
1166 let completions = self.completions.clone();
1167 let matches = self.matches.clone();
1168 let selected_item = self.selected_item;
1169 let style = style.clone();
1170
1171 let multiline_docs = if show_completion_documentation {
1172 let mat = &self.matches[selected_item];
1173 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1174 Some(Documentation::MultiLinePlainText(text)) => {
1175 Some(div().child(SharedString::from(text.clone())))
1176 }
1177 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1178 Some(div().child(render_parsed_markdown(
1179 "completions_markdown",
1180 parsed,
1181 &style,
1182 workspace,
1183 cx,
1184 )))
1185 }
1186 _ => None,
1187 };
1188 multiline_docs.map(|div| {
1189 div.id("multiline_docs")
1190 .max_h(max_height)
1191 .flex_1()
1192 .px_1p5()
1193 .py_1()
1194 .min_w(px(260.))
1195 .max_w(px(640.))
1196 .w(px(500.))
1197 .overflow_y_scroll()
1198 .occlude()
1199 })
1200 } else {
1201 None
1202 };
1203
1204 let list = uniform_list(
1205 cx.view().clone(),
1206 "completions",
1207 matches.len(),
1208 move |_editor, range, cx| {
1209 let start_ix = range.start;
1210 let completions_guard = completions.read();
1211
1212 matches[range]
1213 .iter()
1214 .enumerate()
1215 .map(|(ix, mat)| {
1216 let item_ix = start_ix + ix;
1217 let candidate_id = mat.candidate_id;
1218 let completion = &completions_guard[candidate_id];
1219
1220 let documentation = if show_completion_documentation {
1221 &completion.documentation
1222 } else {
1223 &None
1224 };
1225
1226 let highlights = gpui::combine_highlights(
1227 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1228 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1229 |(range, mut highlight)| {
1230 // Ignore font weight for syntax highlighting, as we'll use it
1231 // for fuzzy matches.
1232 highlight.font_weight = None;
1233
1234 if completion.lsp_completion.deprecated.unwrap_or(false) {
1235 highlight.strikethrough = Some(StrikethroughStyle {
1236 thickness: 1.0.into(),
1237 ..Default::default()
1238 });
1239 highlight.color = Some(cx.theme().colors().text_muted);
1240 }
1241
1242 (range, highlight)
1243 },
1244 ),
1245 );
1246 let completion_label = StyledText::new(completion.label.text.clone())
1247 .with_highlights(&style.text, highlights);
1248 let documentation_label =
1249 if let Some(Documentation::SingleLine(text)) = documentation {
1250 if text.trim().is_empty() {
1251 None
1252 } else {
1253 Some(
1254 Label::new(text.clone())
1255 .ml_4()
1256 .size(LabelSize::Small)
1257 .color(Color::Muted),
1258 )
1259 }
1260 } else {
1261 None
1262 };
1263
1264 let color_swatch = completion
1265 .color()
1266 .map(|color| div().size_4().bg(color).rounded_sm());
1267
1268 div().min_w(px(220.)).max_w(px(540.)).child(
1269 ListItem::new(mat.candidate_id)
1270 .inset(true)
1271 .selected(item_ix == selected_item)
1272 .on_click(cx.listener(move |editor, _event, cx| {
1273 cx.stop_propagation();
1274 if let Some(task) = editor.confirm_completion(
1275 &ConfirmCompletion {
1276 item_ix: Some(item_ix),
1277 },
1278 cx,
1279 ) {
1280 task.detach_and_log_err(cx)
1281 }
1282 }))
1283 .start_slot::<Div>(color_swatch)
1284 .child(h_flex().overflow_hidden().child(completion_label))
1285 .end_slot::<Label>(documentation_label),
1286 )
1287 })
1288 .collect()
1289 },
1290 )
1291 .occlude()
1292 .max_h(max_height)
1293 .track_scroll(self.scroll_handle.clone())
1294 .with_width_from_item(widest_completion_ix)
1295 .with_sizing_behavior(ListSizingBehavior::Infer);
1296
1297 Popover::new()
1298 .child(list)
1299 .when_some(multiline_docs, |popover, multiline_docs| {
1300 popover.aside(multiline_docs)
1301 })
1302 .into_any_element()
1303 }
1304
1305 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1306 let mut matches = if let Some(query) = query {
1307 fuzzy::match_strings(
1308 &self.match_candidates,
1309 query,
1310 query.chars().any(|c| c.is_uppercase()),
1311 100,
1312 &Default::default(),
1313 executor,
1314 )
1315 .await
1316 } else {
1317 self.match_candidates
1318 .iter()
1319 .enumerate()
1320 .map(|(candidate_id, candidate)| StringMatch {
1321 candidate_id,
1322 score: Default::default(),
1323 positions: Default::default(),
1324 string: candidate.string.clone(),
1325 })
1326 .collect()
1327 };
1328
1329 // Remove all candidates where the query's start does not match the start of any word in the candidate
1330 if let Some(query) = query {
1331 if let Some(query_start) = query.chars().next() {
1332 matches.retain(|string_match| {
1333 split_words(&string_match.string).any(|word| {
1334 // Check that the first codepoint of the word as lowercase matches the first
1335 // codepoint of the query as lowercase
1336 word.chars()
1337 .flat_map(|codepoint| codepoint.to_lowercase())
1338 .zip(query_start.to_lowercase())
1339 .all(|(word_cp, query_cp)| word_cp == query_cp)
1340 })
1341 });
1342 }
1343 }
1344
1345 let completions = self.completions.read();
1346 if self.sort_completions {
1347 matches.sort_unstable_by_key(|mat| {
1348 // We do want to strike a balance here between what the language server tells us
1349 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1350 // `Creat` and there is a local variable called `CreateComponent`).
1351 // So what we do is: we bucket all matches into two buckets
1352 // - Strong matches
1353 // - Weak matches
1354 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1355 // and the Weak matches are the rest.
1356 //
1357 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1358 // matches, we prefer language-server sort_text first.
1359 //
1360 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1361 // Rest of the matches(weak) can be sorted as language-server expects.
1362
1363 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1364 enum MatchScore<'a> {
1365 Strong {
1366 score: Reverse<OrderedFloat<f64>>,
1367 sort_text: Option<&'a str>,
1368 sort_key: (usize, &'a str),
1369 },
1370 Weak {
1371 sort_text: Option<&'a str>,
1372 score: Reverse<OrderedFloat<f64>>,
1373 sort_key: (usize, &'a str),
1374 },
1375 }
1376
1377 let completion = &completions[mat.candidate_id];
1378 let sort_key = completion.sort_key();
1379 let sort_text = completion.lsp_completion.sort_text.as_deref();
1380 let score = Reverse(OrderedFloat(mat.score));
1381
1382 if mat.score >= 0.2 {
1383 MatchScore::Strong {
1384 score,
1385 sort_text,
1386 sort_key,
1387 }
1388 } else {
1389 MatchScore::Weak {
1390 sort_text,
1391 score,
1392 sort_key,
1393 }
1394 }
1395 });
1396 }
1397
1398 for mat in &mut matches {
1399 let completion = &completions[mat.candidate_id];
1400 mat.string.clone_from(&completion.label.text);
1401 for position in &mut mat.positions {
1402 *position += completion.label.filter_range.start;
1403 }
1404 }
1405 drop(completions);
1406
1407 self.matches = matches.into();
1408 self.selected_item = 0;
1409 }
1410}
1411
1412struct AvailableCodeAction {
1413 excerpt_id: ExcerptId,
1414 action: CodeAction,
1415 provider: Arc<dyn CodeActionProvider>,
1416}
1417
1418#[derive(Clone)]
1419struct CodeActionContents {
1420 tasks: Option<Arc<ResolvedTasks>>,
1421 actions: Option<Arc<[AvailableCodeAction]>>,
1422}
1423
1424impl CodeActionContents {
1425 fn len(&self) -> usize {
1426 match (&self.tasks, &self.actions) {
1427 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1428 (Some(tasks), None) => tasks.templates.len(),
1429 (None, Some(actions)) => actions.len(),
1430 (None, None) => 0,
1431 }
1432 }
1433
1434 fn is_empty(&self) -> bool {
1435 match (&self.tasks, &self.actions) {
1436 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1437 (Some(tasks), None) => tasks.templates.is_empty(),
1438 (None, Some(actions)) => actions.is_empty(),
1439 (None, None) => true,
1440 }
1441 }
1442
1443 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1444 self.tasks
1445 .iter()
1446 .flat_map(|tasks| {
1447 tasks
1448 .templates
1449 .iter()
1450 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1451 })
1452 .chain(self.actions.iter().flat_map(|actions| {
1453 actions.iter().map(|available| CodeActionsItem::CodeAction {
1454 excerpt_id: available.excerpt_id,
1455 action: available.action.clone(),
1456 provider: available.provider.clone(),
1457 })
1458 }))
1459 }
1460 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1461 match (&self.tasks, &self.actions) {
1462 (Some(tasks), Some(actions)) => {
1463 if index < tasks.templates.len() {
1464 tasks
1465 .templates
1466 .get(index)
1467 .cloned()
1468 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1469 } else {
1470 actions.get(index - tasks.templates.len()).map(|available| {
1471 CodeActionsItem::CodeAction {
1472 excerpt_id: available.excerpt_id,
1473 action: available.action.clone(),
1474 provider: available.provider.clone(),
1475 }
1476 })
1477 }
1478 }
1479 (Some(tasks), None) => tasks
1480 .templates
1481 .get(index)
1482 .cloned()
1483 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1484 (None, Some(actions)) => {
1485 actions
1486 .get(index)
1487 .map(|available| CodeActionsItem::CodeAction {
1488 excerpt_id: available.excerpt_id,
1489 action: available.action.clone(),
1490 provider: available.provider.clone(),
1491 })
1492 }
1493 (None, None) => None,
1494 }
1495 }
1496}
1497
1498#[allow(clippy::large_enum_variant)]
1499#[derive(Clone)]
1500enum CodeActionsItem {
1501 Task(TaskSourceKind, ResolvedTask),
1502 CodeAction {
1503 excerpt_id: ExcerptId,
1504 action: CodeAction,
1505 provider: Arc<dyn CodeActionProvider>,
1506 },
1507}
1508
1509impl CodeActionsItem {
1510 fn as_task(&self) -> Option<&ResolvedTask> {
1511 let Self::Task(_, task) = self else {
1512 return None;
1513 };
1514 Some(task)
1515 }
1516 fn as_code_action(&self) -> Option<&CodeAction> {
1517 let Self::CodeAction { action, .. } = self else {
1518 return None;
1519 };
1520 Some(action)
1521 }
1522 fn label(&self) -> String {
1523 match self {
1524 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1525 Self::Task(_, task) => task.resolved_label.clone(),
1526 }
1527 }
1528}
1529
1530struct CodeActionsMenu {
1531 actions: CodeActionContents,
1532 buffer: Model<Buffer>,
1533 selected_item: usize,
1534 scroll_handle: UniformListScrollHandle,
1535 deployed_from_indicator: Option<DisplayRow>,
1536}
1537
1538impl CodeActionsMenu {
1539 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1540 self.selected_item = 0;
1541 self.scroll_handle.scroll_to_item(self.selected_item);
1542 cx.notify()
1543 }
1544
1545 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1546 if self.selected_item > 0 {
1547 self.selected_item -= 1;
1548 } else {
1549 self.selected_item = self.actions.len() - 1;
1550 }
1551 self.scroll_handle.scroll_to_item(self.selected_item);
1552 cx.notify();
1553 }
1554
1555 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1556 if self.selected_item + 1 < self.actions.len() {
1557 self.selected_item += 1;
1558 } else {
1559 self.selected_item = 0;
1560 }
1561 self.scroll_handle.scroll_to_item(self.selected_item);
1562 cx.notify();
1563 }
1564
1565 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1566 self.selected_item = self.actions.len() - 1;
1567 self.scroll_handle.scroll_to_item(self.selected_item);
1568 cx.notify()
1569 }
1570
1571 fn visible(&self) -> bool {
1572 !self.actions.is_empty()
1573 }
1574
1575 fn render(
1576 &self,
1577 cursor_position: DisplayPoint,
1578 _style: &EditorStyle,
1579 max_height: Pixels,
1580 cx: &mut ViewContext<Editor>,
1581 ) -> (ContextMenuOrigin, AnyElement) {
1582 let actions = self.actions.clone();
1583 let selected_item = self.selected_item;
1584 let element = uniform_list(
1585 cx.view().clone(),
1586 "code_actions_menu",
1587 self.actions.len(),
1588 move |_this, range, cx| {
1589 actions
1590 .iter()
1591 .skip(range.start)
1592 .take(range.end - range.start)
1593 .enumerate()
1594 .map(|(ix, action)| {
1595 let item_ix = range.start + ix;
1596 let selected = selected_item == item_ix;
1597 let colors = cx.theme().colors();
1598 div()
1599 .px_1()
1600 .rounded_md()
1601 .text_color(colors.text)
1602 .when(selected, |style| {
1603 style
1604 .bg(colors.element_active)
1605 .text_color(colors.text_accent)
1606 })
1607 .hover(|style| {
1608 style
1609 .bg(colors.element_hover)
1610 .text_color(colors.text_accent)
1611 })
1612 .whitespace_nowrap()
1613 .when_some(action.as_code_action(), |this, action| {
1614 this.on_mouse_down(
1615 MouseButton::Left,
1616 cx.listener(move |editor, _, cx| {
1617 cx.stop_propagation();
1618 if let Some(task) = editor.confirm_code_action(
1619 &ConfirmCodeAction {
1620 item_ix: Some(item_ix),
1621 },
1622 cx,
1623 ) {
1624 task.detach_and_log_err(cx)
1625 }
1626 }),
1627 )
1628 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1629 .child(SharedString::from(action.lsp_action.title.clone()))
1630 })
1631 .when_some(action.as_task(), |this, task| {
1632 this.on_mouse_down(
1633 MouseButton::Left,
1634 cx.listener(move |editor, _, cx| {
1635 cx.stop_propagation();
1636 if let Some(task) = editor.confirm_code_action(
1637 &ConfirmCodeAction {
1638 item_ix: Some(item_ix),
1639 },
1640 cx,
1641 ) {
1642 task.detach_and_log_err(cx)
1643 }
1644 }),
1645 )
1646 .child(SharedString::from(task.resolved_label.clone()))
1647 })
1648 })
1649 .collect()
1650 },
1651 )
1652 .elevation_1(cx)
1653 .p_1()
1654 .max_h(max_height)
1655 .occlude()
1656 .track_scroll(self.scroll_handle.clone())
1657 .with_width_from_item(
1658 self.actions
1659 .iter()
1660 .enumerate()
1661 .max_by_key(|(_, action)| match action {
1662 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1663 CodeActionsItem::CodeAction { action, .. } => {
1664 action.lsp_action.title.chars().count()
1665 }
1666 })
1667 .map(|(ix, _)| ix),
1668 )
1669 .with_sizing_behavior(ListSizingBehavior::Infer)
1670 .into_any_element();
1671
1672 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1673 ContextMenuOrigin::GutterIndicator(row)
1674 } else {
1675 ContextMenuOrigin::EditorPoint(cursor_position)
1676 };
1677
1678 (cursor_position, element)
1679 }
1680}
1681
1682#[derive(Debug)]
1683struct ActiveDiagnosticGroup {
1684 primary_range: Range<Anchor>,
1685 primary_message: String,
1686 group_id: usize,
1687 blocks: HashMap<CustomBlockId, Diagnostic>,
1688 is_valid: bool,
1689}
1690
1691#[derive(Serialize, Deserialize, Clone, Debug)]
1692pub struct ClipboardSelection {
1693 pub len: usize,
1694 pub is_entire_line: bool,
1695 pub first_line_indent: u32,
1696}
1697
1698#[derive(Debug)]
1699pub(crate) struct NavigationData {
1700 cursor_anchor: Anchor,
1701 cursor_position: Point,
1702 scroll_anchor: ScrollAnchor,
1703 scroll_top_row: u32,
1704}
1705
1706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1707pub enum GotoDefinitionKind {
1708 Symbol,
1709 Declaration,
1710 Type,
1711 Implementation,
1712}
1713
1714#[derive(Debug, Clone)]
1715enum InlayHintRefreshReason {
1716 Toggle(bool),
1717 SettingsChange(InlayHintSettings),
1718 NewLinesShown,
1719 BufferEdited(HashSet<Arc<Language>>),
1720 RefreshRequested,
1721 ExcerptsRemoved(Vec<ExcerptId>),
1722}
1723
1724impl InlayHintRefreshReason {
1725 fn description(&self) -> &'static str {
1726 match self {
1727 Self::Toggle(_) => "toggle",
1728 Self::SettingsChange(_) => "settings change",
1729 Self::NewLinesShown => "new lines shown",
1730 Self::BufferEdited(_) => "buffer edited",
1731 Self::RefreshRequested => "refresh requested",
1732 Self::ExcerptsRemoved(_) => "excerpts removed",
1733 }
1734 }
1735}
1736
1737pub(crate) struct FocusedBlock {
1738 id: BlockId,
1739 focus_handle: WeakFocusHandle,
1740}
1741
1742impl Editor {
1743 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1744 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1745 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1746 Self::new(
1747 EditorMode::SingleLine { auto_width: false },
1748 buffer,
1749 None,
1750 false,
1751 cx,
1752 )
1753 }
1754
1755 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1756 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1757 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1758 Self::new(EditorMode::Full, buffer, None, false, cx)
1759 }
1760
1761 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1762 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1763 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1764 Self::new(
1765 EditorMode::SingleLine { auto_width: true },
1766 buffer,
1767 None,
1768 false,
1769 cx,
1770 )
1771 }
1772
1773 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1774 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1775 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1776 Self::new(
1777 EditorMode::AutoHeight { max_lines },
1778 buffer,
1779 None,
1780 false,
1781 cx,
1782 )
1783 }
1784
1785 pub fn for_buffer(
1786 buffer: Model<Buffer>,
1787 project: Option<Model<Project>>,
1788 cx: &mut ViewContext<Self>,
1789 ) -> Self {
1790 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1791 Self::new(EditorMode::Full, buffer, project, false, cx)
1792 }
1793
1794 pub fn for_multibuffer(
1795 buffer: Model<MultiBuffer>,
1796 project: Option<Model<Project>>,
1797 show_excerpt_controls: bool,
1798 cx: &mut ViewContext<Self>,
1799 ) -> Self {
1800 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1801 }
1802
1803 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1804 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1805 let mut clone = Self::new(
1806 self.mode,
1807 self.buffer.clone(),
1808 self.project.clone(),
1809 show_excerpt_controls,
1810 cx,
1811 );
1812 self.display_map.update(cx, |display_map, cx| {
1813 let snapshot = display_map.snapshot(cx);
1814 clone.display_map.update(cx, |display_map, cx| {
1815 display_map.set_state(&snapshot, cx);
1816 });
1817 });
1818 clone.selections.clone_state(&self.selections);
1819 clone.scroll_manager.clone_state(&self.scroll_manager);
1820 clone.searchable = self.searchable;
1821 clone
1822 }
1823
1824 pub fn new(
1825 mode: EditorMode,
1826 buffer: Model<MultiBuffer>,
1827 project: Option<Model<Project>>,
1828 show_excerpt_controls: bool,
1829 cx: &mut ViewContext<Self>,
1830 ) -> Self {
1831 let style = cx.text_style();
1832 let font_size = style.font_size.to_pixels(cx.rem_size());
1833 let editor = cx.view().downgrade();
1834 let fold_placeholder = FoldPlaceholder {
1835 constrain_width: true,
1836 render: Arc::new(move |fold_id, fold_range, cx| {
1837 let editor = editor.clone();
1838 div()
1839 .id(fold_id)
1840 .bg(cx.theme().colors().ghost_element_background)
1841 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1842 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1843 .rounded_sm()
1844 .size_full()
1845 .cursor_pointer()
1846 .child("⋯")
1847 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1848 .on_click(move |_, cx| {
1849 editor
1850 .update(cx, |editor, cx| {
1851 editor.unfold_ranges(
1852 [fold_range.start..fold_range.end],
1853 true,
1854 false,
1855 cx,
1856 );
1857 cx.stop_propagation();
1858 })
1859 .ok();
1860 })
1861 .into_any()
1862 }),
1863 merge_adjacent: true,
1864 };
1865 let display_map = cx.new_model(|cx| {
1866 DisplayMap::new(
1867 buffer.clone(),
1868 style.font(),
1869 font_size,
1870 None,
1871 show_excerpt_controls,
1872 FILE_HEADER_HEIGHT,
1873 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1874 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1875 fold_placeholder,
1876 cx,
1877 )
1878 });
1879
1880 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1881
1882 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1883
1884 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1885 .then(|| language_settings::SoftWrap::None);
1886
1887 let mut project_subscriptions = Vec::new();
1888 if mode == EditorMode::Full {
1889 if let Some(project) = project.as_ref() {
1890 if buffer.read(cx).is_singleton() {
1891 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1892 cx.emit(EditorEvent::TitleChanged);
1893 }));
1894 }
1895 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1896 if let project::Event::RefreshInlayHints = event {
1897 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1898 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1899 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1900 let focus_handle = editor.focus_handle(cx);
1901 if focus_handle.is_focused(cx) {
1902 let snapshot = buffer.read(cx).snapshot();
1903 for (range, snippet) in snippet_edits {
1904 let editor_range =
1905 language::range_from_lsp(*range).to_offset(&snapshot);
1906 editor
1907 .insert_snippet(&[editor_range], snippet.clone(), cx)
1908 .ok();
1909 }
1910 }
1911 }
1912 }
1913 }));
1914 if let Some(task_inventory) = project
1915 .read(cx)
1916 .task_store()
1917 .read(cx)
1918 .task_inventory()
1919 .cloned()
1920 {
1921 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1922 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1923 }));
1924 }
1925 }
1926 }
1927
1928 let inlay_hint_settings = inlay_hint_settings(
1929 selections.newest_anchor().head(),
1930 &buffer.read(cx).snapshot(cx),
1931 cx,
1932 );
1933 let focus_handle = cx.focus_handle();
1934 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1935 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1936 .detach();
1937 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1938 .detach();
1939 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1940
1941 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1942 Some(false)
1943 } else {
1944 None
1945 };
1946
1947 let mut code_action_providers = Vec::new();
1948 if let Some(project) = project.clone() {
1949 code_action_providers.push(Arc::new(project) as Arc<_>);
1950 }
1951
1952 let mut this = Self {
1953 focus_handle,
1954 show_cursor_when_unfocused: false,
1955 last_focused_descendant: None,
1956 buffer: buffer.clone(),
1957 display_map: display_map.clone(),
1958 selections,
1959 scroll_manager: ScrollManager::new(cx),
1960 columnar_selection_tail: None,
1961 add_selections_state: None,
1962 select_next_state: None,
1963 select_prev_state: None,
1964 selection_history: Default::default(),
1965 autoclose_regions: Default::default(),
1966 snippet_stack: Default::default(),
1967 select_larger_syntax_node_stack: Vec::new(),
1968 ime_transaction: Default::default(),
1969 active_diagnostics: None,
1970 soft_wrap_mode_override,
1971 completion_provider: project.clone().map(|project| Box::new(project) as _),
1972 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1973 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1974 project,
1975 blink_manager: blink_manager.clone(),
1976 show_local_selections: true,
1977 mode,
1978 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1979 show_gutter: mode == EditorMode::Full,
1980 show_line_numbers: None,
1981 use_relative_line_numbers: None,
1982 show_git_diff_gutter: None,
1983 show_code_actions: None,
1984 show_runnables: None,
1985 show_wrap_guides: None,
1986 show_indent_guides,
1987 placeholder_text: None,
1988 highlight_order: 0,
1989 highlighted_rows: HashMap::default(),
1990 background_highlights: Default::default(),
1991 gutter_highlights: TreeMap::default(),
1992 scrollbar_marker_state: ScrollbarMarkerState::default(),
1993 active_indent_guides_state: ActiveIndentGuidesState::default(),
1994 nav_history: None,
1995 context_menu: RwLock::new(None),
1996 mouse_context_menu: None,
1997 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1998 completion_tasks: Default::default(),
1999 signature_help_state: SignatureHelpState::default(),
2000 auto_signature_help: None,
2001 find_all_references_task_sources: Vec::new(),
2002 next_completion_id: 0,
2003 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2004 next_inlay_id: 0,
2005 code_action_providers,
2006 available_code_actions: Default::default(),
2007 code_actions_task: Default::default(),
2008 document_highlights_task: Default::default(),
2009 linked_editing_range_task: Default::default(),
2010 pending_rename: Default::default(),
2011 searchable: true,
2012 cursor_shape: EditorSettings::get_global(cx)
2013 .cursor_shape
2014 .unwrap_or_default(),
2015 current_line_highlight: None,
2016 autoindent_mode: Some(AutoindentMode::EachLine),
2017 collapse_matches: false,
2018 workspace: None,
2019 input_enabled: true,
2020 use_modal_editing: mode == EditorMode::Full,
2021 read_only: false,
2022 use_autoclose: true,
2023 use_auto_surround: true,
2024 auto_replace_emoji_shortcode: false,
2025 leader_peer_id: None,
2026 remote_id: None,
2027 hover_state: Default::default(),
2028 hovered_link_state: Default::default(),
2029 inline_completion_provider: None,
2030 active_inline_completion: None,
2031 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2032 expanded_hunks: ExpandedHunks::default(),
2033 gutter_hovered: false,
2034 pixel_position_of_newest_cursor: None,
2035 last_bounds: None,
2036 expect_bounds_change: None,
2037 gutter_dimensions: GutterDimensions::default(),
2038 style: None,
2039 show_cursor_names: false,
2040 hovered_cursors: Default::default(),
2041 next_editor_action_id: EditorActionId::default(),
2042 editor_actions: Rc::default(),
2043 show_inline_completions_override: None,
2044 enable_inline_completions: true,
2045 custom_context_menu: None,
2046 show_git_blame_gutter: false,
2047 show_git_blame_inline: false,
2048 show_selection_menu: None,
2049 show_git_blame_inline_delay_task: None,
2050 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2051 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2052 .session
2053 .restore_unsaved_buffers,
2054 blame: None,
2055 blame_subscription: None,
2056 tasks: Default::default(),
2057 _subscriptions: vec![
2058 cx.observe(&buffer, Self::on_buffer_changed),
2059 cx.subscribe(&buffer, Self::on_buffer_event),
2060 cx.observe(&display_map, Self::on_display_map_changed),
2061 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2062 cx.observe_global::<SettingsStore>(Self::settings_changed),
2063 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2064 cx.observe_window_activation(|editor, cx| {
2065 let active = cx.is_window_active();
2066 editor.blink_manager.update(cx, |blink_manager, cx| {
2067 if active {
2068 blink_manager.enable(cx);
2069 } else {
2070 blink_manager.disable(cx);
2071 }
2072 });
2073 }),
2074 ],
2075 tasks_update_task: None,
2076 linked_edit_ranges: Default::default(),
2077 previous_search_ranges: None,
2078 breadcrumb_header: None,
2079 focused_block: None,
2080 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2081 addons: HashMap::default(),
2082 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2083 text_style_refinement: None,
2084 };
2085 this.tasks_update_task = Some(this.refresh_runnables(cx));
2086 this._subscriptions.extend(project_subscriptions);
2087
2088 this.end_selection(cx);
2089 this.scroll_manager.show_scrollbar(cx);
2090
2091 if mode == EditorMode::Full {
2092 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2093 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2094
2095 if this.git_blame_inline_enabled {
2096 this.git_blame_inline_enabled = true;
2097 this.start_git_blame_inline(false, cx);
2098 }
2099 }
2100
2101 this.report_editor_event("open", None, cx);
2102 this
2103 }
2104
2105 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2106 self.mouse_context_menu
2107 .as_ref()
2108 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2109 }
2110
2111 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2112 let mut key_context = KeyContext::new_with_defaults();
2113 key_context.add("Editor");
2114 let mode = match self.mode {
2115 EditorMode::SingleLine { .. } => "single_line",
2116 EditorMode::AutoHeight { .. } => "auto_height",
2117 EditorMode::Full => "full",
2118 };
2119
2120 if EditorSettings::jupyter_enabled(cx) {
2121 key_context.add("jupyter");
2122 }
2123
2124 key_context.set("mode", mode);
2125 if self.pending_rename.is_some() {
2126 key_context.add("renaming");
2127 }
2128 if self.context_menu_visible() {
2129 match self.context_menu.read().as_ref() {
2130 Some(ContextMenu::Completions(_)) => {
2131 key_context.add("menu");
2132 key_context.add("showing_completions")
2133 }
2134 Some(ContextMenu::CodeActions(_)) => {
2135 key_context.add("menu");
2136 key_context.add("showing_code_actions")
2137 }
2138 None => {}
2139 }
2140 }
2141
2142 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2143 if !self.focus_handle(cx).contains_focused(cx)
2144 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2145 {
2146 for addon in self.addons.values() {
2147 addon.extend_key_context(&mut key_context, cx)
2148 }
2149 }
2150
2151 if let Some(extension) = self
2152 .buffer
2153 .read(cx)
2154 .as_singleton()
2155 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2156 {
2157 key_context.set("extension", extension.to_string());
2158 }
2159
2160 if self.has_active_inline_completion(cx) {
2161 key_context.add("copilot_suggestion");
2162 key_context.add("inline_completion");
2163 }
2164
2165 key_context
2166 }
2167
2168 pub fn new_file(
2169 workspace: &mut Workspace,
2170 _: &workspace::NewFile,
2171 cx: &mut ViewContext<Workspace>,
2172 ) {
2173 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2174 "Failed to create buffer",
2175 cx,
2176 |e, _| match e.error_code() {
2177 ErrorCode::RemoteUpgradeRequired => Some(format!(
2178 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2179 e.error_tag("required").unwrap_or("the latest version")
2180 )),
2181 _ => None,
2182 },
2183 );
2184 }
2185
2186 pub fn new_in_workspace(
2187 workspace: &mut Workspace,
2188 cx: &mut ViewContext<Workspace>,
2189 ) -> Task<Result<View<Editor>>> {
2190 let project = workspace.project().clone();
2191 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2192
2193 cx.spawn(|workspace, mut cx| async move {
2194 let buffer = create.await?;
2195 workspace.update(&mut cx, |workspace, cx| {
2196 let editor =
2197 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2198 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2199 editor
2200 })
2201 })
2202 }
2203
2204 fn new_file_vertical(
2205 workspace: &mut Workspace,
2206 _: &workspace::NewFileSplitVertical,
2207 cx: &mut ViewContext<Workspace>,
2208 ) {
2209 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2210 }
2211
2212 fn new_file_horizontal(
2213 workspace: &mut Workspace,
2214 _: &workspace::NewFileSplitHorizontal,
2215 cx: &mut ViewContext<Workspace>,
2216 ) {
2217 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2218 }
2219
2220 fn new_file_in_direction(
2221 workspace: &mut Workspace,
2222 direction: SplitDirection,
2223 cx: &mut ViewContext<Workspace>,
2224 ) {
2225 let project = workspace.project().clone();
2226 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2227
2228 cx.spawn(|workspace, mut cx| async move {
2229 let buffer = create.await?;
2230 workspace.update(&mut cx, move |workspace, cx| {
2231 workspace.split_item(
2232 direction,
2233 Box::new(
2234 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2235 ),
2236 cx,
2237 )
2238 })?;
2239 anyhow::Ok(())
2240 })
2241 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2242 ErrorCode::RemoteUpgradeRequired => Some(format!(
2243 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2244 e.error_tag("required").unwrap_or("the latest version")
2245 )),
2246 _ => None,
2247 });
2248 }
2249
2250 pub fn leader_peer_id(&self) -> Option<PeerId> {
2251 self.leader_peer_id
2252 }
2253
2254 pub fn buffer(&self) -> &Model<MultiBuffer> {
2255 &self.buffer
2256 }
2257
2258 pub fn workspace(&self) -> Option<View<Workspace>> {
2259 self.workspace.as_ref()?.0.upgrade()
2260 }
2261
2262 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2263 self.buffer().read(cx).title(cx)
2264 }
2265
2266 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2267 let git_blame_gutter_max_author_length = self
2268 .render_git_blame_gutter(cx)
2269 .then(|| {
2270 if let Some(blame) = self.blame.as_ref() {
2271 let max_author_length =
2272 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2273 Some(max_author_length)
2274 } else {
2275 None
2276 }
2277 })
2278 .flatten();
2279
2280 EditorSnapshot {
2281 mode: self.mode,
2282 show_gutter: self.show_gutter,
2283 show_line_numbers: self.show_line_numbers,
2284 show_git_diff_gutter: self.show_git_diff_gutter,
2285 show_code_actions: self.show_code_actions,
2286 show_runnables: self.show_runnables,
2287 git_blame_gutter_max_author_length,
2288 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2289 scroll_anchor: self.scroll_manager.anchor(),
2290 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2291 placeholder_text: self.placeholder_text.clone(),
2292 is_focused: self.focus_handle.is_focused(cx),
2293 current_line_highlight: self
2294 .current_line_highlight
2295 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2296 gutter_hovered: self.gutter_hovered,
2297 }
2298 }
2299
2300 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2301 self.buffer.read(cx).language_at(point, cx)
2302 }
2303
2304 pub fn file_at<T: ToOffset>(
2305 &self,
2306 point: T,
2307 cx: &AppContext,
2308 ) -> Option<Arc<dyn language::File>> {
2309 self.buffer.read(cx).read(cx).file_at(point).cloned()
2310 }
2311
2312 pub fn active_excerpt(
2313 &self,
2314 cx: &AppContext,
2315 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2316 self.buffer
2317 .read(cx)
2318 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2319 }
2320
2321 pub fn mode(&self) -> EditorMode {
2322 self.mode
2323 }
2324
2325 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2326 self.collaboration_hub.as_deref()
2327 }
2328
2329 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2330 self.collaboration_hub = Some(hub);
2331 }
2332
2333 pub fn set_custom_context_menu(
2334 &mut self,
2335 f: impl 'static
2336 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2337 ) {
2338 self.custom_context_menu = Some(Box::new(f))
2339 }
2340
2341 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2342 self.completion_provider = provider;
2343 }
2344
2345 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2346 self.semantics_provider.clone()
2347 }
2348
2349 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2350 self.semantics_provider = provider;
2351 }
2352
2353 pub fn set_inline_completion_provider<T>(
2354 &mut self,
2355 provider: Option<Model<T>>,
2356 cx: &mut ViewContext<Self>,
2357 ) where
2358 T: InlineCompletionProvider,
2359 {
2360 self.inline_completion_provider =
2361 provider.map(|provider| RegisteredInlineCompletionProvider {
2362 _subscription: cx.observe(&provider, |this, _, cx| {
2363 if this.focus_handle.is_focused(cx) {
2364 this.update_visible_inline_completion(cx);
2365 }
2366 }),
2367 provider: Arc::new(provider),
2368 });
2369 self.refresh_inline_completion(false, false, cx);
2370 }
2371
2372 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2373 self.placeholder_text.as_deref()
2374 }
2375
2376 pub fn set_placeholder_text(
2377 &mut self,
2378 placeholder_text: impl Into<Arc<str>>,
2379 cx: &mut ViewContext<Self>,
2380 ) {
2381 let placeholder_text = Some(placeholder_text.into());
2382 if self.placeholder_text != placeholder_text {
2383 self.placeholder_text = placeholder_text;
2384 cx.notify();
2385 }
2386 }
2387
2388 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2389 self.cursor_shape = cursor_shape;
2390
2391 // Disrupt blink for immediate user feedback that the cursor shape has changed
2392 self.blink_manager.update(cx, BlinkManager::show_cursor);
2393
2394 cx.notify();
2395 }
2396
2397 pub fn set_current_line_highlight(
2398 &mut self,
2399 current_line_highlight: Option<CurrentLineHighlight>,
2400 ) {
2401 self.current_line_highlight = current_line_highlight;
2402 }
2403
2404 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2405 self.collapse_matches = collapse_matches;
2406 }
2407
2408 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2409 if self.collapse_matches {
2410 return range.start..range.start;
2411 }
2412 range.clone()
2413 }
2414
2415 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2416 if self.display_map.read(cx).clip_at_line_ends != clip {
2417 self.display_map
2418 .update(cx, |map, _| map.clip_at_line_ends = clip);
2419 }
2420 }
2421
2422 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2423 self.input_enabled = input_enabled;
2424 }
2425
2426 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2427 self.enable_inline_completions = enabled;
2428 }
2429
2430 pub fn set_autoindent(&mut self, autoindent: bool) {
2431 if autoindent {
2432 self.autoindent_mode = Some(AutoindentMode::EachLine);
2433 } else {
2434 self.autoindent_mode = None;
2435 }
2436 }
2437
2438 pub fn read_only(&self, cx: &AppContext) -> bool {
2439 self.read_only || self.buffer.read(cx).read_only()
2440 }
2441
2442 pub fn set_read_only(&mut self, read_only: bool) {
2443 self.read_only = read_only;
2444 }
2445
2446 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2447 self.use_autoclose = autoclose;
2448 }
2449
2450 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2451 self.use_auto_surround = auto_surround;
2452 }
2453
2454 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2455 self.auto_replace_emoji_shortcode = auto_replace;
2456 }
2457
2458 pub fn toggle_inline_completions(
2459 &mut self,
2460 _: &ToggleInlineCompletions,
2461 cx: &mut ViewContext<Self>,
2462 ) {
2463 if self.show_inline_completions_override.is_some() {
2464 self.set_show_inline_completions(None, cx);
2465 } else {
2466 let cursor = self.selections.newest_anchor().head();
2467 if let Some((buffer, cursor_buffer_position)) =
2468 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2469 {
2470 let show_inline_completions =
2471 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2472 self.set_show_inline_completions(Some(show_inline_completions), cx);
2473 }
2474 }
2475 }
2476
2477 pub fn set_show_inline_completions(
2478 &mut self,
2479 show_inline_completions: Option<bool>,
2480 cx: &mut ViewContext<Self>,
2481 ) {
2482 self.show_inline_completions_override = show_inline_completions;
2483 self.refresh_inline_completion(false, true, cx);
2484 }
2485
2486 fn should_show_inline_completions(
2487 &self,
2488 buffer: &Model<Buffer>,
2489 buffer_position: language::Anchor,
2490 cx: &AppContext,
2491 ) -> bool {
2492 if let Some(provider) = self.inline_completion_provider() {
2493 if let Some(show_inline_completions) = self.show_inline_completions_override {
2494 show_inline_completions
2495 } else {
2496 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2497 }
2498 } else {
2499 false
2500 }
2501 }
2502
2503 pub fn set_use_modal_editing(&mut self, to: bool) {
2504 self.use_modal_editing = to;
2505 }
2506
2507 pub fn use_modal_editing(&self) -> bool {
2508 self.use_modal_editing
2509 }
2510
2511 fn selections_did_change(
2512 &mut self,
2513 local: bool,
2514 old_cursor_position: &Anchor,
2515 show_completions: bool,
2516 cx: &mut ViewContext<Self>,
2517 ) {
2518 cx.invalidate_character_coordinates();
2519
2520 // Copy selections to primary selection buffer
2521 #[cfg(target_os = "linux")]
2522 if local {
2523 let selections = self.selections.all::<usize>(cx);
2524 let buffer_handle = self.buffer.read(cx).read(cx);
2525
2526 let mut text = String::new();
2527 for (index, selection) in selections.iter().enumerate() {
2528 let text_for_selection = buffer_handle
2529 .text_for_range(selection.start..selection.end)
2530 .collect::<String>();
2531
2532 text.push_str(&text_for_selection);
2533 if index != selections.len() - 1 {
2534 text.push('\n');
2535 }
2536 }
2537
2538 if !text.is_empty() {
2539 cx.write_to_primary(ClipboardItem::new_string(text));
2540 }
2541 }
2542
2543 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2544 self.buffer.update(cx, |buffer, cx| {
2545 buffer.set_active_selections(
2546 &self.selections.disjoint_anchors(),
2547 self.selections.line_mode,
2548 self.cursor_shape,
2549 cx,
2550 )
2551 });
2552 }
2553 let display_map = self
2554 .display_map
2555 .update(cx, |display_map, cx| display_map.snapshot(cx));
2556 let buffer = &display_map.buffer_snapshot;
2557 self.add_selections_state = None;
2558 self.select_next_state = None;
2559 self.select_prev_state = None;
2560 self.select_larger_syntax_node_stack.clear();
2561 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2562 self.snippet_stack
2563 .invalidate(&self.selections.disjoint_anchors(), buffer);
2564 self.take_rename(false, cx);
2565
2566 let new_cursor_position = self.selections.newest_anchor().head();
2567
2568 self.push_to_nav_history(
2569 *old_cursor_position,
2570 Some(new_cursor_position.to_point(buffer)),
2571 cx,
2572 );
2573
2574 if local {
2575 let new_cursor_position = self.selections.newest_anchor().head();
2576 let mut context_menu = self.context_menu.write();
2577 let completion_menu = match context_menu.as_ref() {
2578 Some(ContextMenu::Completions(menu)) => Some(menu),
2579
2580 _ => {
2581 *context_menu = None;
2582 None
2583 }
2584 };
2585
2586 if let Some(completion_menu) = completion_menu {
2587 let cursor_position = new_cursor_position.to_offset(buffer);
2588 let (word_range, kind) =
2589 buffer.surrounding_word(completion_menu.initial_position, true);
2590 if kind == Some(CharKind::Word)
2591 && word_range.to_inclusive().contains(&cursor_position)
2592 {
2593 let mut completion_menu = completion_menu.clone();
2594 drop(context_menu);
2595
2596 let query = Self::completion_query(buffer, cursor_position);
2597 cx.spawn(move |this, mut cx| async move {
2598 completion_menu
2599 .filter(query.as_deref(), cx.background_executor().clone())
2600 .await;
2601
2602 this.update(&mut cx, |this, cx| {
2603 let mut context_menu = this.context_menu.write();
2604 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2605 return;
2606 };
2607
2608 if menu.id > completion_menu.id {
2609 return;
2610 }
2611
2612 *context_menu = Some(ContextMenu::Completions(completion_menu));
2613 drop(context_menu);
2614 cx.notify();
2615 })
2616 })
2617 .detach();
2618
2619 if show_completions {
2620 self.show_completions(&ShowCompletions { trigger: None }, cx);
2621 }
2622 } else {
2623 drop(context_menu);
2624 self.hide_context_menu(cx);
2625 }
2626 } else {
2627 drop(context_menu);
2628 }
2629
2630 hide_hover(self, cx);
2631
2632 if old_cursor_position.to_display_point(&display_map).row()
2633 != new_cursor_position.to_display_point(&display_map).row()
2634 {
2635 self.available_code_actions.take();
2636 }
2637 self.refresh_code_actions(cx);
2638 self.refresh_document_highlights(cx);
2639 refresh_matching_bracket_highlights(self, cx);
2640 self.discard_inline_completion(false, cx);
2641 linked_editing_ranges::refresh_linked_ranges(self, cx);
2642 if self.git_blame_inline_enabled {
2643 self.start_inline_blame_timer(cx);
2644 }
2645 }
2646
2647 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2648 cx.emit(EditorEvent::SelectionsChanged { local });
2649
2650 if self.selections.disjoint_anchors().len() == 1 {
2651 cx.emit(SearchEvent::ActiveMatchChanged)
2652 }
2653 cx.notify();
2654 }
2655
2656 pub fn change_selections<R>(
2657 &mut self,
2658 autoscroll: Option<Autoscroll>,
2659 cx: &mut ViewContext<Self>,
2660 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2661 ) -> R {
2662 self.change_selections_inner(autoscroll, true, cx, change)
2663 }
2664
2665 pub fn change_selections_inner<R>(
2666 &mut self,
2667 autoscroll: Option<Autoscroll>,
2668 request_completions: bool,
2669 cx: &mut ViewContext<Self>,
2670 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2671 ) -> R {
2672 let old_cursor_position = self.selections.newest_anchor().head();
2673 self.push_to_selection_history();
2674
2675 let (changed, result) = self.selections.change_with(cx, change);
2676
2677 if changed {
2678 if let Some(autoscroll) = autoscroll {
2679 self.request_autoscroll(autoscroll, cx);
2680 }
2681 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2682
2683 if self.should_open_signature_help_automatically(
2684 &old_cursor_position,
2685 self.signature_help_state.backspace_pressed(),
2686 cx,
2687 ) {
2688 self.show_signature_help(&ShowSignatureHelp, cx);
2689 }
2690 self.signature_help_state.set_backspace_pressed(false);
2691 }
2692
2693 result
2694 }
2695
2696 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2697 where
2698 I: IntoIterator<Item = (Range<S>, T)>,
2699 S: ToOffset,
2700 T: Into<Arc<str>>,
2701 {
2702 if self.read_only(cx) {
2703 return;
2704 }
2705
2706 self.buffer
2707 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2708 }
2709
2710 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2711 where
2712 I: IntoIterator<Item = (Range<S>, T)>,
2713 S: ToOffset,
2714 T: Into<Arc<str>>,
2715 {
2716 if self.read_only(cx) {
2717 return;
2718 }
2719
2720 self.buffer.update(cx, |buffer, cx| {
2721 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2722 });
2723 }
2724
2725 pub fn edit_with_block_indent<I, S, T>(
2726 &mut self,
2727 edits: I,
2728 original_indent_columns: Vec<u32>,
2729 cx: &mut ViewContext<Self>,
2730 ) where
2731 I: IntoIterator<Item = (Range<S>, T)>,
2732 S: ToOffset,
2733 T: Into<Arc<str>>,
2734 {
2735 if self.read_only(cx) {
2736 return;
2737 }
2738
2739 self.buffer.update(cx, |buffer, cx| {
2740 buffer.edit(
2741 edits,
2742 Some(AutoindentMode::Block {
2743 original_indent_columns,
2744 }),
2745 cx,
2746 )
2747 });
2748 }
2749
2750 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2751 self.hide_context_menu(cx);
2752
2753 match phase {
2754 SelectPhase::Begin {
2755 position,
2756 add,
2757 click_count,
2758 } => self.begin_selection(position, add, click_count, cx),
2759 SelectPhase::BeginColumnar {
2760 position,
2761 goal_column,
2762 reset,
2763 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2764 SelectPhase::Extend {
2765 position,
2766 click_count,
2767 } => self.extend_selection(position, click_count, cx),
2768 SelectPhase::Update {
2769 position,
2770 goal_column,
2771 scroll_delta,
2772 } => self.update_selection(position, goal_column, scroll_delta, cx),
2773 SelectPhase::End => self.end_selection(cx),
2774 }
2775 }
2776
2777 fn extend_selection(
2778 &mut self,
2779 position: DisplayPoint,
2780 click_count: usize,
2781 cx: &mut ViewContext<Self>,
2782 ) {
2783 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2784 let tail = self.selections.newest::<usize>(cx).tail();
2785 self.begin_selection(position, false, click_count, cx);
2786
2787 let position = position.to_offset(&display_map, Bias::Left);
2788 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2789
2790 let mut pending_selection = self
2791 .selections
2792 .pending_anchor()
2793 .expect("extend_selection not called with pending selection");
2794 if position >= tail {
2795 pending_selection.start = tail_anchor;
2796 } else {
2797 pending_selection.end = tail_anchor;
2798 pending_selection.reversed = true;
2799 }
2800
2801 let mut pending_mode = self.selections.pending_mode().unwrap();
2802 match &mut pending_mode {
2803 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2804 _ => {}
2805 }
2806
2807 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2808 s.set_pending(pending_selection, pending_mode)
2809 });
2810 }
2811
2812 fn begin_selection(
2813 &mut self,
2814 position: DisplayPoint,
2815 add: bool,
2816 click_count: usize,
2817 cx: &mut ViewContext<Self>,
2818 ) {
2819 if !self.focus_handle.is_focused(cx) {
2820 self.last_focused_descendant = None;
2821 cx.focus(&self.focus_handle);
2822 }
2823
2824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2825 let buffer = &display_map.buffer_snapshot;
2826 let newest_selection = self.selections.newest_anchor().clone();
2827 let position = display_map.clip_point(position, Bias::Left);
2828
2829 let start;
2830 let end;
2831 let mode;
2832 let auto_scroll;
2833 match click_count {
2834 1 => {
2835 start = buffer.anchor_before(position.to_point(&display_map));
2836 end = start;
2837 mode = SelectMode::Character;
2838 auto_scroll = true;
2839 }
2840 2 => {
2841 let range = movement::surrounding_word(&display_map, position);
2842 start = buffer.anchor_before(range.start.to_point(&display_map));
2843 end = buffer.anchor_before(range.end.to_point(&display_map));
2844 mode = SelectMode::Word(start..end);
2845 auto_scroll = true;
2846 }
2847 3 => {
2848 let position = display_map
2849 .clip_point(position, Bias::Left)
2850 .to_point(&display_map);
2851 let line_start = display_map.prev_line_boundary(position).0;
2852 let next_line_start = buffer.clip_point(
2853 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2854 Bias::Left,
2855 );
2856 start = buffer.anchor_before(line_start);
2857 end = buffer.anchor_before(next_line_start);
2858 mode = SelectMode::Line(start..end);
2859 auto_scroll = true;
2860 }
2861 _ => {
2862 start = buffer.anchor_before(0);
2863 end = buffer.anchor_before(buffer.len());
2864 mode = SelectMode::All;
2865 auto_scroll = false;
2866 }
2867 }
2868
2869 let point_to_delete: Option<usize> = {
2870 let selected_points: Vec<Selection<Point>> =
2871 self.selections.disjoint_in_range(start..end, cx);
2872
2873 if !add || click_count > 1 {
2874 None
2875 } else if !selected_points.is_empty() {
2876 Some(selected_points[0].id)
2877 } else {
2878 let clicked_point_already_selected =
2879 self.selections.disjoint.iter().find(|selection| {
2880 selection.start.to_point(buffer) == start.to_point(buffer)
2881 || selection.end.to_point(buffer) == end.to_point(buffer)
2882 });
2883
2884 clicked_point_already_selected.map(|selection| selection.id)
2885 }
2886 };
2887
2888 let selections_count = self.selections.count();
2889
2890 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2891 if let Some(point_to_delete) = point_to_delete {
2892 s.delete(point_to_delete);
2893
2894 if selections_count == 1 {
2895 s.set_pending_anchor_range(start..end, mode);
2896 }
2897 } else {
2898 if !add {
2899 s.clear_disjoint();
2900 } else if click_count > 1 {
2901 s.delete(newest_selection.id)
2902 }
2903
2904 s.set_pending_anchor_range(start..end, mode);
2905 }
2906 });
2907 }
2908
2909 fn begin_columnar_selection(
2910 &mut self,
2911 position: DisplayPoint,
2912 goal_column: u32,
2913 reset: bool,
2914 cx: &mut ViewContext<Self>,
2915 ) {
2916 if !self.focus_handle.is_focused(cx) {
2917 self.last_focused_descendant = None;
2918 cx.focus(&self.focus_handle);
2919 }
2920
2921 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2922
2923 if reset {
2924 let pointer_position = display_map
2925 .buffer_snapshot
2926 .anchor_before(position.to_point(&display_map));
2927
2928 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2929 s.clear_disjoint();
2930 s.set_pending_anchor_range(
2931 pointer_position..pointer_position,
2932 SelectMode::Character,
2933 );
2934 });
2935 }
2936
2937 let tail = self.selections.newest::<Point>(cx).tail();
2938 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2939
2940 if !reset {
2941 self.select_columns(
2942 tail.to_display_point(&display_map),
2943 position,
2944 goal_column,
2945 &display_map,
2946 cx,
2947 );
2948 }
2949 }
2950
2951 fn update_selection(
2952 &mut self,
2953 position: DisplayPoint,
2954 goal_column: u32,
2955 scroll_delta: gpui::Point<f32>,
2956 cx: &mut ViewContext<Self>,
2957 ) {
2958 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2959
2960 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2961 let tail = tail.to_display_point(&display_map);
2962 self.select_columns(tail, position, goal_column, &display_map, cx);
2963 } else if let Some(mut pending) = self.selections.pending_anchor() {
2964 let buffer = self.buffer.read(cx).snapshot(cx);
2965 let head;
2966 let tail;
2967 let mode = self.selections.pending_mode().unwrap();
2968 match &mode {
2969 SelectMode::Character => {
2970 head = position.to_point(&display_map);
2971 tail = pending.tail().to_point(&buffer);
2972 }
2973 SelectMode::Word(original_range) => {
2974 let original_display_range = original_range.start.to_display_point(&display_map)
2975 ..original_range.end.to_display_point(&display_map);
2976 let original_buffer_range = original_display_range.start.to_point(&display_map)
2977 ..original_display_range.end.to_point(&display_map);
2978 if movement::is_inside_word(&display_map, position)
2979 || original_display_range.contains(&position)
2980 {
2981 let word_range = movement::surrounding_word(&display_map, position);
2982 if word_range.start < original_display_range.start {
2983 head = word_range.start.to_point(&display_map);
2984 } else {
2985 head = word_range.end.to_point(&display_map);
2986 }
2987 } else {
2988 head = position.to_point(&display_map);
2989 }
2990
2991 if head <= original_buffer_range.start {
2992 tail = original_buffer_range.end;
2993 } else {
2994 tail = original_buffer_range.start;
2995 }
2996 }
2997 SelectMode::Line(original_range) => {
2998 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2999
3000 let position = display_map
3001 .clip_point(position, Bias::Left)
3002 .to_point(&display_map);
3003 let line_start = display_map.prev_line_boundary(position).0;
3004 let next_line_start = buffer.clip_point(
3005 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3006 Bias::Left,
3007 );
3008
3009 if line_start < original_range.start {
3010 head = line_start
3011 } else {
3012 head = next_line_start
3013 }
3014
3015 if head <= original_range.start {
3016 tail = original_range.end;
3017 } else {
3018 tail = original_range.start;
3019 }
3020 }
3021 SelectMode::All => {
3022 return;
3023 }
3024 };
3025
3026 if head < tail {
3027 pending.start = buffer.anchor_before(head);
3028 pending.end = buffer.anchor_before(tail);
3029 pending.reversed = true;
3030 } else {
3031 pending.start = buffer.anchor_before(tail);
3032 pending.end = buffer.anchor_before(head);
3033 pending.reversed = false;
3034 }
3035
3036 self.change_selections(None, cx, |s| {
3037 s.set_pending(pending, mode);
3038 });
3039 } else {
3040 log::error!("update_selection dispatched with no pending selection");
3041 return;
3042 }
3043
3044 self.apply_scroll_delta(scroll_delta, cx);
3045 cx.notify();
3046 }
3047
3048 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3049 self.columnar_selection_tail.take();
3050 if self.selections.pending_anchor().is_some() {
3051 let selections = self.selections.all::<usize>(cx);
3052 self.change_selections(None, cx, |s| {
3053 s.select(selections);
3054 s.clear_pending();
3055 });
3056 }
3057 }
3058
3059 fn select_columns(
3060 &mut self,
3061 tail: DisplayPoint,
3062 head: DisplayPoint,
3063 goal_column: u32,
3064 display_map: &DisplaySnapshot,
3065 cx: &mut ViewContext<Self>,
3066 ) {
3067 let start_row = cmp::min(tail.row(), head.row());
3068 let end_row = cmp::max(tail.row(), head.row());
3069 let start_column = cmp::min(tail.column(), goal_column);
3070 let end_column = cmp::max(tail.column(), goal_column);
3071 let reversed = start_column < tail.column();
3072
3073 let selection_ranges = (start_row.0..=end_row.0)
3074 .map(DisplayRow)
3075 .filter_map(|row| {
3076 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3077 let start = display_map
3078 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3079 .to_point(display_map);
3080 let end = display_map
3081 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3082 .to_point(display_map);
3083 if reversed {
3084 Some(end..start)
3085 } else {
3086 Some(start..end)
3087 }
3088 } else {
3089 None
3090 }
3091 })
3092 .collect::<Vec<_>>();
3093
3094 self.change_selections(None, cx, |s| {
3095 s.select_ranges(selection_ranges);
3096 });
3097 cx.notify();
3098 }
3099
3100 pub fn has_pending_nonempty_selection(&self) -> bool {
3101 let pending_nonempty_selection = match self.selections.pending_anchor() {
3102 Some(Selection { start, end, .. }) => start != end,
3103 None => false,
3104 };
3105
3106 pending_nonempty_selection
3107 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3108 }
3109
3110 pub fn has_pending_selection(&self) -> bool {
3111 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3112 }
3113
3114 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3115 if self.clear_expanded_diff_hunks(cx) {
3116 cx.notify();
3117 return;
3118 }
3119 if self.dismiss_menus_and_popups(true, cx) {
3120 return;
3121 }
3122
3123 if self.mode == EditorMode::Full
3124 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3125 {
3126 return;
3127 }
3128
3129 cx.propagate();
3130 }
3131
3132 pub fn dismiss_menus_and_popups(
3133 &mut self,
3134 should_report_inline_completion_event: bool,
3135 cx: &mut ViewContext<Self>,
3136 ) -> bool {
3137 if self.take_rename(false, cx).is_some() {
3138 return true;
3139 }
3140
3141 if hide_hover(self, cx) {
3142 return true;
3143 }
3144
3145 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3146 return true;
3147 }
3148
3149 if self.hide_context_menu(cx).is_some() {
3150 return true;
3151 }
3152
3153 if self.mouse_context_menu.take().is_some() {
3154 return true;
3155 }
3156
3157 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3158 return true;
3159 }
3160
3161 if self.snippet_stack.pop().is_some() {
3162 return true;
3163 }
3164
3165 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3166 self.dismiss_diagnostics(cx);
3167 return true;
3168 }
3169
3170 false
3171 }
3172
3173 fn linked_editing_ranges_for(
3174 &self,
3175 selection: Range<text::Anchor>,
3176 cx: &AppContext,
3177 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3178 if self.linked_edit_ranges.is_empty() {
3179 return None;
3180 }
3181 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3182 selection.end.buffer_id.and_then(|end_buffer_id| {
3183 if selection.start.buffer_id != Some(end_buffer_id) {
3184 return None;
3185 }
3186 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3187 let snapshot = buffer.read(cx).snapshot();
3188 self.linked_edit_ranges
3189 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3190 .map(|ranges| (ranges, snapshot, buffer))
3191 })?;
3192 use text::ToOffset as TO;
3193 // find offset from the start of current range to current cursor position
3194 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3195
3196 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3197 let start_difference = start_offset - start_byte_offset;
3198 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3199 let end_difference = end_offset - start_byte_offset;
3200 // Current range has associated linked ranges.
3201 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3202 for range in linked_ranges.iter() {
3203 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3204 let end_offset = start_offset + end_difference;
3205 let start_offset = start_offset + start_difference;
3206 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3207 continue;
3208 }
3209 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3210 if s.start.buffer_id != selection.start.buffer_id
3211 || s.end.buffer_id != selection.end.buffer_id
3212 {
3213 return false;
3214 }
3215 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3216 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3217 }) {
3218 continue;
3219 }
3220 let start = buffer_snapshot.anchor_after(start_offset);
3221 let end = buffer_snapshot.anchor_after(end_offset);
3222 linked_edits
3223 .entry(buffer.clone())
3224 .or_default()
3225 .push(start..end);
3226 }
3227 Some(linked_edits)
3228 }
3229
3230 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3231 let text: Arc<str> = text.into();
3232
3233 if self.read_only(cx) {
3234 return;
3235 }
3236
3237 let selections = self.selections.all_adjusted(cx);
3238 let mut bracket_inserted = false;
3239 let mut edits = Vec::new();
3240 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3241 let mut new_selections = Vec::with_capacity(selections.len());
3242 let mut new_autoclose_regions = Vec::new();
3243 let snapshot = self.buffer.read(cx).read(cx);
3244
3245 for (selection, autoclose_region) in
3246 self.selections_with_autoclose_regions(selections, &snapshot)
3247 {
3248 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3249 // Determine if the inserted text matches the opening or closing
3250 // bracket of any of this language's bracket pairs.
3251 let mut bracket_pair = None;
3252 let mut is_bracket_pair_start = false;
3253 let mut is_bracket_pair_end = false;
3254 if !text.is_empty() {
3255 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3256 // and they are removing the character that triggered IME popup.
3257 for (pair, enabled) in scope.brackets() {
3258 if !pair.close && !pair.surround {
3259 continue;
3260 }
3261
3262 if enabled && pair.start.ends_with(text.as_ref()) {
3263 let prefix_len = pair.start.len() - text.len();
3264 let preceding_text_matches_prefix = prefix_len == 0
3265 || (selection.start.column >= (prefix_len as u32)
3266 && snapshot.contains_str_at(
3267 Point::new(
3268 selection.start.row,
3269 selection.start.column - (prefix_len as u32),
3270 ),
3271 &pair.start[..prefix_len],
3272 ));
3273 if preceding_text_matches_prefix {
3274 bracket_pair = Some(pair.clone());
3275 is_bracket_pair_start = true;
3276 break;
3277 }
3278 }
3279 if pair.end.as_str() == text.as_ref() {
3280 bracket_pair = Some(pair.clone());
3281 is_bracket_pair_end = true;
3282 break;
3283 }
3284 }
3285 }
3286
3287 if let Some(bracket_pair) = bracket_pair {
3288 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3289 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3290 let auto_surround =
3291 self.use_auto_surround && snapshot_settings.use_auto_surround;
3292 if selection.is_empty() {
3293 if is_bracket_pair_start {
3294 // If the inserted text is a suffix of an opening bracket and the
3295 // selection is preceded by the rest of the opening bracket, then
3296 // insert the closing bracket.
3297 let following_text_allows_autoclose = snapshot
3298 .chars_at(selection.start)
3299 .next()
3300 .map_or(true, |c| scope.should_autoclose_before(c));
3301
3302 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3303 && bracket_pair.start.len() == 1
3304 {
3305 let target = bracket_pair.start.chars().next().unwrap();
3306 let current_line_count = snapshot
3307 .reversed_chars_at(selection.start)
3308 .take_while(|&c| c != '\n')
3309 .filter(|&c| c == target)
3310 .count();
3311 current_line_count % 2 == 1
3312 } else {
3313 false
3314 };
3315
3316 if autoclose
3317 && bracket_pair.close
3318 && following_text_allows_autoclose
3319 && !is_closing_quote
3320 {
3321 let anchor = snapshot.anchor_before(selection.end);
3322 new_selections.push((selection.map(|_| anchor), text.len()));
3323 new_autoclose_regions.push((
3324 anchor,
3325 text.len(),
3326 selection.id,
3327 bracket_pair.clone(),
3328 ));
3329 edits.push((
3330 selection.range(),
3331 format!("{}{}", text, bracket_pair.end).into(),
3332 ));
3333 bracket_inserted = true;
3334 continue;
3335 }
3336 }
3337
3338 if let Some(region) = autoclose_region {
3339 // If the selection is followed by an auto-inserted closing bracket,
3340 // then don't insert that closing bracket again; just move the selection
3341 // past the closing bracket.
3342 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3343 && text.as_ref() == region.pair.end.as_str();
3344 if should_skip {
3345 let anchor = snapshot.anchor_after(selection.end);
3346 new_selections
3347 .push((selection.map(|_| anchor), region.pair.end.len()));
3348 continue;
3349 }
3350 }
3351
3352 let always_treat_brackets_as_autoclosed = snapshot
3353 .settings_at(selection.start, cx)
3354 .always_treat_brackets_as_autoclosed;
3355 if always_treat_brackets_as_autoclosed
3356 && is_bracket_pair_end
3357 && snapshot.contains_str_at(selection.end, text.as_ref())
3358 {
3359 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3360 // and the inserted text is a closing bracket and the selection is followed
3361 // by the closing bracket then move the selection past the closing bracket.
3362 let anchor = snapshot.anchor_after(selection.end);
3363 new_selections.push((selection.map(|_| anchor), text.len()));
3364 continue;
3365 }
3366 }
3367 // If an opening bracket is 1 character long and is typed while
3368 // text is selected, then surround that text with the bracket pair.
3369 else if auto_surround
3370 && bracket_pair.surround
3371 && is_bracket_pair_start
3372 && bracket_pair.start.chars().count() == 1
3373 {
3374 edits.push((selection.start..selection.start, text.clone()));
3375 edits.push((
3376 selection.end..selection.end,
3377 bracket_pair.end.as_str().into(),
3378 ));
3379 bracket_inserted = true;
3380 new_selections.push((
3381 Selection {
3382 id: selection.id,
3383 start: snapshot.anchor_after(selection.start),
3384 end: snapshot.anchor_before(selection.end),
3385 reversed: selection.reversed,
3386 goal: selection.goal,
3387 },
3388 0,
3389 ));
3390 continue;
3391 }
3392 }
3393 }
3394
3395 if self.auto_replace_emoji_shortcode
3396 && selection.is_empty()
3397 && text.as_ref().ends_with(':')
3398 {
3399 if let Some(possible_emoji_short_code) =
3400 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3401 {
3402 if !possible_emoji_short_code.is_empty() {
3403 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3404 let emoji_shortcode_start = Point::new(
3405 selection.start.row,
3406 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3407 );
3408
3409 // Remove shortcode from buffer
3410 edits.push((
3411 emoji_shortcode_start..selection.start,
3412 "".to_string().into(),
3413 ));
3414 new_selections.push((
3415 Selection {
3416 id: selection.id,
3417 start: snapshot.anchor_after(emoji_shortcode_start),
3418 end: snapshot.anchor_before(selection.start),
3419 reversed: selection.reversed,
3420 goal: selection.goal,
3421 },
3422 0,
3423 ));
3424
3425 // Insert emoji
3426 let selection_start_anchor = snapshot.anchor_after(selection.start);
3427 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3428 edits.push((selection.start..selection.end, emoji.to_string().into()));
3429
3430 continue;
3431 }
3432 }
3433 }
3434 }
3435
3436 // If not handling any auto-close operation, then just replace the selected
3437 // text with the given input and move the selection to the end of the
3438 // newly inserted text.
3439 let anchor = snapshot.anchor_after(selection.end);
3440 if !self.linked_edit_ranges.is_empty() {
3441 let start_anchor = snapshot.anchor_before(selection.start);
3442
3443 let is_word_char = text.chars().next().map_or(true, |char| {
3444 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3445 classifier.is_word(char)
3446 });
3447
3448 if is_word_char {
3449 if let Some(ranges) = self
3450 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3451 {
3452 for (buffer, edits) in ranges {
3453 linked_edits
3454 .entry(buffer.clone())
3455 .or_default()
3456 .extend(edits.into_iter().map(|range| (range, text.clone())));
3457 }
3458 }
3459 }
3460 }
3461
3462 new_selections.push((selection.map(|_| anchor), 0));
3463 edits.push((selection.start..selection.end, text.clone()));
3464 }
3465
3466 drop(snapshot);
3467
3468 self.transact(cx, |this, cx| {
3469 this.buffer.update(cx, |buffer, cx| {
3470 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3471 });
3472 for (buffer, edits) in linked_edits {
3473 buffer.update(cx, |buffer, cx| {
3474 let snapshot = buffer.snapshot();
3475 let edits = edits
3476 .into_iter()
3477 .map(|(range, text)| {
3478 use text::ToPoint as TP;
3479 let end_point = TP::to_point(&range.end, &snapshot);
3480 let start_point = TP::to_point(&range.start, &snapshot);
3481 (start_point..end_point, text)
3482 })
3483 .sorted_by_key(|(range, _)| range.start)
3484 .collect::<Vec<_>>();
3485 buffer.edit(edits, None, cx);
3486 })
3487 }
3488 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3489 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3490 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3491 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3492 .zip(new_selection_deltas)
3493 .map(|(selection, delta)| Selection {
3494 id: selection.id,
3495 start: selection.start + delta,
3496 end: selection.end + delta,
3497 reversed: selection.reversed,
3498 goal: SelectionGoal::None,
3499 })
3500 .collect::<Vec<_>>();
3501
3502 let mut i = 0;
3503 for (position, delta, selection_id, pair) in new_autoclose_regions {
3504 let position = position.to_offset(&map.buffer_snapshot) + delta;
3505 let start = map.buffer_snapshot.anchor_before(position);
3506 let end = map.buffer_snapshot.anchor_after(position);
3507 while let Some(existing_state) = this.autoclose_regions.get(i) {
3508 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3509 Ordering::Less => i += 1,
3510 Ordering::Greater => break,
3511 Ordering::Equal => {
3512 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3513 Ordering::Less => i += 1,
3514 Ordering::Equal => break,
3515 Ordering::Greater => break,
3516 }
3517 }
3518 }
3519 }
3520 this.autoclose_regions.insert(
3521 i,
3522 AutocloseRegion {
3523 selection_id,
3524 range: start..end,
3525 pair,
3526 },
3527 );
3528 }
3529
3530 let had_active_inline_completion = this.has_active_inline_completion(cx);
3531 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3532 s.select(new_selections)
3533 });
3534
3535 if !bracket_inserted {
3536 if let Some(on_type_format_task) =
3537 this.trigger_on_type_formatting(text.to_string(), cx)
3538 {
3539 on_type_format_task.detach_and_log_err(cx);
3540 }
3541 }
3542
3543 let editor_settings = EditorSettings::get_global(cx);
3544 if bracket_inserted
3545 && (editor_settings.auto_signature_help
3546 || editor_settings.show_signature_help_after_edits)
3547 {
3548 this.show_signature_help(&ShowSignatureHelp, cx);
3549 }
3550
3551 let trigger_in_words = !had_active_inline_completion;
3552 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3553 linked_editing_ranges::refresh_linked_ranges(this, cx);
3554 this.refresh_inline_completion(true, false, cx);
3555 });
3556 }
3557
3558 fn find_possible_emoji_shortcode_at_position(
3559 snapshot: &MultiBufferSnapshot,
3560 position: Point,
3561 ) -> Option<String> {
3562 let mut chars = Vec::new();
3563 let mut found_colon = false;
3564 for char in snapshot.reversed_chars_at(position).take(100) {
3565 // Found a possible emoji shortcode in the middle of the buffer
3566 if found_colon {
3567 if char.is_whitespace() {
3568 chars.reverse();
3569 return Some(chars.iter().collect());
3570 }
3571 // If the previous character is not a whitespace, we are in the middle of a word
3572 // and we only want to complete the shortcode if the word is made up of other emojis
3573 let mut containing_word = String::new();
3574 for ch in snapshot
3575 .reversed_chars_at(position)
3576 .skip(chars.len() + 1)
3577 .take(100)
3578 {
3579 if ch.is_whitespace() {
3580 break;
3581 }
3582 containing_word.push(ch);
3583 }
3584 let containing_word = containing_word.chars().rev().collect::<String>();
3585 if util::word_consists_of_emojis(containing_word.as_str()) {
3586 chars.reverse();
3587 return Some(chars.iter().collect());
3588 }
3589 }
3590
3591 if char.is_whitespace() || !char.is_ascii() {
3592 return None;
3593 }
3594 if char == ':' {
3595 found_colon = true;
3596 } else {
3597 chars.push(char);
3598 }
3599 }
3600 // Found a possible emoji shortcode at the beginning of the buffer
3601 chars.reverse();
3602 Some(chars.iter().collect())
3603 }
3604
3605 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3606 self.transact(cx, |this, cx| {
3607 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3608 let selections = this.selections.all::<usize>(cx);
3609 let multi_buffer = this.buffer.read(cx);
3610 let buffer = multi_buffer.snapshot(cx);
3611 selections
3612 .iter()
3613 .map(|selection| {
3614 let start_point = selection.start.to_point(&buffer);
3615 let mut indent =
3616 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3617 indent.len = cmp::min(indent.len, start_point.column);
3618 let start = selection.start;
3619 let end = selection.end;
3620 let selection_is_empty = start == end;
3621 let language_scope = buffer.language_scope_at(start);
3622 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3623 &language_scope
3624 {
3625 let leading_whitespace_len = buffer
3626 .reversed_chars_at(start)
3627 .take_while(|c| c.is_whitespace() && *c != '\n')
3628 .map(|c| c.len_utf8())
3629 .sum::<usize>();
3630
3631 let trailing_whitespace_len = buffer
3632 .chars_at(end)
3633 .take_while(|c| c.is_whitespace() && *c != '\n')
3634 .map(|c| c.len_utf8())
3635 .sum::<usize>();
3636
3637 let insert_extra_newline =
3638 language.brackets().any(|(pair, enabled)| {
3639 let pair_start = pair.start.trim_end();
3640 let pair_end = pair.end.trim_start();
3641
3642 enabled
3643 && pair.newline
3644 && buffer.contains_str_at(
3645 end + trailing_whitespace_len,
3646 pair_end,
3647 )
3648 && buffer.contains_str_at(
3649 (start - leading_whitespace_len)
3650 .saturating_sub(pair_start.len()),
3651 pair_start,
3652 )
3653 });
3654
3655 // Comment extension on newline is allowed only for cursor selections
3656 let comment_delimiter = maybe!({
3657 if !selection_is_empty {
3658 return None;
3659 }
3660
3661 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3662 return None;
3663 }
3664
3665 let delimiters = language.line_comment_prefixes();
3666 let max_len_of_delimiter =
3667 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3668 let (snapshot, range) =
3669 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3670
3671 let mut index_of_first_non_whitespace = 0;
3672 let comment_candidate = snapshot
3673 .chars_for_range(range)
3674 .skip_while(|c| {
3675 let should_skip = c.is_whitespace();
3676 if should_skip {
3677 index_of_first_non_whitespace += 1;
3678 }
3679 should_skip
3680 })
3681 .take(max_len_of_delimiter)
3682 .collect::<String>();
3683 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3684 comment_candidate.starts_with(comment_prefix.as_ref())
3685 })?;
3686 let cursor_is_placed_after_comment_marker =
3687 index_of_first_non_whitespace + comment_prefix.len()
3688 <= start_point.column as usize;
3689 if cursor_is_placed_after_comment_marker {
3690 Some(comment_prefix.clone())
3691 } else {
3692 None
3693 }
3694 });
3695 (comment_delimiter, insert_extra_newline)
3696 } else {
3697 (None, false)
3698 };
3699
3700 let capacity_for_delimiter = comment_delimiter
3701 .as_deref()
3702 .map(str::len)
3703 .unwrap_or_default();
3704 let mut new_text =
3705 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3706 new_text.push('\n');
3707 new_text.extend(indent.chars());
3708 if let Some(delimiter) = &comment_delimiter {
3709 new_text.push_str(delimiter);
3710 }
3711 if insert_extra_newline {
3712 new_text = new_text.repeat(2);
3713 }
3714
3715 let anchor = buffer.anchor_after(end);
3716 let new_selection = selection.map(|_| anchor);
3717 (
3718 (start..end, new_text),
3719 (insert_extra_newline, new_selection),
3720 )
3721 })
3722 .unzip()
3723 };
3724
3725 this.edit_with_autoindent(edits, cx);
3726 let buffer = this.buffer.read(cx).snapshot(cx);
3727 let new_selections = selection_fixup_info
3728 .into_iter()
3729 .map(|(extra_newline_inserted, new_selection)| {
3730 let mut cursor = new_selection.end.to_point(&buffer);
3731 if extra_newline_inserted {
3732 cursor.row -= 1;
3733 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3734 }
3735 new_selection.map(|_| cursor)
3736 })
3737 .collect();
3738
3739 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3740 this.refresh_inline_completion(true, false, cx);
3741 });
3742 }
3743
3744 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3745 let buffer = self.buffer.read(cx);
3746 let snapshot = buffer.snapshot(cx);
3747
3748 let mut edits = Vec::new();
3749 let mut rows = Vec::new();
3750
3751 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3752 let cursor = selection.head();
3753 let row = cursor.row;
3754
3755 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3756
3757 let newline = "\n".to_string();
3758 edits.push((start_of_line..start_of_line, newline));
3759
3760 rows.push(row + rows_inserted as u32);
3761 }
3762
3763 self.transact(cx, |editor, cx| {
3764 editor.edit(edits, cx);
3765
3766 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3767 let mut index = 0;
3768 s.move_cursors_with(|map, _, _| {
3769 let row = rows[index];
3770 index += 1;
3771
3772 let point = Point::new(row, 0);
3773 let boundary = map.next_line_boundary(point).1;
3774 let clipped = map.clip_point(boundary, Bias::Left);
3775
3776 (clipped, SelectionGoal::None)
3777 });
3778 });
3779
3780 let mut indent_edits = Vec::new();
3781 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3782 for row in rows {
3783 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3784 for (row, indent) in indents {
3785 if indent.len == 0 {
3786 continue;
3787 }
3788
3789 let text = match indent.kind {
3790 IndentKind::Space => " ".repeat(indent.len as usize),
3791 IndentKind::Tab => "\t".repeat(indent.len as usize),
3792 };
3793 let point = Point::new(row.0, 0);
3794 indent_edits.push((point..point, text));
3795 }
3796 }
3797 editor.edit(indent_edits, cx);
3798 });
3799 }
3800
3801 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3802 let buffer = self.buffer.read(cx);
3803 let snapshot = buffer.snapshot(cx);
3804
3805 let mut edits = Vec::new();
3806 let mut rows = Vec::new();
3807 let mut rows_inserted = 0;
3808
3809 for selection in self.selections.all_adjusted(cx) {
3810 let cursor = selection.head();
3811 let row = cursor.row;
3812
3813 let point = Point::new(row + 1, 0);
3814 let start_of_line = snapshot.clip_point(point, Bias::Left);
3815
3816 let newline = "\n".to_string();
3817 edits.push((start_of_line..start_of_line, newline));
3818
3819 rows_inserted += 1;
3820 rows.push(row + rows_inserted);
3821 }
3822
3823 self.transact(cx, |editor, cx| {
3824 editor.edit(edits, cx);
3825
3826 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3827 let mut index = 0;
3828 s.move_cursors_with(|map, _, _| {
3829 let row = rows[index];
3830 index += 1;
3831
3832 let point = Point::new(row, 0);
3833 let boundary = map.next_line_boundary(point).1;
3834 let clipped = map.clip_point(boundary, Bias::Left);
3835
3836 (clipped, SelectionGoal::None)
3837 });
3838 });
3839
3840 let mut indent_edits = Vec::new();
3841 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3842 for row in rows {
3843 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3844 for (row, indent) in indents {
3845 if indent.len == 0 {
3846 continue;
3847 }
3848
3849 let text = match indent.kind {
3850 IndentKind::Space => " ".repeat(indent.len as usize),
3851 IndentKind::Tab => "\t".repeat(indent.len as usize),
3852 };
3853 let point = Point::new(row.0, 0);
3854 indent_edits.push((point..point, text));
3855 }
3856 }
3857 editor.edit(indent_edits, cx);
3858 });
3859 }
3860
3861 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3862 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3863 original_indent_columns: Vec::new(),
3864 });
3865 self.insert_with_autoindent_mode(text, autoindent, cx);
3866 }
3867
3868 fn insert_with_autoindent_mode(
3869 &mut self,
3870 text: &str,
3871 autoindent_mode: Option<AutoindentMode>,
3872 cx: &mut ViewContext<Self>,
3873 ) {
3874 if self.read_only(cx) {
3875 return;
3876 }
3877
3878 let text: Arc<str> = text.into();
3879 self.transact(cx, |this, cx| {
3880 let old_selections = this.selections.all_adjusted(cx);
3881 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3882 let anchors = {
3883 let snapshot = buffer.read(cx);
3884 old_selections
3885 .iter()
3886 .map(|s| {
3887 let anchor = snapshot.anchor_after(s.head());
3888 s.map(|_| anchor)
3889 })
3890 .collect::<Vec<_>>()
3891 };
3892 buffer.edit(
3893 old_selections
3894 .iter()
3895 .map(|s| (s.start..s.end, text.clone())),
3896 autoindent_mode,
3897 cx,
3898 );
3899 anchors
3900 });
3901
3902 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3903 s.select_anchors(selection_anchors);
3904 })
3905 });
3906 }
3907
3908 fn trigger_completion_on_input(
3909 &mut self,
3910 text: &str,
3911 trigger_in_words: bool,
3912 cx: &mut ViewContext<Self>,
3913 ) {
3914 if self.is_completion_trigger(text, trigger_in_words, cx) {
3915 self.show_completions(
3916 &ShowCompletions {
3917 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3918 },
3919 cx,
3920 );
3921 } else {
3922 self.hide_context_menu(cx);
3923 }
3924 }
3925
3926 fn is_completion_trigger(
3927 &self,
3928 text: &str,
3929 trigger_in_words: bool,
3930 cx: &mut ViewContext<Self>,
3931 ) -> bool {
3932 let position = self.selections.newest_anchor().head();
3933 let multibuffer = self.buffer.read(cx);
3934 let Some(buffer) = position
3935 .buffer_id
3936 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3937 else {
3938 return false;
3939 };
3940
3941 if let Some(completion_provider) = &self.completion_provider {
3942 completion_provider.is_completion_trigger(
3943 &buffer,
3944 position.text_anchor,
3945 text,
3946 trigger_in_words,
3947 cx,
3948 )
3949 } else {
3950 false
3951 }
3952 }
3953
3954 /// If any empty selections is touching the start of its innermost containing autoclose
3955 /// region, expand it to select the brackets.
3956 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3957 let selections = self.selections.all::<usize>(cx);
3958 let buffer = self.buffer.read(cx).read(cx);
3959 let new_selections = self
3960 .selections_with_autoclose_regions(selections, &buffer)
3961 .map(|(mut selection, region)| {
3962 if !selection.is_empty() {
3963 return selection;
3964 }
3965
3966 if let Some(region) = region {
3967 let mut range = region.range.to_offset(&buffer);
3968 if selection.start == range.start && range.start >= region.pair.start.len() {
3969 range.start -= region.pair.start.len();
3970 if buffer.contains_str_at(range.start, ®ion.pair.start)
3971 && buffer.contains_str_at(range.end, ®ion.pair.end)
3972 {
3973 range.end += region.pair.end.len();
3974 selection.start = range.start;
3975 selection.end = range.end;
3976
3977 return selection;
3978 }
3979 }
3980 }
3981
3982 let always_treat_brackets_as_autoclosed = buffer
3983 .settings_at(selection.start, cx)
3984 .always_treat_brackets_as_autoclosed;
3985
3986 if !always_treat_brackets_as_autoclosed {
3987 return selection;
3988 }
3989
3990 if let Some(scope) = buffer.language_scope_at(selection.start) {
3991 for (pair, enabled) in scope.brackets() {
3992 if !enabled || !pair.close {
3993 continue;
3994 }
3995
3996 if buffer.contains_str_at(selection.start, &pair.end) {
3997 let pair_start_len = pair.start.len();
3998 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3999 {
4000 selection.start -= pair_start_len;
4001 selection.end += pair.end.len();
4002
4003 return selection;
4004 }
4005 }
4006 }
4007 }
4008
4009 selection
4010 })
4011 .collect();
4012
4013 drop(buffer);
4014 self.change_selections(None, cx, |selections| selections.select(new_selections));
4015 }
4016
4017 /// Iterate the given selections, and for each one, find the smallest surrounding
4018 /// autoclose region. This uses the ordering of the selections and the autoclose
4019 /// regions to avoid repeated comparisons.
4020 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4021 &'a self,
4022 selections: impl IntoIterator<Item = Selection<D>>,
4023 buffer: &'a MultiBufferSnapshot,
4024 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4025 let mut i = 0;
4026 let mut regions = self.autoclose_regions.as_slice();
4027 selections.into_iter().map(move |selection| {
4028 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4029
4030 let mut enclosing = None;
4031 while let Some(pair_state) = regions.get(i) {
4032 if pair_state.range.end.to_offset(buffer) < range.start {
4033 regions = ®ions[i + 1..];
4034 i = 0;
4035 } else if pair_state.range.start.to_offset(buffer) > range.end {
4036 break;
4037 } else {
4038 if pair_state.selection_id == selection.id {
4039 enclosing = Some(pair_state);
4040 }
4041 i += 1;
4042 }
4043 }
4044
4045 (selection, enclosing)
4046 })
4047 }
4048
4049 /// Remove any autoclose regions that no longer contain their selection.
4050 fn invalidate_autoclose_regions(
4051 &mut self,
4052 mut selections: &[Selection<Anchor>],
4053 buffer: &MultiBufferSnapshot,
4054 ) {
4055 self.autoclose_regions.retain(|state| {
4056 let mut i = 0;
4057 while let Some(selection) = selections.get(i) {
4058 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4059 selections = &selections[1..];
4060 continue;
4061 }
4062 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4063 break;
4064 }
4065 if selection.id == state.selection_id {
4066 return true;
4067 } else {
4068 i += 1;
4069 }
4070 }
4071 false
4072 });
4073 }
4074
4075 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4076 let offset = position.to_offset(buffer);
4077 let (word_range, kind) = buffer.surrounding_word(offset, true);
4078 if offset > word_range.start && kind == Some(CharKind::Word) {
4079 Some(
4080 buffer
4081 .text_for_range(word_range.start..offset)
4082 .collect::<String>(),
4083 )
4084 } else {
4085 None
4086 }
4087 }
4088
4089 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4090 self.refresh_inlay_hints(
4091 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4092 cx,
4093 );
4094 }
4095
4096 pub fn inlay_hints_enabled(&self) -> bool {
4097 self.inlay_hint_cache.enabled
4098 }
4099
4100 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4101 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4102 return;
4103 }
4104
4105 let reason_description = reason.description();
4106 let ignore_debounce = matches!(
4107 reason,
4108 InlayHintRefreshReason::SettingsChange(_)
4109 | InlayHintRefreshReason::Toggle(_)
4110 | InlayHintRefreshReason::ExcerptsRemoved(_)
4111 );
4112 let (invalidate_cache, required_languages) = match reason {
4113 InlayHintRefreshReason::Toggle(enabled) => {
4114 self.inlay_hint_cache.enabled = enabled;
4115 if enabled {
4116 (InvalidationStrategy::RefreshRequested, None)
4117 } else {
4118 self.inlay_hint_cache.clear();
4119 self.splice_inlays(
4120 self.visible_inlay_hints(cx)
4121 .iter()
4122 .map(|inlay| inlay.id)
4123 .collect(),
4124 Vec::new(),
4125 cx,
4126 );
4127 return;
4128 }
4129 }
4130 InlayHintRefreshReason::SettingsChange(new_settings) => {
4131 match self.inlay_hint_cache.update_settings(
4132 &self.buffer,
4133 new_settings,
4134 self.visible_inlay_hints(cx),
4135 cx,
4136 ) {
4137 ControlFlow::Break(Some(InlaySplice {
4138 to_remove,
4139 to_insert,
4140 })) => {
4141 self.splice_inlays(to_remove, to_insert, cx);
4142 return;
4143 }
4144 ControlFlow::Break(None) => return,
4145 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4146 }
4147 }
4148 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4149 if let Some(InlaySplice {
4150 to_remove,
4151 to_insert,
4152 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4153 {
4154 self.splice_inlays(to_remove, to_insert, cx);
4155 }
4156 return;
4157 }
4158 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4159 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4160 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4161 }
4162 InlayHintRefreshReason::RefreshRequested => {
4163 (InvalidationStrategy::RefreshRequested, None)
4164 }
4165 };
4166
4167 if let Some(InlaySplice {
4168 to_remove,
4169 to_insert,
4170 }) = self.inlay_hint_cache.spawn_hint_refresh(
4171 reason_description,
4172 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4173 invalidate_cache,
4174 ignore_debounce,
4175 cx,
4176 ) {
4177 self.splice_inlays(to_remove, to_insert, cx);
4178 }
4179 }
4180
4181 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4182 self.display_map
4183 .read(cx)
4184 .current_inlays()
4185 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4186 .cloned()
4187 .collect()
4188 }
4189
4190 pub fn excerpts_for_inlay_hints_query(
4191 &self,
4192 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4193 cx: &mut ViewContext<Editor>,
4194 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4195 let Some(project) = self.project.as_ref() else {
4196 return HashMap::default();
4197 };
4198 let project = project.read(cx);
4199 let multi_buffer = self.buffer().read(cx);
4200 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4201 let multi_buffer_visible_start = self
4202 .scroll_manager
4203 .anchor()
4204 .anchor
4205 .to_point(&multi_buffer_snapshot);
4206 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4207 multi_buffer_visible_start
4208 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4209 Bias::Left,
4210 );
4211 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4212 multi_buffer
4213 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4214 .into_iter()
4215 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4216 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4217 let buffer = buffer_handle.read(cx);
4218 let buffer_file = project::File::from_dyn(buffer.file())?;
4219 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4220 let worktree_entry = buffer_worktree
4221 .read(cx)
4222 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4223 if worktree_entry.is_ignored {
4224 return None;
4225 }
4226
4227 let language = buffer.language()?;
4228 if let Some(restrict_to_languages) = restrict_to_languages {
4229 if !restrict_to_languages.contains(language) {
4230 return None;
4231 }
4232 }
4233 Some((
4234 excerpt_id,
4235 (
4236 buffer_handle,
4237 buffer.version().clone(),
4238 excerpt_visible_range,
4239 ),
4240 ))
4241 })
4242 .collect()
4243 }
4244
4245 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4246 TextLayoutDetails {
4247 text_system: cx.text_system().clone(),
4248 editor_style: self.style.clone().unwrap(),
4249 rem_size: cx.rem_size(),
4250 scroll_anchor: self.scroll_manager.anchor(),
4251 visible_rows: self.visible_line_count(),
4252 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4253 }
4254 }
4255
4256 fn splice_inlays(
4257 &self,
4258 to_remove: Vec<InlayId>,
4259 to_insert: Vec<Inlay>,
4260 cx: &mut ViewContext<Self>,
4261 ) {
4262 self.display_map.update(cx, |display_map, cx| {
4263 display_map.splice_inlays(to_remove, to_insert, cx);
4264 });
4265 cx.notify();
4266 }
4267
4268 fn trigger_on_type_formatting(
4269 &self,
4270 input: String,
4271 cx: &mut ViewContext<Self>,
4272 ) -> Option<Task<Result<()>>> {
4273 if input.len() != 1 {
4274 return None;
4275 }
4276
4277 let project = self.project.as_ref()?;
4278 let position = self.selections.newest_anchor().head();
4279 let (buffer, buffer_position) = self
4280 .buffer
4281 .read(cx)
4282 .text_anchor_for_position(position, cx)?;
4283
4284 let settings = language_settings::language_settings(
4285 buffer
4286 .read(cx)
4287 .language_at(buffer_position)
4288 .map(|l| l.name()),
4289 buffer.read(cx).file(),
4290 cx,
4291 );
4292 if !settings.use_on_type_format {
4293 return None;
4294 }
4295
4296 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4297 // hence we do LSP request & edit on host side only — add formats to host's history.
4298 let push_to_lsp_host_history = true;
4299 // If this is not the host, append its history with new edits.
4300 let push_to_client_history = project.read(cx).is_via_collab();
4301
4302 let on_type_formatting = project.update(cx, |project, cx| {
4303 project.on_type_format(
4304 buffer.clone(),
4305 buffer_position,
4306 input,
4307 push_to_lsp_host_history,
4308 cx,
4309 )
4310 });
4311 Some(cx.spawn(|editor, mut cx| async move {
4312 if let Some(transaction) = on_type_formatting.await? {
4313 if push_to_client_history {
4314 buffer
4315 .update(&mut cx, |buffer, _| {
4316 buffer.push_transaction(transaction, Instant::now());
4317 })
4318 .ok();
4319 }
4320 editor.update(&mut cx, |editor, cx| {
4321 editor.refresh_document_highlights(cx);
4322 })?;
4323 }
4324 Ok(())
4325 }))
4326 }
4327
4328 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4329 if self.pending_rename.is_some() {
4330 return;
4331 }
4332
4333 let Some(provider) = self.completion_provider.as_ref() else {
4334 return;
4335 };
4336
4337 let position = self.selections.newest_anchor().head();
4338 let (buffer, buffer_position) =
4339 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4340 output
4341 } else {
4342 return;
4343 };
4344
4345 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4346 let is_followup_invoke = {
4347 let context_menu_state = self.context_menu.read();
4348 matches!(
4349 context_menu_state.deref(),
4350 Some(ContextMenu::Completions(_))
4351 )
4352 };
4353 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4354 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4355 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4356 CompletionTriggerKind::TRIGGER_CHARACTER
4357 }
4358
4359 _ => CompletionTriggerKind::INVOKED,
4360 };
4361 let completion_context = CompletionContext {
4362 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4363 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4364 Some(String::from(trigger))
4365 } else {
4366 None
4367 }
4368 }),
4369 trigger_kind,
4370 };
4371 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4372 let sort_completions = provider.sort_completions();
4373
4374 let id = post_inc(&mut self.next_completion_id);
4375 let task = cx.spawn(|this, mut cx| {
4376 async move {
4377 this.update(&mut cx, |this, _| {
4378 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4379 })?;
4380 let completions = completions.await.log_err();
4381 let menu = if let Some(completions) = completions {
4382 let mut menu = CompletionsMenu {
4383 id,
4384 sort_completions,
4385 initial_position: position,
4386 match_candidates: completions
4387 .iter()
4388 .enumerate()
4389 .map(|(id, completion)| {
4390 StringMatchCandidate::new(
4391 id,
4392 completion.label.text[completion.label.filter_range.clone()]
4393 .into(),
4394 )
4395 })
4396 .collect(),
4397 buffer: buffer.clone(),
4398 completions: Arc::new(RwLock::new(completions.into())),
4399 matches: Vec::new().into(),
4400 selected_item: 0,
4401 scroll_handle: UniformListScrollHandle::new(),
4402 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4403 DebouncedDelay::new(),
4404 )),
4405 };
4406 menu.filter(query.as_deref(), cx.background_executor().clone())
4407 .await;
4408
4409 if menu.matches.is_empty() {
4410 None
4411 } else {
4412 this.update(&mut cx, |editor, cx| {
4413 let completions = menu.completions.clone();
4414 let matches = menu.matches.clone();
4415
4416 let delay_ms = EditorSettings::get_global(cx)
4417 .completion_documentation_secondary_query_debounce;
4418 let delay = Duration::from_millis(delay_ms);
4419 editor
4420 .completion_documentation_pre_resolve_debounce
4421 .fire_new(delay, cx, |editor, cx| {
4422 CompletionsMenu::pre_resolve_completion_documentation(
4423 buffer,
4424 completions,
4425 matches,
4426 editor,
4427 cx,
4428 )
4429 });
4430 })
4431 .ok();
4432 Some(menu)
4433 }
4434 } else {
4435 None
4436 };
4437
4438 this.update(&mut cx, |this, cx| {
4439 let mut context_menu = this.context_menu.write();
4440 match context_menu.as_ref() {
4441 None => {}
4442
4443 Some(ContextMenu::Completions(prev_menu)) => {
4444 if prev_menu.id > id {
4445 return;
4446 }
4447 }
4448
4449 _ => return,
4450 }
4451
4452 if this.focus_handle.is_focused(cx) && menu.is_some() {
4453 let menu = menu.unwrap();
4454 *context_menu = Some(ContextMenu::Completions(menu));
4455 drop(context_menu);
4456 this.discard_inline_completion(false, cx);
4457 cx.notify();
4458 } else if this.completion_tasks.len() <= 1 {
4459 // If there are no more completion tasks and the last menu was
4460 // empty, we should hide it. If it was already hidden, we should
4461 // also show the copilot completion when available.
4462 drop(context_menu);
4463 if this.hide_context_menu(cx).is_none() {
4464 this.update_visible_inline_completion(cx);
4465 }
4466 }
4467 })?;
4468
4469 Ok::<_, anyhow::Error>(())
4470 }
4471 .log_err()
4472 });
4473
4474 self.completion_tasks.push((id, task));
4475 }
4476
4477 pub fn confirm_completion(
4478 &mut self,
4479 action: &ConfirmCompletion,
4480 cx: &mut ViewContext<Self>,
4481 ) -> Option<Task<Result<()>>> {
4482 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4483 }
4484
4485 pub fn compose_completion(
4486 &mut self,
4487 action: &ComposeCompletion,
4488 cx: &mut ViewContext<Self>,
4489 ) -> Option<Task<Result<()>>> {
4490 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4491 }
4492
4493 fn do_completion(
4494 &mut self,
4495 item_ix: Option<usize>,
4496 intent: CompletionIntent,
4497 cx: &mut ViewContext<Editor>,
4498 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4499 use language::ToOffset as _;
4500
4501 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4502 menu
4503 } else {
4504 return None;
4505 };
4506
4507 let mat = completions_menu
4508 .matches
4509 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4510 let buffer_handle = completions_menu.buffer;
4511 let completions = completions_menu.completions.read();
4512 let completion = completions.get(mat.candidate_id)?;
4513 cx.stop_propagation();
4514
4515 let snippet;
4516 let text;
4517
4518 if completion.is_snippet() {
4519 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4520 text = snippet.as_ref().unwrap().text.clone();
4521 } else {
4522 snippet = None;
4523 text = completion.new_text.clone();
4524 };
4525 let selections = self.selections.all::<usize>(cx);
4526 let buffer = buffer_handle.read(cx);
4527 let old_range = completion.old_range.to_offset(buffer);
4528 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4529
4530 let newest_selection = self.selections.newest_anchor();
4531 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4532 return None;
4533 }
4534
4535 let lookbehind = newest_selection
4536 .start
4537 .text_anchor
4538 .to_offset(buffer)
4539 .saturating_sub(old_range.start);
4540 let lookahead = old_range
4541 .end
4542 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4543 let mut common_prefix_len = old_text
4544 .bytes()
4545 .zip(text.bytes())
4546 .take_while(|(a, b)| a == b)
4547 .count();
4548
4549 let snapshot = self.buffer.read(cx).snapshot(cx);
4550 let mut range_to_replace: Option<Range<isize>> = None;
4551 let mut ranges = Vec::new();
4552 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4553 for selection in &selections {
4554 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4555 let start = selection.start.saturating_sub(lookbehind);
4556 let end = selection.end + lookahead;
4557 if selection.id == newest_selection.id {
4558 range_to_replace = Some(
4559 ((start + common_prefix_len) as isize - selection.start as isize)
4560 ..(end as isize - selection.start as isize),
4561 );
4562 }
4563 ranges.push(start + common_prefix_len..end);
4564 } else {
4565 common_prefix_len = 0;
4566 ranges.clear();
4567 ranges.extend(selections.iter().map(|s| {
4568 if s.id == newest_selection.id {
4569 range_to_replace = Some(
4570 old_range.start.to_offset_utf16(&snapshot).0 as isize
4571 - selection.start as isize
4572 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4573 - selection.start as isize,
4574 );
4575 old_range.clone()
4576 } else {
4577 s.start..s.end
4578 }
4579 }));
4580 break;
4581 }
4582 if !self.linked_edit_ranges.is_empty() {
4583 let start_anchor = snapshot.anchor_before(selection.head());
4584 let end_anchor = snapshot.anchor_after(selection.tail());
4585 if let Some(ranges) = self
4586 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4587 {
4588 for (buffer, edits) in ranges {
4589 linked_edits.entry(buffer.clone()).or_default().extend(
4590 edits
4591 .into_iter()
4592 .map(|range| (range, text[common_prefix_len..].to_owned())),
4593 );
4594 }
4595 }
4596 }
4597 }
4598 let text = &text[common_prefix_len..];
4599
4600 cx.emit(EditorEvent::InputHandled {
4601 utf16_range_to_replace: range_to_replace,
4602 text: text.into(),
4603 });
4604
4605 self.transact(cx, |this, cx| {
4606 if let Some(mut snippet) = snippet {
4607 snippet.text = text.to_string();
4608 for tabstop in snippet.tabstops.iter_mut().flatten() {
4609 tabstop.start -= common_prefix_len as isize;
4610 tabstop.end -= common_prefix_len as isize;
4611 }
4612
4613 this.insert_snippet(&ranges, snippet, cx).log_err();
4614 } else {
4615 this.buffer.update(cx, |buffer, cx| {
4616 buffer.edit(
4617 ranges.iter().map(|range| (range.clone(), text)),
4618 this.autoindent_mode.clone(),
4619 cx,
4620 );
4621 });
4622 }
4623 for (buffer, edits) in linked_edits {
4624 buffer.update(cx, |buffer, cx| {
4625 let snapshot = buffer.snapshot();
4626 let edits = edits
4627 .into_iter()
4628 .map(|(range, text)| {
4629 use text::ToPoint as TP;
4630 let end_point = TP::to_point(&range.end, &snapshot);
4631 let start_point = TP::to_point(&range.start, &snapshot);
4632 (start_point..end_point, text)
4633 })
4634 .sorted_by_key(|(range, _)| range.start)
4635 .collect::<Vec<_>>();
4636 buffer.edit(edits, None, cx);
4637 })
4638 }
4639
4640 this.refresh_inline_completion(true, false, cx);
4641 });
4642
4643 let show_new_completions_on_confirm = completion
4644 .confirm
4645 .as_ref()
4646 .map_or(false, |confirm| confirm(intent, cx));
4647 if show_new_completions_on_confirm {
4648 self.show_completions(&ShowCompletions { trigger: None }, cx);
4649 }
4650
4651 let provider = self.completion_provider.as_ref()?;
4652 let apply_edits = provider.apply_additional_edits_for_completion(
4653 buffer_handle,
4654 completion.clone(),
4655 true,
4656 cx,
4657 );
4658
4659 let editor_settings = EditorSettings::get_global(cx);
4660 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4661 // After the code completion is finished, users often want to know what signatures are needed.
4662 // so we should automatically call signature_help
4663 self.show_signature_help(&ShowSignatureHelp, cx);
4664 }
4665
4666 Some(cx.foreground_executor().spawn(async move {
4667 apply_edits.await?;
4668 Ok(())
4669 }))
4670 }
4671
4672 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4673 let mut context_menu = self.context_menu.write();
4674 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4675 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4676 // Toggle if we're selecting the same one
4677 *context_menu = None;
4678 cx.notify();
4679 return;
4680 } else {
4681 // Otherwise, clear it and start a new one
4682 *context_menu = None;
4683 cx.notify();
4684 }
4685 }
4686 drop(context_menu);
4687 let snapshot = self.snapshot(cx);
4688 let deployed_from_indicator = action.deployed_from_indicator;
4689 let mut task = self.code_actions_task.take();
4690 let action = action.clone();
4691 cx.spawn(|editor, mut cx| async move {
4692 while let Some(prev_task) = task {
4693 prev_task.await.log_err();
4694 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4695 }
4696
4697 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4698 if editor.focus_handle.is_focused(cx) {
4699 let multibuffer_point = action
4700 .deployed_from_indicator
4701 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4702 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4703 let (buffer, buffer_row) = snapshot
4704 .buffer_snapshot
4705 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4706 .and_then(|(buffer_snapshot, range)| {
4707 editor
4708 .buffer
4709 .read(cx)
4710 .buffer(buffer_snapshot.remote_id())
4711 .map(|buffer| (buffer, range.start.row))
4712 })?;
4713 let (_, code_actions) = editor
4714 .available_code_actions
4715 .clone()
4716 .and_then(|(location, code_actions)| {
4717 let snapshot = location.buffer.read(cx).snapshot();
4718 let point_range = location.range.to_point(&snapshot);
4719 let point_range = point_range.start.row..=point_range.end.row;
4720 if point_range.contains(&buffer_row) {
4721 Some((location, code_actions))
4722 } else {
4723 None
4724 }
4725 })
4726 .unzip();
4727 let buffer_id = buffer.read(cx).remote_id();
4728 let tasks = editor
4729 .tasks
4730 .get(&(buffer_id, buffer_row))
4731 .map(|t| Arc::new(t.to_owned()));
4732 if tasks.is_none() && code_actions.is_none() {
4733 return None;
4734 }
4735
4736 editor.completion_tasks.clear();
4737 editor.discard_inline_completion(false, cx);
4738 let task_context =
4739 tasks
4740 .as_ref()
4741 .zip(editor.project.clone())
4742 .map(|(tasks, project)| {
4743 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4744 });
4745
4746 Some(cx.spawn(|editor, mut cx| async move {
4747 let task_context = match task_context {
4748 Some(task_context) => task_context.await,
4749 None => None,
4750 };
4751 let resolved_tasks =
4752 tasks.zip(task_context).map(|(tasks, task_context)| {
4753 Arc::new(ResolvedTasks {
4754 templates: tasks.resolve(&task_context).collect(),
4755 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4756 multibuffer_point.row,
4757 tasks.column,
4758 )),
4759 })
4760 });
4761 let spawn_straight_away = resolved_tasks
4762 .as_ref()
4763 .map_or(false, |tasks| tasks.templates.len() == 1)
4764 && code_actions
4765 .as_ref()
4766 .map_or(true, |actions| actions.is_empty());
4767 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4768 *editor.context_menu.write() =
4769 Some(ContextMenu::CodeActions(CodeActionsMenu {
4770 buffer,
4771 actions: CodeActionContents {
4772 tasks: resolved_tasks,
4773 actions: code_actions,
4774 },
4775 selected_item: Default::default(),
4776 scroll_handle: UniformListScrollHandle::default(),
4777 deployed_from_indicator,
4778 }));
4779 if spawn_straight_away {
4780 if let Some(task) = editor.confirm_code_action(
4781 &ConfirmCodeAction { item_ix: Some(0) },
4782 cx,
4783 ) {
4784 cx.notify();
4785 return task;
4786 }
4787 }
4788 cx.notify();
4789 Task::ready(Ok(()))
4790 }) {
4791 task.await
4792 } else {
4793 Ok(())
4794 }
4795 }))
4796 } else {
4797 Some(Task::ready(Ok(())))
4798 }
4799 })?;
4800 if let Some(task) = spawned_test_task {
4801 task.await?;
4802 }
4803
4804 Ok::<_, anyhow::Error>(())
4805 })
4806 .detach_and_log_err(cx);
4807 }
4808
4809 pub fn confirm_code_action(
4810 &mut self,
4811 action: &ConfirmCodeAction,
4812 cx: &mut ViewContext<Self>,
4813 ) -> Option<Task<Result<()>>> {
4814 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4815 menu
4816 } else {
4817 return None;
4818 };
4819 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4820 let action = actions_menu.actions.get(action_ix)?;
4821 let title = action.label();
4822 let buffer = actions_menu.buffer;
4823 let workspace = self.workspace()?;
4824
4825 match action {
4826 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4827 workspace.update(cx, |workspace, cx| {
4828 workspace::tasks::schedule_resolved_task(
4829 workspace,
4830 task_source_kind,
4831 resolved_task,
4832 false,
4833 cx,
4834 );
4835
4836 Some(Task::ready(Ok(())))
4837 })
4838 }
4839 CodeActionsItem::CodeAction {
4840 excerpt_id,
4841 action,
4842 provider,
4843 } => {
4844 let apply_code_action =
4845 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4846 let workspace = workspace.downgrade();
4847 Some(cx.spawn(|editor, cx| async move {
4848 let project_transaction = apply_code_action.await?;
4849 Self::open_project_transaction(
4850 &editor,
4851 workspace,
4852 project_transaction,
4853 title,
4854 cx,
4855 )
4856 .await
4857 }))
4858 }
4859 }
4860 }
4861
4862 pub async fn open_project_transaction(
4863 this: &WeakView<Editor>,
4864 workspace: WeakView<Workspace>,
4865 transaction: ProjectTransaction,
4866 title: String,
4867 mut cx: AsyncWindowContext,
4868 ) -> Result<()> {
4869 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4870 cx.update(|cx| {
4871 entries.sort_unstable_by_key(|(buffer, _)| {
4872 buffer.read(cx).file().map(|f| f.path().clone())
4873 });
4874 })?;
4875
4876 // If the project transaction's edits are all contained within this editor, then
4877 // avoid opening a new editor to display them.
4878
4879 if let Some((buffer, transaction)) = entries.first() {
4880 if entries.len() == 1 {
4881 let excerpt = this.update(&mut cx, |editor, cx| {
4882 editor
4883 .buffer()
4884 .read(cx)
4885 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4886 })?;
4887 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4888 if excerpted_buffer == *buffer {
4889 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4890 let excerpt_range = excerpt_range.to_offset(buffer);
4891 buffer
4892 .edited_ranges_for_transaction::<usize>(transaction)
4893 .all(|range| {
4894 excerpt_range.start <= range.start
4895 && excerpt_range.end >= range.end
4896 })
4897 })?;
4898
4899 if all_edits_within_excerpt {
4900 return Ok(());
4901 }
4902 }
4903 }
4904 }
4905 } else {
4906 return Ok(());
4907 }
4908
4909 let mut ranges_to_highlight = Vec::new();
4910 let excerpt_buffer = cx.new_model(|cx| {
4911 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4912 for (buffer_handle, transaction) in &entries {
4913 let buffer = buffer_handle.read(cx);
4914 ranges_to_highlight.extend(
4915 multibuffer.push_excerpts_with_context_lines(
4916 buffer_handle.clone(),
4917 buffer
4918 .edited_ranges_for_transaction::<usize>(transaction)
4919 .collect(),
4920 DEFAULT_MULTIBUFFER_CONTEXT,
4921 cx,
4922 ),
4923 );
4924 }
4925 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4926 multibuffer
4927 })?;
4928
4929 workspace.update(&mut cx, |workspace, cx| {
4930 let project = workspace.project().clone();
4931 let editor =
4932 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4933 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4934 editor.update(cx, |editor, cx| {
4935 editor.highlight_background::<Self>(
4936 &ranges_to_highlight,
4937 |theme| theme.editor_highlighted_line_background,
4938 cx,
4939 );
4940 });
4941 })?;
4942
4943 Ok(())
4944 }
4945
4946 pub fn clear_code_action_providers(&mut self) {
4947 self.code_action_providers.clear();
4948 self.available_code_actions.take();
4949 }
4950
4951 pub fn push_code_action_provider(
4952 &mut self,
4953 provider: Arc<dyn CodeActionProvider>,
4954 cx: &mut ViewContext<Self>,
4955 ) {
4956 self.code_action_providers.push(provider);
4957 self.refresh_code_actions(cx);
4958 }
4959
4960 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4961 let buffer = self.buffer.read(cx);
4962 let newest_selection = self.selections.newest_anchor().clone();
4963 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4964 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4965 if start_buffer != end_buffer {
4966 return None;
4967 }
4968
4969 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4970 cx.background_executor()
4971 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4972 .await;
4973
4974 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4975 let providers = this.code_action_providers.clone();
4976 let tasks = this
4977 .code_action_providers
4978 .iter()
4979 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4980 .collect::<Vec<_>>();
4981 (providers, tasks)
4982 })?;
4983
4984 let mut actions = Vec::new();
4985 for (provider, provider_actions) in
4986 providers.into_iter().zip(future::join_all(tasks).await)
4987 {
4988 if let Some(provider_actions) = provider_actions.log_err() {
4989 actions.extend(provider_actions.into_iter().map(|action| {
4990 AvailableCodeAction {
4991 excerpt_id: newest_selection.start.excerpt_id,
4992 action,
4993 provider: provider.clone(),
4994 }
4995 }));
4996 }
4997 }
4998
4999 this.update(&mut cx, |this, cx| {
5000 this.available_code_actions = if actions.is_empty() {
5001 None
5002 } else {
5003 Some((
5004 Location {
5005 buffer: start_buffer,
5006 range: start..end,
5007 },
5008 actions.into(),
5009 ))
5010 };
5011 cx.notify();
5012 })
5013 }));
5014 None
5015 }
5016
5017 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5018 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5019 self.show_git_blame_inline = false;
5020
5021 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5022 cx.background_executor().timer(delay).await;
5023
5024 this.update(&mut cx, |this, cx| {
5025 this.show_git_blame_inline = true;
5026 cx.notify();
5027 })
5028 .log_err();
5029 }));
5030 }
5031 }
5032
5033 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5034 if self.pending_rename.is_some() {
5035 return None;
5036 }
5037
5038 let provider = self.semantics_provider.clone()?;
5039 let buffer = self.buffer.read(cx);
5040 let newest_selection = self.selections.newest_anchor().clone();
5041 let cursor_position = newest_selection.head();
5042 let (cursor_buffer, cursor_buffer_position) =
5043 buffer.text_anchor_for_position(cursor_position, cx)?;
5044 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5045 if cursor_buffer != tail_buffer {
5046 return None;
5047 }
5048
5049 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5050 cx.background_executor()
5051 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5052 .await;
5053
5054 let highlights = if let Some(highlights) = cx
5055 .update(|cx| {
5056 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5057 })
5058 .ok()
5059 .flatten()
5060 {
5061 highlights.await.log_err()
5062 } else {
5063 None
5064 };
5065
5066 if let Some(highlights) = highlights {
5067 this.update(&mut cx, |this, cx| {
5068 if this.pending_rename.is_some() {
5069 return;
5070 }
5071
5072 let buffer_id = cursor_position.buffer_id;
5073 let buffer = this.buffer.read(cx);
5074 if !buffer
5075 .text_anchor_for_position(cursor_position, cx)
5076 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5077 {
5078 return;
5079 }
5080
5081 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5082 let mut write_ranges = Vec::new();
5083 let mut read_ranges = Vec::new();
5084 for highlight in highlights {
5085 for (excerpt_id, excerpt_range) in
5086 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5087 {
5088 let start = highlight
5089 .range
5090 .start
5091 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5092 let end = highlight
5093 .range
5094 .end
5095 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5096 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5097 continue;
5098 }
5099
5100 let range = Anchor {
5101 buffer_id,
5102 excerpt_id,
5103 text_anchor: start,
5104 }..Anchor {
5105 buffer_id,
5106 excerpt_id,
5107 text_anchor: end,
5108 };
5109 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5110 write_ranges.push(range);
5111 } else {
5112 read_ranges.push(range);
5113 }
5114 }
5115 }
5116
5117 this.highlight_background::<DocumentHighlightRead>(
5118 &read_ranges,
5119 |theme| theme.editor_document_highlight_read_background,
5120 cx,
5121 );
5122 this.highlight_background::<DocumentHighlightWrite>(
5123 &write_ranges,
5124 |theme| theme.editor_document_highlight_write_background,
5125 cx,
5126 );
5127 cx.notify();
5128 })
5129 .log_err();
5130 }
5131 }));
5132 None
5133 }
5134
5135 pub fn refresh_inline_completion(
5136 &mut self,
5137 debounce: bool,
5138 user_requested: bool,
5139 cx: &mut ViewContext<Self>,
5140 ) -> Option<()> {
5141 let provider = self.inline_completion_provider()?;
5142 let cursor = self.selections.newest_anchor().head();
5143 let (buffer, cursor_buffer_position) =
5144 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5145
5146 if !user_requested
5147 && (!self.enable_inline_completions
5148 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5149 {
5150 self.discard_inline_completion(false, cx);
5151 return None;
5152 }
5153
5154 self.update_visible_inline_completion(cx);
5155 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5156 Some(())
5157 }
5158
5159 fn cycle_inline_completion(
5160 &mut self,
5161 direction: Direction,
5162 cx: &mut ViewContext<Self>,
5163 ) -> Option<()> {
5164 let provider = self.inline_completion_provider()?;
5165 let cursor = self.selections.newest_anchor().head();
5166 let (buffer, cursor_buffer_position) =
5167 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5168 if !self.enable_inline_completions
5169 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5170 {
5171 return None;
5172 }
5173
5174 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5175 self.update_visible_inline_completion(cx);
5176
5177 Some(())
5178 }
5179
5180 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5181 if !self.has_active_inline_completion(cx) {
5182 self.refresh_inline_completion(false, true, cx);
5183 return;
5184 }
5185
5186 self.update_visible_inline_completion(cx);
5187 }
5188
5189 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5190 self.show_cursor_names(cx);
5191 }
5192
5193 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5194 self.show_cursor_names = true;
5195 cx.notify();
5196 cx.spawn(|this, mut cx| async move {
5197 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5198 this.update(&mut cx, |this, cx| {
5199 this.show_cursor_names = false;
5200 cx.notify()
5201 })
5202 .ok()
5203 })
5204 .detach();
5205 }
5206
5207 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5208 if self.has_active_inline_completion(cx) {
5209 self.cycle_inline_completion(Direction::Next, cx);
5210 } else {
5211 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5212 if is_copilot_disabled {
5213 cx.propagate();
5214 }
5215 }
5216 }
5217
5218 pub fn previous_inline_completion(
5219 &mut self,
5220 _: &PreviousInlineCompletion,
5221 cx: &mut ViewContext<Self>,
5222 ) {
5223 if self.has_active_inline_completion(cx) {
5224 self.cycle_inline_completion(Direction::Prev, cx);
5225 } else {
5226 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5227 if is_copilot_disabled {
5228 cx.propagate();
5229 }
5230 }
5231 }
5232
5233 pub fn accept_inline_completion(
5234 &mut self,
5235 _: &AcceptInlineCompletion,
5236 cx: &mut ViewContext<Self>,
5237 ) {
5238 let Some(completion) = self.take_active_inline_completion(cx) else {
5239 return;
5240 };
5241 if let Some(provider) = self.inline_completion_provider() {
5242 provider.accept(cx);
5243 }
5244
5245 cx.emit(EditorEvent::InputHandled {
5246 utf16_range_to_replace: None,
5247 text: completion.text.to_string().into(),
5248 });
5249
5250 if let Some(range) = completion.delete_range {
5251 self.change_selections(None, cx, |s| s.select_ranges([range]))
5252 }
5253 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5254 self.refresh_inline_completion(true, true, cx);
5255 cx.notify();
5256 }
5257
5258 pub fn accept_partial_inline_completion(
5259 &mut self,
5260 _: &AcceptPartialInlineCompletion,
5261 cx: &mut ViewContext<Self>,
5262 ) {
5263 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5264 if let Some(completion) = self.take_active_inline_completion(cx) {
5265 let mut partial_completion = completion
5266 .text
5267 .chars()
5268 .by_ref()
5269 .take_while(|c| c.is_alphabetic())
5270 .collect::<String>();
5271 if partial_completion.is_empty() {
5272 partial_completion = completion
5273 .text
5274 .chars()
5275 .by_ref()
5276 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5277 .collect::<String>();
5278 }
5279
5280 cx.emit(EditorEvent::InputHandled {
5281 utf16_range_to_replace: None,
5282 text: partial_completion.clone().into(),
5283 });
5284
5285 if let Some(range) = completion.delete_range {
5286 self.change_selections(None, cx, |s| s.select_ranges([range]))
5287 }
5288 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5289
5290 self.refresh_inline_completion(true, true, cx);
5291 cx.notify();
5292 }
5293 }
5294 }
5295
5296 fn discard_inline_completion(
5297 &mut self,
5298 should_report_inline_completion_event: bool,
5299 cx: &mut ViewContext<Self>,
5300 ) -> bool {
5301 if let Some(provider) = self.inline_completion_provider() {
5302 provider.discard(should_report_inline_completion_event, cx);
5303 }
5304
5305 self.take_active_inline_completion(cx).is_some()
5306 }
5307
5308 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5309 if let Some(completion) = self.active_inline_completion.as_ref() {
5310 let buffer = self.buffer.read(cx).read(cx);
5311 completion.position.is_valid(&buffer)
5312 } else {
5313 false
5314 }
5315 }
5316
5317 fn take_active_inline_completion(
5318 &mut self,
5319 cx: &mut ViewContext<Self>,
5320 ) -> Option<CompletionState> {
5321 let completion = self.active_inline_completion.take()?;
5322 let render_inlay_ids = completion.render_inlay_ids.clone();
5323 self.display_map.update(cx, |map, cx| {
5324 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5325 });
5326 let buffer = self.buffer.read(cx).read(cx);
5327
5328 if completion.position.is_valid(&buffer) {
5329 Some(completion)
5330 } else {
5331 None
5332 }
5333 }
5334
5335 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5336 let selection = self.selections.newest_anchor();
5337 let cursor = selection.head();
5338
5339 let excerpt_id = cursor.excerpt_id;
5340
5341 if self.context_menu.read().is_none()
5342 && self.completion_tasks.is_empty()
5343 && selection.start == selection.end
5344 {
5345 if let Some(provider) = self.inline_completion_provider() {
5346 if let Some((buffer, cursor_buffer_position)) =
5347 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5348 {
5349 if let Some(proposal) =
5350 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5351 {
5352 let mut to_remove = Vec::new();
5353 if let Some(completion) = self.active_inline_completion.take() {
5354 to_remove.extend(completion.render_inlay_ids.iter());
5355 }
5356
5357 let to_add = proposal
5358 .inlays
5359 .iter()
5360 .filter_map(|inlay| {
5361 let snapshot = self.buffer.read(cx).snapshot(cx);
5362 let id = post_inc(&mut self.next_inlay_id);
5363 match inlay {
5364 InlayProposal::Hint(position, hint) => {
5365 let position =
5366 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5367 Some(Inlay::hint(id, position, hint))
5368 }
5369 InlayProposal::Suggestion(position, text) => {
5370 let position =
5371 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5372 Some(Inlay::suggestion(id, position, text.clone()))
5373 }
5374 }
5375 })
5376 .collect_vec();
5377
5378 self.active_inline_completion = Some(CompletionState {
5379 position: cursor,
5380 text: proposal.text,
5381 delete_range: proposal.delete_range.and_then(|range| {
5382 let snapshot = self.buffer.read(cx).snapshot(cx);
5383 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5384 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5385 Some(start?..end?)
5386 }),
5387 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5388 });
5389
5390 self.display_map
5391 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5392
5393 cx.notify();
5394 return;
5395 }
5396 }
5397 }
5398 }
5399
5400 self.discard_inline_completion(false, cx);
5401 }
5402
5403 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5404 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5405 }
5406
5407 fn render_code_actions_indicator(
5408 &self,
5409 _style: &EditorStyle,
5410 row: DisplayRow,
5411 is_active: bool,
5412 cx: &mut ViewContext<Self>,
5413 ) -> Option<IconButton> {
5414 if self.available_code_actions.is_some() {
5415 Some(
5416 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5417 .shape(ui::IconButtonShape::Square)
5418 .icon_size(IconSize::XSmall)
5419 .icon_color(Color::Muted)
5420 .selected(is_active)
5421 .tooltip({
5422 let focus_handle = self.focus_handle.clone();
5423 move |cx| {
5424 Tooltip::for_action_in(
5425 "Toggle Code Actions",
5426 &ToggleCodeActions {
5427 deployed_from_indicator: None,
5428 },
5429 &focus_handle,
5430 cx,
5431 )
5432 }
5433 })
5434 .on_click(cx.listener(move |editor, _e, cx| {
5435 editor.focus(cx);
5436 editor.toggle_code_actions(
5437 &ToggleCodeActions {
5438 deployed_from_indicator: Some(row),
5439 },
5440 cx,
5441 );
5442 })),
5443 )
5444 } else {
5445 None
5446 }
5447 }
5448
5449 fn clear_tasks(&mut self) {
5450 self.tasks.clear()
5451 }
5452
5453 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5454 if self.tasks.insert(key, value).is_some() {
5455 // This case should hopefully be rare, but just in case...
5456 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5457 }
5458 }
5459
5460 fn build_tasks_context(
5461 project: &Model<Project>,
5462 buffer: &Model<Buffer>,
5463 buffer_row: u32,
5464 tasks: &Arc<RunnableTasks>,
5465 cx: &mut ViewContext<Self>,
5466 ) -> Task<Option<task::TaskContext>> {
5467 let position = Point::new(buffer_row, tasks.column);
5468 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5469 let location = Location {
5470 buffer: buffer.clone(),
5471 range: range_start..range_start,
5472 };
5473 // Fill in the environmental variables from the tree-sitter captures
5474 let mut captured_task_variables = TaskVariables::default();
5475 for (capture_name, value) in tasks.extra_variables.clone() {
5476 captured_task_variables.insert(
5477 task::VariableName::Custom(capture_name.into()),
5478 value.clone(),
5479 );
5480 }
5481 project.update(cx, |project, cx| {
5482 project.task_store().update(cx, |task_store, cx| {
5483 task_store.task_context_for_location(captured_task_variables, location, cx)
5484 })
5485 })
5486 }
5487
5488 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5489 let Some((workspace, _)) = self.workspace.clone() else {
5490 return;
5491 };
5492 let Some(project) = self.project.clone() else {
5493 return;
5494 };
5495
5496 // Try to find a closest, enclosing node using tree-sitter that has a
5497 // task
5498 let Some((buffer, buffer_row, tasks)) = self
5499 .find_enclosing_node_task(cx)
5500 // Or find the task that's closest in row-distance.
5501 .or_else(|| self.find_closest_task(cx))
5502 else {
5503 return;
5504 };
5505
5506 let reveal_strategy = action.reveal;
5507 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5508 cx.spawn(|_, mut cx| async move {
5509 let context = task_context.await?;
5510 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5511
5512 let resolved = resolved_task.resolved.as_mut()?;
5513 resolved.reveal = reveal_strategy;
5514
5515 workspace
5516 .update(&mut cx, |workspace, cx| {
5517 workspace::tasks::schedule_resolved_task(
5518 workspace,
5519 task_source_kind,
5520 resolved_task,
5521 false,
5522 cx,
5523 );
5524 })
5525 .ok()
5526 })
5527 .detach();
5528 }
5529
5530 fn find_closest_task(
5531 &mut self,
5532 cx: &mut ViewContext<Self>,
5533 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5534 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5535
5536 let ((buffer_id, row), tasks) = self
5537 .tasks
5538 .iter()
5539 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5540
5541 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5542 let tasks = Arc::new(tasks.to_owned());
5543 Some((buffer, *row, tasks))
5544 }
5545
5546 fn find_enclosing_node_task(
5547 &mut self,
5548 cx: &mut ViewContext<Self>,
5549 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5550 let snapshot = self.buffer.read(cx).snapshot(cx);
5551 let offset = self.selections.newest::<usize>(cx).head();
5552 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5553 let buffer_id = excerpt.buffer().remote_id();
5554
5555 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5556 let mut cursor = layer.node().walk();
5557
5558 while cursor.goto_first_child_for_byte(offset).is_some() {
5559 if cursor.node().end_byte() == offset {
5560 cursor.goto_next_sibling();
5561 }
5562 }
5563
5564 // Ascend to the smallest ancestor that contains the range and has a task.
5565 loop {
5566 let node = cursor.node();
5567 let node_range = node.byte_range();
5568 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5569
5570 // Check if this node contains our offset
5571 if node_range.start <= offset && node_range.end >= offset {
5572 // If it contains offset, check for task
5573 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5574 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5575 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5576 }
5577 }
5578
5579 if !cursor.goto_parent() {
5580 break;
5581 }
5582 }
5583 None
5584 }
5585
5586 fn render_run_indicator(
5587 &self,
5588 _style: &EditorStyle,
5589 is_active: bool,
5590 row: DisplayRow,
5591 cx: &mut ViewContext<Self>,
5592 ) -> IconButton {
5593 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5594 .shape(ui::IconButtonShape::Square)
5595 .icon_size(IconSize::XSmall)
5596 .icon_color(Color::Muted)
5597 .selected(is_active)
5598 .on_click(cx.listener(move |editor, _e, cx| {
5599 editor.focus(cx);
5600 editor.toggle_code_actions(
5601 &ToggleCodeActions {
5602 deployed_from_indicator: Some(row),
5603 },
5604 cx,
5605 );
5606 }))
5607 }
5608
5609 pub fn context_menu_visible(&self) -> bool {
5610 self.context_menu
5611 .read()
5612 .as_ref()
5613 .map_or(false, |menu| menu.visible())
5614 }
5615
5616 fn render_context_menu(
5617 &self,
5618 cursor_position: DisplayPoint,
5619 style: &EditorStyle,
5620 max_height: Pixels,
5621 cx: &mut ViewContext<Editor>,
5622 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5623 self.context_menu.read().as_ref().map(|menu| {
5624 menu.render(
5625 cursor_position,
5626 style,
5627 max_height,
5628 self.workspace.as_ref().map(|(w, _)| w.clone()),
5629 cx,
5630 )
5631 })
5632 }
5633
5634 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5635 cx.notify();
5636 self.completion_tasks.clear();
5637 let context_menu = self.context_menu.write().take();
5638 if context_menu.is_some() {
5639 self.update_visible_inline_completion(cx);
5640 }
5641 context_menu
5642 }
5643
5644 pub fn insert_snippet(
5645 &mut self,
5646 insertion_ranges: &[Range<usize>],
5647 snippet: Snippet,
5648 cx: &mut ViewContext<Self>,
5649 ) -> Result<()> {
5650 struct Tabstop<T> {
5651 is_end_tabstop: bool,
5652 ranges: Vec<Range<T>>,
5653 }
5654
5655 let tabstops = self.buffer.update(cx, |buffer, cx| {
5656 let snippet_text: Arc<str> = snippet.text.clone().into();
5657 buffer.edit(
5658 insertion_ranges
5659 .iter()
5660 .cloned()
5661 .map(|range| (range, snippet_text.clone())),
5662 Some(AutoindentMode::EachLine),
5663 cx,
5664 );
5665
5666 let snapshot = &*buffer.read(cx);
5667 let snippet = &snippet;
5668 snippet
5669 .tabstops
5670 .iter()
5671 .map(|tabstop| {
5672 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5673 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5674 });
5675 let mut tabstop_ranges = tabstop
5676 .iter()
5677 .flat_map(|tabstop_range| {
5678 let mut delta = 0_isize;
5679 insertion_ranges.iter().map(move |insertion_range| {
5680 let insertion_start = insertion_range.start as isize + delta;
5681 delta +=
5682 snippet.text.len() as isize - insertion_range.len() as isize;
5683
5684 let start = ((insertion_start + tabstop_range.start) as usize)
5685 .min(snapshot.len());
5686 let end = ((insertion_start + tabstop_range.end) as usize)
5687 .min(snapshot.len());
5688 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5689 })
5690 })
5691 .collect::<Vec<_>>();
5692 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5693
5694 Tabstop {
5695 is_end_tabstop,
5696 ranges: tabstop_ranges,
5697 }
5698 })
5699 .collect::<Vec<_>>()
5700 });
5701 if let Some(tabstop) = tabstops.first() {
5702 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5703 s.select_ranges(tabstop.ranges.iter().cloned());
5704 });
5705
5706 // If we're already at the last tabstop and it's at the end of the snippet,
5707 // we're done, we don't need to keep the state around.
5708 if !tabstop.is_end_tabstop {
5709 let ranges = tabstops
5710 .into_iter()
5711 .map(|tabstop| tabstop.ranges)
5712 .collect::<Vec<_>>();
5713 self.snippet_stack.push(SnippetState {
5714 active_index: 0,
5715 ranges,
5716 });
5717 }
5718
5719 // Check whether the just-entered snippet ends with an auto-closable bracket.
5720 if self.autoclose_regions.is_empty() {
5721 let snapshot = self.buffer.read(cx).snapshot(cx);
5722 for selection in &mut self.selections.all::<Point>(cx) {
5723 let selection_head = selection.head();
5724 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5725 continue;
5726 };
5727
5728 let mut bracket_pair = None;
5729 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5730 let prev_chars = snapshot
5731 .reversed_chars_at(selection_head)
5732 .collect::<String>();
5733 for (pair, enabled) in scope.brackets() {
5734 if enabled
5735 && pair.close
5736 && prev_chars.starts_with(pair.start.as_str())
5737 && next_chars.starts_with(pair.end.as_str())
5738 {
5739 bracket_pair = Some(pair.clone());
5740 break;
5741 }
5742 }
5743 if let Some(pair) = bracket_pair {
5744 let start = snapshot.anchor_after(selection_head);
5745 let end = snapshot.anchor_after(selection_head);
5746 self.autoclose_regions.push(AutocloseRegion {
5747 selection_id: selection.id,
5748 range: start..end,
5749 pair,
5750 });
5751 }
5752 }
5753 }
5754 }
5755 Ok(())
5756 }
5757
5758 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5759 self.move_to_snippet_tabstop(Bias::Right, cx)
5760 }
5761
5762 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5763 self.move_to_snippet_tabstop(Bias::Left, cx)
5764 }
5765
5766 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5767 if let Some(mut snippet) = self.snippet_stack.pop() {
5768 match bias {
5769 Bias::Left => {
5770 if snippet.active_index > 0 {
5771 snippet.active_index -= 1;
5772 } else {
5773 self.snippet_stack.push(snippet);
5774 return false;
5775 }
5776 }
5777 Bias::Right => {
5778 if snippet.active_index + 1 < snippet.ranges.len() {
5779 snippet.active_index += 1;
5780 } else {
5781 self.snippet_stack.push(snippet);
5782 return false;
5783 }
5784 }
5785 }
5786 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5787 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5788 s.select_anchor_ranges(current_ranges.iter().cloned())
5789 });
5790 // If snippet state is not at the last tabstop, push it back on the stack
5791 if snippet.active_index + 1 < snippet.ranges.len() {
5792 self.snippet_stack.push(snippet);
5793 }
5794 return true;
5795 }
5796 }
5797
5798 false
5799 }
5800
5801 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5802 self.transact(cx, |this, cx| {
5803 this.select_all(&SelectAll, cx);
5804 this.insert("", cx);
5805 });
5806 }
5807
5808 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5809 self.transact(cx, |this, cx| {
5810 this.select_autoclose_pair(cx);
5811 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5812 if !this.linked_edit_ranges.is_empty() {
5813 let selections = this.selections.all::<MultiBufferPoint>(cx);
5814 let snapshot = this.buffer.read(cx).snapshot(cx);
5815
5816 for selection in selections.iter() {
5817 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5818 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5819 if selection_start.buffer_id != selection_end.buffer_id {
5820 continue;
5821 }
5822 if let Some(ranges) =
5823 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5824 {
5825 for (buffer, entries) in ranges {
5826 linked_ranges.entry(buffer).or_default().extend(entries);
5827 }
5828 }
5829 }
5830 }
5831
5832 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5833 if !this.selections.line_mode {
5834 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5835 for selection in &mut selections {
5836 if selection.is_empty() {
5837 let old_head = selection.head();
5838 let mut new_head =
5839 movement::left(&display_map, old_head.to_display_point(&display_map))
5840 .to_point(&display_map);
5841 if let Some((buffer, line_buffer_range)) = display_map
5842 .buffer_snapshot
5843 .buffer_line_for_row(MultiBufferRow(old_head.row))
5844 {
5845 let indent_size =
5846 buffer.indent_size_for_line(line_buffer_range.start.row);
5847 let indent_len = match indent_size.kind {
5848 IndentKind::Space => {
5849 buffer.settings_at(line_buffer_range.start, cx).tab_size
5850 }
5851 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5852 };
5853 if old_head.column <= indent_size.len && old_head.column > 0 {
5854 let indent_len = indent_len.get();
5855 new_head = cmp::min(
5856 new_head,
5857 MultiBufferPoint::new(
5858 old_head.row,
5859 ((old_head.column - 1) / indent_len) * indent_len,
5860 ),
5861 );
5862 }
5863 }
5864
5865 selection.set_head(new_head, SelectionGoal::None);
5866 }
5867 }
5868 }
5869
5870 this.signature_help_state.set_backspace_pressed(true);
5871 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5872 this.insert("", cx);
5873 let empty_str: Arc<str> = Arc::from("");
5874 for (buffer, edits) in linked_ranges {
5875 let snapshot = buffer.read(cx).snapshot();
5876 use text::ToPoint as TP;
5877
5878 let edits = edits
5879 .into_iter()
5880 .map(|range| {
5881 let end_point = TP::to_point(&range.end, &snapshot);
5882 let mut start_point = TP::to_point(&range.start, &snapshot);
5883
5884 if end_point == start_point {
5885 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5886 .saturating_sub(1);
5887 start_point = TP::to_point(&offset, &snapshot);
5888 };
5889
5890 (start_point..end_point, empty_str.clone())
5891 })
5892 .sorted_by_key(|(range, _)| range.start)
5893 .collect::<Vec<_>>();
5894 buffer.update(cx, |this, cx| {
5895 this.edit(edits, None, cx);
5896 })
5897 }
5898 this.refresh_inline_completion(true, false, cx);
5899 linked_editing_ranges::refresh_linked_ranges(this, cx);
5900 });
5901 }
5902
5903 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5904 self.transact(cx, |this, cx| {
5905 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5906 let line_mode = s.line_mode;
5907 s.move_with(|map, selection| {
5908 if selection.is_empty() && !line_mode {
5909 let cursor = movement::right(map, selection.head());
5910 selection.end = cursor;
5911 selection.reversed = true;
5912 selection.goal = SelectionGoal::None;
5913 }
5914 })
5915 });
5916 this.insert("", cx);
5917 this.refresh_inline_completion(true, false, cx);
5918 });
5919 }
5920
5921 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5922 if self.move_to_prev_snippet_tabstop(cx) {
5923 return;
5924 }
5925
5926 self.outdent(&Outdent, cx);
5927 }
5928
5929 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5930 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5931 return;
5932 }
5933
5934 let mut selections = self.selections.all_adjusted(cx);
5935 let buffer = self.buffer.read(cx);
5936 let snapshot = buffer.snapshot(cx);
5937 let rows_iter = selections.iter().map(|s| s.head().row);
5938 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5939
5940 let mut edits = Vec::new();
5941 let mut prev_edited_row = 0;
5942 let mut row_delta = 0;
5943 for selection in &mut selections {
5944 if selection.start.row != prev_edited_row {
5945 row_delta = 0;
5946 }
5947 prev_edited_row = selection.end.row;
5948
5949 // If the selection is non-empty, then increase the indentation of the selected lines.
5950 if !selection.is_empty() {
5951 row_delta =
5952 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5953 continue;
5954 }
5955
5956 // If the selection is empty and the cursor is in the leading whitespace before the
5957 // suggested indentation, then auto-indent the line.
5958 let cursor = selection.head();
5959 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5960 if let Some(suggested_indent) =
5961 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5962 {
5963 if cursor.column < suggested_indent.len
5964 && cursor.column <= current_indent.len
5965 && current_indent.len <= suggested_indent.len
5966 {
5967 selection.start = Point::new(cursor.row, suggested_indent.len);
5968 selection.end = selection.start;
5969 if row_delta == 0 {
5970 edits.extend(Buffer::edit_for_indent_size_adjustment(
5971 cursor.row,
5972 current_indent,
5973 suggested_indent,
5974 ));
5975 row_delta = suggested_indent.len - current_indent.len;
5976 }
5977 continue;
5978 }
5979 }
5980
5981 // Otherwise, insert a hard or soft tab.
5982 let settings = buffer.settings_at(cursor, cx);
5983 let tab_size = if settings.hard_tabs {
5984 IndentSize::tab()
5985 } else {
5986 let tab_size = settings.tab_size.get();
5987 let char_column = snapshot
5988 .text_for_range(Point::new(cursor.row, 0)..cursor)
5989 .flat_map(str::chars)
5990 .count()
5991 + row_delta as usize;
5992 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5993 IndentSize::spaces(chars_to_next_tab_stop)
5994 };
5995 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5996 selection.end = selection.start;
5997 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5998 row_delta += tab_size.len;
5999 }
6000
6001 self.transact(cx, |this, cx| {
6002 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6003 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6004 this.refresh_inline_completion(true, false, cx);
6005 });
6006 }
6007
6008 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6009 if self.read_only(cx) {
6010 return;
6011 }
6012 let mut selections = self.selections.all::<Point>(cx);
6013 let mut prev_edited_row = 0;
6014 let mut row_delta = 0;
6015 let mut edits = Vec::new();
6016 let buffer = self.buffer.read(cx);
6017 let snapshot = buffer.snapshot(cx);
6018 for selection in &mut selections {
6019 if selection.start.row != prev_edited_row {
6020 row_delta = 0;
6021 }
6022 prev_edited_row = selection.end.row;
6023
6024 row_delta =
6025 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6026 }
6027
6028 self.transact(cx, |this, cx| {
6029 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6030 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6031 });
6032 }
6033
6034 fn indent_selection(
6035 buffer: &MultiBuffer,
6036 snapshot: &MultiBufferSnapshot,
6037 selection: &mut Selection<Point>,
6038 edits: &mut Vec<(Range<Point>, String)>,
6039 delta_for_start_row: u32,
6040 cx: &AppContext,
6041 ) -> u32 {
6042 let settings = buffer.settings_at(selection.start, cx);
6043 let tab_size = settings.tab_size.get();
6044 let indent_kind = if settings.hard_tabs {
6045 IndentKind::Tab
6046 } else {
6047 IndentKind::Space
6048 };
6049 let mut start_row = selection.start.row;
6050 let mut end_row = selection.end.row + 1;
6051
6052 // If a selection ends at the beginning of a line, don't indent
6053 // that last line.
6054 if selection.end.column == 0 && selection.end.row > selection.start.row {
6055 end_row -= 1;
6056 }
6057
6058 // Avoid re-indenting a row that has already been indented by a
6059 // previous selection, but still update this selection's column
6060 // to reflect that indentation.
6061 if delta_for_start_row > 0 {
6062 start_row += 1;
6063 selection.start.column += delta_for_start_row;
6064 if selection.end.row == selection.start.row {
6065 selection.end.column += delta_for_start_row;
6066 }
6067 }
6068
6069 let mut delta_for_end_row = 0;
6070 let has_multiple_rows = start_row + 1 != end_row;
6071 for row in start_row..end_row {
6072 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6073 let indent_delta = match (current_indent.kind, indent_kind) {
6074 (IndentKind::Space, IndentKind::Space) => {
6075 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6076 IndentSize::spaces(columns_to_next_tab_stop)
6077 }
6078 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6079 (_, IndentKind::Tab) => IndentSize::tab(),
6080 };
6081
6082 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6083 0
6084 } else {
6085 selection.start.column
6086 };
6087 let row_start = Point::new(row, start);
6088 edits.push((
6089 row_start..row_start,
6090 indent_delta.chars().collect::<String>(),
6091 ));
6092
6093 // Update this selection's endpoints to reflect the indentation.
6094 if row == selection.start.row {
6095 selection.start.column += indent_delta.len;
6096 }
6097 if row == selection.end.row {
6098 selection.end.column += indent_delta.len;
6099 delta_for_end_row = indent_delta.len;
6100 }
6101 }
6102
6103 if selection.start.row == selection.end.row {
6104 delta_for_start_row + delta_for_end_row
6105 } else {
6106 delta_for_end_row
6107 }
6108 }
6109
6110 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6111 if self.read_only(cx) {
6112 return;
6113 }
6114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6115 let selections = self.selections.all::<Point>(cx);
6116 let mut deletion_ranges = Vec::new();
6117 let mut last_outdent = None;
6118 {
6119 let buffer = self.buffer.read(cx);
6120 let snapshot = buffer.snapshot(cx);
6121 for selection in &selections {
6122 let settings = buffer.settings_at(selection.start, cx);
6123 let tab_size = settings.tab_size.get();
6124 let mut rows = selection.spanned_rows(false, &display_map);
6125
6126 // Avoid re-outdenting a row that has already been outdented by a
6127 // previous selection.
6128 if let Some(last_row) = last_outdent {
6129 if last_row == rows.start {
6130 rows.start = rows.start.next_row();
6131 }
6132 }
6133 let has_multiple_rows = rows.len() > 1;
6134 for row in rows.iter_rows() {
6135 let indent_size = snapshot.indent_size_for_line(row);
6136 if indent_size.len > 0 {
6137 let deletion_len = match indent_size.kind {
6138 IndentKind::Space => {
6139 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6140 if columns_to_prev_tab_stop == 0 {
6141 tab_size
6142 } else {
6143 columns_to_prev_tab_stop
6144 }
6145 }
6146 IndentKind::Tab => 1,
6147 };
6148 let start = if has_multiple_rows
6149 || deletion_len > selection.start.column
6150 || indent_size.len < selection.start.column
6151 {
6152 0
6153 } else {
6154 selection.start.column - deletion_len
6155 };
6156 deletion_ranges.push(
6157 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6158 );
6159 last_outdent = Some(row);
6160 }
6161 }
6162 }
6163 }
6164
6165 self.transact(cx, |this, cx| {
6166 this.buffer.update(cx, |buffer, cx| {
6167 let empty_str: Arc<str> = Arc::default();
6168 buffer.edit(
6169 deletion_ranges
6170 .into_iter()
6171 .map(|range| (range, empty_str.clone())),
6172 None,
6173 cx,
6174 );
6175 });
6176 let selections = this.selections.all::<usize>(cx);
6177 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6178 });
6179 }
6180
6181 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6182 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6183 let selections = self.selections.all::<Point>(cx);
6184
6185 let mut new_cursors = Vec::new();
6186 let mut edit_ranges = Vec::new();
6187 let mut selections = selections.iter().peekable();
6188 while let Some(selection) = selections.next() {
6189 let mut rows = selection.spanned_rows(false, &display_map);
6190 let goal_display_column = selection.head().to_display_point(&display_map).column();
6191
6192 // Accumulate contiguous regions of rows that we want to delete.
6193 while let Some(next_selection) = selections.peek() {
6194 let next_rows = next_selection.spanned_rows(false, &display_map);
6195 if next_rows.start <= rows.end {
6196 rows.end = next_rows.end;
6197 selections.next().unwrap();
6198 } else {
6199 break;
6200 }
6201 }
6202
6203 let buffer = &display_map.buffer_snapshot;
6204 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6205 let edit_end;
6206 let cursor_buffer_row;
6207 if buffer.max_point().row >= rows.end.0 {
6208 // If there's a line after the range, delete the \n from the end of the row range
6209 // and position the cursor on the next line.
6210 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6211 cursor_buffer_row = rows.end;
6212 } else {
6213 // If there isn't a line after the range, delete the \n from the line before the
6214 // start of the row range and position the cursor there.
6215 edit_start = edit_start.saturating_sub(1);
6216 edit_end = buffer.len();
6217 cursor_buffer_row = rows.start.previous_row();
6218 }
6219
6220 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6221 *cursor.column_mut() =
6222 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6223
6224 new_cursors.push((
6225 selection.id,
6226 buffer.anchor_after(cursor.to_point(&display_map)),
6227 ));
6228 edit_ranges.push(edit_start..edit_end);
6229 }
6230
6231 self.transact(cx, |this, cx| {
6232 let buffer = this.buffer.update(cx, |buffer, cx| {
6233 let empty_str: Arc<str> = Arc::default();
6234 buffer.edit(
6235 edit_ranges
6236 .into_iter()
6237 .map(|range| (range, empty_str.clone())),
6238 None,
6239 cx,
6240 );
6241 buffer.snapshot(cx)
6242 });
6243 let new_selections = new_cursors
6244 .into_iter()
6245 .map(|(id, cursor)| {
6246 let cursor = cursor.to_point(&buffer);
6247 Selection {
6248 id,
6249 start: cursor,
6250 end: cursor,
6251 reversed: false,
6252 goal: SelectionGoal::None,
6253 }
6254 })
6255 .collect();
6256
6257 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6258 s.select(new_selections);
6259 });
6260 });
6261 }
6262
6263 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6264 if self.read_only(cx) {
6265 return;
6266 }
6267 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6268 for selection in self.selections.all::<Point>(cx) {
6269 let start = MultiBufferRow(selection.start.row);
6270 let end = if selection.start.row == selection.end.row {
6271 MultiBufferRow(selection.start.row + 1)
6272 } else {
6273 MultiBufferRow(selection.end.row)
6274 };
6275
6276 if let Some(last_row_range) = row_ranges.last_mut() {
6277 if start <= last_row_range.end {
6278 last_row_range.end = end;
6279 continue;
6280 }
6281 }
6282 row_ranges.push(start..end);
6283 }
6284
6285 let snapshot = self.buffer.read(cx).snapshot(cx);
6286 let mut cursor_positions = Vec::new();
6287 for row_range in &row_ranges {
6288 let anchor = snapshot.anchor_before(Point::new(
6289 row_range.end.previous_row().0,
6290 snapshot.line_len(row_range.end.previous_row()),
6291 ));
6292 cursor_positions.push(anchor..anchor);
6293 }
6294
6295 self.transact(cx, |this, cx| {
6296 for row_range in row_ranges.into_iter().rev() {
6297 for row in row_range.iter_rows().rev() {
6298 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6299 let next_line_row = row.next_row();
6300 let indent = snapshot.indent_size_for_line(next_line_row);
6301 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6302
6303 let replace = if snapshot.line_len(next_line_row) > indent.len {
6304 " "
6305 } else {
6306 ""
6307 };
6308
6309 this.buffer.update(cx, |buffer, cx| {
6310 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6311 });
6312 }
6313 }
6314
6315 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6316 s.select_anchor_ranges(cursor_positions)
6317 });
6318 });
6319 }
6320
6321 pub fn sort_lines_case_sensitive(
6322 &mut self,
6323 _: &SortLinesCaseSensitive,
6324 cx: &mut ViewContext<Self>,
6325 ) {
6326 self.manipulate_lines(cx, |lines| lines.sort())
6327 }
6328
6329 pub fn sort_lines_case_insensitive(
6330 &mut self,
6331 _: &SortLinesCaseInsensitive,
6332 cx: &mut ViewContext<Self>,
6333 ) {
6334 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6335 }
6336
6337 pub fn unique_lines_case_insensitive(
6338 &mut self,
6339 _: &UniqueLinesCaseInsensitive,
6340 cx: &mut ViewContext<Self>,
6341 ) {
6342 self.manipulate_lines(cx, |lines| {
6343 let mut seen = HashSet::default();
6344 lines.retain(|line| seen.insert(line.to_lowercase()));
6345 })
6346 }
6347
6348 pub fn unique_lines_case_sensitive(
6349 &mut self,
6350 _: &UniqueLinesCaseSensitive,
6351 cx: &mut ViewContext<Self>,
6352 ) {
6353 self.manipulate_lines(cx, |lines| {
6354 let mut seen = HashSet::default();
6355 lines.retain(|line| seen.insert(*line));
6356 })
6357 }
6358
6359 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6360 let mut revert_changes = HashMap::default();
6361 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6362 for hunk in hunks_for_rows(
6363 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6364 &multi_buffer_snapshot,
6365 ) {
6366 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6367 }
6368 if !revert_changes.is_empty() {
6369 self.transact(cx, |editor, cx| {
6370 editor.revert(revert_changes, cx);
6371 });
6372 }
6373 }
6374
6375 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6376 let Some(project) = self.project.clone() else {
6377 return;
6378 };
6379 self.reload(project, cx).detach_and_notify_err(cx);
6380 }
6381
6382 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6383 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6384 if !revert_changes.is_empty() {
6385 self.transact(cx, |editor, cx| {
6386 editor.revert(revert_changes, cx);
6387 });
6388 }
6389 }
6390
6391 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6392 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6393 let project_path = buffer.read(cx).project_path(cx)?;
6394 let project = self.project.as_ref()?.read(cx);
6395 let entry = project.entry_for_path(&project_path, cx)?;
6396 let parent = match &entry.canonical_path {
6397 Some(canonical_path) => canonical_path.to_path_buf(),
6398 None => project.absolute_path(&project_path, cx)?,
6399 }
6400 .parent()?
6401 .to_path_buf();
6402 Some(parent)
6403 }) {
6404 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6405 }
6406 }
6407
6408 fn gather_revert_changes(
6409 &mut self,
6410 selections: &[Selection<Anchor>],
6411 cx: &mut ViewContext<'_, Editor>,
6412 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6413 let mut revert_changes = HashMap::default();
6414 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6415 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6416 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6417 }
6418 revert_changes
6419 }
6420
6421 pub fn prepare_revert_change(
6422 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6423 multi_buffer: &Model<MultiBuffer>,
6424 hunk: &MultiBufferDiffHunk,
6425 cx: &AppContext,
6426 ) -> Option<()> {
6427 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6428 let buffer = buffer.read(cx);
6429 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6430 let buffer_snapshot = buffer.snapshot();
6431 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6432 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6433 probe
6434 .0
6435 .start
6436 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6437 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6438 }) {
6439 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6440 Some(())
6441 } else {
6442 None
6443 }
6444 }
6445
6446 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6447 self.manipulate_lines(cx, |lines| lines.reverse())
6448 }
6449
6450 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6451 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6452 }
6453
6454 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6455 where
6456 Fn: FnMut(&mut Vec<&str>),
6457 {
6458 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6459 let buffer = self.buffer.read(cx).snapshot(cx);
6460
6461 let mut edits = Vec::new();
6462
6463 let selections = self.selections.all::<Point>(cx);
6464 let mut selections = selections.iter().peekable();
6465 let mut contiguous_row_selections = Vec::new();
6466 let mut new_selections = Vec::new();
6467 let mut added_lines = 0;
6468 let mut removed_lines = 0;
6469
6470 while let Some(selection) = selections.next() {
6471 let (start_row, end_row) = consume_contiguous_rows(
6472 &mut contiguous_row_selections,
6473 selection,
6474 &display_map,
6475 &mut selections,
6476 );
6477
6478 let start_point = Point::new(start_row.0, 0);
6479 let end_point = Point::new(
6480 end_row.previous_row().0,
6481 buffer.line_len(end_row.previous_row()),
6482 );
6483 let text = buffer
6484 .text_for_range(start_point..end_point)
6485 .collect::<String>();
6486
6487 let mut lines = text.split('\n').collect_vec();
6488
6489 let lines_before = lines.len();
6490 callback(&mut lines);
6491 let lines_after = lines.len();
6492
6493 edits.push((start_point..end_point, lines.join("\n")));
6494
6495 // Selections must change based on added and removed line count
6496 let start_row =
6497 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6498 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6499 new_selections.push(Selection {
6500 id: selection.id,
6501 start: start_row,
6502 end: end_row,
6503 goal: SelectionGoal::None,
6504 reversed: selection.reversed,
6505 });
6506
6507 if lines_after > lines_before {
6508 added_lines += lines_after - lines_before;
6509 } else if lines_before > lines_after {
6510 removed_lines += lines_before - lines_after;
6511 }
6512 }
6513
6514 self.transact(cx, |this, cx| {
6515 let buffer = this.buffer.update(cx, |buffer, cx| {
6516 buffer.edit(edits, None, cx);
6517 buffer.snapshot(cx)
6518 });
6519
6520 // Recalculate offsets on newly edited buffer
6521 let new_selections = new_selections
6522 .iter()
6523 .map(|s| {
6524 let start_point = Point::new(s.start.0, 0);
6525 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6526 Selection {
6527 id: s.id,
6528 start: buffer.point_to_offset(start_point),
6529 end: buffer.point_to_offset(end_point),
6530 goal: s.goal,
6531 reversed: s.reversed,
6532 }
6533 })
6534 .collect();
6535
6536 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6537 s.select(new_selections);
6538 });
6539
6540 this.request_autoscroll(Autoscroll::fit(), cx);
6541 });
6542 }
6543
6544 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6545 self.manipulate_text(cx, |text| text.to_uppercase())
6546 }
6547
6548 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6549 self.manipulate_text(cx, |text| text.to_lowercase())
6550 }
6551
6552 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6553 self.manipulate_text(cx, |text| {
6554 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6555 // https://github.com/rutrum/convert-case/issues/16
6556 text.split('\n')
6557 .map(|line| line.to_case(Case::Title))
6558 .join("\n")
6559 })
6560 }
6561
6562 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6563 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6564 }
6565
6566 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6567 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6568 }
6569
6570 pub fn convert_to_upper_camel_case(
6571 &mut self,
6572 _: &ConvertToUpperCamelCase,
6573 cx: &mut ViewContext<Self>,
6574 ) {
6575 self.manipulate_text(cx, |text| {
6576 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6577 // https://github.com/rutrum/convert-case/issues/16
6578 text.split('\n')
6579 .map(|line| line.to_case(Case::UpperCamel))
6580 .join("\n")
6581 })
6582 }
6583
6584 pub fn convert_to_lower_camel_case(
6585 &mut self,
6586 _: &ConvertToLowerCamelCase,
6587 cx: &mut ViewContext<Self>,
6588 ) {
6589 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6590 }
6591
6592 pub fn convert_to_opposite_case(
6593 &mut self,
6594 _: &ConvertToOppositeCase,
6595 cx: &mut ViewContext<Self>,
6596 ) {
6597 self.manipulate_text(cx, |text| {
6598 text.chars()
6599 .fold(String::with_capacity(text.len()), |mut t, c| {
6600 if c.is_uppercase() {
6601 t.extend(c.to_lowercase());
6602 } else {
6603 t.extend(c.to_uppercase());
6604 }
6605 t
6606 })
6607 })
6608 }
6609
6610 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6611 where
6612 Fn: FnMut(&str) -> String,
6613 {
6614 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6615 let buffer = self.buffer.read(cx).snapshot(cx);
6616
6617 let mut new_selections = Vec::new();
6618 let mut edits = Vec::new();
6619 let mut selection_adjustment = 0i32;
6620
6621 for selection in self.selections.all::<usize>(cx) {
6622 let selection_is_empty = selection.is_empty();
6623
6624 let (start, end) = if selection_is_empty {
6625 let word_range = movement::surrounding_word(
6626 &display_map,
6627 selection.start.to_display_point(&display_map),
6628 );
6629 let start = word_range.start.to_offset(&display_map, Bias::Left);
6630 let end = word_range.end.to_offset(&display_map, Bias::Left);
6631 (start, end)
6632 } else {
6633 (selection.start, selection.end)
6634 };
6635
6636 let text = buffer.text_for_range(start..end).collect::<String>();
6637 let old_length = text.len() as i32;
6638 let text = callback(&text);
6639
6640 new_selections.push(Selection {
6641 start: (start as i32 - selection_adjustment) as usize,
6642 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6643 goal: SelectionGoal::None,
6644 ..selection
6645 });
6646
6647 selection_adjustment += old_length - text.len() as i32;
6648
6649 edits.push((start..end, text));
6650 }
6651
6652 self.transact(cx, |this, cx| {
6653 this.buffer.update(cx, |buffer, cx| {
6654 buffer.edit(edits, None, cx);
6655 });
6656
6657 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6658 s.select(new_selections);
6659 });
6660
6661 this.request_autoscroll(Autoscroll::fit(), cx);
6662 });
6663 }
6664
6665 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6666 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6667 let buffer = &display_map.buffer_snapshot;
6668 let selections = self.selections.all::<Point>(cx);
6669
6670 let mut edits = Vec::new();
6671 let mut selections_iter = selections.iter().peekable();
6672 while let Some(selection) = selections_iter.next() {
6673 // Avoid duplicating the same lines twice.
6674 let mut rows = selection.spanned_rows(false, &display_map);
6675
6676 while let Some(next_selection) = selections_iter.peek() {
6677 let next_rows = next_selection.spanned_rows(false, &display_map);
6678 if next_rows.start < rows.end {
6679 rows.end = next_rows.end;
6680 selections_iter.next().unwrap();
6681 } else {
6682 break;
6683 }
6684 }
6685
6686 // Copy the text from the selected row region and splice it either at the start
6687 // or end of the region.
6688 let start = Point::new(rows.start.0, 0);
6689 let end = Point::new(
6690 rows.end.previous_row().0,
6691 buffer.line_len(rows.end.previous_row()),
6692 );
6693 let text = buffer
6694 .text_for_range(start..end)
6695 .chain(Some("\n"))
6696 .collect::<String>();
6697 let insert_location = if upwards {
6698 Point::new(rows.end.0, 0)
6699 } else {
6700 start
6701 };
6702 edits.push((insert_location..insert_location, text));
6703 }
6704
6705 self.transact(cx, |this, cx| {
6706 this.buffer.update(cx, |buffer, cx| {
6707 buffer.edit(edits, None, cx);
6708 });
6709
6710 this.request_autoscroll(Autoscroll::fit(), cx);
6711 });
6712 }
6713
6714 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6715 self.duplicate_line(true, cx);
6716 }
6717
6718 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6719 self.duplicate_line(false, cx);
6720 }
6721
6722 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6723 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6724 let buffer = self.buffer.read(cx).snapshot(cx);
6725
6726 let mut edits = Vec::new();
6727 let mut unfold_ranges = Vec::new();
6728 let mut refold_ranges = Vec::new();
6729
6730 let selections = self.selections.all::<Point>(cx);
6731 let mut selections = selections.iter().peekable();
6732 let mut contiguous_row_selections = Vec::new();
6733 let mut new_selections = Vec::new();
6734
6735 while let Some(selection) = selections.next() {
6736 // Find all the selections that span a contiguous row range
6737 let (start_row, end_row) = consume_contiguous_rows(
6738 &mut contiguous_row_selections,
6739 selection,
6740 &display_map,
6741 &mut selections,
6742 );
6743
6744 // Move the text spanned by the row range to be before the line preceding the row range
6745 if start_row.0 > 0 {
6746 let range_to_move = Point::new(
6747 start_row.previous_row().0,
6748 buffer.line_len(start_row.previous_row()),
6749 )
6750 ..Point::new(
6751 end_row.previous_row().0,
6752 buffer.line_len(end_row.previous_row()),
6753 );
6754 let insertion_point = display_map
6755 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6756 .0;
6757
6758 // Don't move lines across excerpts
6759 if buffer
6760 .excerpt_boundaries_in_range((
6761 Bound::Excluded(insertion_point),
6762 Bound::Included(range_to_move.end),
6763 ))
6764 .next()
6765 .is_none()
6766 {
6767 let text = buffer
6768 .text_for_range(range_to_move.clone())
6769 .flat_map(|s| s.chars())
6770 .skip(1)
6771 .chain(['\n'])
6772 .collect::<String>();
6773
6774 edits.push((
6775 buffer.anchor_after(range_to_move.start)
6776 ..buffer.anchor_before(range_to_move.end),
6777 String::new(),
6778 ));
6779 let insertion_anchor = buffer.anchor_after(insertion_point);
6780 edits.push((insertion_anchor..insertion_anchor, text));
6781
6782 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6783
6784 // Move selections up
6785 new_selections.extend(contiguous_row_selections.drain(..).map(
6786 |mut selection| {
6787 selection.start.row -= row_delta;
6788 selection.end.row -= row_delta;
6789 selection
6790 },
6791 ));
6792
6793 // Move folds up
6794 unfold_ranges.push(range_to_move.clone());
6795 for fold in display_map.folds_in_range(
6796 buffer.anchor_before(range_to_move.start)
6797 ..buffer.anchor_after(range_to_move.end),
6798 ) {
6799 let mut start = fold.range.start.to_point(&buffer);
6800 let mut end = fold.range.end.to_point(&buffer);
6801 start.row -= row_delta;
6802 end.row -= row_delta;
6803 refold_ranges.push((start..end, fold.placeholder.clone()));
6804 }
6805 }
6806 }
6807
6808 // If we didn't move line(s), preserve the existing selections
6809 new_selections.append(&mut contiguous_row_selections);
6810 }
6811
6812 self.transact(cx, |this, cx| {
6813 this.unfold_ranges(unfold_ranges, true, true, cx);
6814 this.buffer.update(cx, |buffer, cx| {
6815 for (range, text) in edits {
6816 buffer.edit([(range, text)], None, cx);
6817 }
6818 });
6819 this.fold_ranges(refold_ranges, true, cx);
6820 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6821 s.select(new_selections);
6822 })
6823 });
6824 }
6825
6826 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6827 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6828 let buffer = self.buffer.read(cx).snapshot(cx);
6829
6830 let mut edits = Vec::new();
6831 let mut unfold_ranges = Vec::new();
6832 let mut refold_ranges = Vec::new();
6833
6834 let selections = self.selections.all::<Point>(cx);
6835 let mut selections = selections.iter().peekable();
6836 let mut contiguous_row_selections = Vec::new();
6837 let mut new_selections = Vec::new();
6838
6839 while let Some(selection) = selections.next() {
6840 // Find all the selections that span a contiguous row range
6841 let (start_row, end_row) = consume_contiguous_rows(
6842 &mut contiguous_row_selections,
6843 selection,
6844 &display_map,
6845 &mut selections,
6846 );
6847
6848 // Move the text spanned by the row range to be after the last line of the row range
6849 if end_row.0 <= buffer.max_point().row {
6850 let range_to_move =
6851 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6852 let insertion_point = display_map
6853 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6854 .0;
6855
6856 // Don't move lines across excerpt boundaries
6857 if buffer
6858 .excerpt_boundaries_in_range((
6859 Bound::Excluded(range_to_move.start),
6860 Bound::Included(insertion_point),
6861 ))
6862 .next()
6863 .is_none()
6864 {
6865 let mut text = String::from("\n");
6866 text.extend(buffer.text_for_range(range_to_move.clone()));
6867 text.pop(); // Drop trailing newline
6868 edits.push((
6869 buffer.anchor_after(range_to_move.start)
6870 ..buffer.anchor_before(range_to_move.end),
6871 String::new(),
6872 ));
6873 let insertion_anchor = buffer.anchor_after(insertion_point);
6874 edits.push((insertion_anchor..insertion_anchor, text));
6875
6876 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6877
6878 // Move selections down
6879 new_selections.extend(contiguous_row_selections.drain(..).map(
6880 |mut selection| {
6881 selection.start.row += row_delta;
6882 selection.end.row += row_delta;
6883 selection
6884 },
6885 ));
6886
6887 // Move folds down
6888 unfold_ranges.push(range_to_move.clone());
6889 for fold in display_map.folds_in_range(
6890 buffer.anchor_before(range_to_move.start)
6891 ..buffer.anchor_after(range_to_move.end),
6892 ) {
6893 let mut start = fold.range.start.to_point(&buffer);
6894 let mut end = fold.range.end.to_point(&buffer);
6895 start.row += row_delta;
6896 end.row += row_delta;
6897 refold_ranges.push((start..end, fold.placeholder.clone()));
6898 }
6899 }
6900 }
6901
6902 // If we didn't move line(s), preserve the existing selections
6903 new_selections.append(&mut contiguous_row_selections);
6904 }
6905
6906 self.transact(cx, |this, cx| {
6907 this.unfold_ranges(unfold_ranges, true, true, cx);
6908 this.buffer.update(cx, |buffer, cx| {
6909 for (range, text) in edits {
6910 buffer.edit([(range, text)], None, cx);
6911 }
6912 });
6913 this.fold_ranges(refold_ranges, true, cx);
6914 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6915 });
6916 }
6917
6918 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6919 let text_layout_details = &self.text_layout_details(cx);
6920 self.transact(cx, |this, cx| {
6921 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6922 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6923 let line_mode = s.line_mode;
6924 s.move_with(|display_map, selection| {
6925 if !selection.is_empty() || line_mode {
6926 return;
6927 }
6928
6929 let mut head = selection.head();
6930 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6931 if head.column() == display_map.line_len(head.row()) {
6932 transpose_offset = display_map
6933 .buffer_snapshot
6934 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6935 }
6936
6937 if transpose_offset == 0 {
6938 return;
6939 }
6940
6941 *head.column_mut() += 1;
6942 head = display_map.clip_point(head, Bias::Right);
6943 let goal = SelectionGoal::HorizontalPosition(
6944 display_map
6945 .x_for_display_point(head, text_layout_details)
6946 .into(),
6947 );
6948 selection.collapse_to(head, goal);
6949
6950 let transpose_start = display_map
6951 .buffer_snapshot
6952 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6953 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6954 let transpose_end = display_map
6955 .buffer_snapshot
6956 .clip_offset(transpose_offset + 1, Bias::Right);
6957 if let Some(ch) =
6958 display_map.buffer_snapshot.chars_at(transpose_start).next()
6959 {
6960 edits.push((transpose_start..transpose_offset, String::new()));
6961 edits.push((transpose_end..transpose_end, ch.to_string()));
6962 }
6963 }
6964 });
6965 edits
6966 });
6967 this.buffer
6968 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6969 let selections = this.selections.all::<usize>(cx);
6970 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6971 s.select(selections);
6972 });
6973 });
6974 }
6975
6976 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6977 self.rewrap_impl(true, cx)
6978 }
6979
6980 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6981 let buffer = self.buffer.read(cx).snapshot(cx);
6982 let selections = self.selections.all::<Point>(cx);
6983 let mut selections = selections.iter().peekable();
6984
6985 let mut edits = Vec::new();
6986 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6987
6988 while let Some(selection) = selections.next() {
6989 let mut start_row = selection.start.row;
6990 let mut end_row = selection.end.row;
6991
6992 // Skip selections that overlap with a range that has already been rewrapped.
6993 let selection_range = start_row..end_row;
6994 if rewrapped_row_ranges
6995 .iter()
6996 .any(|range| range.overlaps(&selection_range))
6997 {
6998 continue;
6999 }
7000
7001 let mut should_rewrap = !only_text;
7002
7003 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7004 match language_scope.language_name().0.as_ref() {
7005 "Markdown" | "Plain Text" => {
7006 should_rewrap = true;
7007 }
7008 _ => {}
7009 }
7010 }
7011
7012 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7013
7014 // Since not all lines in the selection may be at the same indent
7015 // level, choose the indent size that is the most common between all
7016 // of the lines.
7017 //
7018 // If there is a tie, we use the deepest indent.
7019 let (indent_size, indent_end) = {
7020 let mut indent_size_occurrences = HashMap::default();
7021 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7022
7023 for row in start_row..=end_row {
7024 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7025 rows_by_indent_size.entry(indent).or_default().push(row);
7026 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7027 }
7028
7029 let indent_size = indent_size_occurrences
7030 .into_iter()
7031 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7032 .map(|(indent, _)| indent)
7033 .unwrap_or_default();
7034 let row = rows_by_indent_size[&indent_size][0];
7035 let indent_end = Point::new(row, indent_size.len);
7036
7037 (indent_size, indent_end)
7038 };
7039
7040 let mut line_prefix = indent_size.chars().collect::<String>();
7041
7042 if let Some(comment_prefix) =
7043 buffer
7044 .language_scope_at(selection.head())
7045 .and_then(|language| {
7046 language
7047 .line_comment_prefixes()
7048 .iter()
7049 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7050 .cloned()
7051 })
7052 {
7053 line_prefix.push_str(&comment_prefix);
7054 should_rewrap = true;
7055 }
7056
7057 if !should_rewrap {
7058 continue;
7059 }
7060
7061 if selection.is_empty() {
7062 'expand_upwards: while start_row > 0 {
7063 let prev_row = start_row - 1;
7064 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7065 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7066 {
7067 start_row = prev_row;
7068 } else {
7069 break 'expand_upwards;
7070 }
7071 }
7072
7073 'expand_downwards: while end_row < buffer.max_point().row {
7074 let next_row = end_row + 1;
7075 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7076 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7077 {
7078 end_row = next_row;
7079 } else {
7080 break 'expand_downwards;
7081 }
7082 }
7083 }
7084
7085 let start = Point::new(start_row, 0);
7086 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7087 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7088 let Some(lines_without_prefixes) = selection_text
7089 .lines()
7090 .map(|line| {
7091 line.strip_prefix(&line_prefix)
7092 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7093 .ok_or_else(|| {
7094 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7095 })
7096 })
7097 .collect::<Result<Vec<_>, _>>()
7098 .log_err()
7099 else {
7100 continue;
7101 };
7102
7103 let wrap_column = buffer
7104 .settings_at(Point::new(start_row, 0), cx)
7105 .preferred_line_length as usize;
7106 let wrapped_text = wrap_with_prefix(
7107 line_prefix,
7108 lines_without_prefixes.join(" "),
7109 wrap_column,
7110 tab_size,
7111 );
7112
7113 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7114 let mut offset = start.to_offset(&buffer);
7115 let mut moved_since_edit = true;
7116
7117 for change in diff.iter_all_changes() {
7118 let value = change.value();
7119 match change.tag() {
7120 ChangeTag::Equal => {
7121 offset += value.len();
7122 moved_since_edit = true;
7123 }
7124 ChangeTag::Delete => {
7125 let start = buffer.anchor_after(offset);
7126 let end = buffer.anchor_before(offset + value.len());
7127
7128 if moved_since_edit {
7129 edits.push((start..end, String::new()));
7130 } else {
7131 edits.last_mut().unwrap().0.end = end;
7132 }
7133
7134 offset += value.len();
7135 moved_since_edit = false;
7136 }
7137 ChangeTag::Insert => {
7138 if moved_since_edit {
7139 let anchor = buffer.anchor_after(offset);
7140 edits.push((anchor..anchor, value.to_string()));
7141 } else {
7142 edits.last_mut().unwrap().1.push_str(value);
7143 }
7144
7145 moved_since_edit = false;
7146 }
7147 }
7148 }
7149
7150 rewrapped_row_ranges.push(start_row..=end_row);
7151 }
7152
7153 self.buffer
7154 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7155 }
7156
7157 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7158 let mut text = String::new();
7159 let buffer = self.buffer.read(cx).snapshot(cx);
7160 let mut selections = self.selections.all::<Point>(cx);
7161 let mut clipboard_selections = Vec::with_capacity(selections.len());
7162 {
7163 let max_point = buffer.max_point();
7164 let mut is_first = true;
7165 for selection in &mut selections {
7166 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7167 if is_entire_line {
7168 selection.start = Point::new(selection.start.row, 0);
7169 if !selection.is_empty() && selection.end.column == 0 {
7170 selection.end = cmp::min(max_point, selection.end);
7171 } else {
7172 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7173 }
7174 selection.goal = SelectionGoal::None;
7175 }
7176 if is_first {
7177 is_first = false;
7178 } else {
7179 text += "\n";
7180 }
7181 let mut len = 0;
7182 for chunk in buffer.text_for_range(selection.start..selection.end) {
7183 text.push_str(chunk);
7184 len += chunk.len();
7185 }
7186 clipboard_selections.push(ClipboardSelection {
7187 len,
7188 is_entire_line,
7189 first_line_indent: buffer
7190 .indent_size_for_line(MultiBufferRow(selection.start.row))
7191 .len,
7192 });
7193 }
7194 }
7195
7196 self.transact(cx, |this, cx| {
7197 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7198 s.select(selections);
7199 });
7200 this.insert("", cx);
7201 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7202 text,
7203 clipboard_selections,
7204 ));
7205 });
7206 }
7207
7208 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7209 let selections = self.selections.all::<Point>(cx);
7210 let buffer = self.buffer.read(cx).read(cx);
7211 let mut text = String::new();
7212
7213 let mut clipboard_selections = Vec::with_capacity(selections.len());
7214 {
7215 let max_point = buffer.max_point();
7216 let mut is_first = true;
7217 for selection in selections.iter() {
7218 let mut start = selection.start;
7219 let mut end = selection.end;
7220 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7221 if is_entire_line {
7222 start = Point::new(start.row, 0);
7223 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7224 }
7225 if is_first {
7226 is_first = false;
7227 } else {
7228 text += "\n";
7229 }
7230 let mut len = 0;
7231 for chunk in buffer.text_for_range(start..end) {
7232 text.push_str(chunk);
7233 len += chunk.len();
7234 }
7235 clipboard_selections.push(ClipboardSelection {
7236 len,
7237 is_entire_line,
7238 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7239 });
7240 }
7241 }
7242
7243 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7244 text,
7245 clipboard_selections,
7246 ));
7247 }
7248
7249 pub fn do_paste(
7250 &mut self,
7251 text: &String,
7252 clipboard_selections: Option<Vec<ClipboardSelection>>,
7253 handle_entire_lines: bool,
7254 cx: &mut ViewContext<Self>,
7255 ) {
7256 if self.read_only(cx) {
7257 return;
7258 }
7259
7260 let clipboard_text = Cow::Borrowed(text);
7261
7262 self.transact(cx, |this, cx| {
7263 if let Some(mut clipboard_selections) = clipboard_selections {
7264 let old_selections = this.selections.all::<usize>(cx);
7265 let all_selections_were_entire_line =
7266 clipboard_selections.iter().all(|s| s.is_entire_line);
7267 let first_selection_indent_column =
7268 clipboard_selections.first().map(|s| s.first_line_indent);
7269 if clipboard_selections.len() != old_selections.len() {
7270 clipboard_selections.drain(..);
7271 }
7272 let cursor_offset = this.selections.last::<usize>(cx).head();
7273 let mut auto_indent_on_paste = true;
7274
7275 this.buffer.update(cx, |buffer, cx| {
7276 let snapshot = buffer.read(cx);
7277 auto_indent_on_paste =
7278 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7279
7280 let mut start_offset = 0;
7281 let mut edits = Vec::new();
7282 let mut original_indent_columns = Vec::new();
7283 for (ix, selection) in old_selections.iter().enumerate() {
7284 let to_insert;
7285 let entire_line;
7286 let original_indent_column;
7287 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7288 let end_offset = start_offset + clipboard_selection.len;
7289 to_insert = &clipboard_text[start_offset..end_offset];
7290 entire_line = clipboard_selection.is_entire_line;
7291 start_offset = end_offset + 1;
7292 original_indent_column = Some(clipboard_selection.first_line_indent);
7293 } else {
7294 to_insert = clipboard_text.as_str();
7295 entire_line = all_selections_were_entire_line;
7296 original_indent_column = first_selection_indent_column
7297 }
7298
7299 // If the corresponding selection was empty when this slice of the
7300 // clipboard text was written, then the entire line containing the
7301 // selection was copied. If this selection is also currently empty,
7302 // then paste the line before the current line of the buffer.
7303 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7304 let column = selection.start.to_point(&snapshot).column as usize;
7305 let line_start = selection.start - column;
7306 line_start..line_start
7307 } else {
7308 selection.range()
7309 };
7310
7311 edits.push((range, to_insert));
7312 original_indent_columns.extend(original_indent_column);
7313 }
7314 drop(snapshot);
7315
7316 buffer.edit(
7317 edits,
7318 if auto_indent_on_paste {
7319 Some(AutoindentMode::Block {
7320 original_indent_columns,
7321 })
7322 } else {
7323 None
7324 },
7325 cx,
7326 );
7327 });
7328
7329 let selections = this.selections.all::<usize>(cx);
7330 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7331 } else {
7332 this.insert(&clipboard_text, cx);
7333 }
7334 });
7335 }
7336
7337 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7338 if let Some(item) = cx.read_from_clipboard() {
7339 let entries = item.entries();
7340
7341 match entries.first() {
7342 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7343 // of all the pasted entries.
7344 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7345 .do_paste(
7346 clipboard_string.text(),
7347 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7348 true,
7349 cx,
7350 ),
7351 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7352 }
7353 }
7354 }
7355
7356 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7357 if self.read_only(cx) {
7358 return;
7359 }
7360
7361 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7362 if let Some((selections, _)) =
7363 self.selection_history.transaction(transaction_id).cloned()
7364 {
7365 self.change_selections(None, cx, |s| {
7366 s.select_anchors(selections.to_vec());
7367 });
7368 }
7369 self.request_autoscroll(Autoscroll::fit(), cx);
7370 self.unmark_text(cx);
7371 self.refresh_inline_completion(true, false, cx);
7372 cx.emit(EditorEvent::Edited { transaction_id });
7373 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7374 }
7375 }
7376
7377 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7378 if self.read_only(cx) {
7379 return;
7380 }
7381
7382 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7383 if let Some((_, Some(selections))) =
7384 self.selection_history.transaction(transaction_id).cloned()
7385 {
7386 self.change_selections(None, cx, |s| {
7387 s.select_anchors(selections.to_vec());
7388 });
7389 }
7390 self.request_autoscroll(Autoscroll::fit(), cx);
7391 self.unmark_text(cx);
7392 self.refresh_inline_completion(true, false, cx);
7393 cx.emit(EditorEvent::Edited { transaction_id });
7394 }
7395 }
7396
7397 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7398 self.buffer
7399 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7400 }
7401
7402 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7403 self.buffer
7404 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7405 }
7406
7407 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7408 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7409 let line_mode = s.line_mode;
7410 s.move_with(|map, selection| {
7411 let cursor = if selection.is_empty() && !line_mode {
7412 movement::left(map, selection.start)
7413 } else {
7414 selection.start
7415 };
7416 selection.collapse_to(cursor, SelectionGoal::None);
7417 });
7418 })
7419 }
7420
7421 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7422 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7423 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7424 })
7425 }
7426
7427 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7428 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7429 let line_mode = s.line_mode;
7430 s.move_with(|map, selection| {
7431 let cursor = if selection.is_empty() && !line_mode {
7432 movement::right(map, selection.end)
7433 } else {
7434 selection.end
7435 };
7436 selection.collapse_to(cursor, SelectionGoal::None)
7437 });
7438 })
7439 }
7440
7441 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7443 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7444 })
7445 }
7446
7447 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7448 if self.take_rename(true, cx).is_some() {
7449 return;
7450 }
7451
7452 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7453 cx.propagate();
7454 return;
7455 }
7456
7457 let text_layout_details = &self.text_layout_details(cx);
7458 let selection_count = self.selections.count();
7459 let first_selection = self.selections.first_anchor();
7460
7461 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7462 let line_mode = s.line_mode;
7463 s.move_with(|map, selection| {
7464 if !selection.is_empty() && !line_mode {
7465 selection.goal = SelectionGoal::None;
7466 }
7467 let (cursor, goal) = movement::up(
7468 map,
7469 selection.start,
7470 selection.goal,
7471 false,
7472 text_layout_details,
7473 );
7474 selection.collapse_to(cursor, goal);
7475 });
7476 });
7477
7478 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7479 {
7480 cx.propagate();
7481 }
7482 }
7483
7484 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7485 if self.take_rename(true, cx).is_some() {
7486 return;
7487 }
7488
7489 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7490 cx.propagate();
7491 return;
7492 }
7493
7494 let text_layout_details = &self.text_layout_details(cx);
7495
7496 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7497 let line_mode = s.line_mode;
7498 s.move_with(|map, selection| {
7499 if !selection.is_empty() && !line_mode {
7500 selection.goal = SelectionGoal::None;
7501 }
7502 let (cursor, goal) = movement::up_by_rows(
7503 map,
7504 selection.start,
7505 action.lines,
7506 selection.goal,
7507 false,
7508 text_layout_details,
7509 );
7510 selection.collapse_to(cursor, goal);
7511 });
7512 })
7513 }
7514
7515 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7516 if self.take_rename(true, cx).is_some() {
7517 return;
7518 }
7519
7520 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7521 cx.propagate();
7522 return;
7523 }
7524
7525 let text_layout_details = &self.text_layout_details(cx);
7526
7527 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7528 let line_mode = s.line_mode;
7529 s.move_with(|map, selection| {
7530 if !selection.is_empty() && !line_mode {
7531 selection.goal = SelectionGoal::None;
7532 }
7533 let (cursor, goal) = movement::down_by_rows(
7534 map,
7535 selection.start,
7536 action.lines,
7537 selection.goal,
7538 false,
7539 text_layout_details,
7540 );
7541 selection.collapse_to(cursor, goal);
7542 });
7543 })
7544 }
7545
7546 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7547 let text_layout_details = &self.text_layout_details(cx);
7548 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7549 s.move_heads_with(|map, head, goal| {
7550 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7551 })
7552 })
7553 }
7554
7555 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7556 let text_layout_details = &self.text_layout_details(cx);
7557 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7558 s.move_heads_with(|map, head, goal| {
7559 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7560 })
7561 })
7562 }
7563
7564 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7565 let Some(row_count) = self.visible_row_count() else {
7566 return;
7567 };
7568
7569 let text_layout_details = &self.text_layout_details(cx);
7570
7571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7572 s.move_heads_with(|map, head, goal| {
7573 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7574 })
7575 })
7576 }
7577
7578 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7579 if self.take_rename(true, cx).is_some() {
7580 return;
7581 }
7582
7583 if self
7584 .context_menu
7585 .write()
7586 .as_mut()
7587 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7588 .unwrap_or(false)
7589 {
7590 return;
7591 }
7592
7593 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7594 cx.propagate();
7595 return;
7596 }
7597
7598 let Some(row_count) = self.visible_row_count() else {
7599 return;
7600 };
7601
7602 let autoscroll = if action.center_cursor {
7603 Autoscroll::center()
7604 } else {
7605 Autoscroll::fit()
7606 };
7607
7608 let text_layout_details = &self.text_layout_details(cx);
7609
7610 self.change_selections(Some(autoscroll), cx, |s| {
7611 let line_mode = s.line_mode;
7612 s.move_with(|map, selection| {
7613 if !selection.is_empty() && !line_mode {
7614 selection.goal = SelectionGoal::None;
7615 }
7616 let (cursor, goal) = movement::up_by_rows(
7617 map,
7618 selection.end,
7619 row_count,
7620 selection.goal,
7621 false,
7622 text_layout_details,
7623 );
7624 selection.collapse_to(cursor, goal);
7625 });
7626 });
7627 }
7628
7629 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7630 let text_layout_details = &self.text_layout_details(cx);
7631 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7632 s.move_heads_with(|map, head, goal| {
7633 movement::up(map, head, goal, false, text_layout_details)
7634 })
7635 })
7636 }
7637
7638 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7639 self.take_rename(true, cx);
7640
7641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7642 cx.propagate();
7643 return;
7644 }
7645
7646 let text_layout_details = &self.text_layout_details(cx);
7647 let selection_count = self.selections.count();
7648 let first_selection = self.selections.first_anchor();
7649
7650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7651 let line_mode = s.line_mode;
7652 s.move_with(|map, selection| {
7653 if !selection.is_empty() && !line_mode {
7654 selection.goal = SelectionGoal::None;
7655 }
7656 let (cursor, goal) = movement::down(
7657 map,
7658 selection.end,
7659 selection.goal,
7660 false,
7661 text_layout_details,
7662 );
7663 selection.collapse_to(cursor, goal);
7664 });
7665 });
7666
7667 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7668 {
7669 cx.propagate();
7670 }
7671 }
7672
7673 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7674 let Some(row_count) = self.visible_row_count() else {
7675 return;
7676 };
7677
7678 let text_layout_details = &self.text_layout_details(cx);
7679
7680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7681 s.move_heads_with(|map, head, goal| {
7682 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7683 })
7684 })
7685 }
7686
7687 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7688 if self.take_rename(true, cx).is_some() {
7689 return;
7690 }
7691
7692 if self
7693 .context_menu
7694 .write()
7695 .as_mut()
7696 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7697 .unwrap_or(false)
7698 {
7699 return;
7700 }
7701
7702 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7703 cx.propagate();
7704 return;
7705 }
7706
7707 let Some(row_count) = self.visible_row_count() else {
7708 return;
7709 };
7710
7711 let autoscroll = if action.center_cursor {
7712 Autoscroll::center()
7713 } else {
7714 Autoscroll::fit()
7715 };
7716
7717 let text_layout_details = &self.text_layout_details(cx);
7718 self.change_selections(Some(autoscroll), cx, |s| {
7719 let line_mode = s.line_mode;
7720 s.move_with(|map, selection| {
7721 if !selection.is_empty() && !line_mode {
7722 selection.goal = SelectionGoal::None;
7723 }
7724 let (cursor, goal) = movement::down_by_rows(
7725 map,
7726 selection.end,
7727 row_count,
7728 selection.goal,
7729 false,
7730 text_layout_details,
7731 );
7732 selection.collapse_to(cursor, goal);
7733 });
7734 });
7735 }
7736
7737 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7738 let text_layout_details = &self.text_layout_details(cx);
7739 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7740 s.move_heads_with(|map, head, goal| {
7741 movement::down(map, head, goal, false, text_layout_details)
7742 })
7743 });
7744 }
7745
7746 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7747 if let Some(context_menu) = self.context_menu.write().as_mut() {
7748 context_menu.select_first(self.completion_provider.as_deref(), cx);
7749 }
7750 }
7751
7752 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7753 if let Some(context_menu) = self.context_menu.write().as_mut() {
7754 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7755 }
7756 }
7757
7758 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7759 if let Some(context_menu) = self.context_menu.write().as_mut() {
7760 context_menu.select_next(self.completion_provider.as_deref(), cx);
7761 }
7762 }
7763
7764 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7765 if let Some(context_menu) = self.context_menu.write().as_mut() {
7766 context_menu.select_last(self.completion_provider.as_deref(), cx);
7767 }
7768 }
7769
7770 pub fn move_to_previous_word_start(
7771 &mut self,
7772 _: &MoveToPreviousWordStart,
7773 cx: &mut ViewContext<Self>,
7774 ) {
7775 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7776 s.move_cursors_with(|map, head, _| {
7777 (
7778 movement::previous_word_start(map, head),
7779 SelectionGoal::None,
7780 )
7781 });
7782 })
7783 }
7784
7785 pub fn move_to_previous_subword_start(
7786 &mut self,
7787 _: &MoveToPreviousSubwordStart,
7788 cx: &mut ViewContext<Self>,
7789 ) {
7790 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7791 s.move_cursors_with(|map, head, _| {
7792 (
7793 movement::previous_subword_start(map, head),
7794 SelectionGoal::None,
7795 )
7796 });
7797 })
7798 }
7799
7800 pub fn select_to_previous_word_start(
7801 &mut self,
7802 _: &SelectToPreviousWordStart,
7803 cx: &mut ViewContext<Self>,
7804 ) {
7805 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7806 s.move_heads_with(|map, head, _| {
7807 (
7808 movement::previous_word_start(map, head),
7809 SelectionGoal::None,
7810 )
7811 });
7812 })
7813 }
7814
7815 pub fn select_to_previous_subword_start(
7816 &mut self,
7817 _: &SelectToPreviousSubwordStart,
7818 cx: &mut ViewContext<Self>,
7819 ) {
7820 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7821 s.move_heads_with(|map, head, _| {
7822 (
7823 movement::previous_subword_start(map, head),
7824 SelectionGoal::None,
7825 )
7826 });
7827 })
7828 }
7829
7830 pub fn delete_to_previous_word_start(
7831 &mut self,
7832 action: &DeleteToPreviousWordStart,
7833 cx: &mut ViewContext<Self>,
7834 ) {
7835 self.transact(cx, |this, cx| {
7836 this.select_autoclose_pair(cx);
7837 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7838 let line_mode = s.line_mode;
7839 s.move_with(|map, selection| {
7840 if selection.is_empty() && !line_mode {
7841 let cursor = if action.ignore_newlines {
7842 movement::previous_word_start(map, selection.head())
7843 } else {
7844 movement::previous_word_start_or_newline(map, selection.head())
7845 };
7846 selection.set_head(cursor, SelectionGoal::None);
7847 }
7848 });
7849 });
7850 this.insert("", cx);
7851 });
7852 }
7853
7854 pub fn delete_to_previous_subword_start(
7855 &mut self,
7856 _: &DeleteToPreviousSubwordStart,
7857 cx: &mut ViewContext<Self>,
7858 ) {
7859 self.transact(cx, |this, cx| {
7860 this.select_autoclose_pair(cx);
7861 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7862 let line_mode = s.line_mode;
7863 s.move_with(|map, selection| {
7864 if selection.is_empty() && !line_mode {
7865 let cursor = movement::previous_subword_start(map, selection.head());
7866 selection.set_head(cursor, SelectionGoal::None);
7867 }
7868 });
7869 });
7870 this.insert("", cx);
7871 });
7872 }
7873
7874 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7875 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7876 s.move_cursors_with(|map, head, _| {
7877 (movement::next_word_end(map, head), SelectionGoal::None)
7878 });
7879 })
7880 }
7881
7882 pub fn move_to_next_subword_end(
7883 &mut self,
7884 _: &MoveToNextSubwordEnd,
7885 cx: &mut ViewContext<Self>,
7886 ) {
7887 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7888 s.move_cursors_with(|map, head, _| {
7889 (movement::next_subword_end(map, head), SelectionGoal::None)
7890 });
7891 })
7892 }
7893
7894 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7895 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7896 s.move_heads_with(|map, head, _| {
7897 (movement::next_word_end(map, head), SelectionGoal::None)
7898 });
7899 })
7900 }
7901
7902 pub fn select_to_next_subword_end(
7903 &mut self,
7904 _: &SelectToNextSubwordEnd,
7905 cx: &mut ViewContext<Self>,
7906 ) {
7907 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7908 s.move_heads_with(|map, head, _| {
7909 (movement::next_subword_end(map, head), SelectionGoal::None)
7910 });
7911 })
7912 }
7913
7914 pub fn delete_to_next_word_end(
7915 &mut self,
7916 action: &DeleteToNextWordEnd,
7917 cx: &mut ViewContext<Self>,
7918 ) {
7919 self.transact(cx, |this, cx| {
7920 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7921 let line_mode = s.line_mode;
7922 s.move_with(|map, selection| {
7923 if selection.is_empty() && !line_mode {
7924 let cursor = if action.ignore_newlines {
7925 movement::next_word_end(map, selection.head())
7926 } else {
7927 movement::next_word_end_or_newline(map, selection.head())
7928 };
7929 selection.set_head(cursor, SelectionGoal::None);
7930 }
7931 });
7932 });
7933 this.insert("", cx);
7934 });
7935 }
7936
7937 pub fn delete_to_next_subword_end(
7938 &mut self,
7939 _: &DeleteToNextSubwordEnd,
7940 cx: &mut ViewContext<Self>,
7941 ) {
7942 self.transact(cx, |this, cx| {
7943 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 s.move_with(|map, selection| {
7945 if selection.is_empty() {
7946 let cursor = movement::next_subword_end(map, selection.head());
7947 selection.set_head(cursor, SelectionGoal::None);
7948 }
7949 });
7950 });
7951 this.insert("", cx);
7952 });
7953 }
7954
7955 pub fn move_to_beginning_of_line(
7956 &mut self,
7957 action: &MoveToBeginningOfLine,
7958 cx: &mut ViewContext<Self>,
7959 ) {
7960 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7961 s.move_cursors_with(|map, head, _| {
7962 (
7963 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7964 SelectionGoal::None,
7965 )
7966 });
7967 })
7968 }
7969
7970 pub fn select_to_beginning_of_line(
7971 &mut self,
7972 action: &SelectToBeginningOfLine,
7973 cx: &mut ViewContext<Self>,
7974 ) {
7975 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7976 s.move_heads_with(|map, head, _| {
7977 (
7978 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7979 SelectionGoal::None,
7980 )
7981 });
7982 });
7983 }
7984
7985 pub fn delete_to_beginning_of_line(
7986 &mut self,
7987 _: &DeleteToBeginningOfLine,
7988 cx: &mut ViewContext<Self>,
7989 ) {
7990 self.transact(cx, |this, cx| {
7991 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7992 s.move_with(|_, selection| {
7993 selection.reversed = true;
7994 });
7995 });
7996
7997 this.select_to_beginning_of_line(
7998 &SelectToBeginningOfLine {
7999 stop_at_soft_wraps: false,
8000 },
8001 cx,
8002 );
8003 this.backspace(&Backspace, cx);
8004 });
8005 }
8006
8007 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8008 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8009 s.move_cursors_with(|map, head, _| {
8010 (
8011 movement::line_end(map, head, action.stop_at_soft_wraps),
8012 SelectionGoal::None,
8013 )
8014 });
8015 })
8016 }
8017
8018 pub fn select_to_end_of_line(
8019 &mut self,
8020 action: &SelectToEndOfLine,
8021 cx: &mut ViewContext<Self>,
8022 ) {
8023 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8024 s.move_heads_with(|map, head, _| {
8025 (
8026 movement::line_end(map, head, action.stop_at_soft_wraps),
8027 SelectionGoal::None,
8028 )
8029 });
8030 })
8031 }
8032
8033 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8034 self.transact(cx, |this, cx| {
8035 this.select_to_end_of_line(
8036 &SelectToEndOfLine {
8037 stop_at_soft_wraps: false,
8038 },
8039 cx,
8040 );
8041 this.delete(&Delete, cx);
8042 });
8043 }
8044
8045 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8046 self.transact(cx, |this, cx| {
8047 this.select_to_end_of_line(
8048 &SelectToEndOfLine {
8049 stop_at_soft_wraps: false,
8050 },
8051 cx,
8052 );
8053 this.cut(&Cut, cx);
8054 });
8055 }
8056
8057 pub fn move_to_start_of_paragraph(
8058 &mut self,
8059 _: &MoveToStartOfParagraph,
8060 cx: &mut ViewContext<Self>,
8061 ) {
8062 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8063 cx.propagate();
8064 return;
8065 }
8066
8067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8068 s.move_with(|map, selection| {
8069 selection.collapse_to(
8070 movement::start_of_paragraph(map, selection.head(), 1),
8071 SelectionGoal::None,
8072 )
8073 });
8074 })
8075 }
8076
8077 pub fn move_to_end_of_paragraph(
8078 &mut self,
8079 _: &MoveToEndOfParagraph,
8080 cx: &mut ViewContext<Self>,
8081 ) {
8082 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8083 cx.propagate();
8084 return;
8085 }
8086
8087 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8088 s.move_with(|map, selection| {
8089 selection.collapse_to(
8090 movement::end_of_paragraph(map, selection.head(), 1),
8091 SelectionGoal::None,
8092 )
8093 });
8094 })
8095 }
8096
8097 pub fn select_to_start_of_paragraph(
8098 &mut self,
8099 _: &SelectToStartOfParagraph,
8100 cx: &mut ViewContext<Self>,
8101 ) {
8102 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8103 cx.propagate();
8104 return;
8105 }
8106
8107 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8108 s.move_heads_with(|map, head, _| {
8109 (
8110 movement::start_of_paragraph(map, head, 1),
8111 SelectionGoal::None,
8112 )
8113 });
8114 })
8115 }
8116
8117 pub fn select_to_end_of_paragraph(
8118 &mut self,
8119 _: &SelectToEndOfParagraph,
8120 cx: &mut ViewContext<Self>,
8121 ) {
8122 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8123 cx.propagate();
8124 return;
8125 }
8126
8127 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8128 s.move_heads_with(|map, head, _| {
8129 (
8130 movement::end_of_paragraph(map, head, 1),
8131 SelectionGoal::None,
8132 )
8133 });
8134 })
8135 }
8136
8137 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8138 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8139 cx.propagate();
8140 return;
8141 }
8142
8143 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8144 s.select_ranges(vec![0..0]);
8145 });
8146 }
8147
8148 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8149 let mut selection = self.selections.last::<Point>(cx);
8150 selection.set_head(Point::zero(), SelectionGoal::None);
8151
8152 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8153 s.select(vec![selection]);
8154 });
8155 }
8156
8157 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8158 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8159 cx.propagate();
8160 return;
8161 }
8162
8163 let cursor = self.buffer.read(cx).read(cx).len();
8164 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8165 s.select_ranges(vec![cursor..cursor])
8166 });
8167 }
8168
8169 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8170 self.nav_history = nav_history;
8171 }
8172
8173 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8174 self.nav_history.as_ref()
8175 }
8176
8177 fn push_to_nav_history(
8178 &mut self,
8179 cursor_anchor: Anchor,
8180 new_position: Option<Point>,
8181 cx: &mut ViewContext<Self>,
8182 ) {
8183 if let Some(nav_history) = self.nav_history.as_mut() {
8184 let buffer = self.buffer.read(cx).read(cx);
8185 let cursor_position = cursor_anchor.to_point(&buffer);
8186 let scroll_state = self.scroll_manager.anchor();
8187 let scroll_top_row = scroll_state.top_row(&buffer);
8188 drop(buffer);
8189
8190 if let Some(new_position) = new_position {
8191 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8192 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8193 return;
8194 }
8195 }
8196
8197 nav_history.push(
8198 Some(NavigationData {
8199 cursor_anchor,
8200 cursor_position,
8201 scroll_anchor: scroll_state,
8202 scroll_top_row,
8203 }),
8204 cx,
8205 );
8206 }
8207 }
8208
8209 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8210 let buffer = self.buffer.read(cx).snapshot(cx);
8211 let mut selection = self.selections.first::<usize>(cx);
8212 selection.set_head(buffer.len(), SelectionGoal::None);
8213 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8214 s.select(vec![selection]);
8215 });
8216 }
8217
8218 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8219 let end = self.buffer.read(cx).read(cx).len();
8220 self.change_selections(None, cx, |s| {
8221 s.select_ranges(vec![0..end]);
8222 });
8223 }
8224
8225 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8226 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8227 let mut selections = self.selections.all::<Point>(cx);
8228 let max_point = display_map.buffer_snapshot.max_point();
8229 for selection in &mut selections {
8230 let rows = selection.spanned_rows(true, &display_map);
8231 selection.start = Point::new(rows.start.0, 0);
8232 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8233 selection.reversed = false;
8234 }
8235 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8236 s.select(selections);
8237 });
8238 }
8239
8240 pub fn split_selection_into_lines(
8241 &mut self,
8242 _: &SplitSelectionIntoLines,
8243 cx: &mut ViewContext<Self>,
8244 ) {
8245 let mut to_unfold = Vec::new();
8246 let mut new_selection_ranges = Vec::new();
8247 {
8248 let selections = self.selections.all::<Point>(cx);
8249 let buffer = self.buffer.read(cx).read(cx);
8250 for selection in selections {
8251 for row in selection.start.row..selection.end.row {
8252 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8253 new_selection_ranges.push(cursor..cursor);
8254 }
8255 new_selection_ranges.push(selection.end..selection.end);
8256 to_unfold.push(selection.start..selection.end);
8257 }
8258 }
8259 self.unfold_ranges(to_unfold, true, true, cx);
8260 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8261 s.select_ranges(new_selection_ranges);
8262 });
8263 }
8264
8265 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8266 self.add_selection(true, cx);
8267 }
8268
8269 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8270 self.add_selection(false, cx);
8271 }
8272
8273 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8275 let mut selections = self.selections.all::<Point>(cx);
8276 let text_layout_details = self.text_layout_details(cx);
8277 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8278 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8279 let range = oldest_selection.display_range(&display_map).sorted();
8280
8281 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8282 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8283 let positions = start_x.min(end_x)..start_x.max(end_x);
8284
8285 selections.clear();
8286 let mut stack = Vec::new();
8287 for row in range.start.row().0..=range.end.row().0 {
8288 if let Some(selection) = self.selections.build_columnar_selection(
8289 &display_map,
8290 DisplayRow(row),
8291 &positions,
8292 oldest_selection.reversed,
8293 &text_layout_details,
8294 ) {
8295 stack.push(selection.id);
8296 selections.push(selection);
8297 }
8298 }
8299
8300 if above {
8301 stack.reverse();
8302 }
8303
8304 AddSelectionsState { above, stack }
8305 });
8306
8307 let last_added_selection = *state.stack.last().unwrap();
8308 let mut new_selections = Vec::new();
8309 if above == state.above {
8310 let end_row = if above {
8311 DisplayRow(0)
8312 } else {
8313 display_map.max_point().row()
8314 };
8315
8316 'outer: for selection in selections {
8317 if selection.id == last_added_selection {
8318 let range = selection.display_range(&display_map).sorted();
8319 debug_assert_eq!(range.start.row(), range.end.row());
8320 let mut row = range.start.row();
8321 let positions =
8322 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8323 px(start)..px(end)
8324 } else {
8325 let start_x =
8326 display_map.x_for_display_point(range.start, &text_layout_details);
8327 let end_x =
8328 display_map.x_for_display_point(range.end, &text_layout_details);
8329 start_x.min(end_x)..start_x.max(end_x)
8330 };
8331
8332 while row != end_row {
8333 if above {
8334 row.0 -= 1;
8335 } else {
8336 row.0 += 1;
8337 }
8338
8339 if let Some(new_selection) = self.selections.build_columnar_selection(
8340 &display_map,
8341 row,
8342 &positions,
8343 selection.reversed,
8344 &text_layout_details,
8345 ) {
8346 state.stack.push(new_selection.id);
8347 if above {
8348 new_selections.push(new_selection);
8349 new_selections.push(selection);
8350 } else {
8351 new_selections.push(selection);
8352 new_selections.push(new_selection);
8353 }
8354
8355 continue 'outer;
8356 }
8357 }
8358 }
8359
8360 new_selections.push(selection);
8361 }
8362 } else {
8363 new_selections = selections;
8364 new_selections.retain(|s| s.id != last_added_selection);
8365 state.stack.pop();
8366 }
8367
8368 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8369 s.select(new_selections);
8370 });
8371 if state.stack.len() > 1 {
8372 self.add_selections_state = Some(state);
8373 }
8374 }
8375
8376 pub fn select_next_match_internal(
8377 &mut self,
8378 display_map: &DisplaySnapshot,
8379 replace_newest: bool,
8380 autoscroll: Option<Autoscroll>,
8381 cx: &mut ViewContext<Self>,
8382 ) -> Result<()> {
8383 fn select_next_match_ranges(
8384 this: &mut Editor,
8385 range: Range<usize>,
8386 replace_newest: bool,
8387 auto_scroll: Option<Autoscroll>,
8388 cx: &mut ViewContext<Editor>,
8389 ) {
8390 this.unfold_ranges([range.clone()], false, true, cx);
8391 this.change_selections(auto_scroll, cx, |s| {
8392 if replace_newest {
8393 s.delete(s.newest_anchor().id);
8394 }
8395 s.insert_range(range.clone());
8396 });
8397 }
8398
8399 let buffer = &display_map.buffer_snapshot;
8400 let mut selections = self.selections.all::<usize>(cx);
8401 if let Some(mut select_next_state) = self.select_next_state.take() {
8402 let query = &select_next_state.query;
8403 if !select_next_state.done {
8404 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8405 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8406 let mut next_selected_range = None;
8407
8408 let bytes_after_last_selection =
8409 buffer.bytes_in_range(last_selection.end..buffer.len());
8410 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8411 let query_matches = query
8412 .stream_find_iter(bytes_after_last_selection)
8413 .map(|result| (last_selection.end, result))
8414 .chain(
8415 query
8416 .stream_find_iter(bytes_before_first_selection)
8417 .map(|result| (0, result)),
8418 );
8419
8420 for (start_offset, query_match) in query_matches {
8421 let query_match = query_match.unwrap(); // can only fail due to I/O
8422 let offset_range =
8423 start_offset + query_match.start()..start_offset + query_match.end();
8424 let display_range = offset_range.start.to_display_point(display_map)
8425 ..offset_range.end.to_display_point(display_map);
8426
8427 if !select_next_state.wordwise
8428 || (!movement::is_inside_word(display_map, display_range.start)
8429 && !movement::is_inside_word(display_map, display_range.end))
8430 {
8431 // TODO: This is n^2, because we might check all the selections
8432 if !selections
8433 .iter()
8434 .any(|selection| selection.range().overlaps(&offset_range))
8435 {
8436 next_selected_range = Some(offset_range);
8437 break;
8438 }
8439 }
8440 }
8441
8442 if let Some(next_selected_range) = next_selected_range {
8443 select_next_match_ranges(
8444 self,
8445 next_selected_range,
8446 replace_newest,
8447 autoscroll,
8448 cx,
8449 );
8450 } else {
8451 select_next_state.done = true;
8452 }
8453 }
8454
8455 self.select_next_state = Some(select_next_state);
8456 } else {
8457 let mut only_carets = true;
8458 let mut same_text_selected = true;
8459 let mut selected_text = None;
8460
8461 let mut selections_iter = selections.iter().peekable();
8462 while let Some(selection) = selections_iter.next() {
8463 if selection.start != selection.end {
8464 only_carets = false;
8465 }
8466
8467 if same_text_selected {
8468 if selected_text.is_none() {
8469 selected_text =
8470 Some(buffer.text_for_range(selection.range()).collect::<String>());
8471 }
8472
8473 if let Some(next_selection) = selections_iter.peek() {
8474 if next_selection.range().len() == selection.range().len() {
8475 let next_selected_text = buffer
8476 .text_for_range(next_selection.range())
8477 .collect::<String>();
8478 if Some(next_selected_text) != selected_text {
8479 same_text_selected = false;
8480 selected_text = None;
8481 }
8482 } else {
8483 same_text_selected = false;
8484 selected_text = None;
8485 }
8486 }
8487 }
8488 }
8489
8490 if only_carets {
8491 for selection in &mut selections {
8492 let word_range = movement::surrounding_word(
8493 display_map,
8494 selection.start.to_display_point(display_map),
8495 );
8496 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8497 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8498 selection.goal = SelectionGoal::None;
8499 selection.reversed = false;
8500 select_next_match_ranges(
8501 self,
8502 selection.start..selection.end,
8503 replace_newest,
8504 autoscroll,
8505 cx,
8506 );
8507 }
8508
8509 if selections.len() == 1 {
8510 let selection = selections
8511 .last()
8512 .expect("ensured that there's only one selection");
8513 let query = buffer
8514 .text_for_range(selection.start..selection.end)
8515 .collect::<String>();
8516 let is_empty = query.is_empty();
8517 let select_state = SelectNextState {
8518 query: AhoCorasick::new(&[query])?,
8519 wordwise: true,
8520 done: is_empty,
8521 };
8522 self.select_next_state = Some(select_state);
8523 } else {
8524 self.select_next_state = None;
8525 }
8526 } else if let Some(selected_text) = selected_text {
8527 self.select_next_state = Some(SelectNextState {
8528 query: AhoCorasick::new(&[selected_text])?,
8529 wordwise: false,
8530 done: false,
8531 });
8532 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8533 }
8534 }
8535 Ok(())
8536 }
8537
8538 pub fn select_all_matches(
8539 &mut self,
8540 _action: &SelectAllMatches,
8541 cx: &mut ViewContext<Self>,
8542 ) -> Result<()> {
8543 self.push_to_selection_history();
8544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8545
8546 self.select_next_match_internal(&display_map, false, None, cx)?;
8547 let Some(select_next_state) = self.select_next_state.as_mut() else {
8548 return Ok(());
8549 };
8550 if select_next_state.done {
8551 return Ok(());
8552 }
8553
8554 let mut new_selections = self.selections.all::<usize>(cx);
8555
8556 let buffer = &display_map.buffer_snapshot;
8557 let query_matches = select_next_state
8558 .query
8559 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8560
8561 for query_match in query_matches {
8562 let query_match = query_match.unwrap(); // can only fail due to I/O
8563 let offset_range = query_match.start()..query_match.end();
8564 let display_range = offset_range.start.to_display_point(&display_map)
8565 ..offset_range.end.to_display_point(&display_map);
8566
8567 if !select_next_state.wordwise
8568 || (!movement::is_inside_word(&display_map, display_range.start)
8569 && !movement::is_inside_word(&display_map, display_range.end))
8570 {
8571 self.selections.change_with(cx, |selections| {
8572 new_selections.push(Selection {
8573 id: selections.new_selection_id(),
8574 start: offset_range.start,
8575 end: offset_range.end,
8576 reversed: false,
8577 goal: SelectionGoal::None,
8578 });
8579 });
8580 }
8581 }
8582
8583 new_selections.sort_by_key(|selection| selection.start);
8584 let mut ix = 0;
8585 while ix + 1 < new_selections.len() {
8586 let current_selection = &new_selections[ix];
8587 let next_selection = &new_selections[ix + 1];
8588 if current_selection.range().overlaps(&next_selection.range()) {
8589 if current_selection.id < next_selection.id {
8590 new_selections.remove(ix + 1);
8591 } else {
8592 new_selections.remove(ix);
8593 }
8594 } else {
8595 ix += 1;
8596 }
8597 }
8598
8599 select_next_state.done = true;
8600 self.unfold_ranges(
8601 new_selections.iter().map(|selection| selection.range()),
8602 false,
8603 false,
8604 cx,
8605 );
8606 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8607 selections.select(new_selections)
8608 });
8609
8610 Ok(())
8611 }
8612
8613 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8614 self.push_to_selection_history();
8615 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8616 self.select_next_match_internal(
8617 &display_map,
8618 action.replace_newest,
8619 Some(Autoscroll::newest()),
8620 cx,
8621 )?;
8622 Ok(())
8623 }
8624
8625 pub fn select_previous(
8626 &mut self,
8627 action: &SelectPrevious,
8628 cx: &mut ViewContext<Self>,
8629 ) -> Result<()> {
8630 self.push_to_selection_history();
8631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8632 let buffer = &display_map.buffer_snapshot;
8633 let mut selections = self.selections.all::<usize>(cx);
8634 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8635 let query = &select_prev_state.query;
8636 if !select_prev_state.done {
8637 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8638 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8639 let mut next_selected_range = None;
8640 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8641 let bytes_before_last_selection =
8642 buffer.reversed_bytes_in_range(0..last_selection.start);
8643 let bytes_after_first_selection =
8644 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8645 let query_matches = query
8646 .stream_find_iter(bytes_before_last_selection)
8647 .map(|result| (last_selection.start, result))
8648 .chain(
8649 query
8650 .stream_find_iter(bytes_after_first_selection)
8651 .map(|result| (buffer.len(), result)),
8652 );
8653 for (end_offset, query_match) in query_matches {
8654 let query_match = query_match.unwrap(); // can only fail due to I/O
8655 let offset_range =
8656 end_offset - query_match.end()..end_offset - query_match.start();
8657 let display_range = offset_range.start.to_display_point(&display_map)
8658 ..offset_range.end.to_display_point(&display_map);
8659
8660 if !select_prev_state.wordwise
8661 || (!movement::is_inside_word(&display_map, display_range.start)
8662 && !movement::is_inside_word(&display_map, display_range.end))
8663 {
8664 next_selected_range = Some(offset_range);
8665 break;
8666 }
8667 }
8668
8669 if let Some(next_selected_range) = next_selected_range {
8670 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8671 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8672 if action.replace_newest {
8673 s.delete(s.newest_anchor().id);
8674 }
8675 s.insert_range(next_selected_range);
8676 });
8677 } else {
8678 select_prev_state.done = true;
8679 }
8680 }
8681
8682 self.select_prev_state = Some(select_prev_state);
8683 } else {
8684 let mut only_carets = true;
8685 let mut same_text_selected = true;
8686 let mut selected_text = None;
8687
8688 let mut selections_iter = selections.iter().peekable();
8689 while let Some(selection) = selections_iter.next() {
8690 if selection.start != selection.end {
8691 only_carets = false;
8692 }
8693
8694 if same_text_selected {
8695 if selected_text.is_none() {
8696 selected_text =
8697 Some(buffer.text_for_range(selection.range()).collect::<String>());
8698 }
8699
8700 if let Some(next_selection) = selections_iter.peek() {
8701 if next_selection.range().len() == selection.range().len() {
8702 let next_selected_text = buffer
8703 .text_for_range(next_selection.range())
8704 .collect::<String>();
8705 if Some(next_selected_text) != selected_text {
8706 same_text_selected = false;
8707 selected_text = None;
8708 }
8709 } else {
8710 same_text_selected = false;
8711 selected_text = None;
8712 }
8713 }
8714 }
8715 }
8716
8717 if only_carets {
8718 for selection in &mut selections {
8719 let word_range = movement::surrounding_word(
8720 &display_map,
8721 selection.start.to_display_point(&display_map),
8722 );
8723 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8724 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8725 selection.goal = SelectionGoal::None;
8726 selection.reversed = false;
8727 }
8728 if selections.len() == 1 {
8729 let selection = selections
8730 .last()
8731 .expect("ensured that there's only one selection");
8732 let query = buffer
8733 .text_for_range(selection.start..selection.end)
8734 .collect::<String>();
8735 let is_empty = query.is_empty();
8736 let select_state = SelectNextState {
8737 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8738 wordwise: true,
8739 done: is_empty,
8740 };
8741 self.select_prev_state = Some(select_state);
8742 } else {
8743 self.select_prev_state = None;
8744 }
8745
8746 self.unfold_ranges(
8747 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8748 false,
8749 true,
8750 cx,
8751 );
8752 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8753 s.select(selections);
8754 });
8755 } else if let Some(selected_text) = selected_text {
8756 self.select_prev_state = Some(SelectNextState {
8757 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8758 wordwise: false,
8759 done: false,
8760 });
8761 self.select_previous(action, cx)?;
8762 }
8763 }
8764 Ok(())
8765 }
8766
8767 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8768 let text_layout_details = &self.text_layout_details(cx);
8769 self.transact(cx, |this, cx| {
8770 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8771 let mut edits = Vec::new();
8772 let mut selection_edit_ranges = Vec::new();
8773 let mut last_toggled_row = None;
8774 let snapshot = this.buffer.read(cx).read(cx);
8775 let empty_str: Arc<str> = Arc::default();
8776 let mut suffixes_inserted = Vec::new();
8777 let ignore_indent = action.ignore_indent;
8778
8779 fn comment_prefix_range(
8780 snapshot: &MultiBufferSnapshot,
8781 row: MultiBufferRow,
8782 comment_prefix: &str,
8783 comment_prefix_whitespace: &str,
8784 ignore_indent: bool,
8785 ) -> Range<Point> {
8786 let indent_size = if ignore_indent {
8787 0
8788 } else {
8789 snapshot.indent_size_for_line(row).len
8790 };
8791
8792 let start = Point::new(row.0, indent_size);
8793
8794 let mut line_bytes = snapshot
8795 .bytes_in_range(start..snapshot.max_point())
8796 .flatten()
8797 .copied();
8798
8799 // If this line currently begins with the line comment prefix, then record
8800 // the range containing the prefix.
8801 if line_bytes
8802 .by_ref()
8803 .take(comment_prefix.len())
8804 .eq(comment_prefix.bytes())
8805 {
8806 // Include any whitespace that matches the comment prefix.
8807 let matching_whitespace_len = line_bytes
8808 .zip(comment_prefix_whitespace.bytes())
8809 .take_while(|(a, b)| a == b)
8810 .count() as u32;
8811 let end = Point::new(
8812 start.row,
8813 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8814 );
8815 start..end
8816 } else {
8817 start..start
8818 }
8819 }
8820
8821 fn comment_suffix_range(
8822 snapshot: &MultiBufferSnapshot,
8823 row: MultiBufferRow,
8824 comment_suffix: &str,
8825 comment_suffix_has_leading_space: bool,
8826 ) -> Range<Point> {
8827 let end = Point::new(row.0, snapshot.line_len(row));
8828 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8829
8830 let mut line_end_bytes = snapshot
8831 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8832 .flatten()
8833 .copied();
8834
8835 let leading_space_len = if suffix_start_column > 0
8836 && line_end_bytes.next() == Some(b' ')
8837 && comment_suffix_has_leading_space
8838 {
8839 1
8840 } else {
8841 0
8842 };
8843
8844 // If this line currently begins with the line comment prefix, then record
8845 // the range containing the prefix.
8846 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8847 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8848 start..end
8849 } else {
8850 end..end
8851 }
8852 }
8853
8854 // TODO: Handle selections that cross excerpts
8855 for selection in &mut selections {
8856 let start_column = snapshot
8857 .indent_size_for_line(MultiBufferRow(selection.start.row))
8858 .len;
8859 let language = if let Some(language) =
8860 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8861 {
8862 language
8863 } else {
8864 continue;
8865 };
8866
8867 selection_edit_ranges.clear();
8868
8869 // If multiple selections contain a given row, avoid processing that
8870 // row more than once.
8871 let mut start_row = MultiBufferRow(selection.start.row);
8872 if last_toggled_row == Some(start_row) {
8873 start_row = start_row.next_row();
8874 }
8875 let end_row =
8876 if selection.end.row > selection.start.row && selection.end.column == 0 {
8877 MultiBufferRow(selection.end.row - 1)
8878 } else {
8879 MultiBufferRow(selection.end.row)
8880 };
8881 last_toggled_row = Some(end_row);
8882
8883 if start_row > end_row {
8884 continue;
8885 }
8886
8887 // If the language has line comments, toggle those.
8888 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8889
8890 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8891 if ignore_indent {
8892 full_comment_prefixes = full_comment_prefixes
8893 .into_iter()
8894 .map(|s| Arc::from(s.trim_end()))
8895 .collect();
8896 }
8897
8898 if !full_comment_prefixes.is_empty() {
8899 let first_prefix = full_comment_prefixes
8900 .first()
8901 .expect("prefixes is non-empty");
8902 let prefix_trimmed_lengths = full_comment_prefixes
8903 .iter()
8904 .map(|p| p.trim_end_matches(' ').len())
8905 .collect::<SmallVec<[usize; 4]>>();
8906
8907 let mut all_selection_lines_are_comments = true;
8908
8909 for row in start_row.0..=end_row.0 {
8910 let row = MultiBufferRow(row);
8911 if start_row < end_row && snapshot.is_line_blank(row) {
8912 continue;
8913 }
8914
8915 let prefix_range = full_comment_prefixes
8916 .iter()
8917 .zip(prefix_trimmed_lengths.iter().copied())
8918 .map(|(prefix, trimmed_prefix_len)| {
8919 comment_prefix_range(
8920 snapshot.deref(),
8921 row,
8922 &prefix[..trimmed_prefix_len],
8923 &prefix[trimmed_prefix_len..],
8924 ignore_indent,
8925 )
8926 })
8927 .max_by_key(|range| range.end.column - range.start.column)
8928 .expect("prefixes is non-empty");
8929
8930 if prefix_range.is_empty() {
8931 all_selection_lines_are_comments = false;
8932 }
8933
8934 selection_edit_ranges.push(prefix_range);
8935 }
8936
8937 if all_selection_lines_are_comments {
8938 edits.extend(
8939 selection_edit_ranges
8940 .iter()
8941 .cloned()
8942 .map(|range| (range, empty_str.clone())),
8943 );
8944 } else {
8945 let min_column = selection_edit_ranges
8946 .iter()
8947 .map(|range| range.start.column)
8948 .min()
8949 .unwrap_or(0);
8950 edits.extend(selection_edit_ranges.iter().map(|range| {
8951 let position = Point::new(range.start.row, min_column);
8952 (position..position, first_prefix.clone())
8953 }));
8954 }
8955 } else if let Some((full_comment_prefix, comment_suffix)) =
8956 language.block_comment_delimiters()
8957 {
8958 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8959 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8960 let prefix_range = comment_prefix_range(
8961 snapshot.deref(),
8962 start_row,
8963 comment_prefix,
8964 comment_prefix_whitespace,
8965 ignore_indent,
8966 );
8967 let suffix_range = comment_suffix_range(
8968 snapshot.deref(),
8969 end_row,
8970 comment_suffix.trim_start_matches(' '),
8971 comment_suffix.starts_with(' '),
8972 );
8973
8974 if prefix_range.is_empty() || suffix_range.is_empty() {
8975 edits.push((
8976 prefix_range.start..prefix_range.start,
8977 full_comment_prefix.clone(),
8978 ));
8979 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8980 suffixes_inserted.push((end_row, comment_suffix.len()));
8981 } else {
8982 edits.push((prefix_range, empty_str.clone()));
8983 edits.push((suffix_range, empty_str.clone()));
8984 }
8985 } else {
8986 continue;
8987 }
8988 }
8989
8990 drop(snapshot);
8991 this.buffer.update(cx, |buffer, cx| {
8992 buffer.edit(edits, None, cx);
8993 });
8994
8995 // Adjust selections so that they end before any comment suffixes that
8996 // were inserted.
8997 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8998 let mut selections = this.selections.all::<Point>(cx);
8999 let snapshot = this.buffer.read(cx).read(cx);
9000 for selection in &mut selections {
9001 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9002 match row.cmp(&MultiBufferRow(selection.end.row)) {
9003 Ordering::Less => {
9004 suffixes_inserted.next();
9005 continue;
9006 }
9007 Ordering::Greater => break,
9008 Ordering::Equal => {
9009 if selection.end.column == snapshot.line_len(row) {
9010 if selection.is_empty() {
9011 selection.start.column -= suffix_len as u32;
9012 }
9013 selection.end.column -= suffix_len as u32;
9014 }
9015 break;
9016 }
9017 }
9018 }
9019 }
9020
9021 drop(snapshot);
9022 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9023
9024 let selections = this.selections.all::<Point>(cx);
9025 let selections_on_single_row = selections.windows(2).all(|selections| {
9026 selections[0].start.row == selections[1].start.row
9027 && selections[0].end.row == selections[1].end.row
9028 && selections[0].start.row == selections[0].end.row
9029 });
9030 let selections_selecting = selections
9031 .iter()
9032 .any(|selection| selection.start != selection.end);
9033 let advance_downwards = action.advance_downwards
9034 && selections_on_single_row
9035 && !selections_selecting
9036 && !matches!(this.mode, EditorMode::SingleLine { .. });
9037
9038 if advance_downwards {
9039 let snapshot = this.buffer.read(cx).snapshot(cx);
9040
9041 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9042 s.move_cursors_with(|display_snapshot, display_point, _| {
9043 let mut point = display_point.to_point(display_snapshot);
9044 point.row += 1;
9045 point = snapshot.clip_point(point, Bias::Left);
9046 let display_point = point.to_display_point(display_snapshot);
9047 let goal = SelectionGoal::HorizontalPosition(
9048 display_snapshot
9049 .x_for_display_point(display_point, text_layout_details)
9050 .into(),
9051 );
9052 (display_point, goal)
9053 })
9054 });
9055 }
9056 });
9057 }
9058
9059 pub fn select_enclosing_symbol(
9060 &mut self,
9061 _: &SelectEnclosingSymbol,
9062 cx: &mut ViewContext<Self>,
9063 ) {
9064 let buffer = self.buffer.read(cx).snapshot(cx);
9065 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9066
9067 fn update_selection(
9068 selection: &Selection<usize>,
9069 buffer_snap: &MultiBufferSnapshot,
9070 ) -> Option<Selection<usize>> {
9071 let cursor = selection.head();
9072 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9073 for symbol in symbols.iter().rev() {
9074 let start = symbol.range.start.to_offset(buffer_snap);
9075 let end = symbol.range.end.to_offset(buffer_snap);
9076 let new_range = start..end;
9077 if start < selection.start || end > selection.end {
9078 return Some(Selection {
9079 id: selection.id,
9080 start: new_range.start,
9081 end: new_range.end,
9082 goal: SelectionGoal::None,
9083 reversed: selection.reversed,
9084 });
9085 }
9086 }
9087 None
9088 }
9089
9090 let mut selected_larger_symbol = false;
9091 let new_selections = old_selections
9092 .iter()
9093 .map(|selection| match update_selection(selection, &buffer) {
9094 Some(new_selection) => {
9095 if new_selection.range() != selection.range() {
9096 selected_larger_symbol = true;
9097 }
9098 new_selection
9099 }
9100 None => selection.clone(),
9101 })
9102 .collect::<Vec<_>>();
9103
9104 if selected_larger_symbol {
9105 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9106 s.select(new_selections);
9107 });
9108 }
9109 }
9110
9111 pub fn select_larger_syntax_node(
9112 &mut self,
9113 _: &SelectLargerSyntaxNode,
9114 cx: &mut ViewContext<Self>,
9115 ) {
9116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9117 let buffer = self.buffer.read(cx).snapshot(cx);
9118 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9119
9120 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9121 let mut selected_larger_node = false;
9122 let new_selections = old_selections
9123 .iter()
9124 .map(|selection| {
9125 let old_range = selection.start..selection.end;
9126 let mut new_range = old_range.clone();
9127 while let Some(containing_range) =
9128 buffer.range_for_syntax_ancestor(new_range.clone())
9129 {
9130 new_range = containing_range;
9131 if !display_map.intersects_fold(new_range.start)
9132 && !display_map.intersects_fold(new_range.end)
9133 {
9134 break;
9135 }
9136 }
9137
9138 selected_larger_node |= new_range != old_range;
9139 Selection {
9140 id: selection.id,
9141 start: new_range.start,
9142 end: new_range.end,
9143 goal: SelectionGoal::None,
9144 reversed: selection.reversed,
9145 }
9146 })
9147 .collect::<Vec<_>>();
9148
9149 if selected_larger_node {
9150 stack.push(old_selections);
9151 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9152 s.select(new_selections);
9153 });
9154 }
9155 self.select_larger_syntax_node_stack = stack;
9156 }
9157
9158 pub fn select_smaller_syntax_node(
9159 &mut self,
9160 _: &SelectSmallerSyntaxNode,
9161 cx: &mut ViewContext<Self>,
9162 ) {
9163 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9164 if let Some(selections) = stack.pop() {
9165 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9166 s.select(selections.to_vec());
9167 });
9168 }
9169 self.select_larger_syntax_node_stack = stack;
9170 }
9171
9172 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9173 if !EditorSettings::get_global(cx).gutter.runnables {
9174 self.clear_tasks();
9175 return Task::ready(());
9176 }
9177 let project = self.project.clone();
9178 cx.spawn(|this, mut cx| async move {
9179 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9180 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9181 }) else {
9182 return;
9183 };
9184
9185 let Some(project) = project else {
9186 return;
9187 };
9188
9189 let hide_runnables = project
9190 .update(&mut cx, |project, cx| {
9191 // Do not display any test indicators in non-dev server remote projects.
9192 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9193 })
9194 .unwrap_or(true);
9195 if hide_runnables {
9196 return;
9197 }
9198 let new_rows =
9199 cx.background_executor()
9200 .spawn({
9201 let snapshot = display_snapshot.clone();
9202 async move {
9203 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9204 }
9205 })
9206 .await;
9207 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9208
9209 this.update(&mut cx, |this, _| {
9210 this.clear_tasks();
9211 for (key, value) in rows {
9212 this.insert_tasks(key, value);
9213 }
9214 })
9215 .ok();
9216 })
9217 }
9218 fn fetch_runnable_ranges(
9219 snapshot: &DisplaySnapshot,
9220 range: Range<Anchor>,
9221 ) -> Vec<language::RunnableRange> {
9222 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9223 }
9224
9225 fn runnable_rows(
9226 project: Model<Project>,
9227 snapshot: DisplaySnapshot,
9228 runnable_ranges: Vec<RunnableRange>,
9229 mut cx: AsyncWindowContext,
9230 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9231 runnable_ranges
9232 .into_iter()
9233 .filter_map(|mut runnable| {
9234 let tasks = cx
9235 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9236 .ok()?;
9237 if tasks.is_empty() {
9238 return None;
9239 }
9240
9241 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9242
9243 let row = snapshot
9244 .buffer_snapshot
9245 .buffer_line_for_row(MultiBufferRow(point.row))?
9246 .1
9247 .start
9248 .row;
9249
9250 let context_range =
9251 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9252 Some((
9253 (runnable.buffer_id, row),
9254 RunnableTasks {
9255 templates: tasks,
9256 offset: MultiBufferOffset(runnable.run_range.start),
9257 context_range,
9258 column: point.column,
9259 extra_variables: runnable.extra_captures,
9260 },
9261 ))
9262 })
9263 .collect()
9264 }
9265
9266 fn templates_with_tags(
9267 project: &Model<Project>,
9268 runnable: &mut Runnable,
9269 cx: &WindowContext<'_>,
9270 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9271 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9272 let (worktree_id, file) = project
9273 .buffer_for_id(runnable.buffer, cx)
9274 .and_then(|buffer| buffer.read(cx).file())
9275 .map(|file| (file.worktree_id(cx), file.clone()))
9276 .unzip();
9277
9278 (
9279 project.task_store().read(cx).task_inventory().cloned(),
9280 worktree_id,
9281 file,
9282 )
9283 });
9284
9285 let tags = mem::take(&mut runnable.tags);
9286 let mut tags: Vec<_> = tags
9287 .into_iter()
9288 .flat_map(|tag| {
9289 let tag = tag.0.clone();
9290 inventory
9291 .as_ref()
9292 .into_iter()
9293 .flat_map(|inventory| {
9294 inventory.read(cx).list_tasks(
9295 file.clone(),
9296 Some(runnable.language.clone()),
9297 worktree_id,
9298 cx,
9299 )
9300 })
9301 .filter(move |(_, template)| {
9302 template.tags.iter().any(|source_tag| source_tag == &tag)
9303 })
9304 })
9305 .sorted_by_key(|(kind, _)| kind.to_owned())
9306 .collect();
9307 if let Some((leading_tag_source, _)) = tags.first() {
9308 // Strongest source wins; if we have worktree tag binding, prefer that to
9309 // global and language bindings;
9310 // if we have a global binding, prefer that to language binding.
9311 let first_mismatch = tags
9312 .iter()
9313 .position(|(tag_source, _)| tag_source != leading_tag_source);
9314 if let Some(index) = first_mismatch {
9315 tags.truncate(index);
9316 }
9317 }
9318
9319 tags
9320 }
9321
9322 pub fn move_to_enclosing_bracket(
9323 &mut self,
9324 _: &MoveToEnclosingBracket,
9325 cx: &mut ViewContext<Self>,
9326 ) {
9327 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9328 s.move_offsets_with(|snapshot, selection| {
9329 let Some(enclosing_bracket_ranges) =
9330 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9331 else {
9332 return;
9333 };
9334
9335 let mut best_length = usize::MAX;
9336 let mut best_inside = false;
9337 let mut best_in_bracket_range = false;
9338 let mut best_destination = None;
9339 for (open, close) in enclosing_bracket_ranges {
9340 let close = close.to_inclusive();
9341 let length = close.end() - open.start;
9342 let inside = selection.start >= open.end && selection.end <= *close.start();
9343 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9344 || close.contains(&selection.head());
9345
9346 // If best is next to a bracket and current isn't, skip
9347 if !in_bracket_range && best_in_bracket_range {
9348 continue;
9349 }
9350
9351 // Prefer smaller lengths unless best is inside and current isn't
9352 if length > best_length && (best_inside || !inside) {
9353 continue;
9354 }
9355
9356 best_length = length;
9357 best_inside = inside;
9358 best_in_bracket_range = in_bracket_range;
9359 best_destination = Some(
9360 if close.contains(&selection.start) && close.contains(&selection.end) {
9361 if inside {
9362 open.end
9363 } else {
9364 open.start
9365 }
9366 } else if inside {
9367 *close.start()
9368 } else {
9369 *close.end()
9370 },
9371 );
9372 }
9373
9374 if let Some(destination) = best_destination {
9375 selection.collapse_to(destination, SelectionGoal::None);
9376 }
9377 })
9378 });
9379 }
9380
9381 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9382 self.end_selection(cx);
9383 self.selection_history.mode = SelectionHistoryMode::Undoing;
9384 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9385 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9386 self.select_next_state = entry.select_next_state;
9387 self.select_prev_state = entry.select_prev_state;
9388 self.add_selections_state = entry.add_selections_state;
9389 self.request_autoscroll(Autoscroll::newest(), cx);
9390 }
9391 self.selection_history.mode = SelectionHistoryMode::Normal;
9392 }
9393
9394 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9395 self.end_selection(cx);
9396 self.selection_history.mode = SelectionHistoryMode::Redoing;
9397 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9398 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9399 self.select_next_state = entry.select_next_state;
9400 self.select_prev_state = entry.select_prev_state;
9401 self.add_selections_state = entry.add_selections_state;
9402 self.request_autoscroll(Autoscroll::newest(), cx);
9403 }
9404 self.selection_history.mode = SelectionHistoryMode::Normal;
9405 }
9406
9407 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9408 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9409 }
9410
9411 pub fn expand_excerpts_down(
9412 &mut self,
9413 action: &ExpandExcerptsDown,
9414 cx: &mut ViewContext<Self>,
9415 ) {
9416 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9417 }
9418
9419 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9420 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9421 }
9422
9423 pub fn expand_excerpts_for_direction(
9424 &mut self,
9425 lines: u32,
9426 direction: ExpandExcerptDirection,
9427 cx: &mut ViewContext<Self>,
9428 ) {
9429 let selections = self.selections.disjoint_anchors();
9430
9431 let lines = if lines == 0 {
9432 EditorSettings::get_global(cx).expand_excerpt_lines
9433 } else {
9434 lines
9435 };
9436
9437 self.buffer.update(cx, |buffer, cx| {
9438 buffer.expand_excerpts(
9439 selections
9440 .iter()
9441 .map(|selection| selection.head().excerpt_id)
9442 .dedup(),
9443 lines,
9444 direction,
9445 cx,
9446 )
9447 })
9448 }
9449
9450 pub fn expand_excerpt(
9451 &mut self,
9452 excerpt: ExcerptId,
9453 direction: ExpandExcerptDirection,
9454 cx: &mut ViewContext<Self>,
9455 ) {
9456 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9457 self.buffer.update(cx, |buffer, cx| {
9458 buffer.expand_excerpts([excerpt], lines, direction, cx)
9459 })
9460 }
9461
9462 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9463 self.go_to_diagnostic_impl(Direction::Next, cx)
9464 }
9465
9466 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9467 self.go_to_diagnostic_impl(Direction::Prev, cx)
9468 }
9469
9470 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9471 let buffer = self.buffer.read(cx).snapshot(cx);
9472 let selection = self.selections.newest::<usize>(cx);
9473
9474 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9475 if direction == Direction::Next {
9476 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9477 let (group_id, jump_to) = popover.activation_info();
9478 if self.activate_diagnostics(group_id, cx) {
9479 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9480 let mut new_selection = s.newest_anchor().clone();
9481 new_selection.collapse_to(jump_to, SelectionGoal::None);
9482 s.select_anchors(vec![new_selection.clone()]);
9483 });
9484 }
9485 return;
9486 }
9487 }
9488
9489 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9490 active_diagnostics
9491 .primary_range
9492 .to_offset(&buffer)
9493 .to_inclusive()
9494 });
9495 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9496 if active_primary_range.contains(&selection.head()) {
9497 *active_primary_range.start()
9498 } else {
9499 selection.head()
9500 }
9501 } else {
9502 selection.head()
9503 };
9504 let snapshot = self.snapshot(cx);
9505 loop {
9506 let diagnostics = if direction == Direction::Prev {
9507 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9508 } else {
9509 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9510 }
9511 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9512 let group = diagnostics
9513 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9514 // be sorted in a stable way
9515 // skip until we are at current active diagnostic, if it exists
9516 .skip_while(|entry| {
9517 (match direction {
9518 Direction::Prev => entry.range.start >= search_start,
9519 Direction::Next => entry.range.start <= search_start,
9520 }) && self
9521 .active_diagnostics
9522 .as_ref()
9523 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9524 })
9525 .find_map(|entry| {
9526 if entry.diagnostic.is_primary
9527 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9528 && !entry.range.is_empty()
9529 // if we match with the active diagnostic, skip it
9530 && Some(entry.diagnostic.group_id)
9531 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9532 {
9533 Some((entry.range, entry.diagnostic.group_id))
9534 } else {
9535 None
9536 }
9537 });
9538
9539 if let Some((primary_range, group_id)) = group {
9540 if self.activate_diagnostics(group_id, cx) {
9541 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9542 s.select(vec![Selection {
9543 id: selection.id,
9544 start: primary_range.start,
9545 end: primary_range.start,
9546 reversed: false,
9547 goal: SelectionGoal::None,
9548 }]);
9549 });
9550 }
9551 break;
9552 } else {
9553 // Cycle around to the start of the buffer, potentially moving back to the start of
9554 // the currently active diagnostic.
9555 active_primary_range.take();
9556 if direction == Direction::Prev {
9557 if search_start == buffer.len() {
9558 break;
9559 } else {
9560 search_start = buffer.len();
9561 }
9562 } else if search_start == 0 {
9563 break;
9564 } else {
9565 search_start = 0;
9566 }
9567 }
9568 }
9569 }
9570
9571 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9572 let snapshot = self
9573 .display_map
9574 .update(cx, |display_map, cx| display_map.snapshot(cx));
9575 let selection = self.selections.newest::<Point>(cx);
9576 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9577 }
9578
9579 fn go_to_hunk_after_position(
9580 &mut self,
9581 snapshot: &DisplaySnapshot,
9582 position: Point,
9583 cx: &mut ViewContext<'_, Editor>,
9584 ) -> Option<MultiBufferDiffHunk> {
9585 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9586 snapshot,
9587 position,
9588 false,
9589 snapshot
9590 .buffer_snapshot
9591 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9592 cx,
9593 ) {
9594 return Some(hunk);
9595 }
9596
9597 let wrapped_point = Point::zero();
9598 self.go_to_next_hunk_in_direction(
9599 snapshot,
9600 wrapped_point,
9601 true,
9602 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9603 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9604 ),
9605 cx,
9606 )
9607 }
9608
9609 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9610 let snapshot = self
9611 .display_map
9612 .update(cx, |display_map, cx| display_map.snapshot(cx));
9613 let selection = self.selections.newest::<Point>(cx);
9614
9615 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9616 }
9617
9618 fn go_to_hunk_before_position(
9619 &mut self,
9620 snapshot: &DisplaySnapshot,
9621 position: Point,
9622 cx: &mut ViewContext<'_, Editor>,
9623 ) -> Option<MultiBufferDiffHunk> {
9624 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9625 snapshot,
9626 position,
9627 false,
9628 snapshot
9629 .buffer_snapshot
9630 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9631 cx,
9632 ) {
9633 return Some(hunk);
9634 }
9635
9636 let wrapped_point = snapshot.buffer_snapshot.max_point();
9637 self.go_to_next_hunk_in_direction(
9638 snapshot,
9639 wrapped_point,
9640 true,
9641 snapshot
9642 .buffer_snapshot
9643 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9644 cx,
9645 )
9646 }
9647
9648 fn go_to_next_hunk_in_direction(
9649 &mut self,
9650 snapshot: &DisplaySnapshot,
9651 initial_point: Point,
9652 is_wrapped: bool,
9653 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9654 cx: &mut ViewContext<Editor>,
9655 ) -> Option<MultiBufferDiffHunk> {
9656 let display_point = initial_point.to_display_point(snapshot);
9657 let mut hunks = hunks
9658 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9659 .filter(|(display_hunk, _)| {
9660 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9661 })
9662 .dedup();
9663
9664 if let Some((display_hunk, hunk)) = hunks.next() {
9665 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9666 let row = display_hunk.start_display_row();
9667 let point = DisplayPoint::new(row, 0);
9668 s.select_display_ranges([point..point]);
9669 });
9670
9671 Some(hunk)
9672 } else {
9673 None
9674 }
9675 }
9676
9677 pub fn go_to_definition(
9678 &mut self,
9679 _: &GoToDefinition,
9680 cx: &mut ViewContext<Self>,
9681 ) -> Task<Result<Navigated>> {
9682 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9683 cx.spawn(|editor, mut cx| async move {
9684 if definition.await? == Navigated::Yes {
9685 return Ok(Navigated::Yes);
9686 }
9687 match editor.update(&mut cx, |editor, cx| {
9688 editor.find_all_references(&FindAllReferences, cx)
9689 })? {
9690 Some(references) => references.await,
9691 None => Ok(Navigated::No),
9692 }
9693 })
9694 }
9695
9696 pub fn go_to_declaration(
9697 &mut self,
9698 _: &GoToDeclaration,
9699 cx: &mut ViewContext<Self>,
9700 ) -> Task<Result<Navigated>> {
9701 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9702 }
9703
9704 pub fn go_to_declaration_split(
9705 &mut self,
9706 _: &GoToDeclaration,
9707 cx: &mut ViewContext<Self>,
9708 ) -> Task<Result<Navigated>> {
9709 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9710 }
9711
9712 pub fn go_to_implementation(
9713 &mut self,
9714 _: &GoToImplementation,
9715 cx: &mut ViewContext<Self>,
9716 ) -> Task<Result<Navigated>> {
9717 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9718 }
9719
9720 pub fn go_to_implementation_split(
9721 &mut self,
9722 _: &GoToImplementationSplit,
9723 cx: &mut ViewContext<Self>,
9724 ) -> Task<Result<Navigated>> {
9725 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9726 }
9727
9728 pub fn go_to_type_definition(
9729 &mut self,
9730 _: &GoToTypeDefinition,
9731 cx: &mut ViewContext<Self>,
9732 ) -> Task<Result<Navigated>> {
9733 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9734 }
9735
9736 pub fn go_to_definition_split(
9737 &mut self,
9738 _: &GoToDefinitionSplit,
9739 cx: &mut ViewContext<Self>,
9740 ) -> Task<Result<Navigated>> {
9741 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9742 }
9743
9744 pub fn go_to_type_definition_split(
9745 &mut self,
9746 _: &GoToTypeDefinitionSplit,
9747 cx: &mut ViewContext<Self>,
9748 ) -> Task<Result<Navigated>> {
9749 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9750 }
9751
9752 fn go_to_definition_of_kind(
9753 &mut self,
9754 kind: GotoDefinitionKind,
9755 split: bool,
9756 cx: &mut ViewContext<Self>,
9757 ) -> Task<Result<Navigated>> {
9758 let Some(provider) = self.semantics_provider.clone() else {
9759 return Task::ready(Ok(Navigated::No));
9760 };
9761 let head = self.selections.newest::<usize>(cx).head();
9762 let buffer = self.buffer.read(cx);
9763 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9764 text_anchor
9765 } else {
9766 return Task::ready(Ok(Navigated::No));
9767 };
9768
9769 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9770 return Task::ready(Ok(Navigated::No));
9771 };
9772
9773 cx.spawn(|editor, mut cx| async move {
9774 let definitions = definitions.await?;
9775 let navigated = editor
9776 .update(&mut cx, |editor, cx| {
9777 editor.navigate_to_hover_links(
9778 Some(kind),
9779 definitions
9780 .into_iter()
9781 .filter(|location| {
9782 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9783 })
9784 .map(HoverLink::Text)
9785 .collect::<Vec<_>>(),
9786 split,
9787 cx,
9788 )
9789 })?
9790 .await?;
9791 anyhow::Ok(navigated)
9792 })
9793 }
9794
9795 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9796 let position = self.selections.newest_anchor().head();
9797 let Some((buffer, buffer_position)) =
9798 self.buffer.read(cx).text_anchor_for_position(position, cx)
9799 else {
9800 return;
9801 };
9802
9803 cx.spawn(|editor, mut cx| async move {
9804 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9805 editor.update(&mut cx, |_, cx| {
9806 cx.open_url(&url);
9807 })
9808 } else {
9809 Ok(())
9810 }
9811 })
9812 .detach();
9813 }
9814
9815 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9816 let Some(workspace) = self.workspace() else {
9817 return;
9818 };
9819
9820 let position = self.selections.newest_anchor().head();
9821
9822 let Some((buffer, buffer_position)) =
9823 self.buffer.read(cx).text_anchor_for_position(position, cx)
9824 else {
9825 return;
9826 };
9827
9828 let project = self.project.clone();
9829
9830 cx.spawn(|_, mut cx| async move {
9831 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9832
9833 if let Some((_, path)) = result {
9834 workspace
9835 .update(&mut cx, |workspace, cx| {
9836 workspace.open_resolved_path(path, cx)
9837 })?
9838 .await?;
9839 }
9840 anyhow::Ok(())
9841 })
9842 .detach();
9843 }
9844
9845 pub(crate) fn navigate_to_hover_links(
9846 &mut self,
9847 kind: Option<GotoDefinitionKind>,
9848 mut definitions: Vec<HoverLink>,
9849 split: bool,
9850 cx: &mut ViewContext<Editor>,
9851 ) -> Task<Result<Navigated>> {
9852 // If there is one definition, just open it directly
9853 if definitions.len() == 1 {
9854 let definition = definitions.pop().unwrap();
9855
9856 enum TargetTaskResult {
9857 Location(Option<Location>),
9858 AlreadyNavigated,
9859 }
9860
9861 let target_task = match definition {
9862 HoverLink::Text(link) => {
9863 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9864 }
9865 HoverLink::InlayHint(lsp_location, server_id) => {
9866 let computation = self.compute_target_location(lsp_location, server_id, cx);
9867 cx.background_executor().spawn(async move {
9868 let location = computation.await?;
9869 Ok(TargetTaskResult::Location(location))
9870 })
9871 }
9872 HoverLink::Url(url) => {
9873 cx.open_url(&url);
9874 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9875 }
9876 HoverLink::File(path) => {
9877 if let Some(workspace) = self.workspace() {
9878 cx.spawn(|_, mut cx| async move {
9879 workspace
9880 .update(&mut cx, |workspace, cx| {
9881 workspace.open_resolved_path(path, cx)
9882 })?
9883 .await
9884 .map(|_| TargetTaskResult::AlreadyNavigated)
9885 })
9886 } else {
9887 Task::ready(Ok(TargetTaskResult::Location(None)))
9888 }
9889 }
9890 };
9891 cx.spawn(|editor, mut cx| async move {
9892 let target = match target_task.await.context("target resolution task")? {
9893 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9894 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9895 TargetTaskResult::Location(Some(target)) => target,
9896 };
9897
9898 editor.update(&mut cx, |editor, cx| {
9899 let Some(workspace) = editor.workspace() else {
9900 return Navigated::No;
9901 };
9902 let pane = workspace.read(cx).active_pane().clone();
9903
9904 let range = target.range.to_offset(target.buffer.read(cx));
9905 let range = editor.range_for_match(&range);
9906
9907 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9908 let buffer = target.buffer.read(cx);
9909 let range = check_multiline_range(buffer, range);
9910 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9911 s.select_ranges([range]);
9912 });
9913 } else {
9914 cx.window_context().defer(move |cx| {
9915 let target_editor: View<Self> =
9916 workspace.update(cx, |workspace, cx| {
9917 let pane = if split {
9918 workspace.adjacent_pane(cx)
9919 } else {
9920 workspace.active_pane().clone()
9921 };
9922
9923 workspace.open_project_item(
9924 pane,
9925 target.buffer.clone(),
9926 true,
9927 true,
9928 cx,
9929 )
9930 });
9931 target_editor.update(cx, |target_editor, cx| {
9932 // When selecting a definition in a different buffer, disable the nav history
9933 // to avoid creating a history entry at the previous cursor location.
9934 pane.update(cx, |pane, _| pane.disable_history());
9935 let buffer = target.buffer.read(cx);
9936 let range = check_multiline_range(buffer, range);
9937 target_editor.change_selections(
9938 Some(Autoscroll::focused()),
9939 cx,
9940 |s| {
9941 s.select_ranges([range]);
9942 },
9943 );
9944 pane.update(cx, |pane, _| pane.enable_history());
9945 });
9946 });
9947 }
9948 Navigated::Yes
9949 })
9950 })
9951 } else if !definitions.is_empty() {
9952 cx.spawn(|editor, mut cx| async move {
9953 let (title, location_tasks, workspace) = editor
9954 .update(&mut cx, |editor, cx| {
9955 let tab_kind = match kind {
9956 Some(GotoDefinitionKind::Implementation) => "Implementations",
9957 _ => "Definitions",
9958 };
9959 let title = definitions
9960 .iter()
9961 .find_map(|definition| match definition {
9962 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9963 let buffer = origin.buffer.read(cx);
9964 format!(
9965 "{} for {}",
9966 tab_kind,
9967 buffer
9968 .text_for_range(origin.range.clone())
9969 .collect::<String>()
9970 )
9971 }),
9972 HoverLink::InlayHint(_, _) => None,
9973 HoverLink::Url(_) => None,
9974 HoverLink::File(_) => None,
9975 })
9976 .unwrap_or(tab_kind.to_string());
9977 let location_tasks = definitions
9978 .into_iter()
9979 .map(|definition| match definition {
9980 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9981 HoverLink::InlayHint(lsp_location, server_id) => {
9982 editor.compute_target_location(lsp_location, server_id, cx)
9983 }
9984 HoverLink::Url(_) => Task::ready(Ok(None)),
9985 HoverLink::File(_) => Task::ready(Ok(None)),
9986 })
9987 .collect::<Vec<_>>();
9988 (title, location_tasks, editor.workspace().clone())
9989 })
9990 .context("location tasks preparation")?;
9991
9992 let locations = future::join_all(location_tasks)
9993 .await
9994 .into_iter()
9995 .filter_map(|location| location.transpose())
9996 .collect::<Result<_>>()
9997 .context("location tasks")?;
9998
9999 let Some(workspace) = workspace else {
10000 return Ok(Navigated::No);
10001 };
10002 let opened = workspace
10003 .update(&mut cx, |workspace, cx| {
10004 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10005 })
10006 .ok();
10007
10008 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10009 })
10010 } else {
10011 Task::ready(Ok(Navigated::No))
10012 }
10013 }
10014
10015 fn compute_target_location(
10016 &self,
10017 lsp_location: lsp::Location,
10018 server_id: LanguageServerId,
10019 cx: &mut ViewContext<Self>,
10020 ) -> Task<anyhow::Result<Option<Location>>> {
10021 let Some(project) = self.project.clone() else {
10022 return Task::Ready(Some(Ok(None)));
10023 };
10024
10025 cx.spawn(move |editor, mut cx| async move {
10026 let location_task = editor.update(&mut cx, |_, cx| {
10027 project.update(cx, |project, cx| {
10028 let language_server_name = project
10029 .language_server_statuses(cx)
10030 .find(|(id, _)| server_id == *id)
10031 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10032 language_server_name.map(|language_server_name| {
10033 project.open_local_buffer_via_lsp(
10034 lsp_location.uri.clone(),
10035 server_id,
10036 language_server_name,
10037 cx,
10038 )
10039 })
10040 })
10041 })?;
10042 let location = match location_task {
10043 Some(task) => Some({
10044 let target_buffer_handle = task.await.context("open local buffer")?;
10045 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10046 let target_start = target_buffer
10047 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10048 let target_end = target_buffer
10049 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10050 target_buffer.anchor_after(target_start)
10051 ..target_buffer.anchor_before(target_end)
10052 })?;
10053 Location {
10054 buffer: target_buffer_handle,
10055 range,
10056 }
10057 }),
10058 None => None,
10059 };
10060 Ok(location)
10061 })
10062 }
10063
10064 pub fn find_all_references(
10065 &mut self,
10066 _: &FindAllReferences,
10067 cx: &mut ViewContext<Self>,
10068 ) -> Option<Task<Result<Navigated>>> {
10069 let selection = self.selections.newest::<usize>(cx);
10070 let multi_buffer = self.buffer.read(cx);
10071 let head = selection.head();
10072
10073 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10074 let head_anchor = multi_buffer_snapshot.anchor_at(
10075 head,
10076 if head < selection.tail() {
10077 Bias::Right
10078 } else {
10079 Bias::Left
10080 },
10081 );
10082
10083 match self
10084 .find_all_references_task_sources
10085 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10086 {
10087 Ok(_) => {
10088 log::info!(
10089 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10090 );
10091 return None;
10092 }
10093 Err(i) => {
10094 self.find_all_references_task_sources.insert(i, head_anchor);
10095 }
10096 }
10097
10098 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10099 let workspace = self.workspace()?;
10100 let project = workspace.read(cx).project().clone();
10101 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10102 Some(cx.spawn(|editor, mut cx| async move {
10103 let _cleanup = defer({
10104 let mut cx = cx.clone();
10105 move || {
10106 let _ = editor.update(&mut cx, |editor, _| {
10107 if let Ok(i) =
10108 editor
10109 .find_all_references_task_sources
10110 .binary_search_by(|anchor| {
10111 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10112 })
10113 {
10114 editor.find_all_references_task_sources.remove(i);
10115 }
10116 });
10117 }
10118 });
10119
10120 let locations = references.await?;
10121 if locations.is_empty() {
10122 return anyhow::Ok(Navigated::No);
10123 }
10124
10125 workspace.update(&mut cx, |workspace, cx| {
10126 let title = locations
10127 .first()
10128 .as_ref()
10129 .map(|location| {
10130 let buffer = location.buffer.read(cx);
10131 format!(
10132 "References to `{}`",
10133 buffer
10134 .text_for_range(location.range.clone())
10135 .collect::<String>()
10136 )
10137 })
10138 .unwrap();
10139 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10140 Navigated::Yes
10141 })
10142 }))
10143 }
10144
10145 /// Opens a multibuffer with the given project locations in it
10146 pub fn open_locations_in_multibuffer(
10147 workspace: &mut Workspace,
10148 mut locations: Vec<Location>,
10149 title: String,
10150 split: bool,
10151 cx: &mut ViewContext<Workspace>,
10152 ) {
10153 // If there are multiple definitions, open them in a multibuffer
10154 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10155 let mut locations = locations.into_iter().peekable();
10156 let mut ranges_to_highlight = Vec::new();
10157 let capability = workspace.project().read(cx).capability();
10158
10159 let excerpt_buffer = cx.new_model(|cx| {
10160 let mut multibuffer = MultiBuffer::new(capability);
10161 while let Some(location) = locations.next() {
10162 let buffer = location.buffer.read(cx);
10163 let mut ranges_for_buffer = Vec::new();
10164 let range = location.range.to_offset(buffer);
10165 ranges_for_buffer.push(range.clone());
10166
10167 while let Some(next_location) = locations.peek() {
10168 if next_location.buffer == location.buffer {
10169 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10170 locations.next();
10171 } else {
10172 break;
10173 }
10174 }
10175
10176 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10177 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10178 location.buffer.clone(),
10179 ranges_for_buffer,
10180 DEFAULT_MULTIBUFFER_CONTEXT,
10181 cx,
10182 ))
10183 }
10184
10185 multibuffer.with_title(title)
10186 });
10187
10188 let editor = cx.new_view(|cx| {
10189 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10190 });
10191 editor.update(cx, |editor, cx| {
10192 if let Some(first_range) = ranges_to_highlight.first() {
10193 editor.change_selections(None, cx, |selections| {
10194 selections.clear_disjoint();
10195 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10196 });
10197 }
10198 editor.highlight_background::<Self>(
10199 &ranges_to_highlight,
10200 |theme| theme.editor_highlighted_line_background,
10201 cx,
10202 );
10203 });
10204
10205 let item = Box::new(editor);
10206 let item_id = item.item_id();
10207
10208 if split {
10209 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10210 } else {
10211 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10212 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10213 pane.close_current_preview_item(cx)
10214 } else {
10215 None
10216 }
10217 });
10218 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10219 }
10220 workspace.active_pane().update(cx, |pane, cx| {
10221 pane.set_preview_item_id(Some(item_id), cx);
10222 });
10223 }
10224
10225 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10226 use language::ToOffset as _;
10227
10228 let provider = self.semantics_provider.clone()?;
10229 let selection = self.selections.newest_anchor().clone();
10230 let (cursor_buffer, cursor_buffer_position) = self
10231 .buffer
10232 .read(cx)
10233 .text_anchor_for_position(selection.head(), cx)?;
10234 let (tail_buffer, cursor_buffer_position_end) = self
10235 .buffer
10236 .read(cx)
10237 .text_anchor_for_position(selection.tail(), cx)?;
10238 if tail_buffer != cursor_buffer {
10239 return None;
10240 }
10241
10242 let snapshot = cursor_buffer.read(cx).snapshot();
10243 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10244 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10245 let prepare_rename = provider
10246 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10247 .unwrap_or_else(|| Task::ready(Ok(None)));
10248 drop(snapshot);
10249
10250 Some(cx.spawn(|this, mut cx| async move {
10251 let rename_range = if let Some(range) = prepare_rename.await? {
10252 Some(range)
10253 } else {
10254 this.update(&mut cx, |this, cx| {
10255 let buffer = this.buffer.read(cx).snapshot(cx);
10256 let mut buffer_highlights = this
10257 .document_highlights_for_position(selection.head(), &buffer)
10258 .filter(|highlight| {
10259 highlight.start.excerpt_id == selection.head().excerpt_id
10260 && highlight.end.excerpt_id == selection.head().excerpt_id
10261 });
10262 buffer_highlights
10263 .next()
10264 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10265 })?
10266 };
10267 if let Some(rename_range) = rename_range {
10268 this.update(&mut cx, |this, cx| {
10269 let snapshot = cursor_buffer.read(cx).snapshot();
10270 let rename_buffer_range = rename_range.to_offset(&snapshot);
10271 let cursor_offset_in_rename_range =
10272 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10273 let cursor_offset_in_rename_range_end =
10274 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10275
10276 this.take_rename(false, cx);
10277 let buffer = this.buffer.read(cx).read(cx);
10278 let cursor_offset = selection.head().to_offset(&buffer);
10279 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10280 let rename_end = rename_start + rename_buffer_range.len();
10281 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10282 let mut old_highlight_id = None;
10283 let old_name: Arc<str> = buffer
10284 .chunks(rename_start..rename_end, true)
10285 .map(|chunk| {
10286 if old_highlight_id.is_none() {
10287 old_highlight_id = chunk.syntax_highlight_id;
10288 }
10289 chunk.text
10290 })
10291 .collect::<String>()
10292 .into();
10293
10294 drop(buffer);
10295
10296 // Position the selection in the rename editor so that it matches the current selection.
10297 this.show_local_selections = false;
10298 let rename_editor = cx.new_view(|cx| {
10299 let mut editor = Editor::single_line(cx);
10300 editor.buffer.update(cx, |buffer, cx| {
10301 buffer.edit([(0..0, old_name.clone())], None, cx)
10302 });
10303 let rename_selection_range = match cursor_offset_in_rename_range
10304 .cmp(&cursor_offset_in_rename_range_end)
10305 {
10306 Ordering::Equal => {
10307 editor.select_all(&SelectAll, cx);
10308 return editor;
10309 }
10310 Ordering::Less => {
10311 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10312 }
10313 Ordering::Greater => {
10314 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10315 }
10316 };
10317 if rename_selection_range.end > old_name.len() {
10318 editor.select_all(&SelectAll, cx);
10319 } else {
10320 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10321 s.select_ranges([rename_selection_range]);
10322 });
10323 }
10324 editor
10325 });
10326 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10327 if e == &EditorEvent::Focused {
10328 cx.emit(EditorEvent::FocusedIn)
10329 }
10330 })
10331 .detach();
10332
10333 let write_highlights =
10334 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10335 let read_highlights =
10336 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10337 let ranges = write_highlights
10338 .iter()
10339 .flat_map(|(_, ranges)| ranges.iter())
10340 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10341 .cloned()
10342 .collect();
10343
10344 this.highlight_text::<Rename>(
10345 ranges,
10346 HighlightStyle {
10347 fade_out: Some(0.6),
10348 ..Default::default()
10349 },
10350 cx,
10351 );
10352 let rename_focus_handle = rename_editor.focus_handle(cx);
10353 cx.focus(&rename_focus_handle);
10354 let block_id = this.insert_blocks(
10355 [BlockProperties {
10356 style: BlockStyle::Flex,
10357 placement: BlockPlacement::Below(range.start),
10358 height: 1,
10359 render: Box::new({
10360 let rename_editor = rename_editor.clone();
10361 move |cx: &mut BlockContext| {
10362 let mut text_style = cx.editor_style.text.clone();
10363 if let Some(highlight_style) = old_highlight_id
10364 .and_then(|h| h.style(&cx.editor_style.syntax))
10365 {
10366 text_style = text_style.highlight(highlight_style);
10367 }
10368 div()
10369 .pl(cx.anchor_x)
10370 .child(EditorElement::new(
10371 &rename_editor,
10372 EditorStyle {
10373 background: cx.theme().system().transparent,
10374 local_player: cx.editor_style.local_player,
10375 text: text_style,
10376 scrollbar_width: cx.editor_style.scrollbar_width,
10377 syntax: cx.editor_style.syntax.clone(),
10378 status: cx.editor_style.status.clone(),
10379 inlay_hints_style: HighlightStyle {
10380 font_weight: Some(FontWeight::BOLD),
10381 ..make_inlay_hints_style(cx)
10382 },
10383 suggestions_style: HighlightStyle {
10384 color: Some(cx.theme().status().predictive),
10385 ..HighlightStyle::default()
10386 },
10387 ..EditorStyle::default()
10388 },
10389 ))
10390 .into_any_element()
10391 }
10392 }),
10393 priority: 0,
10394 }],
10395 Some(Autoscroll::fit()),
10396 cx,
10397 )[0];
10398 this.pending_rename = Some(RenameState {
10399 range,
10400 old_name,
10401 editor: rename_editor,
10402 block_id,
10403 });
10404 })?;
10405 }
10406
10407 Ok(())
10408 }))
10409 }
10410
10411 pub fn confirm_rename(
10412 &mut self,
10413 _: &ConfirmRename,
10414 cx: &mut ViewContext<Self>,
10415 ) -> Option<Task<Result<()>>> {
10416 let rename = self.take_rename(false, cx)?;
10417 let workspace = self.workspace()?.downgrade();
10418 let (buffer, start) = self
10419 .buffer
10420 .read(cx)
10421 .text_anchor_for_position(rename.range.start, cx)?;
10422 let (end_buffer, _) = self
10423 .buffer
10424 .read(cx)
10425 .text_anchor_for_position(rename.range.end, cx)?;
10426 if buffer != end_buffer {
10427 return None;
10428 }
10429
10430 let old_name = rename.old_name;
10431 let new_name = rename.editor.read(cx).text(cx);
10432
10433 let rename = self.semantics_provider.as_ref()?.perform_rename(
10434 &buffer,
10435 start,
10436 new_name.clone(),
10437 cx,
10438 )?;
10439
10440 Some(cx.spawn(|editor, mut cx| async move {
10441 let project_transaction = rename.await?;
10442 Self::open_project_transaction(
10443 &editor,
10444 workspace,
10445 project_transaction,
10446 format!("Rename: {} → {}", old_name, new_name),
10447 cx.clone(),
10448 )
10449 .await?;
10450
10451 editor.update(&mut cx, |editor, cx| {
10452 editor.refresh_document_highlights(cx);
10453 })?;
10454 Ok(())
10455 }))
10456 }
10457
10458 fn take_rename(
10459 &mut self,
10460 moving_cursor: bool,
10461 cx: &mut ViewContext<Self>,
10462 ) -> Option<RenameState> {
10463 let rename = self.pending_rename.take()?;
10464 if rename.editor.focus_handle(cx).is_focused(cx) {
10465 cx.focus(&self.focus_handle);
10466 }
10467
10468 self.remove_blocks(
10469 [rename.block_id].into_iter().collect(),
10470 Some(Autoscroll::fit()),
10471 cx,
10472 );
10473 self.clear_highlights::<Rename>(cx);
10474 self.show_local_selections = true;
10475
10476 if moving_cursor {
10477 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10478 editor.selections.newest::<usize>(cx).head()
10479 });
10480
10481 // Update the selection to match the position of the selection inside
10482 // the rename editor.
10483 let snapshot = self.buffer.read(cx).read(cx);
10484 let rename_range = rename.range.to_offset(&snapshot);
10485 let cursor_in_editor = snapshot
10486 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10487 .min(rename_range.end);
10488 drop(snapshot);
10489
10490 self.change_selections(None, cx, |s| {
10491 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10492 });
10493 } else {
10494 self.refresh_document_highlights(cx);
10495 }
10496
10497 Some(rename)
10498 }
10499
10500 pub fn pending_rename(&self) -> Option<&RenameState> {
10501 self.pending_rename.as_ref()
10502 }
10503
10504 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10505 let project = match &self.project {
10506 Some(project) => project.clone(),
10507 None => return None,
10508 };
10509
10510 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10511 }
10512
10513 fn format_selections(
10514 &mut self,
10515 _: &FormatSelections,
10516 cx: &mut ViewContext<Self>,
10517 ) -> Option<Task<Result<()>>> {
10518 let project = match &self.project {
10519 Some(project) => project.clone(),
10520 None => return None,
10521 };
10522
10523 let selections = self
10524 .selections
10525 .all_adjusted(cx)
10526 .into_iter()
10527 .filter(|s| !s.is_empty())
10528 .collect_vec();
10529
10530 Some(self.perform_format(
10531 project,
10532 FormatTrigger::Manual,
10533 FormatTarget::Ranges(selections),
10534 cx,
10535 ))
10536 }
10537
10538 fn perform_format(
10539 &mut self,
10540 project: Model<Project>,
10541 trigger: FormatTrigger,
10542 target: FormatTarget,
10543 cx: &mut ViewContext<Self>,
10544 ) -> Task<Result<()>> {
10545 let buffer = self.buffer().clone();
10546 let mut buffers = buffer.read(cx).all_buffers();
10547 if trigger == FormatTrigger::Save {
10548 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10549 }
10550
10551 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10552 let format = project.update(cx, |project, cx| {
10553 project.format(buffers, true, trigger, target, cx)
10554 });
10555
10556 cx.spawn(|_, mut cx| async move {
10557 let transaction = futures::select_biased! {
10558 () = timeout => {
10559 log::warn!("timed out waiting for formatting");
10560 None
10561 }
10562 transaction = format.log_err().fuse() => transaction,
10563 };
10564
10565 buffer
10566 .update(&mut cx, |buffer, cx| {
10567 if let Some(transaction) = transaction {
10568 if !buffer.is_singleton() {
10569 buffer.push_transaction(&transaction.0, cx);
10570 }
10571 }
10572
10573 cx.notify();
10574 })
10575 .ok();
10576
10577 Ok(())
10578 })
10579 }
10580
10581 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10582 if let Some(project) = self.project.clone() {
10583 self.buffer.update(cx, |multi_buffer, cx| {
10584 project.update(cx, |project, cx| {
10585 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10586 });
10587 })
10588 }
10589 }
10590
10591 fn cancel_language_server_work(
10592 &mut self,
10593 _: &actions::CancelLanguageServerWork,
10594 cx: &mut ViewContext<Self>,
10595 ) {
10596 if let Some(project) = self.project.clone() {
10597 self.buffer.update(cx, |multi_buffer, cx| {
10598 project.update(cx, |project, cx| {
10599 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10600 });
10601 })
10602 }
10603 }
10604
10605 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10606 cx.show_character_palette();
10607 }
10608
10609 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10610 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10611 let buffer = self.buffer.read(cx).snapshot(cx);
10612 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10613 let is_valid = buffer
10614 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10615 .any(|entry| {
10616 entry.diagnostic.is_primary
10617 && !entry.range.is_empty()
10618 && entry.range.start == primary_range_start
10619 && entry.diagnostic.message == active_diagnostics.primary_message
10620 });
10621
10622 if is_valid != active_diagnostics.is_valid {
10623 active_diagnostics.is_valid = is_valid;
10624 let mut new_styles = HashMap::default();
10625 for (block_id, diagnostic) in &active_diagnostics.blocks {
10626 new_styles.insert(
10627 *block_id,
10628 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10629 );
10630 }
10631 self.display_map.update(cx, |display_map, _cx| {
10632 display_map.replace_blocks(new_styles)
10633 });
10634 }
10635 }
10636 }
10637
10638 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10639 self.dismiss_diagnostics(cx);
10640 let snapshot = self.snapshot(cx);
10641 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10642 let buffer = self.buffer.read(cx).snapshot(cx);
10643
10644 let mut primary_range = None;
10645 let mut primary_message = None;
10646 let mut group_end = Point::zero();
10647 let diagnostic_group = buffer
10648 .diagnostic_group::<MultiBufferPoint>(group_id)
10649 .filter_map(|entry| {
10650 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10651 && (entry.range.start.row == entry.range.end.row
10652 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10653 {
10654 return None;
10655 }
10656 if entry.range.end > group_end {
10657 group_end = entry.range.end;
10658 }
10659 if entry.diagnostic.is_primary {
10660 primary_range = Some(entry.range.clone());
10661 primary_message = Some(entry.diagnostic.message.clone());
10662 }
10663 Some(entry)
10664 })
10665 .collect::<Vec<_>>();
10666 let primary_range = primary_range?;
10667 let primary_message = primary_message?;
10668 let primary_range =
10669 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10670
10671 let blocks = display_map
10672 .insert_blocks(
10673 diagnostic_group.iter().map(|entry| {
10674 let diagnostic = entry.diagnostic.clone();
10675 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10676 BlockProperties {
10677 style: BlockStyle::Fixed,
10678 placement: BlockPlacement::Below(
10679 buffer.anchor_after(entry.range.start),
10680 ),
10681 height: message_height,
10682 render: diagnostic_block_renderer(diagnostic, None, true, true),
10683 priority: 0,
10684 }
10685 }),
10686 cx,
10687 )
10688 .into_iter()
10689 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10690 .collect();
10691
10692 Some(ActiveDiagnosticGroup {
10693 primary_range,
10694 primary_message,
10695 group_id,
10696 blocks,
10697 is_valid: true,
10698 })
10699 });
10700 self.active_diagnostics.is_some()
10701 }
10702
10703 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10704 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10705 self.display_map.update(cx, |display_map, cx| {
10706 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10707 });
10708 cx.notify();
10709 }
10710 }
10711
10712 pub fn set_selections_from_remote(
10713 &mut self,
10714 selections: Vec<Selection<Anchor>>,
10715 pending_selection: Option<Selection<Anchor>>,
10716 cx: &mut ViewContext<Self>,
10717 ) {
10718 let old_cursor_position = self.selections.newest_anchor().head();
10719 self.selections.change_with(cx, |s| {
10720 s.select_anchors(selections);
10721 if let Some(pending_selection) = pending_selection {
10722 s.set_pending(pending_selection, SelectMode::Character);
10723 } else {
10724 s.clear_pending();
10725 }
10726 });
10727 self.selections_did_change(false, &old_cursor_position, true, cx);
10728 }
10729
10730 fn push_to_selection_history(&mut self) {
10731 self.selection_history.push(SelectionHistoryEntry {
10732 selections: self.selections.disjoint_anchors(),
10733 select_next_state: self.select_next_state.clone(),
10734 select_prev_state: self.select_prev_state.clone(),
10735 add_selections_state: self.add_selections_state.clone(),
10736 });
10737 }
10738
10739 pub fn transact(
10740 &mut self,
10741 cx: &mut ViewContext<Self>,
10742 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10743 ) -> Option<TransactionId> {
10744 self.start_transaction_at(Instant::now(), cx);
10745 update(self, cx);
10746 self.end_transaction_at(Instant::now(), cx)
10747 }
10748
10749 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10750 self.end_selection(cx);
10751 if let Some(tx_id) = self
10752 .buffer
10753 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10754 {
10755 self.selection_history
10756 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10757 cx.emit(EditorEvent::TransactionBegun {
10758 transaction_id: tx_id,
10759 })
10760 }
10761 }
10762
10763 fn end_transaction_at(
10764 &mut self,
10765 now: Instant,
10766 cx: &mut ViewContext<Self>,
10767 ) -> Option<TransactionId> {
10768 if let Some(transaction_id) = self
10769 .buffer
10770 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10771 {
10772 if let Some((_, end_selections)) =
10773 self.selection_history.transaction_mut(transaction_id)
10774 {
10775 *end_selections = Some(self.selections.disjoint_anchors());
10776 } else {
10777 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10778 }
10779
10780 cx.emit(EditorEvent::Edited { transaction_id });
10781 Some(transaction_id)
10782 } else {
10783 None
10784 }
10785 }
10786
10787 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10788 let selection = self.selections.newest::<Point>(cx);
10789
10790 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10791 let range = if selection.is_empty() {
10792 let point = selection.head().to_display_point(&display_map);
10793 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10794 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10795 .to_point(&display_map);
10796 start..end
10797 } else {
10798 selection.range()
10799 };
10800 if display_map.folds_in_range(range).next().is_some() {
10801 self.unfold_lines(&Default::default(), cx)
10802 } else {
10803 self.fold(&Default::default(), cx)
10804 }
10805 }
10806
10807 pub fn toggle_fold_recursive(
10808 &mut self,
10809 _: &actions::ToggleFoldRecursive,
10810 cx: &mut ViewContext<Self>,
10811 ) {
10812 let selection = self.selections.newest::<Point>(cx);
10813
10814 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10815 let range = if selection.is_empty() {
10816 let point = selection.head().to_display_point(&display_map);
10817 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10818 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10819 .to_point(&display_map);
10820 start..end
10821 } else {
10822 selection.range()
10823 };
10824 if display_map.folds_in_range(range).next().is_some() {
10825 self.unfold_recursive(&Default::default(), cx)
10826 } else {
10827 self.fold_recursive(&Default::default(), cx)
10828 }
10829 }
10830
10831 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10832 let mut fold_ranges = Vec::new();
10833 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10834 let selections = self.selections.all_adjusted(cx);
10835
10836 for selection in selections {
10837 let range = selection.range().sorted();
10838 let buffer_start_row = range.start.row;
10839
10840 if range.start.row != range.end.row {
10841 let mut found = false;
10842 let mut row = range.start.row;
10843 while row <= range.end.row {
10844 if let Some((foldable_range, fold_text)) =
10845 { display_map.foldable_range(MultiBufferRow(row)) }
10846 {
10847 found = true;
10848 row = foldable_range.end.row + 1;
10849 fold_ranges.push((foldable_range, fold_text));
10850 } else {
10851 row += 1
10852 }
10853 }
10854 if found {
10855 continue;
10856 }
10857 }
10858
10859 for row in (0..=range.start.row).rev() {
10860 if let Some((foldable_range, fold_text)) =
10861 display_map.foldable_range(MultiBufferRow(row))
10862 {
10863 if foldable_range.end.row >= buffer_start_row {
10864 fold_ranges.push((foldable_range, fold_text));
10865 if row <= range.start.row {
10866 break;
10867 }
10868 }
10869 }
10870 }
10871 }
10872
10873 self.fold_ranges(fold_ranges, true, cx);
10874 }
10875
10876 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10877 let fold_at_level = fold_at.level;
10878 let snapshot = self.buffer.read(cx).snapshot(cx);
10879 let mut fold_ranges = Vec::new();
10880 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10881
10882 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10883 while start_row < end_row {
10884 match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10885 Some(foldable_range) => {
10886 let nested_start_row = foldable_range.0.start.row + 1;
10887 let nested_end_row = foldable_range.0.end.row;
10888
10889 if current_level < fold_at_level {
10890 stack.push((nested_start_row, nested_end_row, current_level + 1));
10891 } else if current_level == fold_at_level {
10892 fold_ranges.push(foldable_range);
10893 }
10894
10895 start_row = nested_end_row + 1;
10896 }
10897 None => start_row += 1,
10898 }
10899 }
10900 }
10901
10902 self.fold_ranges(fold_ranges, true, cx);
10903 }
10904
10905 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10906 let mut fold_ranges = Vec::new();
10907 let snapshot = self.buffer.read(cx).snapshot(cx);
10908
10909 for row in 0..snapshot.max_buffer_row().0 {
10910 if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10911 fold_ranges.push(foldable_range);
10912 }
10913 }
10914
10915 self.fold_ranges(fold_ranges, true, cx);
10916 }
10917
10918 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10919 let mut fold_ranges = Vec::new();
10920 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10921 let selections = self.selections.all_adjusted(cx);
10922
10923 for selection in selections {
10924 let range = selection.range().sorted();
10925 let buffer_start_row = range.start.row;
10926
10927 if range.start.row != range.end.row {
10928 let mut found = false;
10929 for row in range.start.row..=range.end.row {
10930 if let Some((foldable_range, fold_text)) =
10931 { display_map.foldable_range(MultiBufferRow(row)) }
10932 {
10933 found = true;
10934 fold_ranges.push((foldable_range, fold_text));
10935 }
10936 }
10937 if found {
10938 continue;
10939 }
10940 }
10941
10942 for row in (0..=range.start.row).rev() {
10943 if let Some((foldable_range, fold_text)) =
10944 display_map.foldable_range(MultiBufferRow(row))
10945 {
10946 if foldable_range.end.row >= buffer_start_row {
10947 fold_ranges.push((foldable_range, fold_text));
10948 } else {
10949 break;
10950 }
10951 }
10952 }
10953 }
10954
10955 self.fold_ranges(fold_ranges, true, cx);
10956 }
10957
10958 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10959 let buffer_row = fold_at.buffer_row;
10960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10961
10962 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10963 let autoscroll = self
10964 .selections
10965 .all::<Point>(cx)
10966 .iter()
10967 .any(|selection| fold_range.overlaps(&selection.range()));
10968
10969 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10970 }
10971 }
10972
10973 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10975 let buffer = &display_map.buffer_snapshot;
10976 let selections = self.selections.all::<Point>(cx);
10977 let ranges = selections
10978 .iter()
10979 .map(|s| {
10980 let range = s.display_range(&display_map).sorted();
10981 let mut start = range.start.to_point(&display_map);
10982 let mut end = range.end.to_point(&display_map);
10983 start.column = 0;
10984 end.column = buffer.line_len(MultiBufferRow(end.row));
10985 start..end
10986 })
10987 .collect::<Vec<_>>();
10988
10989 self.unfold_ranges(ranges, true, true, cx);
10990 }
10991
10992 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10993 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10994 let selections = self.selections.all::<Point>(cx);
10995 let ranges = selections
10996 .iter()
10997 .map(|s| {
10998 let mut range = s.display_range(&display_map).sorted();
10999 *range.start.column_mut() = 0;
11000 *range.end.column_mut() = display_map.line_len(range.end.row());
11001 let start = range.start.to_point(&display_map);
11002 let end = range.end.to_point(&display_map);
11003 start..end
11004 })
11005 .collect::<Vec<_>>();
11006
11007 self.unfold_ranges(ranges, true, true, cx);
11008 }
11009
11010 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11012
11013 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11014 ..Point::new(
11015 unfold_at.buffer_row.0,
11016 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11017 );
11018
11019 let autoscroll = self
11020 .selections
11021 .all::<Point>(cx)
11022 .iter()
11023 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11024
11025 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
11026 }
11027
11028 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11029 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11030 self.unfold_ranges(
11031 [Point::zero()..display_map.max_point().to_point(&display_map)],
11032 true,
11033 true,
11034 cx,
11035 );
11036 }
11037
11038 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11039 let selections = self.selections.all::<Point>(cx);
11040 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11041 let line_mode = self.selections.line_mode;
11042 let ranges = selections.into_iter().map(|s| {
11043 if line_mode {
11044 let start = Point::new(s.start.row, 0);
11045 let end = Point::new(
11046 s.end.row,
11047 display_map
11048 .buffer_snapshot
11049 .line_len(MultiBufferRow(s.end.row)),
11050 );
11051 (start..end, display_map.fold_placeholder.clone())
11052 } else {
11053 (s.start..s.end, display_map.fold_placeholder.clone())
11054 }
11055 });
11056 self.fold_ranges(ranges, true, cx);
11057 }
11058
11059 pub fn fold_ranges<T: ToOffset + Clone>(
11060 &mut self,
11061 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11062 auto_scroll: bool,
11063 cx: &mut ViewContext<Self>,
11064 ) {
11065 let mut fold_ranges = Vec::new();
11066 let mut buffers_affected = HashMap::default();
11067 let multi_buffer = self.buffer().read(cx);
11068 for (fold_range, fold_text) in ranges {
11069 if let Some((_, buffer, _)) =
11070 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11071 {
11072 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11073 };
11074 fold_ranges.push((fold_range, fold_text));
11075 }
11076
11077 let mut ranges = fold_ranges.into_iter().peekable();
11078 if ranges.peek().is_some() {
11079 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11080
11081 if auto_scroll {
11082 self.request_autoscroll(Autoscroll::fit(), cx);
11083 }
11084
11085 for buffer in buffers_affected.into_values() {
11086 self.sync_expanded_diff_hunks(buffer, cx);
11087 }
11088
11089 cx.notify();
11090
11091 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11092 // Clear diagnostics block when folding a range that contains it.
11093 let snapshot = self.snapshot(cx);
11094 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11095 drop(snapshot);
11096 self.active_diagnostics = Some(active_diagnostics);
11097 self.dismiss_diagnostics(cx);
11098 } else {
11099 self.active_diagnostics = Some(active_diagnostics);
11100 }
11101 }
11102
11103 self.scrollbar_marker_state.dirty = true;
11104 }
11105 }
11106
11107 pub fn unfold_ranges<T: ToOffset + Clone>(
11108 &mut self,
11109 ranges: impl IntoIterator<Item = Range<T>>,
11110 inclusive: bool,
11111 auto_scroll: bool,
11112 cx: &mut ViewContext<Self>,
11113 ) {
11114 let mut unfold_ranges = Vec::new();
11115 let mut buffers_affected = HashMap::default();
11116 let multi_buffer = self.buffer().read(cx);
11117 for range in ranges {
11118 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11119 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11120 };
11121 unfold_ranges.push(range);
11122 }
11123
11124 let mut ranges = unfold_ranges.into_iter().peekable();
11125 if ranges.peek().is_some() {
11126 self.display_map
11127 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11128 if auto_scroll {
11129 self.request_autoscroll(Autoscroll::fit(), cx);
11130 }
11131
11132 for buffer in buffers_affected.into_values() {
11133 self.sync_expanded_diff_hunks(buffer, cx);
11134 }
11135
11136 cx.notify();
11137 self.scrollbar_marker_state.dirty = true;
11138 self.active_indent_guides_state.dirty = true;
11139 }
11140 }
11141
11142 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11143 self.display_map.read(cx).fold_placeholder.clone()
11144 }
11145
11146 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11147 if hovered != self.gutter_hovered {
11148 self.gutter_hovered = hovered;
11149 cx.notify();
11150 }
11151 }
11152
11153 pub fn insert_blocks(
11154 &mut self,
11155 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11156 autoscroll: Option<Autoscroll>,
11157 cx: &mut ViewContext<Self>,
11158 ) -> Vec<CustomBlockId> {
11159 let blocks = self
11160 .display_map
11161 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11162 if let Some(autoscroll) = autoscroll {
11163 self.request_autoscroll(autoscroll, cx);
11164 }
11165 cx.notify();
11166 blocks
11167 }
11168
11169 pub fn resize_blocks(
11170 &mut self,
11171 heights: HashMap<CustomBlockId, u32>,
11172 autoscroll: Option<Autoscroll>,
11173 cx: &mut ViewContext<Self>,
11174 ) {
11175 self.display_map
11176 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11177 if let Some(autoscroll) = autoscroll {
11178 self.request_autoscroll(autoscroll, cx);
11179 }
11180 cx.notify();
11181 }
11182
11183 pub fn replace_blocks(
11184 &mut self,
11185 renderers: HashMap<CustomBlockId, RenderBlock>,
11186 autoscroll: Option<Autoscroll>,
11187 cx: &mut ViewContext<Self>,
11188 ) {
11189 self.display_map
11190 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11191 if let Some(autoscroll) = autoscroll {
11192 self.request_autoscroll(autoscroll, cx);
11193 }
11194 cx.notify();
11195 }
11196
11197 pub fn remove_blocks(
11198 &mut self,
11199 block_ids: HashSet<CustomBlockId>,
11200 autoscroll: Option<Autoscroll>,
11201 cx: &mut ViewContext<Self>,
11202 ) {
11203 self.display_map.update(cx, |display_map, cx| {
11204 display_map.remove_blocks(block_ids, cx)
11205 });
11206 if let Some(autoscroll) = autoscroll {
11207 self.request_autoscroll(autoscroll, cx);
11208 }
11209 cx.notify();
11210 }
11211
11212 pub fn row_for_block(
11213 &self,
11214 block_id: CustomBlockId,
11215 cx: &mut ViewContext<Self>,
11216 ) -> Option<DisplayRow> {
11217 self.display_map
11218 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11219 }
11220
11221 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11222 self.focused_block = Some(focused_block);
11223 }
11224
11225 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11226 self.focused_block.take()
11227 }
11228
11229 pub fn insert_creases(
11230 &mut self,
11231 creases: impl IntoIterator<Item = Crease>,
11232 cx: &mut ViewContext<Self>,
11233 ) -> Vec<CreaseId> {
11234 self.display_map
11235 .update(cx, |map, cx| map.insert_creases(creases, cx))
11236 }
11237
11238 pub fn remove_creases(
11239 &mut self,
11240 ids: impl IntoIterator<Item = CreaseId>,
11241 cx: &mut ViewContext<Self>,
11242 ) {
11243 self.display_map
11244 .update(cx, |map, cx| map.remove_creases(ids, cx));
11245 }
11246
11247 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11248 self.display_map
11249 .update(cx, |map, cx| map.snapshot(cx))
11250 .longest_row()
11251 }
11252
11253 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11254 self.display_map
11255 .update(cx, |map, cx| map.snapshot(cx))
11256 .max_point()
11257 }
11258
11259 pub fn text(&self, cx: &AppContext) -> String {
11260 self.buffer.read(cx).read(cx).text()
11261 }
11262
11263 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11264 let text = self.text(cx);
11265 let text = text.trim();
11266
11267 if text.is_empty() {
11268 return None;
11269 }
11270
11271 Some(text.to_string())
11272 }
11273
11274 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11275 self.transact(cx, |this, cx| {
11276 this.buffer
11277 .read(cx)
11278 .as_singleton()
11279 .expect("you can only call set_text on editors for singleton buffers")
11280 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11281 });
11282 }
11283
11284 pub fn display_text(&self, cx: &mut AppContext) -> String {
11285 self.display_map
11286 .update(cx, |map, cx| map.snapshot(cx))
11287 .text()
11288 }
11289
11290 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11291 let mut wrap_guides = smallvec::smallvec![];
11292
11293 if self.show_wrap_guides == Some(false) {
11294 return wrap_guides;
11295 }
11296
11297 let settings = self.buffer.read(cx).settings_at(0, cx);
11298 if settings.show_wrap_guides {
11299 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11300 wrap_guides.push((soft_wrap as usize, true));
11301 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11302 wrap_guides.push((soft_wrap as usize, true));
11303 }
11304 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11305 }
11306
11307 wrap_guides
11308 }
11309
11310 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11311 let settings = self.buffer.read(cx).settings_at(0, cx);
11312 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11313 match mode {
11314 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11315 SoftWrap::None
11316 }
11317 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11318 language_settings::SoftWrap::PreferredLineLength => {
11319 SoftWrap::Column(settings.preferred_line_length)
11320 }
11321 language_settings::SoftWrap::Bounded => {
11322 SoftWrap::Bounded(settings.preferred_line_length)
11323 }
11324 }
11325 }
11326
11327 pub fn set_soft_wrap_mode(
11328 &mut self,
11329 mode: language_settings::SoftWrap,
11330 cx: &mut ViewContext<Self>,
11331 ) {
11332 self.soft_wrap_mode_override = Some(mode);
11333 cx.notify();
11334 }
11335
11336 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11337 self.text_style_refinement = Some(style);
11338 }
11339
11340 /// called by the Element so we know what style we were most recently rendered with.
11341 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11342 let rem_size = cx.rem_size();
11343 self.display_map.update(cx, |map, cx| {
11344 map.set_font(
11345 style.text.font(),
11346 style.text.font_size.to_pixels(rem_size),
11347 cx,
11348 )
11349 });
11350 self.style = Some(style);
11351 }
11352
11353 pub fn style(&self) -> Option<&EditorStyle> {
11354 self.style.as_ref()
11355 }
11356
11357 // Called by the element. This method is not designed to be called outside of the editor
11358 // element's layout code because it does not notify when rewrapping is computed synchronously.
11359 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11360 self.display_map
11361 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11362 }
11363
11364 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11365 if self.soft_wrap_mode_override.is_some() {
11366 self.soft_wrap_mode_override.take();
11367 } else {
11368 let soft_wrap = match self.soft_wrap_mode(cx) {
11369 SoftWrap::GitDiff => return,
11370 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11371 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11372 language_settings::SoftWrap::None
11373 }
11374 };
11375 self.soft_wrap_mode_override = Some(soft_wrap);
11376 }
11377 cx.notify();
11378 }
11379
11380 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11381 let Some(workspace) = self.workspace() else {
11382 return;
11383 };
11384 let fs = workspace.read(cx).app_state().fs.clone();
11385 let current_show = TabBarSettings::get_global(cx).show;
11386 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11387 setting.show = Some(!current_show);
11388 });
11389 }
11390
11391 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11392 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11393 self.buffer
11394 .read(cx)
11395 .settings_at(0, cx)
11396 .indent_guides
11397 .enabled
11398 });
11399 self.show_indent_guides = Some(!currently_enabled);
11400 cx.notify();
11401 }
11402
11403 fn should_show_indent_guides(&self) -> Option<bool> {
11404 self.show_indent_guides
11405 }
11406
11407 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11408 let mut editor_settings = EditorSettings::get_global(cx).clone();
11409 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11410 EditorSettings::override_global(editor_settings, cx);
11411 }
11412
11413 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11414 self.use_relative_line_numbers
11415 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11416 }
11417
11418 pub fn toggle_relative_line_numbers(
11419 &mut self,
11420 _: &ToggleRelativeLineNumbers,
11421 cx: &mut ViewContext<Self>,
11422 ) {
11423 let is_relative = self.should_use_relative_line_numbers(cx);
11424 self.set_relative_line_number(Some(!is_relative), cx)
11425 }
11426
11427 pub fn set_relative_line_number(
11428 &mut self,
11429 is_relative: Option<bool>,
11430 cx: &mut ViewContext<Self>,
11431 ) {
11432 self.use_relative_line_numbers = is_relative;
11433 cx.notify();
11434 }
11435
11436 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11437 self.show_gutter = show_gutter;
11438 cx.notify();
11439 }
11440
11441 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11442 self.show_line_numbers = Some(show_line_numbers);
11443 cx.notify();
11444 }
11445
11446 pub fn set_show_git_diff_gutter(
11447 &mut self,
11448 show_git_diff_gutter: bool,
11449 cx: &mut ViewContext<Self>,
11450 ) {
11451 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11452 cx.notify();
11453 }
11454
11455 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11456 self.show_code_actions = Some(show_code_actions);
11457 cx.notify();
11458 }
11459
11460 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11461 self.show_runnables = Some(show_runnables);
11462 cx.notify();
11463 }
11464
11465 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11466 if self.display_map.read(cx).masked != masked {
11467 self.display_map.update(cx, |map, _| map.masked = masked);
11468 }
11469 cx.notify()
11470 }
11471
11472 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11473 self.show_wrap_guides = Some(show_wrap_guides);
11474 cx.notify();
11475 }
11476
11477 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11478 self.show_indent_guides = Some(show_indent_guides);
11479 cx.notify();
11480 }
11481
11482 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11483 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11484 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11485 if let Some(dir) = file.abs_path(cx).parent() {
11486 return Some(dir.to_owned());
11487 }
11488 }
11489
11490 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11491 return Some(project_path.path.to_path_buf());
11492 }
11493 }
11494
11495 None
11496 }
11497
11498 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11499 self.active_excerpt(cx)?
11500 .1
11501 .read(cx)
11502 .file()
11503 .and_then(|f| f.as_local())
11504 }
11505
11506 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11507 if let Some(target) = self.target_file(cx) {
11508 cx.reveal_path(&target.abs_path(cx));
11509 }
11510 }
11511
11512 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11513 if let Some(file) = self.target_file(cx) {
11514 if let Some(path) = file.abs_path(cx).to_str() {
11515 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11516 }
11517 }
11518 }
11519
11520 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11521 if let Some(file) = self.target_file(cx) {
11522 if let Some(path) = file.path().to_str() {
11523 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11524 }
11525 }
11526 }
11527
11528 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11529 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11530
11531 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11532 self.start_git_blame(true, cx);
11533 }
11534
11535 cx.notify();
11536 }
11537
11538 pub fn toggle_git_blame_inline(
11539 &mut self,
11540 _: &ToggleGitBlameInline,
11541 cx: &mut ViewContext<Self>,
11542 ) {
11543 self.toggle_git_blame_inline_internal(true, cx);
11544 cx.notify();
11545 }
11546
11547 pub fn git_blame_inline_enabled(&self) -> bool {
11548 self.git_blame_inline_enabled
11549 }
11550
11551 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11552 self.show_selection_menu = self
11553 .show_selection_menu
11554 .map(|show_selections_menu| !show_selections_menu)
11555 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11556
11557 cx.notify();
11558 }
11559
11560 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11561 self.show_selection_menu
11562 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11563 }
11564
11565 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11566 if let Some(project) = self.project.as_ref() {
11567 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11568 return;
11569 };
11570
11571 if buffer.read(cx).file().is_none() {
11572 return;
11573 }
11574
11575 let focused = self.focus_handle(cx).contains_focused(cx);
11576
11577 let project = project.clone();
11578 let blame =
11579 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11580 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11581 self.blame = Some(blame);
11582 }
11583 }
11584
11585 fn toggle_git_blame_inline_internal(
11586 &mut self,
11587 user_triggered: bool,
11588 cx: &mut ViewContext<Self>,
11589 ) {
11590 if self.git_blame_inline_enabled {
11591 self.git_blame_inline_enabled = false;
11592 self.show_git_blame_inline = false;
11593 self.show_git_blame_inline_delay_task.take();
11594 } else {
11595 self.git_blame_inline_enabled = true;
11596 self.start_git_blame_inline(user_triggered, cx);
11597 }
11598
11599 cx.notify();
11600 }
11601
11602 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11603 self.start_git_blame(user_triggered, cx);
11604
11605 if ProjectSettings::get_global(cx)
11606 .git
11607 .inline_blame_delay()
11608 .is_some()
11609 {
11610 self.start_inline_blame_timer(cx);
11611 } else {
11612 self.show_git_blame_inline = true
11613 }
11614 }
11615
11616 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11617 self.blame.as_ref()
11618 }
11619
11620 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11621 self.show_git_blame_gutter && self.has_blame_entries(cx)
11622 }
11623
11624 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11625 self.show_git_blame_inline
11626 && self.focus_handle.is_focused(cx)
11627 && !self.newest_selection_head_on_empty_line(cx)
11628 && self.has_blame_entries(cx)
11629 }
11630
11631 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11632 self.blame()
11633 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11634 }
11635
11636 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11637 let cursor_anchor = self.selections.newest_anchor().head();
11638
11639 let snapshot = self.buffer.read(cx).snapshot(cx);
11640 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11641
11642 snapshot.line_len(buffer_row) == 0
11643 }
11644
11645 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11646 let buffer_and_selection = maybe!({
11647 let selection = self.selections.newest::<Point>(cx);
11648 let selection_range = selection.range();
11649
11650 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11651 (buffer, selection_range.start.row..selection_range.end.row)
11652 } else {
11653 let buffer_ranges = self
11654 .buffer()
11655 .read(cx)
11656 .range_to_buffer_ranges(selection_range, cx);
11657
11658 let (buffer, range, _) = if selection.reversed {
11659 buffer_ranges.first()
11660 } else {
11661 buffer_ranges.last()
11662 }?;
11663
11664 let snapshot = buffer.read(cx).snapshot();
11665 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11666 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11667 (buffer.clone(), selection)
11668 };
11669
11670 Some((buffer, selection))
11671 });
11672
11673 let Some((buffer, selection)) = buffer_and_selection else {
11674 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11675 };
11676
11677 let Some(project) = self.project.as_ref() else {
11678 return Task::ready(Err(anyhow!("editor does not have project")));
11679 };
11680
11681 project.update(cx, |project, cx| {
11682 project.get_permalink_to_line(&buffer, selection, cx)
11683 })
11684 }
11685
11686 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11687 let permalink_task = self.get_permalink_to_line(cx);
11688 let workspace = self.workspace();
11689
11690 cx.spawn(|_, mut cx| async move {
11691 match permalink_task.await {
11692 Ok(permalink) => {
11693 cx.update(|cx| {
11694 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11695 })
11696 .ok();
11697 }
11698 Err(err) => {
11699 let message = format!("Failed to copy permalink: {err}");
11700
11701 Err::<(), anyhow::Error>(err).log_err();
11702
11703 if let Some(workspace) = workspace {
11704 workspace
11705 .update(&mut cx, |workspace, cx| {
11706 struct CopyPermalinkToLine;
11707
11708 workspace.show_toast(
11709 Toast::new(
11710 NotificationId::unique::<CopyPermalinkToLine>(),
11711 message,
11712 ),
11713 cx,
11714 )
11715 })
11716 .ok();
11717 }
11718 }
11719 }
11720 })
11721 .detach();
11722 }
11723
11724 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11725 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11726 if let Some(file) = self.target_file(cx) {
11727 if let Some(path) = file.path().to_str() {
11728 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11729 }
11730 }
11731 }
11732
11733 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11734 let permalink_task = self.get_permalink_to_line(cx);
11735 let workspace = self.workspace();
11736
11737 cx.spawn(|_, mut cx| async move {
11738 match permalink_task.await {
11739 Ok(permalink) => {
11740 cx.update(|cx| {
11741 cx.open_url(permalink.as_ref());
11742 })
11743 .ok();
11744 }
11745 Err(err) => {
11746 let message = format!("Failed to open permalink: {err}");
11747
11748 Err::<(), anyhow::Error>(err).log_err();
11749
11750 if let Some(workspace) = workspace {
11751 workspace
11752 .update(&mut cx, |workspace, cx| {
11753 struct OpenPermalinkToLine;
11754
11755 workspace.show_toast(
11756 Toast::new(
11757 NotificationId::unique::<OpenPermalinkToLine>(),
11758 message,
11759 ),
11760 cx,
11761 )
11762 })
11763 .ok();
11764 }
11765 }
11766 }
11767 })
11768 .detach();
11769 }
11770
11771 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11772 /// last highlight added will be used.
11773 ///
11774 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11775 pub fn highlight_rows<T: 'static>(
11776 &mut self,
11777 range: Range<Anchor>,
11778 color: Hsla,
11779 should_autoscroll: bool,
11780 cx: &mut ViewContext<Self>,
11781 ) {
11782 let snapshot = self.buffer().read(cx).snapshot(cx);
11783 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11784 let ix = row_highlights.binary_search_by(|highlight| {
11785 Ordering::Equal
11786 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11787 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11788 });
11789
11790 if let Err(mut ix) = ix {
11791 let index = post_inc(&mut self.highlight_order);
11792
11793 // If this range intersects with the preceding highlight, then merge it with
11794 // the preceding highlight. Otherwise insert a new highlight.
11795 let mut merged = false;
11796 if ix > 0 {
11797 let prev_highlight = &mut row_highlights[ix - 1];
11798 if prev_highlight
11799 .range
11800 .end
11801 .cmp(&range.start, &snapshot)
11802 .is_ge()
11803 {
11804 ix -= 1;
11805 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11806 prev_highlight.range.end = range.end;
11807 }
11808 merged = true;
11809 prev_highlight.index = index;
11810 prev_highlight.color = color;
11811 prev_highlight.should_autoscroll = should_autoscroll;
11812 }
11813 }
11814
11815 if !merged {
11816 row_highlights.insert(
11817 ix,
11818 RowHighlight {
11819 range: range.clone(),
11820 index,
11821 color,
11822 should_autoscroll,
11823 },
11824 );
11825 }
11826
11827 // If any of the following highlights intersect with this one, merge them.
11828 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11829 let highlight = &row_highlights[ix];
11830 if next_highlight
11831 .range
11832 .start
11833 .cmp(&highlight.range.end, &snapshot)
11834 .is_le()
11835 {
11836 if next_highlight
11837 .range
11838 .end
11839 .cmp(&highlight.range.end, &snapshot)
11840 .is_gt()
11841 {
11842 row_highlights[ix].range.end = next_highlight.range.end;
11843 }
11844 row_highlights.remove(ix + 1);
11845 } else {
11846 break;
11847 }
11848 }
11849 }
11850 }
11851
11852 /// Remove any highlighted row ranges of the given type that intersect the
11853 /// given ranges.
11854 pub fn remove_highlighted_rows<T: 'static>(
11855 &mut self,
11856 ranges_to_remove: Vec<Range<Anchor>>,
11857 cx: &mut ViewContext<Self>,
11858 ) {
11859 let snapshot = self.buffer().read(cx).snapshot(cx);
11860 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11861 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11862 row_highlights.retain(|highlight| {
11863 while let Some(range_to_remove) = ranges_to_remove.peek() {
11864 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11865 Ordering::Less | Ordering::Equal => {
11866 ranges_to_remove.next();
11867 }
11868 Ordering::Greater => {
11869 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11870 Ordering::Less | Ordering::Equal => {
11871 return false;
11872 }
11873 Ordering::Greater => break,
11874 }
11875 }
11876 }
11877 }
11878
11879 true
11880 })
11881 }
11882
11883 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11884 pub fn clear_row_highlights<T: 'static>(&mut self) {
11885 self.highlighted_rows.remove(&TypeId::of::<T>());
11886 }
11887
11888 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11889 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11890 self.highlighted_rows
11891 .get(&TypeId::of::<T>())
11892 .map_or(&[] as &[_], |vec| vec.as_slice())
11893 .iter()
11894 .map(|highlight| (highlight.range.clone(), highlight.color))
11895 }
11896
11897 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11898 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11899 /// Allows to ignore certain kinds of highlights.
11900 pub fn highlighted_display_rows(
11901 &mut self,
11902 cx: &mut WindowContext,
11903 ) -> BTreeMap<DisplayRow, Hsla> {
11904 let snapshot = self.snapshot(cx);
11905 let mut used_highlight_orders = HashMap::default();
11906 self.highlighted_rows
11907 .iter()
11908 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11909 .fold(
11910 BTreeMap::<DisplayRow, Hsla>::new(),
11911 |mut unique_rows, highlight| {
11912 let start = highlight.range.start.to_display_point(&snapshot);
11913 let end = highlight.range.end.to_display_point(&snapshot);
11914 let start_row = start.row().0;
11915 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11916 && end.column() == 0
11917 {
11918 end.row().0.saturating_sub(1)
11919 } else {
11920 end.row().0
11921 };
11922 for row in start_row..=end_row {
11923 let used_index =
11924 used_highlight_orders.entry(row).or_insert(highlight.index);
11925 if highlight.index >= *used_index {
11926 *used_index = highlight.index;
11927 unique_rows.insert(DisplayRow(row), highlight.color);
11928 }
11929 }
11930 unique_rows
11931 },
11932 )
11933 }
11934
11935 pub fn highlighted_display_row_for_autoscroll(
11936 &self,
11937 snapshot: &DisplaySnapshot,
11938 ) -> Option<DisplayRow> {
11939 self.highlighted_rows
11940 .values()
11941 .flat_map(|highlighted_rows| highlighted_rows.iter())
11942 .filter_map(|highlight| {
11943 if highlight.should_autoscroll {
11944 Some(highlight.range.start.to_display_point(snapshot).row())
11945 } else {
11946 None
11947 }
11948 })
11949 .min()
11950 }
11951
11952 pub fn set_search_within_ranges(
11953 &mut self,
11954 ranges: &[Range<Anchor>],
11955 cx: &mut ViewContext<Self>,
11956 ) {
11957 self.highlight_background::<SearchWithinRange>(
11958 ranges,
11959 |colors| colors.editor_document_highlight_read_background,
11960 cx,
11961 )
11962 }
11963
11964 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11965 self.breadcrumb_header = Some(new_header);
11966 }
11967
11968 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11969 self.clear_background_highlights::<SearchWithinRange>(cx);
11970 }
11971
11972 pub fn highlight_background<T: 'static>(
11973 &mut self,
11974 ranges: &[Range<Anchor>],
11975 color_fetcher: fn(&ThemeColors) -> Hsla,
11976 cx: &mut ViewContext<Self>,
11977 ) {
11978 self.background_highlights
11979 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11980 self.scrollbar_marker_state.dirty = true;
11981 cx.notify();
11982 }
11983
11984 pub fn clear_background_highlights<T: 'static>(
11985 &mut self,
11986 cx: &mut ViewContext<Self>,
11987 ) -> Option<BackgroundHighlight> {
11988 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11989 if !text_highlights.1.is_empty() {
11990 self.scrollbar_marker_state.dirty = true;
11991 cx.notify();
11992 }
11993 Some(text_highlights)
11994 }
11995
11996 pub fn highlight_gutter<T: 'static>(
11997 &mut self,
11998 ranges: &[Range<Anchor>],
11999 color_fetcher: fn(&AppContext) -> Hsla,
12000 cx: &mut ViewContext<Self>,
12001 ) {
12002 self.gutter_highlights
12003 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12004 cx.notify();
12005 }
12006
12007 pub fn clear_gutter_highlights<T: 'static>(
12008 &mut self,
12009 cx: &mut ViewContext<Self>,
12010 ) -> Option<GutterHighlight> {
12011 cx.notify();
12012 self.gutter_highlights.remove(&TypeId::of::<T>())
12013 }
12014
12015 #[cfg(feature = "test-support")]
12016 pub fn all_text_background_highlights(
12017 &mut self,
12018 cx: &mut ViewContext<Self>,
12019 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12020 let snapshot = self.snapshot(cx);
12021 let buffer = &snapshot.buffer_snapshot;
12022 let start = buffer.anchor_before(0);
12023 let end = buffer.anchor_after(buffer.len());
12024 let theme = cx.theme().colors();
12025 self.background_highlights_in_range(start..end, &snapshot, theme)
12026 }
12027
12028 #[cfg(feature = "test-support")]
12029 pub fn search_background_highlights(
12030 &mut self,
12031 cx: &mut ViewContext<Self>,
12032 ) -> Vec<Range<Point>> {
12033 let snapshot = self.buffer().read(cx).snapshot(cx);
12034
12035 let highlights = self
12036 .background_highlights
12037 .get(&TypeId::of::<items::BufferSearchHighlights>());
12038
12039 if let Some((_color, ranges)) = highlights {
12040 ranges
12041 .iter()
12042 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12043 .collect_vec()
12044 } else {
12045 vec![]
12046 }
12047 }
12048
12049 fn document_highlights_for_position<'a>(
12050 &'a self,
12051 position: Anchor,
12052 buffer: &'a MultiBufferSnapshot,
12053 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12054 let read_highlights = self
12055 .background_highlights
12056 .get(&TypeId::of::<DocumentHighlightRead>())
12057 .map(|h| &h.1);
12058 let write_highlights = self
12059 .background_highlights
12060 .get(&TypeId::of::<DocumentHighlightWrite>())
12061 .map(|h| &h.1);
12062 let left_position = position.bias_left(buffer);
12063 let right_position = position.bias_right(buffer);
12064 read_highlights
12065 .into_iter()
12066 .chain(write_highlights)
12067 .flat_map(move |ranges| {
12068 let start_ix = match ranges.binary_search_by(|probe| {
12069 let cmp = probe.end.cmp(&left_position, buffer);
12070 if cmp.is_ge() {
12071 Ordering::Greater
12072 } else {
12073 Ordering::Less
12074 }
12075 }) {
12076 Ok(i) | Err(i) => i,
12077 };
12078
12079 ranges[start_ix..]
12080 .iter()
12081 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12082 })
12083 }
12084
12085 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12086 self.background_highlights
12087 .get(&TypeId::of::<T>())
12088 .map_or(false, |(_, highlights)| !highlights.is_empty())
12089 }
12090
12091 pub fn background_highlights_in_range(
12092 &self,
12093 search_range: Range<Anchor>,
12094 display_snapshot: &DisplaySnapshot,
12095 theme: &ThemeColors,
12096 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12097 let mut results = Vec::new();
12098 for (color_fetcher, ranges) in self.background_highlights.values() {
12099 let color = color_fetcher(theme);
12100 let start_ix = match ranges.binary_search_by(|probe| {
12101 let cmp = probe
12102 .end
12103 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12104 if cmp.is_gt() {
12105 Ordering::Greater
12106 } else {
12107 Ordering::Less
12108 }
12109 }) {
12110 Ok(i) | Err(i) => i,
12111 };
12112 for range in &ranges[start_ix..] {
12113 if range
12114 .start
12115 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12116 .is_ge()
12117 {
12118 break;
12119 }
12120
12121 let start = range.start.to_display_point(display_snapshot);
12122 let end = range.end.to_display_point(display_snapshot);
12123 results.push((start..end, color))
12124 }
12125 }
12126 results
12127 }
12128
12129 pub fn background_highlight_row_ranges<T: 'static>(
12130 &self,
12131 search_range: Range<Anchor>,
12132 display_snapshot: &DisplaySnapshot,
12133 count: usize,
12134 ) -> Vec<RangeInclusive<DisplayPoint>> {
12135 let mut results = Vec::new();
12136 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12137 return vec![];
12138 };
12139
12140 let start_ix = match ranges.binary_search_by(|probe| {
12141 let cmp = probe
12142 .end
12143 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12144 if cmp.is_gt() {
12145 Ordering::Greater
12146 } else {
12147 Ordering::Less
12148 }
12149 }) {
12150 Ok(i) | Err(i) => i,
12151 };
12152 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12153 if let (Some(start_display), Some(end_display)) = (start, end) {
12154 results.push(
12155 start_display.to_display_point(display_snapshot)
12156 ..=end_display.to_display_point(display_snapshot),
12157 );
12158 }
12159 };
12160 let mut start_row: Option<Point> = None;
12161 let mut end_row: Option<Point> = None;
12162 if ranges.len() > count {
12163 return Vec::new();
12164 }
12165 for range in &ranges[start_ix..] {
12166 if range
12167 .start
12168 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12169 .is_ge()
12170 {
12171 break;
12172 }
12173 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12174 if let Some(current_row) = &end_row {
12175 if end.row == current_row.row {
12176 continue;
12177 }
12178 }
12179 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12180 if start_row.is_none() {
12181 assert_eq!(end_row, None);
12182 start_row = Some(start);
12183 end_row = Some(end);
12184 continue;
12185 }
12186 if let Some(current_end) = end_row.as_mut() {
12187 if start.row > current_end.row + 1 {
12188 push_region(start_row, end_row);
12189 start_row = Some(start);
12190 end_row = Some(end);
12191 } else {
12192 // Merge two hunks.
12193 *current_end = end;
12194 }
12195 } else {
12196 unreachable!();
12197 }
12198 }
12199 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12200 push_region(start_row, end_row);
12201 results
12202 }
12203
12204 pub fn gutter_highlights_in_range(
12205 &self,
12206 search_range: Range<Anchor>,
12207 display_snapshot: &DisplaySnapshot,
12208 cx: &AppContext,
12209 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12210 let mut results = Vec::new();
12211 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12212 let color = color_fetcher(cx);
12213 let start_ix = match ranges.binary_search_by(|probe| {
12214 let cmp = probe
12215 .end
12216 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12217 if cmp.is_gt() {
12218 Ordering::Greater
12219 } else {
12220 Ordering::Less
12221 }
12222 }) {
12223 Ok(i) | Err(i) => i,
12224 };
12225 for range in &ranges[start_ix..] {
12226 if range
12227 .start
12228 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12229 .is_ge()
12230 {
12231 break;
12232 }
12233
12234 let start = range.start.to_display_point(display_snapshot);
12235 let end = range.end.to_display_point(display_snapshot);
12236 results.push((start..end, color))
12237 }
12238 }
12239 results
12240 }
12241
12242 /// Get the text ranges corresponding to the redaction query
12243 pub fn redacted_ranges(
12244 &self,
12245 search_range: Range<Anchor>,
12246 display_snapshot: &DisplaySnapshot,
12247 cx: &WindowContext,
12248 ) -> Vec<Range<DisplayPoint>> {
12249 display_snapshot
12250 .buffer_snapshot
12251 .redacted_ranges(search_range, |file| {
12252 if let Some(file) = file {
12253 file.is_private()
12254 && EditorSettings::get(
12255 Some(SettingsLocation {
12256 worktree_id: file.worktree_id(cx),
12257 path: file.path().as_ref(),
12258 }),
12259 cx,
12260 )
12261 .redact_private_values
12262 } else {
12263 false
12264 }
12265 })
12266 .map(|range| {
12267 range.start.to_display_point(display_snapshot)
12268 ..range.end.to_display_point(display_snapshot)
12269 })
12270 .collect()
12271 }
12272
12273 pub fn highlight_text<T: 'static>(
12274 &mut self,
12275 ranges: Vec<Range<Anchor>>,
12276 style: HighlightStyle,
12277 cx: &mut ViewContext<Self>,
12278 ) {
12279 self.display_map.update(cx, |map, _| {
12280 map.highlight_text(TypeId::of::<T>(), ranges, style)
12281 });
12282 cx.notify();
12283 }
12284
12285 pub(crate) fn highlight_inlays<T: 'static>(
12286 &mut self,
12287 highlights: Vec<InlayHighlight>,
12288 style: HighlightStyle,
12289 cx: &mut ViewContext<Self>,
12290 ) {
12291 self.display_map.update(cx, |map, _| {
12292 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12293 });
12294 cx.notify();
12295 }
12296
12297 pub fn text_highlights<'a, T: 'static>(
12298 &'a self,
12299 cx: &'a AppContext,
12300 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12301 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12302 }
12303
12304 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12305 let cleared = self
12306 .display_map
12307 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12308 if cleared {
12309 cx.notify();
12310 }
12311 }
12312
12313 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12314 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12315 && self.focus_handle.is_focused(cx)
12316 }
12317
12318 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12319 self.show_cursor_when_unfocused = is_enabled;
12320 cx.notify();
12321 }
12322
12323 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12324 cx.notify();
12325 }
12326
12327 fn on_buffer_event(
12328 &mut self,
12329 multibuffer: Model<MultiBuffer>,
12330 event: &multi_buffer::Event,
12331 cx: &mut ViewContext<Self>,
12332 ) {
12333 match event {
12334 multi_buffer::Event::Edited {
12335 singleton_buffer_edited,
12336 } => {
12337 self.scrollbar_marker_state.dirty = true;
12338 self.active_indent_guides_state.dirty = true;
12339 self.refresh_active_diagnostics(cx);
12340 self.refresh_code_actions(cx);
12341 if self.has_active_inline_completion(cx) {
12342 self.update_visible_inline_completion(cx);
12343 }
12344 cx.emit(EditorEvent::BufferEdited);
12345 cx.emit(SearchEvent::MatchesInvalidated);
12346 if *singleton_buffer_edited {
12347 if let Some(project) = &self.project {
12348 let project = project.read(cx);
12349 #[allow(clippy::mutable_key_type)]
12350 let languages_affected = multibuffer
12351 .read(cx)
12352 .all_buffers()
12353 .into_iter()
12354 .filter_map(|buffer| {
12355 let buffer = buffer.read(cx);
12356 let language = buffer.language()?;
12357 if project.is_local()
12358 && project.language_servers_for_buffer(buffer, cx).count() == 0
12359 {
12360 None
12361 } else {
12362 Some(language)
12363 }
12364 })
12365 .cloned()
12366 .collect::<HashSet<_>>();
12367 if !languages_affected.is_empty() {
12368 self.refresh_inlay_hints(
12369 InlayHintRefreshReason::BufferEdited(languages_affected),
12370 cx,
12371 );
12372 }
12373 }
12374 }
12375
12376 let Some(project) = &self.project else { return };
12377 let (telemetry, is_via_ssh) = {
12378 let project = project.read(cx);
12379 let telemetry = project.client().telemetry().clone();
12380 let is_via_ssh = project.is_via_ssh();
12381 (telemetry, is_via_ssh)
12382 };
12383 refresh_linked_ranges(self, cx);
12384 telemetry.log_edit_event("editor", is_via_ssh);
12385 }
12386 multi_buffer::Event::ExcerptsAdded {
12387 buffer,
12388 predecessor,
12389 excerpts,
12390 } => {
12391 self.tasks_update_task = Some(self.refresh_runnables(cx));
12392 cx.emit(EditorEvent::ExcerptsAdded {
12393 buffer: buffer.clone(),
12394 predecessor: *predecessor,
12395 excerpts: excerpts.clone(),
12396 });
12397 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12398 }
12399 multi_buffer::Event::ExcerptsRemoved { ids } => {
12400 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12401 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12402 }
12403 multi_buffer::Event::ExcerptsEdited { ids } => {
12404 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12405 }
12406 multi_buffer::Event::ExcerptsExpanded { ids } => {
12407 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12408 }
12409 multi_buffer::Event::Reparsed(buffer_id) => {
12410 self.tasks_update_task = Some(self.refresh_runnables(cx));
12411
12412 cx.emit(EditorEvent::Reparsed(*buffer_id));
12413 }
12414 multi_buffer::Event::LanguageChanged(buffer_id) => {
12415 linked_editing_ranges::refresh_linked_ranges(self, cx);
12416 cx.emit(EditorEvent::Reparsed(*buffer_id));
12417 cx.notify();
12418 }
12419 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12420 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12421 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12422 cx.emit(EditorEvent::TitleChanged)
12423 }
12424 multi_buffer::Event::DiffBaseChanged => {
12425 self.scrollbar_marker_state.dirty = true;
12426 cx.emit(EditorEvent::DiffBaseChanged);
12427 cx.notify();
12428 }
12429 multi_buffer::Event::DiffUpdated { buffer } => {
12430 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12431 cx.notify();
12432 }
12433 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12434 multi_buffer::Event::DiagnosticsUpdated => {
12435 self.refresh_active_diagnostics(cx);
12436 self.scrollbar_marker_state.dirty = true;
12437 cx.notify();
12438 }
12439 _ => {}
12440 };
12441 }
12442
12443 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12444 cx.notify();
12445 }
12446
12447 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12448 self.tasks_update_task = Some(self.refresh_runnables(cx));
12449 self.refresh_inline_completion(true, false, cx);
12450 self.refresh_inlay_hints(
12451 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12452 self.selections.newest_anchor().head(),
12453 &self.buffer.read(cx).snapshot(cx),
12454 cx,
12455 )),
12456 cx,
12457 );
12458
12459 let old_cursor_shape = self.cursor_shape;
12460
12461 {
12462 let editor_settings = EditorSettings::get_global(cx);
12463 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12464 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12465 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12466 }
12467
12468 if old_cursor_shape != self.cursor_shape {
12469 cx.emit(EditorEvent::CursorShapeChanged);
12470 }
12471
12472 let project_settings = ProjectSettings::get_global(cx);
12473 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12474
12475 if self.mode == EditorMode::Full {
12476 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12477 if self.git_blame_inline_enabled != inline_blame_enabled {
12478 self.toggle_git_blame_inline_internal(false, cx);
12479 }
12480 }
12481
12482 cx.notify();
12483 }
12484
12485 pub fn set_searchable(&mut self, searchable: bool) {
12486 self.searchable = searchable;
12487 }
12488
12489 pub fn searchable(&self) -> bool {
12490 self.searchable
12491 }
12492
12493 fn open_proposed_changes_editor(
12494 &mut self,
12495 _: &OpenProposedChangesEditor,
12496 cx: &mut ViewContext<Self>,
12497 ) {
12498 let Some(workspace) = self.workspace() else {
12499 cx.propagate();
12500 return;
12501 };
12502
12503 let selections = self.selections.all::<usize>(cx);
12504 let buffer = self.buffer.read(cx);
12505 let mut new_selections_by_buffer = HashMap::default();
12506 for selection in selections {
12507 for (buffer, range, _) in
12508 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12509 {
12510 let mut range = range.to_point(buffer.read(cx));
12511 range.start.column = 0;
12512 range.end.column = buffer.read(cx).line_len(range.end.row);
12513 new_selections_by_buffer
12514 .entry(buffer)
12515 .or_insert(Vec::new())
12516 .push(range)
12517 }
12518 }
12519
12520 let proposed_changes_buffers = new_selections_by_buffer
12521 .into_iter()
12522 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12523 .collect::<Vec<_>>();
12524 let proposed_changes_editor = cx.new_view(|cx| {
12525 ProposedChangesEditor::new(
12526 "Proposed changes",
12527 proposed_changes_buffers,
12528 self.project.clone(),
12529 cx,
12530 )
12531 });
12532
12533 cx.window_context().defer(move |cx| {
12534 workspace.update(cx, |workspace, cx| {
12535 workspace.active_pane().update(cx, |pane, cx| {
12536 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12537 });
12538 });
12539 });
12540 }
12541
12542 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12543 self.open_excerpts_common(true, cx)
12544 }
12545
12546 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12547 self.open_excerpts_common(false, cx)
12548 }
12549
12550 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12551 let selections = self.selections.all::<usize>(cx);
12552 let buffer = self.buffer.read(cx);
12553 if buffer.is_singleton() {
12554 cx.propagate();
12555 return;
12556 }
12557
12558 let Some(workspace) = self.workspace() else {
12559 cx.propagate();
12560 return;
12561 };
12562
12563 let mut new_selections_by_buffer = HashMap::default();
12564 for selection in selections {
12565 for (mut buffer_handle, mut range, _) in
12566 buffer.range_to_buffer_ranges(selection.range(), cx)
12567 {
12568 // When editing branch buffers, jump to the corresponding location
12569 // in their base buffer.
12570 let buffer = buffer_handle.read(cx);
12571 if let Some(base_buffer) = buffer.diff_base_buffer() {
12572 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12573 buffer_handle = base_buffer;
12574 }
12575
12576 if selection.reversed {
12577 mem::swap(&mut range.start, &mut range.end);
12578 }
12579 new_selections_by_buffer
12580 .entry(buffer_handle)
12581 .or_insert(Vec::new())
12582 .push(range)
12583 }
12584 }
12585
12586 // We defer the pane interaction because we ourselves are a workspace item
12587 // and activating a new item causes the pane to call a method on us reentrantly,
12588 // which panics if we're on the stack.
12589 cx.window_context().defer(move |cx| {
12590 workspace.update(cx, |workspace, cx| {
12591 let pane = if split {
12592 workspace.adjacent_pane(cx)
12593 } else {
12594 workspace.active_pane().clone()
12595 };
12596
12597 for (buffer, ranges) in new_selections_by_buffer {
12598 let editor =
12599 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12600 editor.update(cx, |editor, cx| {
12601 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12602 s.select_ranges(ranges);
12603 });
12604 });
12605 }
12606 })
12607 });
12608 }
12609
12610 fn jump(
12611 &mut self,
12612 path: ProjectPath,
12613 position: Point,
12614 anchor: language::Anchor,
12615 offset_from_top: u32,
12616 cx: &mut ViewContext<Self>,
12617 ) {
12618 let workspace = self.workspace();
12619 cx.spawn(|_, mut cx| async move {
12620 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12621 let editor = workspace.update(&mut cx, |workspace, cx| {
12622 // Reset the preview item id before opening the new item
12623 workspace.active_pane().update(cx, |pane, cx| {
12624 pane.set_preview_item_id(None, cx);
12625 });
12626 workspace.open_path_preview(path, None, true, true, cx)
12627 })?;
12628 let editor = editor
12629 .await?
12630 .downcast::<Editor>()
12631 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12632 .downgrade();
12633 editor.update(&mut cx, |editor, cx| {
12634 let buffer = editor
12635 .buffer()
12636 .read(cx)
12637 .as_singleton()
12638 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12639 let buffer = buffer.read(cx);
12640 let cursor = if buffer.can_resolve(&anchor) {
12641 language::ToPoint::to_point(&anchor, buffer)
12642 } else {
12643 buffer.clip_point(position, Bias::Left)
12644 };
12645
12646 let nav_history = editor.nav_history.take();
12647 editor.change_selections(
12648 Some(Autoscroll::top_relative(offset_from_top as usize)),
12649 cx,
12650 |s| {
12651 s.select_ranges([cursor..cursor]);
12652 },
12653 );
12654 editor.nav_history = nav_history;
12655
12656 anyhow::Ok(())
12657 })??;
12658
12659 anyhow::Ok(())
12660 })
12661 .detach_and_log_err(cx);
12662 }
12663
12664 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12665 let snapshot = self.buffer.read(cx).read(cx);
12666 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12667 Some(
12668 ranges
12669 .iter()
12670 .map(move |range| {
12671 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12672 })
12673 .collect(),
12674 )
12675 }
12676
12677 fn selection_replacement_ranges(
12678 &self,
12679 range: Range<OffsetUtf16>,
12680 cx: &mut AppContext,
12681 ) -> Vec<Range<OffsetUtf16>> {
12682 let selections = self.selections.all::<OffsetUtf16>(cx);
12683 let newest_selection = selections
12684 .iter()
12685 .max_by_key(|selection| selection.id)
12686 .unwrap();
12687 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12688 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12689 let snapshot = self.buffer.read(cx).read(cx);
12690 selections
12691 .into_iter()
12692 .map(|mut selection| {
12693 selection.start.0 =
12694 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12695 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12696 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12697 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12698 })
12699 .collect()
12700 }
12701
12702 fn report_editor_event(
12703 &self,
12704 operation: &'static str,
12705 file_extension: Option<String>,
12706 cx: &AppContext,
12707 ) {
12708 if cfg!(any(test, feature = "test-support")) {
12709 return;
12710 }
12711
12712 let Some(project) = &self.project else { return };
12713
12714 // If None, we are in a file without an extension
12715 let file = self
12716 .buffer
12717 .read(cx)
12718 .as_singleton()
12719 .and_then(|b| b.read(cx).file());
12720 let file_extension = file_extension.or(file
12721 .as_ref()
12722 .and_then(|file| Path::new(file.file_name(cx)).extension())
12723 .and_then(|e| e.to_str())
12724 .map(|a| a.to_string()));
12725
12726 let vim_mode = cx
12727 .global::<SettingsStore>()
12728 .raw_user_settings()
12729 .get("vim_mode")
12730 == Some(&serde_json::Value::Bool(true));
12731
12732 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12733 == language::language_settings::InlineCompletionProvider::Copilot;
12734 let copilot_enabled_for_language = self
12735 .buffer
12736 .read(cx)
12737 .settings_at(0, cx)
12738 .show_inline_completions;
12739
12740 let project = project.read(cx);
12741 let telemetry = project.client().telemetry().clone();
12742 telemetry.report_editor_event(
12743 file_extension,
12744 vim_mode,
12745 operation,
12746 copilot_enabled,
12747 copilot_enabled_for_language,
12748 project.is_via_ssh(),
12749 )
12750 }
12751
12752 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12753 /// with each line being an array of {text, highlight} objects.
12754 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12755 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12756 return;
12757 };
12758
12759 #[derive(Serialize)]
12760 struct Chunk<'a> {
12761 text: String,
12762 highlight: Option<&'a str>,
12763 }
12764
12765 let snapshot = buffer.read(cx).snapshot();
12766 let range = self
12767 .selected_text_range(false, cx)
12768 .and_then(|selection| {
12769 if selection.range.is_empty() {
12770 None
12771 } else {
12772 Some(selection.range)
12773 }
12774 })
12775 .unwrap_or_else(|| 0..snapshot.len());
12776
12777 let chunks = snapshot.chunks(range, true);
12778 let mut lines = Vec::new();
12779 let mut line: VecDeque<Chunk> = VecDeque::new();
12780
12781 let Some(style) = self.style.as_ref() else {
12782 return;
12783 };
12784
12785 for chunk in chunks {
12786 let highlight = chunk
12787 .syntax_highlight_id
12788 .and_then(|id| id.name(&style.syntax));
12789 let mut chunk_lines = chunk.text.split('\n').peekable();
12790 while let Some(text) = chunk_lines.next() {
12791 let mut merged_with_last_token = false;
12792 if let Some(last_token) = line.back_mut() {
12793 if last_token.highlight == highlight {
12794 last_token.text.push_str(text);
12795 merged_with_last_token = true;
12796 }
12797 }
12798
12799 if !merged_with_last_token {
12800 line.push_back(Chunk {
12801 text: text.into(),
12802 highlight,
12803 });
12804 }
12805
12806 if chunk_lines.peek().is_some() {
12807 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12808 line.pop_front();
12809 }
12810 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12811 line.pop_back();
12812 }
12813
12814 lines.push(mem::take(&mut line));
12815 }
12816 }
12817 }
12818
12819 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12820 return;
12821 };
12822 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12823 }
12824
12825 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12826 &self.inlay_hint_cache
12827 }
12828
12829 pub fn replay_insert_event(
12830 &mut self,
12831 text: &str,
12832 relative_utf16_range: Option<Range<isize>>,
12833 cx: &mut ViewContext<Self>,
12834 ) {
12835 if !self.input_enabled {
12836 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12837 return;
12838 }
12839 if let Some(relative_utf16_range) = relative_utf16_range {
12840 let selections = self.selections.all::<OffsetUtf16>(cx);
12841 self.change_selections(None, cx, |s| {
12842 let new_ranges = selections.into_iter().map(|range| {
12843 let start = OffsetUtf16(
12844 range
12845 .head()
12846 .0
12847 .saturating_add_signed(relative_utf16_range.start),
12848 );
12849 let end = OffsetUtf16(
12850 range
12851 .head()
12852 .0
12853 .saturating_add_signed(relative_utf16_range.end),
12854 );
12855 start..end
12856 });
12857 s.select_ranges(new_ranges);
12858 });
12859 }
12860
12861 self.handle_input(text, cx);
12862 }
12863
12864 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12865 let Some(provider) = self.semantics_provider.as_ref() else {
12866 return false;
12867 };
12868
12869 let mut supports = false;
12870 self.buffer().read(cx).for_each_buffer(|buffer| {
12871 supports |= provider.supports_inlay_hints(buffer, cx);
12872 });
12873 supports
12874 }
12875
12876 pub fn focus(&self, cx: &mut WindowContext) {
12877 cx.focus(&self.focus_handle)
12878 }
12879
12880 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12881 self.focus_handle.is_focused(cx)
12882 }
12883
12884 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12885 cx.emit(EditorEvent::Focused);
12886
12887 if let Some(descendant) = self
12888 .last_focused_descendant
12889 .take()
12890 .and_then(|descendant| descendant.upgrade())
12891 {
12892 cx.focus(&descendant);
12893 } else {
12894 if let Some(blame) = self.blame.as_ref() {
12895 blame.update(cx, GitBlame::focus)
12896 }
12897
12898 self.blink_manager.update(cx, BlinkManager::enable);
12899 self.show_cursor_names(cx);
12900 self.buffer.update(cx, |buffer, cx| {
12901 buffer.finalize_last_transaction(cx);
12902 if self.leader_peer_id.is_none() {
12903 buffer.set_active_selections(
12904 &self.selections.disjoint_anchors(),
12905 self.selections.line_mode,
12906 self.cursor_shape,
12907 cx,
12908 );
12909 }
12910 });
12911 }
12912 }
12913
12914 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12915 cx.emit(EditorEvent::FocusedIn)
12916 }
12917
12918 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12919 if event.blurred != self.focus_handle {
12920 self.last_focused_descendant = Some(event.blurred);
12921 }
12922 }
12923
12924 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12925 self.blink_manager.update(cx, BlinkManager::disable);
12926 self.buffer
12927 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12928
12929 if let Some(blame) = self.blame.as_ref() {
12930 blame.update(cx, GitBlame::blur)
12931 }
12932 if !self.hover_state.focused(cx) {
12933 hide_hover(self, cx);
12934 }
12935
12936 self.hide_context_menu(cx);
12937 cx.emit(EditorEvent::Blurred);
12938 cx.notify();
12939 }
12940
12941 pub fn register_action<A: Action>(
12942 &mut self,
12943 listener: impl Fn(&A, &mut WindowContext) + 'static,
12944 ) -> Subscription {
12945 let id = self.next_editor_action_id.post_inc();
12946 let listener = Arc::new(listener);
12947 self.editor_actions.borrow_mut().insert(
12948 id,
12949 Box::new(move |cx| {
12950 let cx = cx.window_context();
12951 let listener = listener.clone();
12952 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12953 let action = action.downcast_ref().unwrap();
12954 if phase == DispatchPhase::Bubble {
12955 listener(action, cx)
12956 }
12957 })
12958 }),
12959 );
12960
12961 let editor_actions = self.editor_actions.clone();
12962 Subscription::new(move || {
12963 editor_actions.borrow_mut().remove(&id);
12964 })
12965 }
12966
12967 pub fn file_header_size(&self) -> u32 {
12968 FILE_HEADER_HEIGHT
12969 }
12970
12971 pub fn revert(
12972 &mut self,
12973 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12974 cx: &mut ViewContext<Self>,
12975 ) {
12976 self.buffer().update(cx, |multi_buffer, cx| {
12977 for (buffer_id, changes) in revert_changes {
12978 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12979 buffer.update(cx, |buffer, cx| {
12980 buffer.edit(
12981 changes.into_iter().map(|(range, text)| {
12982 (range, text.to_string().map(Arc::<str>::from))
12983 }),
12984 None,
12985 cx,
12986 );
12987 });
12988 }
12989 }
12990 });
12991 self.change_selections(None, cx, |selections| selections.refresh());
12992 }
12993
12994 pub fn to_pixel_point(
12995 &mut self,
12996 source: multi_buffer::Anchor,
12997 editor_snapshot: &EditorSnapshot,
12998 cx: &mut ViewContext<Self>,
12999 ) -> Option<gpui::Point<Pixels>> {
13000 let source_point = source.to_display_point(editor_snapshot);
13001 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13002 }
13003
13004 pub fn display_to_pixel_point(
13005 &mut self,
13006 source: DisplayPoint,
13007 editor_snapshot: &EditorSnapshot,
13008 cx: &mut ViewContext<Self>,
13009 ) -> Option<gpui::Point<Pixels>> {
13010 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13011 let text_layout_details = self.text_layout_details(cx);
13012 let scroll_top = text_layout_details
13013 .scroll_anchor
13014 .scroll_position(editor_snapshot)
13015 .y;
13016
13017 if source.row().as_f32() < scroll_top.floor() {
13018 return None;
13019 }
13020 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13021 let source_y = line_height * (source.row().as_f32() - scroll_top);
13022 Some(gpui::Point::new(source_x, source_y))
13023 }
13024
13025 pub fn has_active_completions_menu(&self) -> bool {
13026 self.context_menu.read().as_ref().map_or(false, |menu| {
13027 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13028 })
13029 }
13030
13031 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13032 self.addons
13033 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13034 }
13035
13036 pub fn unregister_addon<T: Addon>(&mut self) {
13037 self.addons.remove(&std::any::TypeId::of::<T>());
13038 }
13039
13040 pub fn addon<T: Addon>(&self) -> Option<&T> {
13041 let type_id = std::any::TypeId::of::<T>();
13042 self.addons
13043 .get(&type_id)
13044 .and_then(|item| item.to_any().downcast_ref::<T>())
13045 }
13046}
13047
13048fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13049 let tab_size = tab_size.get() as usize;
13050 let mut width = offset;
13051
13052 for ch in text.chars() {
13053 width += if ch == '\t' {
13054 tab_size - (width % tab_size)
13055 } else {
13056 1
13057 };
13058 }
13059
13060 width - offset
13061}
13062
13063#[cfg(test)]
13064mod tests {
13065 use super::*;
13066
13067 #[test]
13068 fn test_string_size_with_expanded_tabs() {
13069 let nz = |val| NonZeroU32::new(val).unwrap();
13070 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13071 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13072 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13073 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13074 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13075 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13076 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13077 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13078 }
13079}
13080
13081/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13082struct WordBreakingTokenizer<'a> {
13083 input: &'a str,
13084}
13085
13086impl<'a> WordBreakingTokenizer<'a> {
13087 fn new(input: &'a str) -> Self {
13088 Self { input }
13089 }
13090}
13091
13092fn is_char_ideographic(ch: char) -> bool {
13093 use unicode_script::Script::*;
13094 use unicode_script::UnicodeScript;
13095 matches!(ch.script(), Han | Tangut | Yi)
13096}
13097
13098fn is_grapheme_ideographic(text: &str) -> bool {
13099 text.chars().any(is_char_ideographic)
13100}
13101
13102fn is_grapheme_whitespace(text: &str) -> bool {
13103 text.chars().any(|x| x.is_whitespace())
13104}
13105
13106fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13107 text.chars().next().map_or(false, |ch| {
13108 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13109 })
13110}
13111
13112#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13113struct WordBreakToken<'a> {
13114 token: &'a str,
13115 grapheme_len: usize,
13116 is_whitespace: bool,
13117}
13118
13119impl<'a> Iterator for WordBreakingTokenizer<'a> {
13120 /// Yields a span, the count of graphemes in the token, and whether it was
13121 /// whitespace. Note that it also breaks at word boundaries.
13122 type Item = WordBreakToken<'a>;
13123
13124 fn next(&mut self) -> Option<Self::Item> {
13125 use unicode_segmentation::UnicodeSegmentation;
13126 if self.input.is_empty() {
13127 return None;
13128 }
13129
13130 let mut iter = self.input.graphemes(true).peekable();
13131 let mut offset = 0;
13132 let mut graphemes = 0;
13133 if let Some(first_grapheme) = iter.next() {
13134 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13135 offset += first_grapheme.len();
13136 graphemes += 1;
13137 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13138 if let Some(grapheme) = iter.peek().copied() {
13139 if should_stay_with_preceding_ideograph(grapheme) {
13140 offset += grapheme.len();
13141 graphemes += 1;
13142 }
13143 }
13144 } else {
13145 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13146 let mut next_word_bound = words.peek().copied();
13147 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13148 next_word_bound = words.next();
13149 }
13150 while let Some(grapheme) = iter.peek().copied() {
13151 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13152 break;
13153 };
13154 if is_grapheme_whitespace(grapheme) != is_whitespace {
13155 break;
13156 };
13157 offset += grapheme.len();
13158 graphemes += 1;
13159 iter.next();
13160 }
13161 }
13162 let token = &self.input[..offset];
13163 self.input = &self.input[offset..];
13164 if is_whitespace {
13165 Some(WordBreakToken {
13166 token: " ",
13167 grapheme_len: 1,
13168 is_whitespace: true,
13169 })
13170 } else {
13171 Some(WordBreakToken {
13172 token,
13173 grapheme_len: graphemes,
13174 is_whitespace: false,
13175 })
13176 }
13177 } else {
13178 None
13179 }
13180 }
13181}
13182
13183#[test]
13184fn test_word_breaking_tokenizer() {
13185 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13186 ("", &[]),
13187 (" ", &[(" ", 1, true)]),
13188 ("Ʒ", &[("Ʒ", 1, false)]),
13189 ("Ǽ", &[("Ǽ", 1, false)]),
13190 ("⋑", &[("⋑", 1, false)]),
13191 ("⋑⋑", &[("⋑⋑", 2, false)]),
13192 (
13193 "原理,进而",
13194 &[
13195 ("原", 1, false),
13196 ("理,", 2, false),
13197 ("进", 1, false),
13198 ("而", 1, false),
13199 ],
13200 ),
13201 (
13202 "hello world",
13203 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13204 ),
13205 (
13206 "hello, world",
13207 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13208 ),
13209 (
13210 " hello world",
13211 &[
13212 (" ", 1, true),
13213 ("hello", 5, false),
13214 (" ", 1, true),
13215 ("world", 5, false),
13216 ],
13217 ),
13218 (
13219 "这是什么 \n 钢笔",
13220 &[
13221 ("这", 1, false),
13222 ("是", 1, false),
13223 ("什", 1, false),
13224 ("么", 1, false),
13225 (" ", 1, true),
13226 ("钢", 1, false),
13227 ("笔", 1, false),
13228 ],
13229 ),
13230 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13231 ];
13232
13233 for (input, result) in tests {
13234 assert_eq!(
13235 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13236 result
13237 .iter()
13238 .copied()
13239 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13240 token,
13241 grapheme_len,
13242 is_whitespace,
13243 })
13244 .collect::<Vec<_>>()
13245 );
13246 }
13247}
13248
13249fn wrap_with_prefix(
13250 line_prefix: String,
13251 unwrapped_text: String,
13252 wrap_column: usize,
13253 tab_size: NonZeroU32,
13254) -> String {
13255 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13256 let mut wrapped_text = String::new();
13257 let mut current_line = line_prefix.clone();
13258
13259 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13260 let mut current_line_len = line_prefix_len;
13261 for WordBreakToken {
13262 token,
13263 grapheme_len,
13264 is_whitespace,
13265 } in tokenizer
13266 {
13267 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13268 wrapped_text.push_str(current_line.trim_end());
13269 wrapped_text.push('\n');
13270 current_line.truncate(line_prefix.len());
13271 current_line_len = line_prefix_len;
13272 if !is_whitespace {
13273 current_line.push_str(token);
13274 current_line_len += grapheme_len;
13275 }
13276 } else if !is_whitespace {
13277 current_line.push_str(token);
13278 current_line_len += grapheme_len;
13279 } else if current_line_len != line_prefix_len {
13280 current_line.push(' ');
13281 current_line_len += 1;
13282 }
13283 }
13284
13285 if !current_line.is_empty() {
13286 wrapped_text.push_str(¤t_line);
13287 }
13288 wrapped_text
13289}
13290
13291#[test]
13292fn test_wrap_with_prefix() {
13293 assert_eq!(
13294 wrap_with_prefix(
13295 "# ".to_string(),
13296 "abcdefg".to_string(),
13297 4,
13298 NonZeroU32::new(4).unwrap()
13299 ),
13300 "# abcdefg"
13301 );
13302 assert_eq!(
13303 wrap_with_prefix(
13304 "".to_string(),
13305 "\thello world".to_string(),
13306 8,
13307 NonZeroU32::new(4).unwrap()
13308 ),
13309 "hello\nworld"
13310 );
13311 assert_eq!(
13312 wrap_with_prefix(
13313 "// ".to_string(),
13314 "xx \nyy zz aa bb cc".to_string(),
13315 12,
13316 NonZeroU32::new(4).unwrap()
13317 ),
13318 "// xx yy zz\n// aa bb cc"
13319 );
13320 assert_eq!(
13321 wrap_with_prefix(
13322 String::new(),
13323 "这是什么 \n 钢笔".to_string(),
13324 3,
13325 NonZeroU32::new(4).unwrap()
13326 ),
13327 "这是什\n么 钢\n笔"
13328 );
13329}
13330
13331fn hunks_for_selections(
13332 multi_buffer_snapshot: &MultiBufferSnapshot,
13333 selections: &[Selection<Anchor>],
13334) -> Vec<MultiBufferDiffHunk> {
13335 let buffer_rows_for_selections = selections.iter().map(|selection| {
13336 let head = selection.head();
13337 let tail = selection.tail();
13338 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13339 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13340 if start > end {
13341 end..start
13342 } else {
13343 start..end
13344 }
13345 });
13346
13347 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13348}
13349
13350pub fn hunks_for_rows(
13351 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13352 multi_buffer_snapshot: &MultiBufferSnapshot,
13353) -> Vec<MultiBufferDiffHunk> {
13354 let mut hunks = Vec::new();
13355 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13356 HashMap::default();
13357 for selected_multi_buffer_rows in rows {
13358 let query_rows =
13359 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13360 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13361 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13362 // when the caret is just above or just below the deleted hunk.
13363 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13364 let related_to_selection = if allow_adjacent {
13365 hunk.row_range.overlaps(&query_rows)
13366 || hunk.row_range.start == query_rows.end
13367 || hunk.row_range.end == query_rows.start
13368 } else {
13369 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13370 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13371 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13372 || selected_multi_buffer_rows.end == hunk.row_range.start
13373 };
13374 if related_to_selection {
13375 if !processed_buffer_rows
13376 .entry(hunk.buffer_id)
13377 .or_default()
13378 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13379 {
13380 continue;
13381 }
13382 hunks.push(hunk);
13383 }
13384 }
13385 }
13386
13387 hunks
13388}
13389
13390pub trait CollaborationHub {
13391 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13392 fn user_participant_indices<'a>(
13393 &self,
13394 cx: &'a AppContext,
13395 ) -> &'a HashMap<u64, ParticipantIndex>;
13396 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13397}
13398
13399impl CollaborationHub for Model<Project> {
13400 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13401 self.read(cx).collaborators()
13402 }
13403
13404 fn user_participant_indices<'a>(
13405 &self,
13406 cx: &'a AppContext,
13407 ) -> &'a HashMap<u64, ParticipantIndex> {
13408 self.read(cx).user_store().read(cx).participant_indices()
13409 }
13410
13411 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13412 let this = self.read(cx);
13413 let user_ids = this.collaborators().values().map(|c| c.user_id);
13414 this.user_store().read_with(cx, |user_store, cx| {
13415 user_store.participant_names(user_ids, cx)
13416 })
13417 }
13418}
13419
13420pub trait SemanticsProvider {
13421 fn hover(
13422 &self,
13423 buffer: &Model<Buffer>,
13424 position: text::Anchor,
13425 cx: &mut AppContext,
13426 ) -> Option<Task<Vec<project::Hover>>>;
13427
13428 fn inlay_hints(
13429 &self,
13430 buffer_handle: Model<Buffer>,
13431 range: Range<text::Anchor>,
13432 cx: &mut AppContext,
13433 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13434
13435 fn resolve_inlay_hint(
13436 &self,
13437 hint: InlayHint,
13438 buffer_handle: Model<Buffer>,
13439 server_id: LanguageServerId,
13440 cx: &mut AppContext,
13441 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13442
13443 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13444
13445 fn document_highlights(
13446 &self,
13447 buffer: &Model<Buffer>,
13448 position: text::Anchor,
13449 cx: &mut AppContext,
13450 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13451
13452 fn definitions(
13453 &self,
13454 buffer: &Model<Buffer>,
13455 position: text::Anchor,
13456 kind: GotoDefinitionKind,
13457 cx: &mut AppContext,
13458 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13459
13460 fn range_for_rename(
13461 &self,
13462 buffer: &Model<Buffer>,
13463 position: text::Anchor,
13464 cx: &mut AppContext,
13465 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13466
13467 fn perform_rename(
13468 &self,
13469 buffer: &Model<Buffer>,
13470 position: text::Anchor,
13471 new_name: String,
13472 cx: &mut AppContext,
13473 ) -> Option<Task<Result<ProjectTransaction>>>;
13474}
13475
13476pub trait CompletionProvider {
13477 fn completions(
13478 &self,
13479 buffer: &Model<Buffer>,
13480 buffer_position: text::Anchor,
13481 trigger: CompletionContext,
13482 cx: &mut ViewContext<Editor>,
13483 ) -> Task<Result<Vec<Completion>>>;
13484
13485 fn resolve_completions(
13486 &self,
13487 buffer: Model<Buffer>,
13488 completion_indices: Vec<usize>,
13489 completions: Arc<RwLock<Box<[Completion]>>>,
13490 cx: &mut ViewContext<Editor>,
13491 ) -> Task<Result<bool>>;
13492
13493 fn apply_additional_edits_for_completion(
13494 &self,
13495 buffer: Model<Buffer>,
13496 completion: Completion,
13497 push_to_history: bool,
13498 cx: &mut ViewContext<Editor>,
13499 ) -> Task<Result<Option<language::Transaction>>>;
13500
13501 fn is_completion_trigger(
13502 &self,
13503 buffer: &Model<Buffer>,
13504 position: language::Anchor,
13505 text: &str,
13506 trigger_in_words: bool,
13507 cx: &mut ViewContext<Editor>,
13508 ) -> bool;
13509
13510 fn sort_completions(&self) -> bool {
13511 true
13512 }
13513}
13514
13515pub trait CodeActionProvider {
13516 fn code_actions(
13517 &self,
13518 buffer: &Model<Buffer>,
13519 range: Range<text::Anchor>,
13520 cx: &mut WindowContext,
13521 ) -> Task<Result<Vec<CodeAction>>>;
13522
13523 fn apply_code_action(
13524 &self,
13525 buffer_handle: Model<Buffer>,
13526 action: CodeAction,
13527 excerpt_id: ExcerptId,
13528 push_to_history: bool,
13529 cx: &mut WindowContext,
13530 ) -> Task<Result<ProjectTransaction>>;
13531}
13532
13533impl CodeActionProvider for Model<Project> {
13534 fn code_actions(
13535 &self,
13536 buffer: &Model<Buffer>,
13537 range: Range<text::Anchor>,
13538 cx: &mut WindowContext,
13539 ) -> Task<Result<Vec<CodeAction>>> {
13540 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13541 }
13542
13543 fn apply_code_action(
13544 &self,
13545 buffer_handle: Model<Buffer>,
13546 action: CodeAction,
13547 _excerpt_id: ExcerptId,
13548 push_to_history: bool,
13549 cx: &mut WindowContext,
13550 ) -> Task<Result<ProjectTransaction>> {
13551 self.update(cx, |project, cx| {
13552 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13553 })
13554 }
13555}
13556
13557fn snippet_completions(
13558 project: &Project,
13559 buffer: &Model<Buffer>,
13560 buffer_position: text::Anchor,
13561 cx: &mut AppContext,
13562) -> Vec<Completion> {
13563 let language = buffer.read(cx).language_at(buffer_position);
13564 let language_name = language.as_ref().map(|language| language.lsp_id());
13565 let snippet_store = project.snippets().read(cx);
13566 let snippets = snippet_store.snippets_for(language_name, cx);
13567
13568 if snippets.is_empty() {
13569 return vec![];
13570 }
13571 let snapshot = buffer.read(cx).text_snapshot();
13572 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13573
13574 let scope = language.map(|language| language.default_scope());
13575 let classifier = CharClassifier::new(scope).for_completion(true);
13576 let mut last_word = chars
13577 .take_while(|c| classifier.is_word(*c))
13578 .collect::<String>();
13579 last_word = last_word.chars().rev().collect();
13580 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13581 let to_lsp = |point: &text::Anchor| {
13582 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13583 point_to_lsp(end)
13584 };
13585 let lsp_end = to_lsp(&buffer_position);
13586 snippets
13587 .into_iter()
13588 .filter_map(|snippet| {
13589 let matching_prefix = snippet
13590 .prefix
13591 .iter()
13592 .find(|prefix| prefix.starts_with(&last_word))?;
13593 let start = as_offset - last_word.len();
13594 let start = snapshot.anchor_before(start);
13595 let range = start..buffer_position;
13596 let lsp_start = to_lsp(&start);
13597 let lsp_range = lsp::Range {
13598 start: lsp_start,
13599 end: lsp_end,
13600 };
13601 Some(Completion {
13602 old_range: range,
13603 new_text: snippet.body.clone(),
13604 label: CodeLabel {
13605 text: matching_prefix.clone(),
13606 runs: vec![],
13607 filter_range: 0..matching_prefix.len(),
13608 },
13609 server_id: LanguageServerId(usize::MAX),
13610 documentation: snippet.description.clone().map(Documentation::SingleLine),
13611 lsp_completion: lsp::CompletionItem {
13612 label: snippet.prefix.first().unwrap().clone(),
13613 kind: Some(CompletionItemKind::SNIPPET),
13614 label_details: snippet.description.as_ref().map(|description| {
13615 lsp::CompletionItemLabelDetails {
13616 detail: Some(description.clone()),
13617 description: None,
13618 }
13619 }),
13620 insert_text_format: Some(InsertTextFormat::SNIPPET),
13621 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13622 lsp::InsertReplaceEdit {
13623 new_text: snippet.body.clone(),
13624 insert: lsp_range,
13625 replace: lsp_range,
13626 },
13627 )),
13628 filter_text: Some(snippet.body.clone()),
13629 sort_text: Some(char::MAX.to_string()),
13630 ..Default::default()
13631 },
13632 confirm: None,
13633 })
13634 })
13635 .collect()
13636}
13637
13638impl CompletionProvider for Model<Project> {
13639 fn completions(
13640 &self,
13641 buffer: &Model<Buffer>,
13642 buffer_position: text::Anchor,
13643 options: CompletionContext,
13644 cx: &mut ViewContext<Editor>,
13645 ) -> Task<Result<Vec<Completion>>> {
13646 self.update(cx, |project, cx| {
13647 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13648 let project_completions = project.completions(buffer, buffer_position, options, cx);
13649 cx.background_executor().spawn(async move {
13650 let mut completions = project_completions.await?;
13651 //let snippets = snippets.into_iter().;
13652 completions.extend(snippets);
13653 Ok(completions)
13654 })
13655 })
13656 }
13657
13658 fn resolve_completions(
13659 &self,
13660 buffer: Model<Buffer>,
13661 completion_indices: Vec<usize>,
13662 completions: Arc<RwLock<Box<[Completion]>>>,
13663 cx: &mut ViewContext<Editor>,
13664 ) -> Task<Result<bool>> {
13665 self.update(cx, |project, cx| {
13666 project.resolve_completions(buffer, completion_indices, completions, cx)
13667 })
13668 }
13669
13670 fn apply_additional_edits_for_completion(
13671 &self,
13672 buffer: Model<Buffer>,
13673 completion: Completion,
13674 push_to_history: bool,
13675 cx: &mut ViewContext<Editor>,
13676 ) -> Task<Result<Option<language::Transaction>>> {
13677 self.update(cx, |project, cx| {
13678 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13679 })
13680 }
13681
13682 fn is_completion_trigger(
13683 &self,
13684 buffer: &Model<Buffer>,
13685 position: language::Anchor,
13686 text: &str,
13687 trigger_in_words: bool,
13688 cx: &mut ViewContext<Editor>,
13689 ) -> bool {
13690 if !EditorSettings::get_global(cx).show_completions_on_input {
13691 return false;
13692 }
13693
13694 let mut chars = text.chars();
13695 let char = if let Some(char) = chars.next() {
13696 char
13697 } else {
13698 return false;
13699 };
13700 if chars.next().is_some() {
13701 return false;
13702 }
13703
13704 let buffer = buffer.read(cx);
13705 let classifier = buffer
13706 .snapshot()
13707 .char_classifier_at(position)
13708 .for_completion(true);
13709 if trigger_in_words && classifier.is_word(char) {
13710 return true;
13711 }
13712
13713 buffer
13714 .completion_triggers()
13715 .iter()
13716 .any(|string| string == text)
13717 }
13718}
13719
13720impl SemanticsProvider for Model<Project> {
13721 fn hover(
13722 &self,
13723 buffer: &Model<Buffer>,
13724 position: text::Anchor,
13725 cx: &mut AppContext,
13726 ) -> Option<Task<Vec<project::Hover>>> {
13727 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13728 }
13729
13730 fn document_highlights(
13731 &self,
13732 buffer: &Model<Buffer>,
13733 position: text::Anchor,
13734 cx: &mut AppContext,
13735 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13736 Some(self.update(cx, |project, cx| {
13737 project.document_highlights(buffer, position, cx)
13738 }))
13739 }
13740
13741 fn definitions(
13742 &self,
13743 buffer: &Model<Buffer>,
13744 position: text::Anchor,
13745 kind: GotoDefinitionKind,
13746 cx: &mut AppContext,
13747 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13748 Some(self.update(cx, |project, cx| match kind {
13749 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13750 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13751 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13752 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13753 }))
13754 }
13755
13756 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13757 // TODO: make this work for remote projects
13758 self.read(cx)
13759 .language_servers_for_buffer(buffer.read(cx), cx)
13760 .any(
13761 |(_, server)| match server.capabilities().inlay_hint_provider {
13762 Some(lsp::OneOf::Left(enabled)) => enabled,
13763 Some(lsp::OneOf::Right(_)) => true,
13764 None => false,
13765 },
13766 )
13767 }
13768
13769 fn inlay_hints(
13770 &self,
13771 buffer_handle: Model<Buffer>,
13772 range: Range<text::Anchor>,
13773 cx: &mut AppContext,
13774 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13775 Some(self.update(cx, |project, cx| {
13776 project.inlay_hints(buffer_handle, range, cx)
13777 }))
13778 }
13779
13780 fn resolve_inlay_hint(
13781 &self,
13782 hint: InlayHint,
13783 buffer_handle: Model<Buffer>,
13784 server_id: LanguageServerId,
13785 cx: &mut AppContext,
13786 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13787 Some(self.update(cx, |project, cx| {
13788 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13789 }))
13790 }
13791
13792 fn range_for_rename(
13793 &self,
13794 buffer: &Model<Buffer>,
13795 position: text::Anchor,
13796 cx: &mut AppContext,
13797 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13798 Some(self.update(cx, |project, cx| {
13799 project.prepare_rename(buffer.clone(), position, cx)
13800 }))
13801 }
13802
13803 fn perform_rename(
13804 &self,
13805 buffer: &Model<Buffer>,
13806 position: text::Anchor,
13807 new_name: String,
13808 cx: &mut AppContext,
13809 ) -> Option<Task<Result<ProjectTransaction>>> {
13810 Some(self.update(cx, |project, cx| {
13811 project.perform_rename(buffer.clone(), position, new_name, cx)
13812 }))
13813 }
13814}
13815
13816fn inlay_hint_settings(
13817 location: Anchor,
13818 snapshot: &MultiBufferSnapshot,
13819 cx: &mut ViewContext<'_, Editor>,
13820) -> InlayHintSettings {
13821 let file = snapshot.file_at(location);
13822 let language = snapshot.language_at(location).map(|l| l.name());
13823 language_settings(language, file, cx).inlay_hints
13824}
13825
13826fn consume_contiguous_rows(
13827 contiguous_row_selections: &mut Vec<Selection<Point>>,
13828 selection: &Selection<Point>,
13829 display_map: &DisplaySnapshot,
13830 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13831) -> (MultiBufferRow, MultiBufferRow) {
13832 contiguous_row_selections.push(selection.clone());
13833 let start_row = MultiBufferRow(selection.start.row);
13834 let mut end_row = ending_row(selection, display_map);
13835
13836 while let Some(next_selection) = selections.peek() {
13837 if next_selection.start.row <= end_row.0 {
13838 end_row = ending_row(next_selection, display_map);
13839 contiguous_row_selections.push(selections.next().unwrap().clone());
13840 } else {
13841 break;
13842 }
13843 }
13844 (start_row, end_row)
13845}
13846
13847fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13848 if next_selection.end.column > 0 || next_selection.is_empty() {
13849 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13850 } else {
13851 MultiBufferRow(next_selection.end.row)
13852 }
13853}
13854
13855impl EditorSnapshot {
13856 pub fn remote_selections_in_range<'a>(
13857 &'a self,
13858 range: &'a Range<Anchor>,
13859 collaboration_hub: &dyn CollaborationHub,
13860 cx: &'a AppContext,
13861 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13862 let participant_names = collaboration_hub.user_names(cx);
13863 let participant_indices = collaboration_hub.user_participant_indices(cx);
13864 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13865 let collaborators_by_replica_id = collaborators_by_peer_id
13866 .iter()
13867 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13868 .collect::<HashMap<_, _>>();
13869 self.buffer_snapshot
13870 .selections_in_range(range, false)
13871 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13872 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13873 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13874 let user_name = participant_names.get(&collaborator.user_id).cloned();
13875 Some(RemoteSelection {
13876 replica_id,
13877 selection,
13878 cursor_shape,
13879 line_mode,
13880 participant_index,
13881 peer_id: collaborator.peer_id,
13882 user_name,
13883 })
13884 })
13885 }
13886
13887 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13888 self.display_snapshot.buffer_snapshot.language_at(position)
13889 }
13890
13891 pub fn is_focused(&self) -> bool {
13892 self.is_focused
13893 }
13894
13895 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13896 self.placeholder_text.as_ref()
13897 }
13898
13899 pub fn scroll_position(&self) -> gpui::Point<f32> {
13900 self.scroll_anchor.scroll_position(&self.display_snapshot)
13901 }
13902
13903 fn gutter_dimensions(
13904 &self,
13905 font_id: FontId,
13906 font_size: Pixels,
13907 em_width: Pixels,
13908 em_advance: Pixels,
13909 max_line_number_width: Pixels,
13910 cx: &AppContext,
13911 ) -> GutterDimensions {
13912 if !self.show_gutter {
13913 return GutterDimensions::default();
13914 }
13915 let descent = cx.text_system().descent(font_id, font_size);
13916
13917 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13918 matches!(
13919 ProjectSettings::get_global(cx).git.git_gutter,
13920 Some(GitGutterSetting::TrackedFiles)
13921 )
13922 });
13923 let gutter_settings = EditorSettings::get_global(cx).gutter;
13924 let show_line_numbers = self
13925 .show_line_numbers
13926 .unwrap_or(gutter_settings.line_numbers);
13927 let line_gutter_width = if show_line_numbers {
13928 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13929 let min_width_for_number_on_gutter = em_advance * 4.0;
13930 max_line_number_width.max(min_width_for_number_on_gutter)
13931 } else {
13932 0.0.into()
13933 };
13934
13935 let show_code_actions = self
13936 .show_code_actions
13937 .unwrap_or(gutter_settings.code_actions);
13938
13939 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13940
13941 let git_blame_entries_width =
13942 self.git_blame_gutter_max_author_length
13943 .map(|max_author_length| {
13944 // Length of the author name, but also space for the commit hash,
13945 // the spacing and the timestamp.
13946 let max_char_count = max_author_length
13947 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13948 + 7 // length of commit sha
13949 + 14 // length of max relative timestamp ("60 minutes ago")
13950 + 4; // gaps and margins
13951
13952 em_advance * max_char_count
13953 });
13954
13955 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13956 left_padding += if show_code_actions || show_runnables {
13957 em_width * 3.0
13958 } else if show_git_gutter && show_line_numbers {
13959 em_width * 2.0
13960 } else if show_git_gutter || show_line_numbers {
13961 em_width
13962 } else {
13963 px(0.)
13964 };
13965
13966 let right_padding = if gutter_settings.folds && show_line_numbers {
13967 em_width * 4.0
13968 } else if gutter_settings.folds {
13969 em_width * 3.0
13970 } else if show_line_numbers {
13971 em_width
13972 } else {
13973 px(0.)
13974 };
13975
13976 GutterDimensions {
13977 left_padding,
13978 right_padding,
13979 width: line_gutter_width + left_padding + right_padding,
13980 margin: -descent,
13981 git_blame_entries_width,
13982 }
13983 }
13984
13985 pub fn render_fold_toggle(
13986 &self,
13987 buffer_row: MultiBufferRow,
13988 row_contains_cursor: bool,
13989 editor: View<Editor>,
13990 cx: &mut WindowContext,
13991 ) -> Option<AnyElement> {
13992 let folded = self.is_line_folded(buffer_row);
13993
13994 if let Some(crease) = self
13995 .crease_snapshot
13996 .query_row(buffer_row, &self.buffer_snapshot)
13997 {
13998 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13999 if folded {
14000 editor.update(cx, |editor, cx| {
14001 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14002 });
14003 } else {
14004 editor.update(cx, |editor, cx| {
14005 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14006 });
14007 }
14008 });
14009
14010 Some((crease.render_toggle)(
14011 buffer_row,
14012 folded,
14013 toggle_callback,
14014 cx,
14015 ))
14016 } else if folded
14017 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14018 {
14019 Some(
14020 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14021 .selected(folded)
14022 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14023 if folded {
14024 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14025 } else {
14026 this.fold_at(&FoldAt { buffer_row }, cx);
14027 }
14028 }))
14029 .into_any_element(),
14030 )
14031 } else {
14032 None
14033 }
14034 }
14035
14036 pub fn render_crease_trailer(
14037 &self,
14038 buffer_row: MultiBufferRow,
14039 cx: &mut WindowContext,
14040 ) -> Option<AnyElement> {
14041 let folded = self.is_line_folded(buffer_row);
14042 let crease = self
14043 .crease_snapshot
14044 .query_row(buffer_row, &self.buffer_snapshot)?;
14045 Some((crease.render_trailer)(buffer_row, folded, cx))
14046 }
14047}
14048
14049impl Deref for EditorSnapshot {
14050 type Target = DisplaySnapshot;
14051
14052 fn deref(&self) -> &Self::Target {
14053 &self.display_snapshot
14054 }
14055}
14056
14057#[derive(Clone, Debug, PartialEq, Eq)]
14058pub enum EditorEvent {
14059 InputIgnored {
14060 text: Arc<str>,
14061 },
14062 InputHandled {
14063 utf16_range_to_replace: Option<Range<isize>>,
14064 text: Arc<str>,
14065 },
14066 ExcerptsAdded {
14067 buffer: Model<Buffer>,
14068 predecessor: ExcerptId,
14069 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14070 },
14071 ExcerptsRemoved {
14072 ids: Vec<ExcerptId>,
14073 },
14074 ExcerptsEdited {
14075 ids: Vec<ExcerptId>,
14076 },
14077 ExcerptsExpanded {
14078 ids: Vec<ExcerptId>,
14079 },
14080 BufferEdited,
14081 Edited {
14082 transaction_id: clock::Lamport,
14083 },
14084 Reparsed(BufferId),
14085 Focused,
14086 FocusedIn,
14087 Blurred,
14088 DirtyChanged,
14089 Saved,
14090 TitleChanged,
14091 DiffBaseChanged,
14092 SelectionsChanged {
14093 local: bool,
14094 },
14095 ScrollPositionChanged {
14096 local: bool,
14097 autoscroll: bool,
14098 },
14099 Closed,
14100 TransactionUndone {
14101 transaction_id: clock::Lamport,
14102 },
14103 TransactionBegun {
14104 transaction_id: clock::Lamport,
14105 },
14106 Reloaded,
14107 CursorShapeChanged,
14108}
14109
14110impl EventEmitter<EditorEvent> for Editor {}
14111
14112impl FocusableView for Editor {
14113 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14114 self.focus_handle.clone()
14115 }
14116}
14117
14118impl Render for Editor {
14119 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14120 let settings = ThemeSettings::get_global(cx);
14121
14122 let mut text_style = match self.mode {
14123 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14124 color: cx.theme().colors().editor_foreground,
14125 font_family: settings.ui_font.family.clone(),
14126 font_features: settings.ui_font.features.clone(),
14127 font_fallbacks: settings.ui_font.fallbacks.clone(),
14128 font_size: rems(0.875).into(),
14129 font_weight: settings.ui_font.weight,
14130 line_height: relative(settings.buffer_line_height.value()),
14131 ..Default::default()
14132 },
14133 EditorMode::Full => TextStyle {
14134 color: cx.theme().colors().editor_foreground,
14135 font_family: settings.buffer_font.family.clone(),
14136 font_features: settings.buffer_font.features.clone(),
14137 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14138 font_size: settings.buffer_font_size(cx).into(),
14139 font_weight: settings.buffer_font.weight,
14140 line_height: relative(settings.buffer_line_height.value()),
14141 ..Default::default()
14142 },
14143 };
14144 if let Some(text_style_refinement) = &self.text_style_refinement {
14145 text_style.refine(text_style_refinement)
14146 }
14147
14148 let background = match self.mode {
14149 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14150 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14151 EditorMode::Full => cx.theme().colors().editor_background,
14152 };
14153
14154 EditorElement::new(
14155 cx.view(),
14156 EditorStyle {
14157 background,
14158 local_player: cx.theme().players().local(),
14159 text: text_style,
14160 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14161 syntax: cx.theme().syntax().clone(),
14162 status: cx.theme().status().clone(),
14163 inlay_hints_style: make_inlay_hints_style(cx),
14164 suggestions_style: HighlightStyle {
14165 color: Some(cx.theme().status().predictive),
14166 ..HighlightStyle::default()
14167 },
14168 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14169 },
14170 )
14171 }
14172}
14173
14174impl ViewInputHandler for Editor {
14175 fn text_for_range(
14176 &mut self,
14177 range_utf16: Range<usize>,
14178 cx: &mut ViewContext<Self>,
14179 ) -> Option<String> {
14180 Some(
14181 self.buffer
14182 .read(cx)
14183 .read(cx)
14184 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14185 .collect(),
14186 )
14187 }
14188
14189 fn selected_text_range(
14190 &mut self,
14191 ignore_disabled_input: bool,
14192 cx: &mut ViewContext<Self>,
14193 ) -> Option<UTF16Selection> {
14194 // Prevent the IME menu from appearing when holding down an alphabetic key
14195 // while input is disabled.
14196 if !ignore_disabled_input && !self.input_enabled {
14197 return None;
14198 }
14199
14200 let selection = self.selections.newest::<OffsetUtf16>(cx);
14201 let range = selection.range();
14202
14203 Some(UTF16Selection {
14204 range: range.start.0..range.end.0,
14205 reversed: selection.reversed,
14206 })
14207 }
14208
14209 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14210 let snapshot = self.buffer.read(cx).read(cx);
14211 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14212 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14213 }
14214
14215 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14216 self.clear_highlights::<InputComposition>(cx);
14217 self.ime_transaction.take();
14218 }
14219
14220 fn replace_text_in_range(
14221 &mut self,
14222 range_utf16: Option<Range<usize>>,
14223 text: &str,
14224 cx: &mut ViewContext<Self>,
14225 ) {
14226 if !self.input_enabled {
14227 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14228 return;
14229 }
14230
14231 self.transact(cx, |this, cx| {
14232 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14233 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14234 Some(this.selection_replacement_ranges(range_utf16, cx))
14235 } else {
14236 this.marked_text_ranges(cx)
14237 };
14238
14239 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14240 let newest_selection_id = this.selections.newest_anchor().id;
14241 this.selections
14242 .all::<OffsetUtf16>(cx)
14243 .iter()
14244 .zip(ranges_to_replace.iter())
14245 .find_map(|(selection, range)| {
14246 if selection.id == newest_selection_id {
14247 Some(
14248 (range.start.0 as isize - selection.head().0 as isize)
14249 ..(range.end.0 as isize - selection.head().0 as isize),
14250 )
14251 } else {
14252 None
14253 }
14254 })
14255 });
14256
14257 cx.emit(EditorEvent::InputHandled {
14258 utf16_range_to_replace: range_to_replace,
14259 text: text.into(),
14260 });
14261
14262 if let Some(new_selected_ranges) = new_selected_ranges {
14263 this.change_selections(None, cx, |selections| {
14264 selections.select_ranges(new_selected_ranges)
14265 });
14266 this.backspace(&Default::default(), cx);
14267 }
14268
14269 this.handle_input(text, cx);
14270 });
14271
14272 if let Some(transaction) = self.ime_transaction {
14273 self.buffer.update(cx, |buffer, cx| {
14274 buffer.group_until_transaction(transaction, cx);
14275 });
14276 }
14277
14278 self.unmark_text(cx);
14279 }
14280
14281 fn replace_and_mark_text_in_range(
14282 &mut self,
14283 range_utf16: Option<Range<usize>>,
14284 text: &str,
14285 new_selected_range_utf16: Option<Range<usize>>,
14286 cx: &mut ViewContext<Self>,
14287 ) {
14288 if !self.input_enabled {
14289 return;
14290 }
14291
14292 let transaction = self.transact(cx, |this, cx| {
14293 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14294 let snapshot = this.buffer.read(cx).read(cx);
14295 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14296 for marked_range in &mut marked_ranges {
14297 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14298 marked_range.start.0 += relative_range_utf16.start;
14299 marked_range.start =
14300 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14301 marked_range.end =
14302 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14303 }
14304 }
14305 Some(marked_ranges)
14306 } else if let Some(range_utf16) = range_utf16 {
14307 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14308 Some(this.selection_replacement_ranges(range_utf16, cx))
14309 } else {
14310 None
14311 };
14312
14313 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14314 let newest_selection_id = this.selections.newest_anchor().id;
14315 this.selections
14316 .all::<OffsetUtf16>(cx)
14317 .iter()
14318 .zip(ranges_to_replace.iter())
14319 .find_map(|(selection, range)| {
14320 if selection.id == newest_selection_id {
14321 Some(
14322 (range.start.0 as isize - selection.head().0 as isize)
14323 ..(range.end.0 as isize - selection.head().0 as isize),
14324 )
14325 } else {
14326 None
14327 }
14328 })
14329 });
14330
14331 cx.emit(EditorEvent::InputHandled {
14332 utf16_range_to_replace: range_to_replace,
14333 text: text.into(),
14334 });
14335
14336 if let Some(ranges) = ranges_to_replace {
14337 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14338 }
14339
14340 let marked_ranges = {
14341 let snapshot = this.buffer.read(cx).read(cx);
14342 this.selections
14343 .disjoint_anchors()
14344 .iter()
14345 .map(|selection| {
14346 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14347 })
14348 .collect::<Vec<_>>()
14349 };
14350
14351 if text.is_empty() {
14352 this.unmark_text(cx);
14353 } else {
14354 this.highlight_text::<InputComposition>(
14355 marked_ranges.clone(),
14356 HighlightStyle {
14357 underline: Some(UnderlineStyle {
14358 thickness: px(1.),
14359 color: None,
14360 wavy: false,
14361 }),
14362 ..Default::default()
14363 },
14364 cx,
14365 );
14366 }
14367
14368 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14369 let use_autoclose = this.use_autoclose;
14370 let use_auto_surround = this.use_auto_surround;
14371 this.set_use_autoclose(false);
14372 this.set_use_auto_surround(false);
14373 this.handle_input(text, cx);
14374 this.set_use_autoclose(use_autoclose);
14375 this.set_use_auto_surround(use_auto_surround);
14376
14377 if let Some(new_selected_range) = new_selected_range_utf16 {
14378 let snapshot = this.buffer.read(cx).read(cx);
14379 let new_selected_ranges = marked_ranges
14380 .into_iter()
14381 .map(|marked_range| {
14382 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14383 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14384 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14385 snapshot.clip_offset_utf16(new_start, Bias::Left)
14386 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14387 })
14388 .collect::<Vec<_>>();
14389
14390 drop(snapshot);
14391 this.change_selections(None, cx, |selections| {
14392 selections.select_ranges(new_selected_ranges)
14393 });
14394 }
14395 });
14396
14397 self.ime_transaction = self.ime_transaction.or(transaction);
14398 if let Some(transaction) = self.ime_transaction {
14399 self.buffer.update(cx, |buffer, cx| {
14400 buffer.group_until_transaction(transaction, cx);
14401 });
14402 }
14403
14404 if self.text_highlights::<InputComposition>(cx).is_none() {
14405 self.ime_transaction.take();
14406 }
14407 }
14408
14409 fn bounds_for_range(
14410 &mut self,
14411 range_utf16: Range<usize>,
14412 element_bounds: gpui::Bounds<Pixels>,
14413 cx: &mut ViewContext<Self>,
14414 ) -> Option<gpui::Bounds<Pixels>> {
14415 let text_layout_details = self.text_layout_details(cx);
14416 let style = &text_layout_details.editor_style;
14417 let font_id = cx.text_system().resolve_font(&style.text.font());
14418 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14419 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14420
14421 let em_width = cx
14422 .text_system()
14423 .typographic_bounds(font_id, font_size, 'm')
14424 .unwrap()
14425 .size
14426 .width;
14427
14428 let snapshot = self.snapshot(cx);
14429 let scroll_position = snapshot.scroll_position();
14430 let scroll_left = scroll_position.x * em_width;
14431
14432 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14433 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14434 + self.gutter_dimensions.width;
14435 let y = line_height * (start.row().as_f32() - scroll_position.y);
14436
14437 Some(Bounds {
14438 origin: element_bounds.origin + point(x, y),
14439 size: size(em_width, line_height),
14440 })
14441 }
14442}
14443
14444trait SelectionExt {
14445 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14446 fn spanned_rows(
14447 &self,
14448 include_end_if_at_line_start: bool,
14449 map: &DisplaySnapshot,
14450 ) -> Range<MultiBufferRow>;
14451}
14452
14453impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14454 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14455 let start = self
14456 .start
14457 .to_point(&map.buffer_snapshot)
14458 .to_display_point(map);
14459 let end = self
14460 .end
14461 .to_point(&map.buffer_snapshot)
14462 .to_display_point(map);
14463 if self.reversed {
14464 end..start
14465 } else {
14466 start..end
14467 }
14468 }
14469
14470 fn spanned_rows(
14471 &self,
14472 include_end_if_at_line_start: bool,
14473 map: &DisplaySnapshot,
14474 ) -> Range<MultiBufferRow> {
14475 let start = self.start.to_point(&map.buffer_snapshot);
14476 let mut end = self.end.to_point(&map.buffer_snapshot);
14477 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14478 end.row -= 1;
14479 }
14480
14481 let buffer_start = map.prev_line_boundary(start).0;
14482 let buffer_end = map.next_line_boundary(end).0;
14483 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14484 }
14485}
14486
14487impl<T: InvalidationRegion> InvalidationStack<T> {
14488 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14489 where
14490 S: Clone + ToOffset,
14491 {
14492 while let Some(region) = self.last() {
14493 let all_selections_inside_invalidation_ranges =
14494 if selections.len() == region.ranges().len() {
14495 selections
14496 .iter()
14497 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14498 .all(|(selection, invalidation_range)| {
14499 let head = selection.head().to_offset(buffer);
14500 invalidation_range.start <= head && invalidation_range.end >= head
14501 })
14502 } else {
14503 false
14504 };
14505
14506 if all_selections_inside_invalidation_ranges {
14507 break;
14508 } else {
14509 self.pop();
14510 }
14511 }
14512 }
14513}
14514
14515impl<T> Default for InvalidationStack<T> {
14516 fn default() -> Self {
14517 Self(Default::default())
14518 }
14519}
14520
14521impl<T> Deref for InvalidationStack<T> {
14522 type Target = Vec<T>;
14523
14524 fn deref(&self) -> &Self::Target {
14525 &self.0
14526 }
14527}
14528
14529impl<T> DerefMut for InvalidationStack<T> {
14530 fn deref_mut(&mut self) -> &mut Self::Target {
14531 &mut self.0
14532 }
14533}
14534
14535impl InvalidationRegion for SnippetState {
14536 fn ranges(&self) -> &[Range<Anchor>] {
14537 &self.ranges[self.active_index]
14538 }
14539}
14540
14541pub fn diagnostic_block_renderer(
14542 diagnostic: Diagnostic,
14543 max_message_rows: Option<u8>,
14544 allow_closing: bool,
14545 _is_valid: bool,
14546) -> RenderBlock {
14547 let (text_without_backticks, code_ranges) =
14548 highlight_diagnostic_message(&diagnostic, max_message_rows);
14549
14550 Box::new(move |cx: &mut BlockContext| {
14551 let group_id: SharedString = cx.block_id.to_string().into();
14552
14553 let mut text_style = cx.text_style().clone();
14554 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14555 let theme_settings = ThemeSettings::get_global(cx);
14556 text_style.font_family = theme_settings.buffer_font.family.clone();
14557 text_style.font_style = theme_settings.buffer_font.style;
14558 text_style.font_features = theme_settings.buffer_font.features.clone();
14559 text_style.font_weight = theme_settings.buffer_font.weight;
14560
14561 let multi_line_diagnostic = diagnostic.message.contains('\n');
14562
14563 let buttons = |diagnostic: &Diagnostic| {
14564 if multi_line_diagnostic {
14565 v_flex()
14566 } else {
14567 h_flex()
14568 }
14569 .when(allow_closing, |div| {
14570 div.children(diagnostic.is_primary.then(|| {
14571 IconButton::new("close-block", IconName::XCircle)
14572 .icon_color(Color::Muted)
14573 .size(ButtonSize::Compact)
14574 .style(ButtonStyle::Transparent)
14575 .visible_on_hover(group_id.clone())
14576 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14577 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14578 }))
14579 })
14580 .child(
14581 IconButton::new("copy-block", IconName::Copy)
14582 .icon_color(Color::Muted)
14583 .size(ButtonSize::Compact)
14584 .style(ButtonStyle::Transparent)
14585 .visible_on_hover(group_id.clone())
14586 .on_click({
14587 let message = diagnostic.message.clone();
14588 move |_click, cx| {
14589 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14590 }
14591 })
14592 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14593 )
14594 };
14595
14596 let icon_size = buttons(&diagnostic)
14597 .into_any_element()
14598 .layout_as_root(AvailableSpace::min_size(), cx);
14599
14600 h_flex()
14601 .id(cx.block_id)
14602 .group(group_id.clone())
14603 .relative()
14604 .size_full()
14605 .pl(cx.gutter_dimensions.width)
14606 .w(cx.max_width - cx.gutter_dimensions.full_width())
14607 .child(
14608 div()
14609 .flex()
14610 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14611 .flex_shrink(),
14612 )
14613 .child(buttons(&diagnostic))
14614 .child(div().flex().flex_shrink_0().child(
14615 StyledText::new(text_without_backticks.clone()).with_highlights(
14616 &text_style,
14617 code_ranges.iter().map(|range| {
14618 (
14619 range.clone(),
14620 HighlightStyle {
14621 font_weight: Some(FontWeight::BOLD),
14622 ..Default::default()
14623 },
14624 )
14625 }),
14626 ),
14627 ))
14628 .into_any_element()
14629 })
14630}
14631
14632pub fn highlight_diagnostic_message(
14633 diagnostic: &Diagnostic,
14634 mut max_message_rows: Option<u8>,
14635) -> (SharedString, Vec<Range<usize>>) {
14636 let mut text_without_backticks = String::new();
14637 let mut code_ranges = Vec::new();
14638
14639 if let Some(source) = &diagnostic.source {
14640 text_without_backticks.push_str(source);
14641 code_ranges.push(0..source.len());
14642 text_without_backticks.push_str(": ");
14643 }
14644
14645 let mut prev_offset = 0;
14646 let mut in_code_block = false;
14647 let has_row_limit = max_message_rows.is_some();
14648 let mut newline_indices = diagnostic
14649 .message
14650 .match_indices('\n')
14651 .filter(|_| has_row_limit)
14652 .map(|(ix, _)| ix)
14653 .fuse()
14654 .peekable();
14655
14656 for (quote_ix, _) in diagnostic
14657 .message
14658 .match_indices('`')
14659 .chain([(diagnostic.message.len(), "")])
14660 {
14661 let mut first_newline_ix = None;
14662 let mut last_newline_ix = None;
14663 while let Some(newline_ix) = newline_indices.peek() {
14664 if *newline_ix < quote_ix {
14665 if first_newline_ix.is_none() {
14666 first_newline_ix = Some(*newline_ix);
14667 }
14668 last_newline_ix = Some(*newline_ix);
14669
14670 if let Some(rows_left) = &mut max_message_rows {
14671 if *rows_left == 0 {
14672 break;
14673 } else {
14674 *rows_left -= 1;
14675 }
14676 }
14677 let _ = newline_indices.next();
14678 } else {
14679 break;
14680 }
14681 }
14682 let prev_len = text_without_backticks.len();
14683 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14684 text_without_backticks.push_str(new_text);
14685 if in_code_block {
14686 code_ranges.push(prev_len..text_without_backticks.len());
14687 }
14688 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14689 in_code_block = !in_code_block;
14690 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14691 text_without_backticks.push_str("...");
14692 break;
14693 }
14694 }
14695
14696 (text_without_backticks.into(), code_ranges)
14697}
14698
14699fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14700 match severity {
14701 DiagnosticSeverity::ERROR => colors.error,
14702 DiagnosticSeverity::WARNING => colors.warning,
14703 DiagnosticSeverity::INFORMATION => colors.info,
14704 DiagnosticSeverity::HINT => colors.info,
14705 _ => colors.ignored,
14706 }
14707}
14708
14709pub fn styled_runs_for_code_label<'a>(
14710 label: &'a CodeLabel,
14711 syntax_theme: &'a theme::SyntaxTheme,
14712) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14713 let fade_out = HighlightStyle {
14714 fade_out: Some(0.35),
14715 ..Default::default()
14716 };
14717
14718 let mut prev_end = label.filter_range.end;
14719 label
14720 .runs
14721 .iter()
14722 .enumerate()
14723 .flat_map(move |(ix, (range, highlight_id))| {
14724 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14725 style
14726 } else {
14727 return Default::default();
14728 };
14729 let mut muted_style = style;
14730 muted_style.highlight(fade_out);
14731
14732 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14733 if range.start >= label.filter_range.end {
14734 if range.start > prev_end {
14735 runs.push((prev_end..range.start, fade_out));
14736 }
14737 runs.push((range.clone(), muted_style));
14738 } else if range.end <= label.filter_range.end {
14739 runs.push((range.clone(), style));
14740 } else {
14741 runs.push((range.start..label.filter_range.end, style));
14742 runs.push((label.filter_range.end..range.end, muted_style));
14743 }
14744 prev_end = cmp::max(prev_end, range.end);
14745
14746 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14747 runs.push((prev_end..label.text.len(), fade_out));
14748 }
14749
14750 runs
14751 })
14752}
14753
14754pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14755 let mut prev_index = 0;
14756 let mut prev_codepoint: Option<char> = None;
14757 text.char_indices()
14758 .chain([(text.len(), '\0')])
14759 .filter_map(move |(index, codepoint)| {
14760 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14761 let is_boundary = index == text.len()
14762 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14763 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14764 if is_boundary {
14765 let chunk = &text[prev_index..index];
14766 prev_index = index;
14767 Some(chunk)
14768 } else {
14769 None
14770 }
14771 })
14772}
14773
14774pub trait RangeToAnchorExt: Sized {
14775 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14776
14777 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14778 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14779 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14780 }
14781}
14782
14783impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14784 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14785 let start_offset = self.start.to_offset(snapshot);
14786 let end_offset = self.end.to_offset(snapshot);
14787 if start_offset == end_offset {
14788 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14789 } else {
14790 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14791 }
14792 }
14793}
14794
14795pub trait RowExt {
14796 fn as_f32(&self) -> f32;
14797
14798 fn next_row(&self) -> Self;
14799
14800 fn previous_row(&self) -> Self;
14801
14802 fn minus(&self, other: Self) -> u32;
14803}
14804
14805impl RowExt for DisplayRow {
14806 fn as_f32(&self) -> f32 {
14807 self.0 as f32
14808 }
14809
14810 fn next_row(&self) -> Self {
14811 Self(self.0 + 1)
14812 }
14813
14814 fn previous_row(&self) -> Self {
14815 Self(self.0.saturating_sub(1))
14816 }
14817
14818 fn minus(&self, other: Self) -> u32 {
14819 self.0 - other.0
14820 }
14821}
14822
14823impl RowExt for MultiBufferRow {
14824 fn as_f32(&self) -> f32 {
14825 self.0 as f32
14826 }
14827
14828 fn next_row(&self) -> Self {
14829 Self(self.0 + 1)
14830 }
14831
14832 fn previous_row(&self) -> Self {
14833 Self(self.0.saturating_sub(1))
14834 }
14835
14836 fn minus(&self, other: Self) -> u32 {
14837 self.0 - other.0
14838 }
14839}
14840
14841trait RowRangeExt {
14842 type Row;
14843
14844 fn len(&self) -> usize;
14845
14846 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14847}
14848
14849impl RowRangeExt for Range<MultiBufferRow> {
14850 type Row = MultiBufferRow;
14851
14852 fn len(&self) -> usize {
14853 (self.end.0 - self.start.0) as usize
14854 }
14855
14856 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14857 (self.start.0..self.end.0).map(MultiBufferRow)
14858 }
14859}
14860
14861impl RowRangeExt for Range<DisplayRow> {
14862 type Row = DisplayRow;
14863
14864 fn len(&self) -> usize {
14865 (self.end.0 - self.start.0) as usize
14866 }
14867
14868 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14869 (self.start.0..self.end.0).map(DisplayRow)
14870 }
14871}
14872
14873fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14874 if hunk.diff_base_byte_range.is_empty() {
14875 DiffHunkStatus::Added
14876 } else if hunk.row_range.is_empty() {
14877 DiffHunkStatus::Removed
14878 } else {
14879 DiffHunkStatus::Modified
14880 }
14881}
14882
14883/// If select range has more than one line, we
14884/// just point the cursor to range.start.
14885fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14886 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14887 range
14888 } else {
14889 range.start..range.start
14890 }
14891}