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 task::{ResolvedTask, TaskTemplate, TaskVariables};
107
108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
109pub use lsp::CompletionContext;
110use lsp::{
111 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
112 LanguageServerId,
113};
114use mouse_context_menu::MouseContextMenu;
115use movement::TextLayoutDetails;
116pub use multi_buffer::{
117 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
118 ToPoint,
119};
120use multi_buffer::{
121 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
122};
123use ordered_float::OrderedFloat;
124use parking_lot::{Mutex, RwLock};
125use project::{
126 lsp_store::{FormatTarget, FormatTrigger},
127 project_settings::{GitGutterSetting, ProjectSettings},
128 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
129 LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{
135 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
136};
137use serde::{Deserialize, Serialize};
138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
139use smallvec::SmallVec;
140use snippet::Snippet;
141use std::{
142 any::TypeId,
143 borrow::Cow,
144 cell::RefCell,
145 cmp::{self, Ordering, Reverse},
146 mem,
147 num::NonZeroU32,
148 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
149 path::{Path, PathBuf},
150 rc::Rc,
151 sync::Arc,
152 time::{Duration, Instant},
153};
154pub use sum_tree::Bias;
155use sum_tree::TreeMap;
156use text::{BufferId, OffsetUtf16, Rope};
157use theme::{
158 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
159 ThemeColors, ThemeSettings,
160};
161use ui::{
162 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
163 ListItem, Popover, PopoverMenuHandle, Tooltip,
164};
165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
166use workspace::item::{ItemHandle, PreviewTabsSettings};
167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
168use workspace::{
169 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
170};
171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
172
173use crate::hover_links::find_url;
174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
175
176pub const FILE_HEADER_HEIGHT: u32 = 2;
177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
181const MAX_LINE_LEN: usize = 1024;
182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
185#[doc(hidden)]
186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
187#[doc(hidden)]
188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakView<Workspace>>,
198 cx: &mut WindowContext,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(link_ranges, move |clicked_range_ix, cx| {
243 match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace.open_abs_path(path.clone(), false, cx).detach();
249 });
250 }
251 }
252 }
253 })
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
257pub(crate) enum InlayId {
258 Suggestion(usize),
259 Hint(usize),
260}
261
262impl InlayId {
263 fn id(&self) -> usize {
264 match self {
265 Self::Suggestion(id) => *id,
266 Self::Hint(id) => *id,
267 }
268 }
269}
270
271enum DiffRowHighlight {}
272enum DocumentHighlightRead {}
273enum DocumentHighlightWrite {}
274enum InputComposition {}
275
276#[derive(Copy, Clone, PartialEq, Eq)]
277pub enum Direction {
278 Prev,
279 Next,
280}
281
282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
283pub enum Navigated {
284 Yes,
285 No,
286}
287
288impl Navigated {
289 pub fn from_bool(yes: bool) -> Navigated {
290 if yes {
291 Navigated::Yes
292 } else {
293 Navigated::No
294 }
295 }
296}
297
298pub fn init_settings(cx: &mut AppContext) {
299 EditorSettings::register(cx);
300}
301
302pub fn init(cx: &mut AppContext) {
303 init_settings(cx);
304
305 workspace::register_project_item::<Editor>(cx);
306 workspace::FollowableViewRegistry::register::<Editor>(cx);
307 workspace::register_serializable_item::<Editor>(cx);
308
309 cx.observe_new_views(
310 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
311 workspace.register_action(Editor::new_file);
312 workspace.register_action(Editor::new_file_vertical);
313 workspace.register_action(Editor::new_file_horizontal);
314 },
315 )
316 .detach();
317
318 cx.on_action(move |_: &workspace::NewFile, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327 cx.on_action(move |_: &workspace::NewWindow, cx| {
328 let app_state = workspace::AppState::global(cx);
329 if let Some(app_state) = app_state.upgrade() {
330 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
331 Editor::new_file(workspace, &Default::default(), cx)
332 })
333 .detach();
334 }
335 });
336}
337
338pub struct SearchWithinRange;
339
340trait InvalidationRegion {
341 fn ranges(&self) -> &[Range<Anchor>];
342}
343
344#[derive(Clone, Debug, PartialEq)]
345pub enum SelectPhase {
346 Begin {
347 position: DisplayPoint,
348 add: bool,
349 click_count: usize,
350 },
351 BeginColumnar {
352 position: DisplayPoint,
353 reset: bool,
354 goal_column: u32,
355 },
356 Extend {
357 position: DisplayPoint,
358 click_count: usize,
359 },
360 Update {
361 position: DisplayPoint,
362 goal_column: u32,
363 scroll_delta: gpui::Point<f32>,
364 },
365 End,
366}
367
368#[derive(Clone, Debug)]
369pub enum SelectMode {
370 Character,
371 Word(Range<Anchor>),
372 Line(Range<Anchor>),
373 All,
374}
375
376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
377pub enum EditorMode {
378 SingleLine { auto_width: bool },
379 AutoHeight { max_lines: usize },
380 Full,
381}
382
383#[derive(Copy, Clone, Debug)]
384pub enum SoftWrap {
385 /// Prefer not to wrap at all.
386 ///
387 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
388 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
389 GitDiff,
390 /// Prefer a single line generally, unless an overly long line is encountered.
391 None,
392 /// Soft wrap lines that exceed the editor width.
393 EditorWidth,
394 /// Soft wrap lines at the preferred line length.
395 Column(u32),
396 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
397 Bounded(u32),
398}
399
400#[derive(Clone)]
401pub struct EditorStyle {
402 pub background: Hsla,
403 pub local_player: PlayerColor,
404 pub text: TextStyle,
405 pub scrollbar_width: Pixels,
406 pub syntax: Arc<SyntaxTheme>,
407 pub status: StatusColors,
408 pub inlay_hints_style: HighlightStyle,
409 pub suggestions_style: HighlightStyle,
410 pub unnecessary_code_fade: f32,
411}
412
413impl Default for EditorStyle {
414 fn default() -> Self {
415 Self {
416 background: Hsla::default(),
417 local_player: PlayerColor::default(),
418 text: TextStyle::default(),
419 scrollbar_width: Pixels::default(),
420 syntax: Default::default(),
421 // HACK: Status colors don't have a real default.
422 // We should look into removing the status colors from the editor
423 // style and retrieve them directly from the theme.
424 status: StatusColors::dark(),
425 inlay_hints_style: HighlightStyle::default(),
426 suggestions_style: HighlightStyle::default(),
427 unnecessary_code_fade: Default::default(),
428 }
429 }
430}
431
432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
433 let show_background = language_settings::language_settings(None, None, cx)
434 .inlay_hints
435 .show_background;
436
437 HighlightStyle {
438 color: Some(cx.theme().status().hint),
439 background_color: show_background.then(|| cx.theme().status().hint_background),
440 ..HighlightStyle::default()
441 }
442}
443
444type CompletionId = usize;
445
446#[derive(Clone, Debug)]
447struct CompletionState {
448 // render_inlay_ids represents the inlay hints that are inserted
449 // for rendering the inline completions. They may be discontinuous
450 // in the event that the completion provider returns some intersection
451 // with the existing content.
452 render_inlay_ids: Vec<InlayId>,
453 // text is the resulting rope that is inserted when the user accepts a completion.
454 text: Rope,
455 // position is the position of the cursor when the completion was triggered.
456 position: multi_buffer::Anchor,
457 // delete_range is the range of text that this completion state covers.
458 // if the completion is accepted, this range should be deleted.
459 delete_range: Option<Range<multi_buffer::Anchor>>,
460}
461
462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
463struct EditorActionId(usize);
464
465impl EditorActionId {
466 pub fn post_inc(&mut self) -> Self {
467 let answer = self.0;
468
469 *self = Self(answer + 1);
470
471 Self(answer)
472 }
473}
474
475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
477
478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
480
481#[derive(Default)]
482struct ScrollbarMarkerState {
483 scrollbar_size: Size<Pixels>,
484 dirty: bool,
485 markers: Arc<[PaintQuad]>,
486 pending_refresh: Option<Task<Result<()>>>,
487}
488
489impl ScrollbarMarkerState {
490 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
491 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
492 }
493}
494
495#[derive(Clone, Debug)]
496struct RunnableTasks {
497 templates: Vec<(TaskSourceKind, TaskTemplate)>,
498 offset: MultiBufferOffset,
499 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
500 column: u32,
501 // Values of all named captures, including those starting with '_'
502 extra_variables: HashMap<String, String>,
503 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
504 context_range: Range<BufferOffset>,
505}
506
507impl RunnableTasks {
508 fn resolve<'a>(
509 &'a self,
510 cx: &'a task::TaskContext,
511 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
512 self.templates.iter().filter_map(|(kind, template)| {
513 template
514 .resolve_task(&kind.to_id_base(), cx)
515 .map(|task| (kind.clone(), task))
516 })
517 }
518}
519
520#[derive(Clone)]
521struct ResolvedTasks {
522 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
523 position: Anchor,
524}
525#[derive(Copy, Clone, Debug)]
526struct MultiBufferOffset(usize);
527#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
528struct BufferOffset(usize);
529
530// Addons allow storing per-editor state in other crates (e.g. Vim)
531pub trait Addon: 'static {
532 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
533
534 fn to_any(&self) -> &dyn std::any::Any;
535}
536
537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
538///
539/// See the [module level documentation](self) for more information.
540pub struct Editor {
541 focus_handle: FocusHandle,
542 last_focused_descendant: Option<WeakFocusHandle>,
543 /// The text buffer being edited
544 buffer: Model<MultiBuffer>,
545 /// Map of how text in the buffer should be displayed.
546 /// Handles soft wraps, folds, fake inlay text insertions, etc.
547 pub display_map: Model<DisplayMap>,
548 pub selections: SelectionsCollection,
549 pub scroll_manager: ScrollManager,
550 /// When inline assist editors are linked, they all render cursors because
551 /// typing enters text into each of them, even the ones that aren't focused.
552 pub(crate) show_cursor_when_unfocused: bool,
553 columnar_selection_tail: Option<Anchor>,
554 add_selections_state: Option<AddSelectionsState>,
555 select_next_state: Option<SelectNextState>,
556 select_prev_state: Option<SelectNextState>,
557 selection_history: SelectionHistory,
558 autoclose_regions: Vec<AutocloseRegion>,
559 snippet_stack: InvalidationStack<SnippetState>,
560 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
561 ime_transaction: Option<TransactionId>,
562 active_diagnostics: Option<ActiveDiagnosticGroup>,
563 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
564
565 project: Option<Model<Project>>,
566 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
567 completion_provider: Option<Box<dyn CompletionProvider>>,
568 collaboration_hub: Option<Box<dyn CollaborationHub>>,
569 blink_manager: Model<BlinkManager>,
570 show_cursor_names: bool,
571 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
572 pub show_local_selections: bool,
573 mode: EditorMode,
574 show_breadcrumbs: bool,
575 show_gutter: bool,
576 show_line_numbers: Option<bool>,
577 use_relative_line_numbers: Option<bool>,
578 show_git_diff_gutter: Option<bool>,
579 show_code_actions: Option<bool>,
580 show_runnables: Option<bool>,
581 show_wrap_guides: Option<bool>,
582 show_indent_guides: Option<bool>,
583 placeholder_text: Option<Arc<str>>,
584 highlight_order: usize,
585 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
586 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
587 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
588 scrollbar_marker_state: ScrollbarMarkerState,
589 active_indent_guides_state: ActiveIndentGuidesState,
590 nav_history: Option<ItemNavHistory>,
591 context_menu: RwLock<Option<ContextMenu>>,
592 mouse_context_menu: Option<MouseContextMenu>,
593 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
594 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
595 signature_help_state: SignatureHelpState,
596 auto_signature_help: Option<bool>,
597 find_all_references_task_sources: Vec<Anchor>,
598 next_completion_id: CompletionId,
599 completion_documentation_pre_resolve_debounce: DebouncedDelay,
600 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
601 code_actions_task: Option<Task<Result<()>>>,
602 document_highlights_task: Option<Task<()>>,
603 linked_editing_range_task: Option<Task<Option<()>>>,
604 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
605 pending_rename: Option<RenameState>,
606 searchable: bool,
607 cursor_shape: CursorShape,
608 current_line_highlight: Option<CurrentLineHighlight>,
609 collapse_matches: bool,
610 autoindent_mode: Option<AutoindentMode>,
611 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
612 input_enabled: bool,
613 use_modal_editing: bool,
614 read_only: bool,
615 leader_peer_id: Option<PeerId>,
616 remote_id: Option<ViewId>,
617 hover_state: HoverState,
618 gutter_hovered: bool,
619 hovered_link_state: Option<HoveredLinkState>,
620 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
621 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
622 active_inline_completion: Option<CompletionState>,
623 // enable_inline_completions is a switch that Vim can use to disable
624 // inline completions based on its mode.
625 enable_inline_completions: bool,
626 show_inline_completions_override: Option<bool>,
627 inlay_hint_cache: InlayHintCache,
628 expanded_hunks: ExpandedHunks,
629 next_inlay_id: usize,
630 _subscriptions: Vec<Subscription>,
631 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
632 gutter_dimensions: GutterDimensions,
633 style: Option<EditorStyle>,
634 text_style_refinement: Option<TextStyleRefinement>,
635 next_editor_action_id: EditorActionId,
636 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
637 use_autoclose: bool,
638 use_auto_surround: bool,
639 auto_replace_emoji_shortcode: bool,
640 show_git_blame_gutter: bool,
641 show_git_blame_inline: bool,
642 show_git_blame_inline_delay_task: Option<Task<()>>,
643 git_blame_inline_enabled: bool,
644 serialize_dirty_buffers: bool,
645 show_selection_menu: Option<bool>,
646 blame: Option<Model<GitBlame>>,
647 blame_subscription: Option<Subscription>,
648 custom_context_menu: Option<
649 Box<
650 dyn 'static
651 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
652 >,
653 >,
654 last_bounds: Option<Bounds<Pixels>>,
655 expect_bounds_change: Option<Bounds<Pixels>>,
656 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
657 tasks_update_task: Option<Task<()>>,
658 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
659 breadcrumb_header: Option<String>,
660 focused_block: Option<FocusedBlock>,
661 next_scroll_position: NextScrollCursorCenterTopBottom,
662 addons: HashMap<TypeId, Box<dyn Addon>>,
663 _scroll_cursor_center_top_bottom_task: Task<()>,
664}
665
666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
667enum NextScrollCursorCenterTopBottom {
668 #[default]
669 Center,
670 Top,
671 Bottom,
672}
673
674impl NextScrollCursorCenterTopBottom {
675 fn next(&self) -> Self {
676 match self {
677 Self::Center => Self::Top,
678 Self::Top => Self::Bottom,
679 Self::Bottom => Self::Center,
680 }
681 }
682}
683
684#[derive(Clone)]
685pub struct EditorSnapshot {
686 pub mode: EditorMode,
687 show_gutter: bool,
688 show_line_numbers: Option<bool>,
689 show_git_diff_gutter: Option<bool>,
690 show_code_actions: Option<bool>,
691 show_runnables: Option<bool>,
692 git_blame_gutter_max_author_length: Option<usize>,
693 pub display_snapshot: DisplaySnapshot,
694 pub placeholder_text: Option<Arc<str>>,
695 is_focused: bool,
696 scroll_anchor: ScrollAnchor,
697 ongoing_scroll: OngoingScroll,
698 current_line_highlight: CurrentLineHighlight,
699 gutter_hovered: bool,
700}
701
702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
703
704#[derive(Default, Debug, Clone, Copy)]
705pub struct GutterDimensions {
706 pub left_padding: Pixels,
707 pub right_padding: Pixels,
708 pub width: Pixels,
709 pub margin: Pixels,
710 pub git_blame_entries_width: Option<Pixels>,
711}
712
713impl GutterDimensions {
714 /// The full width of the space taken up by the gutter.
715 pub fn full_width(&self) -> Pixels {
716 self.margin + self.width
717 }
718
719 /// The width of the space reserved for the fold indicators,
720 /// use alongside 'justify_end' and `gutter_width` to
721 /// right align content with the line numbers
722 pub fn fold_area_width(&self) -> Pixels {
723 self.margin + self.right_padding
724 }
725}
726
727#[derive(Debug)]
728pub struct RemoteSelection {
729 pub replica_id: ReplicaId,
730 pub selection: Selection<Anchor>,
731 pub cursor_shape: CursorShape,
732 pub peer_id: PeerId,
733 pub line_mode: bool,
734 pub participant_index: Option<ParticipantIndex>,
735 pub user_name: Option<SharedString>,
736}
737
738#[derive(Clone, Debug)]
739struct SelectionHistoryEntry {
740 selections: Arc<[Selection<Anchor>]>,
741 select_next_state: Option<SelectNextState>,
742 select_prev_state: Option<SelectNextState>,
743 add_selections_state: Option<AddSelectionsState>,
744}
745
746enum SelectionHistoryMode {
747 Normal,
748 Undoing,
749 Redoing,
750}
751
752#[derive(Clone, PartialEq, Eq, Hash)]
753struct HoveredCursor {
754 replica_id: u16,
755 selection_id: usize,
756}
757
758impl Default for SelectionHistoryMode {
759 fn default() -> Self {
760 Self::Normal
761 }
762}
763
764#[derive(Default)]
765struct SelectionHistory {
766 #[allow(clippy::type_complexity)]
767 selections_by_transaction:
768 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
769 mode: SelectionHistoryMode,
770 undo_stack: VecDeque<SelectionHistoryEntry>,
771 redo_stack: VecDeque<SelectionHistoryEntry>,
772}
773
774impl SelectionHistory {
775 fn insert_transaction(
776 &mut self,
777 transaction_id: TransactionId,
778 selections: Arc<[Selection<Anchor>]>,
779 ) {
780 self.selections_by_transaction
781 .insert(transaction_id, (selections, None));
782 }
783
784 #[allow(clippy::type_complexity)]
785 fn transaction(
786 &self,
787 transaction_id: TransactionId,
788 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
789 self.selections_by_transaction.get(&transaction_id)
790 }
791
792 #[allow(clippy::type_complexity)]
793 fn transaction_mut(
794 &mut self,
795 transaction_id: TransactionId,
796 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
797 self.selections_by_transaction.get_mut(&transaction_id)
798 }
799
800 fn push(&mut self, entry: SelectionHistoryEntry) {
801 if !entry.selections.is_empty() {
802 match self.mode {
803 SelectionHistoryMode::Normal => {
804 self.push_undo(entry);
805 self.redo_stack.clear();
806 }
807 SelectionHistoryMode::Undoing => self.push_redo(entry),
808 SelectionHistoryMode::Redoing => self.push_undo(entry),
809 }
810 }
811 }
812
813 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
814 if self
815 .undo_stack
816 .back()
817 .map_or(true, |e| e.selections != entry.selections)
818 {
819 self.undo_stack.push_back(entry);
820 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
821 self.undo_stack.pop_front();
822 }
823 }
824 }
825
826 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
827 if self
828 .redo_stack
829 .back()
830 .map_or(true, |e| e.selections != entry.selections)
831 {
832 self.redo_stack.push_back(entry);
833 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
834 self.redo_stack.pop_front();
835 }
836 }
837 }
838}
839
840struct RowHighlight {
841 index: usize,
842 range: Range<Anchor>,
843 color: Hsla,
844 should_autoscroll: bool,
845}
846
847#[derive(Clone, Debug)]
848struct AddSelectionsState {
849 above: bool,
850 stack: Vec<usize>,
851}
852
853#[derive(Clone)]
854struct SelectNextState {
855 query: AhoCorasick,
856 wordwise: bool,
857 done: bool,
858}
859
860impl std::fmt::Debug for SelectNextState {
861 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
862 f.debug_struct(std::any::type_name::<Self>())
863 .field("wordwise", &self.wordwise)
864 .field("done", &self.done)
865 .finish()
866 }
867}
868
869#[derive(Debug)]
870struct AutocloseRegion {
871 selection_id: usize,
872 range: Range<Anchor>,
873 pair: BracketPair,
874}
875
876#[derive(Debug)]
877struct SnippetState {
878 ranges: Vec<Vec<Range<Anchor>>>,
879 active_index: usize,
880}
881
882#[doc(hidden)]
883pub struct RenameState {
884 pub range: Range<Anchor>,
885 pub old_name: Arc<str>,
886 pub editor: View<Editor>,
887 block_id: CustomBlockId,
888}
889
890struct InvalidationStack<T>(Vec<T>);
891
892struct RegisteredInlineCompletionProvider {
893 provider: Arc<dyn InlineCompletionProviderHandle>,
894 _subscription: Subscription,
895}
896
897enum ContextMenu {
898 Completions(CompletionsMenu),
899 CodeActions(CodeActionsMenu),
900}
901
902impl ContextMenu {
903 fn select_first(
904 &mut self,
905 provider: Option<&dyn CompletionProvider>,
906 cx: &mut ViewContext<Editor>,
907 ) -> bool {
908 if self.visible() {
909 match self {
910 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
911 ContextMenu::CodeActions(menu) => menu.select_first(cx),
912 }
913 true
914 } else {
915 false
916 }
917 }
918
919 fn select_prev(
920 &mut self,
921 provider: Option<&dyn CompletionProvider>,
922 cx: &mut ViewContext<Editor>,
923 ) -> bool {
924 if self.visible() {
925 match self {
926 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
927 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
928 }
929 true
930 } else {
931 false
932 }
933 }
934
935 fn select_next(
936 &mut self,
937 provider: Option<&dyn CompletionProvider>,
938 cx: &mut ViewContext<Editor>,
939 ) -> bool {
940 if self.visible() {
941 match self {
942 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
943 ContextMenu::CodeActions(menu) => menu.select_next(cx),
944 }
945 true
946 } else {
947 false
948 }
949 }
950
951 fn select_last(
952 &mut self,
953 provider: Option<&dyn CompletionProvider>,
954 cx: &mut ViewContext<Editor>,
955 ) -> bool {
956 if self.visible() {
957 match self {
958 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
959 ContextMenu::CodeActions(menu) => menu.select_last(cx),
960 }
961 true
962 } else {
963 false
964 }
965 }
966
967 fn visible(&self) -> bool {
968 match self {
969 ContextMenu::Completions(menu) => menu.visible(),
970 ContextMenu::CodeActions(menu) => menu.visible(),
971 }
972 }
973
974 fn render(
975 &self,
976 cursor_position: DisplayPoint,
977 style: &EditorStyle,
978 max_height: Pixels,
979 workspace: Option<WeakView<Workspace>>,
980 cx: &mut ViewContext<Editor>,
981 ) -> (ContextMenuOrigin, AnyElement) {
982 match self {
983 ContextMenu::Completions(menu) => (
984 ContextMenuOrigin::EditorPoint(cursor_position),
985 menu.render(style, max_height, workspace, cx),
986 ),
987 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
988 }
989 }
990}
991
992enum ContextMenuOrigin {
993 EditorPoint(DisplayPoint),
994 GutterIndicator(DisplayRow),
995}
996
997#[derive(Clone)]
998struct CompletionsMenu {
999 id: CompletionId,
1000 sort_completions: bool,
1001 initial_position: Anchor,
1002 buffer: Model<Buffer>,
1003 completions: Arc<RwLock<Box<[Completion]>>>,
1004 match_candidates: Arc<[StringMatchCandidate]>,
1005 matches: Arc<[StringMatch]>,
1006 selected_item: usize,
1007 scroll_handle: UniformListScrollHandle,
1008 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
1009}
1010
1011impl CompletionsMenu {
1012 fn select_first(
1013 &mut self,
1014 provider: Option<&dyn CompletionProvider>,
1015 cx: &mut ViewContext<Editor>,
1016 ) {
1017 self.selected_item = 0;
1018 self.scroll_handle.scroll_to_item(self.selected_item);
1019 self.attempt_resolve_selected_completion_documentation(provider, cx);
1020 cx.notify();
1021 }
1022
1023 fn select_prev(
1024 &mut self,
1025 provider: Option<&dyn CompletionProvider>,
1026 cx: &mut ViewContext<Editor>,
1027 ) {
1028 if self.selected_item > 0 {
1029 self.selected_item -= 1;
1030 } else {
1031 self.selected_item = self.matches.len() - 1;
1032 }
1033 self.scroll_handle.scroll_to_item(self.selected_item);
1034 self.attempt_resolve_selected_completion_documentation(provider, cx);
1035 cx.notify();
1036 }
1037
1038 fn select_next(
1039 &mut self,
1040 provider: Option<&dyn CompletionProvider>,
1041 cx: &mut ViewContext<Editor>,
1042 ) {
1043 if self.selected_item + 1 < self.matches.len() {
1044 self.selected_item += 1;
1045 } else {
1046 self.selected_item = 0;
1047 }
1048 self.scroll_handle.scroll_to_item(self.selected_item);
1049 self.attempt_resolve_selected_completion_documentation(provider, cx);
1050 cx.notify();
1051 }
1052
1053 fn select_last(
1054 &mut self,
1055 provider: Option<&dyn CompletionProvider>,
1056 cx: &mut ViewContext<Editor>,
1057 ) {
1058 self.selected_item = self.matches.len() - 1;
1059 self.scroll_handle.scroll_to_item(self.selected_item);
1060 self.attempt_resolve_selected_completion_documentation(provider, cx);
1061 cx.notify();
1062 }
1063
1064 fn pre_resolve_completion_documentation(
1065 buffer: Model<Buffer>,
1066 completions: Arc<RwLock<Box<[Completion]>>>,
1067 matches: Arc<[StringMatch]>,
1068 editor: &Editor,
1069 cx: &mut ViewContext<Editor>,
1070 ) -> Task<()> {
1071 let settings = EditorSettings::get_global(cx);
1072 if !settings.show_completion_documentation {
1073 return Task::ready(());
1074 }
1075
1076 let Some(provider) = editor.completion_provider.as_ref() else {
1077 return Task::ready(());
1078 };
1079
1080 let resolve_task = provider.resolve_completions(
1081 buffer,
1082 matches.iter().map(|m| m.candidate_id).collect(),
1083 completions.clone(),
1084 cx,
1085 );
1086
1087 cx.spawn(move |this, mut cx| async move {
1088 if let Some(true) = resolve_task.await.log_err() {
1089 this.update(&mut cx, |_, cx| cx.notify()).ok();
1090 }
1091 })
1092 }
1093
1094 fn attempt_resolve_selected_completion_documentation(
1095 &mut self,
1096 provider: Option<&dyn CompletionProvider>,
1097 cx: &mut ViewContext<Editor>,
1098 ) {
1099 let settings = EditorSettings::get_global(cx);
1100 if !settings.show_completion_documentation {
1101 return;
1102 }
1103
1104 let completion_index = self.matches[self.selected_item].candidate_id;
1105 let Some(provider) = provider else {
1106 return;
1107 };
1108
1109 let resolve_task = provider.resolve_completions(
1110 self.buffer.clone(),
1111 vec![completion_index],
1112 self.completions.clone(),
1113 cx,
1114 );
1115
1116 let delay_ms =
1117 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1118 let delay = Duration::from_millis(delay_ms);
1119
1120 self.selected_completion_documentation_resolve_debounce
1121 .lock()
1122 .fire_new(delay, cx, |_, cx| {
1123 cx.spawn(move |this, mut cx| async move {
1124 if let Some(true) = resolve_task.await.log_err() {
1125 this.update(&mut cx, |_, cx| cx.notify()).ok();
1126 }
1127 })
1128 });
1129 }
1130
1131 fn visible(&self) -> bool {
1132 !self.matches.is_empty()
1133 }
1134
1135 fn render(
1136 &self,
1137 style: &EditorStyle,
1138 max_height: Pixels,
1139 workspace: Option<WeakView<Workspace>>,
1140 cx: &mut ViewContext<Editor>,
1141 ) -> AnyElement {
1142 let settings = EditorSettings::get_global(cx);
1143 let show_completion_documentation = settings.show_completion_documentation;
1144
1145 let widest_completion_ix = self
1146 .matches
1147 .iter()
1148 .enumerate()
1149 .max_by_key(|(_, mat)| {
1150 let completions = self.completions.read();
1151 let completion = &completions[mat.candidate_id];
1152 let documentation = &completion.documentation;
1153
1154 let mut len = completion.label.text.chars().count();
1155 if let Some(Documentation::SingleLine(text)) = documentation {
1156 if show_completion_documentation {
1157 len += text.chars().count();
1158 }
1159 }
1160
1161 len
1162 })
1163 .map(|(ix, _)| ix);
1164
1165 let completions = self.completions.clone();
1166 let matches = self.matches.clone();
1167 let selected_item = self.selected_item;
1168 let style = style.clone();
1169
1170 let multiline_docs = if show_completion_documentation {
1171 let mat = &self.matches[selected_item];
1172 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1173 Some(Documentation::MultiLinePlainText(text)) => {
1174 Some(div().child(SharedString::from(text.clone())))
1175 }
1176 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1177 Some(div().child(render_parsed_markdown(
1178 "completions_markdown",
1179 parsed,
1180 &style,
1181 workspace,
1182 cx,
1183 )))
1184 }
1185 _ => None,
1186 };
1187 multiline_docs.map(|div| {
1188 div.id("multiline_docs")
1189 .max_h(max_height)
1190 .flex_1()
1191 .px_1p5()
1192 .py_1()
1193 .min_w(px(260.))
1194 .max_w(px(640.))
1195 .w(px(500.))
1196 .overflow_y_scroll()
1197 .occlude()
1198 })
1199 } else {
1200 None
1201 };
1202
1203 let list = uniform_list(
1204 cx.view().clone(),
1205 "completions",
1206 matches.len(),
1207 move |_editor, range, cx| {
1208 let start_ix = range.start;
1209 let completions_guard = completions.read();
1210
1211 matches[range]
1212 .iter()
1213 .enumerate()
1214 .map(|(ix, mat)| {
1215 let item_ix = start_ix + ix;
1216 let candidate_id = mat.candidate_id;
1217 let completion = &completions_guard[candidate_id];
1218
1219 let documentation = if show_completion_documentation {
1220 &completion.documentation
1221 } else {
1222 &None
1223 };
1224
1225 let highlights = gpui::combine_highlights(
1226 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1227 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1228 |(range, mut highlight)| {
1229 // Ignore font weight for syntax highlighting, as we'll use it
1230 // for fuzzy matches.
1231 highlight.font_weight = None;
1232
1233 if completion.lsp_completion.deprecated.unwrap_or(false) {
1234 highlight.strikethrough = Some(StrikethroughStyle {
1235 thickness: 1.0.into(),
1236 ..Default::default()
1237 });
1238 highlight.color = Some(cx.theme().colors().text_muted);
1239 }
1240
1241 (range, highlight)
1242 },
1243 ),
1244 );
1245 let completion_label = StyledText::new(completion.label.text.clone())
1246 .with_highlights(&style.text, highlights);
1247 let documentation_label =
1248 if let Some(Documentation::SingleLine(text)) = documentation {
1249 if text.trim().is_empty() {
1250 None
1251 } else {
1252 Some(
1253 Label::new(text.clone())
1254 .ml_4()
1255 .size(LabelSize::Small)
1256 .color(Color::Muted),
1257 )
1258 }
1259 } else {
1260 None
1261 };
1262
1263 let color_swatch = completion
1264 .color()
1265 .map(|color| div().size_4().bg(color).rounded_sm());
1266
1267 div().min_w(px(220.)).max_w(px(540.)).child(
1268 ListItem::new(mat.candidate_id)
1269 .inset(true)
1270 .selected(item_ix == selected_item)
1271 .on_click(cx.listener(move |editor, _event, cx| {
1272 cx.stop_propagation();
1273 if let Some(task) = editor.confirm_completion(
1274 &ConfirmCompletion {
1275 item_ix: Some(item_ix),
1276 },
1277 cx,
1278 ) {
1279 task.detach_and_log_err(cx)
1280 }
1281 }))
1282 .start_slot::<Div>(color_swatch)
1283 .child(h_flex().overflow_hidden().child(completion_label))
1284 .end_slot::<Label>(documentation_label),
1285 )
1286 })
1287 .collect()
1288 },
1289 )
1290 .occlude()
1291 .max_h(max_height)
1292 .track_scroll(self.scroll_handle.clone())
1293 .with_width_from_item(widest_completion_ix)
1294 .with_sizing_behavior(ListSizingBehavior::Infer);
1295
1296 Popover::new()
1297 .child(list)
1298 .when_some(multiline_docs, |popover, multiline_docs| {
1299 popover.aside(multiline_docs)
1300 })
1301 .into_any_element()
1302 }
1303
1304 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1305 let mut matches = if let Some(query) = query {
1306 fuzzy::match_strings(
1307 &self.match_candidates,
1308 query,
1309 query.chars().any(|c| c.is_uppercase()),
1310 100,
1311 &Default::default(),
1312 executor,
1313 )
1314 .await
1315 } else {
1316 self.match_candidates
1317 .iter()
1318 .enumerate()
1319 .map(|(candidate_id, candidate)| StringMatch {
1320 candidate_id,
1321 score: Default::default(),
1322 positions: Default::default(),
1323 string: candidate.string.clone(),
1324 })
1325 .collect()
1326 };
1327
1328 // Remove all candidates where the query's start does not match the start of any word in the candidate
1329 if let Some(query) = query {
1330 if let Some(query_start) = query.chars().next() {
1331 matches.retain(|string_match| {
1332 split_words(&string_match.string).any(|word| {
1333 // Check that the first codepoint of the word as lowercase matches the first
1334 // codepoint of the query as lowercase
1335 word.chars()
1336 .flat_map(|codepoint| codepoint.to_lowercase())
1337 .zip(query_start.to_lowercase())
1338 .all(|(word_cp, query_cp)| word_cp == query_cp)
1339 })
1340 });
1341 }
1342 }
1343
1344 let completions = self.completions.read();
1345 if self.sort_completions {
1346 matches.sort_unstable_by_key(|mat| {
1347 // We do want to strike a balance here between what the language server tells us
1348 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1349 // `Creat` and there is a local variable called `CreateComponent`).
1350 // So what we do is: we bucket all matches into two buckets
1351 // - Strong matches
1352 // - Weak matches
1353 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1354 // and the Weak matches are the rest.
1355 //
1356 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1357 // matches, we prefer language-server sort_text first.
1358 //
1359 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1360 // Rest of the matches(weak) can be sorted as language-server expects.
1361
1362 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1363 enum MatchScore<'a> {
1364 Strong {
1365 score: Reverse<OrderedFloat<f64>>,
1366 sort_text: Option<&'a str>,
1367 sort_key: (usize, &'a str),
1368 },
1369 Weak {
1370 sort_text: Option<&'a str>,
1371 score: Reverse<OrderedFloat<f64>>,
1372 sort_key: (usize, &'a str),
1373 },
1374 }
1375
1376 let completion = &completions[mat.candidate_id];
1377 let sort_key = completion.sort_key();
1378 let sort_text = completion.lsp_completion.sort_text.as_deref();
1379 let score = Reverse(OrderedFloat(mat.score));
1380
1381 if mat.score >= 0.2 {
1382 MatchScore::Strong {
1383 score,
1384 sort_text,
1385 sort_key,
1386 }
1387 } else {
1388 MatchScore::Weak {
1389 sort_text,
1390 score,
1391 sort_key,
1392 }
1393 }
1394 });
1395 }
1396
1397 for mat in &mut matches {
1398 let completion = &completions[mat.candidate_id];
1399 mat.string.clone_from(&completion.label.text);
1400 for position in &mut mat.positions {
1401 *position += completion.label.filter_range.start;
1402 }
1403 }
1404 drop(completions);
1405
1406 self.matches = matches.into();
1407 self.selected_item = 0;
1408 }
1409}
1410
1411struct AvailableCodeAction {
1412 excerpt_id: ExcerptId,
1413 action: CodeAction,
1414 provider: Arc<dyn CodeActionProvider>,
1415}
1416
1417#[derive(Clone)]
1418struct CodeActionContents {
1419 tasks: Option<Arc<ResolvedTasks>>,
1420 actions: Option<Arc<[AvailableCodeAction]>>,
1421}
1422
1423impl CodeActionContents {
1424 fn len(&self) -> usize {
1425 match (&self.tasks, &self.actions) {
1426 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1427 (Some(tasks), None) => tasks.templates.len(),
1428 (None, Some(actions)) => actions.len(),
1429 (None, None) => 0,
1430 }
1431 }
1432
1433 fn is_empty(&self) -> bool {
1434 match (&self.tasks, &self.actions) {
1435 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1436 (Some(tasks), None) => tasks.templates.is_empty(),
1437 (None, Some(actions)) => actions.is_empty(),
1438 (None, None) => true,
1439 }
1440 }
1441
1442 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1443 self.tasks
1444 .iter()
1445 .flat_map(|tasks| {
1446 tasks
1447 .templates
1448 .iter()
1449 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1450 })
1451 .chain(self.actions.iter().flat_map(|actions| {
1452 actions.iter().map(|available| CodeActionsItem::CodeAction {
1453 excerpt_id: available.excerpt_id,
1454 action: available.action.clone(),
1455 provider: available.provider.clone(),
1456 })
1457 }))
1458 }
1459 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1460 match (&self.tasks, &self.actions) {
1461 (Some(tasks), Some(actions)) => {
1462 if index < tasks.templates.len() {
1463 tasks
1464 .templates
1465 .get(index)
1466 .cloned()
1467 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1468 } else {
1469 actions.get(index - tasks.templates.len()).map(|available| {
1470 CodeActionsItem::CodeAction {
1471 excerpt_id: available.excerpt_id,
1472 action: available.action.clone(),
1473 provider: available.provider.clone(),
1474 }
1475 })
1476 }
1477 }
1478 (Some(tasks), None) => tasks
1479 .templates
1480 .get(index)
1481 .cloned()
1482 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1483 (None, Some(actions)) => {
1484 actions
1485 .get(index)
1486 .map(|available| CodeActionsItem::CodeAction {
1487 excerpt_id: available.excerpt_id,
1488 action: available.action.clone(),
1489 provider: available.provider.clone(),
1490 })
1491 }
1492 (None, None) => None,
1493 }
1494 }
1495}
1496
1497#[allow(clippy::large_enum_variant)]
1498#[derive(Clone)]
1499enum CodeActionsItem {
1500 Task(TaskSourceKind, ResolvedTask),
1501 CodeAction {
1502 excerpt_id: ExcerptId,
1503 action: CodeAction,
1504 provider: Arc<dyn CodeActionProvider>,
1505 },
1506}
1507
1508impl CodeActionsItem {
1509 fn as_task(&self) -> Option<&ResolvedTask> {
1510 let Self::Task(_, task) = self else {
1511 return None;
1512 };
1513 Some(task)
1514 }
1515 fn as_code_action(&self) -> Option<&CodeAction> {
1516 let Self::CodeAction { action, .. } = self else {
1517 return None;
1518 };
1519 Some(action)
1520 }
1521 fn label(&self) -> String {
1522 match self {
1523 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1524 Self::Task(_, task) => task.resolved_label.clone(),
1525 }
1526 }
1527}
1528
1529struct CodeActionsMenu {
1530 actions: CodeActionContents,
1531 buffer: Model<Buffer>,
1532 selected_item: usize,
1533 scroll_handle: UniformListScrollHandle,
1534 deployed_from_indicator: Option<DisplayRow>,
1535}
1536
1537impl CodeActionsMenu {
1538 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1539 self.selected_item = 0;
1540 self.scroll_handle.scroll_to_item(self.selected_item);
1541 cx.notify()
1542 }
1543
1544 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1545 if self.selected_item > 0 {
1546 self.selected_item -= 1;
1547 } else {
1548 self.selected_item = self.actions.len() - 1;
1549 }
1550 self.scroll_handle.scroll_to_item(self.selected_item);
1551 cx.notify();
1552 }
1553
1554 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1555 if self.selected_item + 1 < self.actions.len() {
1556 self.selected_item += 1;
1557 } else {
1558 self.selected_item = 0;
1559 }
1560 self.scroll_handle.scroll_to_item(self.selected_item);
1561 cx.notify();
1562 }
1563
1564 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1565 self.selected_item = self.actions.len() - 1;
1566 self.scroll_handle.scroll_to_item(self.selected_item);
1567 cx.notify()
1568 }
1569
1570 fn visible(&self) -> bool {
1571 !self.actions.is_empty()
1572 }
1573
1574 fn render(
1575 &self,
1576 cursor_position: DisplayPoint,
1577 _style: &EditorStyle,
1578 max_height: Pixels,
1579 cx: &mut ViewContext<Editor>,
1580 ) -> (ContextMenuOrigin, AnyElement) {
1581 let actions = self.actions.clone();
1582 let selected_item = self.selected_item;
1583 let element = uniform_list(
1584 cx.view().clone(),
1585 "code_actions_menu",
1586 self.actions.len(),
1587 move |_this, range, cx| {
1588 actions
1589 .iter()
1590 .skip(range.start)
1591 .take(range.end - range.start)
1592 .enumerate()
1593 .map(|(ix, action)| {
1594 let item_ix = range.start + ix;
1595 let selected = selected_item == item_ix;
1596 let colors = cx.theme().colors();
1597 div()
1598 .px_1()
1599 .rounded_md()
1600 .text_color(colors.text)
1601 .when(selected, |style| {
1602 style
1603 .bg(colors.element_active)
1604 .text_color(colors.text_accent)
1605 })
1606 .hover(|style| {
1607 style
1608 .bg(colors.element_hover)
1609 .text_color(colors.text_accent)
1610 })
1611 .whitespace_nowrap()
1612 .when_some(action.as_code_action(), |this, action| {
1613 this.on_mouse_down(
1614 MouseButton::Left,
1615 cx.listener(move |editor, _, cx| {
1616 cx.stop_propagation();
1617 if let Some(task) = editor.confirm_code_action(
1618 &ConfirmCodeAction {
1619 item_ix: Some(item_ix),
1620 },
1621 cx,
1622 ) {
1623 task.detach_and_log_err(cx)
1624 }
1625 }),
1626 )
1627 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1628 .child(SharedString::from(action.lsp_action.title.clone()))
1629 })
1630 .when_some(action.as_task(), |this, task| {
1631 this.on_mouse_down(
1632 MouseButton::Left,
1633 cx.listener(move |editor, _, cx| {
1634 cx.stop_propagation();
1635 if let Some(task) = editor.confirm_code_action(
1636 &ConfirmCodeAction {
1637 item_ix: Some(item_ix),
1638 },
1639 cx,
1640 ) {
1641 task.detach_and_log_err(cx)
1642 }
1643 }),
1644 )
1645 .child(SharedString::from(task.resolved_label.clone()))
1646 })
1647 })
1648 .collect()
1649 },
1650 )
1651 .elevation_1(cx)
1652 .p_1()
1653 .max_h(max_height)
1654 .occlude()
1655 .track_scroll(self.scroll_handle.clone())
1656 .with_width_from_item(
1657 self.actions
1658 .iter()
1659 .enumerate()
1660 .max_by_key(|(_, action)| match action {
1661 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1662 CodeActionsItem::CodeAction { action, .. } => {
1663 action.lsp_action.title.chars().count()
1664 }
1665 })
1666 .map(|(ix, _)| ix),
1667 )
1668 .with_sizing_behavior(ListSizingBehavior::Infer)
1669 .into_any_element();
1670
1671 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1672 ContextMenuOrigin::GutterIndicator(row)
1673 } else {
1674 ContextMenuOrigin::EditorPoint(cursor_position)
1675 };
1676
1677 (cursor_position, element)
1678 }
1679}
1680
1681#[derive(Debug)]
1682struct ActiveDiagnosticGroup {
1683 primary_range: Range<Anchor>,
1684 primary_message: String,
1685 group_id: usize,
1686 blocks: HashMap<CustomBlockId, Diagnostic>,
1687 is_valid: bool,
1688}
1689
1690#[derive(Serialize, Deserialize, Clone, Debug)]
1691pub struct ClipboardSelection {
1692 pub len: usize,
1693 pub is_entire_line: bool,
1694 pub first_line_indent: u32,
1695}
1696
1697#[derive(Debug)]
1698pub(crate) struct NavigationData {
1699 cursor_anchor: Anchor,
1700 cursor_position: Point,
1701 scroll_anchor: ScrollAnchor,
1702 scroll_top_row: u32,
1703}
1704
1705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1706pub enum GotoDefinitionKind {
1707 Symbol,
1708 Declaration,
1709 Type,
1710 Implementation,
1711}
1712
1713#[derive(Debug, Clone)]
1714enum InlayHintRefreshReason {
1715 Toggle(bool),
1716 SettingsChange(InlayHintSettings),
1717 NewLinesShown,
1718 BufferEdited(HashSet<Arc<Language>>),
1719 RefreshRequested,
1720 ExcerptsRemoved(Vec<ExcerptId>),
1721}
1722
1723impl InlayHintRefreshReason {
1724 fn description(&self) -> &'static str {
1725 match self {
1726 Self::Toggle(_) => "toggle",
1727 Self::SettingsChange(_) => "settings change",
1728 Self::NewLinesShown => "new lines shown",
1729 Self::BufferEdited(_) => "buffer edited",
1730 Self::RefreshRequested => "refresh requested",
1731 Self::ExcerptsRemoved(_) => "excerpts removed",
1732 }
1733 }
1734}
1735
1736pub(crate) struct FocusedBlock {
1737 id: BlockId,
1738 focus_handle: WeakFocusHandle,
1739}
1740
1741impl Editor {
1742 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1743 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1744 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1745 Self::new(
1746 EditorMode::SingleLine { auto_width: false },
1747 buffer,
1748 None,
1749 false,
1750 cx,
1751 )
1752 }
1753
1754 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1755 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1756 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1757 Self::new(EditorMode::Full, buffer, None, false, cx)
1758 }
1759
1760 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1761 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1762 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1763 Self::new(
1764 EditorMode::SingleLine { auto_width: true },
1765 buffer,
1766 None,
1767 false,
1768 cx,
1769 )
1770 }
1771
1772 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1773 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1774 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1775 Self::new(
1776 EditorMode::AutoHeight { max_lines },
1777 buffer,
1778 None,
1779 false,
1780 cx,
1781 )
1782 }
1783
1784 pub fn for_buffer(
1785 buffer: Model<Buffer>,
1786 project: Option<Model<Project>>,
1787 cx: &mut ViewContext<Self>,
1788 ) -> Self {
1789 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1790 Self::new(EditorMode::Full, buffer, project, false, cx)
1791 }
1792
1793 pub fn for_multibuffer(
1794 buffer: Model<MultiBuffer>,
1795 project: Option<Model<Project>>,
1796 show_excerpt_controls: bool,
1797 cx: &mut ViewContext<Self>,
1798 ) -> Self {
1799 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1800 }
1801
1802 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1803 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1804 let mut clone = Self::new(
1805 self.mode,
1806 self.buffer.clone(),
1807 self.project.clone(),
1808 show_excerpt_controls,
1809 cx,
1810 );
1811 self.display_map.update(cx, |display_map, cx| {
1812 let snapshot = display_map.snapshot(cx);
1813 clone.display_map.update(cx, |display_map, cx| {
1814 display_map.set_state(&snapshot, cx);
1815 });
1816 });
1817 clone.selections.clone_state(&self.selections);
1818 clone.scroll_manager.clone_state(&self.scroll_manager);
1819 clone.searchable = self.searchable;
1820 clone
1821 }
1822
1823 pub fn new(
1824 mode: EditorMode,
1825 buffer: Model<MultiBuffer>,
1826 project: Option<Model<Project>>,
1827 show_excerpt_controls: bool,
1828 cx: &mut ViewContext<Self>,
1829 ) -> Self {
1830 let style = cx.text_style();
1831 let font_size = style.font_size.to_pixels(cx.rem_size());
1832 let editor = cx.view().downgrade();
1833 let fold_placeholder = FoldPlaceholder {
1834 constrain_width: true,
1835 render: Arc::new(move |fold_id, fold_range, cx| {
1836 let editor = editor.clone();
1837 div()
1838 .id(fold_id)
1839 .bg(cx.theme().colors().ghost_element_background)
1840 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1841 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1842 .rounded_sm()
1843 .size_full()
1844 .cursor_pointer()
1845 .child("⋯")
1846 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1847 .on_click(move |_, cx| {
1848 editor
1849 .update(cx, |editor, cx| {
1850 editor.unfold_ranges(
1851 [fold_range.start..fold_range.end],
1852 true,
1853 false,
1854 cx,
1855 );
1856 cx.stop_propagation();
1857 })
1858 .ok();
1859 })
1860 .into_any()
1861 }),
1862 merge_adjacent: true,
1863 };
1864 let display_map = cx.new_model(|cx| {
1865 DisplayMap::new(
1866 buffer.clone(),
1867 style.font(),
1868 font_size,
1869 None,
1870 show_excerpt_controls,
1871 FILE_HEADER_HEIGHT,
1872 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1873 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1874 fold_placeholder,
1875 cx,
1876 )
1877 });
1878
1879 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1880
1881 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1882
1883 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1884 .then(|| language_settings::SoftWrap::None);
1885
1886 let mut project_subscriptions = Vec::new();
1887 if mode == EditorMode::Full {
1888 if let Some(project) = project.as_ref() {
1889 if buffer.read(cx).is_singleton() {
1890 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1891 cx.emit(EditorEvent::TitleChanged);
1892 }));
1893 }
1894 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1895 if let project::Event::RefreshInlayHints = event {
1896 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1897 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1898 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1899 let focus_handle = editor.focus_handle(cx);
1900 if focus_handle.is_focused(cx) {
1901 let snapshot = buffer.read(cx).snapshot();
1902 for (range, snippet) in snippet_edits {
1903 let editor_range =
1904 language::range_from_lsp(*range).to_offset(&snapshot);
1905 editor
1906 .insert_snippet(&[editor_range], snippet.clone(), cx)
1907 .ok();
1908 }
1909 }
1910 }
1911 }
1912 }));
1913 if let Some(task_inventory) = project
1914 .read(cx)
1915 .task_store()
1916 .read(cx)
1917 .task_inventory()
1918 .cloned()
1919 {
1920 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1921 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1922 }));
1923 }
1924 }
1925 }
1926
1927 let inlay_hint_settings = inlay_hint_settings(
1928 selections.newest_anchor().head(),
1929 &buffer.read(cx).snapshot(cx),
1930 cx,
1931 );
1932 let focus_handle = cx.focus_handle();
1933 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1934 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1935 .detach();
1936 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1937 .detach();
1938 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1939
1940 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1941 Some(false)
1942 } else {
1943 None
1944 };
1945
1946 let mut code_action_providers = Vec::new();
1947 if let Some(project) = project.clone() {
1948 code_action_providers.push(Arc::new(project) as Arc<_>);
1949 }
1950
1951 let mut this = Self {
1952 focus_handle,
1953 show_cursor_when_unfocused: false,
1954 last_focused_descendant: None,
1955 buffer: buffer.clone(),
1956 display_map: display_map.clone(),
1957 selections,
1958 scroll_manager: ScrollManager::new(cx),
1959 columnar_selection_tail: None,
1960 add_selections_state: None,
1961 select_next_state: None,
1962 select_prev_state: None,
1963 selection_history: Default::default(),
1964 autoclose_regions: Default::default(),
1965 snippet_stack: Default::default(),
1966 select_larger_syntax_node_stack: Vec::new(),
1967 ime_transaction: Default::default(),
1968 active_diagnostics: None,
1969 soft_wrap_mode_override,
1970 completion_provider: project.clone().map(|project| Box::new(project) as _),
1971 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1972 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1973 project,
1974 blink_manager: blink_manager.clone(),
1975 show_local_selections: true,
1976 mode,
1977 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1978 show_gutter: mode == EditorMode::Full,
1979 show_line_numbers: None,
1980 use_relative_line_numbers: None,
1981 show_git_diff_gutter: None,
1982 show_code_actions: None,
1983 show_runnables: None,
1984 show_wrap_guides: None,
1985 show_indent_guides,
1986 placeholder_text: None,
1987 highlight_order: 0,
1988 highlighted_rows: HashMap::default(),
1989 background_highlights: Default::default(),
1990 gutter_highlights: TreeMap::default(),
1991 scrollbar_marker_state: ScrollbarMarkerState::default(),
1992 active_indent_guides_state: ActiveIndentGuidesState::default(),
1993 nav_history: None,
1994 context_menu: RwLock::new(None),
1995 mouse_context_menu: None,
1996 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1997 completion_tasks: Default::default(),
1998 signature_help_state: SignatureHelpState::default(),
1999 auto_signature_help: None,
2000 find_all_references_task_sources: Vec::new(),
2001 next_completion_id: 0,
2002 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2003 next_inlay_id: 0,
2004 code_action_providers,
2005 available_code_actions: Default::default(),
2006 code_actions_task: Default::default(),
2007 document_highlights_task: Default::default(),
2008 linked_editing_range_task: Default::default(),
2009 pending_rename: Default::default(),
2010 searchable: true,
2011 cursor_shape: EditorSettings::get_global(cx)
2012 .cursor_shape
2013 .unwrap_or_default(),
2014 current_line_highlight: None,
2015 autoindent_mode: Some(AutoindentMode::EachLine),
2016 collapse_matches: false,
2017 workspace: None,
2018 input_enabled: true,
2019 use_modal_editing: mode == EditorMode::Full,
2020 read_only: false,
2021 use_autoclose: true,
2022 use_auto_surround: true,
2023 auto_replace_emoji_shortcode: false,
2024 leader_peer_id: None,
2025 remote_id: None,
2026 hover_state: Default::default(),
2027 hovered_link_state: Default::default(),
2028 inline_completion_provider: None,
2029 active_inline_completion: None,
2030 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2031 expanded_hunks: ExpandedHunks::default(),
2032 gutter_hovered: false,
2033 pixel_position_of_newest_cursor: None,
2034 last_bounds: None,
2035 expect_bounds_change: None,
2036 gutter_dimensions: GutterDimensions::default(),
2037 style: None,
2038 show_cursor_names: false,
2039 hovered_cursors: Default::default(),
2040 next_editor_action_id: EditorActionId::default(),
2041 editor_actions: Rc::default(),
2042 show_inline_completions_override: None,
2043 enable_inline_completions: true,
2044 custom_context_menu: None,
2045 show_git_blame_gutter: false,
2046 show_git_blame_inline: false,
2047 show_selection_menu: None,
2048 show_git_blame_inline_delay_task: None,
2049 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2050 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2051 .session
2052 .restore_unsaved_buffers,
2053 blame: None,
2054 blame_subscription: None,
2055 tasks: Default::default(),
2056 _subscriptions: vec![
2057 cx.observe(&buffer, Self::on_buffer_changed),
2058 cx.subscribe(&buffer, Self::on_buffer_event),
2059 cx.observe(&display_map, Self::on_display_map_changed),
2060 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2061 cx.observe_global::<SettingsStore>(Self::settings_changed),
2062 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2063 cx.observe_window_activation(|editor, cx| {
2064 let active = cx.is_window_active();
2065 editor.blink_manager.update(cx, |blink_manager, cx| {
2066 if active {
2067 blink_manager.enable(cx);
2068 } else {
2069 blink_manager.disable(cx);
2070 }
2071 });
2072 }),
2073 ],
2074 tasks_update_task: None,
2075 linked_edit_ranges: Default::default(),
2076 previous_search_ranges: None,
2077 breadcrumb_header: None,
2078 focused_block: None,
2079 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2080 addons: HashMap::default(),
2081 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2082 text_style_refinement: None,
2083 };
2084 this.tasks_update_task = Some(this.refresh_runnables(cx));
2085 this._subscriptions.extend(project_subscriptions);
2086
2087 this.end_selection(cx);
2088 this.scroll_manager.show_scrollbar(cx);
2089
2090 if mode == EditorMode::Full {
2091 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2092 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2093
2094 if this.git_blame_inline_enabled {
2095 this.git_blame_inline_enabled = true;
2096 this.start_git_blame_inline(false, cx);
2097 }
2098 }
2099
2100 this.report_editor_event("open", None, cx);
2101 this
2102 }
2103
2104 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2105 self.mouse_context_menu
2106 .as_ref()
2107 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2108 }
2109
2110 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2111 let mut key_context = KeyContext::new_with_defaults();
2112 key_context.add("Editor");
2113 let mode = match self.mode {
2114 EditorMode::SingleLine { .. } => "single_line",
2115 EditorMode::AutoHeight { .. } => "auto_height",
2116 EditorMode::Full => "full",
2117 };
2118
2119 if EditorSettings::jupyter_enabled(cx) {
2120 key_context.add("jupyter");
2121 }
2122
2123 key_context.set("mode", mode);
2124 if self.pending_rename.is_some() {
2125 key_context.add("renaming");
2126 }
2127 if self.context_menu_visible() {
2128 match self.context_menu.read().as_ref() {
2129 Some(ContextMenu::Completions(_)) => {
2130 key_context.add("menu");
2131 key_context.add("showing_completions")
2132 }
2133 Some(ContextMenu::CodeActions(_)) => {
2134 key_context.add("menu");
2135 key_context.add("showing_code_actions")
2136 }
2137 None => {}
2138 }
2139 }
2140
2141 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2142 if !self.focus_handle(cx).contains_focused(cx)
2143 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2144 {
2145 for addon in self.addons.values() {
2146 addon.extend_key_context(&mut key_context, cx)
2147 }
2148 }
2149
2150 if let Some(extension) = self
2151 .buffer
2152 .read(cx)
2153 .as_singleton()
2154 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2155 {
2156 key_context.set("extension", extension.to_string());
2157 }
2158
2159 if self.has_active_inline_completion(cx) {
2160 key_context.add("copilot_suggestion");
2161 key_context.add("inline_completion");
2162 }
2163
2164 key_context
2165 }
2166
2167 pub fn new_file(
2168 workspace: &mut Workspace,
2169 _: &workspace::NewFile,
2170 cx: &mut ViewContext<Workspace>,
2171 ) {
2172 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2173 "Failed to create buffer",
2174 cx,
2175 |e, _| match e.error_code() {
2176 ErrorCode::RemoteUpgradeRequired => Some(format!(
2177 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2178 e.error_tag("required").unwrap_or("the latest version")
2179 )),
2180 _ => None,
2181 },
2182 );
2183 }
2184
2185 pub fn new_in_workspace(
2186 workspace: &mut Workspace,
2187 cx: &mut ViewContext<Workspace>,
2188 ) -> Task<Result<View<Editor>>> {
2189 let project = workspace.project().clone();
2190 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2191
2192 cx.spawn(|workspace, mut cx| async move {
2193 let buffer = create.await?;
2194 workspace.update(&mut cx, |workspace, cx| {
2195 let editor =
2196 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2197 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2198 editor
2199 })
2200 })
2201 }
2202
2203 fn new_file_vertical(
2204 workspace: &mut Workspace,
2205 _: &workspace::NewFileSplitVertical,
2206 cx: &mut ViewContext<Workspace>,
2207 ) {
2208 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2209 }
2210
2211 fn new_file_horizontal(
2212 workspace: &mut Workspace,
2213 _: &workspace::NewFileSplitHorizontal,
2214 cx: &mut ViewContext<Workspace>,
2215 ) {
2216 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2217 }
2218
2219 fn new_file_in_direction(
2220 workspace: &mut Workspace,
2221 direction: SplitDirection,
2222 cx: &mut ViewContext<Workspace>,
2223 ) {
2224 let project = workspace.project().clone();
2225 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2226
2227 cx.spawn(|workspace, mut cx| async move {
2228 let buffer = create.await?;
2229 workspace.update(&mut cx, move |workspace, cx| {
2230 workspace.split_item(
2231 direction,
2232 Box::new(
2233 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2234 ),
2235 cx,
2236 )
2237 })?;
2238 anyhow::Ok(())
2239 })
2240 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2241 ErrorCode::RemoteUpgradeRequired => Some(format!(
2242 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2243 e.error_tag("required").unwrap_or("the latest version")
2244 )),
2245 _ => None,
2246 });
2247 }
2248
2249 pub fn leader_peer_id(&self) -> Option<PeerId> {
2250 self.leader_peer_id
2251 }
2252
2253 pub fn buffer(&self) -> &Model<MultiBuffer> {
2254 &self.buffer
2255 }
2256
2257 pub fn workspace(&self) -> Option<View<Workspace>> {
2258 self.workspace.as_ref()?.0.upgrade()
2259 }
2260
2261 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2262 self.buffer().read(cx).title(cx)
2263 }
2264
2265 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2266 let git_blame_gutter_max_author_length = self
2267 .render_git_blame_gutter(cx)
2268 .then(|| {
2269 if let Some(blame) = self.blame.as_ref() {
2270 let max_author_length =
2271 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2272 Some(max_author_length)
2273 } else {
2274 None
2275 }
2276 })
2277 .flatten();
2278
2279 EditorSnapshot {
2280 mode: self.mode,
2281 show_gutter: self.show_gutter,
2282 show_line_numbers: self.show_line_numbers,
2283 show_git_diff_gutter: self.show_git_diff_gutter,
2284 show_code_actions: self.show_code_actions,
2285 show_runnables: self.show_runnables,
2286 git_blame_gutter_max_author_length,
2287 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2288 scroll_anchor: self.scroll_manager.anchor(),
2289 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2290 placeholder_text: self.placeholder_text.clone(),
2291 is_focused: self.focus_handle.is_focused(cx),
2292 current_line_highlight: self
2293 .current_line_highlight
2294 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2295 gutter_hovered: self.gutter_hovered,
2296 }
2297 }
2298
2299 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2300 self.buffer.read(cx).language_at(point, cx)
2301 }
2302
2303 pub fn file_at<T: ToOffset>(
2304 &self,
2305 point: T,
2306 cx: &AppContext,
2307 ) -> Option<Arc<dyn language::File>> {
2308 self.buffer.read(cx).read(cx).file_at(point).cloned()
2309 }
2310
2311 pub fn active_excerpt(
2312 &self,
2313 cx: &AppContext,
2314 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2315 self.buffer
2316 .read(cx)
2317 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2318 }
2319
2320 pub fn mode(&self) -> EditorMode {
2321 self.mode
2322 }
2323
2324 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2325 self.collaboration_hub.as_deref()
2326 }
2327
2328 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2329 self.collaboration_hub = Some(hub);
2330 }
2331
2332 pub fn set_custom_context_menu(
2333 &mut self,
2334 f: impl 'static
2335 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2336 ) {
2337 self.custom_context_menu = Some(Box::new(f))
2338 }
2339
2340 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2341 self.completion_provider = provider;
2342 }
2343
2344 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2345 self.semantics_provider.clone()
2346 }
2347
2348 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2349 self.semantics_provider = provider;
2350 }
2351
2352 pub fn set_inline_completion_provider<T>(
2353 &mut self,
2354 provider: Option<Model<T>>,
2355 cx: &mut ViewContext<Self>,
2356 ) where
2357 T: InlineCompletionProvider,
2358 {
2359 self.inline_completion_provider =
2360 provider.map(|provider| RegisteredInlineCompletionProvider {
2361 _subscription: cx.observe(&provider, |this, _, cx| {
2362 if this.focus_handle.is_focused(cx) {
2363 this.update_visible_inline_completion(cx);
2364 }
2365 }),
2366 provider: Arc::new(provider),
2367 });
2368 self.refresh_inline_completion(false, false, cx);
2369 }
2370
2371 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2372 self.placeholder_text.as_deref()
2373 }
2374
2375 pub fn set_placeholder_text(
2376 &mut self,
2377 placeholder_text: impl Into<Arc<str>>,
2378 cx: &mut ViewContext<Self>,
2379 ) {
2380 let placeholder_text = Some(placeholder_text.into());
2381 if self.placeholder_text != placeholder_text {
2382 self.placeholder_text = placeholder_text;
2383 cx.notify();
2384 }
2385 }
2386
2387 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2388 self.cursor_shape = cursor_shape;
2389
2390 // Disrupt blink for immediate user feedback that the cursor shape has changed
2391 self.blink_manager.update(cx, BlinkManager::show_cursor);
2392
2393 cx.notify();
2394 }
2395
2396 pub fn set_current_line_highlight(
2397 &mut self,
2398 current_line_highlight: Option<CurrentLineHighlight>,
2399 ) {
2400 self.current_line_highlight = current_line_highlight;
2401 }
2402
2403 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2404 self.collapse_matches = collapse_matches;
2405 }
2406
2407 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2408 if self.collapse_matches {
2409 return range.start..range.start;
2410 }
2411 range.clone()
2412 }
2413
2414 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2415 if self.display_map.read(cx).clip_at_line_ends != clip {
2416 self.display_map
2417 .update(cx, |map, _| map.clip_at_line_ends = clip);
2418 }
2419 }
2420
2421 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2422 self.input_enabled = input_enabled;
2423 }
2424
2425 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2426 self.enable_inline_completions = enabled;
2427 }
2428
2429 pub fn set_autoindent(&mut self, autoindent: bool) {
2430 if autoindent {
2431 self.autoindent_mode = Some(AutoindentMode::EachLine);
2432 } else {
2433 self.autoindent_mode = None;
2434 }
2435 }
2436
2437 pub fn read_only(&self, cx: &AppContext) -> bool {
2438 self.read_only || self.buffer.read(cx).read_only()
2439 }
2440
2441 pub fn set_read_only(&mut self, read_only: bool) {
2442 self.read_only = read_only;
2443 }
2444
2445 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2446 self.use_autoclose = autoclose;
2447 }
2448
2449 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2450 self.use_auto_surround = auto_surround;
2451 }
2452
2453 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2454 self.auto_replace_emoji_shortcode = auto_replace;
2455 }
2456
2457 pub fn toggle_inline_completions(
2458 &mut self,
2459 _: &ToggleInlineCompletions,
2460 cx: &mut ViewContext<Self>,
2461 ) {
2462 if self.show_inline_completions_override.is_some() {
2463 self.set_show_inline_completions(None, cx);
2464 } else {
2465 let cursor = self.selections.newest_anchor().head();
2466 if let Some((buffer, cursor_buffer_position)) =
2467 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2468 {
2469 let show_inline_completions =
2470 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2471 self.set_show_inline_completions(Some(show_inline_completions), cx);
2472 }
2473 }
2474 }
2475
2476 pub fn set_show_inline_completions(
2477 &mut self,
2478 show_inline_completions: Option<bool>,
2479 cx: &mut ViewContext<Self>,
2480 ) {
2481 self.show_inline_completions_override = show_inline_completions;
2482 self.refresh_inline_completion(false, true, cx);
2483 }
2484
2485 fn should_show_inline_completions(
2486 &self,
2487 buffer: &Model<Buffer>,
2488 buffer_position: language::Anchor,
2489 cx: &AppContext,
2490 ) -> bool {
2491 if let Some(provider) = self.inline_completion_provider() {
2492 if let Some(show_inline_completions) = self.show_inline_completions_override {
2493 show_inline_completions
2494 } else {
2495 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2496 }
2497 } else {
2498 false
2499 }
2500 }
2501
2502 pub fn set_use_modal_editing(&mut self, to: bool) {
2503 self.use_modal_editing = to;
2504 }
2505
2506 pub fn use_modal_editing(&self) -> bool {
2507 self.use_modal_editing
2508 }
2509
2510 fn selections_did_change(
2511 &mut self,
2512 local: bool,
2513 old_cursor_position: &Anchor,
2514 show_completions: bool,
2515 cx: &mut ViewContext<Self>,
2516 ) {
2517 cx.invalidate_character_coordinates();
2518
2519 // Copy selections to primary selection buffer
2520 #[cfg(target_os = "linux")]
2521 if local {
2522 let selections = self.selections.all::<usize>(cx);
2523 let buffer_handle = self.buffer.read(cx).read(cx);
2524
2525 let mut text = String::new();
2526 for (index, selection) in selections.iter().enumerate() {
2527 let text_for_selection = buffer_handle
2528 .text_for_range(selection.start..selection.end)
2529 .collect::<String>();
2530
2531 text.push_str(&text_for_selection);
2532 if index != selections.len() - 1 {
2533 text.push('\n');
2534 }
2535 }
2536
2537 if !text.is_empty() {
2538 cx.write_to_primary(ClipboardItem::new_string(text));
2539 }
2540 }
2541
2542 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2543 self.buffer.update(cx, |buffer, cx| {
2544 buffer.set_active_selections(
2545 &self.selections.disjoint_anchors(),
2546 self.selections.line_mode,
2547 self.cursor_shape,
2548 cx,
2549 )
2550 });
2551 }
2552 let display_map = self
2553 .display_map
2554 .update(cx, |display_map, cx| display_map.snapshot(cx));
2555 let buffer = &display_map.buffer_snapshot;
2556 self.add_selections_state = None;
2557 self.select_next_state = None;
2558 self.select_prev_state = None;
2559 self.select_larger_syntax_node_stack.clear();
2560 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2561 self.snippet_stack
2562 .invalidate(&self.selections.disjoint_anchors(), buffer);
2563 self.take_rename(false, cx);
2564
2565 let new_cursor_position = self.selections.newest_anchor().head();
2566
2567 self.push_to_nav_history(
2568 *old_cursor_position,
2569 Some(new_cursor_position.to_point(buffer)),
2570 cx,
2571 );
2572
2573 if local {
2574 let new_cursor_position = self.selections.newest_anchor().head();
2575 let mut context_menu = self.context_menu.write();
2576 let completion_menu = match context_menu.as_ref() {
2577 Some(ContextMenu::Completions(menu)) => Some(menu),
2578
2579 _ => {
2580 *context_menu = None;
2581 None
2582 }
2583 };
2584
2585 if let Some(completion_menu) = completion_menu {
2586 let cursor_position = new_cursor_position.to_offset(buffer);
2587 let (word_range, kind) =
2588 buffer.surrounding_word(completion_menu.initial_position, true);
2589 if kind == Some(CharKind::Word)
2590 && word_range.to_inclusive().contains(&cursor_position)
2591 {
2592 let mut completion_menu = completion_menu.clone();
2593 drop(context_menu);
2594
2595 let query = Self::completion_query(buffer, cursor_position);
2596 cx.spawn(move |this, mut cx| async move {
2597 completion_menu
2598 .filter(query.as_deref(), cx.background_executor().clone())
2599 .await;
2600
2601 this.update(&mut cx, |this, cx| {
2602 let mut context_menu = this.context_menu.write();
2603 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2604 return;
2605 };
2606
2607 if menu.id > completion_menu.id {
2608 return;
2609 }
2610
2611 *context_menu = Some(ContextMenu::Completions(completion_menu));
2612 drop(context_menu);
2613 cx.notify();
2614 })
2615 })
2616 .detach();
2617
2618 if show_completions {
2619 self.show_completions(&ShowCompletions { trigger: None }, cx);
2620 }
2621 } else {
2622 drop(context_menu);
2623 self.hide_context_menu(cx);
2624 }
2625 } else {
2626 drop(context_menu);
2627 }
2628
2629 hide_hover(self, cx);
2630
2631 if old_cursor_position.to_display_point(&display_map).row()
2632 != new_cursor_position.to_display_point(&display_map).row()
2633 {
2634 self.available_code_actions.take();
2635 }
2636 self.refresh_code_actions(cx);
2637 self.refresh_document_highlights(cx);
2638 refresh_matching_bracket_highlights(self, cx);
2639 self.discard_inline_completion(false, cx);
2640 linked_editing_ranges::refresh_linked_ranges(self, cx);
2641 if self.git_blame_inline_enabled {
2642 self.start_inline_blame_timer(cx);
2643 }
2644 }
2645
2646 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2647 cx.emit(EditorEvent::SelectionsChanged { local });
2648
2649 if self.selections.disjoint_anchors().len() == 1 {
2650 cx.emit(SearchEvent::ActiveMatchChanged)
2651 }
2652 cx.notify();
2653 }
2654
2655 pub fn change_selections<R>(
2656 &mut self,
2657 autoscroll: Option<Autoscroll>,
2658 cx: &mut ViewContext<Self>,
2659 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2660 ) -> R {
2661 self.change_selections_inner(autoscroll, true, cx, change)
2662 }
2663
2664 pub fn change_selections_inner<R>(
2665 &mut self,
2666 autoscroll: Option<Autoscroll>,
2667 request_completions: bool,
2668 cx: &mut ViewContext<Self>,
2669 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2670 ) -> R {
2671 let old_cursor_position = self.selections.newest_anchor().head();
2672 self.push_to_selection_history();
2673
2674 let (changed, result) = self.selections.change_with(cx, change);
2675
2676 if changed {
2677 if let Some(autoscroll) = autoscroll {
2678 self.request_autoscroll(autoscroll, cx);
2679 }
2680 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2681
2682 if self.should_open_signature_help_automatically(
2683 &old_cursor_position,
2684 self.signature_help_state.backspace_pressed(),
2685 cx,
2686 ) {
2687 self.show_signature_help(&ShowSignatureHelp, cx);
2688 }
2689 self.signature_help_state.set_backspace_pressed(false);
2690 }
2691
2692 result
2693 }
2694
2695 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2696 where
2697 I: IntoIterator<Item = (Range<S>, T)>,
2698 S: ToOffset,
2699 T: Into<Arc<str>>,
2700 {
2701 if self.read_only(cx) {
2702 return;
2703 }
2704
2705 self.buffer
2706 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2707 }
2708
2709 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2710 where
2711 I: IntoIterator<Item = (Range<S>, T)>,
2712 S: ToOffset,
2713 T: Into<Arc<str>>,
2714 {
2715 if self.read_only(cx) {
2716 return;
2717 }
2718
2719 self.buffer.update(cx, |buffer, cx| {
2720 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2721 });
2722 }
2723
2724 pub fn edit_with_block_indent<I, S, T>(
2725 &mut self,
2726 edits: I,
2727 original_indent_columns: Vec<u32>,
2728 cx: &mut ViewContext<Self>,
2729 ) where
2730 I: IntoIterator<Item = (Range<S>, T)>,
2731 S: ToOffset,
2732 T: Into<Arc<str>>,
2733 {
2734 if self.read_only(cx) {
2735 return;
2736 }
2737
2738 self.buffer.update(cx, |buffer, cx| {
2739 buffer.edit(
2740 edits,
2741 Some(AutoindentMode::Block {
2742 original_indent_columns,
2743 }),
2744 cx,
2745 )
2746 });
2747 }
2748
2749 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2750 self.hide_context_menu(cx);
2751
2752 match phase {
2753 SelectPhase::Begin {
2754 position,
2755 add,
2756 click_count,
2757 } => self.begin_selection(position, add, click_count, cx),
2758 SelectPhase::BeginColumnar {
2759 position,
2760 goal_column,
2761 reset,
2762 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2763 SelectPhase::Extend {
2764 position,
2765 click_count,
2766 } => self.extend_selection(position, click_count, cx),
2767 SelectPhase::Update {
2768 position,
2769 goal_column,
2770 scroll_delta,
2771 } => self.update_selection(position, goal_column, scroll_delta, cx),
2772 SelectPhase::End => self.end_selection(cx),
2773 }
2774 }
2775
2776 fn extend_selection(
2777 &mut self,
2778 position: DisplayPoint,
2779 click_count: usize,
2780 cx: &mut ViewContext<Self>,
2781 ) {
2782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2783 let tail = self.selections.newest::<usize>(cx).tail();
2784 self.begin_selection(position, false, click_count, cx);
2785
2786 let position = position.to_offset(&display_map, Bias::Left);
2787 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2788
2789 let mut pending_selection = self
2790 .selections
2791 .pending_anchor()
2792 .expect("extend_selection not called with pending selection");
2793 if position >= tail {
2794 pending_selection.start = tail_anchor;
2795 } else {
2796 pending_selection.end = tail_anchor;
2797 pending_selection.reversed = true;
2798 }
2799
2800 let mut pending_mode = self.selections.pending_mode().unwrap();
2801 match &mut pending_mode {
2802 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2803 _ => {}
2804 }
2805
2806 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2807 s.set_pending(pending_selection, pending_mode)
2808 });
2809 }
2810
2811 fn begin_selection(
2812 &mut self,
2813 position: DisplayPoint,
2814 add: bool,
2815 click_count: usize,
2816 cx: &mut ViewContext<Self>,
2817 ) {
2818 if !self.focus_handle.is_focused(cx) {
2819 self.last_focused_descendant = None;
2820 cx.focus(&self.focus_handle);
2821 }
2822
2823 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2824 let buffer = &display_map.buffer_snapshot;
2825 let newest_selection = self.selections.newest_anchor().clone();
2826 let position = display_map.clip_point(position, Bias::Left);
2827
2828 let start;
2829 let end;
2830 let mode;
2831 let auto_scroll;
2832 match click_count {
2833 1 => {
2834 start = buffer.anchor_before(position.to_point(&display_map));
2835 end = start;
2836 mode = SelectMode::Character;
2837 auto_scroll = true;
2838 }
2839 2 => {
2840 let range = movement::surrounding_word(&display_map, position);
2841 start = buffer.anchor_before(range.start.to_point(&display_map));
2842 end = buffer.anchor_before(range.end.to_point(&display_map));
2843 mode = SelectMode::Word(start..end);
2844 auto_scroll = true;
2845 }
2846 3 => {
2847 let position = display_map
2848 .clip_point(position, Bias::Left)
2849 .to_point(&display_map);
2850 let line_start = display_map.prev_line_boundary(position).0;
2851 let next_line_start = buffer.clip_point(
2852 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2853 Bias::Left,
2854 );
2855 start = buffer.anchor_before(line_start);
2856 end = buffer.anchor_before(next_line_start);
2857 mode = SelectMode::Line(start..end);
2858 auto_scroll = true;
2859 }
2860 _ => {
2861 start = buffer.anchor_before(0);
2862 end = buffer.anchor_before(buffer.len());
2863 mode = SelectMode::All;
2864 auto_scroll = false;
2865 }
2866 }
2867
2868 let point_to_delete: Option<usize> = {
2869 let selected_points: Vec<Selection<Point>> =
2870 self.selections.disjoint_in_range(start..end, cx);
2871
2872 if !add || click_count > 1 {
2873 None
2874 } else if !selected_points.is_empty() {
2875 Some(selected_points[0].id)
2876 } else {
2877 let clicked_point_already_selected =
2878 self.selections.disjoint.iter().find(|selection| {
2879 selection.start.to_point(buffer) == start.to_point(buffer)
2880 || selection.end.to_point(buffer) == end.to_point(buffer)
2881 });
2882
2883 clicked_point_already_selected.map(|selection| selection.id)
2884 }
2885 };
2886
2887 let selections_count = self.selections.count();
2888
2889 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2890 if let Some(point_to_delete) = point_to_delete {
2891 s.delete(point_to_delete);
2892
2893 if selections_count == 1 {
2894 s.set_pending_anchor_range(start..end, mode);
2895 }
2896 } else {
2897 if !add {
2898 s.clear_disjoint();
2899 } else if click_count > 1 {
2900 s.delete(newest_selection.id)
2901 }
2902
2903 s.set_pending_anchor_range(start..end, mode);
2904 }
2905 });
2906 }
2907
2908 fn begin_columnar_selection(
2909 &mut self,
2910 position: DisplayPoint,
2911 goal_column: u32,
2912 reset: bool,
2913 cx: &mut ViewContext<Self>,
2914 ) {
2915 if !self.focus_handle.is_focused(cx) {
2916 self.last_focused_descendant = None;
2917 cx.focus(&self.focus_handle);
2918 }
2919
2920 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2921
2922 if reset {
2923 let pointer_position = display_map
2924 .buffer_snapshot
2925 .anchor_before(position.to_point(&display_map));
2926
2927 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2928 s.clear_disjoint();
2929 s.set_pending_anchor_range(
2930 pointer_position..pointer_position,
2931 SelectMode::Character,
2932 );
2933 });
2934 }
2935
2936 let tail = self.selections.newest::<Point>(cx).tail();
2937 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2938
2939 if !reset {
2940 self.select_columns(
2941 tail.to_display_point(&display_map),
2942 position,
2943 goal_column,
2944 &display_map,
2945 cx,
2946 );
2947 }
2948 }
2949
2950 fn update_selection(
2951 &mut self,
2952 position: DisplayPoint,
2953 goal_column: u32,
2954 scroll_delta: gpui::Point<f32>,
2955 cx: &mut ViewContext<Self>,
2956 ) {
2957 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2958
2959 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2960 let tail = tail.to_display_point(&display_map);
2961 self.select_columns(tail, position, goal_column, &display_map, cx);
2962 } else if let Some(mut pending) = self.selections.pending_anchor() {
2963 let buffer = self.buffer.read(cx).snapshot(cx);
2964 let head;
2965 let tail;
2966 let mode = self.selections.pending_mode().unwrap();
2967 match &mode {
2968 SelectMode::Character => {
2969 head = position.to_point(&display_map);
2970 tail = pending.tail().to_point(&buffer);
2971 }
2972 SelectMode::Word(original_range) => {
2973 let original_display_range = original_range.start.to_display_point(&display_map)
2974 ..original_range.end.to_display_point(&display_map);
2975 let original_buffer_range = original_display_range.start.to_point(&display_map)
2976 ..original_display_range.end.to_point(&display_map);
2977 if movement::is_inside_word(&display_map, position)
2978 || original_display_range.contains(&position)
2979 {
2980 let word_range = movement::surrounding_word(&display_map, position);
2981 if word_range.start < original_display_range.start {
2982 head = word_range.start.to_point(&display_map);
2983 } else {
2984 head = word_range.end.to_point(&display_map);
2985 }
2986 } else {
2987 head = position.to_point(&display_map);
2988 }
2989
2990 if head <= original_buffer_range.start {
2991 tail = original_buffer_range.end;
2992 } else {
2993 tail = original_buffer_range.start;
2994 }
2995 }
2996 SelectMode::Line(original_range) => {
2997 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2998
2999 let position = display_map
3000 .clip_point(position, Bias::Left)
3001 .to_point(&display_map);
3002 let line_start = display_map.prev_line_boundary(position).0;
3003 let next_line_start = buffer.clip_point(
3004 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3005 Bias::Left,
3006 );
3007
3008 if line_start < original_range.start {
3009 head = line_start
3010 } else {
3011 head = next_line_start
3012 }
3013
3014 if head <= original_range.start {
3015 tail = original_range.end;
3016 } else {
3017 tail = original_range.start;
3018 }
3019 }
3020 SelectMode::All => {
3021 return;
3022 }
3023 };
3024
3025 if head < tail {
3026 pending.start = buffer.anchor_before(head);
3027 pending.end = buffer.anchor_before(tail);
3028 pending.reversed = true;
3029 } else {
3030 pending.start = buffer.anchor_before(tail);
3031 pending.end = buffer.anchor_before(head);
3032 pending.reversed = false;
3033 }
3034
3035 self.change_selections(None, cx, |s| {
3036 s.set_pending(pending, mode);
3037 });
3038 } else {
3039 log::error!("update_selection dispatched with no pending selection");
3040 return;
3041 }
3042
3043 self.apply_scroll_delta(scroll_delta, cx);
3044 cx.notify();
3045 }
3046
3047 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3048 self.columnar_selection_tail.take();
3049 if self.selections.pending_anchor().is_some() {
3050 let selections = self.selections.all::<usize>(cx);
3051 self.change_selections(None, cx, |s| {
3052 s.select(selections);
3053 s.clear_pending();
3054 });
3055 }
3056 }
3057
3058 fn select_columns(
3059 &mut self,
3060 tail: DisplayPoint,
3061 head: DisplayPoint,
3062 goal_column: u32,
3063 display_map: &DisplaySnapshot,
3064 cx: &mut ViewContext<Self>,
3065 ) {
3066 let start_row = cmp::min(tail.row(), head.row());
3067 let end_row = cmp::max(tail.row(), head.row());
3068 let start_column = cmp::min(tail.column(), goal_column);
3069 let end_column = cmp::max(tail.column(), goal_column);
3070 let reversed = start_column < tail.column();
3071
3072 let selection_ranges = (start_row.0..=end_row.0)
3073 .map(DisplayRow)
3074 .filter_map(|row| {
3075 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3076 let start = display_map
3077 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3078 .to_point(display_map);
3079 let end = display_map
3080 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3081 .to_point(display_map);
3082 if reversed {
3083 Some(end..start)
3084 } else {
3085 Some(start..end)
3086 }
3087 } else {
3088 None
3089 }
3090 })
3091 .collect::<Vec<_>>();
3092
3093 self.change_selections(None, cx, |s| {
3094 s.select_ranges(selection_ranges);
3095 });
3096 cx.notify();
3097 }
3098
3099 pub fn has_pending_nonempty_selection(&self) -> bool {
3100 let pending_nonempty_selection = match self.selections.pending_anchor() {
3101 Some(Selection { start, end, .. }) => start != end,
3102 None => false,
3103 };
3104
3105 pending_nonempty_selection
3106 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3107 }
3108
3109 pub fn has_pending_selection(&self) -> bool {
3110 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3111 }
3112
3113 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3114 if self.clear_expanded_diff_hunks(cx) {
3115 cx.notify();
3116 return;
3117 }
3118 if self.dismiss_menus_and_popups(true, cx) {
3119 return;
3120 }
3121
3122 if self.mode == EditorMode::Full
3123 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3124 {
3125 return;
3126 }
3127
3128 cx.propagate();
3129 }
3130
3131 pub fn dismiss_menus_and_popups(
3132 &mut self,
3133 should_report_inline_completion_event: bool,
3134 cx: &mut ViewContext<Self>,
3135 ) -> bool {
3136 if self.take_rename(false, cx).is_some() {
3137 return true;
3138 }
3139
3140 if hide_hover(self, cx) {
3141 return true;
3142 }
3143
3144 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3145 return true;
3146 }
3147
3148 if self.hide_context_menu(cx).is_some() {
3149 return true;
3150 }
3151
3152 if self.mouse_context_menu.take().is_some() {
3153 return true;
3154 }
3155
3156 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3157 return true;
3158 }
3159
3160 if self.snippet_stack.pop().is_some() {
3161 return true;
3162 }
3163
3164 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3165 self.dismiss_diagnostics(cx);
3166 return true;
3167 }
3168
3169 false
3170 }
3171
3172 fn linked_editing_ranges_for(
3173 &self,
3174 selection: Range<text::Anchor>,
3175 cx: &AppContext,
3176 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3177 if self.linked_edit_ranges.is_empty() {
3178 return None;
3179 }
3180 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3181 selection.end.buffer_id.and_then(|end_buffer_id| {
3182 if selection.start.buffer_id != Some(end_buffer_id) {
3183 return None;
3184 }
3185 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3186 let snapshot = buffer.read(cx).snapshot();
3187 self.linked_edit_ranges
3188 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3189 .map(|ranges| (ranges, snapshot, buffer))
3190 })?;
3191 use text::ToOffset as TO;
3192 // find offset from the start of current range to current cursor position
3193 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3194
3195 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3196 let start_difference = start_offset - start_byte_offset;
3197 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3198 let end_difference = end_offset - start_byte_offset;
3199 // Current range has associated linked ranges.
3200 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3201 for range in linked_ranges.iter() {
3202 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3203 let end_offset = start_offset + end_difference;
3204 let start_offset = start_offset + start_difference;
3205 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3206 continue;
3207 }
3208 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3209 if s.start.buffer_id != selection.start.buffer_id
3210 || s.end.buffer_id != selection.end.buffer_id
3211 {
3212 return false;
3213 }
3214 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3215 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3216 }) {
3217 continue;
3218 }
3219 let start = buffer_snapshot.anchor_after(start_offset);
3220 let end = buffer_snapshot.anchor_after(end_offset);
3221 linked_edits
3222 .entry(buffer.clone())
3223 .or_default()
3224 .push(start..end);
3225 }
3226 Some(linked_edits)
3227 }
3228
3229 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3230 let text: Arc<str> = text.into();
3231
3232 if self.read_only(cx) {
3233 return;
3234 }
3235
3236 let selections = self.selections.all_adjusted(cx);
3237 let mut bracket_inserted = false;
3238 let mut edits = Vec::new();
3239 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3240 let mut new_selections = Vec::with_capacity(selections.len());
3241 let mut new_autoclose_regions = Vec::new();
3242 let snapshot = self.buffer.read(cx).read(cx);
3243
3244 for (selection, autoclose_region) in
3245 self.selections_with_autoclose_regions(selections, &snapshot)
3246 {
3247 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3248 // Determine if the inserted text matches the opening or closing
3249 // bracket of any of this language's bracket pairs.
3250 let mut bracket_pair = None;
3251 let mut is_bracket_pair_start = false;
3252 let mut is_bracket_pair_end = false;
3253 if !text.is_empty() {
3254 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3255 // and they are removing the character that triggered IME popup.
3256 for (pair, enabled) in scope.brackets() {
3257 if !pair.close && !pair.surround {
3258 continue;
3259 }
3260
3261 if enabled && pair.start.ends_with(text.as_ref()) {
3262 let prefix_len = pair.start.len() - text.len();
3263 let preceding_text_matches_prefix = prefix_len == 0
3264 || (selection.start.column >= (prefix_len as u32)
3265 && snapshot.contains_str_at(
3266 Point::new(
3267 selection.start.row,
3268 selection.start.column - (prefix_len as u32),
3269 ),
3270 &pair.start[..prefix_len],
3271 ));
3272 if preceding_text_matches_prefix {
3273 bracket_pair = Some(pair.clone());
3274 is_bracket_pair_start = true;
3275 break;
3276 }
3277 }
3278 if pair.end.as_str() == text.as_ref() {
3279 bracket_pair = Some(pair.clone());
3280 is_bracket_pair_end = true;
3281 break;
3282 }
3283 }
3284 }
3285
3286 if let Some(bracket_pair) = bracket_pair {
3287 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3288 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3289 let auto_surround =
3290 self.use_auto_surround && snapshot_settings.use_auto_surround;
3291 if selection.is_empty() {
3292 if is_bracket_pair_start {
3293 // If the inserted text is a suffix of an opening bracket and the
3294 // selection is preceded by the rest of the opening bracket, then
3295 // insert the closing bracket.
3296 let following_text_allows_autoclose = snapshot
3297 .chars_at(selection.start)
3298 .next()
3299 .map_or(true, |c| scope.should_autoclose_before(c));
3300
3301 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3302 && bracket_pair.start.len() == 1
3303 {
3304 let target = bracket_pair.start.chars().next().unwrap();
3305 let current_line_count = snapshot
3306 .reversed_chars_at(selection.start)
3307 .take_while(|&c| c != '\n')
3308 .filter(|&c| c == target)
3309 .count();
3310 current_line_count % 2 == 1
3311 } else {
3312 false
3313 };
3314
3315 if autoclose
3316 && bracket_pair.close
3317 && following_text_allows_autoclose
3318 && !is_closing_quote
3319 {
3320 let anchor = snapshot.anchor_before(selection.end);
3321 new_selections.push((selection.map(|_| anchor), text.len()));
3322 new_autoclose_regions.push((
3323 anchor,
3324 text.len(),
3325 selection.id,
3326 bracket_pair.clone(),
3327 ));
3328 edits.push((
3329 selection.range(),
3330 format!("{}{}", text, bracket_pair.end).into(),
3331 ));
3332 bracket_inserted = true;
3333 continue;
3334 }
3335 }
3336
3337 if let Some(region) = autoclose_region {
3338 // If the selection is followed by an auto-inserted closing bracket,
3339 // then don't insert that closing bracket again; just move the selection
3340 // past the closing bracket.
3341 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3342 && text.as_ref() == region.pair.end.as_str();
3343 if should_skip {
3344 let anchor = snapshot.anchor_after(selection.end);
3345 new_selections
3346 .push((selection.map(|_| anchor), region.pair.end.len()));
3347 continue;
3348 }
3349 }
3350
3351 let always_treat_brackets_as_autoclosed = snapshot
3352 .settings_at(selection.start, cx)
3353 .always_treat_brackets_as_autoclosed;
3354 if always_treat_brackets_as_autoclosed
3355 && is_bracket_pair_end
3356 && snapshot.contains_str_at(selection.end, text.as_ref())
3357 {
3358 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3359 // and the inserted text is a closing bracket and the selection is followed
3360 // by the closing bracket then move the selection past the closing bracket.
3361 let anchor = snapshot.anchor_after(selection.end);
3362 new_selections.push((selection.map(|_| anchor), text.len()));
3363 continue;
3364 }
3365 }
3366 // If an opening bracket is 1 character long and is typed while
3367 // text is selected, then surround that text with the bracket pair.
3368 else if auto_surround
3369 && bracket_pair.surround
3370 && is_bracket_pair_start
3371 && bracket_pair.start.chars().count() == 1
3372 {
3373 edits.push((selection.start..selection.start, text.clone()));
3374 edits.push((
3375 selection.end..selection.end,
3376 bracket_pair.end.as_str().into(),
3377 ));
3378 bracket_inserted = true;
3379 new_selections.push((
3380 Selection {
3381 id: selection.id,
3382 start: snapshot.anchor_after(selection.start),
3383 end: snapshot.anchor_before(selection.end),
3384 reversed: selection.reversed,
3385 goal: selection.goal,
3386 },
3387 0,
3388 ));
3389 continue;
3390 }
3391 }
3392 }
3393
3394 if self.auto_replace_emoji_shortcode
3395 && selection.is_empty()
3396 && text.as_ref().ends_with(':')
3397 {
3398 if let Some(possible_emoji_short_code) =
3399 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3400 {
3401 if !possible_emoji_short_code.is_empty() {
3402 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3403 let emoji_shortcode_start = Point::new(
3404 selection.start.row,
3405 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3406 );
3407
3408 // Remove shortcode from buffer
3409 edits.push((
3410 emoji_shortcode_start..selection.start,
3411 "".to_string().into(),
3412 ));
3413 new_selections.push((
3414 Selection {
3415 id: selection.id,
3416 start: snapshot.anchor_after(emoji_shortcode_start),
3417 end: snapshot.anchor_before(selection.start),
3418 reversed: selection.reversed,
3419 goal: selection.goal,
3420 },
3421 0,
3422 ));
3423
3424 // Insert emoji
3425 let selection_start_anchor = snapshot.anchor_after(selection.start);
3426 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3427 edits.push((selection.start..selection.end, emoji.to_string().into()));
3428
3429 continue;
3430 }
3431 }
3432 }
3433 }
3434
3435 // If not handling any auto-close operation, then just replace the selected
3436 // text with the given input and move the selection to the end of the
3437 // newly inserted text.
3438 let anchor = snapshot.anchor_after(selection.end);
3439 if !self.linked_edit_ranges.is_empty() {
3440 let start_anchor = snapshot.anchor_before(selection.start);
3441
3442 let is_word_char = text.chars().next().map_or(true, |char| {
3443 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3444 classifier.is_word(char)
3445 });
3446
3447 if is_word_char {
3448 if let Some(ranges) = self
3449 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3450 {
3451 for (buffer, edits) in ranges {
3452 linked_edits
3453 .entry(buffer.clone())
3454 .or_default()
3455 .extend(edits.into_iter().map(|range| (range, text.clone())));
3456 }
3457 }
3458 }
3459 }
3460
3461 new_selections.push((selection.map(|_| anchor), 0));
3462 edits.push((selection.start..selection.end, text.clone()));
3463 }
3464
3465 drop(snapshot);
3466
3467 self.transact(cx, |this, cx| {
3468 this.buffer.update(cx, |buffer, cx| {
3469 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3470 });
3471 for (buffer, edits) in linked_edits {
3472 buffer.update(cx, |buffer, cx| {
3473 let snapshot = buffer.snapshot();
3474 let edits = edits
3475 .into_iter()
3476 .map(|(range, text)| {
3477 use text::ToPoint as TP;
3478 let end_point = TP::to_point(&range.end, &snapshot);
3479 let start_point = TP::to_point(&range.start, &snapshot);
3480 (start_point..end_point, text)
3481 })
3482 .sorted_by_key(|(range, _)| range.start)
3483 .collect::<Vec<_>>();
3484 buffer.edit(edits, None, cx);
3485 })
3486 }
3487 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3488 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3489 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3490 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3491 .zip(new_selection_deltas)
3492 .map(|(selection, delta)| Selection {
3493 id: selection.id,
3494 start: selection.start + delta,
3495 end: selection.end + delta,
3496 reversed: selection.reversed,
3497 goal: SelectionGoal::None,
3498 })
3499 .collect::<Vec<_>>();
3500
3501 let mut i = 0;
3502 for (position, delta, selection_id, pair) in new_autoclose_regions {
3503 let position = position.to_offset(&map.buffer_snapshot) + delta;
3504 let start = map.buffer_snapshot.anchor_before(position);
3505 let end = map.buffer_snapshot.anchor_after(position);
3506 while let Some(existing_state) = this.autoclose_regions.get(i) {
3507 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3508 Ordering::Less => i += 1,
3509 Ordering::Greater => break,
3510 Ordering::Equal => {
3511 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3512 Ordering::Less => i += 1,
3513 Ordering::Equal => break,
3514 Ordering::Greater => break,
3515 }
3516 }
3517 }
3518 }
3519 this.autoclose_regions.insert(
3520 i,
3521 AutocloseRegion {
3522 selection_id,
3523 range: start..end,
3524 pair,
3525 },
3526 );
3527 }
3528
3529 let had_active_inline_completion = this.has_active_inline_completion(cx);
3530 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3531 s.select(new_selections)
3532 });
3533
3534 if !bracket_inserted {
3535 if let Some(on_type_format_task) =
3536 this.trigger_on_type_formatting(text.to_string(), cx)
3537 {
3538 on_type_format_task.detach_and_log_err(cx);
3539 }
3540 }
3541
3542 let editor_settings = EditorSettings::get_global(cx);
3543 if bracket_inserted
3544 && (editor_settings.auto_signature_help
3545 || editor_settings.show_signature_help_after_edits)
3546 {
3547 this.show_signature_help(&ShowSignatureHelp, cx);
3548 }
3549
3550 let trigger_in_words = !had_active_inline_completion;
3551 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3552 linked_editing_ranges::refresh_linked_ranges(this, cx);
3553 this.refresh_inline_completion(true, false, cx);
3554 });
3555 }
3556
3557 fn find_possible_emoji_shortcode_at_position(
3558 snapshot: &MultiBufferSnapshot,
3559 position: Point,
3560 ) -> Option<String> {
3561 let mut chars = Vec::new();
3562 let mut found_colon = false;
3563 for char in snapshot.reversed_chars_at(position).take(100) {
3564 // Found a possible emoji shortcode in the middle of the buffer
3565 if found_colon {
3566 if char.is_whitespace() {
3567 chars.reverse();
3568 return Some(chars.iter().collect());
3569 }
3570 // If the previous character is not a whitespace, we are in the middle of a word
3571 // and we only want to complete the shortcode if the word is made up of other emojis
3572 let mut containing_word = String::new();
3573 for ch in snapshot
3574 .reversed_chars_at(position)
3575 .skip(chars.len() + 1)
3576 .take(100)
3577 {
3578 if ch.is_whitespace() {
3579 break;
3580 }
3581 containing_word.push(ch);
3582 }
3583 let containing_word = containing_word.chars().rev().collect::<String>();
3584 if util::word_consists_of_emojis(containing_word.as_str()) {
3585 chars.reverse();
3586 return Some(chars.iter().collect());
3587 }
3588 }
3589
3590 if char.is_whitespace() || !char.is_ascii() {
3591 return None;
3592 }
3593 if char == ':' {
3594 found_colon = true;
3595 } else {
3596 chars.push(char);
3597 }
3598 }
3599 // Found a possible emoji shortcode at the beginning of the buffer
3600 chars.reverse();
3601 Some(chars.iter().collect())
3602 }
3603
3604 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3605 self.transact(cx, |this, cx| {
3606 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3607 let selections = this.selections.all::<usize>(cx);
3608 let multi_buffer = this.buffer.read(cx);
3609 let buffer = multi_buffer.snapshot(cx);
3610 selections
3611 .iter()
3612 .map(|selection| {
3613 let start_point = selection.start.to_point(&buffer);
3614 let mut indent =
3615 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3616 indent.len = cmp::min(indent.len, start_point.column);
3617 let start = selection.start;
3618 let end = selection.end;
3619 let selection_is_empty = start == end;
3620 let language_scope = buffer.language_scope_at(start);
3621 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3622 &language_scope
3623 {
3624 let leading_whitespace_len = buffer
3625 .reversed_chars_at(start)
3626 .take_while(|c| c.is_whitespace() && *c != '\n')
3627 .map(|c| c.len_utf8())
3628 .sum::<usize>();
3629
3630 let trailing_whitespace_len = buffer
3631 .chars_at(end)
3632 .take_while(|c| c.is_whitespace() && *c != '\n')
3633 .map(|c| c.len_utf8())
3634 .sum::<usize>();
3635
3636 let insert_extra_newline =
3637 language.brackets().any(|(pair, enabled)| {
3638 let pair_start = pair.start.trim_end();
3639 let pair_end = pair.end.trim_start();
3640
3641 enabled
3642 && pair.newline
3643 && buffer.contains_str_at(
3644 end + trailing_whitespace_len,
3645 pair_end,
3646 )
3647 && buffer.contains_str_at(
3648 (start - leading_whitespace_len)
3649 .saturating_sub(pair_start.len()),
3650 pair_start,
3651 )
3652 });
3653
3654 // Comment extension on newline is allowed only for cursor selections
3655 let comment_delimiter = maybe!({
3656 if !selection_is_empty {
3657 return None;
3658 }
3659
3660 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3661 return None;
3662 }
3663
3664 let delimiters = language.line_comment_prefixes();
3665 let max_len_of_delimiter =
3666 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3667 let (snapshot, range) =
3668 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3669
3670 let mut index_of_first_non_whitespace = 0;
3671 let comment_candidate = snapshot
3672 .chars_for_range(range)
3673 .skip_while(|c| {
3674 let should_skip = c.is_whitespace();
3675 if should_skip {
3676 index_of_first_non_whitespace += 1;
3677 }
3678 should_skip
3679 })
3680 .take(max_len_of_delimiter)
3681 .collect::<String>();
3682 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3683 comment_candidate.starts_with(comment_prefix.as_ref())
3684 })?;
3685 let cursor_is_placed_after_comment_marker =
3686 index_of_first_non_whitespace + comment_prefix.len()
3687 <= start_point.column as usize;
3688 if cursor_is_placed_after_comment_marker {
3689 Some(comment_prefix.clone())
3690 } else {
3691 None
3692 }
3693 });
3694 (comment_delimiter, insert_extra_newline)
3695 } else {
3696 (None, false)
3697 };
3698
3699 let capacity_for_delimiter = comment_delimiter
3700 .as_deref()
3701 .map(str::len)
3702 .unwrap_or_default();
3703 let mut new_text =
3704 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3705 new_text.push('\n');
3706 new_text.extend(indent.chars());
3707 if let Some(delimiter) = &comment_delimiter {
3708 new_text.push_str(delimiter);
3709 }
3710 if insert_extra_newline {
3711 new_text = new_text.repeat(2);
3712 }
3713
3714 let anchor = buffer.anchor_after(end);
3715 let new_selection = selection.map(|_| anchor);
3716 (
3717 (start..end, new_text),
3718 (insert_extra_newline, new_selection),
3719 )
3720 })
3721 .unzip()
3722 };
3723
3724 this.edit_with_autoindent(edits, cx);
3725 let buffer = this.buffer.read(cx).snapshot(cx);
3726 let new_selections = selection_fixup_info
3727 .into_iter()
3728 .map(|(extra_newline_inserted, new_selection)| {
3729 let mut cursor = new_selection.end.to_point(&buffer);
3730 if extra_newline_inserted {
3731 cursor.row -= 1;
3732 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3733 }
3734 new_selection.map(|_| cursor)
3735 })
3736 .collect();
3737
3738 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3739 this.refresh_inline_completion(true, false, cx);
3740 });
3741 }
3742
3743 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3744 let buffer = self.buffer.read(cx);
3745 let snapshot = buffer.snapshot(cx);
3746
3747 let mut edits = Vec::new();
3748 let mut rows = Vec::new();
3749
3750 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3751 let cursor = selection.head();
3752 let row = cursor.row;
3753
3754 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3755
3756 let newline = "\n".to_string();
3757 edits.push((start_of_line..start_of_line, newline));
3758
3759 rows.push(row + rows_inserted as u32);
3760 }
3761
3762 self.transact(cx, |editor, cx| {
3763 editor.edit(edits, cx);
3764
3765 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3766 let mut index = 0;
3767 s.move_cursors_with(|map, _, _| {
3768 let row = rows[index];
3769 index += 1;
3770
3771 let point = Point::new(row, 0);
3772 let boundary = map.next_line_boundary(point).1;
3773 let clipped = map.clip_point(boundary, Bias::Left);
3774
3775 (clipped, SelectionGoal::None)
3776 });
3777 });
3778
3779 let mut indent_edits = Vec::new();
3780 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3781 for row in rows {
3782 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3783 for (row, indent) in indents {
3784 if indent.len == 0 {
3785 continue;
3786 }
3787
3788 let text = match indent.kind {
3789 IndentKind::Space => " ".repeat(indent.len as usize),
3790 IndentKind::Tab => "\t".repeat(indent.len as usize),
3791 };
3792 let point = Point::new(row.0, 0);
3793 indent_edits.push((point..point, text));
3794 }
3795 }
3796 editor.edit(indent_edits, cx);
3797 });
3798 }
3799
3800 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3801 let buffer = self.buffer.read(cx);
3802 let snapshot = buffer.snapshot(cx);
3803
3804 let mut edits = Vec::new();
3805 let mut rows = Vec::new();
3806 let mut rows_inserted = 0;
3807
3808 for selection in self.selections.all_adjusted(cx) {
3809 let cursor = selection.head();
3810 let row = cursor.row;
3811
3812 let point = Point::new(row + 1, 0);
3813 let start_of_line = snapshot.clip_point(point, Bias::Left);
3814
3815 let newline = "\n".to_string();
3816 edits.push((start_of_line..start_of_line, newline));
3817
3818 rows_inserted += 1;
3819 rows.push(row + rows_inserted);
3820 }
3821
3822 self.transact(cx, |editor, cx| {
3823 editor.edit(edits, cx);
3824
3825 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3826 let mut index = 0;
3827 s.move_cursors_with(|map, _, _| {
3828 let row = rows[index];
3829 index += 1;
3830
3831 let point = Point::new(row, 0);
3832 let boundary = map.next_line_boundary(point).1;
3833 let clipped = map.clip_point(boundary, Bias::Left);
3834
3835 (clipped, SelectionGoal::None)
3836 });
3837 });
3838
3839 let mut indent_edits = Vec::new();
3840 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3841 for row in rows {
3842 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3843 for (row, indent) in indents {
3844 if indent.len == 0 {
3845 continue;
3846 }
3847
3848 let text = match indent.kind {
3849 IndentKind::Space => " ".repeat(indent.len as usize),
3850 IndentKind::Tab => "\t".repeat(indent.len as usize),
3851 };
3852 let point = Point::new(row.0, 0);
3853 indent_edits.push((point..point, text));
3854 }
3855 }
3856 editor.edit(indent_edits, cx);
3857 });
3858 }
3859
3860 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3861 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3862 original_indent_columns: Vec::new(),
3863 });
3864 self.insert_with_autoindent_mode(text, autoindent, cx);
3865 }
3866
3867 fn insert_with_autoindent_mode(
3868 &mut self,
3869 text: &str,
3870 autoindent_mode: Option<AutoindentMode>,
3871 cx: &mut ViewContext<Self>,
3872 ) {
3873 if self.read_only(cx) {
3874 return;
3875 }
3876
3877 let text: Arc<str> = text.into();
3878 self.transact(cx, |this, cx| {
3879 let old_selections = this.selections.all_adjusted(cx);
3880 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3881 let anchors = {
3882 let snapshot = buffer.read(cx);
3883 old_selections
3884 .iter()
3885 .map(|s| {
3886 let anchor = snapshot.anchor_after(s.head());
3887 s.map(|_| anchor)
3888 })
3889 .collect::<Vec<_>>()
3890 };
3891 buffer.edit(
3892 old_selections
3893 .iter()
3894 .map(|s| (s.start..s.end, text.clone())),
3895 autoindent_mode,
3896 cx,
3897 );
3898 anchors
3899 });
3900
3901 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3902 s.select_anchors(selection_anchors);
3903 })
3904 });
3905 }
3906
3907 fn trigger_completion_on_input(
3908 &mut self,
3909 text: &str,
3910 trigger_in_words: bool,
3911 cx: &mut ViewContext<Self>,
3912 ) {
3913 if self.is_completion_trigger(text, trigger_in_words, cx) {
3914 self.show_completions(
3915 &ShowCompletions {
3916 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3917 },
3918 cx,
3919 );
3920 } else {
3921 self.hide_context_menu(cx);
3922 }
3923 }
3924
3925 fn is_completion_trigger(
3926 &self,
3927 text: &str,
3928 trigger_in_words: bool,
3929 cx: &mut ViewContext<Self>,
3930 ) -> bool {
3931 let position = self.selections.newest_anchor().head();
3932 let multibuffer = self.buffer.read(cx);
3933 let Some(buffer) = position
3934 .buffer_id
3935 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3936 else {
3937 return false;
3938 };
3939
3940 if let Some(completion_provider) = &self.completion_provider {
3941 completion_provider.is_completion_trigger(
3942 &buffer,
3943 position.text_anchor,
3944 text,
3945 trigger_in_words,
3946 cx,
3947 )
3948 } else {
3949 false
3950 }
3951 }
3952
3953 /// If any empty selections is touching the start of its innermost containing autoclose
3954 /// region, expand it to select the brackets.
3955 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3956 let selections = self.selections.all::<usize>(cx);
3957 let buffer = self.buffer.read(cx).read(cx);
3958 let new_selections = self
3959 .selections_with_autoclose_regions(selections, &buffer)
3960 .map(|(mut selection, region)| {
3961 if !selection.is_empty() {
3962 return selection;
3963 }
3964
3965 if let Some(region) = region {
3966 let mut range = region.range.to_offset(&buffer);
3967 if selection.start == range.start && range.start >= region.pair.start.len() {
3968 range.start -= region.pair.start.len();
3969 if buffer.contains_str_at(range.start, ®ion.pair.start)
3970 && buffer.contains_str_at(range.end, ®ion.pair.end)
3971 {
3972 range.end += region.pair.end.len();
3973 selection.start = range.start;
3974 selection.end = range.end;
3975
3976 return selection;
3977 }
3978 }
3979 }
3980
3981 let always_treat_brackets_as_autoclosed = buffer
3982 .settings_at(selection.start, cx)
3983 .always_treat_brackets_as_autoclosed;
3984
3985 if !always_treat_brackets_as_autoclosed {
3986 return selection;
3987 }
3988
3989 if let Some(scope) = buffer.language_scope_at(selection.start) {
3990 for (pair, enabled) in scope.brackets() {
3991 if !enabled || !pair.close {
3992 continue;
3993 }
3994
3995 if buffer.contains_str_at(selection.start, &pair.end) {
3996 let pair_start_len = pair.start.len();
3997 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3998 {
3999 selection.start -= pair_start_len;
4000 selection.end += pair.end.len();
4001
4002 return selection;
4003 }
4004 }
4005 }
4006 }
4007
4008 selection
4009 })
4010 .collect();
4011
4012 drop(buffer);
4013 self.change_selections(None, cx, |selections| selections.select(new_selections));
4014 }
4015
4016 /// Iterate the given selections, and for each one, find the smallest surrounding
4017 /// autoclose region. This uses the ordering of the selections and the autoclose
4018 /// regions to avoid repeated comparisons.
4019 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4020 &'a self,
4021 selections: impl IntoIterator<Item = Selection<D>>,
4022 buffer: &'a MultiBufferSnapshot,
4023 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4024 let mut i = 0;
4025 let mut regions = self.autoclose_regions.as_slice();
4026 selections.into_iter().map(move |selection| {
4027 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4028
4029 let mut enclosing = None;
4030 while let Some(pair_state) = regions.get(i) {
4031 if pair_state.range.end.to_offset(buffer) < range.start {
4032 regions = ®ions[i + 1..];
4033 i = 0;
4034 } else if pair_state.range.start.to_offset(buffer) > range.end {
4035 break;
4036 } else {
4037 if pair_state.selection_id == selection.id {
4038 enclosing = Some(pair_state);
4039 }
4040 i += 1;
4041 }
4042 }
4043
4044 (selection, enclosing)
4045 })
4046 }
4047
4048 /// Remove any autoclose regions that no longer contain their selection.
4049 fn invalidate_autoclose_regions(
4050 &mut self,
4051 mut selections: &[Selection<Anchor>],
4052 buffer: &MultiBufferSnapshot,
4053 ) {
4054 self.autoclose_regions.retain(|state| {
4055 let mut i = 0;
4056 while let Some(selection) = selections.get(i) {
4057 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4058 selections = &selections[1..];
4059 continue;
4060 }
4061 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4062 break;
4063 }
4064 if selection.id == state.selection_id {
4065 return true;
4066 } else {
4067 i += 1;
4068 }
4069 }
4070 false
4071 });
4072 }
4073
4074 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4075 let offset = position.to_offset(buffer);
4076 let (word_range, kind) = buffer.surrounding_word(offset, true);
4077 if offset > word_range.start && kind == Some(CharKind::Word) {
4078 Some(
4079 buffer
4080 .text_for_range(word_range.start..offset)
4081 .collect::<String>(),
4082 )
4083 } else {
4084 None
4085 }
4086 }
4087
4088 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4089 self.refresh_inlay_hints(
4090 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4091 cx,
4092 );
4093 }
4094
4095 pub fn inlay_hints_enabled(&self) -> bool {
4096 self.inlay_hint_cache.enabled
4097 }
4098
4099 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4100 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4101 return;
4102 }
4103
4104 let reason_description = reason.description();
4105 let ignore_debounce = matches!(
4106 reason,
4107 InlayHintRefreshReason::SettingsChange(_)
4108 | InlayHintRefreshReason::Toggle(_)
4109 | InlayHintRefreshReason::ExcerptsRemoved(_)
4110 );
4111 let (invalidate_cache, required_languages) = match reason {
4112 InlayHintRefreshReason::Toggle(enabled) => {
4113 self.inlay_hint_cache.enabled = enabled;
4114 if enabled {
4115 (InvalidationStrategy::RefreshRequested, None)
4116 } else {
4117 self.inlay_hint_cache.clear();
4118 self.splice_inlays(
4119 self.visible_inlay_hints(cx)
4120 .iter()
4121 .map(|inlay| inlay.id)
4122 .collect(),
4123 Vec::new(),
4124 cx,
4125 );
4126 return;
4127 }
4128 }
4129 InlayHintRefreshReason::SettingsChange(new_settings) => {
4130 match self.inlay_hint_cache.update_settings(
4131 &self.buffer,
4132 new_settings,
4133 self.visible_inlay_hints(cx),
4134 cx,
4135 ) {
4136 ControlFlow::Break(Some(InlaySplice {
4137 to_remove,
4138 to_insert,
4139 })) => {
4140 self.splice_inlays(to_remove, to_insert, cx);
4141 return;
4142 }
4143 ControlFlow::Break(None) => return,
4144 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4145 }
4146 }
4147 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4148 if let Some(InlaySplice {
4149 to_remove,
4150 to_insert,
4151 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4152 {
4153 self.splice_inlays(to_remove, to_insert, cx);
4154 }
4155 return;
4156 }
4157 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4158 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4159 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4160 }
4161 InlayHintRefreshReason::RefreshRequested => {
4162 (InvalidationStrategy::RefreshRequested, None)
4163 }
4164 };
4165
4166 if let Some(InlaySplice {
4167 to_remove,
4168 to_insert,
4169 }) = self.inlay_hint_cache.spawn_hint_refresh(
4170 reason_description,
4171 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4172 invalidate_cache,
4173 ignore_debounce,
4174 cx,
4175 ) {
4176 self.splice_inlays(to_remove, to_insert, cx);
4177 }
4178 }
4179
4180 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4181 self.display_map
4182 .read(cx)
4183 .current_inlays()
4184 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4185 .cloned()
4186 .collect()
4187 }
4188
4189 pub fn excerpts_for_inlay_hints_query(
4190 &self,
4191 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4192 cx: &mut ViewContext<Editor>,
4193 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4194 let Some(project) = self.project.as_ref() else {
4195 return HashMap::default();
4196 };
4197 let project = project.read(cx);
4198 let multi_buffer = self.buffer().read(cx);
4199 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4200 let multi_buffer_visible_start = self
4201 .scroll_manager
4202 .anchor()
4203 .anchor
4204 .to_point(&multi_buffer_snapshot);
4205 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4206 multi_buffer_visible_start
4207 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4208 Bias::Left,
4209 );
4210 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4211 multi_buffer
4212 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4213 .into_iter()
4214 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4215 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4216 let buffer = buffer_handle.read(cx);
4217 let buffer_file = project::File::from_dyn(buffer.file())?;
4218 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4219 let worktree_entry = buffer_worktree
4220 .read(cx)
4221 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4222 if worktree_entry.is_ignored {
4223 return None;
4224 }
4225
4226 let language = buffer.language()?;
4227 if let Some(restrict_to_languages) = restrict_to_languages {
4228 if !restrict_to_languages.contains(language) {
4229 return None;
4230 }
4231 }
4232 Some((
4233 excerpt_id,
4234 (
4235 buffer_handle,
4236 buffer.version().clone(),
4237 excerpt_visible_range,
4238 ),
4239 ))
4240 })
4241 .collect()
4242 }
4243
4244 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4245 TextLayoutDetails {
4246 text_system: cx.text_system().clone(),
4247 editor_style: self.style.clone().unwrap(),
4248 rem_size: cx.rem_size(),
4249 scroll_anchor: self.scroll_manager.anchor(),
4250 visible_rows: self.visible_line_count(),
4251 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4252 }
4253 }
4254
4255 fn splice_inlays(
4256 &self,
4257 to_remove: Vec<InlayId>,
4258 to_insert: Vec<Inlay>,
4259 cx: &mut ViewContext<Self>,
4260 ) {
4261 self.display_map.update(cx, |display_map, cx| {
4262 display_map.splice_inlays(to_remove, to_insert, cx);
4263 });
4264 cx.notify();
4265 }
4266
4267 fn trigger_on_type_formatting(
4268 &self,
4269 input: String,
4270 cx: &mut ViewContext<Self>,
4271 ) -> Option<Task<Result<()>>> {
4272 if input.len() != 1 {
4273 return None;
4274 }
4275
4276 let project = self.project.as_ref()?;
4277 let position = self.selections.newest_anchor().head();
4278 let (buffer, buffer_position) = self
4279 .buffer
4280 .read(cx)
4281 .text_anchor_for_position(position, cx)?;
4282
4283 let settings = language_settings::language_settings(
4284 buffer
4285 .read(cx)
4286 .language_at(buffer_position)
4287 .map(|l| l.name()),
4288 buffer.read(cx).file(),
4289 cx,
4290 );
4291 if !settings.use_on_type_format {
4292 return None;
4293 }
4294
4295 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4296 // hence we do LSP request & edit on host side only — add formats to host's history.
4297 let push_to_lsp_host_history = true;
4298 // If this is not the host, append its history with new edits.
4299 let push_to_client_history = project.read(cx).is_via_collab();
4300
4301 let on_type_formatting = project.update(cx, |project, cx| {
4302 project.on_type_format(
4303 buffer.clone(),
4304 buffer_position,
4305 input,
4306 push_to_lsp_host_history,
4307 cx,
4308 )
4309 });
4310 Some(cx.spawn(|editor, mut cx| async move {
4311 if let Some(transaction) = on_type_formatting.await? {
4312 if push_to_client_history {
4313 buffer
4314 .update(&mut cx, |buffer, _| {
4315 buffer.push_transaction(transaction, Instant::now());
4316 })
4317 .ok();
4318 }
4319 editor.update(&mut cx, |editor, cx| {
4320 editor.refresh_document_highlights(cx);
4321 })?;
4322 }
4323 Ok(())
4324 }))
4325 }
4326
4327 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4328 if self.pending_rename.is_some() {
4329 return;
4330 }
4331
4332 let Some(provider) = self.completion_provider.as_ref() else {
4333 return;
4334 };
4335
4336 let position = self.selections.newest_anchor().head();
4337 let (buffer, buffer_position) =
4338 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4339 output
4340 } else {
4341 return;
4342 };
4343
4344 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4345 let is_followup_invoke = {
4346 let context_menu_state = self.context_menu.read();
4347 matches!(
4348 context_menu_state.deref(),
4349 Some(ContextMenu::Completions(_))
4350 )
4351 };
4352 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4353 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4354 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4355 CompletionTriggerKind::TRIGGER_CHARACTER
4356 }
4357
4358 _ => CompletionTriggerKind::INVOKED,
4359 };
4360 let completion_context = CompletionContext {
4361 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4362 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4363 Some(String::from(trigger))
4364 } else {
4365 None
4366 }
4367 }),
4368 trigger_kind,
4369 };
4370 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4371 let sort_completions = provider.sort_completions();
4372
4373 let id = post_inc(&mut self.next_completion_id);
4374 let task = cx.spawn(|this, mut cx| {
4375 async move {
4376 this.update(&mut cx, |this, _| {
4377 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4378 })?;
4379 let completions = completions.await.log_err();
4380 let menu = if let Some(completions) = completions {
4381 let mut menu = CompletionsMenu {
4382 id,
4383 sort_completions,
4384 initial_position: position,
4385 match_candidates: completions
4386 .iter()
4387 .enumerate()
4388 .map(|(id, completion)| {
4389 StringMatchCandidate::new(
4390 id,
4391 completion.label.text[completion.label.filter_range.clone()]
4392 .into(),
4393 )
4394 })
4395 .collect(),
4396 buffer: buffer.clone(),
4397 completions: Arc::new(RwLock::new(completions.into())),
4398 matches: Vec::new().into(),
4399 selected_item: 0,
4400 scroll_handle: UniformListScrollHandle::new(),
4401 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4402 DebouncedDelay::new(),
4403 )),
4404 };
4405 menu.filter(query.as_deref(), cx.background_executor().clone())
4406 .await;
4407
4408 if menu.matches.is_empty() {
4409 None
4410 } else {
4411 this.update(&mut cx, |editor, cx| {
4412 let completions = menu.completions.clone();
4413 let matches = menu.matches.clone();
4414
4415 let delay_ms = EditorSettings::get_global(cx)
4416 .completion_documentation_secondary_query_debounce;
4417 let delay = Duration::from_millis(delay_ms);
4418 editor
4419 .completion_documentation_pre_resolve_debounce
4420 .fire_new(delay, cx, |editor, cx| {
4421 CompletionsMenu::pre_resolve_completion_documentation(
4422 buffer,
4423 completions,
4424 matches,
4425 editor,
4426 cx,
4427 )
4428 });
4429 })
4430 .ok();
4431 Some(menu)
4432 }
4433 } else {
4434 None
4435 };
4436
4437 this.update(&mut cx, |this, cx| {
4438 let mut context_menu = this.context_menu.write();
4439 match context_menu.as_ref() {
4440 None => {}
4441
4442 Some(ContextMenu::Completions(prev_menu)) => {
4443 if prev_menu.id > id {
4444 return;
4445 }
4446 }
4447
4448 _ => return,
4449 }
4450
4451 if this.focus_handle.is_focused(cx) && menu.is_some() {
4452 let menu = menu.unwrap();
4453 *context_menu = Some(ContextMenu::Completions(menu));
4454 drop(context_menu);
4455 this.discard_inline_completion(false, cx);
4456 cx.notify();
4457 } else if this.completion_tasks.len() <= 1 {
4458 // If there are no more completion tasks and the last menu was
4459 // empty, we should hide it. If it was already hidden, we should
4460 // also show the copilot completion when available.
4461 drop(context_menu);
4462 if this.hide_context_menu(cx).is_none() {
4463 this.update_visible_inline_completion(cx);
4464 }
4465 }
4466 })?;
4467
4468 Ok::<_, anyhow::Error>(())
4469 }
4470 .log_err()
4471 });
4472
4473 self.completion_tasks.push((id, task));
4474 }
4475
4476 pub fn confirm_completion(
4477 &mut self,
4478 action: &ConfirmCompletion,
4479 cx: &mut ViewContext<Self>,
4480 ) -> Option<Task<Result<()>>> {
4481 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4482 }
4483
4484 pub fn compose_completion(
4485 &mut self,
4486 action: &ComposeCompletion,
4487 cx: &mut ViewContext<Self>,
4488 ) -> Option<Task<Result<()>>> {
4489 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4490 }
4491
4492 fn do_completion(
4493 &mut self,
4494 item_ix: Option<usize>,
4495 intent: CompletionIntent,
4496 cx: &mut ViewContext<Editor>,
4497 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4498 use language::ToOffset as _;
4499
4500 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4501 menu
4502 } else {
4503 return None;
4504 };
4505
4506 let mat = completions_menu
4507 .matches
4508 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4509 let buffer_handle = completions_menu.buffer;
4510 let completions = completions_menu.completions.read();
4511 let completion = completions.get(mat.candidate_id)?;
4512 cx.stop_propagation();
4513
4514 let snippet;
4515 let text;
4516
4517 if completion.is_snippet() {
4518 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4519 text = snippet.as_ref().unwrap().text.clone();
4520 } else {
4521 snippet = None;
4522 text = completion.new_text.clone();
4523 };
4524 let selections = self.selections.all::<usize>(cx);
4525 let buffer = buffer_handle.read(cx);
4526 let old_range = completion.old_range.to_offset(buffer);
4527 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4528
4529 let newest_selection = self.selections.newest_anchor();
4530 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4531 return None;
4532 }
4533
4534 let lookbehind = newest_selection
4535 .start
4536 .text_anchor
4537 .to_offset(buffer)
4538 .saturating_sub(old_range.start);
4539 let lookahead = old_range
4540 .end
4541 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4542 let mut common_prefix_len = old_text
4543 .bytes()
4544 .zip(text.bytes())
4545 .take_while(|(a, b)| a == b)
4546 .count();
4547
4548 let snapshot = self.buffer.read(cx).snapshot(cx);
4549 let mut range_to_replace: Option<Range<isize>> = None;
4550 let mut ranges = Vec::new();
4551 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4552 for selection in &selections {
4553 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4554 let start = selection.start.saturating_sub(lookbehind);
4555 let end = selection.end + lookahead;
4556 if selection.id == newest_selection.id {
4557 range_to_replace = Some(
4558 ((start + common_prefix_len) as isize - selection.start as isize)
4559 ..(end as isize - selection.start as isize),
4560 );
4561 }
4562 ranges.push(start + common_prefix_len..end);
4563 } else {
4564 common_prefix_len = 0;
4565 ranges.clear();
4566 ranges.extend(selections.iter().map(|s| {
4567 if s.id == newest_selection.id {
4568 range_to_replace = Some(
4569 old_range.start.to_offset_utf16(&snapshot).0 as isize
4570 - selection.start as isize
4571 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4572 - selection.start as isize,
4573 );
4574 old_range.clone()
4575 } else {
4576 s.start..s.end
4577 }
4578 }));
4579 break;
4580 }
4581 if !self.linked_edit_ranges.is_empty() {
4582 let start_anchor = snapshot.anchor_before(selection.head());
4583 let end_anchor = snapshot.anchor_after(selection.tail());
4584 if let Some(ranges) = self
4585 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4586 {
4587 for (buffer, edits) in ranges {
4588 linked_edits.entry(buffer.clone()).or_default().extend(
4589 edits
4590 .into_iter()
4591 .map(|range| (range, text[common_prefix_len..].to_owned())),
4592 );
4593 }
4594 }
4595 }
4596 }
4597 let text = &text[common_prefix_len..];
4598
4599 cx.emit(EditorEvent::InputHandled {
4600 utf16_range_to_replace: range_to_replace,
4601 text: text.into(),
4602 });
4603
4604 self.transact(cx, |this, cx| {
4605 if let Some(mut snippet) = snippet {
4606 snippet.text = text.to_string();
4607 for tabstop in snippet.tabstops.iter_mut().flatten() {
4608 tabstop.start -= common_prefix_len as isize;
4609 tabstop.end -= common_prefix_len as isize;
4610 }
4611
4612 this.insert_snippet(&ranges, snippet, cx).log_err();
4613 } else {
4614 this.buffer.update(cx, |buffer, cx| {
4615 buffer.edit(
4616 ranges.iter().map(|range| (range.clone(), text)),
4617 this.autoindent_mode.clone(),
4618 cx,
4619 );
4620 });
4621 }
4622 for (buffer, edits) in linked_edits {
4623 buffer.update(cx, |buffer, cx| {
4624 let snapshot = buffer.snapshot();
4625 let edits = edits
4626 .into_iter()
4627 .map(|(range, text)| {
4628 use text::ToPoint as TP;
4629 let end_point = TP::to_point(&range.end, &snapshot);
4630 let start_point = TP::to_point(&range.start, &snapshot);
4631 (start_point..end_point, text)
4632 })
4633 .sorted_by_key(|(range, _)| range.start)
4634 .collect::<Vec<_>>();
4635 buffer.edit(edits, None, cx);
4636 })
4637 }
4638
4639 this.refresh_inline_completion(true, false, cx);
4640 });
4641
4642 let show_new_completions_on_confirm = completion
4643 .confirm
4644 .as_ref()
4645 .map_or(false, |confirm| confirm(intent, cx));
4646 if show_new_completions_on_confirm {
4647 self.show_completions(&ShowCompletions { trigger: None }, cx);
4648 }
4649
4650 let provider = self.completion_provider.as_ref()?;
4651 let apply_edits = provider.apply_additional_edits_for_completion(
4652 buffer_handle,
4653 completion.clone(),
4654 true,
4655 cx,
4656 );
4657
4658 let editor_settings = EditorSettings::get_global(cx);
4659 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4660 // After the code completion is finished, users often want to know what signatures are needed.
4661 // so we should automatically call signature_help
4662 self.show_signature_help(&ShowSignatureHelp, cx);
4663 }
4664
4665 Some(cx.foreground_executor().spawn(async move {
4666 apply_edits.await?;
4667 Ok(())
4668 }))
4669 }
4670
4671 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4672 let mut context_menu = self.context_menu.write();
4673 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4674 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4675 // Toggle if we're selecting the same one
4676 *context_menu = None;
4677 cx.notify();
4678 return;
4679 } else {
4680 // Otherwise, clear it and start a new one
4681 *context_menu = None;
4682 cx.notify();
4683 }
4684 }
4685 drop(context_menu);
4686 let snapshot = self.snapshot(cx);
4687 let deployed_from_indicator = action.deployed_from_indicator;
4688 let mut task = self.code_actions_task.take();
4689 let action = action.clone();
4690 cx.spawn(|editor, mut cx| async move {
4691 while let Some(prev_task) = task {
4692 prev_task.await.log_err();
4693 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4694 }
4695
4696 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4697 if editor.focus_handle.is_focused(cx) {
4698 let multibuffer_point = action
4699 .deployed_from_indicator
4700 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4701 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4702 let (buffer, buffer_row) = snapshot
4703 .buffer_snapshot
4704 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4705 .and_then(|(buffer_snapshot, range)| {
4706 editor
4707 .buffer
4708 .read(cx)
4709 .buffer(buffer_snapshot.remote_id())
4710 .map(|buffer| (buffer, range.start.row))
4711 })?;
4712 let (_, code_actions) = editor
4713 .available_code_actions
4714 .clone()
4715 .and_then(|(location, code_actions)| {
4716 let snapshot = location.buffer.read(cx).snapshot();
4717 let point_range = location.range.to_point(&snapshot);
4718 let point_range = point_range.start.row..=point_range.end.row;
4719 if point_range.contains(&buffer_row) {
4720 Some((location, code_actions))
4721 } else {
4722 None
4723 }
4724 })
4725 .unzip();
4726 let buffer_id = buffer.read(cx).remote_id();
4727 let tasks = editor
4728 .tasks
4729 .get(&(buffer_id, buffer_row))
4730 .map(|t| Arc::new(t.to_owned()));
4731 if tasks.is_none() && code_actions.is_none() {
4732 return None;
4733 }
4734
4735 editor.completion_tasks.clear();
4736 editor.discard_inline_completion(false, cx);
4737 let task_context =
4738 tasks
4739 .as_ref()
4740 .zip(editor.project.clone())
4741 .map(|(tasks, project)| {
4742 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4743 });
4744
4745 Some(cx.spawn(|editor, mut cx| async move {
4746 let task_context = match task_context {
4747 Some(task_context) => task_context.await,
4748 None => None,
4749 };
4750 let resolved_tasks =
4751 tasks.zip(task_context).map(|(tasks, task_context)| {
4752 Arc::new(ResolvedTasks {
4753 templates: tasks.resolve(&task_context).collect(),
4754 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4755 multibuffer_point.row,
4756 tasks.column,
4757 )),
4758 })
4759 });
4760 let spawn_straight_away = resolved_tasks
4761 .as_ref()
4762 .map_or(false, |tasks| tasks.templates.len() == 1)
4763 && code_actions
4764 .as_ref()
4765 .map_or(true, |actions| actions.is_empty());
4766 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4767 *editor.context_menu.write() =
4768 Some(ContextMenu::CodeActions(CodeActionsMenu {
4769 buffer,
4770 actions: CodeActionContents {
4771 tasks: resolved_tasks,
4772 actions: code_actions,
4773 },
4774 selected_item: Default::default(),
4775 scroll_handle: UniformListScrollHandle::default(),
4776 deployed_from_indicator,
4777 }));
4778 if spawn_straight_away {
4779 if let Some(task) = editor.confirm_code_action(
4780 &ConfirmCodeAction { item_ix: Some(0) },
4781 cx,
4782 ) {
4783 cx.notify();
4784 return task;
4785 }
4786 }
4787 cx.notify();
4788 Task::ready(Ok(()))
4789 }) {
4790 task.await
4791 } else {
4792 Ok(())
4793 }
4794 }))
4795 } else {
4796 Some(Task::ready(Ok(())))
4797 }
4798 })?;
4799 if let Some(task) = spawned_test_task {
4800 task.await?;
4801 }
4802
4803 Ok::<_, anyhow::Error>(())
4804 })
4805 .detach_and_log_err(cx);
4806 }
4807
4808 pub fn confirm_code_action(
4809 &mut self,
4810 action: &ConfirmCodeAction,
4811 cx: &mut ViewContext<Self>,
4812 ) -> Option<Task<Result<()>>> {
4813 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4814 menu
4815 } else {
4816 return None;
4817 };
4818 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4819 let action = actions_menu.actions.get(action_ix)?;
4820 let title = action.label();
4821 let buffer = actions_menu.buffer;
4822 let workspace = self.workspace()?;
4823
4824 match action {
4825 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4826 workspace.update(cx, |workspace, cx| {
4827 workspace::tasks::schedule_resolved_task(
4828 workspace,
4829 task_source_kind,
4830 resolved_task,
4831 false,
4832 cx,
4833 );
4834
4835 Some(Task::ready(Ok(())))
4836 })
4837 }
4838 CodeActionsItem::CodeAction {
4839 excerpt_id,
4840 action,
4841 provider,
4842 } => {
4843 let apply_code_action =
4844 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4845 let workspace = workspace.downgrade();
4846 Some(cx.spawn(|editor, cx| async move {
4847 let project_transaction = apply_code_action.await?;
4848 Self::open_project_transaction(
4849 &editor,
4850 workspace,
4851 project_transaction,
4852 title,
4853 cx,
4854 )
4855 .await
4856 }))
4857 }
4858 }
4859 }
4860
4861 pub async fn open_project_transaction(
4862 this: &WeakView<Editor>,
4863 workspace: WeakView<Workspace>,
4864 transaction: ProjectTransaction,
4865 title: String,
4866 mut cx: AsyncWindowContext,
4867 ) -> Result<()> {
4868 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4869 cx.update(|cx| {
4870 entries.sort_unstable_by_key(|(buffer, _)| {
4871 buffer.read(cx).file().map(|f| f.path().clone())
4872 });
4873 })?;
4874
4875 // If the project transaction's edits are all contained within this editor, then
4876 // avoid opening a new editor to display them.
4877
4878 if let Some((buffer, transaction)) = entries.first() {
4879 if entries.len() == 1 {
4880 let excerpt = this.update(&mut cx, |editor, cx| {
4881 editor
4882 .buffer()
4883 .read(cx)
4884 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4885 })?;
4886 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4887 if excerpted_buffer == *buffer {
4888 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4889 let excerpt_range = excerpt_range.to_offset(buffer);
4890 buffer
4891 .edited_ranges_for_transaction::<usize>(transaction)
4892 .all(|range| {
4893 excerpt_range.start <= range.start
4894 && excerpt_range.end >= range.end
4895 })
4896 })?;
4897
4898 if all_edits_within_excerpt {
4899 return Ok(());
4900 }
4901 }
4902 }
4903 }
4904 } else {
4905 return Ok(());
4906 }
4907
4908 let mut ranges_to_highlight = Vec::new();
4909 let excerpt_buffer = cx.new_model(|cx| {
4910 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4911 for (buffer_handle, transaction) in &entries {
4912 let buffer = buffer_handle.read(cx);
4913 ranges_to_highlight.extend(
4914 multibuffer.push_excerpts_with_context_lines(
4915 buffer_handle.clone(),
4916 buffer
4917 .edited_ranges_for_transaction::<usize>(transaction)
4918 .collect(),
4919 DEFAULT_MULTIBUFFER_CONTEXT,
4920 cx,
4921 ),
4922 );
4923 }
4924 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4925 multibuffer
4926 })?;
4927
4928 workspace.update(&mut cx, |workspace, cx| {
4929 let project = workspace.project().clone();
4930 let editor =
4931 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4932 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4933 editor.update(cx, |editor, cx| {
4934 editor.highlight_background::<Self>(
4935 &ranges_to_highlight,
4936 |theme| theme.editor_highlighted_line_background,
4937 cx,
4938 );
4939 });
4940 })?;
4941
4942 Ok(())
4943 }
4944
4945 pub fn clear_code_action_providers(&mut self) {
4946 self.code_action_providers.clear();
4947 self.available_code_actions.take();
4948 }
4949
4950 pub fn push_code_action_provider(
4951 &mut self,
4952 provider: Arc<dyn CodeActionProvider>,
4953 cx: &mut ViewContext<Self>,
4954 ) {
4955 self.code_action_providers.push(provider);
4956 self.refresh_code_actions(cx);
4957 }
4958
4959 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4960 let buffer = self.buffer.read(cx);
4961 let newest_selection = self.selections.newest_anchor().clone();
4962 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4963 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4964 if start_buffer != end_buffer {
4965 return None;
4966 }
4967
4968 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4969 cx.background_executor()
4970 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4971 .await;
4972
4973 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4974 let providers = this.code_action_providers.clone();
4975 let tasks = this
4976 .code_action_providers
4977 .iter()
4978 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4979 .collect::<Vec<_>>();
4980 (providers, tasks)
4981 })?;
4982
4983 let mut actions = Vec::new();
4984 for (provider, provider_actions) in
4985 providers.into_iter().zip(future::join_all(tasks).await)
4986 {
4987 if let Some(provider_actions) = provider_actions.log_err() {
4988 actions.extend(provider_actions.into_iter().map(|action| {
4989 AvailableCodeAction {
4990 excerpt_id: newest_selection.start.excerpt_id,
4991 action,
4992 provider: provider.clone(),
4993 }
4994 }));
4995 }
4996 }
4997
4998 this.update(&mut cx, |this, cx| {
4999 this.available_code_actions = if actions.is_empty() {
5000 None
5001 } else {
5002 Some((
5003 Location {
5004 buffer: start_buffer,
5005 range: start..end,
5006 },
5007 actions.into(),
5008 ))
5009 };
5010 cx.notify();
5011 })
5012 }));
5013 None
5014 }
5015
5016 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5017 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5018 self.show_git_blame_inline = false;
5019
5020 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5021 cx.background_executor().timer(delay).await;
5022
5023 this.update(&mut cx, |this, cx| {
5024 this.show_git_blame_inline = true;
5025 cx.notify();
5026 })
5027 .log_err();
5028 }));
5029 }
5030 }
5031
5032 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5033 if self.pending_rename.is_some() {
5034 return None;
5035 }
5036
5037 let provider = self.semantics_provider.clone()?;
5038 let buffer = self.buffer.read(cx);
5039 let newest_selection = self.selections.newest_anchor().clone();
5040 let cursor_position = newest_selection.head();
5041 let (cursor_buffer, cursor_buffer_position) =
5042 buffer.text_anchor_for_position(cursor_position, cx)?;
5043 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5044 if cursor_buffer != tail_buffer {
5045 return None;
5046 }
5047
5048 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5049 cx.background_executor()
5050 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5051 .await;
5052
5053 let highlights = if let Some(highlights) = cx
5054 .update(|cx| {
5055 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5056 })
5057 .ok()
5058 .flatten()
5059 {
5060 highlights.await.log_err()
5061 } else {
5062 None
5063 };
5064
5065 if let Some(highlights) = highlights {
5066 this.update(&mut cx, |this, cx| {
5067 if this.pending_rename.is_some() {
5068 return;
5069 }
5070
5071 let buffer_id = cursor_position.buffer_id;
5072 let buffer = this.buffer.read(cx);
5073 if !buffer
5074 .text_anchor_for_position(cursor_position, cx)
5075 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5076 {
5077 return;
5078 }
5079
5080 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5081 let mut write_ranges = Vec::new();
5082 let mut read_ranges = Vec::new();
5083 for highlight in highlights {
5084 for (excerpt_id, excerpt_range) in
5085 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5086 {
5087 let start = highlight
5088 .range
5089 .start
5090 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5091 let end = highlight
5092 .range
5093 .end
5094 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5095 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5096 continue;
5097 }
5098
5099 let range = Anchor {
5100 buffer_id,
5101 excerpt_id,
5102 text_anchor: start,
5103 }..Anchor {
5104 buffer_id,
5105 excerpt_id,
5106 text_anchor: end,
5107 };
5108 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5109 write_ranges.push(range);
5110 } else {
5111 read_ranges.push(range);
5112 }
5113 }
5114 }
5115
5116 this.highlight_background::<DocumentHighlightRead>(
5117 &read_ranges,
5118 |theme| theme.editor_document_highlight_read_background,
5119 cx,
5120 );
5121 this.highlight_background::<DocumentHighlightWrite>(
5122 &write_ranges,
5123 |theme| theme.editor_document_highlight_write_background,
5124 cx,
5125 );
5126 cx.notify();
5127 })
5128 .log_err();
5129 }
5130 }));
5131 None
5132 }
5133
5134 pub fn refresh_inline_completion(
5135 &mut self,
5136 debounce: bool,
5137 user_requested: bool,
5138 cx: &mut ViewContext<Self>,
5139 ) -> Option<()> {
5140 let provider = self.inline_completion_provider()?;
5141 let cursor = self.selections.newest_anchor().head();
5142 let (buffer, cursor_buffer_position) =
5143 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5144
5145 if !user_requested
5146 && (!self.enable_inline_completions
5147 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5148 {
5149 self.discard_inline_completion(false, cx);
5150 return None;
5151 }
5152
5153 self.update_visible_inline_completion(cx);
5154 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5155 Some(())
5156 }
5157
5158 fn cycle_inline_completion(
5159 &mut self,
5160 direction: Direction,
5161 cx: &mut ViewContext<Self>,
5162 ) -> Option<()> {
5163 let provider = self.inline_completion_provider()?;
5164 let cursor = self.selections.newest_anchor().head();
5165 let (buffer, cursor_buffer_position) =
5166 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5167 if !self.enable_inline_completions
5168 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5169 {
5170 return None;
5171 }
5172
5173 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5174 self.update_visible_inline_completion(cx);
5175
5176 Some(())
5177 }
5178
5179 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5180 if !self.has_active_inline_completion(cx) {
5181 self.refresh_inline_completion(false, true, cx);
5182 return;
5183 }
5184
5185 self.update_visible_inline_completion(cx);
5186 }
5187
5188 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5189 self.show_cursor_names(cx);
5190 }
5191
5192 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5193 self.show_cursor_names = true;
5194 cx.notify();
5195 cx.spawn(|this, mut cx| async move {
5196 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5197 this.update(&mut cx, |this, cx| {
5198 this.show_cursor_names = false;
5199 cx.notify()
5200 })
5201 .ok()
5202 })
5203 .detach();
5204 }
5205
5206 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5207 if self.has_active_inline_completion(cx) {
5208 self.cycle_inline_completion(Direction::Next, cx);
5209 } else {
5210 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5211 if is_copilot_disabled {
5212 cx.propagate();
5213 }
5214 }
5215 }
5216
5217 pub fn previous_inline_completion(
5218 &mut self,
5219 _: &PreviousInlineCompletion,
5220 cx: &mut ViewContext<Self>,
5221 ) {
5222 if self.has_active_inline_completion(cx) {
5223 self.cycle_inline_completion(Direction::Prev, cx);
5224 } else {
5225 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5226 if is_copilot_disabled {
5227 cx.propagate();
5228 }
5229 }
5230 }
5231
5232 pub fn accept_inline_completion(
5233 &mut self,
5234 _: &AcceptInlineCompletion,
5235 cx: &mut ViewContext<Self>,
5236 ) {
5237 let Some(completion) = self.take_active_inline_completion(cx) else {
5238 return;
5239 };
5240 if let Some(provider) = self.inline_completion_provider() {
5241 provider.accept(cx);
5242 }
5243
5244 cx.emit(EditorEvent::InputHandled {
5245 utf16_range_to_replace: None,
5246 text: completion.text.to_string().into(),
5247 });
5248
5249 if let Some(range) = completion.delete_range {
5250 self.change_selections(None, cx, |s| s.select_ranges([range]))
5251 }
5252 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5253 self.refresh_inline_completion(true, true, cx);
5254 cx.notify();
5255 }
5256
5257 pub fn accept_partial_inline_completion(
5258 &mut self,
5259 _: &AcceptPartialInlineCompletion,
5260 cx: &mut ViewContext<Self>,
5261 ) {
5262 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5263 if let Some(completion) = self.take_active_inline_completion(cx) {
5264 let mut partial_completion = completion
5265 .text
5266 .chars()
5267 .by_ref()
5268 .take_while(|c| c.is_alphabetic())
5269 .collect::<String>();
5270 if partial_completion.is_empty() {
5271 partial_completion = completion
5272 .text
5273 .chars()
5274 .by_ref()
5275 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5276 .collect::<String>();
5277 }
5278
5279 cx.emit(EditorEvent::InputHandled {
5280 utf16_range_to_replace: None,
5281 text: partial_completion.clone().into(),
5282 });
5283
5284 if let Some(range) = completion.delete_range {
5285 self.change_selections(None, cx, |s| s.select_ranges([range]))
5286 }
5287 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5288
5289 self.refresh_inline_completion(true, true, cx);
5290 cx.notify();
5291 }
5292 }
5293 }
5294
5295 fn discard_inline_completion(
5296 &mut self,
5297 should_report_inline_completion_event: bool,
5298 cx: &mut ViewContext<Self>,
5299 ) -> bool {
5300 if let Some(provider) = self.inline_completion_provider() {
5301 provider.discard(should_report_inline_completion_event, cx);
5302 }
5303
5304 self.take_active_inline_completion(cx).is_some()
5305 }
5306
5307 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5308 if let Some(completion) = self.active_inline_completion.as_ref() {
5309 let buffer = self.buffer.read(cx).read(cx);
5310 completion.position.is_valid(&buffer)
5311 } else {
5312 false
5313 }
5314 }
5315
5316 fn take_active_inline_completion(
5317 &mut self,
5318 cx: &mut ViewContext<Self>,
5319 ) -> Option<CompletionState> {
5320 let completion = self.active_inline_completion.take()?;
5321 let render_inlay_ids = completion.render_inlay_ids.clone();
5322 self.display_map.update(cx, |map, cx| {
5323 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5324 });
5325 let buffer = self.buffer.read(cx).read(cx);
5326
5327 if completion.position.is_valid(&buffer) {
5328 Some(completion)
5329 } else {
5330 None
5331 }
5332 }
5333
5334 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5335 let selection = self.selections.newest_anchor();
5336 let cursor = selection.head();
5337
5338 let excerpt_id = cursor.excerpt_id;
5339
5340 if self.context_menu.read().is_none()
5341 && self.completion_tasks.is_empty()
5342 && selection.start == selection.end
5343 {
5344 if let Some(provider) = self.inline_completion_provider() {
5345 if let Some((buffer, cursor_buffer_position)) =
5346 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5347 {
5348 if let Some(proposal) =
5349 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5350 {
5351 let mut to_remove = Vec::new();
5352 if let Some(completion) = self.active_inline_completion.take() {
5353 to_remove.extend(completion.render_inlay_ids.iter());
5354 }
5355
5356 let to_add = proposal
5357 .inlays
5358 .iter()
5359 .filter_map(|inlay| {
5360 let snapshot = self.buffer.read(cx).snapshot(cx);
5361 let id = post_inc(&mut self.next_inlay_id);
5362 match inlay {
5363 InlayProposal::Hint(position, hint) => {
5364 let position =
5365 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5366 Some(Inlay::hint(id, position, hint))
5367 }
5368 InlayProposal::Suggestion(position, text) => {
5369 let position =
5370 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5371 Some(Inlay::suggestion(id, position, text.clone()))
5372 }
5373 }
5374 })
5375 .collect_vec();
5376
5377 self.active_inline_completion = Some(CompletionState {
5378 position: cursor,
5379 text: proposal.text,
5380 delete_range: proposal.delete_range.and_then(|range| {
5381 let snapshot = self.buffer.read(cx).snapshot(cx);
5382 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5383 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5384 Some(start?..end?)
5385 }),
5386 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5387 });
5388
5389 self.display_map
5390 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5391
5392 cx.notify();
5393 return;
5394 }
5395 }
5396 }
5397 }
5398
5399 self.discard_inline_completion(false, cx);
5400 }
5401
5402 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5403 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5404 }
5405
5406 fn render_code_actions_indicator(
5407 &self,
5408 _style: &EditorStyle,
5409 row: DisplayRow,
5410 is_active: bool,
5411 cx: &mut ViewContext<Self>,
5412 ) -> Option<IconButton> {
5413 if self.available_code_actions.is_some() {
5414 Some(
5415 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5416 .shape(ui::IconButtonShape::Square)
5417 .icon_size(IconSize::XSmall)
5418 .icon_color(Color::Muted)
5419 .selected(is_active)
5420 .tooltip({
5421 let focus_handle = self.focus_handle.clone();
5422 move |cx| {
5423 Tooltip::for_action_in(
5424 "Toggle Code Actions",
5425 &ToggleCodeActions {
5426 deployed_from_indicator: None,
5427 },
5428 &focus_handle,
5429 cx,
5430 )
5431 }
5432 })
5433 .on_click(cx.listener(move |editor, _e, cx| {
5434 editor.focus(cx);
5435 editor.toggle_code_actions(
5436 &ToggleCodeActions {
5437 deployed_from_indicator: Some(row),
5438 },
5439 cx,
5440 );
5441 })),
5442 )
5443 } else {
5444 None
5445 }
5446 }
5447
5448 fn clear_tasks(&mut self) {
5449 self.tasks.clear()
5450 }
5451
5452 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5453 if self.tasks.insert(key, value).is_some() {
5454 // This case should hopefully be rare, but just in case...
5455 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5456 }
5457 }
5458
5459 fn build_tasks_context(
5460 project: &Model<Project>,
5461 buffer: &Model<Buffer>,
5462 buffer_row: u32,
5463 tasks: &Arc<RunnableTasks>,
5464 cx: &mut ViewContext<Self>,
5465 ) -> Task<Option<task::TaskContext>> {
5466 let position = Point::new(buffer_row, tasks.column);
5467 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5468 let location = Location {
5469 buffer: buffer.clone(),
5470 range: range_start..range_start,
5471 };
5472 // Fill in the environmental variables from the tree-sitter captures
5473 let mut captured_task_variables = TaskVariables::default();
5474 for (capture_name, value) in tasks.extra_variables.clone() {
5475 captured_task_variables.insert(
5476 task::VariableName::Custom(capture_name.into()),
5477 value.clone(),
5478 );
5479 }
5480 project.update(cx, |project, cx| {
5481 project.task_store().update(cx, |task_store, cx| {
5482 task_store.task_context_for_location(captured_task_variables, location, cx)
5483 })
5484 })
5485 }
5486
5487 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5488 let Some((workspace, _)) = self.workspace.clone() else {
5489 return;
5490 };
5491 let Some(project) = self.project.clone() else {
5492 return;
5493 };
5494
5495 // Try to find a closest, enclosing node using tree-sitter that has a
5496 // task
5497 let Some((buffer, buffer_row, tasks)) = self
5498 .find_enclosing_node_task(cx)
5499 // Or find the task that's closest in row-distance.
5500 .or_else(|| self.find_closest_task(cx))
5501 else {
5502 return;
5503 };
5504
5505 let reveal_strategy = action.reveal;
5506 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5507 cx.spawn(|_, mut cx| async move {
5508 let context = task_context.await?;
5509 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5510
5511 let resolved = resolved_task.resolved.as_mut()?;
5512 resolved.reveal = reveal_strategy;
5513
5514 workspace
5515 .update(&mut cx, |workspace, cx| {
5516 workspace::tasks::schedule_resolved_task(
5517 workspace,
5518 task_source_kind,
5519 resolved_task,
5520 false,
5521 cx,
5522 );
5523 })
5524 .ok()
5525 })
5526 .detach();
5527 }
5528
5529 fn find_closest_task(
5530 &mut self,
5531 cx: &mut ViewContext<Self>,
5532 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5533 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5534
5535 let ((buffer_id, row), tasks) = self
5536 .tasks
5537 .iter()
5538 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5539
5540 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5541 let tasks = Arc::new(tasks.to_owned());
5542 Some((buffer, *row, tasks))
5543 }
5544
5545 fn find_enclosing_node_task(
5546 &mut self,
5547 cx: &mut ViewContext<Self>,
5548 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5549 let snapshot = self.buffer.read(cx).snapshot(cx);
5550 let offset = self.selections.newest::<usize>(cx).head();
5551 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5552 let buffer_id = excerpt.buffer().remote_id();
5553
5554 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5555 let mut cursor = layer.node().walk();
5556
5557 while cursor.goto_first_child_for_byte(offset).is_some() {
5558 if cursor.node().end_byte() == offset {
5559 cursor.goto_next_sibling();
5560 }
5561 }
5562
5563 // Ascend to the smallest ancestor that contains the range and has a task.
5564 loop {
5565 let node = cursor.node();
5566 let node_range = node.byte_range();
5567 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5568
5569 // Check if this node contains our offset
5570 if node_range.start <= offset && node_range.end >= offset {
5571 // If it contains offset, check for task
5572 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5573 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5574 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5575 }
5576 }
5577
5578 if !cursor.goto_parent() {
5579 break;
5580 }
5581 }
5582 None
5583 }
5584
5585 fn render_run_indicator(
5586 &self,
5587 _style: &EditorStyle,
5588 is_active: bool,
5589 row: DisplayRow,
5590 cx: &mut ViewContext<Self>,
5591 ) -> IconButton {
5592 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5593 .shape(ui::IconButtonShape::Square)
5594 .icon_size(IconSize::XSmall)
5595 .icon_color(Color::Muted)
5596 .selected(is_active)
5597 .on_click(cx.listener(move |editor, _e, cx| {
5598 editor.focus(cx);
5599 editor.toggle_code_actions(
5600 &ToggleCodeActions {
5601 deployed_from_indicator: Some(row),
5602 },
5603 cx,
5604 );
5605 }))
5606 }
5607
5608 pub fn context_menu_visible(&self) -> bool {
5609 self.context_menu
5610 .read()
5611 .as_ref()
5612 .map_or(false, |menu| menu.visible())
5613 }
5614
5615 fn render_context_menu(
5616 &self,
5617 cursor_position: DisplayPoint,
5618 style: &EditorStyle,
5619 max_height: Pixels,
5620 cx: &mut ViewContext<Editor>,
5621 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5622 self.context_menu.read().as_ref().map(|menu| {
5623 menu.render(
5624 cursor_position,
5625 style,
5626 max_height,
5627 self.workspace.as_ref().map(|(w, _)| w.clone()),
5628 cx,
5629 )
5630 })
5631 }
5632
5633 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5634 cx.notify();
5635 self.completion_tasks.clear();
5636 let context_menu = self.context_menu.write().take();
5637 if context_menu.is_some() {
5638 self.update_visible_inline_completion(cx);
5639 }
5640 context_menu
5641 }
5642
5643 pub fn insert_snippet(
5644 &mut self,
5645 insertion_ranges: &[Range<usize>],
5646 snippet: Snippet,
5647 cx: &mut ViewContext<Self>,
5648 ) -> Result<()> {
5649 struct Tabstop<T> {
5650 is_end_tabstop: bool,
5651 ranges: Vec<Range<T>>,
5652 }
5653
5654 let tabstops = self.buffer.update(cx, |buffer, cx| {
5655 let snippet_text: Arc<str> = snippet.text.clone().into();
5656 buffer.edit(
5657 insertion_ranges
5658 .iter()
5659 .cloned()
5660 .map(|range| (range, snippet_text.clone())),
5661 Some(AutoindentMode::EachLine),
5662 cx,
5663 );
5664
5665 let snapshot = &*buffer.read(cx);
5666 let snippet = &snippet;
5667 snippet
5668 .tabstops
5669 .iter()
5670 .map(|tabstop| {
5671 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5672 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5673 });
5674 let mut tabstop_ranges = tabstop
5675 .iter()
5676 .flat_map(|tabstop_range| {
5677 let mut delta = 0_isize;
5678 insertion_ranges.iter().map(move |insertion_range| {
5679 let insertion_start = insertion_range.start as isize + delta;
5680 delta +=
5681 snippet.text.len() as isize - insertion_range.len() as isize;
5682
5683 let start = ((insertion_start + tabstop_range.start) as usize)
5684 .min(snapshot.len());
5685 let end = ((insertion_start + tabstop_range.end) as usize)
5686 .min(snapshot.len());
5687 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5688 })
5689 })
5690 .collect::<Vec<_>>();
5691 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5692
5693 Tabstop {
5694 is_end_tabstop,
5695 ranges: tabstop_ranges,
5696 }
5697 })
5698 .collect::<Vec<_>>()
5699 });
5700 if let Some(tabstop) = tabstops.first() {
5701 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5702 s.select_ranges(tabstop.ranges.iter().cloned());
5703 });
5704
5705 // If we're already at the last tabstop and it's at the end of the snippet,
5706 // we're done, we don't need to keep the state around.
5707 if !tabstop.is_end_tabstop {
5708 let ranges = tabstops
5709 .into_iter()
5710 .map(|tabstop| tabstop.ranges)
5711 .collect::<Vec<_>>();
5712 self.snippet_stack.push(SnippetState {
5713 active_index: 0,
5714 ranges,
5715 });
5716 }
5717
5718 // Check whether the just-entered snippet ends with an auto-closable bracket.
5719 if self.autoclose_regions.is_empty() {
5720 let snapshot = self.buffer.read(cx).snapshot(cx);
5721 for selection in &mut self.selections.all::<Point>(cx) {
5722 let selection_head = selection.head();
5723 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5724 continue;
5725 };
5726
5727 let mut bracket_pair = None;
5728 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5729 let prev_chars = snapshot
5730 .reversed_chars_at(selection_head)
5731 .collect::<String>();
5732 for (pair, enabled) in scope.brackets() {
5733 if enabled
5734 && pair.close
5735 && prev_chars.starts_with(pair.start.as_str())
5736 && next_chars.starts_with(pair.end.as_str())
5737 {
5738 bracket_pair = Some(pair.clone());
5739 break;
5740 }
5741 }
5742 if let Some(pair) = bracket_pair {
5743 let start = snapshot.anchor_after(selection_head);
5744 let end = snapshot.anchor_after(selection_head);
5745 self.autoclose_regions.push(AutocloseRegion {
5746 selection_id: selection.id,
5747 range: start..end,
5748 pair,
5749 });
5750 }
5751 }
5752 }
5753 }
5754 Ok(())
5755 }
5756
5757 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5758 self.move_to_snippet_tabstop(Bias::Right, cx)
5759 }
5760
5761 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5762 self.move_to_snippet_tabstop(Bias::Left, cx)
5763 }
5764
5765 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5766 if let Some(mut snippet) = self.snippet_stack.pop() {
5767 match bias {
5768 Bias::Left => {
5769 if snippet.active_index > 0 {
5770 snippet.active_index -= 1;
5771 } else {
5772 self.snippet_stack.push(snippet);
5773 return false;
5774 }
5775 }
5776 Bias::Right => {
5777 if snippet.active_index + 1 < snippet.ranges.len() {
5778 snippet.active_index += 1;
5779 } else {
5780 self.snippet_stack.push(snippet);
5781 return false;
5782 }
5783 }
5784 }
5785 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5786 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5787 s.select_anchor_ranges(current_ranges.iter().cloned())
5788 });
5789 // If snippet state is not at the last tabstop, push it back on the stack
5790 if snippet.active_index + 1 < snippet.ranges.len() {
5791 self.snippet_stack.push(snippet);
5792 }
5793 return true;
5794 }
5795 }
5796
5797 false
5798 }
5799
5800 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5801 self.transact(cx, |this, cx| {
5802 this.select_all(&SelectAll, cx);
5803 this.insert("", cx);
5804 });
5805 }
5806
5807 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5808 self.transact(cx, |this, cx| {
5809 this.select_autoclose_pair(cx);
5810 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5811 if !this.linked_edit_ranges.is_empty() {
5812 let selections = this.selections.all::<MultiBufferPoint>(cx);
5813 let snapshot = this.buffer.read(cx).snapshot(cx);
5814
5815 for selection in selections.iter() {
5816 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5817 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5818 if selection_start.buffer_id != selection_end.buffer_id {
5819 continue;
5820 }
5821 if let Some(ranges) =
5822 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5823 {
5824 for (buffer, entries) in ranges {
5825 linked_ranges.entry(buffer).or_default().extend(entries);
5826 }
5827 }
5828 }
5829 }
5830
5831 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5832 if !this.selections.line_mode {
5833 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5834 for selection in &mut selections {
5835 if selection.is_empty() {
5836 let old_head = selection.head();
5837 let mut new_head =
5838 movement::left(&display_map, old_head.to_display_point(&display_map))
5839 .to_point(&display_map);
5840 if let Some((buffer, line_buffer_range)) = display_map
5841 .buffer_snapshot
5842 .buffer_line_for_row(MultiBufferRow(old_head.row))
5843 {
5844 let indent_size =
5845 buffer.indent_size_for_line(line_buffer_range.start.row);
5846 let indent_len = match indent_size.kind {
5847 IndentKind::Space => {
5848 buffer.settings_at(line_buffer_range.start, cx).tab_size
5849 }
5850 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5851 };
5852 if old_head.column <= indent_size.len && old_head.column > 0 {
5853 let indent_len = indent_len.get();
5854 new_head = cmp::min(
5855 new_head,
5856 MultiBufferPoint::new(
5857 old_head.row,
5858 ((old_head.column - 1) / indent_len) * indent_len,
5859 ),
5860 );
5861 }
5862 }
5863
5864 selection.set_head(new_head, SelectionGoal::None);
5865 }
5866 }
5867 }
5868
5869 this.signature_help_state.set_backspace_pressed(true);
5870 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5871 this.insert("", cx);
5872 let empty_str: Arc<str> = Arc::from("");
5873 for (buffer, edits) in linked_ranges {
5874 let snapshot = buffer.read(cx).snapshot();
5875 use text::ToPoint as TP;
5876
5877 let edits = edits
5878 .into_iter()
5879 .map(|range| {
5880 let end_point = TP::to_point(&range.end, &snapshot);
5881 let mut start_point = TP::to_point(&range.start, &snapshot);
5882
5883 if end_point == start_point {
5884 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5885 .saturating_sub(1);
5886 start_point = TP::to_point(&offset, &snapshot);
5887 };
5888
5889 (start_point..end_point, empty_str.clone())
5890 })
5891 .sorted_by_key(|(range, _)| range.start)
5892 .collect::<Vec<_>>();
5893 buffer.update(cx, |this, cx| {
5894 this.edit(edits, None, cx);
5895 })
5896 }
5897 this.refresh_inline_completion(true, false, cx);
5898 linked_editing_ranges::refresh_linked_ranges(this, cx);
5899 });
5900 }
5901
5902 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5903 self.transact(cx, |this, cx| {
5904 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5905 let line_mode = s.line_mode;
5906 s.move_with(|map, selection| {
5907 if selection.is_empty() && !line_mode {
5908 let cursor = movement::right(map, selection.head());
5909 selection.end = cursor;
5910 selection.reversed = true;
5911 selection.goal = SelectionGoal::None;
5912 }
5913 })
5914 });
5915 this.insert("", cx);
5916 this.refresh_inline_completion(true, false, cx);
5917 });
5918 }
5919
5920 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5921 if self.move_to_prev_snippet_tabstop(cx) {
5922 return;
5923 }
5924
5925 self.outdent(&Outdent, cx);
5926 }
5927
5928 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5929 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5930 return;
5931 }
5932
5933 let mut selections = self.selections.all_adjusted(cx);
5934 let buffer = self.buffer.read(cx);
5935 let snapshot = buffer.snapshot(cx);
5936 let rows_iter = selections.iter().map(|s| s.head().row);
5937 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5938
5939 let mut edits = Vec::new();
5940 let mut prev_edited_row = 0;
5941 let mut row_delta = 0;
5942 for selection in &mut selections {
5943 if selection.start.row != prev_edited_row {
5944 row_delta = 0;
5945 }
5946 prev_edited_row = selection.end.row;
5947
5948 // If the selection is non-empty, then increase the indentation of the selected lines.
5949 if !selection.is_empty() {
5950 row_delta =
5951 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5952 continue;
5953 }
5954
5955 // If the selection is empty and the cursor is in the leading whitespace before the
5956 // suggested indentation, then auto-indent the line.
5957 let cursor = selection.head();
5958 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5959 if let Some(suggested_indent) =
5960 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5961 {
5962 if cursor.column < suggested_indent.len
5963 && cursor.column <= current_indent.len
5964 && current_indent.len <= suggested_indent.len
5965 {
5966 selection.start = Point::new(cursor.row, suggested_indent.len);
5967 selection.end = selection.start;
5968 if row_delta == 0 {
5969 edits.extend(Buffer::edit_for_indent_size_adjustment(
5970 cursor.row,
5971 current_indent,
5972 suggested_indent,
5973 ));
5974 row_delta = suggested_indent.len - current_indent.len;
5975 }
5976 continue;
5977 }
5978 }
5979
5980 // Otherwise, insert a hard or soft tab.
5981 let settings = buffer.settings_at(cursor, cx);
5982 let tab_size = if settings.hard_tabs {
5983 IndentSize::tab()
5984 } else {
5985 let tab_size = settings.tab_size.get();
5986 let char_column = snapshot
5987 .text_for_range(Point::new(cursor.row, 0)..cursor)
5988 .flat_map(str::chars)
5989 .count()
5990 + row_delta as usize;
5991 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5992 IndentSize::spaces(chars_to_next_tab_stop)
5993 };
5994 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5995 selection.end = selection.start;
5996 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5997 row_delta += tab_size.len;
5998 }
5999
6000 self.transact(cx, |this, cx| {
6001 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6002 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6003 this.refresh_inline_completion(true, false, cx);
6004 });
6005 }
6006
6007 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6008 if self.read_only(cx) {
6009 return;
6010 }
6011 let mut selections = self.selections.all::<Point>(cx);
6012 let mut prev_edited_row = 0;
6013 let mut row_delta = 0;
6014 let mut edits = Vec::new();
6015 let buffer = self.buffer.read(cx);
6016 let snapshot = buffer.snapshot(cx);
6017 for selection in &mut selections {
6018 if selection.start.row != prev_edited_row {
6019 row_delta = 0;
6020 }
6021 prev_edited_row = selection.end.row;
6022
6023 row_delta =
6024 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6025 }
6026
6027 self.transact(cx, |this, cx| {
6028 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6029 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6030 });
6031 }
6032
6033 fn indent_selection(
6034 buffer: &MultiBuffer,
6035 snapshot: &MultiBufferSnapshot,
6036 selection: &mut Selection<Point>,
6037 edits: &mut Vec<(Range<Point>, String)>,
6038 delta_for_start_row: u32,
6039 cx: &AppContext,
6040 ) -> u32 {
6041 let settings = buffer.settings_at(selection.start, cx);
6042 let tab_size = settings.tab_size.get();
6043 let indent_kind = if settings.hard_tabs {
6044 IndentKind::Tab
6045 } else {
6046 IndentKind::Space
6047 };
6048 let mut start_row = selection.start.row;
6049 let mut end_row = selection.end.row + 1;
6050
6051 // If a selection ends at the beginning of a line, don't indent
6052 // that last line.
6053 if selection.end.column == 0 && selection.end.row > selection.start.row {
6054 end_row -= 1;
6055 }
6056
6057 // Avoid re-indenting a row that has already been indented by a
6058 // previous selection, but still update this selection's column
6059 // to reflect that indentation.
6060 if delta_for_start_row > 0 {
6061 start_row += 1;
6062 selection.start.column += delta_for_start_row;
6063 if selection.end.row == selection.start.row {
6064 selection.end.column += delta_for_start_row;
6065 }
6066 }
6067
6068 let mut delta_for_end_row = 0;
6069 let has_multiple_rows = start_row + 1 != end_row;
6070 for row in start_row..end_row {
6071 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6072 let indent_delta = match (current_indent.kind, indent_kind) {
6073 (IndentKind::Space, IndentKind::Space) => {
6074 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6075 IndentSize::spaces(columns_to_next_tab_stop)
6076 }
6077 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6078 (_, IndentKind::Tab) => IndentSize::tab(),
6079 };
6080
6081 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6082 0
6083 } else {
6084 selection.start.column
6085 };
6086 let row_start = Point::new(row, start);
6087 edits.push((
6088 row_start..row_start,
6089 indent_delta.chars().collect::<String>(),
6090 ));
6091
6092 // Update this selection's endpoints to reflect the indentation.
6093 if row == selection.start.row {
6094 selection.start.column += indent_delta.len;
6095 }
6096 if row == selection.end.row {
6097 selection.end.column += indent_delta.len;
6098 delta_for_end_row = indent_delta.len;
6099 }
6100 }
6101
6102 if selection.start.row == selection.end.row {
6103 delta_for_start_row + delta_for_end_row
6104 } else {
6105 delta_for_end_row
6106 }
6107 }
6108
6109 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6110 if self.read_only(cx) {
6111 return;
6112 }
6113 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6114 let selections = self.selections.all::<Point>(cx);
6115 let mut deletion_ranges = Vec::new();
6116 let mut last_outdent = None;
6117 {
6118 let buffer = self.buffer.read(cx);
6119 let snapshot = buffer.snapshot(cx);
6120 for selection in &selections {
6121 let settings = buffer.settings_at(selection.start, cx);
6122 let tab_size = settings.tab_size.get();
6123 let mut rows = selection.spanned_rows(false, &display_map);
6124
6125 // Avoid re-outdenting a row that has already been outdented by a
6126 // previous selection.
6127 if let Some(last_row) = last_outdent {
6128 if last_row == rows.start {
6129 rows.start = rows.start.next_row();
6130 }
6131 }
6132 let has_multiple_rows = rows.len() > 1;
6133 for row in rows.iter_rows() {
6134 let indent_size = snapshot.indent_size_for_line(row);
6135 if indent_size.len > 0 {
6136 let deletion_len = match indent_size.kind {
6137 IndentKind::Space => {
6138 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6139 if columns_to_prev_tab_stop == 0 {
6140 tab_size
6141 } else {
6142 columns_to_prev_tab_stop
6143 }
6144 }
6145 IndentKind::Tab => 1,
6146 };
6147 let start = if has_multiple_rows
6148 || deletion_len > selection.start.column
6149 || indent_size.len < selection.start.column
6150 {
6151 0
6152 } else {
6153 selection.start.column - deletion_len
6154 };
6155 deletion_ranges.push(
6156 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6157 );
6158 last_outdent = Some(row);
6159 }
6160 }
6161 }
6162 }
6163
6164 self.transact(cx, |this, cx| {
6165 this.buffer.update(cx, |buffer, cx| {
6166 let empty_str: Arc<str> = Arc::default();
6167 buffer.edit(
6168 deletion_ranges
6169 .into_iter()
6170 .map(|range| (range, empty_str.clone())),
6171 None,
6172 cx,
6173 );
6174 });
6175 let selections = this.selections.all::<usize>(cx);
6176 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6177 });
6178 }
6179
6180 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6181 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6182 let selections = self.selections.all::<Point>(cx);
6183
6184 let mut new_cursors = Vec::new();
6185 let mut edit_ranges = Vec::new();
6186 let mut selections = selections.iter().peekable();
6187 while let Some(selection) = selections.next() {
6188 let mut rows = selection.spanned_rows(false, &display_map);
6189 let goal_display_column = selection.head().to_display_point(&display_map).column();
6190
6191 // Accumulate contiguous regions of rows that we want to delete.
6192 while let Some(next_selection) = selections.peek() {
6193 let next_rows = next_selection.spanned_rows(false, &display_map);
6194 if next_rows.start <= rows.end {
6195 rows.end = next_rows.end;
6196 selections.next().unwrap();
6197 } else {
6198 break;
6199 }
6200 }
6201
6202 let buffer = &display_map.buffer_snapshot;
6203 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6204 let edit_end;
6205 let cursor_buffer_row;
6206 if buffer.max_point().row >= rows.end.0 {
6207 // If there's a line after the range, delete the \n from the end of the row range
6208 // and position the cursor on the next line.
6209 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6210 cursor_buffer_row = rows.end;
6211 } else {
6212 // If there isn't a line after the range, delete the \n from the line before the
6213 // start of the row range and position the cursor there.
6214 edit_start = edit_start.saturating_sub(1);
6215 edit_end = buffer.len();
6216 cursor_buffer_row = rows.start.previous_row();
6217 }
6218
6219 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6220 *cursor.column_mut() =
6221 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6222
6223 new_cursors.push((
6224 selection.id,
6225 buffer.anchor_after(cursor.to_point(&display_map)),
6226 ));
6227 edit_ranges.push(edit_start..edit_end);
6228 }
6229
6230 self.transact(cx, |this, cx| {
6231 let buffer = this.buffer.update(cx, |buffer, cx| {
6232 let empty_str: Arc<str> = Arc::default();
6233 buffer.edit(
6234 edit_ranges
6235 .into_iter()
6236 .map(|range| (range, empty_str.clone())),
6237 None,
6238 cx,
6239 );
6240 buffer.snapshot(cx)
6241 });
6242 let new_selections = new_cursors
6243 .into_iter()
6244 .map(|(id, cursor)| {
6245 let cursor = cursor.to_point(&buffer);
6246 Selection {
6247 id,
6248 start: cursor,
6249 end: cursor,
6250 reversed: false,
6251 goal: SelectionGoal::None,
6252 }
6253 })
6254 .collect();
6255
6256 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6257 s.select(new_selections);
6258 });
6259 });
6260 }
6261
6262 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6263 if self.read_only(cx) {
6264 return;
6265 }
6266 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6267 for selection in self.selections.all::<Point>(cx) {
6268 let start = MultiBufferRow(selection.start.row);
6269 let end = if selection.start.row == selection.end.row {
6270 MultiBufferRow(selection.start.row + 1)
6271 } else {
6272 MultiBufferRow(selection.end.row)
6273 };
6274
6275 if let Some(last_row_range) = row_ranges.last_mut() {
6276 if start <= last_row_range.end {
6277 last_row_range.end = end;
6278 continue;
6279 }
6280 }
6281 row_ranges.push(start..end);
6282 }
6283
6284 let snapshot = self.buffer.read(cx).snapshot(cx);
6285 let mut cursor_positions = Vec::new();
6286 for row_range in &row_ranges {
6287 let anchor = snapshot.anchor_before(Point::new(
6288 row_range.end.previous_row().0,
6289 snapshot.line_len(row_range.end.previous_row()),
6290 ));
6291 cursor_positions.push(anchor..anchor);
6292 }
6293
6294 self.transact(cx, |this, cx| {
6295 for row_range in row_ranges.into_iter().rev() {
6296 for row in row_range.iter_rows().rev() {
6297 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6298 let next_line_row = row.next_row();
6299 let indent = snapshot.indent_size_for_line(next_line_row);
6300 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6301
6302 let replace = if snapshot.line_len(next_line_row) > indent.len {
6303 " "
6304 } else {
6305 ""
6306 };
6307
6308 this.buffer.update(cx, |buffer, cx| {
6309 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6310 });
6311 }
6312 }
6313
6314 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6315 s.select_anchor_ranges(cursor_positions)
6316 });
6317 });
6318 }
6319
6320 pub fn sort_lines_case_sensitive(
6321 &mut self,
6322 _: &SortLinesCaseSensitive,
6323 cx: &mut ViewContext<Self>,
6324 ) {
6325 self.manipulate_lines(cx, |lines| lines.sort())
6326 }
6327
6328 pub fn sort_lines_case_insensitive(
6329 &mut self,
6330 _: &SortLinesCaseInsensitive,
6331 cx: &mut ViewContext<Self>,
6332 ) {
6333 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6334 }
6335
6336 pub fn unique_lines_case_insensitive(
6337 &mut self,
6338 _: &UniqueLinesCaseInsensitive,
6339 cx: &mut ViewContext<Self>,
6340 ) {
6341 self.manipulate_lines(cx, |lines| {
6342 let mut seen = HashSet::default();
6343 lines.retain(|line| seen.insert(line.to_lowercase()));
6344 })
6345 }
6346
6347 pub fn unique_lines_case_sensitive(
6348 &mut self,
6349 _: &UniqueLinesCaseSensitive,
6350 cx: &mut ViewContext<Self>,
6351 ) {
6352 self.manipulate_lines(cx, |lines| {
6353 let mut seen = HashSet::default();
6354 lines.retain(|line| seen.insert(*line));
6355 })
6356 }
6357
6358 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6359 let mut revert_changes = HashMap::default();
6360 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6361 for hunk in hunks_for_rows(
6362 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6363 &multi_buffer_snapshot,
6364 ) {
6365 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6366 }
6367 if !revert_changes.is_empty() {
6368 self.transact(cx, |editor, cx| {
6369 editor.revert(revert_changes, cx);
6370 });
6371 }
6372 }
6373
6374 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6375 let Some(project) = self.project.clone() else {
6376 return;
6377 };
6378 self.reload(project, cx).detach_and_notify_err(cx);
6379 }
6380
6381 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6382 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6383 if !revert_changes.is_empty() {
6384 self.transact(cx, |editor, cx| {
6385 editor.revert(revert_changes, cx);
6386 });
6387 }
6388 }
6389
6390 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6391 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6392 let project_path = buffer.read(cx).project_path(cx)?;
6393 let project = self.project.as_ref()?.read(cx);
6394 let entry = project.entry_for_path(&project_path, cx)?;
6395 let parent = match &entry.canonical_path {
6396 Some(canonical_path) => canonical_path.to_path_buf(),
6397 None => project.absolute_path(&project_path, cx)?,
6398 }
6399 .parent()?
6400 .to_path_buf();
6401 Some(parent)
6402 }) {
6403 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6404 }
6405 }
6406
6407 fn gather_revert_changes(
6408 &mut self,
6409 selections: &[Selection<Anchor>],
6410 cx: &mut ViewContext<'_, Editor>,
6411 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6412 let mut revert_changes = HashMap::default();
6413 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6414 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6415 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6416 }
6417 revert_changes
6418 }
6419
6420 pub fn prepare_revert_change(
6421 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6422 multi_buffer: &Model<MultiBuffer>,
6423 hunk: &MultiBufferDiffHunk,
6424 cx: &AppContext,
6425 ) -> Option<()> {
6426 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6427 let buffer = buffer.read(cx);
6428 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6429 let buffer_snapshot = buffer.snapshot();
6430 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6431 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6432 probe
6433 .0
6434 .start
6435 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6436 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6437 }) {
6438 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6439 Some(())
6440 } else {
6441 None
6442 }
6443 }
6444
6445 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6446 self.manipulate_lines(cx, |lines| lines.reverse())
6447 }
6448
6449 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6450 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6451 }
6452
6453 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6454 where
6455 Fn: FnMut(&mut Vec<&str>),
6456 {
6457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6458 let buffer = self.buffer.read(cx).snapshot(cx);
6459
6460 let mut edits = Vec::new();
6461
6462 let selections = self.selections.all::<Point>(cx);
6463 let mut selections = selections.iter().peekable();
6464 let mut contiguous_row_selections = Vec::new();
6465 let mut new_selections = Vec::new();
6466 let mut added_lines = 0;
6467 let mut removed_lines = 0;
6468
6469 while let Some(selection) = selections.next() {
6470 let (start_row, end_row) = consume_contiguous_rows(
6471 &mut contiguous_row_selections,
6472 selection,
6473 &display_map,
6474 &mut selections,
6475 );
6476
6477 let start_point = Point::new(start_row.0, 0);
6478 let end_point = Point::new(
6479 end_row.previous_row().0,
6480 buffer.line_len(end_row.previous_row()),
6481 );
6482 let text = buffer
6483 .text_for_range(start_point..end_point)
6484 .collect::<String>();
6485
6486 let mut lines = text.split('\n').collect_vec();
6487
6488 let lines_before = lines.len();
6489 callback(&mut lines);
6490 let lines_after = lines.len();
6491
6492 edits.push((start_point..end_point, lines.join("\n")));
6493
6494 // Selections must change based on added and removed line count
6495 let start_row =
6496 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6497 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6498 new_selections.push(Selection {
6499 id: selection.id,
6500 start: start_row,
6501 end: end_row,
6502 goal: SelectionGoal::None,
6503 reversed: selection.reversed,
6504 });
6505
6506 if lines_after > lines_before {
6507 added_lines += lines_after - lines_before;
6508 } else if lines_before > lines_after {
6509 removed_lines += lines_before - lines_after;
6510 }
6511 }
6512
6513 self.transact(cx, |this, cx| {
6514 let buffer = this.buffer.update(cx, |buffer, cx| {
6515 buffer.edit(edits, None, cx);
6516 buffer.snapshot(cx)
6517 });
6518
6519 // Recalculate offsets on newly edited buffer
6520 let new_selections = new_selections
6521 .iter()
6522 .map(|s| {
6523 let start_point = Point::new(s.start.0, 0);
6524 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6525 Selection {
6526 id: s.id,
6527 start: buffer.point_to_offset(start_point),
6528 end: buffer.point_to_offset(end_point),
6529 goal: s.goal,
6530 reversed: s.reversed,
6531 }
6532 })
6533 .collect();
6534
6535 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6536 s.select(new_selections);
6537 });
6538
6539 this.request_autoscroll(Autoscroll::fit(), cx);
6540 });
6541 }
6542
6543 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6544 self.manipulate_text(cx, |text| text.to_uppercase())
6545 }
6546
6547 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6548 self.manipulate_text(cx, |text| text.to_lowercase())
6549 }
6550
6551 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6552 self.manipulate_text(cx, |text| {
6553 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6554 // https://github.com/rutrum/convert-case/issues/16
6555 text.split('\n')
6556 .map(|line| line.to_case(Case::Title))
6557 .join("\n")
6558 })
6559 }
6560
6561 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6562 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6563 }
6564
6565 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6566 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6567 }
6568
6569 pub fn convert_to_upper_camel_case(
6570 &mut self,
6571 _: &ConvertToUpperCamelCase,
6572 cx: &mut ViewContext<Self>,
6573 ) {
6574 self.manipulate_text(cx, |text| {
6575 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6576 // https://github.com/rutrum/convert-case/issues/16
6577 text.split('\n')
6578 .map(|line| line.to_case(Case::UpperCamel))
6579 .join("\n")
6580 })
6581 }
6582
6583 pub fn convert_to_lower_camel_case(
6584 &mut self,
6585 _: &ConvertToLowerCamelCase,
6586 cx: &mut ViewContext<Self>,
6587 ) {
6588 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6589 }
6590
6591 pub fn convert_to_opposite_case(
6592 &mut self,
6593 _: &ConvertToOppositeCase,
6594 cx: &mut ViewContext<Self>,
6595 ) {
6596 self.manipulate_text(cx, |text| {
6597 text.chars()
6598 .fold(String::with_capacity(text.len()), |mut t, c| {
6599 if c.is_uppercase() {
6600 t.extend(c.to_lowercase());
6601 } else {
6602 t.extend(c.to_uppercase());
6603 }
6604 t
6605 })
6606 })
6607 }
6608
6609 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6610 where
6611 Fn: FnMut(&str) -> String,
6612 {
6613 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6614 let buffer = self.buffer.read(cx).snapshot(cx);
6615
6616 let mut new_selections = Vec::new();
6617 let mut edits = Vec::new();
6618 let mut selection_adjustment = 0i32;
6619
6620 for selection in self.selections.all::<usize>(cx) {
6621 let selection_is_empty = selection.is_empty();
6622
6623 let (start, end) = if selection_is_empty {
6624 let word_range = movement::surrounding_word(
6625 &display_map,
6626 selection.start.to_display_point(&display_map),
6627 );
6628 let start = word_range.start.to_offset(&display_map, Bias::Left);
6629 let end = word_range.end.to_offset(&display_map, Bias::Left);
6630 (start, end)
6631 } else {
6632 (selection.start, selection.end)
6633 };
6634
6635 let text = buffer.text_for_range(start..end).collect::<String>();
6636 let old_length = text.len() as i32;
6637 let text = callback(&text);
6638
6639 new_selections.push(Selection {
6640 start: (start as i32 - selection_adjustment) as usize,
6641 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6642 goal: SelectionGoal::None,
6643 ..selection
6644 });
6645
6646 selection_adjustment += old_length - text.len() as i32;
6647
6648 edits.push((start..end, text));
6649 }
6650
6651 self.transact(cx, |this, cx| {
6652 this.buffer.update(cx, |buffer, cx| {
6653 buffer.edit(edits, None, cx);
6654 });
6655
6656 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6657 s.select(new_selections);
6658 });
6659
6660 this.request_autoscroll(Autoscroll::fit(), cx);
6661 });
6662 }
6663
6664 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6665 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6666 let buffer = &display_map.buffer_snapshot;
6667 let selections = self.selections.all::<Point>(cx);
6668
6669 let mut edits = Vec::new();
6670 let mut selections_iter = selections.iter().peekable();
6671 while let Some(selection) = selections_iter.next() {
6672 // Avoid duplicating the same lines twice.
6673 let mut rows = selection.spanned_rows(false, &display_map);
6674
6675 while let Some(next_selection) = selections_iter.peek() {
6676 let next_rows = next_selection.spanned_rows(false, &display_map);
6677 if next_rows.start < rows.end {
6678 rows.end = next_rows.end;
6679 selections_iter.next().unwrap();
6680 } else {
6681 break;
6682 }
6683 }
6684
6685 // Copy the text from the selected row region and splice it either at the start
6686 // or end of the region.
6687 let start = Point::new(rows.start.0, 0);
6688 let end = Point::new(
6689 rows.end.previous_row().0,
6690 buffer.line_len(rows.end.previous_row()),
6691 );
6692 let text = buffer
6693 .text_for_range(start..end)
6694 .chain(Some("\n"))
6695 .collect::<String>();
6696 let insert_location = if upwards {
6697 Point::new(rows.end.0, 0)
6698 } else {
6699 start
6700 };
6701 edits.push((insert_location..insert_location, text));
6702 }
6703
6704 self.transact(cx, |this, cx| {
6705 this.buffer.update(cx, |buffer, cx| {
6706 buffer.edit(edits, None, cx);
6707 });
6708
6709 this.request_autoscroll(Autoscroll::fit(), cx);
6710 });
6711 }
6712
6713 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6714 self.duplicate_line(true, cx);
6715 }
6716
6717 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6718 self.duplicate_line(false, cx);
6719 }
6720
6721 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6722 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6723 let buffer = self.buffer.read(cx).snapshot(cx);
6724
6725 let mut edits = Vec::new();
6726 let mut unfold_ranges = Vec::new();
6727 let mut refold_ranges = Vec::new();
6728
6729 let selections = self.selections.all::<Point>(cx);
6730 let mut selections = selections.iter().peekable();
6731 let mut contiguous_row_selections = Vec::new();
6732 let mut new_selections = Vec::new();
6733
6734 while let Some(selection) = selections.next() {
6735 // Find all the selections that span a contiguous row range
6736 let (start_row, end_row) = consume_contiguous_rows(
6737 &mut contiguous_row_selections,
6738 selection,
6739 &display_map,
6740 &mut selections,
6741 );
6742
6743 // Move the text spanned by the row range to be before the line preceding the row range
6744 if start_row.0 > 0 {
6745 let range_to_move = Point::new(
6746 start_row.previous_row().0,
6747 buffer.line_len(start_row.previous_row()),
6748 )
6749 ..Point::new(
6750 end_row.previous_row().0,
6751 buffer.line_len(end_row.previous_row()),
6752 );
6753 let insertion_point = display_map
6754 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6755 .0;
6756
6757 // Don't move lines across excerpts
6758 if buffer
6759 .excerpt_boundaries_in_range((
6760 Bound::Excluded(insertion_point),
6761 Bound::Included(range_to_move.end),
6762 ))
6763 .next()
6764 .is_none()
6765 {
6766 let text = buffer
6767 .text_for_range(range_to_move.clone())
6768 .flat_map(|s| s.chars())
6769 .skip(1)
6770 .chain(['\n'])
6771 .collect::<String>();
6772
6773 edits.push((
6774 buffer.anchor_after(range_to_move.start)
6775 ..buffer.anchor_before(range_to_move.end),
6776 String::new(),
6777 ));
6778 let insertion_anchor = buffer.anchor_after(insertion_point);
6779 edits.push((insertion_anchor..insertion_anchor, text));
6780
6781 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6782
6783 // Move selections up
6784 new_selections.extend(contiguous_row_selections.drain(..).map(
6785 |mut selection| {
6786 selection.start.row -= row_delta;
6787 selection.end.row -= row_delta;
6788 selection
6789 },
6790 ));
6791
6792 // Move folds up
6793 unfold_ranges.push(range_to_move.clone());
6794 for fold in display_map.folds_in_range(
6795 buffer.anchor_before(range_to_move.start)
6796 ..buffer.anchor_after(range_to_move.end),
6797 ) {
6798 let mut start = fold.range.start.to_point(&buffer);
6799 let mut end = fold.range.end.to_point(&buffer);
6800 start.row -= row_delta;
6801 end.row -= row_delta;
6802 refold_ranges.push((start..end, fold.placeholder.clone()));
6803 }
6804 }
6805 }
6806
6807 // If we didn't move line(s), preserve the existing selections
6808 new_selections.append(&mut contiguous_row_selections);
6809 }
6810
6811 self.transact(cx, |this, cx| {
6812 this.unfold_ranges(unfold_ranges, true, true, cx);
6813 this.buffer.update(cx, |buffer, cx| {
6814 for (range, text) in edits {
6815 buffer.edit([(range, text)], None, cx);
6816 }
6817 });
6818 this.fold_ranges(refold_ranges, true, cx);
6819 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6820 s.select(new_selections);
6821 })
6822 });
6823 }
6824
6825 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6826 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6827 let buffer = self.buffer.read(cx).snapshot(cx);
6828
6829 let mut edits = Vec::new();
6830 let mut unfold_ranges = Vec::new();
6831 let mut refold_ranges = Vec::new();
6832
6833 let selections = self.selections.all::<Point>(cx);
6834 let mut selections = selections.iter().peekable();
6835 let mut contiguous_row_selections = Vec::new();
6836 let mut new_selections = Vec::new();
6837
6838 while let Some(selection) = selections.next() {
6839 // Find all the selections that span a contiguous row range
6840 let (start_row, end_row) = consume_contiguous_rows(
6841 &mut contiguous_row_selections,
6842 selection,
6843 &display_map,
6844 &mut selections,
6845 );
6846
6847 // Move the text spanned by the row range to be after the last line of the row range
6848 if end_row.0 <= buffer.max_point().row {
6849 let range_to_move =
6850 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6851 let insertion_point = display_map
6852 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6853 .0;
6854
6855 // Don't move lines across excerpt boundaries
6856 if buffer
6857 .excerpt_boundaries_in_range((
6858 Bound::Excluded(range_to_move.start),
6859 Bound::Included(insertion_point),
6860 ))
6861 .next()
6862 .is_none()
6863 {
6864 let mut text = String::from("\n");
6865 text.extend(buffer.text_for_range(range_to_move.clone()));
6866 text.pop(); // Drop trailing newline
6867 edits.push((
6868 buffer.anchor_after(range_to_move.start)
6869 ..buffer.anchor_before(range_to_move.end),
6870 String::new(),
6871 ));
6872 let insertion_anchor = buffer.anchor_after(insertion_point);
6873 edits.push((insertion_anchor..insertion_anchor, text));
6874
6875 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6876
6877 // Move selections down
6878 new_selections.extend(contiguous_row_selections.drain(..).map(
6879 |mut selection| {
6880 selection.start.row += row_delta;
6881 selection.end.row += row_delta;
6882 selection
6883 },
6884 ));
6885
6886 // Move folds down
6887 unfold_ranges.push(range_to_move.clone());
6888 for fold in display_map.folds_in_range(
6889 buffer.anchor_before(range_to_move.start)
6890 ..buffer.anchor_after(range_to_move.end),
6891 ) {
6892 let mut start = fold.range.start.to_point(&buffer);
6893 let mut end = fold.range.end.to_point(&buffer);
6894 start.row += row_delta;
6895 end.row += row_delta;
6896 refold_ranges.push((start..end, fold.placeholder.clone()));
6897 }
6898 }
6899 }
6900
6901 // If we didn't move line(s), preserve the existing selections
6902 new_selections.append(&mut contiguous_row_selections);
6903 }
6904
6905 self.transact(cx, |this, cx| {
6906 this.unfold_ranges(unfold_ranges, true, true, cx);
6907 this.buffer.update(cx, |buffer, cx| {
6908 for (range, text) in edits {
6909 buffer.edit([(range, text)], None, cx);
6910 }
6911 });
6912 this.fold_ranges(refold_ranges, true, cx);
6913 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6914 });
6915 }
6916
6917 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6918 let text_layout_details = &self.text_layout_details(cx);
6919 self.transact(cx, |this, cx| {
6920 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6921 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6922 let line_mode = s.line_mode;
6923 s.move_with(|display_map, selection| {
6924 if !selection.is_empty() || line_mode {
6925 return;
6926 }
6927
6928 let mut head = selection.head();
6929 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6930 if head.column() == display_map.line_len(head.row()) {
6931 transpose_offset = display_map
6932 .buffer_snapshot
6933 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6934 }
6935
6936 if transpose_offset == 0 {
6937 return;
6938 }
6939
6940 *head.column_mut() += 1;
6941 head = display_map.clip_point(head, Bias::Right);
6942 let goal = SelectionGoal::HorizontalPosition(
6943 display_map
6944 .x_for_display_point(head, text_layout_details)
6945 .into(),
6946 );
6947 selection.collapse_to(head, goal);
6948
6949 let transpose_start = display_map
6950 .buffer_snapshot
6951 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6952 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6953 let transpose_end = display_map
6954 .buffer_snapshot
6955 .clip_offset(transpose_offset + 1, Bias::Right);
6956 if let Some(ch) =
6957 display_map.buffer_snapshot.chars_at(transpose_start).next()
6958 {
6959 edits.push((transpose_start..transpose_offset, String::new()));
6960 edits.push((transpose_end..transpose_end, ch.to_string()));
6961 }
6962 }
6963 });
6964 edits
6965 });
6966 this.buffer
6967 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6968 let selections = this.selections.all::<usize>(cx);
6969 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6970 s.select(selections);
6971 });
6972 });
6973 }
6974
6975 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6976 self.rewrap_impl(true, cx)
6977 }
6978
6979 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6980 let buffer = self.buffer.read(cx).snapshot(cx);
6981 let selections = self.selections.all::<Point>(cx);
6982 let mut selections = selections.iter().peekable();
6983
6984 let mut edits = Vec::new();
6985 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6986
6987 while let Some(selection) = selections.next() {
6988 let mut start_row = selection.start.row;
6989 let mut end_row = selection.end.row;
6990
6991 // Skip selections that overlap with a range that has already been rewrapped.
6992 let selection_range = start_row..end_row;
6993 if rewrapped_row_ranges
6994 .iter()
6995 .any(|range| range.overlaps(&selection_range))
6996 {
6997 continue;
6998 }
6999
7000 let mut should_rewrap = !only_text;
7001
7002 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7003 match language_scope.language_name().0.as_ref() {
7004 "Markdown" | "Plain Text" => {
7005 should_rewrap = true;
7006 }
7007 _ => {}
7008 }
7009 }
7010
7011 // Since not all lines in the selection may be at the same indent
7012 // level, choose the indent size that is the most common between all
7013 // of the lines.
7014 //
7015 // If there is a tie, we use the deepest indent.
7016 let (indent_size, indent_end) = {
7017 let mut indent_size_occurrences = HashMap::default();
7018 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7019
7020 for row in start_row..=end_row {
7021 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7022 rows_by_indent_size.entry(indent).or_default().push(row);
7023 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7024 }
7025
7026 let indent_size = indent_size_occurrences
7027 .into_iter()
7028 .max_by_key(|(indent, count)| (*count, indent.len))
7029 .map(|(indent, _)| indent)
7030 .unwrap_or_default();
7031 let row = rows_by_indent_size[&indent_size][0];
7032 let indent_end = Point::new(row, indent_size.len);
7033
7034 (indent_size, indent_end)
7035 };
7036
7037 let mut line_prefix = indent_size.chars().collect::<String>();
7038
7039 if let Some(comment_prefix) =
7040 buffer
7041 .language_scope_at(selection.head())
7042 .and_then(|language| {
7043 language
7044 .line_comment_prefixes()
7045 .iter()
7046 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7047 .cloned()
7048 })
7049 {
7050 line_prefix.push_str(&comment_prefix);
7051 should_rewrap = true;
7052 }
7053
7054 if selection.is_empty() {
7055 'expand_upwards: while start_row > 0 {
7056 let prev_row = start_row - 1;
7057 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7058 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7059 {
7060 start_row = prev_row;
7061 } else {
7062 break 'expand_upwards;
7063 }
7064 }
7065
7066 'expand_downwards: while end_row < buffer.max_point().row {
7067 let next_row = end_row + 1;
7068 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7069 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7070 {
7071 end_row = next_row;
7072 } else {
7073 break 'expand_downwards;
7074 }
7075 }
7076 }
7077
7078 if !should_rewrap {
7079 continue;
7080 }
7081
7082 let start = Point::new(start_row, 0);
7083 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7084 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7085 let Some(lines_without_prefixes) = selection_text
7086 .lines()
7087 .map(|line| {
7088 line.strip_prefix(&line_prefix)
7089 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7090 .ok_or_else(|| {
7091 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7092 })
7093 })
7094 .collect::<Result<Vec<_>, _>>()
7095 .log_err()
7096 else {
7097 continue;
7098 };
7099
7100 let unwrapped_text = lines_without_prefixes.join(" ");
7101 let wrap_column = buffer
7102 .settings_at(Point::new(start_row, 0), cx)
7103 .preferred_line_length as usize;
7104 let mut wrapped_text = String::new();
7105 let mut current_line = line_prefix.clone();
7106 for word in unwrapped_text.split_whitespace() {
7107 if current_line.len() + word.len() >= wrap_column {
7108 wrapped_text.push_str(¤t_line);
7109 wrapped_text.push('\n');
7110 current_line.truncate(line_prefix.len());
7111 }
7112
7113 if current_line.len() > line_prefix.len() {
7114 current_line.push(' ');
7115 }
7116
7117 current_line.push_str(word);
7118 }
7119
7120 if !current_line.is_empty() {
7121 wrapped_text.push_str(¤t_line);
7122 }
7123
7124 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7125 let mut offset = start.to_offset(&buffer);
7126 let mut moved_since_edit = true;
7127
7128 for change in diff.iter_all_changes() {
7129 let value = change.value();
7130 match change.tag() {
7131 ChangeTag::Equal => {
7132 offset += value.len();
7133 moved_since_edit = true;
7134 }
7135 ChangeTag::Delete => {
7136 let start = buffer.anchor_after(offset);
7137 let end = buffer.anchor_before(offset + value.len());
7138
7139 if moved_since_edit {
7140 edits.push((start..end, String::new()));
7141 } else {
7142 edits.last_mut().unwrap().0.end = end;
7143 }
7144
7145 offset += value.len();
7146 moved_since_edit = false;
7147 }
7148 ChangeTag::Insert => {
7149 if moved_since_edit {
7150 let anchor = buffer.anchor_after(offset);
7151 edits.push((anchor..anchor, value.to_string()));
7152 } else {
7153 edits.last_mut().unwrap().1.push_str(value);
7154 }
7155
7156 moved_since_edit = false;
7157 }
7158 }
7159 }
7160
7161 rewrapped_row_ranges.push(start_row..=end_row);
7162 }
7163
7164 self.buffer
7165 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7166 }
7167
7168 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7169 let mut text = String::new();
7170 let buffer = self.buffer.read(cx).snapshot(cx);
7171 let mut selections = self.selections.all::<Point>(cx);
7172 let mut clipboard_selections = Vec::with_capacity(selections.len());
7173 {
7174 let max_point = buffer.max_point();
7175 let mut is_first = true;
7176 for selection in &mut selections {
7177 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7178 if is_entire_line {
7179 selection.start = Point::new(selection.start.row, 0);
7180 if !selection.is_empty() && selection.end.column == 0 {
7181 selection.end = cmp::min(max_point, selection.end);
7182 } else {
7183 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7184 }
7185 selection.goal = SelectionGoal::None;
7186 }
7187 if is_first {
7188 is_first = false;
7189 } else {
7190 text += "\n";
7191 }
7192 let mut len = 0;
7193 for chunk in buffer.text_for_range(selection.start..selection.end) {
7194 text.push_str(chunk);
7195 len += chunk.len();
7196 }
7197 clipboard_selections.push(ClipboardSelection {
7198 len,
7199 is_entire_line,
7200 first_line_indent: buffer
7201 .indent_size_for_line(MultiBufferRow(selection.start.row))
7202 .len,
7203 });
7204 }
7205 }
7206
7207 self.transact(cx, |this, cx| {
7208 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7209 s.select(selections);
7210 });
7211 this.insert("", cx);
7212 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7213 text,
7214 clipboard_selections,
7215 ));
7216 });
7217 }
7218
7219 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7220 let selections = self.selections.all::<Point>(cx);
7221 let buffer = self.buffer.read(cx).read(cx);
7222 let mut text = String::new();
7223
7224 let mut clipboard_selections = Vec::with_capacity(selections.len());
7225 {
7226 let max_point = buffer.max_point();
7227 let mut is_first = true;
7228 for selection in selections.iter() {
7229 let mut start = selection.start;
7230 let mut end = selection.end;
7231 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7232 if is_entire_line {
7233 start = Point::new(start.row, 0);
7234 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7235 }
7236 if is_first {
7237 is_first = false;
7238 } else {
7239 text += "\n";
7240 }
7241 let mut len = 0;
7242 for chunk in buffer.text_for_range(start..end) {
7243 text.push_str(chunk);
7244 len += chunk.len();
7245 }
7246 clipboard_selections.push(ClipboardSelection {
7247 len,
7248 is_entire_line,
7249 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7250 });
7251 }
7252 }
7253
7254 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7255 text,
7256 clipboard_selections,
7257 ));
7258 }
7259
7260 pub fn do_paste(
7261 &mut self,
7262 text: &String,
7263 clipboard_selections: Option<Vec<ClipboardSelection>>,
7264 handle_entire_lines: bool,
7265 cx: &mut ViewContext<Self>,
7266 ) {
7267 if self.read_only(cx) {
7268 return;
7269 }
7270
7271 let clipboard_text = Cow::Borrowed(text);
7272
7273 self.transact(cx, |this, cx| {
7274 if let Some(mut clipboard_selections) = clipboard_selections {
7275 let old_selections = this.selections.all::<usize>(cx);
7276 let all_selections_were_entire_line =
7277 clipboard_selections.iter().all(|s| s.is_entire_line);
7278 let first_selection_indent_column =
7279 clipboard_selections.first().map(|s| s.first_line_indent);
7280 if clipboard_selections.len() != old_selections.len() {
7281 clipboard_selections.drain(..);
7282 }
7283 let cursor_offset = this.selections.last::<usize>(cx).head();
7284 let mut auto_indent_on_paste = true;
7285
7286 this.buffer.update(cx, |buffer, cx| {
7287 let snapshot = buffer.read(cx);
7288 auto_indent_on_paste =
7289 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7290
7291 let mut start_offset = 0;
7292 let mut edits = Vec::new();
7293 let mut original_indent_columns = Vec::new();
7294 for (ix, selection) in old_selections.iter().enumerate() {
7295 let to_insert;
7296 let entire_line;
7297 let original_indent_column;
7298 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7299 let end_offset = start_offset + clipboard_selection.len;
7300 to_insert = &clipboard_text[start_offset..end_offset];
7301 entire_line = clipboard_selection.is_entire_line;
7302 start_offset = end_offset + 1;
7303 original_indent_column = Some(clipboard_selection.first_line_indent);
7304 } else {
7305 to_insert = clipboard_text.as_str();
7306 entire_line = all_selections_were_entire_line;
7307 original_indent_column = first_selection_indent_column
7308 }
7309
7310 // If the corresponding selection was empty when this slice of the
7311 // clipboard text was written, then the entire line containing the
7312 // selection was copied. If this selection is also currently empty,
7313 // then paste the line before the current line of the buffer.
7314 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7315 let column = selection.start.to_point(&snapshot).column as usize;
7316 let line_start = selection.start - column;
7317 line_start..line_start
7318 } else {
7319 selection.range()
7320 };
7321
7322 edits.push((range, to_insert));
7323 original_indent_columns.extend(original_indent_column);
7324 }
7325 drop(snapshot);
7326
7327 buffer.edit(
7328 edits,
7329 if auto_indent_on_paste {
7330 Some(AutoindentMode::Block {
7331 original_indent_columns,
7332 })
7333 } else {
7334 None
7335 },
7336 cx,
7337 );
7338 });
7339
7340 let selections = this.selections.all::<usize>(cx);
7341 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7342 } else {
7343 this.insert(&clipboard_text, cx);
7344 }
7345 });
7346 }
7347
7348 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7349 if let Some(item) = cx.read_from_clipboard() {
7350 let entries = item.entries();
7351
7352 match entries.first() {
7353 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7354 // of all the pasted entries.
7355 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7356 .do_paste(
7357 clipboard_string.text(),
7358 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7359 true,
7360 cx,
7361 ),
7362 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7363 }
7364 }
7365 }
7366
7367 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7368 if self.read_only(cx) {
7369 return;
7370 }
7371
7372 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7373 if let Some((selections, _)) =
7374 self.selection_history.transaction(transaction_id).cloned()
7375 {
7376 self.change_selections(None, cx, |s| {
7377 s.select_anchors(selections.to_vec());
7378 });
7379 }
7380 self.request_autoscroll(Autoscroll::fit(), cx);
7381 self.unmark_text(cx);
7382 self.refresh_inline_completion(true, false, cx);
7383 cx.emit(EditorEvent::Edited { transaction_id });
7384 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7385 }
7386 }
7387
7388 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7389 if self.read_only(cx) {
7390 return;
7391 }
7392
7393 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7394 if let Some((_, Some(selections))) =
7395 self.selection_history.transaction(transaction_id).cloned()
7396 {
7397 self.change_selections(None, cx, |s| {
7398 s.select_anchors(selections.to_vec());
7399 });
7400 }
7401 self.request_autoscroll(Autoscroll::fit(), cx);
7402 self.unmark_text(cx);
7403 self.refresh_inline_completion(true, false, cx);
7404 cx.emit(EditorEvent::Edited { transaction_id });
7405 }
7406 }
7407
7408 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7409 self.buffer
7410 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7411 }
7412
7413 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7414 self.buffer
7415 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7416 }
7417
7418 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7419 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7420 let line_mode = s.line_mode;
7421 s.move_with(|map, selection| {
7422 let cursor = if selection.is_empty() && !line_mode {
7423 movement::left(map, selection.start)
7424 } else {
7425 selection.start
7426 };
7427 selection.collapse_to(cursor, SelectionGoal::None);
7428 });
7429 })
7430 }
7431
7432 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7433 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7434 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7435 })
7436 }
7437
7438 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7439 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7440 let line_mode = s.line_mode;
7441 s.move_with(|map, selection| {
7442 let cursor = if selection.is_empty() && !line_mode {
7443 movement::right(map, selection.end)
7444 } else {
7445 selection.end
7446 };
7447 selection.collapse_to(cursor, SelectionGoal::None)
7448 });
7449 })
7450 }
7451
7452 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7453 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7454 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7455 })
7456 }
7457
7458 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7459 if self.take_rename(true, cx).is_some() {
7460 return;
7461 }
7462
7463 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7464 cx.propagate();
7465 return;
7466 }
7467
7468 let text_layout_details = &self.text_layout_details(cx);
7469 let selection_count = self.selections.count();
7470 let first_selection = self.selections.first_anchor();
7471
7472 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7473 let line_mode = s.line_mode;
7474 s.move_with(|map, selection| {
7475 if !selection.is_empty() && !line_mode {
7476 selection.goal = SelectionGoal::None;
7477 }
7478 let (cursor, goal) = movement::up(
7479 map,
7480 selection.start,
7481 selection.goal,
7482 false,
7483 text_layout_details,
7484 );
7485 selection.collapse_to(cursor, goal);
7486 });
7487 });
7488
7489 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7490 {
7491 cx.propagate();
7492 }
7493 }
7494
7495 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7496 if self.take_rename(true, cx).is_some() {
7497 return;
7498 }
7499
7500 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7501 cx.propagate();
7502 return;
7503 }
7504
7505 let text_layout_details = &self.text_layout_details(cx);
7506
7507 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7508 let line_mode = s.line_mode;
7509 s.move_with(|map, selection| {
7510 if !selection.is_empty() && !line_mode {
7511 selection.goal = SelectionGoal::None;
7512 }
7513 let (cursor, goal) = movement::up_by_rows(
7514 map,
7515 selection.start,
7516 action.lines,
7517 selection.goal,
7518 false,
7519 text_layout_details,
7520 );
7521 selection.collapse_to(cursor, goal);
7522 });
7523 })
7524 }
7525
7526 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7527 if self.take_rename(true, cx).is_some() {
7528 return;
7529 }
7530
7531 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7532 cx.propagate();
7533 return;
7534 }
7535
7536 let text_layout_details = &self.text_layout_details(cx);
7537
7538 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7539 let line_mode = s.line_mode;
7540 s.move_with(|map, selection| {
7541 if !selection.is_empty() && !line_mode {
7542 selection.goal = SelectionGoal::None;
7543 }
7544 let (cursor, goal) = movement::down_by_rows(
7545 map,
7546 selection.start,
7547 action.lines,
7548 selection.goal,
7549 false,
7550 text_layout_details,
7551 );
7552 selection.collapse_to(cursor, goal);
7553 });
7554 })
7555 }
7556
7557 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7558 let text_layout_details = &self.text_layout_details(cx);
7559 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7560 s.move_heads_with(|map, head, goal| {
7561 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7562 })
7563 })
7564 }
7565
7566 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7567 let text_layout_details = &self.text_layout_details(cx);
7568 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7569 s.move_heads_with(|map, head, goal| {
7570 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7571 })
7572 })
7573 }
7574
7575 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7576 let Some(row_count) = self.visible_row_count() else {
7577 return;
7578 };
7579
7580 let text_layout_details = &self.text_layout_details(cx);
7581
7582 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7583 s.move_heads_with(|map, head, goal| {
7584 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7585 })
7586 })
7587 }
7588
7589 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7590 if self.take_rename(true, cx).is_some() {
7591 return;
7592 }
7593
7594 if self
7595 .context_menu
7596 .write()
7597 .as_mut()
7598 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7599 .unwrap_or(false)
7600 {
7601 return;
7602 }
7603
7604 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7605 cx.propagate();
7606 return;
7607 }
7608
7609 let Some(row_count) = self.visible_row_count() else {
7610 return;
7611 };
7612
7613 let autoscroll = if action.center_cursor {
7614 Autoscroll::center()
7615 } else {
7616 Autoscroll::fit()
7617 };
7618
7619 let text_layout_details = &self.text_layout_details(cx);
7620
7621 self.change_selections(Some(autoscroll), cx, |s| {
7622 let line_mode = s.line_mode;
7623 s.move_with(|map, selection| {
7624 if !selection.is_empty() && !line_mode {
7625 selection.goal = SelectionGoal::None;
7626 }
7627 let (cursor, goal) = movement::up_by_rows(
7628 map,
7629 selection.end,
7630 row_count,
7631 selection.goal,
7632 false,
7633 text_layout_details,
7634 );
7635 selection.collapse_to(cursor, goal);
7636 });
7637 });
7638 }
7639
7640 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7641 let text_layout_details = &self.text_layout_details(cx);
7642 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7643 s.move_heads_with(|map, head, goal| {
7644 movement::up(map, head, goal, false, text_layout_details)
7645 })
7646 })
7647 }
7648
7649 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7650 self.take_rename(true, cx);
7651
7652 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7653 cx.propagate();
7654 return;
7655 }
7656
7657 let text_layout_details = &self.text_layout_details(cx);
7658 let selection_count = self.selections.count();
7659 let first_selection = self.selections.first_anchor();
7660
7661 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7662 let line_mode = s.line_mode;
7663 s.move_with(|map, selection| {
7664 if !selection.is_empty() && !line_mode {
7665 selection.goal = SelectionGoal::None;
7666 }
7667 let (cursor, goal) = movement::down(
7668 map,
7669 selection.end,
7670 selection.goal,
7671 false,
7672 text_layout_details,
7673 );
7674 selection.collapse_to(cursor, goal);
7675 });
7676 });
7677
7678 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7679 {
7680 cx.propagate();
7681 }
7682 }
7683
7684 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7685 let Some(row_count) = self.visible_row_count() else {
7686 return;
7687 };
7688
7689 let text_layout_details = &self.text_layout_details(cx);
7690
7691 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7692 s.move_heads_with(|map, head, goal| {
7693 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7694 })
7695 })
7696 }
7697
7698 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7699 if self.take_rename(true, cx).is_some() {
7700 return;
7701 }
7702
7703 if self
7704 .context_menu
7705 .write()
7706 .as_mut()
7707 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7708 .unwrap_or(false)
7709 {
7710 return;
7711 }
7712
7713 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7714 cx.propagate();
7715 return;
7716 }
7717
7718 let Some(row_count) = self.visible_row_count() else {
7719 return;
7720 };
7721
7722 let autoscroll = if action.center_cursor {
7723 Autoscroll::center()
7724 } else {
7725 Autoscroll::fit()
7726 };
7727
7728 let text_layout_details = &self.text_layout_details(cx);
7729 self.change_selections(Some(autoscroll), cx, |s| {
7730 let line_mode = s.line_mode;
7731 s.move_with(|map, selection| {
7732 if !selection.is_empty() && !line_mode {
7733 selection.goal = SelectionGoal::None;
7734 }
7735 let (cursor, goal) = movement::down_by_rows(
7736 map,
7737 selection.end,
7738 row_count,
7739 selection.goal,
7740 false,
7741 text_layout_details,
7742 );
7743 selection.collapse_to(cursor, goal);
7744 });
7745 });
7746 }
7747
7748 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7749 let text_layout_details = &self.text_layout_details(cx);
7750 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 s.move_heads_with(|map, head, goal| {
7752 movement::down(map, head, goal, false, text_layout_details)
7753 })
7754 });
7755 }
7756
7757 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7758 if let Some(context_menu) = self.context_menu.write().as_mut() {
7759 context_menu.select_first(self.completion_provider.as_deref(), cx);
7760 }
7761 }
7762
7763 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7764 if let Some(context_menu) = self.context_menu.write().as_mut() {
7765 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7766 }
7767 }
7768
7769 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7770 if let Some(context_menu) = self.context_menu.write().as_mut() {
7771 context_menu.select_next(self.completion_provider.as_deref(), cx);
7772 }
7773 }
7774
7775 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7776 if let Some(context_menu) = self.context_menu.write().as_mut() {
7777 context_menu.select_last(self.completion_provider.as_deref(), cx);
7778 }
7779 }
7780
7781 pub fn move_to_previous_word_start(
7782 &mut self,
7783 _: &MoveToPreviousWordStart,
7784 cx: &mut ViewContext<Self>,
7785 ) {
7786 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7787 s.move_cursors_with(|map, head, _| {
7788 (
7789 movement::previous_word_start(map, head),
7790 SelectionGoal::None,
7791 )
7792 });
7793 })
7794 }
7795
7796 pub fn move_to_previous_subword_start(
7797 &mut self,
7798 _: &MoveToPreviousSubwordStart,
7799 cx: &mut ViewContext<Self>,
7800 ) {
7801 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7802 s.move_cursors_with(|map, head, _| {
7803 (
7804 movement::previous_subword_start(map, head),
7805 SelectionGoal::None,
7806 )
7807 });
7808 })
7809 }
7810
7811 pub fn select_to_previous_word_start(
7812 &mut self,
7813 _: &SelectToPreviousWordStart,
7814 cx: &mut ViewContext<Self>,
7815 ) {
7816 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7817 s.move_heads_with(|map, head, _| {
7818 (
7819 movement::previous_word_start(map, head),
7820 SelectionGoal::None,
7821 )
7822 });
7823 })
7824 }
7825
7826 pub fn select_to_previous_subword_start(
7827 &mut self,
7828 _: &SelectToPreviousSubwordStart,
7829 cx: &mut ViewContext<Self>,
7830 ) {
7831 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7832 s.move_heads_with(|map, head, _| {
7833 (
7834 movement::previous_subword_start(map, head),
7835 SelectionGoal::None,
7836 )
7837 });
7838 })
7839 }
7840
7841 pub fn delete_to_previous_word_start(
7842 &mut self,
7843 action: &DeleteToPreviousWordStart,
7844 cx: &mut ViewContext<Self>,
7845 ) {
7846 self.transact(cx, |this, cx| {
7847 this.select_autoclose_pair(cx);
7848 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7849 let line_mode = s.line_mode;
7850 s.move_with(|map, selection| {
7851 if selection.is_empty() && !line_mode {
7852 let cursor = if action.ignore_newlines {
7853 movement::previous_word_start(map, selection.head())
7854 } else {
7855 movement::previous_word_start_or_newline(map, selection.head())
7856 };
7857 selection.set_head(cursor, SelectionGoal::None);
7858 }
7859 });
7860 });
7861 this.insert("", cx);
7862 });
7863 }
7864
7865 pub fn delete_to_previous_subword_start(
7866 &mut self,
7867 _: &DeleteToPreviousSubwordStart,
7868 cx: &mut ViewContext<Self>,
7869 ) {
7870 self.transact(cx, |this, cx| {
7871 this.select_autoclose_pair(cx);
7872 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7873 let line_mode = s.line_mode;
7874 s.move_with(|map, selection| {
7875 if selection.is_empty() && !line_mode {
7876 let cursor = movement::previous_subword_start(map, selection.head());
7877 selection.set_head(cursor, SelectionGoal::None);
7878 }
7879 });
7880 });
7881 this.insert("", cx);
7882 });
7883 }
7884
7885 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7887 s.move_cursors_with(|map, head, _| {
7888 (movement::next_word_end(map, head), SelectionGoal::None)
7889 });
7890 })
7891 }
7892
7893 pub fn move_to_next_subword_end(
7894 &mut self,
7895 _: &MoveToNextSubwordEnd,
7896 cx: &mut ViewContext<Self>,
7897 ) {
7898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7899 s.move_cursors_with(|map, head, _| {
7900 (movement::next_subword_end(map, head), SelectionGoal::None)
7901 });
7902 })
7903 }
7904
7905 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7907 s.move_heads_with(|map, head, _| {
7908 (movement::next_word_end(map, head), SelectionGoal::None)
7909 });
7910 })
7911 }
7912
7913 pub fn select_to_next_subword_end(
7914 &mut self,
7915 _: &SelectToNextSubwordEnd,
7916 cx: &mut ViewContext<Self>,
7917 ) {
7918 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7919 s.move_heads_with(|map, head, _| {
7920 (movement::next_subword_end(map, head), SelectionGoal::None)
7921 });
7922 })
7923 }
7924
7925 pub fn delete_to_next_word_end(
7926 &mut self,
7927 action: &DeleteToNextWordEnd,
7928 cx: &mut ViewContext<Self>,
7929 ) {
7930 self.transact(cx, |this, cx| {
7931 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7932 let line_mode = s.line_mode;
7933 s.move_with(|map, selection| {
7934 if selection.is_empty() && !line_mode {
7935 let cursor = if action.ignore_newlines {
7936 movement::next_word_end(map, selection.head())
7937 } else {
7938 movement::next_word_end_or_newline(map, selection.head())
7939 };
7940 selection.set_head(cursor, SelectionGoal::None);
7941 }
7942 });
7943 });
7944 this.insert("", cx);
7945 });
7946 }
7947
7948 pub fn delete_to_next_subword_end(
7949 &mut self,
7950 _: &DeleteToNextSubwordEnd,
7951 cx: &mut ViewContext<Self>,
7952 ) {
7953 self.transact(cx, |this, cx| {
7954 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7955 s.move_with(|map, selection| {
7956 if selection.is_empty() {
7957 let cursor = movement::next_subword_end(map, selection.head());
7958 selection.set_head(cursor, SelectionGoal::None);
7959 }
7960 });
7961 });
7962 this.insert("", cx);
7963 });
7964 }
7965
7966 pub fn move_to_beginning_of_line(
7967 &mut self,
7968 action: &MoveToBeginningOfLine,
7969 cx: &mut ViewContext<Self>,
7970 ) {
7971 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7972 s.move_cursors_with(|map, head, _| {
7973 (
7974 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7975 SelectionGoal::None,
7976 )
7977 });
7978 })
7979 }
7980
7981 pub fn select_to_beginning_of_line(
7982 &mut self,
7983 action: &SelectToBeginningOfLine,
7984 cx: &mut ViewContext<Self>,
7985 ) {
7986 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7987 s.move_heads_with(|map, head, _| {
7988 (
7989 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7990 SelectionGoal::None,
7991 )
7992 });
7993 });
7994 }
7995
7996 pub fn delete_to_beginning_of_line(
7997 &mut self,
7998 _: &DeleteToBeginningOfLine,
7999 cx: &mut ViewContext<Self>,
8000 ) {
8001 self.transact(cx, |this, cx| {
8002 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8003 s.move_with(|_, selection| {
8004 selection.reversed = true;
8005 });
8006 });
8007
8008 this.select_to_beginning_of_line(
8009 &SelectToBeginningOfLine {
8010 stop_at_soft_wraps: false,
8011 },
8012 cx,
8013 );
8014 this.backspace(&Backspace, cx);
8015 });
8016 }
8017
8018 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8019 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8020 s.move_cursors_with(|map, head, _| {
8021 (
8022 movement::line_end(map, head, action.stop_at_soft_wraps),
8023 SelectionGoal::None,
8024 )
8025 });
8026 })
8027 }
8028
8029 pub fn select_to_end_of_line(
8030 &mut self,
8031 action: &SelectToEndOfLine,
8032 cx: &mut ViewContext<Self>,
8033 ) {
8034 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8035 s.move_heads_with(|map, head, _| {
8036 (
8037 movement::line_end(map, head, action.stop_at_soft_wraps),
8038 SelectionGoal::None,
8039 )
8040 });
8041 })
8042 }
8043
8044 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8045 self.transact(cx, |this, cx| {
8046 this.select_to_end_of_line(
8047 &SelectToEndOfLine {
8048 stop_at_soft_wraps: false,
8049 },
8050 cx,
8051 );
8052 this.delete(&Delete, cx);
8053 });
8054 }
8055
8056 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8057 self.transact(cx, |this, cx| {
8058 this.select_to_end_of_line(
8059 &SelectToEndOfLine {
8060 stop_at_soft_wraps: false,
8061 },
8062 cx,
8063 );
8064 this.cut(&Cut, cx);
8065 });
8066 }
8067
8068 pub fn move_to_start_of_paragraph(
8069 &mut self,
8070 _: &MoveToStartOfParagraph,
8071 cx: &mut ViewContext<Self>,
8072 ) {
8073 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8074 cx.propagate();
8075 return;
8076 }
8077
8078 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8079 s.move_with(|map, selection| {
8080 selection.collapse_to(
8081 movement::start_of_paragraph(map, selection.head(), 1),
8082 SelectionGoal::None,
8083 )
8084 });
8085 })
8086 }
8087
8088 pub fn move_to_end_of_paragraph(
8089 &mut self,
8090 _: &MoveToEndOfParagraph,
8091 cx: &mut ViewContext<Self>,
8092 ) {
8093 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8094 cx.propagate();
8095 return;
8096 }
8097
8098 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8099 s.move_with(|map, selection| {
8100 selection.collapse_to(
8101 movement::end_of_paragraph(map, selection.head(), 1),
8102 SelectionGoal::None,
8103 )
8104 });
8105 })
8106 }
8107
8108 pub fn select_to_start_of_paragraph(
8109 &mut self,
8110 _: &SelectToStartOfParagraph,
8111 cx: &mut ViewContext<Self>,
8112 ) {
8113 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8114 cx.propagate();
8115 return;
8116 }
8117
8118 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8119 s.move_heads_with(|map, head, _| {
8120 (
8121 movement::start_of_paragraph(map, head, 1),
8122 SelectionGoal::None,
8123 )
8124 });
8125 })
8126 }
8127
8128 pub fn select_to_end_of_paragraph(
8129 &mut self,
8130 _: &SelectToEndOfParagraph,
8131 cx: &mut ViewContext<Self>,
8132 ) {
8133 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8134 cx.propagate();
8135 return;
8136 }
8137
8138 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8139 s.move_heads_with(|map, head, _| {
8140 (
8141 movement::end_of_paragraph(map, head, 1),
8142 SelectionGoal::None,
8143 )
8144 });
8145 })
8146 }
8147
8148 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8149 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8150 cx.propagate();
8151 return;
8152 }
8153
8154 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8155 s.select_ranges(vec![0..0]);
8156 });
8157 }
8158
8159 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8160 let mut selection = self.selections.last::<Point>(cx);
8161 selection.set_head(Point::zero(), SelectionGoal::None);
8162
8163 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8164 s.select(vec![selection]);
8165 });
8166 }
8167
8168 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8169 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8170 cx.propagate();
8171 return;
8172 }
8173
8174 let cursor = self.buffer.read(cx).read(cx).len();
8175 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8176 s.select_ranges(vec![cursor..cursor])
8177 });
8178 }
8179
8180 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8181 self.nav_history = nav_history;
8182 }
8183
8184 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8185 self.nav_history.as_ref()
8186 }
8187
8188 fn push_to_nav_history(
8189 &mut self,
8190 cursor_anchor: Anchor,
8191 new_position: Option<Point>,
8192 cx: &mut ViewContext<Self>,
8193 ) {
8194 if let Some(nav_history) = self.nav_history.as_mut() {
8195 let buffer = self.buffer.read(cx).read(cx);
8196 let cursor_position = cursor_anchor.to_point(&buffer);
8197 let scroll_state = self.scroll_manager.anchor();
8198 let scroll_top_row = scroll_state.top_row(&buffer);
8199 drop(buffer);
8200
8201 if let Some(new_position) = new_position {
8202 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8203 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8204 return;
8205 }
8206 }
8207
8208 nav_history.push(
8209 Some(NavigationData {
8210 cursor_anchor,
8211 cursor_position,
8212 scroll_anchor: scroll_state,
8213 scroll_top_row,
8214 }),
8215 cx,
8216 );
8217 }
8218 }
8219
8220 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8221 let buffer = self.buffer.read(cx).snapshot(cx);
8222 let mut selection = self.selections.first::<usize>(cx);
8223 selection.set_head(buffer.len(), SelectionGoal::None);
8224 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8225 s.select(vec![selection]);
8226 });
8227 }
8228
8229 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8230 let end = self.buffer.read(cx).read(cx).len();
8231 self.change_selections(None, cx, |s| {
8232 s.select_ranges(vec![0..end]);
8233 });
8234 }
8235
8236 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8237 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8238 let mut selections = self.selections.all::<Point>(cx);
8239 let max_point = display_map.buffer_snapshot.max_point();
8240 for selection in &mut selections {
8241 let rows = selection.spanned_rows(true, &display_map);
8242 selection.start = Point::new(rows.start.0, 0);
8243 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8244 selection.reversed = false;
8245 }
8246 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8247 s.select(selections);
8248 });
8249 }
8250
8251 pub fn split_selection_into_lines(
8252 &mut self,
8253 _: &SplitSelectionIntoLines,
8254 cx: &mut ViewContext<Self>,
8255 ) {
8256 let mut to_unfold = Vec::new();
8257 let mut new_selection_ranges = Vec::new();
8258 {
8259 let selections = self.selections.all::<Point>(cx);
8260 let buffer = self.buffer.read(cx).read(cx);
8261 for selection in selections {
8262 for row in selection.start.row..selection.end.row {
8263 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8264 new_selection_ranges.push(cursor..cursor);
8265 }
8266 new_selection_ranges.push(selection.end..selection.end);
8267 to_unfold.push(selection.start..selection.end);
8268 }
8269 }
8270 self.unfold_ranges(to_unfold, true, true, cx);
8271 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8272 s.select_ranges(new_selection_ranges);
8273 });
8274 }
8275
8276 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8277 self.add_selection(true, cx);
8278 }
8279
8280 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8281 self.add_selection(false, cx);
8282 }
8283
8284 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8286 let mut selections = self.selections.all::<Point>(cx);
8287 let text_layout_details = self.text_layout_details(cx);
8288 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8289 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8290 let range = oldest_selection.display_range(&display_map).sorted();
8291
8292 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8293 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8294 let positions = start_x.min(end_x)..start_x.max(end_x);
8295
8296 selections.clear();
8297 let mut stack = Vec::new();
8298 for row in range.start.row().0..=range.end.row().0 {
8299 if let Some(selection) = self.selections.build_columnar_selection(
8300 &display_map,
8301 DisplayRow(row),
8302 &positions,
8303 oldest_selection.reversed,
8304 &text_layout_details,
8305 ) {
8306 stack.push(selection.id);
8307 selections.push(selection);
8308 }
8309 }
8310
8311 if above {
8312 stack.reverse();
8313 }
8314
8315 AddSelectionsState { above, stack }
8316 });
8317
8318 let last_added_selection = *state.stack.last().unwrap();
8319 let mut new_selections = Vec::new();
8320 if above == state.above {
8321 let end_row = if above {
8322 DisplayRow(0)
8323 } else {
8324 display_map.max_point().row()
8325 };
8326
8327 'outer: for selection in selections {
8328 if selection.id == last_added_selection {
8329 let range = selection.display_range(&display_map).sorted();
8330 debug_assert_eq!(range.start.row(), range.end.row());
8331 let mut row = range.start.row();
8332 let positions =
8333 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8334 px(start)..px(end)
8335 } else {
8336 let start_x =
8337 display_map.x_for_display_point(range.start, &text_layout_details);
8338 let end_x =
8339 display_map.x_for_display_point(range.end, &text_layout_details);
8340 start_x.min(end_x)..start_x.max(end_x)
8341 };
8342
8343 while row != end_row {
8344 if above {
8345 row.0 -= 1;
8346 } else {
8347 row.0 += 1;
8348 }
8349
8350 if let Some(new_selection) = self.selections.build_columnar_selection(
8351 &display_map,
8352 row,
8353 &positions,
8354 selection.reversed,
8355 &text_layout_details,
8356 ) {
8357 state.stack.push(new_selection.id);
8358 if above {
8359 new_selections.push(new_selection);
8360 new_selections.push(selection);
8361 } else {
8362 new_selections.push(selection);
8363 new_selections.push(new_selection);
8364 }
8365
8366 continue 'outer;
8367 }
8368 }
8369 }
8370
8371 new_selections.push(selection);
8372 }
8373 } else {
8374 new_selections = selections;
8375 new_selections.retain(|s| s.id != last_added_selection);
8376 state.stack.pop();
8377 }
8378
8379 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8380 s.select(new_selections);
8381 });
8382 if state.stack.len() > 1 {
8383 self.add_selections_state = Some(state);
8384 }
8385 }
8386
8387 pub fn select_next_match_internal(
8388 &mut self,
8389 display_map: &DisplaySnapshot,
8390 replace_newest: bool,
8391 autoscroll: Option<Autoscroll>,
8392 cx: &mut ViewContext<Self>,
8393 ) -> Result<()> {
8394 fn select_next_match_ranges(
8395 this: &mut Editor,
8396 range: Range<usize>,
8397 replace_newest: bool,
8398 auto_scroll: Option<Autoscroll>,
8399 cx: &mut ViewContext<Editor>,
8400 ) {
8401 this.unfold_ranges([range.clone()], false, true, cx);
8402 this.change_selections(auto_scroll, cx, |s| {
8403 if replace_newest {
8404 s.delete(s.newest_anchor().id);
8405 }
8406 s.insert_range(range.clone());
8407 });
8408 }
8409
8410 let buffer = &display_map.buffer_snapshot;
8411 let mut selections = self.selections.all::<usize>(cx);
8412 if let Some(mut select_next_state) = self.select_next_state.take() {
8413 let query = &select_next_state.query;
8414 if !select_next_state.done {
8415 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8416 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8417 let mut next_selected_range = None;
8418
8419 let bytes_after_last_selection =
8420 buffer.bytes_in_range(last_selection.end..buffer.len());
8421 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8422 let query_matches = query
8423 .stream_find_iter(bytes_after_last_selection)
8424 .map(|result| (last_selection.end, result))
8425 .chain(
8426 query
8427 .stream_find_iter(bytes_before_first_selection)
8428 .map(|result| (0, result)),
8429 );
8430
8431 for (start_offset, query_match) in query_matches {
8432 let query_match = query_match.unwrap(); // can only fail due to I/O
8433 let offset_range =
8434 start_offset + query_match.start()..start_offset + query_match.end();
8435 let display_range = offset_range.start.to_display_point(display_map)
8436 ..offset_range.end.to_display_point(display_map);
8437
8438 if !select_next_state.wordwise
8439 || (!movement::is_inside_word(display_map, display_range.start)
8440 && !movement::is_inside_word(display_map, display_range.end))
8441 {
8442 // TODO: This is n^2, because we might check all the selections
8443 if !selections
8444 .iter()
8445 .any(|selection| selection.range().overlaps(&offset_range))
8446 {
8447 next_selected_range = Some(offset_range);
8448 break;
8449 }
8450 }
8451 }
8452
8453 if let Some(next_selected_range) = next_selected_range {
8454 select_next_match_ranges(
8455 self,
8456 next_selected_range,
8457 replace_newest,
8458 autoscroll,
8459 cx,
8460 );
8461 } else {
8462 select_next_state.done = true;
8463 }
8464 }
8465
8466 self.select_next_state = Some(select_next_state);
8467 } else {
8468 let mut only_carets = true;
8469 let mut same_text_selected = true;
8470 let mut selected_text = None;
8471
8472 let mut selections_iter = selections.iter().peekable();
8473 while let Some(selection) = selections_iter.next() {
8474 if selection.start != selection.end {
8475 only_carets = false;
8476 }
8477
8478 if same_text_selected {
8479 if selected_text.is_none() {
8480 selected_text =
8481 Some(buffer.text_for_range(selection.range()).collect::<String>());
8482 }
8483
8484 if let Some(next_selection) = selections_iter.peek() {
8485 if next_selection.range().len() == selection.range().len() {
8486 let next_selected_text = buffer
8487 .text_for_range(next_selection.range())
8488 .collect::<String>();
8489 if Some(next_selected_text) != selected_text {
8490 same_text_selected = false;
8491 selected_text = None;
8492 }
8493 } else {
8494 same_text_selected = false;
8495 selected_text = None;
8496 }
8497 }
8498 }
8499 }
8500
8501 if only_carets {
8502 for selection in &mut selections {
8503 let word_range = movement::surrounding_word(
8504 display_map,
8505 selection.start.to_display_point(display_map),
8506 );
8507 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8508 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8509 selection.goal = SelectionGoal::None;
8510 selection.reversed = false;
8511 select_next_match_ranges(
8512 self,
8513 selection.start..selection.end,
8514 replace_newest,
8515 autoscroll,
8516 cx,
8517 );
8518 }
8519
8520 if selections.len() == 1 {
8521 let selection = selections
8522 .last()
8523 .expect("ensured that there's only one selection");
8524 let query = buffer
8525 .text_for_range(selection.start..selection.end)
8526 .collect::<String>();
8527 let is_empty = query.is_empty();
8528 let select_state = SelectNextState {
8529 query: AhoCorasick::new(&[query])?,
8530 wordwise: true,
8531 done: is_empty,
8532 };
8533 self.select_next_state = Some(select_state);
8534 } else {
8535 self.select_next_state = None;
8536 }
8537 } else if let Some(selected_text) = selected_text {
8538 self.select_next_state = Some(SelectNextState {
8539 query: AhoCorasick::new(&[selected_text])?,
8540 wordwise: false,
8541 done: false,
8542 });
8543 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8544 }
8545 }
8546 Ok(())
8547 }
8548
8549 pub fn select_all_matches(
8550 &mut self,
8551 _action: &SelectAllMatches,
8552 cx: &mut ViewContext<Self>,
8553 ) -> Result<()> {
8554 self.push_to_selection_history();
8555 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8556
8557 self.select_next_match_internal(&display_map, false, None, cx)?;
8558 let Some(select_next_state) = self.select_next_state.as_mut() else {
8559 return Ok(());
8560 };
8561 if select_next_state.done {
8562 return Ok(());
8563 }
8564
8565 let mut new_selections = self.selections.all::<usize>(cx);
8566
8567 let buffer = &display_map.buffer_snapshot;
8568 let query_matches = select_next_state
8569 .query
8570 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8571
8572 for query_match in query_matches {
8573 let query_match = query_match.unwrap(); // can only fail due to I/O
8574 let offset_range = query_match.start()..query_match.end();
8575 let display_range = offset_range.start.to_display_point(&display_map)
8576 ..offset_range.end.to_display_point(&display_map);
8577
8578 if !select_next_state.wordwise
8579 || (!movement::is_inside_word(&display_map, display_range.start)
8580 && !movement::is_inside_word(&display_map, display_range.end))
8581 {
8582 self.selections.change_with(cx, |selections| {
8583 new_selections.push(Selection {
8584 id: selections.new_selection_id(),
8585 start: offset_range.start,
8586 end: offset_range.end,
8587 reversed: false,
8588 goal: SelectionGoal::None,
8589 });
8590 });
8591 }
8592 }
8593
8594 new_selections.sort_by_key(|selection| selection.start);
8595 let mut ix = 0;
8596 while ix + 1 < new_selections.len() {
8597 let current_selection = &new_selections[ix];
8598 let next_selection = &new_selections[ix + 1];
8599 if current_selection.range().overlaps(&next_selection.range()) {
8600 if current_selection.id < next_selection.id {
8601 new_selections.remove(ix + 1);
8602 } else {
8603 new_selections.remove(ix);
8604 }
8605 } else {
8606 ix += 1;
8607 }
8608 }
8609
8610 select_next_state.done = true;
8611 self.unfold_ranges(
8612 new_selections.iter().map(|selection| selection.range()),
8613 false,
8614 false,
8615 cx,
8616 );
8617 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8618 selections.select(new_selections)
8619 });
8620
8621 Ok(())
8622 }
8623
8624 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8625 self.push_to_selection_history();
8626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8627 self.select_next_match_internal(
8628 &display_map,
8629 action.replace_newest,
8630 Some(Autoscroll::newest()),
8631 cx,
8632 )?;
8633 Ok(())
8634 }
8635
8636 pub fn select_previous(
8637 &mut self,
8638 action: &SelectPrevious,
8639 cx: &mut ViewContext<Self>,
8640 ) -> Result<()> {
8641 self.push_to_selection_history();
8642 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8643 let buffer = &display_map.buffer_snapshot;
8644 let mut selections = self.selections.all::<usize>(cx);
8645 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8646 let query = &select_prev_state.query;
8647 if !select_prev_state.done {
8648 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8649 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8650 let mut next_selected_range = None;
8651 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8652 let bytes_before_last_selection =
8653 buffer.reversed_bytes_in_range(0..last_selection.start);
8654 let bytes_after_first_selection =
8655 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8656 let query_matches = query
8657 .stream_find_iter(bytes_before_last_selection)
8658 .map(|result| (last_selection.start, result))
8659 .chain(
8660 query
8661 .stream_find_iter(bytes_after_first_selection)
8662 .map(|result| (buffer.len(), result)),
8663 );
8664 for (end_offset, query_match) in query_matches {
8665 let query_match = query_match.unwrap(); // can only fail due to I/O
8666 let offset_range =
8667 end_offset - query_match.end()..end_offset - query_match.start();
8668 let display_range = offset_range.start.to_display_point(&display_map)
8669 ..offset_range.end.to_display_point(&display_map);
8670
8671 if !select_prev_state.wordwise
8672 || (!movement::is_inside_word(&display_map, display_range.start)
8673 && !movement::is_inside_word(&display_map, display_range.end))
8674 {
8675 next_selected_range = Some(offset_range);
8676 break;
8677 }
8678 }
8679
8680 if let Some(next_selected_range) = next_selected_range {
8681 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8682 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8683 if action.replace_newest {
8684 s.delete(s.newest_anchor().id);
8685 }
8686 s.insert_range(next_selected_range);
8687 });
8688 } else {
8689 select_prev_state.done = true;
8690 }
8691 }
8692
8693 self.select_prev_state = Some(select_prev_state);
8694 } else {
8695 let mut only_carets = true;
8696 let mut same_text_selected = true;
8697 let mut selected_text = None;
8698
8699 let mut selections_iter = selections.iter().peekable();
8700 while let Some(selection) = selections_iter.next() {
8701 if selection.start != selection.end {
8702 only_carets = false;
8703 }
8704
8705 if same_text_selected {
8706 if selected_text.is_none() {
8707 selected_text =
8708 Some(buffer.text_for_range(selection.range()).collect::<String>());
8709 }
8710
8711 if let Some(next_selection) = selections_iter.peek() {
8712 if next_selection.range().len() == selection.range().len() {
8713 let next_selected_text = buffer
8714 .text_for_range(next_selection.range())
8715 .collect::<String>();
8716 if Some(next_selected_text) != selected_text {
8717 same_text_selected = false;
8718 selected_text = None;
8719 }
8720 } else {
8721 same_text_selected = false;
8722 selected_text = None;
8723 }
8724 }
8725 }
8726 }
8727
8728 if only_carets {
8729 for selection in &mut selections {
8730 let word_range = movement::surrounding_word(
8731 &display_map,
8732 selection.start.to_display_point(&display_map),
8733 );
8734 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8735 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8736 selection.goal = SelectionGoal::None;
8737 selection.reversed = false;
8738 }
8739 if selections.len() == 1 {
8740 let selection = selections
8741 .last()
8742 .expect("ensured that there's only one selection");
8743 let query = buffer
8744 .text_for_range(selection.start..selection.end)
8745 .collect::<String>();
8746 let is_empty = query.is_empty();
8747 let select_state = SelectNextState {
8748 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8749 wordwise: true,
8750 done: is_empty,
8751 };
8752 self.select_prev_state = Some(select_state);
8753 } else {
8754 self.select_prev_state = None;
8755 }
8756
8757 self.unfold_ranges(
8758 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8759 false,
8760 true,
8761 cx,
8762 );
8763 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8764 s.select(selections);
8765 });
8766 } else if let Some(selected_text) = selected_text {
8767 self.select_prev_state = Some(SelectNextState {
8768 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8769 wordwise: false,
8770 done: false,
8771 });
8772 self.select_previous(action, cx)?;
8773 }
8774 }
8775 Ok(())
8776 }
8777
8778 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8779 let text_layout_details = &self.text_layout_details(cx);
8780 self.transact(cx, |this, cx| {
8781 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8782 let mut edits = Vec::new();
8783 let mut selection_edit_ranges = Vec::new();
8784 let mut last_toggled_row = None;
8785 let snapshot = this.buffer.read(cx).read(cx);
8786 let empty_str: Arc<str> = Arc::default();
8787 let mut suffixes_inserted = Vec::new();
8788 let ignore_indent = action.ignore_indent;
8789
8790 fn comment_prefix_range(
8791 snapshot: &MultiBufferSnapshot,
8792 row: MultiBufferRow,
8793 comment_prefix: &str,
8794 comment_prefix_whitespace: &str,
8795 ignore_indent: bool,
8796 ) -> Range<Point> {
8797 let indent_size = if ignore_indent {
8798 0
8799 } else {
8800 snapshot.indent_size_for_line(row).len
8801 };
8802
8803 let start = Point::new(row.0, indent_size);
8804
8805 let mut line_bytes = snapshot
8806 .bytes_in_range(start..snapshot.max_point())
8807 .flatten()
8808 .copied();
8809
8810 // If this line currently begins with the line comment prefix, then record
8811 // the range containing the prefix.
8812 if line_bytes
8813 .by_ref()
8814 .take(comment_prefix.len())
8815 .eq(comment_prefix.bytes())
8816 {
8817 // Include any whitespace that matches the comment prefix.
8818 let matching_whitespace_len = line_bytes
8819 .zip(comment_prefix_whitespace.bytes())
8820 .take_while(|(a, b)| a == b)
8821 .count() as u32;
8822 let end = Point::new(
8823 start.row,
8824 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8825 );
8826 start..end
8827 } else {
8828 start..start
8829 }
8830 }
8831
8832 fn comment_suffix_range(
8833 snapshot: &MultiBufferSnapshot,
8834 row: MultiBufferRow,
8835 comment_suffix: &str,
8836 comment_suffix_has_leading_space: bool,
8837 ) -> Range<Point> {
8838 let end = Point::new(row.0, snapshot.line_len(row));
8839 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8840
8841 let mut line_end_bytes = snapshot
8842 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8843 .flatten()
8844 .copied();
8845
8846 let leading_space_len = if suffix_start_column > 0
8847 && line_end_bytes.next() == Some(b' ')
8848 && comment_suffix_has_leading_space
8849 {
8850 1
8851 } else {
8852 0
8853 };
8854
8855 // If this line currently begins with the line comment prefix, then record
8856 // the range containing the prefix.
8857 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8858 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8859 start..end
8860 } else {
8861 end..end
8862 }
8863 }
8864
8865 // TODO: Handle selections that cross excerpts
8866 for selection in &mut selections {
8867 let start_column = snapshot
8868 .indent_size_for_line(MultiBufferRow(selection.start.row))
8869 .len;
8870 let language = if let Some(language) =
8871 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8872 {
8873 language
8874 } else {
8875 continue;
8876 };
8877
8878 selection_edit_ranges.clear();
8879
8880 // If multiple selections contain a given row, avoid processing that
8881 // row more than once.
8882 let mut start_row = MultiBufferRow(selection.start.row);
8883 if last_toggled_row == Some(start_row) {
8884 start_row = start_row.next_row();
8885 }
8886 let end_row =
8887 if selection.end.row > selection.start.row && selection.end.column == 0 {
8888 MultiBufferRow(selection.end.row - 1)
8889 } else {
8890 MultiBufferRow(selection.end.row)
8891 };
8892 last_toggled_row = Some(end_row);
8893
8894 if start_row > end_row {
8895 continue;
8896 }
8897
8898 // If the language has line comments, toggle those.
8899 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8900
8901 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8902 if ignore_indent {
8903 full_comment_prefixes = full_comment_prefixes
8904 .into_iter()
8905 .map(|s| Arc::from(s.trim_end()))
8906 .collect();
8907 }
8908
8909 if !full_comment_prefixes.is_empty() {
8910 let first_prefix = full_comment_prefixes
8911 .first()
8912 .expect("prefixes is non-empty");
8913 let prefix_trimmed_lengths = full_comment_prefixes
8914 .iter()
8915 .map(|p| p.trim_end_matches(' ').len())
8916 .collect::<SmallVec<[usize; 4]>>();
8917
8918 let mut all_selection_lines_are_comments = true;
8919
8920 for row in start_row.0..=end_row.0 {
8921 let row = MultiBufferRow(row);
8922 if start_row < end_row && snapshot.is_line_blank(row) {
8923 continue;
8924 }
8925
8926 let prefix_range = full_comment_prefixes
8927 .iter()
8928 .zip(prefix_trimmed_lengths.iter().copied())
8929 .map(|(prefix, trimmed_prefix_len)| {
8930 comment_prefix_range(
8931 snapshot.deref(),
8932 row,
8933 &prefix[..trimmed_prefix_len],
8934 &prefix[trimmed_prefix_len..],
8935 ignore_indent,
8936 )
8937 })
8938 .max_by_key(|range| range.end.column - range.start.column)
8939 .expect("prefixes is non-empty");
8940
8941 if prefix_range.is_empty() {
8942 all_selection_lines_are_comments = false;
8943 }
8944
8945 selection_edit_ranges.push(prefix_range);
8946 }
8947
8948 if all_selection_lines_are_comments {
8949 edits.extend(
8950 selection_edit_ranges
8951 .iter()
8952 .cloned()
8953 .map(|range| (range, empty_str.clone())),
8954 );
8955 } else {
8956 let min_column = selection_edit_ranges
8957 .iter()
8958 .map(|range| range.start.column)
8959 .min()
8960 .unwrap_or(0);
8961 edits.extend(selection_edit_ranges.iter().map(|range| {
8962 let position = Point::new(range.start.row, min_column);
8963 (position..position, first_prefix.clone())
8964 }));
8965 }
8966 } else if let Some((full_comment_prefix, comment_suffix)) =
8967 language.block_comment_delimiters()
8968 {
8969 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8970 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8971 let prefix_range = comment_prefix_range(
8972 snapshot.deref(),
8973 start_row,
8974 comment_prefix,
8975 comment_prefix_whitespace,
8976 ignore_indent,
8977 );
8978 let suffix_range = comment_suffix_range(
8979 snapshot.deref(),
8980 end_row,
8981 comment_suffix.trim_start_matches(' '),
8982 comment_suffix.starts_with(' '),
8983 );
8984
8985 if prefix_range.is_empty() || suffix_range.is_empty() {
8986 edits.push((
8987 prefix_range.start..prefix_range.start,
8988 full_comment_prefix.clone(),
8989 ));
8990 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8991 suffixes_inserted.push((end_row, comment_suffix.len()));
8992 } else {
8993 edits.push((prefix_range, empty_str.clone()));
8994 edits.push((suffix_range, empty_str.clone()));
8995 }
8996 } else {
8997 continue;
8998 }
8999 }
9000
9001 drop(snapshot);
9002 this.buffer.update(cx, |buffer, cx| {
9003 buffer.edit(edits, None, cx);
9004 });
9005
9006 // Adjust selections so that they end before any comment suffixes that
9007 // were inserted.
9008 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9009 let mut selections = this.selections.all::<Point>(cx);
9010 let snapshot = this.buffer.read(cx).read(cx);
9011 for selection in &mut selections {
9012 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9013 match row.cmp(&MultiBufferRow(selection.end.row)) {
9014 Ordering::Less => {
9015 suffixes_inserted.next();
9016 continue;
9017 }
9018 Ordering::Greater => break,
9019 Ordering::Equal => {
9020 if selection.end.column == snapshot.line_len(row) {
9021 if selection.is_empty() {
9022 selection.start.column -= suffix_len as u32;
9023 }
9024 selection.end.column -= suffix_len as u32;
9025 }
9026 break;
9027 }
9028 }
9029 }
9030 }
9031
9032 drop(snapshot);
9033 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9034
9035 let selections = this.selections.all::<Point>(cx);
9036 let selections_on_single_row = selections.windows(2).all(|selections| {
9037 selections[0].start.row == selections[1].start.row
9038 && selections[0].end.row == selections[1].end.row
9039 && selections[0].start.row == selections[0].end.row
9040 });
9041 let selections_selecting = selections
9042 .iter()
9043 .any(|selection| selection.start != selection.end);
9044 let advance_downwards = action.advance_downwards
9045 && selections_on_single_row
9046 && !selections_selecting
9047 && !matches!(this.mode, EditorMode::SingleLine { .. });
9048
9049 if advance_downwards {
9050 let snapshot = this.buffer.read(cx).snapshot(cx);
9051
9052 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9053 s.move_cursors_with(|display_snapshot, display_point, _| {
9054 let mut point = display_point.to_point(display_snapshot);
9055 point.row += 1;
9056 point = snapshot.clip_point(point, Bias::Left);
9057 let display_point = point.to_display_point(display_snapshot);
9058 let goal = SelectionGoal::HorizontalPosition(
9059 display_snapshot
9060 .x_for_display_point(display_point, text_layout_details)
9061 .into(),
9062 );
9063 (display_point, goal)
9064 })
9065 });
9066 }
9067 });
9068 }
9069
9070 pub fn select_enclosing_symbol(
9071 &mut self,
9072 _: &SelectEnclosingSymbol,
9073 cx: &mut ViewContext<Self>,
9074 ) {
9075 let buffer = self.buffer.read(cx).snapshot(cx);
9076 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9077
9078 fn update_selection(
9079 selection: &Selection<usize>,
9080 buffer_snap: &MultiBufferSnapshot,
9081 ) -> Option<Selection<usize>> {
9082 let cursor = selection.head();
9083 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9084 for symbol in symbols.iter().rev() {
9085 let start = symbol.range.start.to_offset(buffer_snap);
9086 let end = symbol.range.end.to_offset(buffer_snap);
9087 let new_range = start..end;
9088 if start < selection.start || end > selection.end {
9089 return Some(Selection {
9090 id: selection.id,
9091 start: new_range.start,
9092 end: new_range.end,
9093 goal: SelectionGoal::None,
9094 reversed: selection.reversed,
9095 });
9096 }
9097 }
9098 None
9099 }
9100
9101 let mut selected_larger_symbol = false;
9102 let new_selections = old_selections
9103 .iter()
9104 .map(|selection| match update_selection(selection, &buffer) {
9105 Some(new_selection) => {
9106 if new_selection.range() != selection.range() {
9107 selected_larger_symbol = true;
9108 }
9109 new_selection
9110 }
9111 None => selection.clone(),
9112 })
9113 .collect::<Vec<_>>();
9114
9115 if selected_larger_symbol {
9116 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9117 s.select(new_selections);
9118 });
9119 }
9120 }
9121
9122 pub fn select_larger_syntax_node(
9123 &mut self,
9124 _: &SelectLargerSyntaxNode,
9125 cx: &mut ViewContext<Self>,
9126 ) {
9127 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9128 let buffer = self.buffer.read(cx).snapshot(cx);
9129 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9130
9131 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9132 let mut selected_larger_node = false;
9133 let new_selections = old_selections
9134 .iter()
9135 .map(|selection| {
9136 let old_range = selection.start..selection.end;
9137 let mut new_range = old_range.clone();
9138 while let Some(containing_range) =
9139 buffer.range_for_syntax_ancestor(new_range.clone())
9140 {
9141 new_range = containing_range;
9142 if !display_map.intersects_fold(new_range.start)
9143 && !display_map.intersects_fold(new_range.end)
9144 {
9145 break;
9146 }
9147 }
9148
9149 selected_larger_node |= new_range != old_range;
9150 Selection {
9151 id: selection.id,
9152 start: new_range.start,
9153 end: new_range.end,
9154 goal: SelectionGoal::None,
9155 reversed: selection.reversed,
9156 }
9157 })
9158 .collect::<Vec<_>>();
9159
9160 if selected_larger_node {
9161 stack.push(old_selections);
9162 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9163 s.select(new_selections);
9164 });
9165 }
9166 self.select_larger_syntax_node_stack = stack;
9167 }
9168
9169 pub fn select_smaller_syntax_node(
9170 &mut self,
9171 _: &SelectSmallerSyntaxNode,
9172 cx: &mut ViewContext<Self>,
9173 ) {
9174 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9175 if let Some(selections) = stack.pop() {
9176 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9177 s.select(selections.to_vec());
9178 });
9179 }
9180 self.select_larger_syntax_node_stack = stack;
9181 }
9182
9183 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9184 if !EditorSettings::get_global(cx).gutter.runnables {
9185 self.clear_tasks();
9186 return Task::ready(());
9187 }
9188 let project = self.project.clone();
9189 cx.spawn(|this, mut cx| async move {
9190 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9191 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9192 }) else {
9193 return;
9194 };
9195
9196 let Some(project) = project else {
9197 return;
9198 };
9199
9200 let hide_runnables = project
9201 .update(&mut cx, |project, cx| {
9202 // Do not display any test indicators in non-dev server remote projects.
9203 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9204 })
9205 .unwrap_or(true);
9206 if hide_runnables {
9207 return;
9208 }
9209 let new_rows =
9210 cx.background_executor()
9211 .spawn({
9212 let snapshot = display_snapshot.clone();
9213 async move {
9214 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9215 }
9216 })
9217 .await;
9218 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9219
9220 this.update(&mut cx, |this, _| {
9221 this.clear_tasks();
9222 for (key, value) in rows {
9223 this.insert_tasks(key, value);
9224 }
9225 })
9226 .ok();
9227 })
9228 }
9229 fn fetch_runnable_ranges(
9230 snapshot: &DisplaySnapshot,
9231 range: Range<Anchor>,
9232 ) -> Vec<language::RunnableRange> {
9233 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9234 }
9235
9236 fn runnable_rows(
9237 project: Model<Project>,
9238 snapshot: DisplaySnapshot,
9239 runnable_ranges: Vec<RunnableRange>,
9240 mut cx: AsyncWindowContext,
9241 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9242 runnable_ranges
9243 .into_iter()
9244 .filter_map(|mut runnable| {
9245 let tasks = cx
9246 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9247 .ok()?;
9248 if tasks.is_empty() {
9249 return None;
9250 }
9251
9252 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9253
9254 let row = snapshot
9255 .buffer_snapshot
9256 .buffer_line_for_row(MultiBufferRow(point.row))?
9257 .1
9258 .start
9259 .row;
9260
9261 let context_range =
9262 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9263 Some((
9264 (runnable.buffer_id, row),
9265 RunnableTasks {
9266 templates: tasks,
9267 offset: MultiBufferOffset(runnable.run_range.start),
9268 context_range,
9269 column: point.column,
9270 extra_variables: runnable.extra_captures,
9271 },
9272 ))
9273 })
9274 .collect()
9275 }
9276
9277 fn templates_with_tags(
9278 project: &Model<Project>,
9279 runnable: &mut Runnable,
9280 cx: &WindowContext<'_>,
9281 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9282 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9283 let (worktree_id, file) = project
9284 .buffer_for_id(runnable.buffer, cx)
9285 .and_then(|buffer| buffer.read(cx).file())
9286 .map(|file| (file.worktree_id(cx), file.clone()))
9287 .unzip();
9288
9289 (
9290 project.task_store().read(cx).task_inventory().cloned(),
9291 worktree_id,
9292 file,
9293 )
9294 });
9295
9296 let tags = mem::take(&mut runnable.tags);
9297 let mut tags: Vec<_> = tags
9298 .into_iter()
9299 .flat_map(|tag| {
9300 let tag = tag.0.clone();
9301 inventory
9302 .as_ref()
9303 .into_iter()
9304 .flat_map(|inventory| {
9305 inventory.read(cx).list_tasks(
9306 file.clone(),
9307 Some(runnable.language.clone()),
9308 worktree_id,
9309 cx,
9310 )
9311 })
9312 .filter(move |(_, template)| {
9313 template.tags.iter().any(|source_tag| source_tag == &tag)
9314 })
9315 })
9316 .sorted_by_key(|(kind, _)| kind.to_owned())
9317 .collect();
9318 if let Some((leading_tag_source, _)) = tags.first() {
9319 // Strongest source wins; if we have worktree tag binding, prefer that to
9320 // global and language bindings;
9321 // if we have a global binding, prefer that to language binding.
9322 let first_mismatch = tags
9323 .iter()
9324 .position(|(tag_source, _)| tag_source != leading_tag_source);
9325 if let Some(index) = first_mismatch {
9326 tags.truncate(index);
9327 }
9328 }
9329
9330 tags
9331 }
9332
9333 pub fn move_to_enclosing_bracket(
9334 &mut self,
9335 _: &MoveToEnclosingBracket,
9336 cx: &mut ViewContext<Self>,
9337 ) {
9338 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9339 s.move_offsets_with(|snapshot, selection| {
9340 let Some(enclosing_bracket_ranges) =
9341 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9342 else {
9343 return;
9344 };
9345
9346 let mut best_length = usize::MAX;
9347 let mut best_inside = false;
9348 let mut best_in_bracket_range = false;
9349 let mut best_destination = None;
9350 for (open, close) in enclosing_bracket_ranges {
9351 let close = close.to_inclusive();
9352 let length = close.end() - open.start;
9353 let inside = selection.start >= open.end && selection.end <= *close.start();
9354 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9355 || close.contains(&selection.head());
9356
9357 // If best is next to a bracket and current isn't, skip
9358 if !in_bracket_range && best_in_bracket_range {
9359 continue;
9360 }
9361
9362 // Prefer smaller lengths unless best is inside and current isn't
9363 if length > best_length && (best_inside || !inside) {
9364 continue;
9365 }
9366
9367 best_length = length;
9368 best_inside = inside;
9369 best_in_bracket_range = in_bracket_range;
9370 best_destination = Some(
9371 if close.contains(&selection.start) && close.contains(&selection.end) {
9372 if inside {
9373 open.end
9374 } else {
9375 open.start
9376 }
9377 } else if inside {
9378 *close.start()
9379 } else {
9380 *close.end()
9381 },
9382 );
9383 }
9384
9385 if let Some(destination) = best_destination {
9386 selection.collapse_to(destination, SelectionGoal::None);
9387 }
9388 })
9389 });
9390 }
9391
9392 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9393 self.end_selection(cx);
9394 self.selection_history.mode = SelectionHistoryMode::Undoing;
9395 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9396 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9397 self.select_next_state = entry.select_next_state;
9398 self.select_prev_state = entry.select_prev_state;
9399 self.add_selections_state = entry.add_selections_state;
9400 self.request_autoscroll(Autoscroll::newest(), cx);
9401 }
9402 self.selection_history.mode = SelectionHistoryMode::Normal;
9403 }
9404
9405 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9406 self.end_selection(cx);
9407 self.selection_history.mode = SelectionHistoryMode::Redoing;
9408 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9409 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9410 self.select_next_state = entry.select_next_state;
9411 self.select_prev_state = entry.select_prev_state;
9412 self.add_selections_state = entry.add_selections_state;
9413 self.request_autoscroll(Autoscroll::newest(), cx);
9414 }
9415 self.selection_history.mode = SelectionHistoryMode::Normal;
9416 }
9417
9418 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9419 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9420 }
9421
9422 pub fn expand_excerpts_down(
9423 &mut self,
9424 action: &ExpandExcerptsDown,
9425 cx: &mut ViewContext<Self>,
9426 ) {
9427 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9428 }
9429
9430 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9431 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9432 }
9433
9434 pub fn expand_excerpts_for_direction(
9435 &mut self,
9436 lines: u32,
9437 direction: ExpandExcerptDirection,
9438 cx: &mut ViewContext<Self>,
9439 ) {
9440 let selections = self.selections.disjoint_anchors();
9441
9442 let lines = if lines == 0 {
9443 EditorSettings::get_global(cx).expand_excerpt_lines
9444 } else {
9445 lines
9446 };
9447
9448 self.buffer.update(cx, |buffer, cx| {
9449 buffer.expand_excerpts(
9450 selections
9451 .iter()
9452 .map(|selection| selection.head().excerpt_id)
9453 .dedup(),
9454 lines,
9455 direction,
9456 cx,
9457 )
9458 })
9459 }
9460
9461 pub fn expand_excerpt(
9462 &mut self,
9463 excerpt: ExcerptId,
9464 direction: ExpandExcerptDirection,
9465 cx: &mut ViewContext<Self>,
9466 ) {
9467 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9468 self.buffer.update(cx, |buffer, cx| {
9469 buffer.expand_excerpts([excerpt], lines, direction, cx)
9470 })
9471 }
9472
9473 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9474 self.go_to_diagnostic_impl(Direction::Next, cx)
9475 }
9476
9477 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9478 self.go_to_diagnostic_impl(Direction::Prev, cx)
9479 }
9480
9481 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9482 let buffer = self.buffer.read(cx).snapshot(cx);
9483 let selection = self.selections.newest::<usize>(cx);
9484
9485 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9486 if direction == Direction::Next {
9487 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9488 let (group_id, jump_to) = popover.activation_info();
9489 if self.activate_diagnostics(group_id, cx) {
9490 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9491 let mut new_selection = s.newest_anchor().clone();
9492 new_selection.collapse_to(jump_to, SelectionGoal::None);
9493 s.select_anchors(vec![new_selection.clone()]);
9494 });
9495 }
9496 return;
9497 }
9498 }
9499
9500 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9501 active_diagnostics
9502 .primary_range
9503 .to_offset(&buffer)
9504 .to_inclusive()
9505 });
9506 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9507 if active_primary_range.contains(&selection.head()) {
9508 *active_primary_range.start()
9509 } else {
9510 selection.head()
9511 }
9512 } else {
9513 selection.head()
9514 };
9515 let snapshot = self.snapshot(cx);
9516 loop {
9517 let diagnostics = if direction == Direction::Prev {
9518 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9519 } else {
9520 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9521 }
9522 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9523 let group = diagnostics
9524 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9525 // be sorted in a stable way
9526 // skip until we are at current active diagnostic, if it exists
9527 .skip_while(|entry| {
9528 (match direction {
9529 Direction::Prev => entry.range.start >= search_start,
9530 Direction::Next => entry.range.start <= search_start,
9531 }) && self
9532 .active_diagnostics
9533 .as_ref()
9534 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9535 })
9536 .find_map(|entry| {
9537 if entry.diagnostic.is_primary
9538 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9539 && !entry.range.is_empty()
9540 // if we match with the active diagnostic, skip it
9541 && Some(entry.diagnostic.group_id)
9542 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9543 {
9544 Some((entry.range, entry.diagnostic.group_id))
9545 } else {
9546 None
9547 }
9548 });
9549
9550 if let Some((primary_range, group_id)) = group {
9551 if self.activate_diagnostics(group_id, cx) {
9552 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9553 s.select(vec![Selection {
9554 id: selection.id,
9555 start: primary_range.start,
9556 end: primary_range.start,
9557 reversed: false,
9558 goal: SelectionGoal::None,
9559 }]);
9560 });
9561 }
9562 break;
9563 } else {
9564 // Cycle around to the start of the buffer, potentially moving back to the start of
9565 // the currently active diagnostic.
9566 active_primary_range.take();
9567 if direction == Direction::Prev {
9568 if search_start == buffer.len() {
9569 break;
9570 } else {
9571 search_start = buffer.len();
9572 }
9573 } else if search_start == 0 {
9574 break;
9575 } else {
9576 search_start = 0;
9577 }
9578 }
9579 }
9580 }
9581
9582 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9583 let snapshot = self
9584 .display_map
9585 .update(cx, |display_map, cx| display_map.snapshot(cx));
9586 let selection = self.selections.newest::<Point>(cx);
9587 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9588 }
9589
9590 fn go_to_hunk_after_position(
9591 &mut self,
9592 snapshot: &DisplaySnapshot,
9593 position: Point,
9594 cx: &mut ViewContext<'_, Editor>,
9595 ) -> Option<MultiBufferDiffHunk> {
9596 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9597 snapshot,
9598 position,
9599 false,
9600 snapshot
9601 .buffer_snapshot
9602 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9603 cx,
9604 ) {
9605 return Some(hunk);
9606 }
9607
9608 let wrapped_point = Point::zero();
9609 self.go_to_next_hunk_in_direction(
9610 snapshot,
9611 wrapped_point,
9612 true,
9613 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9614 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9615 ),
9616 cx,
9617 )
9618 }
9619
9620 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9621 let snapshot = self
9622 .display_map
9623 .update(cx, |display_map, cx| display_map.snapshot(cx));
9624 let selection = self.selections.newest::<Point>(cx);
9625
9626 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9627 }
9628
9629 fn go_to_hunk_before_position(
9630 &mut self,
9631 snapshot: &DisplaySnapshot,
9632 position: Point,
9633 cx: &mut ViewContext<'_, Editor>,
9634 ) -> Option<MultiBufferDiffHunk> {
9635 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9636 snapshot,
9637 position,
9638 false,
9639 snapshot
9640 .buffer_snapshot
9641 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9642 cx,
9643 ) {
9644 return Some(hunk);
9645 }
9646
9647 let wrapped_point = snapshot.buffer_snapshot.max_point();
9648 self.go_to_next_hunk_in_direction(
9649 snapshot,
9650 wrapped_point,
9651 true,
9652 snapshot
9653 .buffer_snapshot
9654 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9655 cx,
9656 )
9657 }
9658
9659 fn go_to_next_hunk_in_direction(
9660 &mut self,
9661 snapshot: &DisplaySnapshot,
9662 initial_point: Point,
9663 is_wrapped: bool,
9664 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9665 cx: &mut ViewContext<Editor>,
9666 ) -> Option<MultiBufferDiffHunk> {
9667 let display_point = initial_point.to_display_point(snapshot);
9668 let mut hunks = hunks
9669 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9670 .filter(|(display_hunk, _)| {
9671 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9672 })
9673 .dedup();
9674
9675 if let Some((display_hunk, hunk)) = hunks.next() {
9676 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9677 let row = display_hunk.start_display_row();
9678 let point = DisplayPoint::new(row, 0);
9679 s.select_display_ranges([point..point]);
9680 });
9681
9682 Some(hunk)
9683 } else {
9684 None
9685 }
9686 }
9687
9688 pub fn go_to_definition(
9689 &mut self,
9690 _: &GoToDefinition,
9691 cx: &mut ViewContext<Self>,
9692 ) -> Task<Result<Navigated>> {
9693 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9694 cx.spawn(|editor, mut cx| async move {
9695 if definition.await? == Navigated::Yes {
9696 return Ok(Navigated::Yes);
9697 }
9698 match editor.update(&mut cx, |editor, cx| {
9699 editor.find_all_references(&FindAllReferences, cx)
9700 })? {
9701 Some(references) => references.await,
9702 None => Ok(Navigated::No),
9703 }
9704 })
9705 }
9706
9707 pub fn go_to_declaration(
9708 &mut self,
9709 _: &GoToDeclaration,
9710 cx: &mut ViewContext<Self>,
9711 ) -> Task<Result<Navigated>> {
9712 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9713 }
9714
9715 pub fn go_to_declaration_split(
9716 &mut self,
9717 _: &GoToDeclaration,
9718 cx: &mut ViewContext<Self>,
9719 ) -> Task<Result<Navigated>> {
9720 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9721 }
9722
9723 pub fn go_to_implementation(
9724 &mut self,
9725 _: &GoToImplementation,
9726 cx: &mut ViewContext<Self>,
9727 ) -> Task<Result<Navigated>> {
9728 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9729 }
9730
9731 pub fn go_to_implementation_split(
9732 &mut self,
9733 _: &GoToImplementationSplit,
9734 cx: &mut ViewContext<Self>,
9735 ) -> Task<Result<Navigated>> {
9736 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9737 }
9738
9739 pub fn go_to_type_definition(
9740 &mut self,
9741 _: &GoToTypeDefinition,
9742 cx: &mut ViewContext<Self>,
9743 ) -> Task<Result<Navigated>> {
9744 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9745 }
9746
9747 pub fn go_to_definition_split(
9748 &mut self,
9749 _: &GoToDefinitionSplit,
9750 cx: &mut ViewContext<Self>,
9751 ) -> Task<Result<Navigated>> {
9752 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9753 }
9754
9755 pub fn go_to_type_definition_split(
9756 &mut self,
9757 _: &GoToTypeDefinitionSplit,
9758 cx: &mut ViewContext<Self>,
9759 ) -> Task<Result<Navigated>> {
9760 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9761 }
9762
9763 fn go_to_definition_of_kind(
9764 &mut self,
9765 kind: GotoDefinitionKind,
9766 split: bool,
9767 cx: &mut ViewContext<Self>,
9768 ) -> Task<Result<Navigated>> {
9769 let Some(provider) = self.semantics_provider.clone() else {
9770 return Task::ready(Ok(Navigated::No));
9771 };
9772 let head = self.selections.newest::<usize>(cx).head();
9773 let buffer = self.buffer.read(cx);
9774 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9775 text_anchor
9776 } else {
9777 return Task::ready(Ok(Navigated::No));
9778 };
9779
9780 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9781 return Task::ready(Ok(Navigated::No));
9782 };
9783
9784 cx.spawn(|editor, mut cx| async move {
9785 let definitions = definitions.await?;
9786 let navigated = editor
9787 .update(&mut cx, |editor, cx| {
9788 editor.navigate_to_hover_links(
9789 Some(kind),
9790 definitions
9791 .into_iter()
9792 .filter(|location| {
9793 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9794 })
9795 .map(HoverLink::Text)
9796 .collect::<Vec<_>>(),
9797 split,
9798 cx,
9799 )
9800 })?
9801 .await?;
9802 anyhow::Ok(navigated)
9803 })
9804 }
9805
9806 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9807 let position = self.selections.newest_anchor().head();
9808 let Some((buffer, buffer_position)) =
9809 self.buffer.read(cx).text_anchor_for_position(position, cx)
9810 else {
9811 return;
9812 };
9813
9814 cx.spawn(|editor, mut cx| async move {
9815 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9816 editor.update(&mut cx, |_, cx| {
9817 cx.open_url(&url);
9818 })
9819 } else {
9820 Ok(())
9821 }
9822 })
9823 .detach();
9824 }
9825
9826 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9827 let Some(workspace) = self.workspace() else {
9828 return;
9829 };
9830
9831 let position = self.selections.newest_anchor().head();
9832
9833 let Some((buffer, buffer_position)) =
9834 self.buffer.read(cx).text_anchor_for_position(position, cx)
9835 else {
9836 return;
9837 };
9838
9839 let project = self.project.clone();
9840
9841 cx.spawn(|_, mut cx| async move {
9842 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9843
9844 if let Some((_, path)) = result {
9845 workspace
9846 .update(&mut cx, |workspace, cx| {
9847 workspace.open_resolved_path(path, cx)
9848 })?
9849 .await?;
9850 }
9851 anyhow::Ok(())
9852 })
9853 .detach();
9854 }
9855
9856 pub(crate) fn navigate_to_hover_links(
9857 &mut self,
9858 kind: Option<GotoDefinitionKind>,
9859 mut definitions: Vec<HoverLink>,
9860 split: bool,
9861 cx: &mut ViewContext<Editor>,
9862 ) -> Task<Result<Navigated>> {
9863 // If there is one definition, just open it directly
9864 if definitions.len() == 1 {
9865 let definition = definitions.pop().unwrap();
9866
9867 enum TargetTaskResult {
9868 Location(Option<Location>),
9869 AlreadyNavigated,
9870 }
9871
9872 let target_task = match definition {
9873 HoverLink::Text(link) => {
9874 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9875 }
9876 HoverLink::InlayHint(lsp_location, server_id) => {
9877 let computation = self.compute_target_location(lsp_location, server_id, cx);
9878 cx.background_executor().spawn(async move {
9879 let location = computation.await?;
9880 Ok(TargetTaskResult::Location(location))
9881 })
9882 }
9883 HoverLink::Url(url) => {
9884 cx.open_url(&url);
9885 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9886 }
9887 HoverLink::File(path) => {
9888 if let Some(workspace) = self.workspace() {
9889 cx.spawn(|_, mut cx| async move {
9890 workspace
9891 .update(&mut cx, |workspace, cx| {
9892 workspace.open_resolved_path(path, cx)
9893 })?
9894 .await
9895 .map(|_| TargetTaskResult::AlreadyNavigated)
9896 })
9897 } else {
9898 Task::ready(Ok(TargetTaskResult::Location(None)))
9899 }
9900 }
9901 };
9902 cx.spawn(|editor, mut cx| async move {
9903 let target = match target_task.await.context("target resolution task")? {
9904 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9905 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9906 TargetTaskResult::Location(Some(target)) => target,
9907 };
9908
9909 editor.update(&mut cx, |editor, cx| {
9910 let Some(workspace) = editor.workspace() else {
9911 return Navigated::No;
9912 };
9913 let pane = workspace.read(cx).active_pane().clone();
9914
9915 let range = target.range.to_offset(target.buffer.read(cx));
9916 let range = editor.range_for_match(&range);
9917
9918 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9919 let buffer = target.buffer.read(cx);
9920 let range = check_multiline_range(buffer, range);
9921 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9922 s.select_ranges([range]);
9923 });
9924 } else {
9925 cx.window_context().defer(move |cx| {
9926 let target_editor: View<Self> =
9927 workspace.update(cx, |workspace, cx| {
9928 let pane = if split {
9929 workspace.adjacent_pane(cx)
9930 } else {
9931 workspace.active_pane().clone()
9932 };
9933
9934 workspace.open_project_item(
9935 pane,
9936 target.buffer.clone(),
9937 true,
9938 true,
9939 cx,
9940 )
9941 });
9942 target_editor.update(cx, |target_editor, cx| {
9943 // When selecting a definition in a different buffer, disable the nav history
9944 // to avoid creating a history entry at the previous cursor location.
9945 pane.update(cx, |pane, _| pane.disable_history());
9946 let buffer = target.buffer.read(cx);
9947 let range = check_multiline_range(buffer, range);
9948 target_editor.change_selections(
9949 Some(Autoscroll::focused()),
9950 cx,
9951 |s| {
9952 s.select_ranges([range]);
9953 },
9954 );
9955 pane.update(cx, |pane, _| pane.enable_history());
9956 });
9957 });
9958 }
9959 Navigated::Yes
9960 })
9961 })
9962 } else if !definitions.is_empty() {
9963 cx.spawn(|editor, mut cx| async move {
9964 let (title, location_tasks, workspace) = editor
9965 .update(&mut cx, |editor, cx| {
9966 let tab_kind = match kind {
9967 Some(GotoDefinitionKind::Implementation) => "Implementations",
9968 _ => "Definitions",
9969 };
9970 let title = definitions
9971 .iter()
9972 .find_map(|definition| match definition {
9973 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9974 let buffer = origin.buffer.read(cx);
9975 format!(
9976 "{} for {}",
9977 tab_kind,
9978 buffer
9979 .text_for_range(origin.range.clone())
9980 .collect::<String>()
9981 )
9982 }),
9983 HoverLink::InlayHint(_, _) => None,
9984 HoverLink::Url(_) => None,
9985 HoverLink::File(_) => None,
9986 })
9987 .unwrap_or(tab_kind.to_string());
9988 let location_tasks = definitions
9989 .into_iter()
9990 .map(|definition| match definition {
9991 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9992 HoverLink::InlayHint(lsp_location, server_id) => {
9993 editor.compute_target_location(lsp_location, server_id, cx)
9994 }
9995 HoverLink::Url(_) => Task::ready(Ok(None)),
9996 HoverLink::File(_) => Task::ready(Ok(None)),
9997 })
9998 .collect::<Vec<_>>();
9999 (title, location_tasks, editor.workspace().clone())
10000 })
10001 .context("location tasks preparation")?;
10002
10003 let locations = future::join_all(location_tasks)
10004 .await
10005 .into_iter()
10006 .filter_map(|location| location.transpose())
10007 .collect::<Result<_>>()
10008 .context("location tasks")?;
10009
10010 let Some(workspace) = workspace else {
10011 return Ok(Navigated::No);
10012 };
10013 let opened = workspace
10014 .update(&mut cx, |workspace, cx| {
10015 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10016 })
10017 .ok();
10018
10019 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10020 })
10021 } else {
10022 Task::ready(Ok(Navigated::No))
10023 }
10024 }
10025
10026 fn compute_target_location(
10027 &self,
10028 lsp_location: lsp::Location,
10029 server_id: LanguageServerId,
10030 cx: &mut ViewContext<Self>,
10031 ) -> Task<anyhow::Result<Option<Location>>> {
10032 let Some(project) = self.project.clone() else {
10033 return Task::Ready(Some(Ok(None)));
10034 };
10035
10036 cx.spawn(move |editor, mut cx| async move {
10037 let location_task = editor.update(&mut cx, |_, cx| {
10038 project.update(cx, |project, cx| {
10039 let language_server_name = project
10040 .language_server_statuses(cx)
10041 .find(|(id, _)| server_id == *id)
10042 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10043 language_server_name.map(|language_server_name| {
10044 project.open_local_buffer_via_lsp(
10045 lsp_location.uri.clone(),
10046 server_id,
10047 language_server_name,
10048 cx,
10049 )
10050 })
10051 })
10052 })?;
10053 let location = match location_task {
10054 Some(task) => Some({
10055 let target_buffer_handle = task.await.context("open local buffer")?;
10056 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10057 let target_start = target_buffer
10058 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10059 let target_end = target_buffer
10060 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10061 target_buffer.anchor_after(target_start)
10062 ..target_buffer.anchor_before(target_end)
10063 })?;
10064 Location {
10065 buffer: target_buffer_handle,
10066 range,
10067 }
10068 }),
10069 None => None,
10070 };
10071 Ok(location)
10072 })
10073 }
10074
10075 pub fn find_all_references(
10076 &mut self,
10077 _: &FindAllReferences,
10078 cx: &mut ViewContext<Self>,
10079 ) -> Option<Task<Result<Navigated>>> {
10080 let selection = self.selections.newest::<usize>(cx);
10081 let multi_buffer = self.buffer.read(cx);
10082 let head = selection.head();
10083
10084 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10085 let head_anchor = multi_buffer_snapshot.anchor_at(
10086 head,
10087 if head < selection.tail() {
10088 Bias::Right
10089 } else {
10090 Bias::Left
10091 },
10092 );
10093
10094 match self
10095 .find_all_references_task_sources
10096 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10097 {
10098 Ok(_) => {
10099 log::info!(
10100 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10101 );
10102 return None;
10103 }
10104 Err(i) => {
10105 self.find_all_references_task_sources.insert(i, head_anchor);
10106 }
10107 }
10108
10109 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10110 let workspace = self.workspace()?;
10111 let project = workspace.read(cx).project().clone();
10112 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10113 Some(cx.spawn(|editor, mut cx| async move {
10114 let _cleanup = defer({
10115 let mut cx = cx.clone();
10116 move || {
10117 let _ = editor.update(&mut cx, |editor, _| {
10118 if let Ok(i) =
10119 editor
10120 .find_all_references_task_sources
10121 .binary_search_by(|anchor| {
10122 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10123 })
10124 {
10125 editor.find_all_references_task_sources.remove(i);
10126 }
10127 });
10128 }
10129 });
10130
10131 let locations = references.await?;
10132 if locations.is_empty() {
10133 return anyhow::Ok(Navigated::No);
10134 }
10135
10136 workspace.update(&mut cx, |workspace, cx| {
10137 let title = locations
10138 .first()
10139 .as_ref()
10140 .map(|location| {
10141 let buffer = location.buffer.read(cx);
10142 format!(
10143 "References to `{}`",
10144 buffer
10145 .text_for_range(location.range.clone())
10146 .collect::<String>()
10147 )
10148 })
10149 .unwrap();
10150 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10151 Navigated::Yes
10152 })
10153 }))
10154 }
10155
10156 /// Opens a multibuffer with the given project locations in it
10157 pub fn open_locations_in_multibuffer(
10158 workspace: &mut Workspace,
10159 mut locations: Vec<Location>,
10160 title: String,
10161 split: bool,
10162 cx: &mut ViewContext<Workspace>,
10163 ) {
10164 // If there are multiple definitions, open them in a multibuffer
10165 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10166 let mut locations = locations.into_iter().peekable();
10167 let mut ranges_to_highlight = Vec::new();
10168 let capability = workspace.project().read(cx).capability();
10169
10170 let excerpt_buffer = cx.new_model(|cx| {
10171 let mut multibuffer = MultiBuffer::new(capability);
10172 while let Some(location) = locations.next() {
10173 let buffer = location.buffer.read(cx);
10174 let mut ranges_for_buffer = Vec::new();
10175 let range = location.range.to_offset(buffer);
10176 ranges_for_buffer.push(range.clone());
10177
10178 while let Some(next_location) = locations.peek() {
10179 if next_location.buffer == location.buffer {
10180 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10181 locations.next();
10182 } else {
10183 break;
10184 }
10185 }
10186
10187 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10188 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10189 location.buffer.clone(),
10190 ranges_for_buffer,
10191 DEFAULT_MULTIBUFFER_CONTEXT,
10192 cx,
10193 ))
10194 }
10195
10196 multibuffer.with_title(title)
10197 });
10198
10199 let editor = cx.new_view(|cx| {
10200 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10201 });
10202 editor.update(cx, |editor, cx| {
10203 if let Some(first_range) = ranges_to_highlight.first() {
10204 editor.change_selections(None, cx, |selections| {
10205 selections.clear_disjoint();
10206 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10207 });
10208 }
10209 editor.highlight_background::<Self>(
10210 &ranges_to_highlight,
10211 |theme| theme.editor_highlighted_line_background,
10212 cx,
10213 );
10214 });
10215
10216 let item = Box::new(editor);
10217 let item_id = item.item_id();
10218
10219 if split {
10220 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10221 } else {
10222 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10223 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10224 pane.close_current_preview_item(cx)
10225 } else {
10226 None
10227 }
10228 });
10229 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10230 }
10231 workspace.active_pane().update(cx, |pane, cx| {
10232 pane.set_preview_item_id(Some(item_id), cx);
10233 });
10234 }
10235
10236 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10237 use language::ToOffset as _;
10238
10239 let provider = self.semantics_provider.clone()?;
10240 let selection = self.selections.newest_anchor().clone();
10241 let (cursor_buffer, cursor_buffer_position) = self
10242 .buffer
10243 .read(cx)
10244 .text_anchor_for_position(selection.head(), cx)?;
10245 let (tail_buffer, cursor_buffer_position_end) = self
10246 .buffer
10247 .read(cx)
10248 .text_anchor_for_position(selection.tail(), cx)?;
10249 if tail_buffer != cursor_buffer {
10250 return None;
10251 }
10252
10253 let snapshot = cursor_buffer.read(cx).snapshot();
10254 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10255 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10256 let prepare_rename = provider
10257 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10258 .unwrap_or_else(|| Task::ready(Ok(None)));
10259 drop(snapshot);
10260
10261 Some(cx.spawn(|this, mut cx| async move {
10262 let rename_range = if let Some(range) = prepare_rename.await? {
10263 Some(range)
10264 } else {
10265 this.update(&mut cx, |this, cx| {
10266 let buffer = this.buffer.read(cx).snapshot(cx);
10267 let mut buffer_highlights = this
10268 .document_highlights_for_position(selection.head(), &buffer)
10269 .filter(|highlight| {
10270 highlight.start.excerpt_id == selection.head().excerpt_id
10271 && highlight.end.excerpt_id == selection.head().excerpt_id
10272 });
10273 buffer_highlights
10274 .next()
10275 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10276 })?
10277 };
10278 if let Some(rename_range) = rename_range {
10279 this.update(&mut cx, |this, cx| {
10280 let snapshot = cursor_buffer.read(cx).snapshot();
10281 let rename_buffer_range = rename_range.to_offset(&snapshot);
10282 let cursor_offset_in_rename_range =
10283 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10284 let cursor_offset_in_rename_range_end =
10285 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10286
10287 this.take_rename(false, cx);
10288 let buffer = this.buffer.read(cx).read(cx);
10289 let cursor_offset = selection.head().to_offset(&buffer);
10290 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10291 let rename_end = rename_start + rename_buffer_range.len();
10292 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10293 let mut old_highlight_id = None;
10294 let old_name: Arc<str> = buffer
10295 .chunks(rename_start..rename_end, true)
10296 .map(|chunk| {
10297 if old_highlight_id.is_none() {
10298 old_highlight_id = chunk.syntax_highlight_id;
10299 }
10300 chunk.text
10301 })
10302 .collect::<String>()
10303 .into();
10304
10305 drop(buffer);
10306
10307 // Position the selection in the rename editor so that it matches the current selection.
10308 this.show_local_selections = false;
10309 let rename_editor = cx.new_view(|cx| {
10310 let mut editor = Editor::single_line(cx);
10311 editor.buffer.update(cx, |buffer, cx| {
10312 buffer.edit([(0..0, old_name.clone())], None, cx)
10313 });
10314 let rename_selection_range = match cursor_offset_in_rename_range
10315 .cmp(&cursor_offset_in_rename_range_end)
10316 {
10317 Ordering::Equal => {
10318 editor.select_all(&SelectAll, cx);
10319 return editor;
10320 }
10321 Ordering::Less => {
10322 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10323 }
10324 Ordering::Greater => {
10325 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10326 }
10327 };
10328 if rename_selection_range.end > old_name.len() {
10329 editor.select_all(&SelectAll, cx);
10330 } else {
10331 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10332 s.select_ranges([rename_selection_range]);
10333 });
10334 }
10335 editor
10336 });
10337 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10338 if e == &EditorEvent::Focused {
10339 cx.emit(EditorEvent::FocusedIn)
10340 }
10341 })
10342 .detach();
10343
10344 let write_highlights =
10345 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10346 let read_highlights =
10347 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10348 let ranges = write_highlights
10349 .iter()
10350 .flat_map(|(_, ranges)| ranges.iter())
10351 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10352 .cloned()
10353 .collect();
10354
10355 this.highlight_text::<Rename>(
10356 ranges,
10357 HighlightStyle {
10358 fade_out: Some(0.6),
10359 ..Default::default()
10360 },
10361 cx,
10362 );
10363 let rename_focus_handle = rename_editor.focus_handle(cx);
10364 cx.focus(&rename_focus_handle);
10365 let block_id = this.insert_blocks(
10366 [BlockProperties {
10367 style: BlockStyle::Flex,
10368 placement: BlockPlacement::Below(range.start),
10369 height: 1,
10370 render: Box::new({
10371 let rename_editor = rename_editor.clone();
10372 move |cx: &mut BlockContext| {
10373 let mut text_style = cx.editor_style.text.clone();
10374 if let Some(highlight_style) = old_highlight_id
10375 .and_then(|h| h.style(&cx.editor_style.syntax))
10376 {
10377 text_style = text_style.highlight(highlight_style);
10378 }
10379 div()
10380 .pl(cx.anchor_x)
10381 .child(EditorElement::new(
10382 &rename_editor,
10383 EditorStyle {
10384 background: cx.theme().system().transparent,
10385 local_player: cx.editor_style.local_player,
10386 text: text_style,
10387 scrollbar_width: cx.editor_style.scrollbar_width,
10388 syntax: cx.editor_style.syntax.clone(),
10389 status: cx.editor_style.status.clone(),
10390 inlay_hints_style: HighlightStyle {
10391 font_weight: Some(FontWeight::BOLD),
10392 ..make_inlay_hints_style(cx)
10393 },
10394 suggestions_style: HighlightStyle {
10395 color: Some(cx.theme().status().predictive),
10396 ..HighlightStyle::default()
10397 },
10398 ..EditorStyle::default()
10399 },
10400 ))
10401 .into_any_element()
10402 }
10403 }),
10404 priority: 0,
10405 }],
10406 Some(Autoscroll::fit()),
10407 cx,
10408 )[0];
10409 this.pending_rename = Some(RenameState {
10410 range,
10411 old_name,
10412 editor: rename_editor,
10413 block_id,
10414 });
10415 })?;
10416 }
10417
10418 Ok(())
10419 }))
10420 }
10421
10422 pub fn confirm_rename(
10423 &mut self,
10424 _: &ConfirmRename,
10425 cx: &mut ViewContext<Self>,
10426 ) -> Option<Task<Result<()>>> {
10427 let rename = self.take_rename(false, cx)?;
10428 let workspace = self.workspace()?.downgrade();
10429 let (buffer, start) = self
10430 .buffer
10431 .read(cx)
10432 .text_anchor_for_position(rename.range.start, cx)?;
10433 let (end_buffer, _) = self
10434 .buffer
10435 .read(cx)
10436 .text_anchor_for_position(rename.range.end, cx)?;
10437 if buffer != end_buffer {
10438 return None;
10439 }
10440
10441 let old_name = rename.old_name;
10442 let new_name = rename.editor.read(cx).text(cx);
10443
10444 let rename = self.semantics_provider.as_ref()?.perform_rename(
10445 &buffer,
10446 start,
10447 new_name.clone(),
10448 cx,
10449 )?;
10450
10451 Some(cx.spawn(|editor, mut cx| async move {
10452 let project_transaction = rename.await?;
10453 Self::open_project_transaction(
10454 &editor,
10455 workspace,
10456 project_transaction,
10457 format!("Rename: {} → {}", old_name, new_name),
10458 cx.clone(),
10459 )
10460 .await?;
10461
10462 editor.update(&mut cx, |editor, cx| {
10463 editor.refresh_document_highlights(cx);
10464 })?;
10465 Ok(())
10466 }))
10467 }
10468
10469 fn take_rename(
10470 &mut self,
10471 moving_cursor: bool,
10472 cx: &mut ViewContext<Self>,
10473 ) -> Option<RenameState> {
10474 let rename = self.pending_rename.take()?;
10475 if rename.editor.focus_handle(cx).is_focused(cx) {
10476 cx.focus(&self.focus_handle);
10477 }
10478
10479 self.remove_blocks(
10480 [rename.block_id].into_iter().collect(),
10481 Some(Autoscroll::fit()),
10482 cx,
10483 );
10484 self.clear_highlights::<Rename>(cx);
10485 self.show_local_selections = true;
10486
10487 if moving_cursor {
10488 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10489 editor.selections.newest::<usize>(cx).head()
10490 });
10491
10492 // Update the selection to match the position of the selection inside
10493 // the rename editor.
10494 let snapshot = self.buffer.read(cx).read(cx);
10495 let rename_range = rename.range.to_offset(&snapshot);
10496 let cursor_in_editor = snapshot
10497 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10498 .min(rename_range.end);
10499 drop(snapshot);
10500
10501 self.change_selections(None, cx, |s| {
10502 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10503 });
10504 } else {
10505 self.refresh_document_highlights(cx);
10506 }
10507
10508 Some(rename)
10509 }
10510
10511 pub fn pending_rename(&self) -> Option<&RenameState> {
10512 self.pending_rename.as_ref()
10513 }
10514
10515 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10516 let project = match &self.project {
10517 Some(project) => project.clone(),
10518 None => return None,
10519 };
10520
10521 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10522 }
10523
10524 fn format_selections(
10525 &mut self,
10526 _: &FormatSelections,
10527 cx: &mut ViewContext<Self>,
10528 ) -> Option<Task<Result<()>>> {
10529 let project = match &self.project {
10530 Some(project) => project.clone(),
10531 None => return None,
10532 };
10533
10534 let selections = self
10535 .selections
10536 .all_adjusted(cx)
10537 .into_iter()
10538 .filter(|s| !s.is_empty())
10539 .collect_vec();
10540
10541 Some(self.perform_format(
10542 project,
10543 FormatTrigger::Manual,
10544 FormatTarget::Ranges(selections),
10545 cx,
10546 ))
10547 }
10548
10549 fn perform_format(
10550 &mut self,
10551 project: Model<Project>,
10552 trigger: FormatTrigger,
10553 target: FormatTarget,
10554 cx: &mut ViewContext<Self>,
10555 ) -> Task<Result<()>> {
10556 let buffer = self.buffer().clone();
10557 let mut buffers = buffer.read(cx).all_buffers();
10558 if trigger == FormatTrigger::Save {
10559 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10560 }
10561
10562 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10563 let format = project.update(cx, |project, cx| {
10564 project.format(buffers, true, trigger, target, cx)
10565 });
10566
10567 cx.spawn(|_, mut cx| async move {
10568 let transaction = futures::select_biased! {
10569 () = timeout => {
10570 log::warn!("timed out waiting for formatting");
10571 None
10572 }
10573 transaction = format.log_err().fuse() => transaction,
10574 };
10575
10576 buffer
10577 .update(&mut cx, |buffer, cx| {
10578 if let Some(transaction) = transaction {
10579 if !buffer.is_singleton() {
10580 buffer.push_transaction(&transaction.0, cx);
10581 }
10582 }
10583
10584 cx.notify();
10585 })
10586 .ok();
10587
10588 Ok(())
10589 })
10590 }
10591
10592 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10593 if let Some(project) = self.project.clone() {
10594 self.buffer.update(cx, |multi_buffer, cx| {
10595 project.update(cx, |project, cx| {
10596 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10597 });
10598 })
10599 }
10600 }
10601
10602 fn cancel_language_server_work(
10603 &mut self,
10604 _: &actions::CancelLanguageServerWork,
10605 cx: &mut ViewContext<Self>,
10606 ) {
10607 if let Some(project) = self.project.clone() {
10608 self.buffer.update(cx, |multi_buffer, cx| {
10609 project.update(cx, |project, cx| {
10610 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10611 });
10612 })
10613 }
10614 }
10615
10616 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10617 cx.show_character_palette();
10618 }
10619
10620 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10621 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10622 let buffer = self.buffer.read(cx).snapshot(cx);
10623 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10624 let is_valid = buffer
10625 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10626 .any(|entry| {
10627 entry.diagnostic.is_primary
10628 && !entry.range.is_empty()
10629 && entry.range.start == primary_range_start
10630 && entry.diagnostic.message == active_diagnostics.primary_message
10631 });
10632
10633 if is_valid != active_diagnostics.is_valid {
10634 active_diagnostics.is_valid = is_valid;
10635 let mut new_styles = HashMap::default();
10636 for (block_id, diagnostic) in &active_diagnostics.blocks {
10637 new_styles.insert(
10638 *block_id,
10639 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10640 );
10641 }
10642 self.display_map.update(cx, |display_map, _cx| {
10643 display_map.replace_blocks(new_styles)
10644 });
10645 }
10646 }
10647 }
10648
10649 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10650 self.dismiss_diagnostics(cx);
10651 let snapshot = self.snapshot(cx);
10652 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10653 let buffer = self.buffer.read(cx).snapshot(cx);
10654
10655 let mut primary_range = None;
10656 let mut primary_message = None;
10657 let mut group_end = Point::zero();
10658 let diagnostic_group = buffer
10659 .diagnostic_group::<MultiBufferPoint>(group_id)
10660 .filter_map(|entry| {
10661 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10662 && (entry.range.start.row == entry.range.end.row
10663 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10664 {
10665 return None;
10666 }
10667 if entry.range.end > group_end {
10668 group_end = entry.range.end;
10669 }
10670 if entry.diagnostic.is_primary {
10671 primary_range = Some(entry.range.clone());
10672 primary_message = Some(entry.diagnostic.message.clone());
10673 }
10674 Some(entry)
10675 })
10676 .collect::<Vec<_>>();
10677 let primary_range = primary_range?;
10678 let primary_message = primary_message?;
10679 let primary_range =
10680 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10681
10682 let blocks = display_map
10683 .insert_blocks(
10684 diagnostic_group.iter().map(|entry| {
10685 let diagnostic = entry.diagnostic.clone();
10686 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10687 BlockProperties {
10688 style: BlockStyle::Fixed,
10689 placement: BlockPlacement::Below(
10690 buffer.anchor_after(entry.range.start),
10691 ),
10692 height: message_height,
10693 render: diagnostic_block_renderer(diagnostic, None, true, true),
10694 priority: 0,
10695 }
10696 }),
10697 cx,
10698 )
10699 .into_iter()
10700 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10701 .collect();
10702
10703 Some(ActiveDiagnosticGroup {
10704 primary_range,
10705 primary_message,
10706 group_id,
10707 blocks,
10708 is_valid: true,
10709 })
10710 });
10711 self.active_diagnostics.is_some()
10712 }
10713
10714 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10715 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10716 self.display_map.update(cx, |display_map, cx| {
10717 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10718 });
10719 cx.notify();
10720 }
10721 }
10722
10723 pub fn set_selections_from_remote(
10724 &mut self,
10725 selections: Vec<Selection<Anchor>>,
10726 pending_selection: Option<Selection<Anchor>>,
10727 cx: &mut ViewContext<Self>,
10728 ) {
10729 let old_cursor_position = self.selections.newest_anchor().head();
10730 self.selections.change_with(cx, |s| {
10731 s.select_anchors(selections);
10732 if let Some(pending_selection) = pending_selection {
10733 s.set_pending(pending_selection, SelectMode::Character);
10734 } else {
10735 s.clear_pending();
10736 }
10737 });
10738 self.selections_did_change(false, &old_cursor_position, true, cx);
10739 }
10740
10741 fn push_to_selection_history(&mut self) {
10742 self.selection_history.push(SelectionHistoryEntry {
10743 selections: self.selections.disjoint_anchors(),
10744 select_next_state: self.select_next_state.clone(),
10745 select_prev_state: self.select_prev_state.clone(),
10746 add_selections_state: self.add_selections_state.clone(),
10747 });
10748 }
10749
10750 pub fn transact(
10751 &mut self,
10752 cx: &mut ViewContext<Self>,
10753 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10754 ) -> Option<TransactionId> {
10755 self.start_transaction_at(Instant::now(), cx);
10756 update(self, cx);
10757 self.end_transaction_at(Instant::now(), cx)
10758 }
10759
10760 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10761 self.end_selection(cx);
10762 if let Some(tx_id) = self
10763 .buffer
10764 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10765 {
10766 self.selection_history
10767 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10768 cx.emit(EditorEvent::TransactionBegun {
10769 transaction_id: tx_id,
10770 })
10771 }
10772 }
10773
10774 fn end_transaction_at(
10775 &mut self,
10776 now: Instant,
10777 cx: &mut ViewContext<Self>,
10778 ) -> Option<TransactionId> {
10779 if let Some(transaction_id) = self
10780 .buffer
10781 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10782 {
10783 if let Some((_, end_selections)) =
10784 self.selection_history.transaction_mut(transaction_id)
10785 {
10786 *end_selections = Some(self.selections.disjoint_anchors());
10787 } else {
10788 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10789 }
10790
10791 cx.emit(EditorEvent::Edited { transaction_id });
10792 Some(transaction_id)
10793 } else {
10794 None
10795 }
10796 }
10797
10798 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10799 let selection = self.selections.newest::<Point>(cx);
10800
10801 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10802 let range = if selection.is_empty() {
10803 let point = selection.head().to_display_point(&display_map);
10804 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10805 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10806 .to_point(&display_map);
10807 start..end
10808 } else {
10809 selection.range()
10810 };
10811 if display_map.folds_in_range(range).next().is_some() {
10812 self.unfold_lines(&Default::default(), cx)
10813 } else {
10814 self.fold(&Default::default(), cx)
10815 }
10816 }
10817
10818 pub fn toggle_fold_recursive(
10819 &mut self,
10820 _: &actions::ToggleFoldRecursive,
10821 cx: &mut ViewContext<Self>,
10822 ) {
10823 let selection = self.selections.newest::<Point>(cx);
10824
10825 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10826 let range = if selection.is_empty() {
10827 let point = selection.head().to_display_point(&display_map);
10828 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10829 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10830 .to_point(&display_map);
10831 start..end
10832 } else {
10833 selection.range()
10834 };
10835 if display_map.folds_in_range(range).next().is_some() {
10836 self.unfold_recursive(&Default::default(), cx)
10837 } else {
10838 self.fold_recursive(&Default::default(), cx)
10839 }
10840 }
10841
10842 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10843 let mut fold_ranges = Vec::new();
10844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10845 let selections = self.selections.all_adjusted(cx);
10846
10847 for selection in selections {
10848 let range = selection.range().sorted();
10849 let buffer_start_row = range.start.row;
10850
10851 if range.start.row != range.end.row {
10852 let mut found = false;
10853 let mut row = range.start.row;
10854 while row <= range.end.row {
10855 if let Some((foldable_range, fold_text)) =
10856 { display_map.foldable_range(MultiBufferRow(row)) }
10857 {
10858 found = true;
10859 row = foldable_range.end.row + 1;
10860 fold_ranges.push((foldable_range, fold_text));
10861 } else {
10862 row += 1
10863 }
10864 }
10865 if found {
10866 continue;
10867 }
10868 }
10869
10870 for row in (0..=range.start.row).rev() {
10871 if let Some((foldable_range, fold_text)) =
10872 display_map.foldable_range(MultiBufferRow(row))
10873 {
10874 if foldable_range.end.row >= buffer_start_row {
10875 fold_ranges.push((foldable_range, fold_text));
10876 if row <= range.start.row {
10877 break;
10878 }
10879 }
10880 }
10881 }
10882 }
10883
10884 self.fold_ranges(fold_ranges, true, cx);
10885 }
10886
10887 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10888 let fold_at_level = fold_at.level;
10889 let snapshot = self.buffer.read(cx).snapshot(cx);
10890 let mut fold_ranges = Vec::new();
10891 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10892
10893 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10894 while start_row < end_row {
10895 match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10896 Some(foldable_range) => {
10897 let nested_start_row = foldable_range.0.start.row + 1;
10898 let nested_end_row = foldable_range.0.end.row;
10899
10900 if current_level < fold_at_level {
10901 stack.push((nested_start_row, nested_end_row, current_level + 1));
10902 } else if current_level == fold_at_level {
10903 fold_ranges.push(foldable_range);
10904 }
10905
10906 start_row = nested_end_row + 1;
10907 }
10908 None => start_row += 1,
10909 }
10910 }
10911 }
10912
10913 self.fold_ranges(fold_ranges, true, cx);
10914 }
10915
10916 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10917 let mut fold_ranges = Vec::new();
10918 let snapshot = self.buffer.read(cx).snapshot(cx);
10919
10920 for row in 0..snapshot.max_buffer_row().0 {
10921 if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10922 fold_ranges.push(foldable_range);
10923 }
10924 }
10925
10926 self.fold_ranges(fold_ranges, true, cx);
10927 }
10928
10929 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10930 let mut fold_ranges = Vec::new();
10931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10932 let selections = self.selections.all_adjusted(cx);
10933
10934 for selection in selections {
10935 let range = selection.range().sorted();
10936 let buffer_start_row = range.start.row;
10937
10938 if range.start.row != range.end.row {
10939 let mut found = false;
10940 for row in range.start.row..=range.end.row {
10941 if let Some((foldable_range, fold_text)) =
10942 { display_map.foldable_range(MultiBufferRow(row)) }
10943 {
10944 found = true;
10945 fold_ranges.push((foldable_range, fold_text));
10946 }
10947 }
10948 if found {
10949 continue;
10950 }
10951 }
10952
10953 for row in (0..=range.start.row).rev() {
10954 if let Some((foldable_range, fold_text)) =
10955 display_map.foldable_range(MultiBufferRow(row))
10956 {
10957 if foldable_range.end.row >= buffer_start_row {
10958 fold_ranges.push((foldable_range, fold_text));
10959 } else {
10960 break;
10961 }
10962 }
10963 }
10964 }
10965
10966 self.fold_ranges(fold_ranges, true, cx);
10967 }
10968
10969 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10970 let buffer_row = fold_at.buffer_row;
10971 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10972
10973 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10974 let autoscroll = self
10975 .selections
10976 .all::<Point>(cx)
10977 .iter()
10978 .any(|selection| fold_range.overlaps(&selection.range()));
10979
10980 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10981 }
10982 }
10983
10984 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10986 let buffer = &display_map.buffer_snapshot;
10987 let selections = self.selections.all::<Point>(cx);
10988 let ranges = selections
10989 .iter()
10990 .map(|s| {
10991 let range = s.display_range(&display_map).sorted();
10992 let mut start = range.start.to_point(&display_map);
10993 let mut end = range.end.to_point(&display_map);
10994 start.column = 0;
10995 end.column = buffer.line_len(MultiBufferRow(end.row));
10996 start..end
10997 })
10998 .collect::<Vec<_>>();
10999
11000 self.unfold_ranges(ranges, true, true, cx);
11001 }
11002
11003 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11004 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11005 let selections = self.selections.all::<Point>(cx);
11006 let ranges = selections
11007 .iter()
11008 .map(|s| {
11009 let mut range = s.display_range(&display_map).sorted();
11010 *range.start.column_mut() = 0;
11011 *range.end.column_mut() = display_map.line_len(range.end.row());
11012 let start = range.start.to_point(&display_map);
11013 let end = range.end.to_point(&display_map);
11014 start..end
11015 })
11016 .collect::<Vec<_>>();
11017
11018 self.unfold_ranges(ranges, true, true, cx);
11019 }
11020
11021 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11022 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11023
11024 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11025 ..Point::new(
11026 unfold_at.buffer_row.0,
11027 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11028 );
11029
11030 let autoscroll = self
11031 .selections
11032 .all::<Point>(cx)
11033 .iter()
11034 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11035
11036 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
11037 }
11038
11039 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11040 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11041 self.unfold_ranges(
11042 [Point::zero()..display_map.max_point().to_point(&display_map)],
11043 true,
11044 true,
11045 cx,
11046 );
11047 }
11048
11049 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11050 let selections = self.selections.all::<Point>(cx);
11051 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11052 let line_mode = self.selections.line_mode;
11053 let ranges = selections.into_iter().map(|s| {
11054 if line_mode {
11055 let start = Point::new(s.start.row, 0);
11056 let end = Point::new(
11057 s.end.row,
11058 display_map
11059 .buffer_snapshot
11060 .line_len(MultiBufferRow(s.end.row)),
11061 );
11062 (start..end, display_map.fold_placeholder.clone())
11063 } else {
11064 (s.start..s.end, display_map.fold_placeholder.clone())
11065 }
11066 });
11067 self.fold_ranges(ranges, true, cx);
11068 }
11069
11070 pub fn fold_ranges<T: ToOffset + Clone>(
11071 &mut self,
11072 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11073 auto_scroll: bool,
11074 cx: &mut ViewContext<Self>,
11075 ) {
11076 let mut fold_ranges = Vec::new();
11077 let mut buffers_affected = HashMap::default();
11078 let multi_buffer = self.buffer().read(cx);
11079 for (fold_range, fold_text) in ranges {
11080 if let Some((_, buffer, _)) =
11081 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11082 {
11083 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11084 };
11085 fold_ranges.push((fold_range, fold_text));
11086 }
11087
11088 let mut ranges = fold_ranges.into_iter().peekable();
11089 if ranges.peek().is_some() {
11090 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11091
11092 if auto_scroll {
11093 self.request_autoscroll(Autoscroll::fit(), cx);
11094 }
11095
11096 for buffer in buffers_affected.into_values() {
11097 self.sync_expanded_diff_hunks(buffer, cx);
11098 }
11099
11100 cx.notify();
11101
11102 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11103 // Clear diagnostics block when folding a range that contains it.
11104 let snapshot = self.snapshot(cx);
11105 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11106 drop(snapshot);
11107 self.active_diagnostics = Some(active_diagnostics);
11108 self.dismiss_diagnostics(cx);
11109 } else {
11110 self.active_diagnostics = Some(active_diagnostics);
11111 }
11112 }
11113
11114 self.scrollbar_marker_state.dirty = true;
11115 }
11116 }
11117
11118 pub fn unfold_ranges<T: ToOffset + Clone>(
11119 &mut self,
11120 ranges: impl IntoIterator<Item = Range<T>>,
11121 inclusive: bool,
11122 auto_scroll: bool,
11123 cx: &mut ViewContext<Self>,
11124 ) {
11125 let mut unfold_ranges = Vec::new();
11126 let mut buffers_affected = HashMap::default();
11127 let multi_buffer = self.buffer().read(cx);
11128 for range in ranges {
11129 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11130 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11131 };
11132 unfold_ranges.push(range);
11133 }
11134
11135 let mut ranges = unfold_ranges.into_iter().peekable();
11136 if ranges.peek().is_some() {
11137 self.display_map
11138 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11139 if auto_scroll {
11140 self.request_autoscroll(Autoscroll::fit(), cx);
11141 }
11142
11143 for buffer in buffers_affected.into_values() {
11144 self.sync_expanded_diff_hunks(buffer, cx);
11145 }
11146
11147 cx.notify();
11148 self.scrollbar_marker_state.dirty = true;
11149 self.active_indent_guides_state.dirty = true;
11150 }
11151 }
11152
11153 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11154 self.display_map.read(cx).fold_placeholder.clone()
11155 }
11156
11157 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11158 if hovered != self.gutter_hovered {
11159 self.gutter_hovered = hovered;
11160 cx.notify();
11161 }
11162 }
11163
11164 pub fn insert_blocks(
11165 &mut self,
11166 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11167 autoscroll: Option<Autoscroll>,
11168 cx: &mut ViewContext<Self>,
11169 ) -> Vec<CustomBlockId> {
11170 let blocks = self
11171 .display_map
11172 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11173 if let Some(autoscroll) = autoscroll {
11174 self.request_autoscroll(autoscroll, cx);
11175 }
11176 cx.notify();
11177 blocks
11178 }
11179
11180 pub fn resize_blocks(
11181 &mut self,
11182 heights: HashMap<CustomBlockId, u32>,
11183 autoscroll: Option<Autoscroll>,
11184 cx: &mut ViewContext<Self>,
11185 ) {
11186 self.display_map
11187 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11188 if let Some(autoscroll) = autoscroll {
11189 self.request_autoscroll(autoscroll, cx);
11190 }
11191 cx.notify();
11192 }
11193
11194 pub fn replace_blocks(
11195 &mut self,
11196 renderers: HashMap<CustomBlockId, RenderBlock>,
11197 autoscroll: Option<Autoscroll>,
11198 cx: &mut ViewContext<Self>,
11199 ) {
11200 self.display_map
11201 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11202 if let Some(autoscroll) = autoscroll {
11203 self.request_autoscroll(autoscroll, cx);
11204 }
11205 cx.notify();
11206 }
11207
11208 pub fn remove_blocks(
11209 &mut self,
11210 block_ids: HashSet<CustomBlockId>,
11211 autoscroll: Option<Autoscroll>,
11212 cx: &mut ViewContext<Self>,
11213 ) {
11214 self.display_map.update(cx, |display_map, cx| {
11215 display_map.remove_blocks(block_ids, cx)
11216 });
11217 if let Some(autoscroll) = autoscroll {
11218 self.request_autoscroll(autoscroll, cx);
11219 }
11220 cx.notify();
11221 }
11222
11223 pub fn row_for_block(
11224 &self,
11225 block_id: CustomBlockId,
11226 cx: &mut ViewContext<Self>,
11227 ) -> Option<DisplayRow> {
11228 self.display_map
11229 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11230 }
11231
11232 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11233 self.focused_block = Some(focused_block);
11234 }
11235
11236 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11237 self.focused_block.take()
11238 }
11239
11240 pub fn insert_creases(
11241 &mut self,
11242 creases: impl IntoIterator<Item = Crease>,
11243 cx: &mut ViewContext<Self>,
11244 ) -> Vec<CreaseId> {
11245 self.display_map
11246 .update(cx, |map, cx| map.insert_creases(creases, cx))
11247 }
11248
11249 pub fn remove_creases(
11250 &mut self,
11251 ids: impl IntoIterator<Item = CreaseId>,
11252 cx: &mut ViewContext<Self>,
11253 ) {
11254 self.display_map
11255 .update(cx, |map, cx| map.remove_creases(ids, cx));
11256 }
11257
11258 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11259 self.display_map
11260 .update(cx, |map, cx| map.snapshot(cx))
11261 .longest_row()
11262 }
11263
11264 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11265 self.display_map
11266 .update(cx, |map, cx| map.snapshot(cx))
11267 .max_point()
11268 }
11269
11270 pub fn text(&self, cx: &AppContext) -> String {
11271 self.buffer.read(cx).read(cx).text()
11272 }
11273
11274 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11275 let text = self.text(cx);
11276 let text = text.trim();
11277
11278 if text.is_empty() {
11279 return None;
11280 }
11281
11282 Some(text.to_string())
11283 }
11284
11285 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11286 self.transact(cx, |this, cx| {
11287 this.buffer
11288 .read(cx)
11289 .as_singleton()
11290 .expect("you can only call set_text on editors for singleton buffers")
11291 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11292 });
11293 }
11294
11295 pub fn display_text(&self, cx: &mut AppContext) -> String {
11296 self.display_map
11297 .update(cx, |map, cx| map.snapshot(cx))
11298 .text()
11299 }
11300
11301 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11302 let mut wrap_guides = smallvec::smallvec![];
11303
11304 if self.show_wrap_guides == Some(false) {
11305 return wrap_guides;
11306 }
11307
11308 let settings = self.buffer.read(cx).settings_at(0, cx);
11309 if settings.show_wrap_guides {
11310 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11311 wrap_guides.push((soft_wrap as usize, true));
11312 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11313 wrap_guides.push((soft_wrap as usize, true));
11314 }
11315 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11316 }
11317
11318 wrap_guides
11319 }
11320
11321 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11322 let settings = self.buffer.read(cx).settings_at(0, cx);
11323 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11324 match mode {
11325 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11326 SoftWrap::None
11327 }
11328 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11329 language_settings::SoftWrap::PreferredLineLength => {
11330 SoftWrap::Column(settings.preferred_line_length)
11331 }
11332 language_settings::SoftWrap::Bounded => {
11333 SoftWrap::Bounded(settings.preferred_line_length)
11334 }
11335 }
11336 }
11337
11338 pub fn set_soft_wrap_mode(
11339 &mut self,
11340 mode: language_settings::SoftWrap,
11341 cx: &mut ViewContext<Self>,
11342 ) {
11343 self.soft_wrap_mode_override = Some(mode);
11344 cx.notify();
11345 }
11346
11347 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11348 self.text_style_refinement = Some(style);
11349 }
11350
11351 /// called by the Element so we know what style we were most recently rendered with.
11352 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11353 let rem_size = cx.rem_size();
11354 self.display_map.update(cx, |map, cx| {
11355 map.set_font(
11356 style.text.font(),
11357 style.text.font_size.to_pixels(rem_size),
11358 cx,
11359 )
11360 });
11361 self.style = Some(style);
11362 }
11363
11364 pub fn style(&self) -> Option<&EditorStyle> {
11365 self.style.as_ref()
11366 }
11367
11368 // Called by the element. This method is not designed to be called outside of the editor
11369 // element's layout code because it does not notify when rewrapping is computed synchronously.
11370 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11371 self.display_map
11372 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11373 }
11374
11375 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11376 if self.soft_wrap_mode_override.is_some() {
11377 self.soft_wrap_mode_override.take();
11378 } else {
11379 let soft_wrap = match self.soft_wrap_mode(cx) {
11380 SoftWrap::GitDiff => return,
11381 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11382 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11383 language_settings::SoftWrap::None
11384 }
11385 };
11386 self.soft_wrap_mode_override = Some(soft_wrap);
11387 }
11388 cx.notify();
11389 }
11390
11391 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11392 let Some(workspace) = self.workspace() else {
11393 return;
11394 };
11395 let fs = workspace.read(cx).app_state().fs.clone();
11396 let current_show = TabBarSettings::get_global(cx).show;
11397 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11398 setting.show = Some(!current_show);
11399 });
11400 }
11401
11402 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11403 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11404 self.buffer
11405 .read(cx)
11406 .settings_at(0, cx)
11407 .indent_guides
11408 .enabled
11409 });
11410 self.show_indent_guides = Some(!currently_enabled);
11411 cx.notify();
11412 }
11413
11414 fn should_show_indent_guides(&self) -> Option<bool> {
11415 self.show_indent_guides
11416 }
11417
11418 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11419 let mut editor_settings = EditorSettings::get_global(cx).clone();
11420 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11421 EditorSettings::override_global(editor_settings, cx);
11422 }
11423
11424 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11425 self.use_relative_line_numbers
11426 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11427 }
11428
11429 pub fn toggle_relative_line_numbers(
11430 &mut self,
11431 _: &ToggleRelativeLineNumbers,
11432 cx: &mut ViewContext<Self>,
11433 ) {
11434 let is_relative = self.should_use_relative_line_numbers(cx);
11435 self.set_relative_line_number(Some(!is_relative), cx)
11436 }
11437
11438 pub fn set_relative_line_number(
11439 &mut self,
11440 is_relative: Option<bool>,
11441 cx: &mut ViewContext<Self>,
11442 ) {
11443 self.use_relative_line_numbers = is_relative;
11444 cx.notify();
11445 }
11446
11447 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11448 self.show_gutter = show_gutter;
11449 cx.notify();
11450 }
11451
11452 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11453 self.show_line_numbers = Some(show_line_numbers);
11454 cx.notify();
11455 }
11456
11457 pub fn set_show_git_diff_gutter(
11458 &mut self,
11459 show_git_diff_gutter: bool,
11460 cx: &mut ViewContext<Self>,
11461 ) {
11462 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11463 cx.notify();
11464 }
11465
11466 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11467 self.show_code_actions = Some(show_code_actions);
11468 cx.notify();
11469 }
11470
11471 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11472 self.show_runnables = Some(show_runnables);
11473 cx.notify();
11474 }
11475
11476 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11477 if self.display_map.read(cx).masked != masked {
11478 self.display_map.update(cx, |map, _| map.masked = masked);
11479 }
11480 cx.notify()
11481 }
11482
11483 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11484 self.show_wrap_guides = Some(show_wrap_guides);
11485 cx.notify();
11486 }
11487
11488 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11489 self.show_indent_guides = Some(show_indent_guides);
11490 cx.notify();
11491 }
11492
11493 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11494 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11495 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11496 if let Some(dir) = file.abs_path(cx).parent() {
11497 return Some(dir.to_owned());
11498 }
11499 }
11500
11501 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11502 return Some(project_path.path.to_path_buf());
11503 }
11504 }
11505
11506 None
11507 }
11508
11509 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11510 self.active_excerpt(cx)?
11511 .1
11512 .read(cx)
11513 .file()
11514 .and_then(|f| f.as_local())
11515 }
11516
11517 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11518 if let Some(target) = self.target_file(cx) {
11519 cx.reveal_path(&target.abs_path(cx));
11520 }
11521 }
11522
11523 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11524 if let Some(file) = self.target_file(cx) {
11525 if let Some(path) = file.abs_path(cx).to_str() {
11526 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11527 }
11528 }
11529 }
11530
11531 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11532 if let Some(file) = self.target_file(cx) {
11533 if let Some(path) = file.path().to_str() {
11534 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11535 }
11536 }
11537 }
11538
11539 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11540 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11541
11542 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11543 self.start_git_blame(true, cx);
11544 }
11545
11546 cx.notify();
11547 }
11548
11549 pub fn toggle_git_blame_inline(
11550 &mut self,
11551 _: &ToggleGitBlameInline,
11552 cx: &mut ViewContext<Self>,
11553 ) {
11554 self.toggle_git_blame_inline_internal(true, cx);
11555 cx.notify();
11556 }
11557
11558 pub fn git_blame_inline_enabled(&self) -> bool {
11559 self.git_blame_inline_enabled
11560 }
11561
11562 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11563 self.show_selection_menu = self
11564 .show_selection_menu
11565 .map(|show_selections_menu| !show_selections_menu)
11566 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11567
11568 cx.notify();
11569 }
11570
11571 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11572 self.show_selection_menu
11573 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11574 }
11575
11576 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11577 if let Some(project) = self.project.as_ref() {
11578 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11579 return;
11580 };
11581
11582 if buffer.read(cx).file().is_none() {
11583 return;
11584 }
11585
11586 let focused = self.focus_handle(cx).contains_focused(cx);
11587
11588 let project = project.clone();
11589 let blame =
11590 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11591 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11592 self.blame = Some(blame);
11593 }
11594 }
11595
11596 fn toggle_git_blame_inline_internal(
11597 &mut self,
11598 user_triggered: bool,
11599 cx: &mut ViewContext<Self>,
11600 ) {
11601 if self.git_blame_inline_enabled {
11602 self.git_blame_inline_enabled = false;
11603 self.show_git_blame_inline = false;
11604 self.show_git_blame_inline_delay_task.take();
11605 } else {
11606 self.git_blame_inline_enabled = true;
11607 self.start_git_blame_inline(user_triggered, cx);
11608 }
11609
11610 cx.notify();
11611 }
11612
11613 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11614 self.start_git_blame(user_triggered, cx);
11615
11616 if ProjectSettings::get_global(cx)
11617 .git
11618 .inline_blame_delay()
11619 .is_some()
11620 {
11621 self.start_inline_blame_timer(cx);
11622 } else {
11623 self.show_git_blame_inline = true
11624 }
11625 }
11626
11627 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11628 self.blame.as_ref()
11629 }
11630
11631 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11632 self.show_git_blame_gutter && self.has_blame_entries(cx)
11633 }
11634
11635 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11636 self.show_git_blame_inline
11637 && self.focus_handle.is_focused(cx)
11638 && !self.newest_selection_head_on_empty_line(cx)
11639 && self.has_blame_entries(cx)
11640 }
11641
11642 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11643 self.blame()
11644 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11645 }
11646
11647 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11648 let cursor_anchor = self.selections.newest_anchor().head();
11649
11650 let snapshot = self.buffer.read(cx).snapshot(cx);
11651 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11652
11653 snapshot.line_len(buffer_row) == 0
11654 }
11655
11656 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11657 let buffer_and_selection = maybe!({
11658 let selection = self.selections.newest::<Point>(cx);
11659 let selection_range = selection.range();
11660
11661 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11662 (buffer, selection_range.start.row..selection_range.end.row)
11663 } else {
11664 let buffer_ranges = self
11665 .buffer()
11666 .read(cx)
11667 .range_to_buffer_ranges(selection_range, cx);
11668
11669 let (buffer, range, _) = if selection.reversed {
11670 buffer_ranges.first()
11671 } else {
11672 buffer_ranges.last()
11673 }?;
11674
11675 let snapshot = buffer.read(cx).snapshot();
11676 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11677 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11678 (buffer.clone(), selection)
11679 };
11680
11681 Some((buffer, selection))
11682 });
11683
11684 let Some((buffer, selection)) = buffer_and_selection else {
11685 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11686 };
11687
11688 let Some(project) = self.project.as_ref() else {
11689 return Task::ready(Err(anyhow!("editor does not have project")));
11690 };
11691
11692 project.update(cx, |project, cx| {
11693 project.get_permalink_to_line(&buffer, selection, cx)
11694 })
11695 }
11696
11697 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11698 let permalink_task = self.get_permalink_to_line(cx);
11699 let workspace = self.workspace();
11700
11701 cx.spawn(|_, mut cx| async move {
11702 match permalink_task.await {
11703 Ok(permalink) => {
11704 cx.update(|cx| {
11705 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11706 })
11707 .ok();
11708 }
11709 Err(err) => {
11710 let message = format!("Failed to copy permalink: {err}");
11711
11712 Err::<(), anyhow::Error>(err).log_err();
11713
11714 if let Some(workspace) = workspace {
11715 workspace
11716 .update(&mut cx, |workspace, cx| {
11717 struct CopyPermalinkToLine;
11718
11719 workspace.show_toast(
11720 Toast::new(
11721 NotificationId::unique::<CopyPermalinkToLine>(),
11722 message,
11723 ),
11724 cx,
11725 )
11726 })
11727 .ok();
11728 }
11729 }
11730 }
11731 })
11732 .detach();
11733 }
11734
11735 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11736 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11737 if let Some(file) = self.target_file(cx) {
11738 if let Some(path) = file.path().to_str() {
11739 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11740 }
11741 }
11742 }
11743
11744 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11745 let permalink_task = self.get_permalink_to_line(cx);
11746 let workspace = self.workspace();
11747
11748 cx.spawn(|_, mut cx| async move {
11749 match permalink_task.await {
11750 Ok(permalink) => {
11751 cx.update(|cx| {
11752 cx.open_url(permalink.as_ref());
11753 })
11754 .ok();
11755 }
11756 Err(err) => {
11757 let message = format!("Failed to open permalink: {err}");
11758
11759 Err::<(), anyhow::Error>(err).log_err();
11760
11761 if let Some(workspace) = workspace {
11762 workspace
11763 .update(&mut cx, |workspace, cx| {
11764 struct OpenPermalinkToLine;
11765
11766 workspace.show_toast(
11767 Toast::new(
11768 NotificationId::unique::<OpenPermalinkToLine>(),
11769 message,
11770 ),
11771 cx,
11772 )
11773 })
11774 .ok();
11775 }
11776 }
11777 }
11778 })
11779 .detach();
11780 }
11781
11782 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11783 /// last highlight added will be used.
11784 ///
11785 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11786 pub fn highlight_rows<T: 'static>(
11787 &mut self,
11788 range: Range<Anchor>,
11789 color: Hsla,
11790 should_autoscroll: bool,
11791 cx: &mut ViewContext<Self>,
11792 ) {
11793 let snapshot = self.buffer().read(cx).snapshot(cx);
11794 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11795 let ix = row_highlights.binary_search_by(|highlight| {
11796 Ordering::Equal
11797 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11798 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11799 });
11800
11801 if let Err(mut ix) = ix {
11802 let index = post_inc(&mut self.highlight_order);
11803
11804 // If this range intersects with the preceding highlight, then merge it with
11805 // the preceding highlight. Otherwise insert a new highlight.
11806 let mut merged = false;
11807 if ix > 0 {
11808 let prev_highlight = &mut row_highlights[ix - 1];
11809 if prev_highlight
11810 .range
11811 .end
11812 .cmp(&range.start, &snapshot)
11813 .is_ge()
11814 {
11815 ix -= 1;
11816 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11817 prev_highlight.range.end = range.end;
11818 }
11819 merged = true;
11820 prev_highlight.index = index;
11821 prev_highlight.color = color;
11822 prev_highlight.should_autoscroll = should_autoscroll;
11823 }
11824 }
11825
11826 if !merged {
11827 row_highlights.insert(
11828 ix,
11829 RowHighlight {
11830 range: range.clone(),
11831 index,
11832 color,
11833 should_autoscroll,
11834 },
11835 );
11836 }
11837
11838 // If any of the following highlights intersect with this one, merge them.
11839 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11840 let highlight = &row_highlights[ix];
11841 if next_highlight
11842 .range
11843 .start
11844 .cmp(&highlight.range.end, &snapshot)
11845 .is_le()
11846 {
11847 if next_highlight
11848 .range
11849 .end
11850 .cmp(&highlight.range.end, &snapshot)
11851 .is_gt()
11852 {
11853 row_highlights[ix].range.end = next_highlight.range.end;
11854 }
11855 row_highlights.remove(ix + 1);
11856 } else {
11857 break;
11858 }
11859 }
11860 }
11861 }
11862
11863 /// Remove any highlighted row ranges of the given type that intersect the
11864 /// given ranges.
11865 pub fn remove_highlighted_rows<T: 'static>(
11866 &mut self,
11867 ranges_to_remove: Vec<Range<Anchor>>,
11868 cx: &mut ViewContext<Self>,
11869 ) {
11870 let snapshot = self.buffer().read(cx).snapshot(cx);
11871 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11872 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11873 row_highlights.retain(|highlight| {
11874 while let Some(range_to_remove) = ranges_to_remove.peek() {
11875 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11876 Ordering::Less | Ordering::Equal => {
11877 ranges_to_remove.next();
11878 }
11879 Ordering::Greater => {
11880 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11881 Ordering::Less | Ordering::Equal => {
11882 return false;
11883 }
11884 Ordering::Greater => break,
11885 }
11886 }
11887 }
11888 }
11889
11890 true
11891 })
11892 }
11893
11894 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11895 pub fn clear_row_highlights<T: 'static>(&mut self) {
11896 self.highlighted_rows.remove(&TypeId::of::<T>());
11897 }
11898
11899 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11900 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11901 self.highlighted_rows
11902 .get(&TypeId::of::<T>())
11903 .map_or(&[] as &[_], |vec| vec.as_slice())
11904 .iter()
11905 .map(|highlight| (highlight.range.clone(), highlight.color))
11906 }
11907
11908 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11909 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11910 /// Allows to ignore certain kinds of highlights.
11911 pub fn highlighted_display_rows(
11912 &mut self,
11913 cx: &mut WindowContext,
11914 ) -> BTreeMap<DisplayRow, Hsla> {
11915 let snapshot = self.snapshot(cx);
11916 let mut used_highlight_orders = HashMap::default();
11917 self.highlighted_rows
11918 .iter()
11919 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11920 .fold(
11921 BTreeMap::<DisplayRow, Hsla>::new(),
11922 |mut unique_rows, highlight| {
11923 let start = highlight.range.start.to_display_point(&snapshot);
11924 let end = highlight.range.end.to_display_point(&snapshot);
11925 let start_row = start.row().0;
11926 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11927 && end.column() == 0
11928 {
11929 end.row().0.saturating_sub(1)
11930 } else {
11931 end.row().0
11932 };
11933 for row in start_row..=end_row {
11934 let used_index =
11935 used_highlight_orders.entry(row).or_insert(highlight.index);
11936 if highlight.index >= *used_index {
11937 *used_index = highlight.index;
11938 unique_rows.insert(DisplayRow(row), highlight.color);
11939 }
11940 }
11941 unique_rows
11942 },
11943 )
11944 }
11945
11946 pub fn highlighted_display_row_for_autoscroll(
11947 &self,
11948 snapshot: &DisplaySnapshot,
11949 ) -> Option<DisplayRow> {
11950 self.highlighted_rows
11951 .values()
11952 .flat_map(|highlighted_rows| highlighted_rows.iter())
11953 .filter_map(|highlight| {
11954 if highlight.should_autoscroll {
11955 Some(highlight.range.start.to_display_point(snapshot).row())
11956 } else {
11957 None
11958 }
11959 })
11960 .min()
11961 }
11962
11963 pub fn set_search_within_ranges(
11964 &mut self,
11965 ranges: &[Range<Anchor>],
11966 cx: &mut ViewContext<Self>,
11967 ) {
11968 self.highlight_background::<SearchWithinRange>(
11969 ranges,
11970 |colors| colors.editor_document_highlight_read_background,
11971 cx,
11972 )
11973 }
11974
11975 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11976 self.breadcrumb_header = Some(new_header);
11977 }
11978
11979 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11980 self.clear_background_highlights::<SearchWithinRange>(cx);
11981 }
11982
11983 pub fn highlight_background<T: 'static>(
11984 &mut self,
11985 ranges: &[Range<Anchor>],
11986 color_fetcher: fn(&ThemeColors) -> Hsla,
11987 cx: &mut ViewContext<Self>,
11988 ) {
11989 self.background_highlights
11990 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11991 self.scrollbar_marker_state.dirty = true;
11992 cx.notify();
11993 }
11994
11995 pub fn clear_background_highlights<T: 'static>(
11996 &mut self,
11997 cx: &mut ViewContext<Self>,
11998 ) -> Option<BackgroundHighlight> {
11999 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12000 if !text_highlights.1.is_empty() {
12001 self.scrollbar_marker_state.dirty = true;
12002 cx.notify();
12003 }
12004 Some(text_highlights)
12005 }
12006
12007 pub fn highlight_gutter<T: 'static>(
12008 &mut self,
12009 ranges: &[Range<Anchor>],
12010 color_fetcher: fn(&AppContext) -> Hsla,
12011 cx: &mut ViewContext<Self>,
12012 ) {
12013 self.gutter_highlights
12014 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12015 cx.notify();
12016 }
12017
12018 pub fn clear_gutter_highlights<T: 'static>(
12019 &mut self,
12020 cx: &mut ViewContext<Self>,
12021 ) -> Option<GutterHighlight> {
12022 cx.notify();
12023 self.gutter_highlights.remove(&TypeId::of::<T>())
12024 }
12025
12026 #[cfg(feature = "test-support")]
12027 pub fn all_text_background_highlights(
12028 &mut self,
12029 cx: &mut ViewContext<Self>,
12030 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12031 let snapshot = self.snapshot(cx);
12032 let buffer = &snapshot.buffer_snapshot;
12033 let start = buffer.anchor_before(0);
12034 let end = buffer.anchor_after(buffer.len());
12035 let theme = cx.theme().colors();
12036 self.background_highlights_in_range(start..end, &snapshot, theme)
12037 }
12038
12039 #[cfg(feature = "test-support")]
12040 pub fn search_background_highlights(
12041 &mut self,
12042 cx: &mut ViewContext<Self>,
12043 ) -> Vec<Range<Point>> {
12044 let snapshot = self.buffer().read(cx).snapshot(cx);
12045
12046 let highlights = self
12047 .background_highlights
12048 .get(&TypeId::of::<items::BufferSearchHighlights>());
12049
12050 if let Some((_color, ranges)) = highlights {
12051 ranges
12052 .iter()
12053 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12054 .collect_vec()
12055 } else {
12056 vec![]
12057 }
12058 }
12059
12060 fn document_highlights_for_position<'a>(
12061 &'a self,
12062 position: Anchor,
12063 buffer: &'a MultiBufferSnapshot,
12064 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12065 let read_highlights = self
12066 .background_highlights
12067 .get(&TypeId::of::<DocumentHighlightRead>())
12068 .map(|h| &h.1);
12069 let write_highlights = self
12070 .background_highlights
12071 .get(&TypeId::of::<DocumentHighlightWrite>())
12072 .map(|h| &h.1);
12073 let left_position = position.bias_left(buffer);
12074 let right_position = position.bias_right(buffer);
12075 read_highlights
12076 .into_iter()
12077 .chain(write_highlights)
12078 .flat_map(move |ranges| {
12079 let start_ix = match ranges.binary_search_by(|probe| {
12080 let cmp = probe.end.cmp(&left_position, buffer);
12081 if cmp.is_ge() {
12082 Ordering::Greater
12083 } else {
12084 Ordering::Less
12085 }
12086 }) {
12087 Ok(i) | Err(i) => i,
12088 };
12089
12090 ranges[start_ix..]
12091 .iter()
12092 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12093 })
12094 }
12095
12096 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12097 self.background_highlights
12098 .get(&TypeId::of::<T>())
12099 .map_or(false, |(_, highlights)| !highlights.is_empty())
12100 }
12101
12102 pub fn background_highlights_in_range(
12103 &self,
12104 search_range: Range<Anchor>,
12105 display_snapshot: &DisplaySnapshot,
12106 theme: &ThemeColors,
12107 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12108 let mut results = Vec::new();
12109 for (color_fetcher, ranges) in self.background_highlights.values() {
12110 let color = color_fetcher(theme);
12111 let start_ix = match ranges.binary_search_by(|probe| {
12112 let cmp = probe
12113 .end
12114 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12115 if cmp.is_gt() {
12116 Ordering::Greater
12117 } else {
12118 Ordering::Less
12119 }
12120 }) {
12121 Ok(i) | Err(i) => i,
12122 };
12123 for range in &ranges[start_ix..] {
12124 if range
12125 .start
12126 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12127 .is_ge()
12128 {
12129 break;
12130 }
12131
12132 let start = range.start.to_display_point(display_snapshot);
12133 let end = range.end.to_display_point(display_snapshot);
12134 results.push((start..end, color))
12135 }
12136 }
12137 results
12138 }
12139
12140 pub fn background_highlight_row_ranges<T: 'static>(
12141 &self,
12142 search_range: Range<Anchor>,
12143 display_snapshot: &DisplaySnapshot,
12144 count: usize,
12145 ) -> Vec<RangeInclusive<DisplayPoint>> {
12146 let mut results = Vec::new();
12147 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12148 return vec![];
12149 };
12150
12151 let start_ix = match ranges.binary_search_by(|probe| {
12152 let cmp = probe
12153 .end
12154 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12155 if cmp.is_gt() {
12156 Ordering::Greater
12157 } else {
12158 Ordering::Less
12159 }
12160 }) {
12161 Ok(i) | Err(i) => i,
12162 };
12163 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12164 if let (Some(start_display), Some(end_display)) = (start, end) {
12165 results.push(
12166 start_display.to_display_point(display_snapshot)
12167 ..=end_display.to_display_point(display_snapshot),
12168 );
12169 }
12170 };
12171 let mut start_row: Option<Point> = None;
12172 let mut end_row: Option<Point> = None;
12173 if ranges.len() > count {
12174 return Vec::new();
12175 }
12176 for range in &ranges[start_ix..] {
12177 if range
12178 .start
12179 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12180 .is_ge()
12181 {
12182 break;
12183 }
12184 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12185 if let Some(current_row) = &end_row {
12186 if end.row == current_row.row {
12187 continue;
12188 }
12189 }
12190 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12191 if start_row.is_none() {
12192 assert_eq!(end_row, None);
12193 start_row = Some(start);
12194 end_row = Some(end);
12195 continue;
12196 }
12197 if let Some(current_end) = end_row.as_mut() {
12198 if start.row > current_end.row + 1 {
12199 push_region(start_row, end_row);
12200 start_row = Some(start);
12201 end_row = Some(end);
12202 } else {
12203 // Merge two hunks.
12204 *current_end = end;
12205 }
12206 } else {
12207 unreachable!();
12208 }
12209 }
12210 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12211 push_region(start_row, end_row);
12212 results
12213 }
12214
12215 pub fn gutter_highlights_in_range(
12216 &self,
12217 search_range: Range<Anchor>,
12218 display_snapshot: &DisplaySnapshot,
12219 cx: &AppContext,
12220 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12221 let mut results = Vec::new();
12222 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12223 let color = color_fetcher(cx);
12224 let start_ix = match ranges.binary_search_by(|probe| {
12225 let cmp = probe
12226 .end
12227 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12228 if cmp.is_gt() {
12229 Ordering::Greater
12230 } else {
12231 Ordering::Less
12232 }
12233 }) {
12234 Ok(i) | Err(i) => i,
12235 };
12236 for range in &ranges[start_ix..] {
12237 if range
12238 .start
12239 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12240 .is_ge()
12241 {
12242 break;
12243 }
12244
12245 let start = range.start.to_display_point(display_snapshot);
12246 let end = range.end.to_display_point(display_snapshot);
12247 results.push((start..end, color))
12248 }
12249 }
12250 results
12251 }
12252
12253 /// Get the text ranges corresponding to the redaction query
12254 pub fn redacted_ranges(
12255 &self,
12256 search_range: Range<Anchor>,
12257 display_snapshot: &DisplaySnapshot,
12258 cx: &WindowContext,
12259 ) -> Vec<Range<DisplayPoint>> {
12260 display_snapshot
12261 .buffer_snapshot
12262 .redacted_ranges(search_range, |file| {
12263 if let Some(file) = file {
12264 file.is_private()
12265 && EditorSettings::get(
12266 Some(SettingsLocation {
12267 worktree_id: file.worktree_id(cx),
12268 path: file.path().as_ref(),
12269 }),
12270 cx,
12271 )
12272 .redact_private_values
12273 } else {
12274 false
12275 }
12276 })
12277 .map(|range| {
12278 range.start.to_display_point(display_snapshot)
12279 ..range.end.to_display_point(display_snapshot)
12280 })
12281 .collect()
12282 }
12283
12284 pub fn highlight_text<T: 'static>(
12285 &mut self,
12286 ranges: Vec<Range<Anchor>>,
12287 style: HighlightStyle,
12288 cx: &mut ViewContext<Self>,
12289 ) {
12290 self.display_map.update(cx, |map, _| {
12291 map.highlight_text(TypeId::of::<T>(), ranges, style)
12292 });
12293 cx.notify();
12294 }
12295
12296 pub(crate) fn highlight_inlays<T: 'static>(
12297 &mut self,
12298 highlights: Vec<InlayHighlight>,
12299 style: HighlightStyle,
12300 cx: &mut ViewContext<Self>,
12301 ) {
12302 self.display_map.update(cx, |map, _| {
12303 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12304 });
12305 cx.notify();
12306 }
12307
12308 pub fn text_highlights<'a, T: 'static>(
12309 &'a self,
12310 cx: &'a AppContext,
12311 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12312 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12313 }
12314
12315 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12316 let cleared = self
12317 .display_map
12318 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12319 if cleared {
12320 cx.notify();
12321 }
12322 }
12323
12324 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12325 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12326 && self.focus_handle.is_focused(cx)
12327 }
12328
12329 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12330 self.show_cursor_when_unfocused = is_enabled;
12331 cx.notify();
12332 }
12333
12334 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12335 cx.notify();
12336 }
12337
12338 fn on_buffer_event(
12339 &mut self,
12340 multibuffer: Model<MultiBuffer>,
12341 event: &multi_buffer::Event,
12342 cx: &mut ViewContext<Self>,
12343 ) {
12344 match event {
12345 multi_buffer::Event::Edited {
12346 singleton_buffer_edited,
12347 } => {
12348 self.scrollbar_marker_state.dirty = true;
12349 self.active_indent_guides_state.dirty = true;
12350 self.refresh_active_diagnostics(cx);
12351 self.refresh_code_actions(cx);
12352 if self.has_active_inline_completion(cx) {
12353 self.update_visible_inline_completion(cx);
12354 }
12355 cx.emit(EditorEvent::BufferEdited);
12356 cx.emit(SearchEvent::MatchesInvalidated);
12357 if *singleton_buffer_edited {
12358 if let Some(project) = &self.project {
12359 let project = project.read(cx);
12360 #[allow(clippy::mutable_key_type)]
12361 let languages_affected = multibuffer
12362 .read(cx)
12363 .all_buffers()
12364 .into_iter()
12365 .filter_map(|buffer| {
12366 let buffer = buffer.read(cx);
12367 let language = buffer.language()?;
12368 if project.is_local()
12369 && project.language_servers_for_buffer(buffer, cx).count() == 0
12370 {
12371 None
12372 } else {
12373 Some(language)
12374 }
12375 })
12376 .cloned()
12377 .collect::<HashSet<_>>();
12378 if !languages_affected.is_empty() {
12379 self.refresh_inlay_hints(
12380 InlayHintRefreshReason::BufferEdited(languages_affected),
12381 cx,
12382 );
12383 }
12384 }
12385 }
12386
12387 let Some(project) = &self.project else { return };
12388 let (telemetry, is_via_ssh) = {
12389 let project = project.read(cx);
12390 let telemetry = project.client().telemetry().clone();
12391 let is_via_ssh = project.is_via_ssh();
12392 (telemetry, is_via_ssh)
12393 };
12394 refresh_linked_ranges(self, cx);
12395 telemetry.log_edit_event("editor", is_via_ssh);
12396 }
12397 multi_buffer::Event::ExcerptsAdded {
12398 buffer,
12399 predecessor,
12400 excerpts,
12401 } => {
12402 self.tasks_update_task = Some(self.refresh_runnables(cx));
12403 cx.emit(EditorEvent::ExcerptsAdded {
12404 buffer: buffer.clone(),
12405 predecessor: *predecessor,
12406 excerpts: excerpts.clone(),
12407 });
12408 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12409 }
12410 multi_buffer::Event::ExcerptsRemoved { ids } => {
12411 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12412 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12413 }
12414 multi_buffer::Event::ExcerptsEdited { ids } => {
12415 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12416 }
12417 multi_buffer::Event::ExcerptsExpanded { ids } => {
12418 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12419 }
12420 multi_buffer::Event::Reparsed(buffer_id) => {
12421 self.tasks_update_task = Some(self.refresh_runnables(cx));
12422
12423 cx.emit(EditorEvent::Reparsed(*buffer_id));
12424 }
12425 multi_buffer::Event::LanguageChanged(buffer_id) => {
12426 linked_editing_ranges::refresh_linked_ranges(self, cx);
12427 cx.emit(EditorEvent::Reparsed(*buffer_id));
12428 cx.notify();
12429 }
12430 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12431 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12432 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12433 cx.emit(EditorEvent::TitleChanged)
12434 }
12435 multi_buffer::Event::DiffBaseChanged => {
12436 self.scrollbar_marker_state.dirty = true;
12437 cx.emit(EditorEvent::DiffBaseChanged);
12438 cx.notify();
12439 }
12440 multi_buffer::Event::DiffUpdated { buffer } => {
12441 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12442 cx.notify();
12443 }
12444 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12445 multi_buffer::Event::DiagnosticsUpdated => {
12446 self.refresh_active_diagnostics(cx);
12447 self.scrollbar_marker_state.dirty = true;
12448 cx.notify();
12449 }
12450 _ => {}
12451 };
12452 }
12453
12454 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12455 cx.notify();
12456 }
12457
12458 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12459 self.tasks_update_task = Some(self.refresh_runnables(cx));
12460 self.refresh_inline_completion(true, false, cx);
12461 self.refresh_inlay_hints(
12462 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12463 self.selections.newest_anchor().head(),
12464 &self.buffer.read(cx).snapshot(cx),
12465 cx,
12466 )),
12467 cx,
12468 );
12469
12470 let old_cursor_shape = self.cursor_shape;
12471
12472 {
12473 let editor_settings = EditorSettings::get_global(cx);
12474 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12475 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12476 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12477 }
12478
12479 if old_cursor_shape != self.cursor_shape {
12480 cx.emit(EditorEvent::CursorShapeChanged);
12481 }
12482
12483 let project_settings = ProjectSettings::get_global(cx);
12484 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12485
12486 if self.mode == EditorMode::Full {
12487 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12488 if self.git_blame_inline_enabled != inline_blame_enabled {
12489 self.toggle_git_blame_inline_internal(false, cx);
12490 }
12491 }
12492
12493 cx.notify();
12494 }
12495
12496 pub fn set_searchable(&mut self, searchable: bool) {
12497 self.searchable = searchable;
12498 }
12499
12500 pub fn searchable(&self) -> bool {
12501 self.searchable
12502 }
12503
12504 fn open_proposed_changes_editor(
12505 &mut self,
12506 _: &OpenProposedChangesEditor,
12507 cx: &mut ViewContext<Self>,
12508 ) {
12509 let Some(workspace) = self.workspace() else {
12510 cx.propagate();
12511 return;
12512 };
12513
12514 let selections = self.selections.all::<usize>(cx);
12515 let buffer = self.buffer.read(cx);
12516 let mut new_selections_by_buffer = HashMap::default();
12517 for selection in selections {
12518 for (buffer, range, _) in
12519 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12520 {
12521 let mut range = range.to_point(buffer.read(cx));
12522 range.start.column = 0;
12523 range.end.column = buffer.read(cx).line_len(range.end.row);
12524 new_selections_by_buffer
12525 .entry(buffer)
12526 .or_insert(Vec::new())
12527 .push(range)
12528 }
12529 }
12530
12531 let proposed_changes_buffers = new_selections_by_buffer
12532 .into_iter()
12533 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12534 .collect::<Vec<_>>();
12535 let proposed_changes_editor = cx.new_view(|cx| {
12536 ProposedChangesEditor::new(
12537 "Proposed changes",
12538 proposed_changes_buffers,
12539 self.project.clone(),
12540 cx,
12541 )
12542 });
12543
12544 cx.window_context().defer(move |cx| {
12545 workspace.update(cx, |workspace, cx| {
12546 workspace.active_pane().update(cx, |pane, cx| {
12547 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12548 });
12549 });
12550 });
12551 }
12552
12553 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12554 self.open_excerpts_common(true, cx)
12555 }
12556
12557 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12558 self.open_excerpts_common(false, cx)
12559 }
12560
12561 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12562 let selections = self.selections.all::<usize>(cx);
12563 let buffer = self.buffer.read(cx);
12564 if buffer.is_singleton() {
12565 cx.propagate();
12566 return;
12567 }
12568
12569 let Some(workspace) = self.workspace() else {
12570 cx.propagate();
12571 return;
12572 };
12573
12574 let mut new_selections_by_buffer = HashMap::default();
12575 for selection in selections {
12576 for (mut buffer_handle, mut range, _) in
12577 buffer.range_to_buffer_ranges(selection.range(), cx)
12578 {
12579 // When editing branch buffers, jump to the corresponding location
12580 // in their base buffer.
12581 let buffer = buffer_handle.read(cx);
12582 if let Some(base_buffer) = buffer.diff_base_buffer() {
12583 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12584 buffer_handle = base_buffer;
12585 }
12586
12587 if selection.reversed {
12588 mem::swap(&mut range.start, &mut range.end);
12589 }
12590 new_selections_by_buffer
12591 .entry(buffer_handle)
12592 .or_insert(Vec::new())
12593 .push(range)
12594 }
12595 }
12596
12597 // We defer the pane interaction because we ourselves are a workspace item
12598 // and activating a new item causes the pane to call a method on us reentrantly,
12599 // which panics if we're on the stack.
12600 cx.window_context().defer(move |cx| {
12601 workspace.update(cx, |workspace, cx| {
12602 let pane = if split {
12603 workspace.adjacent_pane(cx)
12604 } else {
12605 workspace.active_pane().clone()
12606 };
12607
12608 for (buffer, ranges) in new_selections_by_buffer {
12609 let editor =
12610 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12611 editor.update(cx, |editor, cx| {
12612 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12613 s.select_ranges(ranges);
12614 });
12615 });
12616 }
12617 })
12618 });
12619 }
12620
12621 fn jump(
12622 &mut self,
12623 path: ProjectPath,
12624 position: Point,
12625 anchor: language::Anchor,
12626 offset_from_top: u32,
12627 cx: &mut ViewContext<Self>,
12628 ) {
12629 let workspace = self.workspace();
12630 cx.spawn(|_, mut cx| async move {
12631 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12632 let editor = workspace.update(&mut cx, |workspace, cx| {
12633 // Reset the preview item id before opening the new item
12634 workspace.active_pane().update(cx, |pane, cx| {
12635 pane.set_preview_item_id(None, cx);
12636 });
12637 workspace.open_path_preview(path, None, true, true, cx)
12638 })?;
12639 let editor = editor
12640 .await?
12641 .downcast::<Editor>()
12642 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12643 .downgrade();
12644 editor.update(&mut cx, |editor, cx| {
12645 let buffer = editor
12646 .buffer()
12647 .read(cx)
12648 .as_singleton()
12649 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12650 let buffer = buffer.read(cx);
12651 let cursor = if buffer.can_resolve(&anchor) {
12652 language::ToPoint::to_point(&anchor, buffer)
12653 } else {
12654 buffer.clip_point(position, Bias::Left)
12655 };
12656
12657 let nav_history = editor.nav_history.take();
12658 editor.change_selections(
12659 Some(Autoscroll::top_relative(offset_from_top as usize)),
12660 cx,
12661 |s| {
12662 s.select_ranges([cursor..cursor]);
12663 },
12664 );
12665 editor.nav_history = nav_history;
12666
12667 anyhow::Ok(())
12668 })??;
12669
12670 anyhow::Ok(())
12671 })
12672 .detach_and_log_err(cx);
12673 }
12674
12675 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12676 let snapshot = self.buffer.read(cx).read(cx);
12677 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12678 Some(
12679 ranges
12680 .iter()
12681 .map(move |range| {
12682 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12683 })
12684 .collect(),
12685 )
12686 }
12687
12688 fn selection_replacement_ranges(
12689 &self,
12690 range: Range<OffsetUtf16>,
12691 cx: &mut AppContext,
12692 ) -> Vec<Range<OffsetUtf16>> {
12693 let selections = self.selections.all::<OffsetUtf16>(cx);
12694 let newest_selection = selections
12695 .iter()
12696 .max_by_key(|selection| selection.id)
12697 .unwrap();
12698 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12699 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12700 let snapshot = self.buffer.read(cx).read(cx);
12701 selections
12702 .into_iter()
12703 .map(|mut selection| {
12704 selection.start.0 =
12705 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12706 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12707 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12708 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12709 })
12710 .collect()
12711 }
12712
12713 fn report_editor_event(
12714 &self,
12715 operation: &'static str,
12716 file_extension: Option<String>,
12717 cx: &AppContext,
12718 ) {
12719 if cfg!(any(test, feature = "test-support")) {
12720 return;
12721 }
12722
12723 let Some(project) = &self.project else { return };
12724
12725 // If None, we are in a file without an extension
12726 let file = self
12727 .buffer
12728 .read(cx)
12729 .as_singleton()
12730 .and_then(|b| b.read(cx).file());
12731 let file_extension = file_extension.or(file
12732 .as_ref()
12733 .and_then(|file| Path::new(file.file_name(cx)).extension())
12734 .and_then(|e| e.to_str())
12735 .map(|a| a.to_string()));
12736
12737 let vim_mode = cx
12738 .global::<SettingsStore>()
12739 .raw_user_settings()
12740 .get("vim_mode")
12741 == Some(&serde_json::Value::Bool(true));
12742
12743 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12744 == language::language_settings::InlineCompletionProvider::Copilot;
12745 let copilot_enabled_for_language = self
12746 .buffer
12747 .read(cx)
12748 .settings_at(0, cx)
12749 .show_inline_completions;
12750
12751 let project = project.read(cx);
12752 let telemetry = project.client().telemetry().clone();
12753 telemetry.report_editor_event(
12754 file_extension,
12755 vim_mode,
12756 operation,
12757 copilot_enabled,
12758 copilot_enabled_for_language,
12759 project.is_via_ssh(),
12760 )
12761 }
12762
12763 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12764 /// with each line being an array of {text, highlight} objects.
12765 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12766 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12767 return;
12768 };
12769
12770 #[derive(Serialize)]
12771 struct Chunk<'a> {
12772 text: String,
12773 highlight: Option<&'a str>,
12774 }
12775
12776 let snapshot = buffer.read(cx).snapshot();
12777 let range = self
12778 .selected_text_range(false, cx)
12779 .and_then(|selection| {
12780 if selection.range.is_empty() {
12781 None
12782 } else {
12783 Some(selection.range)
12784 }
12785 })
12786 .unwrap_or_else(|| 0..snapshot.len());
12787
12788 let chunks = snapshot.chunks(range, true);
12789 let mut lines = Vec::new();
12790 let mut line: VecDeque<Chunk> = VecDeque::new();
12791
12792 let Some(style) = self.style.as_ref() else {
12793 return;
12794 };
12795
12796 for chunk in chunks {
12797 let highlight = chunk
12798 .syntax_highlight_id
12799 .and_then(|id| id.name(&style.syntax));
12800 let mut chunk_lines = chunk.text.split('\n').peekable();
12801 while let Some(text) = chunk_lines.next() {
12802 let mut merged_with_last_token = false;
12803 if let Some(last_token) = line.back_mut() {
12804 if last_token.highlight == highlight {
12805 last_token.text.push_str(text);
12806 merged_with_last_token = true;
12807 }
12808 }
12809
12810 if !merged_with_last_token {
12811 line.push_back(Chunk {
12812 text: text.into(),
12813 highlight,
12814 });
12815 }
12816
12817 if chunk_lines.peek().is_some() {
12818 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12819 line.pop_front();
12820 }
12821 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12822 line.pop_back();
12823 }
12824
12825 lines.push(mem::take(&mut line));
12826 }
12827 }
12828 }
12829
12830 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12831 return;
12832 };
12833 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12834 }
12835
12836 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12837 &self.inlay_hint_cache
12838 }
12839
12840 pub fn replay_insert_event(
12841 &mut self,
12842 text: &str,
12843 relative_utf16_range: Option<Range<isize>>,
12844 cx: &mut ViewContext<Self>,
12845 ) {
12846 if !self.input_enabled {
12847 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12848 return;
12849 }
12850 if let Some(relative_utf16_range) = relative_utf16_range {
12851 let selections = self.selections.all::<OffsetUtf16>(cx);
12852 self.change_selections(None, cx, |s| {
12853 let new_ranges = selections.into_iter().map(|range| {
12854 let start = OffsetUtf16(
12855 range
12856 .head()
12857 .0
12858 .saturating_add_signed(relative_utf16_range.start),
12859 );
12860 let end = OffsetUtf16(
12861 range
12862 .head()
12863 .0
12864 .saturating_add_signed(relative_utf16_range.end),
12865 );
12866 start..end
12867 });
12868 s.select_ranges(new_ranges);
12869 });
12870 }
12871
12872 self.handle_input(text, cx);
12873 }
12874
12875 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12876 let Some(provider) = self.semantics_provider.as_ref() else {
12877 return false;
12878 };
12879
12880 let mut supports = false;
12881 self.buffer().read(cx).for_each_buffer(|buffer| {
12882 supports |= provider.supports_inlay_hints(buffer, cx);
12883 });
12884 supports
12885 }
12886
12887 pub fn focus(&self, cx: &mut WindowContext) {
12888 cx.focus(&self.focus_handle)
12889 }
12890
12891 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12892 self.focus_handle.is_focused(cx)
12893 }
12894
12895 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12896 cx.emit(EditorEvent::Focused);
12897
12898 if let Some(descendant) = self
12899 .last_focused_descendant
12900 .take()
12901 .and_then(|descendant| descendant.upgrade())
12902 {
12903 cx.focus(&descendant);
12904 } else {
12905 if let Some(blame) = self.blame.as_ref() {
12906 blame.update(cx, GitBlame::focus)
12907 }
12908
12909 self.blink_manager.update(cx, BlinkManager::enable);
12910 self.show_cursor_names(cx);
12911 self.buffer.update(cx, |buffer, cx| {
12912 buffer.finalize_last_transaction(cx);
12913 if self.leader_peer_id.is_none() {
12914 buffer.set_active_selections(
12915 &self.selections.disjoint_anchors(),
12916 self.selections.line_mode,
12917 self.cursor_shape,
12918 cx,
12919 );
12920 }
12921 });
12922 }
12923 }
12924
12925 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12926 cx.emit(EditorEvent::FocusedIn)
12927 }
12928
12929 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12930 if event.blurred != self.focus_handle {
12931 self.last_focused_descendant = Some(event.blurred);
12932 }
12933 }
12934
12935 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12936 self.blink_manager.update(cx, BlinkManager::disable);
12937 self.buffer
12938 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12939
12940 if let Some(blame) = self.blame.as_ref() {
12941 blame.update(cx, GitBlame::blur)
12942 }
12943 if !self.hover_state.focused(cx) {
12944 hide_hover(self, cx);
12945 }
12946
12947 self.hide_context_menu(cx);
12948 cx.emit(EditorEvent::Blurred);
12949 cx.notify();
12950 }
12951
12952 pub fn register_action<A: Action>(
12953 &mut self,
12954 listener: impl Fn(&A, &mut WindowContext) + 'static,
12955 ) -> Subscription {
12956 let id = self.next_editor_action_id.post_inc();
12957 let listener = Arc::new(listener);
12958 self.editor_actions.borrow_mut().insert(
12959 id,
12960 Box::new(move |cx| {
12961 let cx = cx.window_context();
12962 let listener = listener.clone();
12963 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12964 let action = action.downcast_ref().unwrap();
12965 if phase == DispatchPhase::Bubble {
12966 listener(action, cx)
12967 }
12968 })
12969 }),
12970 );
12971
12972 let editor_actions = self.editor_actions.clone();
12973 Subscription::new(move || {
12974 editor_actions.borrow_mut().remove(&id);
12975 })
12976 }
12977
12978 pub fn file_header_size(&self) -> u32 {
12979 FILE_HEADER_HEIGHT
12980 }
12981
12982 pub fn revert(
12983 &mut self,
12984 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12985 cx: &mut ViewContext<Self>,
12986 ) {
12987 self.buffer().update(cx, |multi_buffer, cx| {
12988 for (buffer_id, changes) in revert_changes {
12989 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12990 buffer.update(cx, |buffer, cx| {
12991 buffer.edit(
12992 changes.into_iter().map(|(range, text)| {
12993 (range, text.to_string().map(Arc::<str>::from))
12994 }),
12995 None,
12996 cx,
12997 );
12998 });
12999 }
13000 }
13001 });
13002 self.change_selections(None, cx, |selections| selections.refresh());
13003 }
13004
13005 pub fn to_pixel_point(
13006 &mut self,
13007 source: multi_buffer::Anchor,
13008 editor_snapshot: &EditorSnapshot,
13009 cx: &mut ViewContext<Self>,
13010 ) -> Option<gpui::Point<Pixels>> {
13011 let source_point = source.to_display_point(editor_snapshot);
13012 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13013 }
13014
13015 pub fn display_to_pixel_point(
13016 &mut self,
13017 source: DisplayPoint,
13018 editor_snapshot: &EditorSnapshot,
13019 cx: &mut ViewContext<Self>,
13020 ) -> Option<gpui::Point<Pixels>> {
13021 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13022 let text_layout_details = self.text_layout_details(cx);
13023 let scroll_top = text_layout_details
13024 .scroll_anchor
13025 .scroll_position(editor_snapshot)
13026 .y;
13027
13028 if source.row().as_f32() < scroll_top.floor() {
13029 return None;
13030 }
13031 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13032 let source_y = line_height * (source.row().as_f32() - scroll_top);
13033 Some(gpui::Point::new(source_x, source_y))
13034 }
13035
13036 pub fn has_active_completions_menu(&self) -> bool {
13037 self.context_menu.read().as_ref().map_or(false, |menu| {
13038 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13039 })
13040 }
13041
13042 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13043 self.addons
13044 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13045 }
13046
13047 pub fn unregister_addon<T: Addon>(&mut self) {
13048 self.addons.remove(&std::any::TypeId::of::<T>());
13049 }
13050
13051 pub fn addon<T: Addon>(&self) -> Option<&T> {
13052 let type_id = std::any::TypeId::of::<T>();
13053 self.addons
13054 .get(&type_id)
13055 .and_then(|item| item.to_any().downcast_ref::<T>())
13056 }
13057}
13058
13059fn hunks_for_selections(
13060 multi_buffer_snapshot: &MultiBufferSnapshot,
13061 selections: &[Selection<Anchor>],
13062) -> Vec<MultiBufferDiffHunk> {
13063 let buffer_rows_for_selections = selections.iter().map(|selection| {
13064 let head = selection.head();
13065 let tail = selection.tail();
13066 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13067 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13068 if start > end {
13069 end..start
13070 } else {
13071 start..end
13072 }
13073 });
13074
13075 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13076}
13077
13078pub fn hunks_for_rows(
13079 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13080 multi_buffer_snapshot: &MultiBufferSnapshot,
13081) -> Vec<MultiBufferDiffHunk> {
13082 let mut hunks = Vec::new();
13083 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13084 HashMap::default();
13085 for selected_multi_buffer_rows in rows {
13086 let query_rows =
13087 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13088 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13089 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13090 // when the caret is just above or just below the deleted hunk.
13091 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13092 let related_to_selection = if allow_adjacent {
13093 hunk.row_range.overlaps(&query_rows)
13094 || hunk.row_range.start == query_rows.end
13095 || hunk.row_range.end == query_rows.start
13096 } else {
13097 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13098 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13099 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13100 || selected_multi_buffer_rows.end == hunk.row_range.start
13101 };
13102 if related_to_selection {
13103 if !processed_buffer_rows
13104 .entry(hunk.buffer_id)
13105 .or_default()
13106 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13107 {
13108 continue;
13109 }
13110 hunks.push(hunk);
13111 }
13112 }
13113 }
13114
13115 hunks
13116}
13117
13118pub trait CollaborationHub {
13119 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13120 fn user_participant_indices<'a>(
13121 &self,
13122 cx: &'a AppContext,
13123 ) -> &'a HashMap<u64, ParticipantIndex>;
13124 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13125}
13126
13127impl CollaborationHub for Model<Project> {
13128 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13129 self.read(cx).collaborators()
13130 }
13131
13132 fn user_participant_indices<'a>(
13133 &self,
13134 cx: &'a AppContext,
13135 ) -> &'a HashMap<u64, ParticipantIndex> {
13136 self.read(cx).user_store().read(cx).participant_indices()
13137 }
13138
13139 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13140 let this = self.read(cx);
13141 let user_ids = this.collaborators().values().map(|c| c.user_id);
13142 this.user_store().read_with(cx, |user_store, cx| {
13143 user_store.participant_names(user_ids, cx)
13144 })
13145 }
13146}
13147
13148pub trait SemanticsProvider {
13149 fn hover(
13150 &self,
13151 buffer: &Model<Buffer>,
13152 position: text::Anchor,
13153 cx: &mut AppContext,
13154 ) -> Option<Task<Vec<project::Hover>>>;
13155
13156 fn inlay_hints(
13157 &self,
13158 buffer_handle: Model<Buffer>,
13159 range: Range<text::Anchor>,
13160 cx: &mut AppContext,
13161 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13162
13163 fn resolve_inlay_hint(
13164 &self,
13165 hint: InlayHint,
13166 buffer_handle: Model<Buffer>,
13167 server_id: LanguageServerId,
13168 cx: &mut AppContext,
13169 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13170
13171 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13172
13173 fn document_highlights(
13174 &self,
13175 buffer: &Model<Buffer>,
13176 position: text::Anchor,
13177 cx: &mut AppContext,
13178 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13179
13180 fn definitions(
13181 &self,
13182 buffer: &Model<Buffer>,
13183 position: text::Anchor,
13184 kind: GotoDefinitionKind,
13185 cx: &mut AppContext,
13186 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13187
13188 fn range_for_rename(
13189 &self,
13190 buffer: &Model<Buffer>,
13191 position: text::Anchor,
13192 cx: &mut AppContext,
13193 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13194
13195 fn perform_rename(
13196 &self,
13197 buffer: &Model<Buffer>,
13198 position: text::Anchor,
13199 new_name: String,
13200 cx: &mut AppContext,
13201 ) -> Option<Task<Result<ProjectTransaction>>>;
13202}
13203
13204pub trait CompletionProvider {
13205 fn completions(
13206 &self,
13207 buffer: &Model<Buffer>,
13208 buffer_position: text::Anchor,
13209 trigger: CompletionContext,
13210 cx: &mut ViewContext<Editor>,
13211 ) -> Task<Result<Vec<Completion>>>;
13212
13213 fn resolve_completions(
13214 &self,
13215 buffer: Model<Buffer>,
13216 completion_indices: Vec<usize>,
13217 completions: Arc<RwLock<Box<[Completion]>>>,
13218 cx: &mut ViewContext<Editor>,
13219 ) -> Task<Result<bool>>;
13220
13221 fn apply_additional_edits_for_completion(
13222 &self,
13223 buffer: Model<Buffer>,
13224 completion: Completion,
13225 push_to_history: bool,
13226 cx: &mut ViewContext<Editor>,
13227 ) -> Task<Result<Option<language::Transaction>>>;
13228
13229 fn is_completion_trigger(
13230 &self,
13231 buffer: &Model<Buffer>,
13232 position: language::Anchor,
13233 text: &str,
13234 trigger_in_words: bool,
13235 cx: &mut ViewContext<Editor>,
13236 ) -> bool;
13237
13238 fn sort_completions(&self) -> bool {
13239 true
13240 }
13241}
13242
13243pub trait CodeActionProvider {
13244 fn code_actions(
13245 &self,
13246 buffer: &Model<Buffer>,
13247 range: Range<text::Anchor>,
13248 cx: &mut WindowContext,
13249 ) -> Task<Result<Vec<CodeAction>>>;
13250
13251 fn apply_code_action(
13252 &self,
13253 buffer_handle: Model<Buffer>,
13254 action: CodeAction,
13255 excerpt_id: ExcerptId,
13256 push_to_history: bool,
13257 cx: &mut WindowContext,
13258 ) -> Task<Result<ProjectTransaction>>;
13259}
13260
13261impl CodeActionProvider for Model<Project> {
13262 fn code_actions(
13263 &self,
13264 buffer: &Model<Buffer>,
13265 range: Range<text::Anchor>,
13266 cx: &mut WindowContext,
13267 ) -> Task<Result<Vec<CodeAction>>> {
13268 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13269 }
13270
13271 fn apply_code_action(
13272 &self,
13273 buffer_handle: Model<Buffer>,
13274 action: CodeAction,
13275 _excerpt_id: ExcerptId,
13276 push_to_history: bool,
13277 cx: &mut WindowContext,
13278 ) -> Task<Result<ProjectTransaction>> {
13279 self.update(cx, |project, cx| {
13280 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13281 })
13282 }
13283}
13284
13285fn snippet_completions(
13286 project: &Project,
13287 buffer: &Model<Buffer>,
13288 buffer_position: text::Anchor,
13289 cx: &mut AppContext,
13290) -> Vec<Completion> {
13291 let language = buffer.read(cx).language_at(buffer_position);
13292 let language_name = language.as_ref().map(|language| language.lsp_id());
13293 let snippet_store = project.snippets().read(cx);
13294 let snippets = snippet_store.snippets_for(language_name, cx);
13295
13296 if snippets.is_empty() {
13297 return vec![];
13298 }
13299 let snapshot = buffer.read(cx).text_snapshot();
13300 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13301
13302 let scope = language.map(|language| language.default_scope());
13303 let classifier = CharClassifier::new(scope).for_completion(true);
13304 let mut last_word = chars
13305 .take_while(|c| classifier.is_word(*c))
13306 .collect::<String>();
13307 last_word = last_word.chars().rev().collect();
13308 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13309 let to_lsp = |point: &text::Anchor| {
13310 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13311 point_to_lsp(end)
13312 };
13313 let lsp_end = to_lsp(&buffer_position);
13314 snippets
13315 .into_iter()
13316 .filter_map(|snippet| {
13317 let matching_prefix = snippet
13318 .prefix
13319 .iter()
13320 .find(|prefix| prefix.starts_with(&last_word))?;
13321 let start = as_offset - last_word.len();
13322 let start = snapshot.anchor_before(start);
13323 let range = start..buffer_position;
13324 let lsp_start = to_lsp(&start);
13325 let lsp_range = lsp::Range {
13326 start: lsp_start,
13327 end: lsp_end,
13328 };
13329 Some(Completion {
13330 old_range: range,
13331 new_text: snippet.body.clone(),
13332 label: CodeLabel {
13333 text: matching_prefix.clone(),
13334 runs: vec![],
13335 filter_range: 0..matching_prefix.len(),
13336 },
13337 server_id: LanguageServerId(usize::MAX),
13338 documentation: snippet.description.clone().map(Documentation::SingleLine),
13339 lsp_completion: lsp::CompletionItem {
13340 label: snippet.prefix.first().unwrap().clone(),
13341 kind: Some(CompletionItemKind::SNIPPET),
13342 label_details: snippet.description.as_ref().map(|description| {
13343 lsp::CompletionItemLabelDetails {
13344 detail: Some(description.clone()),
13345 description: None,
13346 }
13347 }),
13348 insert_text_format: Some(InsertTextFormat::SNIPPET),
13349 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13350 lsp::InsertReplaceEdit {
13351 new_text: snippet.body.clone(),
13352 insert: lsp_range,
13353 replace: lsp_range,
13354 },
13355 )),
13356 filter_text: Some(snippet.body.clone()),
13357 sort_text: Some(char::MAX.to_string()),
13358 ..Default::default()
13359 },
13360 confirm: None,
13361 })
13362 })
13363 .collect()
13364}
13365
13366impl CompletionProvider for Model<Project> {
13367 fn completions(
13368 &self,
13369 buffer: &Model<Buffer>,
13370 buffer_position: text::Anchor,
13371 options: CompletionContext,
13372 cx: &mut ViewContext<Editor>,
13373 ) -> Task<Result<Vec<Completion>>> {
13374 self.update(cx, |project, cx| {
13375 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13376 let project_completions = project.completions(buffer, buffer_position, options, cx);
13377 cx.background_executor().spawn(async move {
13378 let mut completions = project_completions.await?;
13379 //let snippets = snippets.into_iter().;
13380 completions.extend(snippets);
13381 Ok(completions)
13382 })
13383 })
13384 }
13385
13386 fn resolve_completions(
13387 &self,
13388 buffer: Model<Buffer>,
13389 completion_indices: Vec<usize>,
13390 completions: Arc<RwLock<Box<[Completion]>>>,
13391 cx: &mut ViewContext<Editor>,
13392 ) -> Task<Result<bool>> {
13393 self.update(cx, |project, cx| {
13394 project.resolve_completions(buffer, completion_indices, completions, cx)
13395 })
13396 }
13397
13398 fn apply_additional_edits_for_completion(
13399 &self,
13400 buffer: Model<Buffer>,
13401 completion: Completion,
13402 push_to_history: bool,
13403 cx: &mut ViewContext<Editor>,
13404 ) -> Task<Result<Option<language::Transaction>>> {
13405 self.update(cx, |project, cx| {
13406 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13407 })
13408 }
13409
13410 fn is_completion_trigger(
13411 &self,
13412 buffer: &Model<Buffer>,
13413 position: language::Anchor,
13414 text: &str,
13415 trigger_in_words: bool,
13416 cx: &mut ViewContext<Editor>,
13417 ) -> bool {
13418 if !EditorSettings::get_global(cx).show_completions_on_input {
13419 return false;
13420 }
13421
13422 let mut chars = text.chars();
13423 let char = if let Some(char) = chars.next() {
13424 char
13425 } else {
13426 return false;
13427 };
13428 if chars.next().is_some() {
13429 return false;
13430 }
13431
13432 let buffer = buffer.read(cx);
13433 let classifier = buffer
13434 .snapshot()
13435 .char_classifier_at(position)
13436 .for_completion(true);
13437 if trigger_in_words && classifier.is_word(char) {
13438 return true;
13439 }
13440
13441 buffer
13442 .completion_triggers()
13443 .iter()
13444 .any(|string| string == text)
13445 }
13446}
13447
13448impl SemanticsProvider for Model<Project> {
13449 fn hover(
13450 &self,
13451 buffer: &Model<Buffer>,
13452 position: text::Anchor,
13453 cx: &mut AppContext,
13454 ) -> Option<Task<Vec<project::Hover>>> {
13455 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13456 }
13457
13458 fn document_highlights(
13459 &self,
13460 buffer: &Model<Buffer>,
13461 position: text::Anchor,
13462 cx: &mut AppContext,
13463 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13464 Some(self.update(cx, |project, cx| {
13465 project.document_highlights(buffer, position, cx)
13466 }))
13467 }
13468
13469 fn definitions(
13470 &self,
13471 buffer: &Model<Buffer>,
13472 position: text::Anchor,
13473 kind: GotoDefinitionKind,
13474 cx: &mut AppContext,
13475 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13476 Some(self.update(cx, |project, cx| match kind {
13477 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13478 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13479 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13480 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13481 }))
13482 }
13483
13484 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13485 // TODO: make this work for remote projects
13486 self.read(cx)
13487 .language_servers_for_buffer(buffer.read(cx), cx)
13488 .any(
13489 |(_, server)| match server.capabilities().inlay_hint_provider {
13490 Some(lsp::OneOf::Left(enabled)) => enabled,
13491 Some(lsp::OneOf::Right(_)) => true,
13492 None => false,
13493 },
13494 )
13495 }
13496
13497 fn inlay_hints(
13498 &self,
13499 buffer_handle: Model<Buffer>,
13500 range: Range<text::Anchor>,
13501 cx: &mut AppContext,
13502 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13503 Some(self.update(cx, |project, cx| {
13504 project.inlay_hints(buffer_handle, range, cx)
13505 }))
13506 }
13507
13508 fn resolve_inlay_hint(
13509 &self,
13510 hint: InlayHint,
13511 buffer_handle: Model<Buffer>,
13512 server_id: LanguageServerId,
13513 cx: &mut AppContext,
13514 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13515 Some(self.update(cx, |project, cx| {
13516 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13517 }))
13518 }
13519
13520 fn range_for_rename(
13521 &self,
13522 buffer: &Model<Buffer>,
13523 position: text::Anchor,
13524 cx: &mut AppContext,
13525 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13526 Some(self.update(cx, |project, cx| {
13527 project.prepare_rename(buffer.clone(), position, cx)
13528 }))
13529 }
13530
13531 fn perform_rename(
13532 &self,
13533 buffer: &Model<Buffer>,
13534 position: text::Anchor,
13535 new_name: String,
13536 cx: &mut AppContext,
13537 ) -> Option<Task<Result<ProjectTransaction>>> {
13538 Some(self.update(cx, |project, cx| {
13539 project.perform_rename(buffer.clone(), position, new_name, cx)
13540 }))
13541 }
13542}
13543
13544fn inlay_hint_settings(
13545 location: Anchor,
13546 snapshot: &MultiBufferSnapshot,
13547 cx: &mut ViewContext<'_, Editor>,
13548) -> InlayHintSettings {
13549 let file = snapshot.file_at(location);
13550 let language = snapshot.language_at(location).map(|l| l.name());
13551 language_settings(language, file, cx).inlay_hints
13552}
13553
13554fn consume_contiguous_rows(
13555 contiguous_row_selections: &mut Vec<Selection<Point>>,
13556 selection: &Selection<Point>,
13557 display_map: &DisplaySnapshot,
13558 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13559) -> (MultiBufferRow, MultiBufferRow) {
13560 contiguous_row_selections.push(selection.clone());
13561 let start_row = MultiBufferRow(selection.start.row);
13562 let mut end_row = ending_row(selection, display_map);
13563
13564 while let Some(next_selection) = selections.peek() {
13565 if next_selection.start.row <= end_row.0 {
13566 end_row = ending_row(next_selection, display_map);
13567 contiguous_row_selections.push(selections.next().unwrap().clone());
13568 } else {
13569 break;
13570 }
13571 }
13572 (start_row, end_row)
13573}
13574
13575fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13576 if next_selection.end.column > 0 || next_selection.is_empty() {
13577 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13578 } else {
13579 MultiBufferRow(next_selection.end.row)
13580 }
13581}
13582
13583impl EditorSnapshot {
13584 pub fn remote_selections_in_range<'a>(
13585 &'a self,
13586 range: &'a Range<Anchor>,
13587 collaboration_hub: &dyn CollaborationHub,
13588 cx: &'a AppContext,
13589 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13590 let participant_names = collaboration_hub.user_names(cx);
13591 let participant_indices = collaboration_hub.user_participant_indices(cx);
13592 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13593 let collaborators_by_replica_id = collaborators_by_peer_id
13594 .iter()
13595 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13596 .collect::<HashMap<_, _>>();
13597 self.buffer_snapshot
13598 .selections_in_range(range, false)
13599 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13600 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13601 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13602 let user_name = participant_names.get(&collaborator.user_id).cloned();
13603 Some(RemoteSelection {
13604 replica_id,
13605 selection,
13606 cursor_shape,
13607 line_mode,
13608 participant_index,
13609 peer_id: collaborator.peer_id,
13610 user_name,
13611 })
13612 })
13613 }
13614
13615 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13616 self.display_snapshot.buffer_snapshot.language_at(position)
13617 }
13618
13619 pub fn is_focused(&self) -> bool {
13620 self.is_focused
13621 }
13622
13623 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13624 self.placeholder_text.as_ref()
13625 }
13626
13627 pub fn scroll_position(&self) -> gpui::Point<f32> {
13628 self.scroll_anchor.scroll_position(&self.display_snapshot)
13629 }
13630
13631 fn gutter_dimensions(
13632 &self,
13633 font_id: FontId,
13634 font_size: Pixels,
13635 em_width: Pixels,
13636 em_advance: Pixels,
13637 max_line_number_width: Pixels,
13638 cx: &AppContext,
13639 ) -> GutterDimensions {
13640 if !self.show_gutter {
13641 return GutterDimensions::default();
13642 }
13643 let descent = cx.text_system().descent(font_id, font_size);
13644
13645 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13646 matches!(
13647 ProjectSettings::get_global(cx).git.git_gutter,
13648 Some(GitGutterSetting::TrackedFiles)
13649 )
13650 });
13651 let gutter_settings = EditorSettings::get_global(cx).gutter;
13652 let show_line_numbers = self
13653 .show_line_numbers
13654 .unwrap_or(gutter_settings.line_numbers);
13655 let line_gutter_width = if show_line_numbers {
13656 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13657 let min_width_for_number_on_gutter = em_advance * 4.0;
13658 max_line_number_width.max(min_width_for_number_on_gutter)
13659 } else {
13660 0.0.into()
13661 };
13662
13663 let show_code_actions = self
13664 .show_code_actions
13665 .unwrap_or(gutter_settings.code_actions);
13666
13667 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13668
13669 let git_blame_entries_width =
13670 self.git_blame_gutter_max_author_length
13671 .map(|max_author_length| {
13672 // Length of the author name, but also space for the commit hash,
13673 // the spacing and the timestamp.
13674 let max_char_count = max_author_length
13675 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13676 + 7 // length of commit sha
13677 + 14 // length of max relative timestamp ("60 minutes ago")
13678 + 4; // gaps and margins
13679
13680 em_advance * max_char_count
13681 });
13682
13683 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13684 left_padding += if show_code_actions || show_runnables {
13685 em_width * 3.0
13686 } else if show_git_gutter && show_line_numbers {
13687 em_width * 2.0
13688 } else if show_git_gutter || show_line_numbers {
13689 em_width
13690 } else {
13691 px(0.)
13692 };
13693
13694 let right_padding = if gutter_settings.folds && show_line_numbers {
13695 em_width * 4.0
13696 } else if gutter_settings.folds {
13697 em_width * 3.0
13698 } else if show_line_numbers {
13699 em_width
13700 } else {
13701 px(0.)
13702 };
13703
13704 GutterDimensions {
13705 left_padding,
13706 right_padding,
13707 width: line_gutter_width + left_padding + right_padding,
13708 margin: -descent,
13709 git_blame_entries_width,
13710 }
13711 }
13712
13713 pub fn render_fold_toggle(
13714 &self,
13715 buffer_row: MultiBufferRow,
13716 row_contains_cursor: bool,
13717 editor: View<Editor>,
13718 cx: &mut WindowContext,
13719 ) -> Option<AnyElement> {
13720 let folded = self.is_line_folded(buffer_row);
13721
13722 if let Some(crease) = self
13723 .crease_snapshot
13724 .query_row(buffer_row, &self.buffer_snapshot)
13725 {
13726 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13727 if folded {
13728 editor.update(cx, |editor, cx| {
13729 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13730 });
13731 } else {
13732 editor.update(cx, |editor, cx| {
13733 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13734 });
13735 }
13736 });
13737
13738 Some((crease.render_toggle)(
13739 buffer_row,
13740 folded,
13741 toggle_callback,
13742 cx,
13743 ))
13744 } else if folded
13745 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13746 {
13747 Some(
13748 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13749 .selected(folded)
13750 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13751 if folded {
13752 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13753 } else {
13754 this.fold_at(&FoldAt { buffer_row }, cx);
13755 }
13756 }))
13757 .into_any_element(),
13758 )
13759 } else {
13760 None
13761 }
13762 }
13763
13764 pub fn render_crease_trailer(
13765 &self,
13766 buffer_row: MultiBufferRow,
13767 cx: &mut WindowContext,
13768 ) -> Option<AnyElement> {
13769 let folded = self.is_line_folded(buffer_row);
13770 let crease = self
13771 .crease_snapshot
13772 .query_row(buffer_row, &self.buffer_snapshot)?;
13773 Some((crease.render_trailer)(buffer_row, folded, cx))
13774 }
13775}
13776
13777impl Deref for EditorSnapshot {
13778 type Target = DisplaySnapshot;
13779
13780 fn deref(&self) -> &Self::Target {
13781 &self.display_snapshot
13782 }
13783}
13784
13785#[derive(Clone, Debug, PartialEq, Eq)]
13786pub enum EditorEvent {
13787 InputIgnored {
13788 text: Arc<str>,
13789 },
13790 InputHandled {
13791 utf16_range_to_replace: Option<Range<isize>>,
13792 text: Arc<str>,
13793 },
13794 ExcerptsAdded {
13795 buffer: Model<Buffer>,
13796 predecessor: ExcerptId,
13797 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13798 },
13799 ExcerptsRemoved {
13800 ids: Vec<ExcerptId>,
13801 },
13802 ExcerptsEdited {
13803 ids: Vec<ExcerptId>,
13804 },
13805 ExcerptsExpanded {
13806 ids: Vec<ExcerptId>,
13807 },
13808 BufferEdited,
13809 Edited {
13810 transaction_id: clock::Lamport,
13811 },
13812 Reparsed(BufferId),
13813 Focused,
13814 FocusedIn,
13815 Blurred,
13816 DirtyChanged,
13817 Saved,
13818 TitleChanged,
13819 DiffBaseChanged,
13820 SelectionsChanged {
13821 local: bool,
13822 },
13823 ScrollPositionChanged {
13824 local: bool,
13825 autoscroll: bool,
13826 },
13827 Closed,
13828 TransactionUndone {
13829 transaction_id: clock::Lamport,
13830 },
13831 TransactionBegun {
13832 transaction_id: clock::Lamport,
13833 },
13834 Reloaded,
13835 CursorShapeChanged,
13836}
13837
13838impl EventEmitter<EditorEvent> for Editor {}
13839
13840impl FocusableView for Editor {
13841 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13842 self.focus_handle.clone()
13843 }
13844}
13845
13846impl Render for Editor {
13847 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13848 let settings = ThemeSettings::get_global(cx);
13849
13850 let mut text_style = match self.mode {
13851 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13852 color: cx.theme().colors().editor_foreground,
13853 font_family: settings.ui_font.family.clone(),
13854 font_features: settings.ui_font.features.clone(),
13855 font_fallbacks: settings.ui_font.fallbacks.clone(),
13856 font_size: rems(0.875).into(),
13857 font_weight: settings.ui_font.weight,
13858 line_height: relative(settings.buffer_line_height.value()),
13859 ..Default::default()
13860 },
13861 EditorMode::Full => TextStyle {
13862 color: cx.theme().colors().editor_foreground,
13863 font_family: settings.buffer_font.family.clone(),
13864 font_features: settings.buffer_font.features.clone(),
13865 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13866 font_size: settings.buffer_font_size(cx).into(),
13867 font_weight: settings.buffer_font.weight,
13868 line_height: relative(settings.buffer_line_height.value()),
13869 ..Default::default()
13870 },
13871 };
13872 if let Some(text_style_refinement) = &self.text_style_refinement {
13873 text_style.refine(text_style_refinement)
13874 }
13875
13876 let background = match self.mode {
13877 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13878 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13879 EditorMode::Full => cx.theme().colors().editor_background,
13880 };
13881
13882 EditorElement::new(
13883 cx.view(),
13884 EditorStyle {
13885 background,
13886 local_player: cx.theme().players().local(),
13887 text: text_style,
13888 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13889 syntax: cx.theme().syntax().clone(),
13890 status: cx.theme().status().clone(),
13891 inlay_hints_style: make_inlay_hints_style(cx),
13892 suggestions_style: HighlightStyle {
13893 color: Some(cx.theme().status().predictive),
13894 ..HighlightStyle::default()
13895 },
13896 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13897 },
13898 )
13899 }
13900}
13901
13902impl ViewInputHandler for Editor {
13903 fn text_for_range(
13904 &mut self,
13905 range_utf16: Range<usize>,
13906 cx: &mut ViewContext<Self>,
13907 ) -> Option<String> {
13908 Some(
13909 self.buffer
13910 .read(cx)
13911 .read(cx)
13912 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13913 .collect(),
13914 )
13915 }
13916
13917 fn selected_text_range(
13918 &mut self,
13919 ignore_disabled_input: bool,
13920 cx: &mut ViewContext<Self>,
13921 ) -> Option<UTF16Selection> {
13922 // Prevent the IME menu from appearing when holding down an alphabetic key
13923 // while input is disabled.
13924 if !ignore_disabled_input && !self.input_enabled {
13925 return None;
13926 }
13927
13928 let selection = self.selections.newest::<OffsetUtf16>(cx);
13929 let range = selection.range();
13930
13931 Some(UTF16Selection {
13932 range: range.start.0..range.end.0,
13933 reversed: selection.reversed,
13934 })
13935 }
13936
13937 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13938 let snapshot = self.buffer.read(cx).read(cx);
13939 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13940 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13941 }
13942
13943 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13944 self.clear_highlights::<InputComposition>(cx);
13945 self.ime_transaction.take();
13946 }
13947
13948 fn replace_text_in_range(
13949 &mut self,
13950 range_utf16: Option<Range<usize>>,
13951 text: &str,
13952 cx: &mut ViewContext<Self>,
13953 ) {
13954 if !self.input_enabled {
13955 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13956 return;
13957 }
13958
13959 self.transact(cx, |this, cx| {
13960 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13961 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13962 Some(this.selection_replacement_ranges(range_utf16, cx))
13963 } else {
13964 this.marked_text_ranges(cx)
13965 };
13966
13967 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13968 let newest_selection_id = this.selections.newest_anchor().id;
13969 this.selections
13970 .all::<OffsetUtf16>(cx)
13971 .iter()
13972 .zip(ranges_to_replace.iter())
13973 .find_map(|(selection, range)| {
13974 if selection.id == newest_selection_id {
13975 Some(
13976 (range.start.0 as isize - selection.head().0 as isize)
13977 ..(range.end.0 as isize - selection.head().0 as isize),
13978 )
13979 } else {
13980 None
13981 }
13982 })
13983 });
13984
13985 cx.emit(EditorEvent::InputHandled {
13986 utf16_range_to_replace: range_to_replace,
13987 text: text.into(),
13988 });
13989
13990 if let Some(new_selected_ranges) = new_selected_ranges {
13991 this.change_selections(None, cx, |selections| {
13992 selections.select_ranges(new_selected_ranges)
13993 });
13994 this.backspace(&Default::default(), cx);
13995 }
13996
13997 this.handle_input(text, cx);
13998 });
13999
14000 if let Some(transaction) = self.ime_transaction {
14001 self.buffer.update(cx, |buffer, cx| {
14002 buffer.group_until_transaction(transaction, cx);
14003 });
14004 }
14005
14006 self.unmark_text(cx);
14007 }
14008
14009 fn replace_and_mark_text_in_range(
14010 &mut self,
14011 range_utf16: Option<Range<usize>>,
14012 text: &str,
14013 new_selected_range_utf16: Option<Range<usize>>,
14014 cx: &mut ViewContext<Self>,
14015 ) {
14016 if !self.input_enabled {
14017 return;
14018 }
14019
14020 let transaction = self.transact(cx, |this, cx| {
14021 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14022 let snapshot = this.buffer.read(cx).read(cx);
14023 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14024 for marked_range in &mut marked_ranges {
14025 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14026 marked_range.start.0 += relative_range_utf16.start;
14027 marked_range.start =
14028 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14029 marked_range.end =
14030 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14031 }
14032 }
14033 Some(marked_ranges)
14034 } else if let Some(range_utf16) = range_utf16 {
14035 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14036 Some(this.selection_replacement_ranges(range_utf16, cx))
14037 } else {
14038 None
14039 };
14040
14041 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14042 let newest_selection_id = this.selections.newest_anchor().id;
14043 this.selections
14044 .all::<OffsetUtf16>(cx)
14045 .iter()
14046 .zip(ranges_to_replace.iter())
14047 .find_map(|(selection, range)| {
14048 if selection.id == newest_selection_id {
14049 Some(
14050 (range.start.0 as isize - selection.head().0 as isize)
14051 ..(range.end.0 as isize - selection.head().0 as isize),
14052 )
14053 } else {
14054 None
14055 }
14056 })
14057 });
14058
14059 cx.emit(EditorEvent::InputHandled {
14060 utf16_range_to_replace: range_to_replace,
14061 text: text.into(),
14062 });
14063
14064 if let Some(ranges) = ranges_to_replace {
14065 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14066 }
14067
14068 let marked_ranges = {
14069 let snapshot = this.buffer.read(cx).read(cx);
14070 this.selections
14071 .disjoint_anchors()
14072 .iter()
14073 .map(|selection| {
14074 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14075 })
14076 .collect::<Vec<_>>()
14077 };
14078
14079 if text.is_empty() {
14080 this.unmark_text(cx);
14081 } else {
14082 this.highlight_text::<InputComposition>(
14083 marked_ranges.clone(),
14084 HighlightStyle {
14085 underline: Some(UnderlineStyle {
14086 thickness: px(1.),
14087 color: None,
14088 wavy: false,
14089 }),
14090 ..Default::default()
14091 },
14092 cx,
14093 );
14094 }
14095
14096 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14097 let use_autoclose = this.use_autoclose;
14098 let use_auto_surround = this.use_auto_surround;
14099 this.set_use_autoclose(false);
14100 this.set_use_auto_surround(false);
14101 this.handle_input(text, cx);
14102 this.set_use_autoclose(use_autoclose);
14103 this.set_use_auto_surround(use_auto_surround);
14104
14105 if let Some(new_selected_range) = new_selected_range_utf16 {
14106 let snapshot = this.buffer.read(cx).read(cx);
14107 let new_selected_ranges = marked_ranges
14108 .into_iter()
14109 .map(|marked_range| {
14110 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14111 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14112 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14113 snapshot.clip_offset_utf16(new_start, Bias::Left)
14114 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14115 })
14116 .collect::<Vec<_>>();
14117
14118 drop(snapshot);
14119 this.change_selections(None, cx, |selections| {
14120 selections.select_ranges(new_selected_ranges)
14121 });
14122 }
14123 });
14124
14125 self.ime_transaction = self.ime_transaction.or(transaction);
14126 if let Some(transaction) = self.ime_transaction {
14127 self.buffer.update(cx, |buffer, cx| {
14128 buffer.group_until_transaction(transaction, cx);
14129 });
14130 }
14131
14132 if self.text_highlights::<InputComposition>(cx).is_none() {
14133 self.ime_transaction.take();
14134 }
14135 }
14136
14137 fn bounds_for_range(
14138 &mut self,
14139 range_utf16: Range<usize>,
14140 element_bounds: gpui::Bounds<Pixels>,
14141 cx: &mut ViewContext<Self>,
14142 ) -> Option<gpui::Bounds<Pixels>> {
14143 let text_layout_details = self.text_layout_details(cx);
14144 let style = &text_layout_details.editor_style;
14145 let font_id = cx.text_system().resolve_font(&style.text.font());
14146 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14147 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14148
14149 let em_width = cx
14150 .text_system()
14151 .typographic_bounds(font_id, font_size, 'm')
14152 .unwrap()
14153 .size
14154 .width;
14155
14156 let snapshot = self.snapshot(cx);
14157 let scroll_position = snapshot.scroll_position();
14158 let scroll_left = scroll_position.x * em_width;
14159
14160 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14161 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14162 + self.gutter_dimensions.width;
14163 let y = line_height * (start.row().as_f32() - scroll_position.y);
14164
14165 Some(Bounds {
14166 origin: element_bounds.origin + point(x, y),
14167 size: size(em_width, line_height),
14168 })
14169 }
14170}
14171
14172trait SelectionExt {
14173 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14174 fn spanned_rows(
14175 &self,
14176 include_end_if_at_line_start: bool,
14177 map: &DisplaySnapshot,
14178 ) -> Range<MultiBufferRow>;
14179}
14180
14181impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14182 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14183 let start = self
14184 .start
14185 .to_point(&map.buffer_snapshot)
14186 .to_display_point(map);
14187 let end = self
14188 .end
14189 .to_point(&map.buffer_snapshot)
14190 .to_display_point(map);
14191 if self.reversed {
14192 end..start
14193 } else {
14194 start..end
14195 }
14196 }
14197
14198 fn spanned_rows(
14199 &self,
14200 include_end_if_at_line_start: bool,
14201 map: &DisplaySnapshot,
14202 ) -> Range<MultiBufferRow> {
14203 let start = self.start.to_point(&map.buffer_snapshot);
14204 let mut end = self.end.to_point(&map.buffer_snapshot);
14205 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14206 end.row -= 1;
14207 }
14208
14209 let buffer_start = map.prev_line_boundary(start).0;
14210 let buffer_end = map.next_line_boundary(end).0;
14211 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14212 }
14213}
14214
14215impl<T: InvalidationRegion> InvalidationStack<T> {
14216 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14217 where
14218 S: Clone + ToOffset,
14219 {
14220 while let Some(region) = self.last() {
14221 let all_selections_inside_invalidation_ranges =
14222 if selections.len() == region.ranges().len() {
14223 selections
14224 .iter()
14225 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14226 .all(|(selection, invalidation_range)| {
14227 let head = selection.head().to_offset(buffer);
14228 invalidation_range.start <= head && invalidation_range.end >= head
14229 })
14230 } else {
14231 false
14232 };
14233
14234 if all_selections_inside_invalidation_ranges {
14235 break;
14236 } else {
14237 self.pop();
14238 }
14239 }
14240 }
14241}
14242
14243impl<T> Default for InvalidationStack<T> {
14244 fn default() -> Self {
14245 Self(Default::default())
14246 }
14247}
14248
14249impl<T> Deref for InvalidationStack<T> {
14250 type Target = Vec<T>;
14251
14252 fn deref(&self) -> &Self::Target {
14253 &self.0
14254 }
14255}
14256
14257impl<T> DerefMut for InvalidationStack<T> {
14258 fn deref_mut(&mut self) -> &mut Self::Target {
14259 &mut self.0
14260 }
14261}
14262
14263impl InvalidationRegion for SnippetState {
14264 fn ranges(&self) -> &[Range<Anchor>] {
14265 &self.ranges[self.active_index]
14266 }
14267}
14268
14269pub fn diagnostic_block_renderer(
14270 diagnostic: Diagnostic,
14271 max_message_rows: Option<u8>,
14272 allow_closing: bool,
14273 _is_valid: bool,
14274) -> RenderBlock {
14275 let (text_without_backticks, code_ranges) =
14276 highlight_diagnostic_message(&diagnostic, max_message_rows);
14277
14278 Box::new(move |cx: &mut BlockContext| {
14279 let group_id: SharedString = cx.block_id.to_string().into();
14280
14281 let mut text_style = cx.text_style().clone();
14282 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14283 let theme_settings = ThemeSettings::get_global(cx);
14284 text_style.font_family = theme_settings.buffer_font.family.clone();
14285 text_style.font_style = theme_settings.buffer_font.style;
14286 text_style.font_features = theme_settings.buffer_font.features.clone();
14287 text_style.font_weight = theme_settings.buffer_font.weight;
14288
14289 let multi_line_diagnostic = diagnostic.message.contains('\n');
14290
14291 let buttons = |diagnostic: &Diagnostic| {
14292 if multi_line_diagnostic {
14293 v_flex()
14294 } else {
14295 h_flex()
14296 }
14297 .when(allow_closing, |div| {
14298 div.children(diagnostic.is_primary.then(|| {
14299 IconButton::new("close-block", IconName::XCircle)
14300 .icon_color(Color::Muted)
14301 .size(ButtonSize::Compact)
14302 .style(ButtonStyle::Transparent)
14303 .visible_on_hover(group_id.clone())
14304 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14305 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14306 }))
14307 })
14308 .child(
14309 IconButton::new("copy-block", IconName::Copy)
14310 .icon_color(Color::Muted)
14311 .size(ButtonSize::Compact)
14312 .style(ButtonStyle::Transparent)
14313 .visible_on_hover(group_id.clone())
14314 .on_click({
14315 let message = diagnostic.message.clone();
14316 move |_click, cx| {
14317 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14318 }
14319 })
14320 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14321 )
14322 };
14323
14324 let icon_size = buttons(&diagnostic)
14325 .into_any_element()
14326 .layout_as_root(AvailableSpace::min_size(), cx);
14327
14328 h_flex()
14329 .id(cx.block_id)
14330 .group(group_id.clone())
14331 .relative()
14332 .size_full()
14333 .pl(cx.gutter_dimensions.width)
14334 .w(cx.max_width - cx.gutter_dimensions.full_width())
14335 .child(
14336 div()
14337 .flex()
14338 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14339 .flex_shrink(),
14340 )
14341 .child(buttons(&diagnostic))
14342 .child(div().flex().flex_shrink_0().child(
14343 StyledText::new(text_without_backticks.clone()).with_highlights(
14344 &text_style,
14345 code_ranges.iter().map(|range| {
14346 (
14347 range.clone(),
14348 HighlightStyle {
14349 font_weight: Some(FontWeight::BOLD),
14350 ..Default::default()
14351 },
14352 )
14353 }),
14354 ),
14355 ))
14356 .into_any_element()
14357 })
14358}
14359
14360pub fn highlight_diagnostic_message(
14361 diagnostic: &Diagnostic,
14362 mut max_message_rows: Option<u8>,
14363) -> (SharedString, Vec<Range<usize>>) {
14364 let mut text_without_backticks = String::new();
14365 let mut code_ranges = Vec::new();
14366
14367 if let Some(source) = &diagnostic.source {
14368 text_without_backticks.push_str(source);
14369 code_ranges.push(0..source.len());
14370 text_without_backticks.push_str(": ");
14371 }
14372
14373 let mut prev_offset = 0;
14374 let mut in_code_block = false;
14375 let has_row_limit = max_message_rows.is_some();
14376 let mut newline_indices = diagnostic
14377 .message
14378 .match_indices('\n')
14379 .filter(|_| has_row_limit)
14380 .map(|(ix, _)| ix)
14381 .fuse()
14382 .peekable();
14383
14384 for (quote_ix, _) in diagnostic
14385 .message
14386 .match_indices('`')
14387 .chain([(diagnostic.message.len(), "")])
14388 {
14389 let mut first_newline_ix = None;
14390 let mut last_newline_ix = None;
14391 while let Some(newline_ix) = newline_indices.peek() {
14392 if *newline_ix < quote_ix {
14393 if first_newline_ix.is_none() {
14394 first_newline_ix = Some(*newline_ix);
14395 }
14396 last_newline_ix = Some(*newline_ix);
14397
14398 if let Some(rows_left) = &mut max_message_rows {
14399 if *rows_left == 0 {
14400 break;
14401 } else {
14402 *rows_left -= 1;
14403 }
14404 }
14405 let _ = newline_indices.next();
14406 } else {
14407 break;
14408 }
14409 }
14410 let prev_len = text_without_backticks.len();
14411 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14412 text_without_backticks.push_str(new_text);
14413 if in_code_block {
14414 code_ranges.push(prev_len..text_without_backticks.len());
14415 }
14416 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14417 in_code_block = !in_code_block;
14418 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14419 text_without_backticks.push_str("...");
14420 break;
14421 }
14422 }
14423
14424 (text_without_backticks.into(), code_ranges)
14425}
14426
14427fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14428 match severity {
14429 DiagnosticSeverity::ERROR => colors.error,
14430 DiagnosticSeverity::WARNING => colors.warning,
14431 DiagnosticSeverity::INFORMATION => colors.info,
14432 DiagnosticSeverity::HINT => colors.info,
14433 _ => colors.ignored,
14434 }
14435}
14436
14437pub fn styled_runs_for_code_label<'a>(
14438 label: &'a CodeLabel,
14439 syntax_theme: &'a theme::SyntaxTheme,
14440) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14441 let fade_out = HighlightStyle {
14442 fade_out: Some(0.35),
14443 ..Default::default()
14444 };
14445
14446 let mut prev_end = label.filter_range.end;
14447 label
14448 .runs
14449 .iter()
14450 .enumerate()
14451 .flat_map(move |(ix, (range, highlight_id))| {
14452 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14453 style
14454 } else {
14455 return Default::default();
14456 };
14457 let mut muted_style = style;
14458 muted_style.highlight(fade_out);
14459
14460 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14461 if range.start >= label.filter_range.end {
14462 if range.start > prev_end {
14463 runs.push((prev_end..range.start, fade_out));
14464 }
14465 runs.push((range.clone(), muted_style));
14466 } else if range.end <= label.filter_range.end {
14467 runs.push((range.clone(), style));
14468 } else {
14469 runs.push((range.start..label.filter_range.end, style));
14470 runs.push((label.filter_range.end..range.end, muted_style));
14471 }
14472 prev_end = cmp::max(prev_end, range.end);
14473
14474 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14475 runs.push((prev_end..label.text.len(), fade_out));
14476 }
14477
14478 runs
14479 })
14480}
14481
14482pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14483 let mut prev_index = 0;
14484 let mut prev_codepoint: Option<char> = None;
14485 text.char_indices()
14486 .chain([(text.len(), '\0')])
14487 .filter_map(move |(index, codepoint)| {
14488 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14489 let is_boundary = index == text.len()
14490 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14491 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14492 if is_boundary {
14493 let chunk = &text[prev_index..index];
14494 prev_index = index;
14495 Some(chunk)
14496 } else {
14497 None
14498 }
14499 })
14500}
14501
14502pub trait RangeToAnchorExt: Sized {
14503 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14504
14505 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14506 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14507 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14508 }
14509}
14510
14511impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14512 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14513 let start_offset = self.start.to_offset(snapshot);
14514 let end_offset = self.end.to_offset(snapshot);
14515 if start_offset == end_offset {
14516 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14517 } else {
14518 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14519 }
14520 }
14521}
14522
14523pub trait RowExt {
14524 fn as_f32(&self) -> f32;
14525
14526 fn next_row(&self) -> Self;
14527
14528 fn previous_row(&self) -> Self;
14529
14530 fn minus(&self, other: Self) -> u32;
14531}
14532
14533impl RowExt for DisplayRow {
14534 fn as_f32(&self) -> f32 {
14535 self.0 as f32
14536 }
14537
14538 fn next_row(&self) -> Self {
14539 Self(self.0 + 1)
14540 }
14541
14542 fn previous_row(&self) -> Self {
14543 Self(self.0.saturating_sub(1))
14544 }
14545
14546 fn minus(&self, other: Self) -> u32 {
14547 self.0 - other.0
14548 }
14549}
14550
14551impl RowExt for MultiBufferRow {
14552 fn as_f32(&self) -> f32 {
14553 self.0 as f32
14554 }
14555
14556 fn next_row(&self) -> Self {
14557 Self(self.0 + 1)
14558 }
14559
14560 fn previous_row(&self) -> Self {
14561 Self(self.0.saturating_sub(1))
14562 }
14563
14564 fn minus(&self, other: Self) -> u32 {
14565 self.0 - other.0
14566 }
14567}
14568
14569trait RowRangeExt {
14570 type Row;
14571
14572 fn len(&self) -> usize;
14573
14574 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14575}
14576
14577impl RowRangeExt for Range<MultiBufferRow> {
14578 type Row = MultiBufferRow;
14579
14580 fn len(&self) -> usize {
14581 (self.end.0 - self.start.0) as usize
14582 }
14583
14584 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14585 (self.start.0..self.end.0).map(MultiBufferRow)
14586 }
14587}
14588
14589impl RowRangeExt for Range<DisplayRow> {
14590 type Row = DisplayRow;
14591
14592 fn len(&self) -> usize {
14593 (self.end.0 - self.start.0) as usize
14594 }
14595
14596 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14597 (self.start.0..self.end.0).map(DisplayRow)
14598 }
14599}
14600
14601fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14602 if hunk.diff_base_byte_range.is_empty() {
14603 DiffHunkStatus::Added
14604 } else if hunk.row_range.is_empty() {
14605 DiffHunkStatus::Removed
14606 } else {
14607 DiffHunkStatus::Modified
14608 }
14609}
14610
14611/// If select range has more than one line, we
14612/// just point the cursor to range.start.
14613fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14614 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14615 range
14616 } else {
14617 range.start..range.start
14618 }
14619}