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;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::DiffHunkStatus;
50pub(crate) use actions::*;
51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
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, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
79 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
80 TextStyle, 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::Direction;
90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use std::iter::Peekable;
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, LanguageServerName,
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, 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(Debug, Copy, Clone, PartialEq, Eq)]
277pub enum Navigated {
278 Yes,
279 No,
280}
281
282impl Navigated {
283 pub fn from_bool(yes: bool) -> Navigated {
284 if yes {
285 Navigated::Yes
286 } else {
287 Navigated::No
288 }
289 }
290}
291
292pub fn init_settings(cx: &mut AppContext) {
293 EditorSettings::register(cx);
294}
295
296pub fn init(cx: &mut AppContext) {
297 init_settings(cx);
298
299 workspace::register_project_item::<Editor>(cx);
300 workspace::FollowableViewRegistry::register::<Editor>(cx);
301 workspace::register_serializable_item::<Editor>(cx);
302
303 cx.observe_new_views(
304 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
305 workspace.register_action(Editor::new_file);
306 workspace.register_action(Editor::new_file_vertical);
307 workspace.register_action(Editor::new_file_horizontal);
308 },
309 )
310 .detach();
311
312 cx.on_action(move |_: &workspace::NewFile, cx| {
313 let app_state = workspace::AppState::global(cx);
314 if let Some(app_state) = app_state.upgrade() {
315 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
316 Editor::new_file(workspace, &Default::default(), cx)
317 })
318 .detach();
319 }
320 });
321 cx.on_action(move |_: &workspace::NewWindow, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
325 Editor::new_file(workspace, &Default::default(), cx)
326 })
327 .detach();
328 }
329 });
330}
331
332pub struct SearchWithinRange;
333
334trait InvalidationRegion {
335 fn ranges(&self) -> &[Range<Anchor>];
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub enum SelectPhase {
340 Begin {
341 position: DisplayPoint,
342 add: bool,
343 click_count: usize,
344 },
345 BeginColumnar {
346 position: DisplayPoint,
347 reset: bool,
348 goal_column: u32,
349 },
350 Extend {
351 position: DisplayPoint,
352 click_count: usize,
353 },
354 Update {
355 position: DisplayPoint,
356 goal_column: u32,
357 scroll_delta: gpui::Point<f32>,
358 },
359 End,
360}
361
362#[derive(Clone, Debug)]
363pub enum SelectMode {
364 Character,
365 Word(Range<Anchor>),
366 Line(Range<Anchor>),
367 All,
368}
369
370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
371pub enum EditorMode {
372 SingleLine { auto_width: bool },
373 AutoHeight { max_lines: usize },
374 Full,
375}
376
377#[derive(Copy, Clone, Debug)]
378pub enum SoftWrap {
379 /// Prefer not to wrap at all.
380 ///
381 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
382 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
383 GitDiff,
384 /// Prefer a single line generally, unless an overly long line is encountered.
385 None,
386 /// Soft wrap lines that exceed the editor width.
387 EditorWidth,
388 /// Soft wrap lines at the preferred line length.
389 Column(u32),
390 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
391 Bounded(u32),
392}
393
394#[derive(Clone)]
395pub struct EditorStyle {
396 pub background: Hsla,
397 pub local_player: PlayerColor,
398 pub text: TextStyle,
399 pub scrollbar_width: Pixels,
400 pub syntax: Arc<SyntaxTheme>,
401 pub status: StatusColors,
402 pub inlay_hints_style: HighlightStyle,
403 pub suggestions_style: HighlightStyle,
404 pub unnecessary_code_fade: f32,
405}
406
407impl Default for EditorStyle {
408 fn default() -> Self {
409 Self {
410 background: Hsla::default(),
411 local_player: PlayerColor::default(),
412 text: TextStyle::default(),
413 scrollbar_width: Pixels::default(),
414 syntax: Default::default(),
415 // HACK: Status colors don't have a real default.
416 // We should look into removing the status colors from the editor
417 // style and retrieve them directly from the theme.
418 status: StatusColors::dark(),
419 inlay_hints_style: HighlightStyle::default(),
420 suggestions_style: HighlightStyle::default(),
421 unnecessary_code_fade: Default::default(),
422 }
423 }
424}
425
426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
427 let show_background = language_settings::language_settings(None, None, cx)
428 .inlay_hints
429 .show_background;
430
431 HighlightStyle {
432 color: Some(cx.theme().status().hint),
433 background_color: show_background.then(|| cx.theme().status().hint_background),
434 ..HighlightStyle::default()
435 }
436}
437
438type CompletionId = usize;
439
440#[derive(Clone, Debug)]
441struct CompletionState {
442 // render_inlay_ids represents the inlay hints that are inserted
443 // for rendering the inline completions. They may be discontinuous
444 // in the event that the completion provider returns some intersection
445 // with the existing content.
446 render_inlay_ids: Vec<InlayId>,
447 // text is the resulting rope that is inserted when the user accepts a completion.
448 text: Rope,
449 // position is the position of the cursor when the completion was triggered.
450 position: multi_buffer::Anchor,
451 // delete_range is the range of text that this completion state covers.
452 // if the completion is accepted, this range should be deleted.
453 delete_range: Option<Range<multi_buffer::Anchor>>,
454}
455
456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
457struct EditorActionId(usize);
458
459impl EditorActionId {
460 pub fn post_inc(&mut self) -> Self {
461 let answer = self.0;
462
463 *self = Self(answer + 1);
464
465 Self(answer)
466 }
467}
468
469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
471
472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
474
475#[derive(Default)]
476struct ScrollbarMarkerState {
477 scrollbar_size: Size<Pixels>,
478 dirty: bool,
479 markers: Arc<[PaintQuad]>,
480 pending_refresh: Option<Task<Result<()>>>,
481}
482
483impl ScrollbarMarkerState {
484 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
485 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
486 }
487}
488
489#[derive(Clone, Debug)]
490struct RunnableTasks {
491 templates: Vec<(TaskSourceKind, TaskTemplate)>,
492 offset: MultiBufferOffset,
493 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
494 column: u32,
495 // Values of all named captures, including those starting with '_'
496 extra_variables: HashMap<String, String>,
497 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
498 context_range: Range<BufferOffset>,
499}
500
501impl RunnableTasks {
502 fn resolve<'a>(
503 &'a self,
504 cx: &'a task::TaskContext,
505 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
506 self.templates.iter().filter_map(|(kind, template)| {
507 template
508 .resolve_task(&kind.to_id_base(), cx)
509 .map(|task| (kind.clone(), task))
510 })
511 }
512}
513
514#[derive(Clone)]
515struct ResolvedTasks {
516 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
517 position: Anchor,
518}
519#[derive(Copy, Clone, Debug)]
520struct MultiBufferOffset(usize);
521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
522struct BufferOffset(usize);
523
524// Addons allow storing per-editor state in other crates (e.g. Vim)
525pub trait Addon: 'static {
526 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
527
528 fn to_any(&self) -> &dyn std::any::Any;
529}
530
531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
532pub enum IsVimMode {
533 Yes,
534 No,
535}
536
537pub trait ActiveLineTrailerProvider {
538 fn render_active_line_trailer(
539 &mut self,
540 style: &EditorStyle,
541 focus_handle: &FocusHandle,
542 cx: &mut WindowContext,
543 ) -> Option<AnyElement>;
544}
545
546/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
547///
548/// See the [module level documentation](self) for more information.
549pub struct Editor {
550 focus_handle: FocusHandle,
551 last_focused_descendant: Option<WeakFocusHandle>,
552 /// The text buffer being edited
553 buffer: Model<MultiBuffer>,
554 /// Map of how text in the buffer should be displayed.
555 /// Handles soft wraps, folds, fake inlay text insertions, etc.
556 pub display_map: Model<DisplayMap>,
557 pub selections: SelectionsCollection,
558 pub scroll_manager: ScrollManager,
559 /// When inline assist editors are linked, they all render cursors because
560 /// typing enters text into each of them, even the ones that aren't focused.
561 pub(crate) show_cursor_when_unfocused: bool,
562 columnar_selection_tail: Option<Anchor>,
563 add_selections_state: Option<AddSelectionsState>,
564 select_next_state: Option<SelectNextState>,
565 select_prev_state: Option<SelectNextState>,
566 selection_history: SelectionHistory,
567 autoclose_regions: Vec<AutocloseRegion>,
568 snippet_stack: InvalidationStack<SnippetState>,
569 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
570 ime_transaction: Option<TransactionId>,
571 active_diagnostics: Option<ActiveDiagnosticGroup>,
572 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
573
574 project: Option<Model<Project>>,
575 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
576 completion_provider: Option<Box<dyn CompletionProvider>>,
577 collaboration_hub: Option<Box<dyn CollaborationHub>>,
578 blink_manager: Model<BlinkManager>,
579 show_cursor_names: bool,
580 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
581 pub show_local_selections: bool,
582 mode: EditorMode,
583 show_breadcrumbs: bool,
584 show_gutter: bool,
585 show_line_numbers: Option<bool>,
586 use_relative_line_numbers: Option<bool>,
587 show_git_diff_gutter: Option<bool>,
588 show_code_actions: Option<bool>,
589 show_runnables: Option<bool>,
590 show_wrap_guides: Option<bool>,
591 show_indent_guides: Option<bool>,
592 placeholder_text: Option<Arc<str>>,
593 highlight_order: usize,
594 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
595 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
596 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
597 scrollbar_marker_state: ScrollbarMarkerState,
598 active_indent_guides_state: ActiveIndentGuidesState,
599 nav_history: Option<ItemNavHistory>,
600 context_menu: RwLock<Option<ContextMenu>>,
601 mouse_context_menu: Option<MouseContextMenu>,
602 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
603 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
604 signature_help_state: SignatureHelpState,
605 auto_signature_help: Option<bool>,
606 find_all_references_task_sources: Vec<Anchor>,
607 next_completion_id: CompletionId,
608 completion_documentation_pre_resolve_debounce: DebouncedDelay,
609 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
610 code_actions_task: Option<Task<Result<()>>>,
611 document_highlights_task: Option<Task<()>>,
612 linked_editing_range_task: Option<Task<Option<()>>>,
613 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
614 pending_rename: Option<RenameState>,
615 searchable: bool,
616 cursor_shape: CursorShape,
617 current_line_highlight: Option<CurrentLineHighlight>,
618 collapse_matches: bool,
619 autoindent_mode: Option<AutoindentMode>,
620 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
621 input_enabled: bool,
622 use_modal_editing: bool,
623 read_only: bool,
624 leader_peer_id: Option<PeerId>,
625 remote_id: Option<ViewId>,
626 hover_state: HoverState,
627 gutter_hovered: bool,
628 hovered_link_state: Option<HoveredLinkState>,
629 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
630 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
631 active_inline_completion: Option<CompletionState>,
632 // enable_inline_completions is a switch that Vim can use to disable
633 // inline completions based on its mode.
634 enable_inline_completions: bool,
635 show_inline_completions_override: Option<bool>,
636 inlay_hint_cache: InlayHintCache,
637 expanded_hunks: ExpandedHunks,
638 next_inlay_id: usize,
639 _subscriptions: Vec<Subscription>,
640 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
641 gutter_dimensions: GutterDimensions,
642 style: Option<EditorStyle>,
643 text_style_refinement: Option<TextStyleRefinement>,
644 next_editor_action_id: EditorActionId,
645 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
646 use_autoclose: bool,
647 use_auto_surround: bool,
648 auto_replace_emoji_shortcode: bool,
649 show_git_blame_gutter: bool,
650 show_git_blame_inline: bool,
651 show_git_blame_inline_delay_task: Option<Task<()>>,
652 git_blame_inline_enabled: bool,
653 serialize_dirty_buffers: bool,
654 show_selection_menu: Option<bool>,
655 blame: Option<Model<GitBlame>>,
656 blame_subscription: Option<Subscription>,
657 custom_context_menu: Option<
658 Box<
659 dyn 'static
660 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
661 >,
662 >,
663 last_bounds: Option<Bounds<Pixels>>,
664 expect_bounds_change: Option<Bounds<Pixels>>,
665 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
666 tasks_update_task: Option<Task<()>>,
667 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
668 breadcrumb_header: Option<String>,
669 focused_block: Option<FocusedBlock>,
670 next_scroll_position: NextScrollCursorCenterTopBottom,
671 addons: HashMap<TypeId, Box<dyn Addon>>,
672 _scroll_cursor_center_top_bottom_task: Task<()>,
673 active_line_trailer_provider: Option<Box<dyn ActiveLineTrailerProvider>>,
674}
675
676#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
677enum NextScrollCursorCenterTopBottom {
678 #[default]
679 Center,
680 Top,
681 Bottom,
682}
683
684impl NextScrollCursorCenterTopBottom {
685 fn next(&self) -> Self {
686 match self {
687 Self::Center => Self::Top,
688 Self::Top => Self::Bottom,
689 Self::Bottom => Self::Center,
690 }
691 }
692}
693
694#[derive(Clone)]
695pub struct EditorSnapshot {
696 pub mode: EditorMode,
697 show_gutter: bool,
698 show_line_numbers: Option<bool>,
699 show_git_diff_gutter: Option<bool>,
700 show_code_actions: Option<bool>,
701 show_runnables: Option<bool>,
702 git_blame_gutter_max_author_length: Option<usize>,
703 pub display_snapshot: DisplaySnapshot,
704 pub placeholder_text: Option<Arc<str>>,
705 is_focused: bool,
706 scroll_anchor: ScrollAnchor,
707 ongoing_scroll: OngoingScroll,
708 current_line_highlight: CurrentLineHighlight,
709 gutter_hovered: bool,
710}
711
712const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
713
714#[derive(Default, Debug, Clone, Copy)]
715pub struct GutterDimensions {
716 pub left_padding: Pixels,
717 pub right_padding: Pixels,
718 pub width: Pixels,
719 pub margin: Pixels,
720 pub git_blame_entries_width: Option<Pixels>,
721}
722
723impl GutterDimensions {
724 /// The full width of the space taken up by the gutter.
725 pub fn full_width(&self) -> Pixels {
726 self.margin + self.width
727 }
728
729 /// The width of the space reserved for the fold indicators,
730 /// use alongside 'justify_end' and `gutter_width` to
731 /// right align content with the line numbers
732 pub fn fold_area_width(&self) -> Pixels {
733 self.margin + self.right_padding
734 }
735}
736
737#[derive(Debug)]
738pub struct RemoteSelection {
739 pub replica_id: ReplicaId,
740 pub selection: Selection<Anchor>,
741 pub cursor_shape: CursorShape,
742 pub peer_id: PeerId,
743 pub line_mode: bool,
744 pub participant_index: Option<ParticipantIndex>,
745 pub user_name: Option<SharedString>,
746}
747
748#[derive(Clone, Debug)]
749struct SelectionHistoryEntry {
750 selections: Arc<[Selection<Anchor>]>,
751 select_next_state: Option<SelectNextState>,
752 select_prev_state: Option<SelectNextState>,
753 add_selections_state: Option<AddSelectionsState>,
754}
755
756enum SelectionHistoryMode {
757 Normal,
758 Undoing,
759 Redoing,
760}
761
762#[derive(Clone, PartialEq, Eq, Hash)]
763struct HoveredCursor {
764 replica_id: u16,
765 selection_id: usize,
766}
767
768impl Default for SelectionHistoryMode {
769 fn default() -> Self {
770 Self::Normal
771 }
772}
773
774#[derive(Default)]
775struct SelectionHistory {
776 #[allow(clippy::type_complexity)]
777 selections_by_transaction:
778 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
779 mode: SelectionHistoryMode,
780 undo_stack: VecDeque<SelectionHistoryEntry>,
781 redo_stack: VecDeque<SelectionHistoryEntry>,
782}
783
784impl SelectionHistory {
785 fn insert_transaction(
786 &mut self,
787 transaction_id: TransactionId,
788 selections: Arc<[Selection<Anchor>]>,
789 ) {
790 self.selections_by_transaction
791 .insert(transaction_id, (selections, None));
792 }
793
794 #[allow(clippy::type_complexity)]
795 fn transaction(
796 &self,
797 transaction_id: TransactionId,
798 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
799 self.selections_by_transaction.get(&transaction_id)
800 }
801
802 #[allow(clippy::type_complexity)]
803 fn transaction_mut(
804 &mut self,
805 transaction_id: TransactionId,
806 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
807 self.selections_by_transaction.get_mut(&transaction_id)
808 }
809
810 fn push(&mut self, entry: SelectionHistoryEntry) {
811 if !entry.selections.is_empty() {
812 match self.mode {
813 SelectionHistoryMode::Normal => {
814 self.push_undo(entry);
815 self.redo_stack.clear();
816 }
817 SelectionHistoryMode::Undoing => self.push_redo(entry),
818 SelectionHistoryMode::Redoing => self.push_undo(entry),
819 }
820 }
821 }
822
823 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
824 if self
825 .undo_stack
826 .back()
827 .map_or(true, |e| e.selections != entry.selections)
828 {
829 self.undo_stack.push_back(entry);
830 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
831 self.undo_stack.pop_front();
832 }
833 }
834 }
835
836 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
837 if self
838 .redo_stack
839 .back()
840 .map_or(true, |e| e.selections != entry.selections)
841 {
842 self.redo_stack.push_back(entry);
843 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
844 self.redo_stack.pop_front();
845 }
846 }
847 }
848}
849
850struct RowHighlight {
851 index: usize,
852 range: Range<Anchor>,
853 color: Hsla,
854 should_autoscroll: bool,
855}
856
857#[derive(Clone, Debug)]
858struct AddSelectionsState {
859 above: bool,
860 stack: Vec<usize>,
861}
862
863#[derive(Clone)]
864struct SelectNextState {
865 query: AhoCorasick,
866 wordwise: bool,
867 done: bool,
868}
869
870impl std::fmt::Debug for SelectNextState {
871 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
872 f.debug_struct(std::any::type_name::<Self>())
873 .field("wordwise", &self.wordwise)
874 .field("done", &self.done)
875 .finish()
876 }
877}
878
879#[derive(Debug)]
880struct AutocloseRegion {
881 selection_id: usize,
882 range: Range<Anchor>,
883 pair: BracketPair,
884}
885
886#[derive(Debug)]
887struct SnippetState {
888 ranges: Vec<Vec<Range<Anchor>>>,
889 active_index: usize,
890 choices: Vec<Option<Vec<String>>>,
891}
892
893#[doc(hidden)]
894pub struct RenameState {
895 pub range: Range<Anchor>,
896 pub old_name: Arc<str>,
897 pub editor: View<Editor>,
898 block_id: CustomBlockId,
899}
900
901struct InvalidationStack<T>(Vec<T>);
902
903struct RegisteredInlineCompletionProvider {
904 provider: Arc<dyn InlineCompletionProviderHandle>,
905 _subscription: Subscription,
906}
907
908enum ContextMenu {
909 Completions(CompletionsMenu),
910 CodeActions(CodeActionsMenu),
911}
912
913impl ContextMenu {
914 fn select_first(
915 &mut self,
916 provider: Option<&dyn CompletionProvider>,
917 cx: &mut ViewContext<Editor>,
918 ) -> bool {
919 if self.visible() {
920 match self {
921 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
922 ContextMenu::CodeActions(menu) => menu.select_first(cx),
923 }
924 true
925 } else {
926 false
927 }
928 }
929
930 fn select_prev(
931 &mut self,
932 provider: Option<&dyn CompletionProvider>,
933 cx: &mut ViewContext<Editor>,
934 ) -> bool {
935 if self.visible() {
936 match self {
937 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
938 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
939 }
940 true
941 } else {
942 false
943 }
944 }
945
946 fn select_next(
947 &mut self,
948 provider: Option<&dyn CompletionProvider>,
949 cx: &mut ViewContext<Editor>,
950 ) -> bool {
951 if self.visible() {
952 match self {
953 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
954 ContextMenu::CodeActions(menu) => menu.select_next(cx),
955 }
956 true
957 } else {
958 false
959 }
960 }
961
962 fn select_last(
963 &mut self,
964 provider: Option<&dyn CompletionProvider>,
965 cx: &mut ViewContext<Editor>,
966 ) -> bool {
967 if self.visible() {
968 match self {
969 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
970 ContextMenu::CodeActions(menu) => menu.select_last(cx),
971 }
972 true
973 } else {
974 false
975 }
976 }
977
978 fn visible(&self) -> bool {
979 match self {
980 ContextMenu::Completions(menu) => menu.visible(),
981 ContextMenu::CodeActions(menu) => menu.visible(),
982 }
983 }
984
985 fn render(
986 &self,
987 cursor_position: DisplayPoint,
988 style: &EditorStyle,
989 max_height: Pixels,
990 workspace: Option<WeakView<Workspace>>,
991 cx: &mut ViewContext<Editor>,
992 ) -> (ContextMenuOrigin, AnyElement) {
993 match self {
994 ContextMenu::Completions(menu) => (
995 ContextMenuOrigin::EditorPoint(cursor_position),
996 menu.render(style, max_height, workspace, cx),
997 ),
998 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
999 }
1000 }
1001}
1002
1003enum ContextMenuOrigin {
1004 EditorPoint(DisplayPoint),
1005 GutterIndicator(DisplayRow),
1006}
1007
1008#[derive(Clone, Debug)]
1009struct CompletionsMenu {
1010 id: CompletionId,
1011 sort_completions: bool,
1012 initial_position: Anchor,
1013 buffer: Model<Buffer>,
1014 completions: Arc<RwLock<Box<[Completion]>>>,
1015 match_candidates: Arc<[StringMatchCandidate]>,
1016 matches: Arc<[StringMatch]>,
1017 selected_item: usize,
1018 scroll_handle: UniformListScrollHandle,
1019 selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
1020}
1021
1022impl CompletionsMenu {
1023 fn new(
1024 id: CompletionId,
1025 sort_completions: bool,
1026 initial_position: Anchor,
1027 buffer: Model<Buffer>,
1028 completions: Box<[Completion]>,
1029 ) -> Self {
1030 let match_candidates = completions
1031 .iter()
1032 .enumerate()
1033 .map(|(id, completion)| {
1034 StringMatchCandidate::new(
1035 id,
1036 completion.label.text[completion.label.filter_range.clone()].into(),
1037 )
1038 })
1039 .collect();
1040
1041 Self {
1042 id,
1043 sort_completions,
1044 initial_position,
1045 buffer,
1046 completions: Arc::new(RwLock::new(completions)),
1047 match_candidates,
1048 matches: Vec::new().into(),
1049 selected_item: 0,
1050 scroll_handle: UniformListScrollHandle::new(),
1051 selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
1052 DebouncedDelay::new(),
1053 ))),
1054 }
1055 }
1056
1057 fn new_snippet_choices(
1058 id: CompletionId,
1059 sort_completions: bool,
1060 choices: &Vec<String>,
1061 selection: Range<Anchor>,
1062 buffer: Model<Buffer>,
1063 ) -> Self {
1064 let completions = choices
1065 .iter()
1066 .map(|choice| Completion {
1067 old_range: selection.start.text_anchor..selection.end.text_anchor,
1068 new_text: choice.to_string(),
1069 label: CodeLabel {
1070 text: choice.to_string(),
1071 runs: Default::default(),
1072 filter_range: Default::default(),
1073 },
1074 server_id: LanguageServerId(usize::MAX),
1075 documentation: None,
1076 lsp_completion: Default::default(),
1077 confirm: None,
1078 })
1079 .collect();
1080
1081 let match_candidates = choices
1082 .iter()
1083 .enumerate()
1084 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1085 .collect();
1086 let matches = choices
1087 .iter()
1088 .enumerate()
1089 .map(|(id, completion)| StringMatch {
1090 candidate_id: id,
1091 score: 1.,
1092 positions: vec![],
1093 string: completion.clone(),
1094 })
1095 .collect();
1096 Self {
1097 id,
1098 sort_completions,
1099 initial_position: selection.start,
1100 buffer,
1101 completions: Arc::new(RwLock::new(completions)),
1102 match_candidates,
1103 matches,
1104 selected_item: 0,
1105 scroll_handle: UniformListScrollHandle::new(),
1106 selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
1107 DebouncedDelay::new(),
1108 ))),
1109 }
1110 }
1111
1112 fn suppress_documentation_resolution(mut self) -> Self {
1113 self.selected_completion_documentation_resolve_debounce
1114 .take();
1115 self
1116 }
1117
1118 fn select_first(
1119 &mut self,
1120 provider: Option<&dyn CompletionProvider>,
1121 cx: &mut ViewContext<Editor>,
1122 ) {
1123 self.selected_item = 0;
1124 self.scroll_handle
1125 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1126 self.attempt_resolve_selected_completion_documentation(provider, cx);
1127 cx.notify();
1128 }
1129
1130 fn select_prev(
1131 &mut self,
1132 provider: Option<&dyn CompletionProvider>,
1133 cx: &mut ViewContext<Editor>,
1134 ) {
1135 if self.selected_item > 0 {
1136 self.selected_item -= 1;
1137 } else {
1138 self.selected_item = self.matches.len() - 1;
1139 }
1140 self.scroll_handle
1141 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1142 self.attempt_resolve_selected_completion_documentation(provider, cx);
1143 cx.notify();
1144 }
1145
1146 fn select_next(
1147 &mut self,
1148 provider: Option<&dyn CompletionProvider>,
1149 cx: &mut ViewContext<Editor>,
1150 ) {
1151 if self.selected_item + 1 < self.matches.len() {
1152 self.selected_item += 1;
1153 } else {
1154 self.selected_item = 0;
1155 }
1156 self.scroll_handle
1157 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1158 self.attempt_resolve_selected_completion_documentation(provider, cx);
1159 cx.notify();
1160 }
1161
1162 fn select_last(
1163 &mut self,
1164 provider: Option<&dyn CompletionProvider>,
1165 cx: &mut ViewContext<Editor>,
1166 ) {
1167 self.selected_item = self.matches.len() - 1;
1168 self.scroll_handle
1169 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1170 self.attempt_resolve_selected_completion_documentation(provider, cx);
1171 cx.notify();
1172 }
1173
1174 fn pre_resolve_completion_documentation(
1175 buffer: Model<Buffer>,
1176 completions: Arc<RwLock<Box<[Completion]>>>,
1177 matches: Arc<[StringMatch]>,
1178 editor: &Editor,
1179 cx: &mut ViewContext<Editor>,
1180 ) -> Task<()> {
1181 let settings = EditorSettings::get_global(cx);
1182 if !settings.show_completion_documentation {
1183 return Task::ready(());
1184 }
1185
1186 let Some(provider) = editor.completion_provider.as_ref() else {
1187 return Task::ready(());
1188 };
1189
1190 let resolve_task = provider.resolve_completions(
1191 buffer,
1192 matches.iter().map(|m| m.candidate_id).collect(),
1193 completions.clone(),
1194 cx,
1195 );
1196
1197 cx.spawn(move |this, mut cx| async move {
1198 if let Some(true) = resolve_task.await.log_err() {
1199 this.update(&mut cx, |_, cx| cx.notify()).ok();
1200 }
1201 })
1202 }
1203
1204 fn attempt_resolve_selected_completion_documentation(
1205 &mut self,
1206 provider: Option<&dyn CompletionProvider>,
1207 cx: &mut ViewContext<Editor>,
1208 ) {
1209 let settings = EditorSettings::get_global(cx);
1210 if !settings.show_completion_documentation {
1211 return;
1212 }
1213
1214 let completion_index = self.matches[self.selected_item].candidate_id;
1215 let Some(provider) = provider else {
1216 return;
1217 };
1218 let Some(documentation_resolve) = self
1219 .selected_completion_documentation_resolve_debounce
1220 .as_ref()
1221 else {
1222 return;
1223 };
1224
1225 let resolve_task = provider.resolve_completions(
1226 self.buffer.clone(),
1227 vec![completion_index],
1228 self.completions.clone(),
1229 cx,
1230 );
1231
1232 let delay_ms =
1233 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1234 let delay = Duration::from_millis(delay_ms);
1235
1236 documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
1237 cx.spawn(move |this, mut cx| async move {
1238 if let Some(true) = resolve_task.await.log_err() {
1239 this.update(&mut cx, |_, cx| cx.notify()).ok();
1240 }
1241 })
1242 });
1243 }
1244
1245 fn visible(&self) -> bool {
1246 !self.matches.is_empty()
1247 }
1248
1249 fn render(
1250 &self,
1251 style: &EditorStyle,
1252 max_height: Pixels,
1253 workspace: Option<WeakView<Workspace>>,
1254 cx: &mut ViewContext<Editor>,
1255 ) -> AnyElement {
1256 let settings = EditorSettings::get_global(cx);
1257 let show_completion_documentation = settings.show_completion_documentation;
1258
1259 let widest_completion_ix = self
1260 .matches
1261 .iter()
1262 .enumerate()
1263 .max_by_key(|(_, mat)| {
1264 let completions = self.completions.read();
1265 let completion = &completions[mat.candidate_id];
1266 let documentation = &completion.documentation;
1267
1268 let mut len = completion.label.text.chars().count();
1269 if let Some(Documentation::SingleLine(text)) = documentation {
1270 if show_completion_documentation {
1271 len += text.chars().count();
1272 }
1273 }
1274
1275 len
1276 })
1277 .map(|(ix, _)| ix);
1278
1279 let completions = self.completions.clone();
1280 let matches = self.matches.clone();
1281 let selected_item = self.selected_item;
1282 let style = style.clone();
1283
1284 let multiline_docs = if show_completion_documentation {
1285 let mat = &self.matches[selected_item];
1286 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1287 Some(Documentation::MultiLinePlainText(text)) => {
1288 Some(div().child(SharedString::from(text.clone())))
1289 }
1290 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1291 Some(div().child(render_parsed_markdown(
1292 "completions_markdown",
1293 parsed,
1294 &style,
1295 workspace,
1296 cx,
1297 )))
1298 }
1299 _ => None,
1300 };
1301 multiline_docs.map(|div| {
1302 div.id("multiline_docs")
1303 .max_h(max_height)
1304 .flex_1()
1305 .px_1p5()
1306 .py_1()
1307 .min_w(px(260.))
1308 .max_w(px(640.))
1309 .w(px(500.))
1310 .overflow_y_scroll()
1311 .occlude()
1312 })
1313 } else {
1314 None
1315 };
1316
1317 let list = uniform_list(
1318 cx.view().clone(),
1319 "completions",
1320 matches.len(),
1321 move |_editor, range, cx| {
1322 let start_ix = range.start;
1323 let completions_guard = completions.read();
1324
1325 matches[range]
1326 .iter()
1327 .enumerate()
1328 .map(|(ix, mat)| {
1329 let item_ix = start_ix + ix;
1330 let candidate_id = mat.candidate_id;
1331 let completion = &completions_guard[candidate_id];
1332
1333 let documentation = if show_completion_documentation {
1334 &completion.documentation
1335 } else {
1336 &None
1337 };
1338
1339 let highlights = gpui::combine_highlights(
1340 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1341 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1342 |(range, mut highlight)| {
1343 // Ignore font weight for syntax highlighting, as we'll use it
1344 // for fuzzy matches.
1345 highlight.font_weight = None;
1346
1347 if completion.lsp_completion.deprecated.unwrap_or(false) {
1348 highlight.strikethrough = Some(StrikethroughStyle {
1349 thickness: 1.0.into(),
1350 ..Default::default()
1351 });
1352 highlight.color = Some(cx.theme().colors().text_muted);
1353 }
1354
1355 (range, highlight)
1356 },
1357 ),
1358 );
1359 let completion_label = StyledText::new(completion.label.text.clone())
1360 .with_highlights(&style.text, highlights);
1361 let documentation_label =
1362 if let Some(Documentation::SingleLine(text)) = documentation {
1363 if text.trim().is_empty() {
1364 None
1365 } else {
1366 Some(
1367 Label::new(text.clone())
1368 .ml_4()
1369 .size(LabelSize::Small)
1370 .color(Color::Muted),
1371 )
1372 }
1373 } else {
1374 None
1375 };
1376
1377 let color_swatch = completion
1378 .color()
1379 .map(|color| div().size_4().bg(color).rounded_sm());
1380
1381 div().min_w(px(220.)).max_w(px(540.)).child(
1382 ListItem::new(mat.candidate_id)
1383 .inset(true)
1384 .selected(item_ix == selected_item)
1385 .on_click(cx.listener(move |editor, _event, cx| {
1386 cx.stop_propagation();
1387 if let Some(task) = editor.confirm_completion(
1388 &ConfirmCompletion {
1389 item_ix: Some(item_ix),
1390 },
1391 cx,
1392 ) {
1393 task.detach_and_log_err(cx)
1394 }
1395 }))
1396 .start_slot::<Div>(color_swatch)
1397 .child(h_flex().overflow_hidden().child(completion_label))
1398 .end_slot::<Label>(documentation_label),
1399 )
1400 })
1401 .collect()
1402 },
1403 )
1404 .occlude()
1405 .max_h(max_height)
1406 .track_scroll(self.scroll_handle.clone())
1407 .with_width_from_item(widest_completion_ix)
1408 .with_sizing_behavior(ListSizingBehavior::Infer);
1409
1410 Popover::new()
1411 .child(list)
1412 .when_some(multiline_docs, |popover, multiline_docs| {
1413 popover.aside(multiline_docs)
1414 })
1415 .into_any_element()
1416 }
1417
1418 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1419 let mut matches = if let Some(query) = query {
1420 fuzzy::match_strings(
1421 &self.match_candidates,
1422 query,
1423 query.chars().any(|c| c.is_uppercase()),
1424 100,
1425 &Default::default(),
1426 executor,
1427 )
1428 .await
1429 } else {
1430 self.match_candidates
1431 .iter()
1432 .enumerate()
1433 .map(|(candidate_id, candidate)| StringMatch {
1434 candidate_id,
1435 score: Default::default(),
1436 positions: Default::default(),
1437 string: candidate.string.clone(),
1438 })
1439 .collect()
1440 };
1441
1442 // Remove all candidates where the query's start does not match the start of any word in the candidate
1443 if let Some(query) = query {
1444 if let Some(query_start) = query.chars().next() {
1445 matches.retain(|string_match| {
1446 split_words(&string_match.string).any(|word| {
1447 // Check that the first codepoint of the word as lowercase matches the first
1448 // codepoint of the query as lowercase
1449 word.chars()
1450 .flat_map(|codepoint| codepoint.to_lowercase())
1451 .zip(query_start.to_lowercase())
1452 .all(|(word_cp, query_cp)| word_cp == query_cp)
1453 })
1454 });
1455 }
1456 }
1457
1458 let completions = self.completions.read();
1459 if self.sort_completions {
1460 matches.sort_unstable_by_key(|mat| {
1461 // We do want to strike a balance here between what the language server tells us
1462 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1463 // `Creat` and there is a local variable called `CreateComponent`).
1464 // So what we do is: we bucket all matches into two buckets
1465 // - Strong matches
1466 // - Weak matches
1467 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1468 // and the Weak matches are the rest.
1469 //
1470 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1471 // matches, we prefer language-server sort_text first.
1472 //
1473 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1474 // Rest of the matches(weak) can be sorted as language-server expects.
1475
1476 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1477 enum MatchScore<'a> {
1478 Strong {
1479 score: Reverse<OrderedFloat<f64>>,
1480 sort_text: Option<&'a str>,
1481 sort_key: (usize, &'a str),
1482 },
1483 Weak {
1484 sort_text: Option<&'a str>,
1485 score: Reverse<OrderedFloat<f64>>,
1486 sort_key: (usize, &'a str),
1487 },
1488 }
1489
1490 let completion = &completions[mat.candidate_id];
1491 let sort_key = completion.sort_key();
1492 let sort_text = completion.lsp_completion.sort_text.as_deref();
1493 let score = Reverse(OrderedFloat(mat.score));
1494
1495 if mat.score >= 0.2 {
1496 MatchScore::Strong {
1497 score,
1498 sort_text,
1499 sort_key,
1500 }
1501 } else {
1502 MatchScore::Weak {
1503 sort_text,
1504 score,
1505 sort_key,
1506 }
1507 }
1508 });
1509 }
1510
1511 for mat in &mut matches {
1512 let completion = &completions[mat.candidate_id];
1513 mat.string.clone_from(&completion.label.text);
1514 for position in &mut mat.positions {
1515 *position += completion.label.filter_range.start;
1516 }
1517 }
1518 drop(completions);
1519
1520 self.matches = matches.into();
1521 self.selected_item = 0;
1522 }
1523}
1524
1525#[derive(Clone)]
1526struct AvailableCodeAction {
1527 excerpt_id: ExcerptId,
1528 action: CodeAction,
1529 provider: Arc<dyn CodeActionProvider>,
1530}
1531
1532#[derive(Clone)]
1533struct CodeActionContents {
1534 tasks: Option<Arc<ResolvedTasks>>,
1535 actions: Option<Arc<[AvailableCodeAction]>>,
1536}
1537
1538impl CodeActionContents {
1539 fn len(&self) -> usize {
1540 match (&self.tasks, &self.actions) {
1541 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1542 (Some(tasks), None) => tasks.templates.len(),
1543 (None, Some(actions)) => actions.len(),
1544 (None, None) => 0,
1545 }
1546 }
1547
1548 fn is_empty(&self) -> bool {
1549 match (&self.tasks, &self.actions) {
1550 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1551 (Some(tasks), None) => tasks.templates.is_empty(),
1552 (None, Some(actions)) => actions.is_empty(),
1553 (None, None) => true,
1554 }
1555 }
1556
1557 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1558 self.tasks
1559 .iter()
1560 .flat_map(|tasks| {
1561 tasks
1562 .templates
1563 .iter()
1564 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1565 })
1566 .chain(self.actions.iter().flat_map(|actions| {
1567 actions.iter().map(|available| CodeActionsItem::CodeAction {
1568 excerpt_id: available.excerpt_id,
1569 action: available.action.clone(),
1570 provider: available.provider.clone(),
1571 })
1572 }))
1573 }
1574 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1575 match (&self.tasks, &self.actions) {
1576 (Some(tasks), Some(actions)) => {
1577 if index < tasks.templates.len() {
1578 tasks
1579 .templates
1580 .get(index)
1581 .cloned()
1582 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1583 } else {
1584 actions.get(index - tasks.templates.len()).map(|available| {
1585 CodeActionsItem::CodeAction {
1586 excerpt_id: available.excerpt_id,
1587 action: available.action.clone(),
1588 provider: available.provider.clone(),
1589 }
1590 })
1591 }
1592 }
1593 (Some(tasks), None) => tasks
1594 .templates
1595 .get(index)
1596 .cloned()
1597 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1598 (None, Some(actions)) => {
1599 actions
1600 .get(index)
1601 .map(|available| CodeActionsItem::CodeAction {
1602 excerpt_id: available.excerpt_id,
1603 action: available.action.clone(),
1604 provider: available.provider.clone(),
1605 })
1606 }
1607 (None, None) => None,
1608 }
1609 }
1610}
1611
1612#[allow(clippy::large_enum_variant)]
1613#[derive(Clone)]
1614enum CodeActionsItem {
1615 Task(TaskSourceKind, ResolvedTask),
1616 CodeAction {
1617 excerpt_id: ExcerptId,
1618 action: CodeAction,
1619 provider: Arc<dyn CodeActionProvider>,
1620 },
1621}
1622
1623impl CodeActionsItem {
1624 fn as_task(&self) -> Option<&ResolvedTask> {
1625 let Self::Task(_, task) = self else {
1626 return None;
1627 };
1628 Some(task)
1629 }
1630 fn as_code_action(&self) -> Option<&CodeAction> {
1631 let Self::CodeAction { action, .. } = self else {
1632 return None;
1633 };
1634 Some(action)
1635 }
1636 fn label(&self) -> String {
1637 match self {
1638 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1639 Self::Task(_, task) => task.resolved_label.clone(),
1640 }
1641 }
1642}
1643
1644struct CodeActionsMenu {
1645 actions: CodeActionContents,
1646 buffer: Model<Buffer>,
1647 selected_item: usize,
1648 scroll_handle: UniformListScrollHandle,
1649 deployed_from_indicator: Option<DisplayRow>,
1650}
1651
1652impl CodeActionsMenu {
1653 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1654 self.selected_item = 0;
1655 self.scroll_handle
1656 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1657 cx.notify()
1658 }
1659
1660 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1661 if self.selected_item > 0 {
1662 self.selected_item -= 1;
1663 } else {
1664 self.selected_item = self.actions.len() - 1;
1665 }
1666 self.scroll_handle
1667 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1668 cx.notify();
1669 }
1670
1671 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1672 if self.selected_item + 1 < self.actions.len() {
1673 self.selected_item += 1;
1674 } else {
1675 self.selected_item = 0;
1676 }
1677 self.scroll_handle
1678 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1679 cx.notify();
1680 }
1681
1682 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1683 self.selected_item = self.actions.len() - 1;
1684 self.scroll_handle
1685 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1686 cx.notify()
1687 }
1688
1689 fn visible(&self) -> bool {
1690 !self.actions.is_empty()
1691 }
1692
1693 fn render(
1694 &self,
1695 cursor_position: DisplayPoint,
1696 _style: &EditorStyle,
1697 max_height: Pixels,
1698 cx: &mut ViewContext<Editor>,
1699 ) -> (ContextMenuOrigin, AnyElement) {
1700 let actions = self.actions.clone();
1701 let selected_item = self.selected_item;
1702 let element = uniform_list(
1703 cx.view().clone(),
1704 "code_actions_menu",
1705 self.actions.len(),
1706 move |_this, range, cx| {
1707 actions
1708 .iter()
1709 .skip(range.start)
1710 .take(range.end - range.start)
1711 .enumerate()
1712 .map(|(ix, action)| {
1713 let item_ix = range.start + ix;
1714 let selected = selected_item == item_ix;
1715 let colors = cx.theme().colors();
1716 div()
1717 .px_1()
1718 .rounded_md()
1719 .text_color(colors.text)
1720 .when(selected, |style| {
1721 style
1722 .bg(colors.element_active)
1723 .text_color(colors.text_accent)
1724 })
1725 .hover(|style| {
1726 style
1727 .bg(colors.element_hover)
1728 .text_color(colors.text_accent)
1729 })
1730 .whitespace_nowrap()
1731 .when_some(action.as_code_action(), |this, action| {
1732 this.on_mouse_down(
1733 MouseButton::Left,
1734 cx.listener(move |editor, _, cx| {
1735 cx.stop_propagation();
1736 if let Some(task) = editor.confirm_code_action(
1737 &ConfirmCodeAction {
1738 item_ix: Some(item_ix),
1739 },
1740 cx,
1741 ) {
1742 task.detach_and_log_err(cx)
1743 }
1744 }),
1745 )
1746 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1747 .child(SharedString::from(action.lsp_action.title.clone()))
1748 })
1749 .when_some(action.as_task(), |this, task| {
1750 this.on_mouse_down(
1751 MouseButton::Left,
1752 cx.listener(move |editor, _, cx| {
1753 cx.stop_propagation();
1754 if let Some(task) = editor.confirm_code_action(
1755 &ConfirmCodeAction {
1756 item_ix: Some(item_ix),
1757 },
1758 cx,
1759 ) {
1760 task.detach_and_log_err(cx)
1761 }
1762 }),
1763 )
1764 .child(SharedString::from(task.resolved_label.clone()))
1765 })
1766 })
1767 .collect()
1768 },
1769 )
1770 .elevation_1(cx)
1771 .p_1()
1772 .max_h(max_height)
1773 .occlude()
1774 .track_scroll(self.scroll_handle.clone())
1775 .with_width_from_item(
1776 self.actions
1777 .iter()
1778 .enumerate()
1779 .max_by_key(|(_, action)| match action {
1780 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1781 CodeActionsItem::CodeAction { action, .. } => {
1782 action.lsp_action.title.chars().count()
1783 }
1784 })
1785 .map(|(ix, _)| ix),
1786 )
1787 .with_sizing_behavior(ListSizingBehavior::Infer)
1788 .into_any_element();
1789
1790 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1791 ContextMenuOrigin::GutterIndicator(row)
1792 } else {
1793 ContextMenuOrigin::EditorPoint(cursor_position)
1794 };
1795
1796 (cursor_position, element)
1797 }
1798}
1799
1800#[derive(Debug)]
1801struct ActiveDiagnosticGroup {
1802 primary_range: Range<Anchor>,
1803 primary_message: String,
1804 group_id: usize,
1805 blocks: HashMap<CustomBlockId, Diagnostic>,
1806 is_valid: bool,
1807}
1808
1809#[derive(Serialize, Deserialize, Clone, Debug)]
1810pub struct ClipboardSelection {
1811 pub len: usize,
1812 pub is_entire_line: bool,
1813 pub first_line_indent: u32,
1814}
1815
1816#[derive(Debug)]
1817pub(crate) struct NavigationData {
1818 cursor_anchor: Anchor,
1819 cursor_position: Point,
1820 scroll_anchor: ScrollAnchor,
1821 scroll_top_row: u32,
1822}
1823
1824#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1825pub enum GotoDefinitionKind {
1826 Symbol,
1827 Declaration,
1828 Type,
1829 Implementation,
1830}
1831
1832#[derive(Debug, Clone)]
1833enum InlayHintRefreshReason {
1834 Toggle(bool),
1835 SettingsChange(InlayHintSettings),
1836 NewLinesShown,
1837 BufferEdited(HashSet<Arc<Language>>),
1838 RefreshRequested,
1839 ExcerptsRemoved(Vec<ExcerptId>),
1840}
1841
1842impl InlayHintRefreshReason {
1843 fn description(&self) -> &'static str {
1844 match self {
1845 Self::Toggle(_) => "toggle",
1846 Self::SettingsChange(_) => "settings change",
1847 Self::NewLinesShown => "new lines shown",
1848 Self::BufferEdited(_) => "buffer edited",
1849 Self::RefreshRequested => "refresh requested",
1850 Self::ExcerptsRemoved(_) => "excerpts removed",
1851 }
1852 }
1853}
1854
1855pub(crate) struct FocusedBlock {
1856 id: BlockId,
1857 focus_handle: WeakFocusHandle,
1858}
1859
1860#[derive(Clone)]
1861struct JumpData {
1862 excerpt_id: ExcerptId,
1863 position: Point,
1864 anchor: text::Anchor,
1865 path: Option<project::ProjectPath>,
1866 line_offset_from_top: u32,
1867}
1868
1869impl Editor {
1870 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1871 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1872 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1873 Self::new(
1874 EditorMode::SingleLine { auto_width: false },
1875 buffer,
1876 None,
1877 false,
1878 cx,
1879 )
1880 }
1881
1882 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1883 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1884 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1885 Self::new(EditorMode::Full, buffer, None, false, cx)
1886 }
1887
1888 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1889 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1890 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1891 Self::new(
1892 EditorMode::SingleLine { auto_width: true },
1893 buffer,
1894 None,
1895 false,
1896 cx,
1897 )
1898 }
1899
1900 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1901 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1902 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1903 Self::new(
1904 EditorMode::AutoHeight { max_lines },
1905 buffer,
1906 None,
1907 false,
1908 cx,
1909 )
1910 }
1911
1912 pub fn for_buffer(
1913 buffer: Model<Buffer>,
1914 project: Option<Model<Project>>,
1915 cx: &mut ViewContext<Self>,
1916 ) -> Self {
1917 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1918 Self::new(EditorMode::Full, buffer, project, false, cx)
1919 }
1920
1921 pub fn for_multibuffer(
1922 buffer: Model<MultiBuffer>,
1923 project: Option<Model<Project>>,
1924 show_excerpt_controls: bool,
1925 cx: &mut ViewContext<Self>,
1926 ) -> Self {
1927 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1928 }
1929
1930 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1931 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1932 let mut clone = Self::new(
1933 self.mode,
1934 self.buffer.clone(),
1935 self.project.clone(),
1936 show_excerpt_controls,
1937 cx,
1938 );
1939 self.display_map.update(cx, |display_map, cx| {
1940 let snapshot = display_map.snapshot(cx);
1941 clone.display_map.update(cx, |display_map, cx| {
1942 display_map.set_state(&snapshot, cx);
1943 });
1944 });
1945 clone.selections.clone_state(&self.selections);
1946 clone.scroll_manager.clone_state(&self.scroll_manager);
1947 clone.searchable = self.searchable;
1948 clone
1949 }
1950
1951 pub fn new(
1952 mode: EditorMode,
1953 buffer: Model<MultiBuffer>,
1954 project: Option<Model<Project>>,
1955 show_excerpt_controls: bool,
1956 cx: &mut ViewContext<Self>,
1957 ) -> Self {
1958 let style = cx.text_style();
1959 let font_size = style.font_size.to_pixels(cx.rem_size());
1960 let editor = cx.view().downgrade();
1961 let fold_placeholder = FoldPlaceholder {
1962 constrain_width: true,
1963 render: Arc::new(move |fold_id, fold_range, cx| {
1964 let editor = editor.clone();
1965 div()
1966 .id(fold_id)
1967 .bg(cx.theme().colors().ghost_element_background)
1968 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1969 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1970 .rounded_sm()
1971 .size_full()
1972 .cursor_pointer()
1973 .child("⋯")
1974 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1975 .on_click(move |_, cx| {
1976 editor
1977 .update(cx, |editor, cx| {
1978 editor.unfold_ranges(
1979 &[fold_range.start..fold_range.end],
1980 true,
1981 false,
1982 cx,
1983 );
1984 cx.stop_propagation();
1985 })
1986 .ok();
1987 })
1988 .into_any()
1989 }),
1990 merge_adjacent: true,
1991 ..Default::default()
1992 };
1993 let display_map = cx.new_model(|cx| {
1994 DisplayMap::new(
1995 buffer.clone(),
1996 style.font(),
1997 font_size,
1998 None,
1999 show_excerpt_controls,
2000 FILE_HEADER_HEIGHT,
2001 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
2002 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
2003 fold_placeholder,
2004 cx,
2005 )
2006 });
2007
2008 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
2009
2010 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
2011
2012 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
2013 .then(|| language_settings::SoftWrap::None);
2014
2015 let mut project_subscriptions = Vec::new();
2016 if mode == EditorMode::Full {
2017 if let Some(project) = project.as_ref() {
2018 if buffer.read(cx).is_singleton() {
2019 project_subscriptions.push(cx.observe(project, |_, _, cx| {
2020 cx.emit(EditorEvent::TitleChanged);
2021 }));
2022 }
2023 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
2024 if let project::Event::RefreshInlayHints = event {
2025 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
2026 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
2027 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
2028 let focus_handle = editor.focus_handle(cx);
2029 if focus_handle.is_focused(cx) {
2030 let snapshot = buffer.read(cx).snapshot();
2031 for (range, snippet) in snippet_edits {
2032 let editor_range =
2033 language::range_from_lsp(*range).to_offset(&snapshot);
2034 editor
2035 .insert_snippet(&[editor_range], snippet.clone(), cx)
2036 .ok();
2037 }
2038 }
2039 }
2040 }
2041 }));
2042 if let Some(task_inventory) = project
2043 .read(cx)
2044 .task_store()
2045 .read(cx)
2046 .task_inventory()
2047 .cloned()
2048 {
2049 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
2050 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
2051 }));
2052 }
2053 }
2054 }
2055
2056 let inlay_hint_settings = inlay_hint_settings(
2057 selections.newest_anchor().head(),
2058 &buffer.read(cx).snapshot(cx),
2059 cx,
2060 );
2061 let focus_handle = cx.focus_handle();
2062 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2063 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2064 .detach();
2065 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2066 .detach();
2067 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2068
2069 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2070 Some(false)
2071 } else {
2072 None
2073 };
2074
2075 let mut code_action_providers = Vec::new();
2076 if let Some(project) = project.clone() {
2077 code_action_providers.push(Arc::new(project) as Arc<_>);
2078 }
2079
2080 let mut this = Self {
2081 focus_handle,
2082 show_cursor_when_unfocused: false,
2083 last_focused_descendant: None,
2084 buffer: buffer.clone(),
2085 display_map: display_map.clone(),
2086 selections,
2087 scroll_manager: ScrollManager::new(cx),
2088 columnar_selection_tail: None,
2089 add_selections_state: None,
2090 select_next_state: None,
2091 select_prev_state: None,
2092 selection_history: Default::default(),
2093 autoclose_regions: Default::default(),
2094 snippet_stack: Default::default(),
2095 select_larger_syntax_node_stack: Vec::new(),
2096 ime_transaction: Default::default(),
2097 active_diagnostics: None,
2098 soft_wrap_mode_override,
2099 completion_provider: project.clone().map(|project| Box::new(project) as _),
2100 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2101 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2102 project,
2103 blink_manager: blink_manager.clone(),
2104 show_local_selections: true,
2105 mode,
2106 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2107 show_gutter: mode == EditorMode::Full,
2108 show_line_numbers: None,
2109 use_relative_line_numbers: None,
2110 show_git_diff_gutter: None,
2111 show_code_actions: None,
2112 show_runnables: None,
2113 show_wrap_guides: None,
2114 show_indent_guides,
2115 placeholder_text: None,
2116 highlight_order: 0,
2117 highlighted_rows: HashMap::default(),
2118 background_highlights: Default::default(),
2119 gutter_highlights: TreeMap::default(),
2120 scrollbar_marker_state: ScrollbarMarkerState::default(),
2121 active_indent_guides_state: ActiveIndentGuidesState::default(),
2122 nav_history: None,
2123 context_menu: RwLock::new(None),
2124 mouse_context_menu: None,
2125 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2126 completion_tasks: Default::default(),
2127 signature_help_state: SignatureHelpState::default(),
2128 auto_signature_help: None,
2129 find_all_references_task_sources: Vec::new(),
2130 next_completion_id: 0,
2131 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2132 next_inlay_id: 0,
2133 code_action_providers,
2134 available_code_actions: Default::default(),
2135 code_actions_task: Default::default(),
2136 document_highlights_task: Default::default(),
2137 linked_editing_range_task: Default::default(),
2138 pending_rename: Default::default(),
2139 searchable: true,
2140 cursor_shape: EditorSettings::get_global(cx)
2141 .cursor_shape
2142 .unwrap_or_default(),
2143 current_line_highlight: None,
2144 autoindent_mode: Some(AutoindentMode::EachLine),
2145 collapse_matches: false,
2146 workspace: None,
2147 input_enabled: true,
2148 use_modal_editing: mode == EditorMode::Full,
2149 read_only: false,
2150 use_autoclose: true,
2151 use_auto_surround: true,
2152 auto_replace_emoji_shortcode: false,
2153 leader_peer_id: None,
2154 remote_id: None,
2155 hover_state: Default::default(),
2156 hovered_link_state: Default::default(),
2157 inline_completion_provider: None,
2158 active_inline_completion: None,
2159 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2160 expanded_hunks: ExpandedHunks::default(),
2161 gutter_hovered: false,
2162 pixel_position_of_newest_cursor: None,
2163 last_bounds: None,
2164 expect_bounds_change: None,
2165 gutter_dimensions: GutterDimensions::default(),
2166 style: None,
2167 show_cursor_names: false,
2168 hovered_cursors: Default::default(),
2169 next_editor_action_id: EditorActionId::default(),
2170 editor_actions: Rc::default(),
2171 show_inline_completions_override: None,
2172 enable_inline_completions: true,
2173 custom_context_menu: None,
2174 show_git_blame_gutter: false,
2175 show_git_blame_inline: false,
2176 show_selection_menu: None,
2177 show_git_blame_inline_delay_task: None,
2178 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2179 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2180 .session
2181 .restore_unsaved_buffers,
2182 blame: None,
2183 blame_subscription: None,
2184 tasks: Default::default(),
2185 _subscriptions: vec![
2186 cx.observe(&buffer, Self::on_buffer_changed),
2187 cx.subscribe(&buffer, Self::on_buffer_event),
2188 cx.observe(&display_map, Self::on_display_map_changed),
2189 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2190 cx.observe_global::<SettingsStore>(Self::settings_changed),
2191 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2192 cx.observe_window_activation(|editor, cx| {
2193 let active = cx.is_window_active();
2194 editor.blink_manager.update(cx, |blink_manager, cx| {
2195 if active {
2196 blink_manager.enable(cx);
2197 } else {
2198 blink_manager.disable(cx);
2199 }
2200 });
2201 }),
2202 ],
2203 tasks_update_task: None,
2204 linked_edit_ranges: Default::default(),
2205 previous_search_ranges: None,
2206 breadcrumb_header: None,
2207 focused_block: None,
2208 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2209 addons: HashMap::default(),
2210 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2211 text_style_refinement: None,
2212 active_line_trailer_provider: None,
2213 };
2214 this.tasks_update_task = Some(this.refresh_runnables(cx));
2215 this._subscriptions.extend(project_subscriptions);
2216
2217 this.end_selection(cx);
2218 this.scroll_manager.show_scrollbar(cx);
2219
2220 if mode == EditorMode::Full {
2221 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2222 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2223
2224 if this.git_blame_inline_enabled {
2225 this.git_blame_inline_enabled = true;
2226 this.start_git_blame_inline(false, cx);
2227 }
2228 }
2229
2230 this.report_editor_event("open", None, cx);
2231 this
2232 }
2233
2234 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2235 self.mouse_context_menu
2236 .as_ref()
2237 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2238 }
2239
2240 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2241 let mut key_context = KeyContext::new_with_defaults();
2242 key_context.add("Editor");
2243 let mode = match self.mode {
2244 EditorMode::SingleLine { .. } => "single_line",
2245 EditorMode::AutoHeight { .. } => "auto_height",
2246 EditorMode::Full => "full",
2247 };
2248
2249 if EditorSettings::jupyter_enabled(cx) {
2250 key_context.add("jupyter");
2251 }
2252
2253 key_context.set("mode", mode);
2254 if self.pending_rename.is_some() {
2255 key_context.add("renaming");
2256 }
2257 if self.context_menu_visible() {
2258 match self.context_menu.read().as_ref() {
2259 Some(ContextMenu::Completions(_)) => {
2260 key_context.add("menu");
2261 key_context.add("showing_completions")
2262 }
2263 Some(ContextMenu::CodeActions(_)) => {
2264 key_context.add("menu");
2265 key_context.add("showing_code_actions")
2266 }
2267 None => {}
2268 }
2269 }
2270
2271 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2272 if !self.focus_handle(cx).contains_focused(cx)
2273 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2274 {
2275 for addon in self.addons.values() {
2276 addon.extend_key_context(&mut key_context, cx)
2277 }
2278 }
2279
2280 if let Some(extension) = self
2281 .buffer
2282 .read(cx)
2283 .as_singleton()
2284 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2285 {
2286 key_context.set("extension", extension.to_string());
2287 }
2288
2289 if self.has_active_inline_completion(cx) {
2290 key_context.add("copilot_suggestion");
2291 key_context.add("inline_completion");
2292 }
2293
2294 key_context
2295 }
2296
2297 pub fn new_file(
2298 workspace: &mut Workspace,
2299 _: &workspace::NewFile,
2300 cx: &mut ViewContext<Workspace>,
2301 ) {
2302 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2303 "Failed to create buffer",
2304 cx,
2305 |e, _| match e.error_code() {
2306 ErrorCode::RemoteUpgradeRequired => Some(format!(
2307 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2308 e.error_tag("required").unwrap_or("the latest version")
2309 )),
2310 _ => None,
2311 },
2312 );
2313 }
2314
2315 pub fn new_in_workspace(
2316 workspace: &mut Workspace,
2317 cx: &mut ViewContext<Workspace>,
2318 ) -> Task<Result<View<Editor>>> {
2319 let project = workspace.project().clone();
2320 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2321
2322 cx.spawn(|workspace, mut cx| async move {
2323 let buffer = create.await?;
2324 workspace.update(&mut cx, |workspace, cx| {
2325 let editor =
2326 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2327 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2328 editor
2329 })
2330 })
2331 }
2332
2333 fn new_file_vertical(
2334 workspace: &mut Workspace,
2335 _: &workspace::NewFileSplitVertical,
2336 cx: &mut ViewContext<Workspace>,
2337 ) {
2338 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2339 }
2340
2341 fn new_file_horizontal(
2342 workspace: &mut Workspace,
2343 _: &workspace::NewFileSplitHorizontal,
2344 cx: &mut ViewContext<Workspace>,
2345 ) {
2346 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2347 }
2348
2349 fn new_file_in_direction(
2350 workspace: &mut Workspace,
2351 direction: SplitDirection,
2352 cx: &mut ViewContext<Workspace>,
2353 ) {
2354 let project = workspace.project().clone();
2355 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2356
2357 cx.spawn(|workspace, mut cx| async move {
2358 let buffer = create.await?;
2359 workspace.update(&mut cx, move |workspace, cx| {
2360 workspace.split_item(
2361 direction,
2362 Box::new(
2363 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2364 ),
2365 cx,
2366 )
2367 })?;
2368 anyhow::Ok(())
2369 })
2370 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2371 ErrorCode::RemoteUpgradeRequired => Some(format!(
2372 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2373 e.error_tag("required").unwrap_or("the latest version")
2374 )),
2375 _ => None,
2376 });
2377 }
2378
2379 pub fn leader_peer_id(&self) -> Option<PeerId> {
2380 self.leader_peer_id
2381 }
2382
2383 pub fn buffer(&self) -> &Model<MultiBuffer> {
2384 &self.buffer
2385 }
2386
2387 pub fn workspace(&self) -> Option<View<Workspace>> {
2388 self.workspace.as_ref()?.0.upgrade()
2389 }
2390
2391 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2392 self.buffer().read(cx).title(cx)
2393 }
2394
2395 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2396 let git_blame_gutter_max_author_length = self
2397 .render_git_blame_gutter(cx)
2398 .then(|| {
2399 if let Some(blame) = self.blame.as_ref() {
2400 let max_author_length =
2401 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2402 Some(max_author_length)
2403 } else {
2404 None
2405 }
2406 })
2407 .flatten();
2408
2409 EditorSnapshot {
2410 mode: self.mode,
2411 show_gutter: self.show_gutter,
2412 show_line_numbers: self.show_line_numbers,
2413 show_git_diff_gutter: self.show_git_diff_gutter,
2414 show_code_actions: self.show_code_actions,
2415 show_runnables: self.show_runnables,
2416 git_blame_gutter_max_author_length,
2417 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2418 scroll_anchor: self.scroll_manager.anchor(),
2419 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2420 placeholder_text: self.placeholder_text.clone(),
2421 is_focused: self.focus_handle.is_focused(cx),
2422 current_line_highlight: self
2423 .current_line_highlight
2424 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2425 gutter_hovered: self.gutter_hovered,
2426 }
2427 }
2428
2429 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2430 self.buffer.read(cx).language_at(point, cx)
2431 }
2432
2433 pub fn file_at<T: ToOffset>(
2434 &self,
2435 point: T,
2436 cx: &AppContext,
2437 ) -> Option<Arc<dyn language::File>> {
2438 self.buffer.read(cx).read(cx).file_at(point).cloned()
2439 }
2440
2441 pub fn active_excerpt(
2442 &self,
2443 cx: &AppContext,
2444 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2445 self.buffer
2446 .read(cx)
2447 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2448 }
2449
2450 pub fn mode(&self) -> EditorMode {
2451 self.mode
2452 }
2453
2454 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2455 self.collaboration_hub.as_deref()
2456 }
2457
2458 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2459 self.collaboration_hub = Some(hub);
2460 }
2461
2462 pub fn set_custom_context_menu(
2463 &mut self,
2464 f: impl 'static
2465 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2466 ) {
2467 self.custom_context_menu = Some(Box::new(f))
2468 }
2469
2470 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2471 self.completion_provider = provider;
2472 }
2473
2474 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2475 self.semantics_provider.clone()
2476 }
2477
2478 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2479 self.semantics_provider = provider;
2480 }
2481
2482 pub fn set_inline_completion_provider<T>(
2483 &mut self,
2484 provider: Option<Model<T>>,
2485 cx: &mut ViewContext<Self>,
2486 ) where
2487 T: InlineCompletionProvider,
2488 {
2489 self.inline_completion_provider =
2490 provider.map(|provider| RegisteredInlineCompletionProvider {
2491 _subscription: cx.observe(&provider, |this, _, cx| {
2492 if this.focus_handle.is_focused(cx) {
2493 this.update_visible_inline_completion(cx);
2494 }
2495 }),
2496 provider: Arc::new(provider),
2497 });
2498 self.refresh_inline_completion(false, false, cx);
2499 }
2500
2501 pub fn set_active_line_trailer_provider<T>(
2502 &mut self,
2503 provider: Option<T>,
2504 _cx: &mut ViewContext<Self>,
2505 ) where
2506 T: ActiveLineTrailerProvider + 'static,
2507 {
2508 self.active_line_trailer_provider = provider.map(|provider| Box::new(provider) as Box<_>);
2509 }
2510
2511 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2512 self.placeholder_text.as_deref()
2513 }
2514
2515 pub fn set_placeholder_text(
2516 &mut self,
2517 placeholder_text: impl Into<Arc<str>>,
2518 cx: &mut ViewContext<Self>,
2519 ) {
2520 let placeholder_text = Some(placeholder_text.into());
2521 if self.placeholder_text != placeholder_text {
2522 self.placeholder_text = placeholder_text;
2523 cx.notify();
2524 }
2525 }
2526
2527 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2528 self.cursor_shape = cursor_shape;
2529
2530 // Disrupt blink for immediate user feedback that the cursor shape has changed
2531 self.blink_manager.update(cx, BlinkManager::show_cursor);
2532
2533 cx.notify();
2534 }
2535
2536 pub fn set_current_line_highlight(
2537 &mut self,
2538 current_line_highlight: Option<CurrentLineHighlight>,
2539 ) {
2540 self.current_line_highlight = current_line_highlight;
2541 }
2542
2543 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2544 self.collapse_matches = collapse_matches;
2545 }
2546
2547 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2548 if self.collapse_matches {
2549 return range.start..range.start;
2550 }
2551 range.clone()
2552 }
2553
2554 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2555 if self.display_map.read(cx).clip_at_line_ends != clip {
2556 self.display_map
2557 .update(cx, |map, _| map.clip_at_line_ends = clip);
2558 }
2559 }
2560
2561 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2562 self.input_enabled = input_enabled;
2563 }
2564
2565 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2566 self.enable_inline_completions = enabled;
2567 }
2568
2569 pub fn set_autoindent(&mut self, autoindent: bool) {
2570 if autoindent {
2571 self.autoindent_mode = Some(AutoindentMode::EachLine);
2572 } else {
2573 self.autoindent_mode = None;
2574 }
2575 }
2576
2577 pub fn read_only(&self, cx: &AppContext) -> bool {
2578 self.read_only || self.buffer.read(cx).read_only()
2579 }
2580
2581 pub fn set_read_only(&mut self, read_only: bool) {
2582 self.read_only = read_only;
2583 }
2584
2585 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2586 self.use_autoclose = autoclose;
2587 }
2588
2589 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2590 self.use_auto_surround = auto_surround;
2591 }
2592
2593 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2594 self.auto_replace_emoji_shortcode = auto_replace;
2595 }
2596
2597 pub fn toggle_inline_completions(
2598 &mut self,
2599 _: &ToggleInlineCompletions,
2600 cx: &mut ViewContext<Self>,
2601 ) {
2602 if self.show_inline_completions_override.is_some() {
2603 self.set_show_inline_completions(None, cx);
2604 } else {
2605 let cursor = self.selections.newest_anchor().head();
2606 if let Some((buffer, cursor_buffer_position)) =
2607 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2608 {
2609 let show_inline_completions =
2610 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2611 self.set_show_inline_completions(Some(show_inline_completions), cx);
2612 }
2613 }
2614 }
2615
2616 pub fn set_show_inline_completions(
2617 &mut self,
2618 show_inline_completions: Option<bool>,
2619 cx: &mut ViewContext<Self>,
2620 ) {
2621 self.show_inline_completions_override = show_inline_completions;
2622 self.refresh_inline_completion(false, true, cx);
2623 }
2624
2625 fn should_show_inline_completions(
2626 &self,
2627 buffer: &Model<Buffer>,
2628 buffer_position: language::Anchor,
2629 cx: &AppContext,
2630 ) -> bool {
2631 if !self.snippet_stack.is_empty() {
2632 return false;
2633 }
2634
2635 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2636 return false;
2637 }
2638
2639 if let Some(provider) = self.inline_completion_provider() {
2640 if let Some(show_inline_completions) = self.show_inline_completions_override {
2641 show_inline_completions
2642 } else {
2643 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2644 }
2645 } else {
2646 false
2647 }
2648 }
2649
2650 fn inline_completions_disabled_in_scope(
2651 &self,
2652 buffer: &Model<Buffer>,
2653 buffer_position: language::Anchor,
2654 cx: &AppContext,
2655 ) -> bool {
2656 let snapshot = buffer.read(cx).snapshot();
2657 let settings = snapshot.settings_at(buffer_position, cx);
2658
2659 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2660 return false;
2661 };
2662
2663 scope.override_name().map_or(false, |scope_name| {
2664 settings
2665 .inline_completions_disabled_in
2666 .iter()
2667 .any(|s| s == scope_name)
2668 })
2669 }
2670
2671 pub fn set_use_modal_editing(&mut self, to: bool) {
2672 self.use_modal_editing = to;
2673 }
2674
2675 pub fn use_modal_editing(&self) -> bool {
2676 self.use_modal_editing
2677 }
2678
2679 fn selections_did_change(
2680 &mut self,
2681 local: bool,
2682 old_cursor_position: &Anchor,
2683 show_completions: bool,
2684 cx: &mut ViewContext<Self>,
2685 ) {
2686 cx.invalidate_character_coordinates();
2687
2688 // Copy selections to primary selection buffer
2689 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2690 if local {
2691 let selections = self.selections.all::<usize>(cx);
2692 let buffer_handle = self.buffer.read(cx).read(cx);
2693
2694 let mut text = String::new();
2695 for (index, selection) in selections.iter().enumerate() {
2696 let text_for_selection = buffer_handle
2697 .text_for_range(selection.start..selection.end)
2698 .collect::<String>();
2699
2700 text.push_str(&text_for_selection);
2701 if index != selections.len() - 1 {
2702 text.push('\n');
2703 }
2704 }
2705
2706 if !text.is_empty() {
2707 cx.write_to_primary(ClipboardItem::new_string(text));
2708 }
2709 }
2710
2711 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2712 self.buffer.update(cx, |buffer, cx| {
2713 buffer.set_active_selections(
2714 &self.selections.disjoint_anchors(),
2715 self.selections.line_mode,
2716 self.cursor_shape,
2717 cx,
2718 )
2719 });
2720 }
2721 let display_map = self
2722 .display_map
2723 .update(cx, |display_map, cx| display_map.snapshot(cx));
2724 let buffer = &display_map.buffer_snapshot;
2725 self.add_selections_state = None;
2726 self.select_next_state = None;
2727 self.select_prev_state = None;
2728 self.select_larger_syntax_node_stack.clear();
2729 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2730 self.snippet_stack
2731 .invalidate(&self.selections.disjoint_anchors(), buffer);
2732 self.take_rename(false, cx);
2733
2734 let new_cursor_position = self.selections.newest_anchor().head();
2735
2736 self.push_to_nav_history(
2737 *old_cursor_position,
2738 Some(new_cursor_position.to_point(buffer)),
2739 cx,
2740 );
2741
2742 if local {
2743 let new_cursor_position = self.selections.newest_anchor().head();
2744 let mut context_menu = self.context_menu.write();
2745 let completion_menu = match context_menu.as_ref() {
2746 Some(ContextMenu::Completions(menu)) => Some(menu),
2747
2748 _ => {
2749 *context_menu = None;
2750 None
2751 }
2752 };
2753
2754 if let Some(completion_menu) = completion_menu {
2755 let cursor_position = new_cursor_position.to_offset(buffer);
2756 let (word_range, kind) =
2757 buffer.surrounding_word(completion_menu.initial_position, true);
2758 if kind == Some(CharKind::Word)
2759 && word_range.to_inclusive().contains(&cursor_position)
2760 {
2761 let mut completion_menu = completion_menu.clone();
2762 drop(context_menu);
2763
2764 let query = Self::completion_query(buffer, cursor_position);
2765 cx.spawn(move |this, mut cx| async move {
2766 completion_menu
2767 .filter(query.as_deref(), cx.background_executor().clone())
2768 .await;
2769
2770 this.update(&mut cx, |this, cx| {
2771 let mut context_menu = this.context_menu.write();
2772 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2773 return;
2774 };
2775
2776 if menu.id > completion_menu.id {
2777 return;
2778 }
2779
2780 *context_menu = Some(ContextMenu::Completions(completion_menu));
2781 drop(context_menu);
2782 cx.notify();
2783 })
2784 })
2785 .detach();
2786
2787 if show_completions {
2788 self.show_completions(&ShowCompletions { trigger: None }, cx);
2789 }
2790 } else {
2791 drop(context_menu);
2792 self.hide_context_menu(cx);
2793 }
2794 } else {
2795 drop(context_menu);
2796 }
2797
2798 hide_hover(self, cx);
2799
2800 if old_cursor_position.to_display_point(&display_map).row()
2801 != new_cursor_position.to_display_point(&display_map).row()
2802 {
2803 self.available_code_actions.take();
2804 }
2805 self.refresh_code_actions(cx);
2806 self.refresh_document_highlights(cx);
2807 refresh_matching_bracket_highlights(self, cx);
2808 self.discard_inline_completion(false, cx);
2809 linked_editing_ranges::refresh_linked_ranges(self, cx);
2810 if self.git_blame_inline_enabled {
2811 self.start_inline_blame_timer(cx);
2812 }
2813 }
2814
2815 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2816 cx.emit(EditorEvent::SelectionsChanged { local });
2817
2818 if self.selections.disjoint_anchors().len() == 1 {
2819 cx.emit(SearchEvent::ActiveMatchChanged)
2820 }
2821 cx.notify();
2822 }
2823
2824 pub fn change_selections<R>(
2825 &mut self,
2826 autoscroll: Option<Autoscroll>,
2827 cx: &mut ViewContext<Self>,
2828 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2829 ) -> R {
2830 self.change_selections_inner(autoscroll, true, cx, change)
2831 }
2832
2833 pub fn change_selections_inner<R>(
2834 &mut self,
2835 autoscroll: Option<Autoscroll>,
2836 request_completions: bool,
2837 cx: &mut ViewContext<Self>,
2838 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2839 ) -> R {
2840 let old_cursor_position = self.selections.newest_anchor().head();
2841 self.push_to_selection_history();
2842
2843 let (changed, result) = self.selections.change_with(cx, change);
2844
2845 if changed {
2846 if let Some(autoscroll) = autoscroll {
2847 self.request_autoscroll(autoscroll, cx);
2848 }
2849 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2850
2851 if self.should_open_signature_help_automatically(
2852 &old_cursor_position,
2853 self.signature_help_state.backspace_pressed(),
2854 cx,
2855 ) {
2856 self.show_signature_help(&ShowSignatureHelp, cx);
2857 }
2858 self.signature_help_state.set_backspace_pressed(false);
2859 }
2860
2861 result
2862 }
2863
2864 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2865 where
2866 I: IntoIterator<Item = (Range<S>, T)>,
2867 S: ToOffset,
2868 T: Into<Arc<str>>,
2869 {
2870 if self.read_only(cx) {
2871 return;
2872 }
2873
2874 self.buffer
2875 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2876 }
2877
2878 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2879 where
2880 I: IntoIterator<Item = (Range<S>, T)>,
2881 S: ToOffset,
2882 T: Into<Arc<str>>,
2883 {
2884 if self.read_only(cx) {
2885 return;
2886 }
2887
2888 self.buffer.update(cx, |buffer, cx| {
2889 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2890 });
2891 }
2892
2893 pub fn edit_with_block_indent<I, S, T>(
2894 &mut self,
2895 edits: I,
2896 original_indent_columns: Vec<u32>,
2897 cx: &mut ViewContext<Self>,
2898 ) where
2899 I: IntoIterator<Item = (Range<S>, T)>,
2900 S: ToOffset,
2901 T: Into<Arc<str>>,
2902 {
2903 if self.read_only(cx) {
2904 return;
2905 }
2906
2907 self.buffer.update(cx, |buffer, cx| {
2908 buffer.edit(
2909 edits,
2910 Some(AutoindentMode::Block {
2911 original_indent_columns,
2912 }),
2913 cx,
2914 )
2915 });
2916 }
2917
2918 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2919 self.hide_context_menu(cx);
2920
2921 match phase {
2922 SelectPhase::Begin {
2923 position,
2924 add,
2925 click_count,
2926 } => self.begin_selection(position, add, click_count, cx),
2927 SelectPhase::BeginColumnar {
2928 position,
2929 goal_column,
2930 reset,
2931 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2932 SelectPhase::Extend {
2933 position,
2934 click_count,
2935 } => self.extend_selection(position, click_count, cx),
2936 SelectPhase::Update {
2937 position,
2938 goal_column,
2939 scroll_delta,
2940 } => self.update_selection(position, goal_column, scroll_delta, cx),
2941 SelectPhase::End => self.end_selection(cx),
2942 }
2943 }
2944
2945 fn extend_selection(
2946 &mut self,
2947 position: DisplayPoint,
2948 click_count: usize,
2949 cx: &mut ViewContext<Self>,
2950 ) {
2951 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2952 let tail = self.selections.newest::<usize>(cx).tail();
2953 self.begin_selection(position, false, click_count, cx);
2954
2955 let position = position.to_offset(&display_map, Bias::Left);
2956 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2957
2958 let mut pending_selection = self
2959 .selections
2960 .pending_anchor()
2961 .expect("extend_selection not called with pending selection");
2962 if position >= tail {
2963 pending_selection.start = tail_anchor;
2964 } else {
2965 pending_selection.end = tail_anchor;
2966 pending_selection.reversed = true;
2967 }
2968
2969 let mut pending_mode = self.selections.pending_mode().unwrap();
2970 match &mut pending_mode {
2971 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2972 _ => {}
2973 }
2974
2975 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2976 s.set_pending(pending_selection, pending_mode)
2977 });
2978 }
2979
2980 fn begin_selection(
2981 &mut self,
2982 position: DisplayPoint,
2983 add: bool,
2984 click_count: usize,
2985 cx: &mut ViewContext<Self>,
2986 ) {
2987 if !self.focus_handle.is_focused(cx) {
2988 self.last_focused_descendant = None;
2989 cx.focus(&self.focus_handle);
2990 }
2991
2992 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2993 let buffer = &display_map.buffer_snapshot;
2994 let newest_selection = self.selections.newest_anchor().clone();
2995 let position = display_map.clip_point(position, Bias::Left);
2996
2997 let start;
2998 let end;
2999 let mode;
3000 let auto_scroll;
3001 match click_count {
3002 1 => {
3003 start = buffer.anchor_before(position.to_point(&display_map));
3004 end = start;
3005 mode = SelectMode::Character;
3006 auto_scroll = true;
3007 }
3008 2 => {
3009 let range = movement::surrounding_word(&display_map, position);
3010 start = buffer.anchor_before(range.start.to_point(&display_map));
3011 end = buffer.anchor_before(range.end.to_point(&display_map));
3012 mode = SelectMode::Word(start..end);
3013 auto_scroll = true;
3014 }
3015 3 => {
3016 let position = display_map
3017 .clip_point(position, Bias::Left)
3018 .to_point(&display_map);
3019 let line_start = display_map.prev_line_boundary(position).0;
3020 let next_line_start = buffer.clip_point(
3021 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3022 Bias::Left,
3023 );
3024 start = buffer.anchor_before(line_start);
3025 end = buffer.anchor_before(next_line_start);
3026 mode = SelectMode::Line(start..end);
3027 auto_scroll = true;
3028 }
3029 _ => {
3030 start = buffer.anchor_before(0);
3031 end = buffer.anchor_before(buffer.len());
3032 mode = SelectMode::All;
3033 auto_scroll = false;
3034 }
3035 }
3036
3037 let point_to_delete: Option<usize> = {
3038 let selected_points: Vec<Selection<Point>> =
3039 self.selections.disjoint_in_range(start..end, cx);
3040
3041 if !add || click_count > 1 {
3042 None
3043 } else if !selected_points.is_empty() {
3044 Some(selected_points[0].id)
3045 } else {
3046 let clicked_point_already_selected =
3047 self.selections.disjoint.iter().find(|selection| {
3048 selection.start.to_point(buffer) == start.to_point(buffer)
3049 || selection.end.to_point(buffer) == end.to_point(buffer)
3050 });
3051
3052 clicked_point_already_selected.map(|selection| selection.id)
3053 }
3054 };
3055
3056 let selections_count = self.selections.count();
3057
3058 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
3059 if let Some(point_to_delete) = point_to_delete {
3060 s.delete(point_to_delete);
3061
3062 if selections_count == 1 {
3063 s.set_pending_anchor_range(start..end, mode);
3064 }
3065 } else {
3066 if !add {
3067 s.clear_disjoint();
3068 } else if click_count > 1 {
3069 s.delete(newest_selection.id)
3070 }
3071
3072 s.set_pending_anchor_range(start..end, mode);
3073 }
3074 });
3075 }
3076
3077 fn begin_columnar_selection(
3078 &mut self,
3079 position: DisplayPoint,
3080 goal_column: u32,
3081 reset: bool,
3082 cx: &mut ViewContext<Self>,
3083 ) {
3084 if !self.focus_handle.is_focused(cx) {
3085 self.last_focused_descendant = None;
3086 cx.focus(&self.focus_handle);
3087 }
3088
3089 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3090
3091 if reset {
3092 let pointer_position = display_map
3093 .buffer_snapshot
3094 .anchor_before(position.to_point(&display_map));
3095
3096 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3097 s.clear_disjoint();
3098 s.set_pending_anchor_range(
3099 pointer_position..pointer_position,
3100 SelectMode::Character,
3101 );
3102 });
3103 }
3104
3105 let tail = self.selections.newest::<Point>(cx).tail();
3106 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3107
3108 if !reset {
3109 self.select_columns(
3110 tail.to_display_point(&display_map),
3111 position,
3112 goal_column,
3113 &display_map,
3114 cx,
3115 );
3116 }
3117 }
3118
3119 fn update_selection(
3120 &mut self,
3121 position: DisplayPoint,
3122 goal_column: u32,
3123 scroll_delta: gpui::Point<f32>,
3124 cx: &mut ViewContext<Self>,
3125 ) {
3126 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3127
3128 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3129 let tail = tail.to_display_point(&display_map);
3130 self.select_columns(tail, position, goal_column, &display_map, cx);
3131 } else if let Some(mut pending) = self.selections.pending_anchor() {
3132 let buffer = self.buffer.read(cx).snapshot(cx);
3133 let head;
3134 let tail;
3135 let mode = self.selections.pending_mode().unwrap();
3136 match &mode {
3137 SelectMode::Character => {
3138 head = position.to_point(&display_map);
3139 tail = pending.tail().to_point(&buffer);
3140 }
3141 SelectMode::Word(original_range) => {
3142 let original_display_range = original_range.start.to_display_point(&display_map)
3143 ..original_range.end.to_display_point(&display_map);
3144 let original_buffer_range = original_display_range.start.to_point(&display_map)
3145 ..original_display_range.end.to_point(&display_map);
3146 if movement::is_inside_word(&display_map, position)
3147 || original_display_range.contains(&position)
3148 {
3149 let word_range = movement::surrounding_word(&display_map, position);
3150 if word_range.start < original_display_range.start {
3151 head = word_range.start.to_point(&display_map);
3152 } else {
3153 head = word_range.end.to_point(&display_map);
3154 }
3155 } else {
3156 head = position.to_point(&display_map);
3157 }
3158
3159 if head <= original_buffer_range.start {
3160 tail = original_buffer_range.end;
3161 } else {
3162 tail = original_buffer_range.start;
3163 }
3164 }
3165 SelectMode::Line(original_range) => {
3166 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3167
3168 let position = display_map
3169 .clip_point(position, Bias::Left)
3170 .to_point(&display_map);
3171 let line_start = display_map.prev_line_boundary(position).0;
3172 let next_line_start = buffer.clip_point(
3173 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3174 Bias::Left,
3175 );
3176
3177 if line_start < original_range.start {
3178 head = line_start
3179 } else {
3180 head = next_line_start
3181 }
3182
3183 if head <= original_range.start {
3184 tail = original_range.end;
3185 } else {
3186 tail = original_range.start;
3187 }
3188 }
3189 SelectMode::All => {
3190 return;
3191 }
3192 };
3193
3194 if head < tail {
3195 pending.start = buffer.anchor_before(head);
3196 pending.end = buffer.anchor_before(tail);
3197 pending.reversed = true;
3198 } else {
3199 pending.start = buffer.anchor_before(tail);
3200 pending.end = buffer.anchor_before(head);
3201 pending.reversed = false;
3202 }
3203
3204 self.change_selections(None, cx, |s| {
3205 s.set_pending(pending, mode);
3206 });
3207 } else {
3208 log::error!("update_selection dispatched with no pending selection");
3209 return;
3210 }
3211
3212 self.apply_scroll_delta(scroll_delta, cx);
3213 cx.notify();
3214 }
3215
3216 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3217 self.columnar_selection_tail.take();
3218 if self.selections.pending_anchor().is_some() {
3219 let selections = self.selections.all::<usize>(cx);
3220 self.change_selections(None, cx, |s| {
3221 s.select(selections);
3222 s.clear_pending();
3223 });
3224 }
3225 }
3226
3227 fn select_columns(
3228 &mut self,
3229 tail: DisplayPoint,
3230 head: DisplayPoint,
3231 goal_column: u32,
3232 display_map: &DisplaySnapshot,
3233 cx: &mut ViewContext<Self>,
3234 ) {
3235 let start_row = cmp::min(tail.row(), head.row());
3236 let end_row = cmp::max(tail.row(), head.row());
3237 let start_column = cmp::min(tail.column(), goal_column);
3238 let end_column = cmp::max(tail.column(), goal_column);
3239 let reversed = start_column < tail.column();
3240
3241 let selection_ranges = (start_row.0..=end_row.0)
3242 .map(DisplayRow)
3243 .filter_map(|row| {
3244 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3245 let start = display_map
3246 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3247 .to_point(display_map);
3248 let end = display_map
3249 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3250 .to_point(display_map);
3251 if reversed {
3252 Some(end..start)
3253 } else {
3254 Some(start..end)
3255 }
3256 } else {
3257 None
3258 }
3259 })
3260 .collect::<Vec<_>>();
3261
3262 self.change_selections(None, cx, |s| {
3263 s.select_ranges(selection_ranges);
3264 });
3265 cx.notify();
3266 }
3267
3268 pub fn has_pending_nonempty_selection(&self) -> bool {
3269 let pending_nonempty_selection = match self.selections.pending_anchor() {
3270 Some(Selection { start, end, .. }) => start != end,
3271 None => false,
3272 };
3273
3274 pending_nonempty_selection
3275 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3276 }
3277
3278 pub fn has_pending_selection(&self) -> bool {
3279 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3280 }
3281
3282 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3283 if self.clear_expanded_diff_hunks(cx) {
3284 cx.notify();
3285 return;
3286 }
3287 if self.dismiss_menus_and_popups(true, cx) {
3288 return;
3289 }
3290
3291 if self.mode == EditorMode::Full
3292 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3293 {
3294 return;
3295 }
3296
3297 cx.propagate();
3298 }
3299
3300 pub fn dismiss_menus_and_popups(
3301 &mut self,
3302 should_report_inline_completion_event: bool,
3303 cx: &mut ViewContext<Self>,
3304 ) -> bool {
3305 if self.take_rename(false, cx).is_some() {
3306 return true;
3307 }
3308
3309 if hide_hover(self, cx) {
3310 return true;
3311 }
3312
3313 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3314 return true;
3315 }
3316
3317 if self.hide_context_menu(cx).is_some() {
3318 return true;
3319 }
3320
3321 if self.mouse_context_menu.take().is_some() {
3322 return true;
3323 }
3324
3325 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3326 return true;
3327 }
3328
3329 if self.snippet_stack.pop().is_some() {
3330 return true;
3331 }
3332
3333 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3334 self.dismiss_diagnostics(cx);
3335 return true;
3336 }
3337
3338 false
3339 }
3340
3341 fn linked_editing_ranges_for(
3342 &self,
3343 selection: Range<text::Anchor>,
3344 cx: &AppContext,
3345 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3346 if self.linked_edit_ranges.is_empty() {
3347 return None;
3348 }
3349 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3350 selection.end.buffer_id.and_then(|end_buffer_id| {
3351 if selection.start.buffer_id != Some(end_buffer_id) {
3352 return None;
3353 }
3354 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3355 let snapshot = buffer.read(cx).snapshot();
3356 self.linked_edit_ranges
3357 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3358 .map(|ranges| (ranges, snapshot, buffer))
3359 })?;
3360 use text::ToOffset as TO;
3361 // find offset from the start of current range to current cursor position
3362 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3363
3364 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3365 let start_difference = start_offset - start_byte_offset;
3366 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3367 let end_difference = end_offset - start_byte_offset;
3368 // Current range has associated linked ranges.
3369 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3370 for range in linked_ranges.iter() {
3371 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3372 let end_offset = start_offset + end_difference;
3373 let start_offset = start_offset + start_difference;
3374 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3375 continue;
3376 }
3377 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3378 if s.start.buffer_id != selection.start.buffer_id
3379 || s.end.buffer_id != selection.end.buffer_id
3380 {
3381 return false;
3382 }
3383 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3384 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3385 }) {
3386 continue;
3387 }
3388 let start = buffer_snapshot.anchor_after(start_offset);
3389 let end = buffer_snapshot.anchor_after(end_offset);
3390 linked_edits
3391 .entry(buffer.clone())
3392 .or_default()
3393 .push(start..end);
3394 }
3395 Some(linked_edits)
3396 }
3397
3398 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3399 let text: Arc<str> = text.into();
3400
3401 if self.read_only(cx) {
3402 return;
3403 }
3404
3405 let selections = self.selections.all_adjusted(cx);
3406 let mut bracket_inserted = false;
3407 let mut edits = Vec::new();
3408 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3409 let mut new_selections = Vec::with_capacity(selections.len());
3410 let mut new_autoclose_regions = Vec::new();
3411 let snapshot = self.buffer.read(cx).read(cx);
3412
3413 for (selection, autoclose_region) in
3414 self.selections_with_autoclose_regions(selections, &snapshot)
3415 {
3416 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3417 // Determine if the inserted text matches the opening or closing
3418 // bracket of any of this language's bracket pairs.
3419 let mut bracket_pair = None;
3420 let mut is_bracket_pair_start = false;
3421 let mut is_bracket_pair_end = false;
3422 if !text.is_empty() {
3423 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3424 // and they are removing the character that triggered IME popup.
3425 for (pair, enabled) in scope.brackets() {
3426 if !pair.close && !pair.surround {
3427 continue;
3428 }
3429
3430 if enabled && pair.start.ends_with(text.as_ref()) {
3431 let prefix_len = pair.start.len() - text.len();
3432 let preceding_text_matches_prefix = prefix_len == 0
3433 || (selection.start.column >= (prefix_len as u32)
3434 && snapshot.contains_str_at(
3435 Point::new(
3436 selection.start.row,
3437 selection.start.column - (prefix_len as u32),
3438 ),
3439 &pair.start[..prefix_len],
3440 ));
3441 if preceding_text_matches_prefix {
3442 bracket_pair = Some(pair.clone());
3443 is_bracket_pair_start = true;
3444 break;
3445 }
3446 }
3447 if pair.end.as_str() == text.as_ref() {
3448 bracket_pair = Some(pair.clone());
3449 is_bracket_pair_end = true;
3450 break;
3451 }
3452 }
3453 }
3454
3455 if let Some(bracket_pair) = bracket_pair {
3456 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3457 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3458 let auto_surround =
3459 self.use_auto_surround && snapshot_settings.use_auto_surround;
3460 if selection.is_empty() {
3461 if is_bracket_pair_start {
3462 // If the inserted text is a suffix of an opening bracket and the
3463 // selection is preceded by the rest of the opening bracket, then
3464 // insert the closing bracket.
3465 let following_text_allows_autoclose = snapshot
3466 .chars_at(selection.start)
3467 .next()
3468 .map_or(true, |c| scope.should_autoclose_before(c));
3469
3470 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3471 && bracket_pair.start.len() == 1
3472 {
3473 let target = bracket_pair.start.chars().next().unwrap();
3474 let current_line_count = snapshot
3475 .reversed_chars_at(selection.start)
3476 .take_while(|&c| c != '\n')
3477 .filter(|&c| c == target)
3478 .count();
3479 current_line_count % 2 == 1
3480 } else {
3481 false
3482 };
3483
3484 if autoclose
3485 && bracket_pair.close
3486 && following_text_allows_autoclose
3487 && !is_closing_quote
3488 {
3489 let anchor = snapshot.anchor_before(selection.end);
3490 new_selections.push((selection.map(|_| anchor), text.len()));
3491 new_autoclose_regions.push((
3492 anchor,
3493 text.len(),
3494 selection.id,
3495 bracket_pair.clone(),
3496 ));
3497 edits.push((
3498 selection.range(),
3499 format!("{}{}", text, bracket_pair.end).into(),
3500 ));
3501 bracket_inserted = true;
3502 continue;
3503 }
3504 }
3505
3506 if let Some(region) = autoclose_region {
3507 // If the selection is followed by an auto-inserted closing bracket,
3508 // then don't insert that closing bracket again; just move the selection
3509 // past the closing bracket.
3510 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3511 && text.as_ref() == region.pair.end.as_str();
3512 if should_skip {
3513 let anchor = snapshot.anchor_after(selection.end);
3514 new_selections
3515 .push((selection.map(|_| anchor), region.pair.end.len()));
3516 continue;
3517 }
3518 }
3519
3520 let always_treat_brackets_as_autoclosed = snapshot
3521 .settings_at(selection.start, cx)
3522 .always_treat_brackets_as_autoclosed;
3523 if always_treat_brackets_as_autoclosed
3524 && is_bracket_pair_end
3525 && snapshot.contains_str_at(selection.end, text.as_ref())
3526 {
3527 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3528 // and the inserted text is a closing bracket and the selection is followed
3529 // by the closing bracket then move the selection past the closing bracket.
3530 let anchor = snapshot.anchor_after(selection.end);
3531 new_selections.push((selection.map(|_| anchor), text.len()));
3532 continue;
3533 }
3534 }
3535 // If an opening bracket is 1 character long and is typed while
3536 // text is selected, then surround that text with the bracket pair.
3537 else if auto_surround
3538 && bracket_pair.surround
3539 && is_bracket_pair_start
3540 && bracket_pair.start.chars().count() == 1
3541 {
3542 edits.push((selection.start..selection.start, text.clone()));
3543 edits.push((
3544 selection.end..selection.end,
3545 bracket_pair.end.as_str().into(),
3546 ));
3547 bracket_inserted = true;
3548 new_selections.push((
3549 Selection {
3550 id: selection.id,
3551 start: snapshot.anchor_after(selection.start),
3552 end: snapshot.anchor_before(selection.end),
3553 reversed: selection.reversed,
3554 goal: selection.goal,
3555 },
3556 0,
3557 ));
3558 continue;
3559 }
3560 }
3561 }
3562
3563 if self.auto_replace_emoji_shortcode
3564 && selection.is_empty()
3565 && text.as_ref().ends_with(':')
3566 {
3567 if let Some(possible_emoji_short_code) =
3568 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3569 {
3570 if !possible_emoji_short_code.is_empty() {
3571 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3572 let emoji_shortcode_start = Point::new(
3573 selection.start.row,
3574 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3575 );
3576
3577 // Remove shortcode from buffer
3578 edits.push((
3579 emoji_shortcode_start..selection.start,
3580 "".to_string().into(),
3581 ));
3582 new_selections.push((
3583 Selection {
3584 id: selection.id,
3585 start: snapshot.anchor_after(emoji_shortcode_start),
3586 end: snapshot.anchor_before(selection.start),
3587 reversed: selection.reversed,
3588 goal: selection.goal,
3589 },
3590 0,
3591 ));
3592
3593 // Insert emoji
3594 let selection_start_anchor = snapshot.anchor_after(selection.start);
3595 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3596 edits.push((selection.start..selection.end, emoji.to_string().into()));
3597
3598 continue;
3599 }
3600 }
3601 }
3602 }
3603
3604 // If not handling any auto-close operation, then just replace the selected
3605 // text with the given input and move the selection to the end of the
3606 // newly inserted text.
3607 let anchor = snapshot.anchor_after(selection.end);
3608 if !self.linked_edit_ranges.is_empty() {
3609 let start_anchor = snapshot.anchor_before(selection.start);
3610
3611 let is_word_char = text.chars().next().map_or(true, |char| {
3612 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3613 classifier.is_word(char)
3614 });
3615
3616 if is_word_char {
3617 if let Some(ranges) = self
3618 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3619 {
3620 for (buffer, edits) in ranges {
3621 linked_edits
3622 .entry(buffer.clone())
3623 .or_default()
3624 .extend(edits.into_iter().map(|range| (range, text.clone())));
3625 }
3626 }
3627 }
3628 }
3629
3630 new_selections.push((selection.map(|_| anchor), 0));
3631 edits.push((selection.start..selection.end, text.clone()));
3632 }
3633
3634 drop(snapshot);
3635
3636 self.transact(cx, |this, cx| {
3637 this.buffer.update(cx, |buffer, cx| {
3638 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3639 });
3640 for (buffer, edits) in linked_edits {
3641 buffer.update(cx, |buffer, cx| {
3642 let snapshot = buffer.snapshot();
3643 let edits = edits
3644 .into_iter()
3645 .map(|(range, text)| {
3646 use text::ToPoint as TP;
3647 let end_point = TP::to_point(&range.end, &snapshot);
3648 let start_point = TP::to_point(&range.start, &snapshot);
3649 (start_point..end_point, text)
3650 })
3651 .sorted_by_key(|(range, _)| range.start)
3652 .collect::<Vec<_>>();
3653 buffer.edit(edits, None, cx);
3654 })
3655 }
3656 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3657 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3658 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3659 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3660 .zip(new_selection_deltas)
3661 .map(|(selection, delta)| Selection {
3662 id: selection.id,
3663 start: selection.start + delta,
3664 end: selection.end + delta,
3665 reversed: selection.reversed,
3666 goal: SelectionGoal::None,
3667 })
3668 .collect::<Vec<_>>();
3669
3670 let mut i = 0;
3671 for (position, delta, selection_id, pair) in new_autoclose_regions {
3672 let position = position.to_offset(&map.buffer_snapshot) + delta;
3673 let start = map.buffer_snapshot.anchor_before(position);
3674 let end = map.buffer_snapshot.anchor_after(position);
3675 while let Some(existing_state) = this.autoclose_regions.get(i) {
3676 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3677 Ordering::Less => i += 1,
3678 Ordering::Greater => break,
3679 Ordering::Equal => {
3680 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3681 Ordering::Less => i += 1,
3682 Ordering::Equal => break,
3683 Ordering::Greater => break,
3684 }
3685 }
3686 }
3687 }
3688 this.autoclose_regions.insert(
3689 i,
3690 AutocloseRegion {
3691 selection_id,
3692 range: start..end,
3693 pair,
3694 },
3695 );
3696 }
3697
3698 let had_active_inline_completion = this.has_active_inline_completion(cx);
3699 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3700 s.select(new_selections)
3701 });
3702
3703 if !bracket_inserted {
3704 if let Some(on_type_format_task) =
3705 this.trigger_on_type_formatting(text.to_string(), cx)
3706 {
3707 on_type_format_task.detach_and_log_err(cx);
3708 }
3709 }
3710
3711 let editor_settings = EditorSettings::get_global(cx);
3712 if bracket_inserted
3713 && (editor_settings.auto_signature_help
3714 || editor_settings.show_signature_help_after_edits)
3715 {
3716 this.show_signature_help(&ShowSignatureHelp, cx);
3717 }
3718
3719 let trigger_in_words = !had_active_inline_completion;
3720 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3721 linked_editing_ranges::refresh_linked_ranges(this, cx);
3722 this.refresh_inline_completion(true, false, cx);
3723 });
3724 }
3725
3726 fn find_possible_emoji_shortcode_at_position(
3727 snapshot: &MultiBufferSnapshot,
3728 position: Point,
3729 ) -> Option<String> {
3730 let mut chars = Vec::new();
3731 let mut found_colon = false;
3732 for char in snapshot.reversed_chars_at(position).take(100) {
3733 // Found a possible emoji shortcode in the middle of the buffer
3734 if found_colon {
3735 if char.is_whitespace() {
3736 chars.reverse();
3737 return Some(chars.iter().collect());
3738 }
3739 // If the previous character is not a whitespace, we are in the middle of a word
3740 // and we only want to complete the shortcode if the word is made up of other emojis
3741 let mut containing_word = String::new();
3742 for ch in snapshot
3743 .reversed_chars_at(position)
3744 .skip(chars.len() + 1)
3745 .take(100)
3746 {
3747 if ch.is_whitespace() {
3748 break;
3749 }
3750 containing_word.push(ch);
3751 }
3752 let containing_word = containing_word.chars().rev().collect::<String>();
3753 if util::word_consists_of_emojis(containing_word.as_str()) {
3754 chars.reverse();
3755 return Some(chars.iter().collect());
3756 }
3757 }
3758
3759 if char.is_whitespace() || !char.is_ascii() {
3760 return None;
3761 }
3762 if char == ':' {
3763 found_colon = true;
3764 } else {
3765 chars.push(char);
3766 }
3767 }
3768 // Found a possible emoji shortcode at the beginning of the buffer
3769 chars.reverse();
3770 Some(chars.iter().collect())
3771 }
3772
3773 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3774 self.transact(cx, |this, cx| {
3775 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3776 let selections = this.selections.all::<usize>(cx);
3777 let multi_buffer = this.buffer.read(cx);
3778 let buffer = multi_buffer.snapshot(cx);
3779 selections
3780 .iter()
3781 .map(|selection| {
3782 let start_point = selection.start.to_point(&buffer);
3783 let mut indent =
3784 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3785 indent.len = cmp::min(indent.len, start_point.column);
3786 let start = selection.start;
3787 let end = selection.end;
3788 let selection_is_empty = start == end;
3789 let language_scope = buffer.language_scope_at(start);
3790 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3791 &language_scope
3792 {
3793 let leading_whitespace_len = buffer
3794 .reversed_chars_at(start)
3795 .take_while(|c| c.is_whitespace() && *c != '\n')
3796 .map(|c| c.len_utf8())
3797 .sum::<usize>();
3798
3799 let trailing_whitespace_len = buffer
3800 .chars_at(end)
3801 .take_while(|c| c.is_whitespace() && *c != '\n')
3802 .map(|c| c.len_utf8())
3803 .sum::<usize>();
3804
3805 let insert_extra_newline =
3806 language.brackets().any(|(pair, enabled)| {
3807 let pair_start = pair.start.trim_end();
3808 let pair_end = pair.end.trim_start();
3809
3810 enabled
3811 && pair.newline
3812 && buffer.contains_str_at(
3813 end + trailing_whitespace_len,
3814 pair_end,
3815 )
3816 && buffer.contains_str_at(
3817 (start - leading_whitespace_len)
3818 .saturating_sub(pair_start.len()),
3819 pair_start,
3820 )
3821 });
3822
3823 // Comment extension on newline is allowed only for cursor selections
3824 let comment_delimiter = maybe!({
3825 if !selection_is_empty {
3826 return None;
3827 }
3828
3829 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3830 return None;
3831 }
3832
3833 let delimiters = language.line_comment_prefixes();
3834 let max_len_of_delimiter =
3835 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3836 let (snapshot, range) =
3837 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3838
3839 let mut index_of_first_non_whitespace = 0;
3840 let comment_candidate = snapshot
3841 .chars_for_range(range)
3842 .skip_while(|c| {
3843 let should_skip = c.is_whitespace();
3844 if should_skip {
3845 index_of_first_non_whitespace += 1;
3846 }
3847 should_skip
3848 })
3849 .take(max_len_of_delimiter)
3850 .collect::<String>();
3851 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3852 comment_candidate.starts_with(comment_prefix.as_ref())
3853 })?;
3854 let cursor_is_placed_after_comment_marker =
3855 index_of_first_non_whitespace + comment_prefix.len()
3856 <= start_point.column as usize;
3857 if cursor_is_placed_after_comment_marker {
3858 Some(comment_prefix.clone())
3859 } else {
3860 None
3861 }
3862 });
3863 (comment_delimiter, insert_extra_newline)
3864 } else {
3865 (None, false)
3866 };
3867
3868 let capacity_for_delimiter = comment_delimiter
3869 .as_deref()
3870 .map(str::len)
3871 .unwrap_or_default();
3872 let mut new_text =
3873 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3874 new_text.push('\n');
3875 new_text.extend(indent.chars());
3876 if let Some(delimiter) = &comment_delimiter {
3877 new_text.push_str(delimiter);
3878 }
3879 if insert_extra_newline {
3880 new_text = new_text.repeat(2);
3881 }
3882
3883 let anchor = buffer.anchor_after(end);
3884 let new_selection = selection.map(|_| anchor);
3885 (
3886 (start..end, new_text),
3887 (insert_extra_newline, new_selection),
3888 )
3889 })
3890 .unzip()
3891 };
3892
3893 this.edit_with_autoindent(edits, cx);
3894 let buffer = this.buffer.read(cx).snapshot(cx);
3895 let new_selections = selection_fixup_info
3896 .into_iter()
3897 .map(|(extra_newline_inserted, new_selection)| {
3898 let mut cursor = new_selection.end.to_point(&buffer);
3899 if extra_newline_inserted {
3900 cursor.row -= 1;
3901 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3902 }
3903 new_selection.map(|_| cursor)
3904 })
3905 .collect();
3906
3907 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3908 this.refresh_inline_completion(true, false, cx);
3909 });
3910 }
3911
3912 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3913 let buffer = self.buffer.read(cx);
3914 let snapshot = buffer.snapshot(cx);
3915
3916 let mut edits = Vec::new();
3917 let mut rows = Vec::new();
3918
3919 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3920 let cursor = selection.head();
3921 let row = cursor.row;
3922
3923 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3924
3925 let newline = "\n".to_string();
3926 edits.push((start_of_line..start_of_line, newline));
3927
3928 rows.push(row + rows_inserted as u32);
3929 }
3930
3931 self.transact(cx, |editor, cx| {
3932 editor.edit(edits, cx);
3933
3934 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3935 let mut index = 0;
3936 s.move_cursors_with(|map, _, _| {
3937 let row = rows[index];
3938 index += 1;
3939
3940 let point = Point::new(row, 0);
3941 let boundary = map.next_line_boundary(point).1;
3942 let clipped = map.clip_point(boundary, Bias::Left);
3943
3944 (clipped, SelectionGoal::None)
3945 });
3946 });
3947
3948 let mut indent_edits = Vec::new();
3949 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3950 for row in rows {
3951 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3952 for (row, indent) in indents {
3953 if indent.len == 0 {
3954 continue;
3955 }
3956
3957 let text = match indent.kind {
3958 IndentKind::Space => " ".repeat(indent.len as usize),
3959 IndentKind::Tab => "\t".repeat(indent.len as usize),
3960 };
3961 let point = Point::new(row.0, 0);
3962 indent_edits.push((point..point, text));
3963 }
3964 }
3965 editor.edit(indent_edits, cx);
3966 });
3967 }
3968
3969 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3970 let buffer = self.buffer.read(cx);
3971 let snapshot = buffer.snapshot(cx);
3972
3973 let mut edits = Vec::new();
3974 let mut rows = Vec::new();
3975 let mut rows_inserted = 0;
3976
3977 for selection in self.selections.all_adjusted(cx) {
3978 let cursor = selection.head();
3979 let row = cursor.row;
3980
3981 let point = Point::new(row + 1, 0);
3982 let start_of_line = snapshot.clip_point(point, Bias::Left);
3983
3984 let newline = "\n".to_string();
3985 edits.push((start_of_line..start_of_line, newline));
3986
3987 rows_inserted += 1;
3988 rows.push(row + rows_inserted);
3989 }
3990
3991 self.transact(cx, |editor, cx| {
3992 editor.edit(edits, cx);
3993
3994 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3995 let mut index = 0;
3996 s.move_cursors_with(|map, _, _| {
3997 let row = rows[index];
3998 index += 1;
3999
4000 let point = Point::new(row, 0);
4001 let boundary = map.next_line_boundary(point).1;
4002 let clipped = map.clip_point(boundary, Bias::Left);
4003
4004 (clipped, SelectionGoal::None)
4005 });
4006 });
4007
4008 let mut indent_edits = Vec::new();
4009 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4010 for row in rows {
4011 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4012 for (row, indent) in indents {
4013 if indent.len == 0 {
4014 continue;
4015 }
4016
4017 let text = match indent.kind {
4018 IndentKind::Space => " ".repeat(indent.len as usize),
4019 IndentKind::Tab => "\t".repeat(indent.len as usize),
4020 };
4021 let point = Point::new(row.0, 0);
4022 indent_edits.push((point..point, text));
4023 }
4024 }
4025 editor.edit(indent_edits, cx);
4026 });
4027 }
4028
4029 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
4030 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4031 original_indent_columns: Vec::new(),
4032 });
4033 self.insert_with_autoindent_mode(text, autoindent, cx);
4034 }
4035
4036 fn insert_with_autoindent_mode(
4037 &mut self,
4038 text: &str,
4039 autoindent_mode: Option<AutoindentMode>,
4040 cx: &mut ViewContext<Self>,
4041 ) {
4042 if self.read_only(cx) {
4043 return;
4044 }
4045
4046 let text: Arc<str> = text.into();
4047 self.transact(cx, |this, cx| {
4048 let old_selections = this.selections.all_adjusted(cx);
4049 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4050 let anchors = {
4051 let snapshot = buffer.read(cx);
4052 old_selections
4053 .iter()
4054 .map(|s| {
4055 let anchor = snapshot.anchor_after(s.head());
4056 s.map(|_| anchor)
4057 })
4058 .collect::<Vec<_>>()
4059 };
4060 buffer.edit(
4061 old_selections
4062 .iter()
4063 .map(|s| (s.start..s.end, text.clone())),
4064 autoindent_mode,
4065 cx,
4066 );
4067 anchors
4068 });
4069
4070 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4071 s.select_anchors(selection_anchors);
4072 })
4073 });
4074 }
4075
4076 fn trigger_completion_on_input(
4077 &mut self,
4078 text: &str,
4079 trigger_in_words: bool,
4080 cx: &mut ViewContext<Self>,
4081 ) {
4082 if self.is_completion_trigger(text, trigger_in_words, cx) {
4083 self.show_completions(
4084 &ShowCompletions {
4085 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4086 },
4087 cx,
4088 );
4089 } else {
4090 self.hide_context_menu(cx);
4091 }
4092 }
4093
4094 fn is_completion_trigger(
4095 &self,
4096 text: &str,
4097 trigger_in_words: bool,
4098 cx: &mut ViewContext<Self>,
4099 ) -> bool {
4100 let position = self.selections.newest_anchor().head();
4101 let multibuffer = self.buffer.read(cx);
4102 let Some(buffer) = position
4103 .buffer_id
4104 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4105 else {
4106 return false;
4107 };
4108
4109 if let Some(completion_provider) = &self.completion_provider {
4110 completion_provider.is_completion_trigger(
4111 &buffer,
4112 position.text_anchor,
4113 text,
4114 trigger_in_words,
4115 cx,
4116 )
4117 } else {
4118 false
4119 }
4120 }
4121
4122 /// If any empty selections is touching the start of its innermost containing autoclose
4123 /// region, expand it to select the brackets.
4124 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4125 let selections = self.selections.all::<usize>(cx);
4126 let buffer = self.buffer.read(cx).read(cx);
4127 let new_selections = self
4128 .selections_with_autoclose_regions(selections, &buffer)
4129 .map(|(mut selection, region)| {
4130 if !selection.is_empty() {
4131 return selection;
4132 }
4133
4134 if let Some(region) = region {
4135 let mut range = region.range.to_offset(&buffer);
4136 if selection.start == range.start && range.start >= region.pair.start.len() {
4137 range.start -= region.pair.start.len();
4138 if buffer.contains_str_at(range.start, ®ion.pair.start)
4139 && buffer.contains_str_at(range.end, ®ion.pair.end)
4140 {
4141 range.end += region.pair.end.len();
4142 selection.start = range.start;
4143 selection.end = range.end;
4144
4145 return selection;
4146 }
4147 }
4148 }
4149
4150 let always_treat_brackets_as_autoclosed = buffer
4151 .settings_at(selection.start, cx)
4152 .always_treat_brackets_as_autoclosed;
4153
4154 if !always_treat_brackets_as_autoclosed {
4155 return selection;
4156 }
4157
4158 if let Some(scope) = buffer.language_scope_at(selection.start) {
4159 for (pair, enabled) in scope.brackets() {
4160 if !enabled || !pair.close {
4161 continue;
4162 }
4163
4164 if buffer.contains_str_at(selection.start, &pair.end) {
4165 let pair_start_len = pair.start.len();
4166 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4167 {
4168 selection.start -= pair_start_len;
4169 selection.end += pair.end.len();
4170
4171 return selection;
4172 }
4173 }
4174 }
4175 }
4176
4177 selection
4178 })
4179 .collect();
4180
4181 drop(buffer);
4182 self.change_selections(None, cx, |selections| selections.select(new_selections));
4183 }
4184
4185 /// Iterate the given selections, and for each one, find the smallest surrounding
4186 /// autoclose region. This uses the ordering of the selections and the autoclose
4187 /// regions to avoid repeated comparisons.
4188 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4189 &'a self,
4190 selections: impl IntoIterator<Item = Selection<D>>,
4191 buffer: &'a MultiBufferSnapshot,
4192 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4193 let mut i = 0;
4194 let mut regions = self.autoclose_regions.as_slice();
4195 selections.into_iter().map(move |selection| {
4196 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4197
4198 let mut enclosing = None;
4199 while let Some(pair_state) = regions.get(i) {
4200 if pair_state.range.end.to_offset(buffer) < range.start {
4201 regions = ®ions[i + 1..];
4202 i = 0;
4203 } else if pair_state.range.start.to_offset(buffer) > range.end {
4204 break;
4205 } else {
4206 if pair_state.selection_id == selection.id {
4207 enclosing = Some(pair_state);
4208 }
4209 i += 1;
4210 }
4211 }
4212
4213 (selection, enclosing)
4214 })
4215 }
4216
4217 /// Remove any autoclose regions that no longer contain their selection.
4218 fn invalidate_autoclose_regions(
4219 &mut self,
4220 mut selections: &[Selection<Anchor>],
4221 buffer: &MultiBufferSnapshot,
4222 ) {
4223 self.autoclose_regions.retain(|state| {
4224 let mut i = 0;
4225 while let Some(selection) = selections.get(i) {
4226 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4227 selections = &selections[1..];
4228 continue;
4229 }
4230 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4231 break;
4232 }
4233 if selection.id == state.selection_id {
4234 return true;
4235 } else {
4236 i += 1;
4237 }
4238 }
4239 false
4240 });
4241 }
4242
4243 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4244 let offset = position.to_offset(buffer);
4245 let (word_range, kind) = buffer.surrounding_word(offset, true);
4246 if offset > word_range.start && kind == Some(CharKind::Word) {
4247 Some(
4248 buffer
4249 .text_for_range(word_range.start..offset)
4250 .collect::<String>(),
4251 )
4252 } else {
4253 None
4254 }
4255 }
4256
4257 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4258 self.refresh_inlay_hints(
4259 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4260 cx,
4261 );
4262 }
4263
4264 pub fn inlay_hints_enabled(&self) -> bool {
4265 self.inlay_hint_cache.enabled
4266 }
4267
4268 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4269 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4270 return;
4271 }
4272
4273 let reason_description = reason.description();
4274 let ignore_debounce = matches!(
4275 reason,
4276 InlayHintRefreshReason::SettingsChange(_)
4277 | InlayHintRefreshReason::Toggle(_)
4278 | InlayHintRefreshReason::ExcerptsRemoved(_)
4279 );
4280 let (invalidate_cache, required_languages) = match reason {
4281 InlayHintRefreshReason::Toggle(enabled) => {
4282 self.inlay_hint_cache.enabled = enabled;
4283 if enabled {
4284 (InvalidationStrategy::RefreshRequested, None)
4285 } else {
4286 self.inlay_hint_cache.clear();
4287 self.splice_inlays(
4288 self.visible_inlay_hints(cx)
4289 .iter()
4290 .map(|inlay| inlay.id)
4291 .collect(),
4292 Vec::new(),
4293 cx,
4294 );
4295 return;
4296 }
4297 }
4298 InlayHintRefreshReason::SettingsChange(new_settings) => {
4299 match self.inlay_hint_cache.update_settings(
4300 &self.buffer,
4301 new_settings,
4302 self.visible_inlay_hints(cx),
4303 cx,
4304 ) {
4305 ControlFlow::Break(Some(InlaySplice {
4306 to_remove,
4307 to_insert,
4308 })) => {
4309 self.splice_inlays(to_remove, to_insert, cx);
4310 return;
4311 }
4312 ControlFlow::Break(None) => return,
4313 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4314 }
4315 }
4316 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4317 if let Some(InlaySplice {
4318 to_remove,
4319 to_insert,
4320 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4321 {
4322 self.splice_inlays(to_remove, to_insert, cx);
4323 }
4324 return;
4325 }
4326 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4327 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4328 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4329 }
4330 InlayHintRefreshReason::RefreshRequested => {
4331 (InvalidationStrategy::RefreshRequested, None)
4332 }
4333 };
4334
4335 if let Some(InlaySplice {
4336 to_remove,
4337 to_insert,
4338 }) = self.inlay_hint_cache.spawn_hint_refresh(
4339 reason_description,
4340 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4341 invalidate_cache,
4342 ignore_debounce,
4343 cx,
4344 ) {
4345 self.splice_inlays(to_remove, to_insert, cx);
4346 }
4347 }
4348
4349 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4350 self.display_map
4351 .read(cx)
4352 .current_inlays()
4353 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4354 .cloned()
4355 .collect()
4356 }
4357
4358 pub fn excerpts_for_inlay_hints_query(
4359 &self,
4360 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4361 cx: &mut ViewContext<Editor>,
4362 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4363 let Some(project) = self.project.as_ref() else {
4364 return HashMap::default();
4365 };
4366 let project = project.read(cx);
4367 let multi_buffer = self.buffer().read(cx);
4368 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4369 let multi_buffer_visible_start = self
4370 .scroll_manager
4371 .anchor()
4372 .anchor
4373 .to_point(&multi_buffer_snapshot);
4374 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4375 multi_buffer_visible_start
4376 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4377 Bias::Left,
4378 );
4379 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4380 multi_buffer
4381 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4382 .into_iter()
4383 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4384 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4385 let buffer = buffer_handle.read(cx);
4386 let buffer_file = project::File::from_dyn(buffer.file())?;
4387 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4388 let worktree_entry = buffer_worktree
4389 .read(cx)
4390 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4391 if worktree_entry.is_ignored {
4392 return None;
4393 }
4394
4395 let language = buffer.language()?;
4396 if let Some(restrict_to_languages) = restrict_to_languages {
4397 if !restrict_to_languages.contains(language) {
4398 return None;
4399 }
4400 }
4401 Some((
4402 excerpt_id,
4403 (
4404 buffer_handle,
4405 buffer.version().clone(),
4406 excerpt_visible_range,
4407 ),
4408 ))
4409 })
4410 .collect()
4411 }
4412
4413 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4414 TextLayoutDetails {
4415 text_system: cx.text_system().clone(),
4416 editor_style: self.style.clone().unwrap(),
4417 rem_size: cx.rem_size(),
4418 scroll_anchor: self.scroll_manager.anchor(),
4419 visible_rows: self.visible_line_count(),
4420 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4421 }
4422 }
4423
4424 fn splice_inlays(
4425 &self,
4426 to_remove: Vec<InlayId>,
4427 to_insert: Vec<Inlay>,
4428 cx: &mut ViewContext<Self>,
4429 ) {
4430 self.display_map.update(cx, |display_map, cx| {
4431 display_map.splice_inlays(to_remove, to_insert, cx);
4432 });
4433 cx.notify();
4434 }
4435
4436 fn trigger_on_type_formatting(
4437 &self,
4438 input: String,
4439 cx: &mut ViewContext<Self>,
4440 ) -> Option<Task<Result<()>>> {
4441 if input.len() != 1 {
4442 return None;
4443 }
4444
4445 let project = self.project.as_ref()?;
4446 let position = self.selections.newest_anchor().head();
4447 let (buffer, buffer_position) = self
4448 .buffer
4449 .read(cx)
4450 .text_anchor_for_position(position, cx)?;
4451
4452 let settings = language_settings::language_settings(
4453 buffer
4454 .read(cx)
4455 .language_at(buffer_position)
4456 .map(|l| l.name()),
4457 buffer.read(cx).file(),
4458 cx,
4459 );
4460 if !settings.use_on_type_format {
4461 return None;
4462 }
4463
4464 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4465 // hence we do LSP request & edit on host side only — add formats to host's history.
4466 let push_to_lsp_host_history = true;
4467 // If this is not the host, append its history with new edits.
4468 let push_to_client_history = project.read(cx).is_via_collab();
4469
4470 let on_type_formatting = project.update(cx, |project, cx| {
4471 project.on_type_format(
4472 buffer.clone(),
4473 buffer_position,
4474 input,
4475 push_to_lsp_host_history,
4476 cx,
4477 )
4478 });
4479 Some(cx.spawn(|editor, mut cx| async move {
4480 if let Some(transaction) = on_type_formatting.await? {
4481 if push_to_client_history {
4482 buffer
4483 .update(&mut cx, |buffer, _| {
4484 buffer.push_transaction(transaction, Instant::now());
4485 })
4486 .ok();
4487 }
4488 editor.update(&mut cx, |editor, cx| {
4489 editor.refresh_document_highlights(cx);
4490 })?;
4491 }
4492 Ok(())
4493 }))
4494 }
4495
4496 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4497 if self.pending_rename.is_some() {
4498 return;
4499 }
4500
4501 let Some(provider) = self.completion_provider.as_ref() else {
4502 return;
4503 };
4504
4505 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4506 return;
4507 }
4508
4509 let position = self.selections.newest_anchor().head();
4510 let (buffer, buffer_position) =
4511 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4512 output
4513 } else {
4514 return;
4515 };
4516
4517 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4518 let is_followup_invoke = {
4519 let context_menu_state = self.context_menu.read();
4520 matches!(
4521 context_menu_state.deref(),
4522 Some(ContextMenu::Completions(_))
4523 )
4524 };
4525 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4526 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4527 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4528 CompletionTriggerKind::TRIGGER_CHARACTER
4529 }
4530
4531 _ => CompletionTriggerKind::INVOKED,
4532 };
4533 let completion_context = CompletionContext {
4534 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4535 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4536 Some(String::from(trigger))
4537 } else {
4538 None
4539 }
4540 }),
4541 trigger_kind,
4542 };
4543 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4544 let sort_completions = provider.sort_completions();
4545
4546 let id = post_inc(&mut self.next_completion_id);
4547 let task = cx.spawn(|this, mut cx| {
4548 async move {
4549 this.update(&mut cx, |this, _| {
4550 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4551 })?;
4552 let completions = completions.await.log_err();
4553 let menu = if let Some(completions) = completions {
4554 let mut menu = CompletionsMenu::new(
4555 id,
4556 sort_completions,
4557 position,
4558 buffer.clone(),
4559 completions.into(),
4560 );
4561 menu.filter(query.as_deref(), cx.background_executor().clone())
4562 .await;
4563
4564 if menu.matches.is_empty() {
4565 None
4566 } else {
4567 this.update(&mut cx, |editor, cx| {
4568 let completions = menu.completions.clone();
4569 let matches = menu.matches.clone();
4570
4571 let delay_ms = EditorSettings::get_global(cx)
4572 .completion_documentation_secondary_query_debounce;
4573 let delay = Duration::from_millis(delay_ms);
4574 editor
4575 .completion_documentation_pre_resolve_debounce
4576 .fire_new(delay, cx, |editor, cx| {
4577 CompletionsMenu::pre_resolve_completion_documentation(
4578 buffer,
4579 completions,
4580 matches,
4581 editor,
4582 cx,
4583 )
4584 });
4585 })
4586 .ok();
4587 Some(menu)
4588 }
4589 } else {
4590 None
4591 };
4592
4593 this.update(&mut cx, |this, cx| {
4594 let mut context_menu = this.context_menu.write();
4595 match context_menu.as_ref() {
4596 None => {}
4597
4598 Some(ContextMenu::Completions(prev_menu)) => {
4599 if prev_menu.id > id {
4600 return;
4601 }
4602 }
4603
4604 _ => return,
4605 }
4606
4607 if this.focus_handle.is_focused(cx) && menu.is_some() {
4608 let menu = menu.unwrap();
4609 *context_menu = Some(ContextMenu::Completions(menu));
4610 drop(context_menu);
4611 this.discard_inline_completion(false, cx);
4612 cx.notify();
4613 } else if this.completion_tasks.len() <= 1 {
4614 // If there are no more completion tasks and the last menu was
4615 // empty, we should hide it. If it was already hidden, we should
4616 // also show the copilot completion when available.
4617 drop(context_menu);
4618 if this.hide_context_menu(cx).is_none() {
4619 this.update_visible_inline_completion(cx);
4620 }
4621 }
4622 })?;
4623
4624 Ok::<_, anyhow::Error>(())
4625 }
4626 .log_err()
4627 });
4628
4629 self.completion_tasks.push((id, task));
4630 }
4631
4632 pub fn confirm_completion(
4633 &mut self,
4634 action: &ConfirmCompletion,
4635 cx: &mut ViewContext<Self>,
4636 ) -> Option<Task<Result<()>>> {
4637 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4638 }
4639
4640 pub fn compose_completion(
4641 &mut self,
4642 action: &ComposeCompletion,
4643 cx: &mut ViewContext<Self>,
4644 ) -> Option<Task<Result<()>>> {
4645 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4646 }
4647
4648 fn do_completion(
4649 &mut self,
4650 item_ix: Option<usize>,
4651 intent: CompletionIntent,
4652 cx: &mut ViewContext<Editor>,
4653 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4654 use language::ToOffset as _;
4655
4656 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4657 menu
4658 } else {
4659 return None;
4660 };
4661
4662 let mat = completions_menu
4663 .matches
4664 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4665 let buffer_handle = completions_menu.buffer;
4666 let completions = completions_menu.completions.read();
4667 let completion = completions.get(mat.candidate_id)?;
4668 cx.stop_propagation();
4669
4670 let snippet;
4671 let text;
4672
4673 if completion.is_snippet() {
4674 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4675 text = snippet.as_ref().unwrap().text.clone();
4676 } else {
4677 snippet = None;
4678 text = completion.new_text.clone();
4679 };
4680 let selections = self.selections.all::<usize>(cx);
4681 let buffer = buffer_handle.read(cx);
4682 let old_range = completion.old_range.to_offset(buffer);
4683 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4684
4685 let newest_selection = self.selections.newest_anchor();
4686 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4687 return None;
4688 }
4689
4690 let lookbehind = newest_selection
4691 .start
4692 .text_anchor
4693 .to_offset(buffer)
4694 .saturating_sub(old_range.start);
4695 let lookahead = old_range
4696 .end
4697 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4698 let mut common_prefix_len = old_text
4699 .bytes()
4700 .zip(text.bytes())
4701 .take_while(|(a, b)| a == b)
4702 .count();
4703
4704 let snapshot = self.buffer.read(cx).snapshot(cx);
4705 let mut range_to_replace: Option<Range<isize>> = None;
4706 let mut ranges = Vec::new();
4707 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4708 for selection in &selections {
4709 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4710 let start = selection.start.saturating_sub(lookbehind);
4711 let end = selection.end + lookahead;
4712 if selection.id == newest_selection.id {
4713 range_to_replace = Some(
4714 ((start + common_prefix_len) as isize - selection.start as isize)
4715 ..(end as isize - selection.start as isize),
4716 );
4717 }
4718 ranges.push(start + common_prefix_len..end);
4719 } else {
4720 common_prefix_len = 0;
4721 ranges.clear();
4722 ranges.extend(selections.iter().map(|s| {
4723 if s.id == newest_selection.id {
4724 range_to_replace = Some(
4725 old_range.start.to_offset_utf16(&snapshot).0 as isize
4726 - selection.start as isize
4727 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4728 - selection.start as isize,
4729 );
4730 old_range.clone()
4731 } else {
4732 s.start..s.end
4733 }
4734 }));
4735 break;
4736 }
4737 if !self.linked_edit_ranges.is_empty() {
4738 let start_anchor = snapshot.anchor_before(selection.head());
4739 let end_anchor = snapshot.anchor_after(selection.tail());
4740 if let Some(ranges) = self
4741 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4742 {
4743 for (buffer, edits) in ranges {
4744 linked_edits.entry(buffer.clone()).or_default().extend(
4745 edits
4746 .into_iter()
4747 .map(|range| (range, text[common_prefix_len..].to_owned())),
4748 );
4749 }
4750 }
4751 }
4752 }
4753 let text = &text[common_prefix_len..];
4754
4755 cx.emit(EditorEvent::InputHandled {
4756 utf16_range_to_replace: range_to_replace,
4757 text: text.into(),
4758 });
4759
4760 self.transact(cx, |this, cx| {
4761 if let Some(mut snippet) = snippet {
4762 snippet.text = text.to_string();
4763 for tabstop in snippet
4764 .tabstops
4765 .iter_mut()
4766 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4767 {
4768 tabstop.start -= common_prefix_len as isize;
4769 tabstop.end -= common_prefix_len as isize;
4770 }
4771
4772 this.insert_snippet(&ranges, snippet, cx).log_err();
4773 } else {
4774 this.buffer.update(cx, |buffer, cx| {
4775 buffer.edit(
4776 ranges.iter().map(|range| (range.clone(), text)),
4777 this.autoindent_mode.clone(),
4778 cx,
4779 );
4780 });
4781 }
4782 for (buffer, edits) in linked_edits {
4783 buffer.update(cx, |buffer, cx| {
4784 let snapshot = buffer.snapshot();
4785 let edits = edits
4786 .into_iter()
4787 .map(|(range, text)| {
4788 use text::ToPoint as TP;
4789 let end_point = TP::to_point(&range.end, &snapshot);
4790 let start_point = TP::to_point(&range.start, &snapshot);
4791 (start_point..end_point, text)
4792 })
4793 .sorted_by_key(|(range, _)| range.start)
4794 .collect::<Vec<_>>();
4795 buffer.edit(edits, None, cx);
4796 })
4797 }
4798
4799 this.refresh_inline_completion(true, false, cx);
4800 });
4801
4802 let show_new_completions_on_confirm = completion
4803 .confirm
4804 .as_ref()
4805 .map_or(false, |confirm| confirm(intent, cx));
4806 if show_new_completions_on_confirm {
4807 self.show_completions(&ShowCompletions { trigger: None }, cx);
4808 }
4809
4810 let provider = self.completion_provider.as_ref()?;
4811 let apply_edits = provider.apply_additional_edits_for_completion(
4812 buffer_handle,
4813 completion.clone(),
4814 true,
4815 cx,
4816 );
4817
4818 let editor_settings = EditorSettings::get_global(cx);
4819 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4820 // After the code completion is finished, users often want to know what signatures are needed.
4821 // so we should automatically call signature_help
4822 self.show_signature_help(&ShowSignatureHelp, cx);
4823 }
4824
4825 Some(cx.foreground_executor().spawn(async move {
4826 apply_edits.await?;
4827 Ok(())
4828 }))
4829 }
4830
4831 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4832 let mut context_menu = self.context_menu.write();
4833 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4834 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4835 // Toggle if we're selecting the same one
4836 *context_menu = None;
4837 cx.notify();
4838 return;
4839 } else {
4840 // Otherwise, clear it and start a new one
4841 *context_menu = None;
4842 cx.notify();
4843 }
4844 }
4845 drop(context_menu);
4846 let snapshot = self.snapshot(cx);
4847 let deployed_from_indicator = action.deployed_from_indicator;
4848 let mut task = self.code_actions_task.take();
4849 let action = action.clone();
4850 cx.spawn(|editor, mut cx| async move {
4851 while let Some(prev_task) = task {
4852 prev_task.await.log_err();
4853 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4854 }
4855
4856 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4857 if editor.focus_handle.is_focused(cx) {
4858 let multibuffer_point = action
4859 .deployed_from_indicator
4860 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4861 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4862 let (buffer, buffer_row) = snapshot
4863 .buffer_snapshot
4864 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4865 .and_then(|(buffer_snapshot, range)| {
4866 editor
4867 .buffer
4868 .read(cx)
4869 .buffer(buffer_snapshot.remote_id())
4870 .map(|buffer| (buffer, range.start.row))
4871 })?;
4872 let (_, code_actions) = editor
4873 .available_code_actions
4874 .clone()
4875 .and_then(|(location, code_actions)| {
4876 let snapshot = location.buffer.read(cx).snapshot();
4877 let point_range = location.range.to_point(&snapshot);
4878 let point_range = point_range.start.row..=point_range.end.row;
4879 if point_range.contains(&buffer_row) {
4880 Some((location, code_actions))
4881 } else {
4882 None
4883 }
4884 })
4885 .unzip();
4886 let buffer_id = buffer.read(cx).remote_id();
4887 let tasks = editor
4888 .tasks
4889 .get(&(buffer_id, buffer_row))
4890 .map(|t| Arc::new(t.to_owned()));
4891 if tasks.is_none() && code_actions.is_none() {
4892 return None;
4893 }
4894
4895 editor.completion_tasks.clear();
4896 editor.discard_inline_completion(false, cx);
4897 let task_context =
4898 tasks
4899 .as_ref()
4900 .zip(editor.project.clone())
4901 .map(|(tasks, project)| {
4902 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4903 });
4904
4905 Some(cx.spawn(|editor, mut cx| async move {
4906 let task_context = match task_context {
4907 Some(task_context) => task_context.await,
4908 None => None,
4909 };
4910 let resolved_tasks =
4911 tasks.zip(task_context).map(|(tasks, task_context)| {
4912 Arc::new(ResolvedTasks {
4913 templates: tasks.resolve(&task_context).collect(),
4914 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4915 multibuffer_point.row,
4916 tasks.column,
4917 )),
4918 })
4919 });
4920 let spawn_straight_away = resolved_tasks
4921 .as_ref()
4922 .map_or(false, |tasks| tasks.templates.len() == 1)
4923 && code_actions
4924 .as_ref()
4925 .map_or(true, |actions| actions.is_empty());
4926 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4927 *editor.context_menu.write() =
4928 Some(ContextMenu::CodeActions(CodeActionsMenu {
4929 buffer,
4930 actions: CodeActionContents {
4931 tasks: resolved_tasks,
4932 actions: code_actions,
4933 },
4934 selected_item: Default::default(),
4935 scroll_handle: UniformListScrollHandle::default(),
4936 deployed_from_indicator,
4937 }));
4938 if spawn_straight_away {
4939 if let Some(task) = editor.confirm_code_action(
4940 &ConfirmCodeAction { item_ix: Some(0) },
4941 cx,
4942 ) {
4943 cx.notify();
4944 return task;
4945 }
4946 }
4947 cx.notify();
4948 Task::ready(Ok(()))
4949 }) {
4950 task.await
4951 } else {
4952 Ok(())
4953 }
4954 }))
4955 } else {
4956 Some(Task::ready(Ok(())))
4957 }
4958 })?;
4959 if let Some(task) = spawned_test_task {
4960 task.await?;
4961 }
4962
4963 Ok::<_, anyhow::Error>(())
4964 })
4965 .detach_and_log_err(cx);
4966 }
4967
4968 pub fn confirm_code_action(
4969 &mut self,
4970 action: &ConfirmCodeAction,
4971 cx: &mut ViewContext<Self>,
4972 ) -> Option<Task<Result<()>>> {
4973 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4974 menu
4975 } else {
4976 return None;
4977 };
4978 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4979 let action = actions_menu.actions.get(action_ix)?;
4980 let title = action.label();
4981 let buffer = actions_menu.buffer;
4982 let workspace = self.workspace()?;
4983
4984 match action {
4985 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4986 workspace.update(cx, |workspace, cx| {
4987 workspace::tasks::schedule_resolved_task(
4988 workspace,
4989 task_source_kind,
4990 resolved_task,
4991 false,
4992 cx,
4993 );
4994
4995 Some(Task::ready(Ok(())))
4996 })
4997 }
4998 CodeActionsItem::CodeAction {
4999 excerpt_id,
5000 action,
5001 provider,
5002 } => {
5003 let apply_code_action =
5004 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
5005 let workspace = workspace.downgrade();
5006 Some(cx.spawn(|editor, cx| async move {
5007 let project_transaction = apply_code_action.await?;
5008 Self::open_project_transaction(
5009 &editor,
5010 workspace,
5011 project_transaction,
5012 title,
5013 cx,
5014 )
5015 .await
5016 }))
5017 }
5018 }
5019 }
5020
5021 pub async fn open_project_transaction(
5022 this: &WeakView<Editor>,
5023 workspace: WeakView<Workspace>,
5024 transaction: ProjectTransaction,
5025 title: String,
5026 mut cx: AsyncWindowContext,
5027 ) -> Result<()> {
5028 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5029 cx.update(|cx| {
5030 entries.sort_unstable_by_key(|(buffer, _)| {
5031 buffer.read(cx).file().map(|f| f.path().clone())
5032 });
5033 })?;
5034
5035 // If the project transaction's edits are all contained within this editor, then
5036 // avoid opening a new editor to display them.
5037
5038 if let Some((buffer, transaction)) = entries.first() {
5039 if entries.len() == 1 {
5040 let excerpt = this.update(&mut cx, |editor, cx| {
5041 editor
5042 .buffer()
5043 .read(cx)
5044 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5045 })?;
5046 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5047 if excerpted_buffer == *buffer {
5048 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
5049 let excerpt_range = excerpt_range.to_offset(buffer);
5050 buffer
5051 .edited_ranges_for_transaction::<usize>(transaction)
5052 .all(|range| {
5053 excerpt_range.start <= range.start
5054 && excerpt_range.end >= range.end
5055 })
5056 })?;
5057
5058 if all_edits_within_excerpt {
5059 return Ok(());
5060 }
5061 }
5062 }
5063 }
5064 } else {
5065 return Ok(());
5066 }
5067
5068 let mut ranges_to_highlight = Vec::new();
5069 let excerpt_buffer = cx.new_model(|cx| {
5070 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5071 for (buffer_handle, transaction) in &entries {
5072 let buffer = buffer_handle.read(cx);
5073 ranges_to_highlight.extend(
5074 multibuffer.push_excerpts_with_context_lines(
5075 buffer_handle.clone(),
5076 buffer
5077 .edited_ranges_for_transaction::<usize>(transaction)
5078 .collect(),
5079 DEFAULT_MULTIBUFFER_CONTEXT,
5080 cx,
5081 ),
5082 );
5083 }
5084 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5085 multibuffer
5086 })?;
5087
5088 workspace.update(&mut cx, |workspace, cx| {
5089 let project = workspace.project().clone();
5090 let editor =
5091 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5092 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5093 editor.update(cx, |editor, cx| {
5094 editor.highlight_background::<Self>(
5095 &ranges_to_highlight,
5096 |theme| theme.editor_highlighted_line_background,
5097 cx,
5098 );
5099 });
5100 })?;
5101
5102 Ok(())
5103 }
5104
5105 pub fn clear_code_action_providers(&mut self) {
5106 self.code_action_providers.clear();
5107 self.available_code_actions.take();
5108 }
5109
5110 pub fn push_code_action_provider(
5111 &mut self,
5112 provider: Arc<dyn CodeActionProvider>,
5113 cx: &mut ViewContext<Self>,
5114 ) {
5115 self.code_action_providers.push(provider);
5116 self.refresh_code_actions(cx);
5117 }
5118
5119 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5120 let buffer = self.buffer.read(cx);
5121 let newest_selection = self.selections.newest_anchor().clone();
5122 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5123 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5124 if start_buffer != end_buffer {
5125 return None;
5126 }
5127
5128 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5129 cx.background_executor()
5130 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5131 .await;
5132
5133 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5134 let providers = this.code_action_providers.clone();
5135 let tasks = this
5136 .code_action_providers
5137 .iter()
5138 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5139 .collect::<Vec<_>>();
5140 (providers, tasks)
5141 })?;
5142
5143 let mut actions = Vec::new();
5144 for (provider, provider_actions) in
5145 providers.into_iter().zip(future::join_all(tasks).await)
5146 {
5147 if let Some(provider_actions) = provider_actions.log_err() {
5148 actions.extend(provider_actions.into_iter().map(|action| {
5149 AvailableCodeAction {
5150 excerpt_id: newest_selection.start.excerpt_id,
5151 action,
5152 provider: provider.clone(),
5153 }
5154 }));
5155 }
5156 }
5157
5158 this.update(&mut cx, |this, cx| {
5159 this.available_code_actions = if actions.is_empty() {
5160 None
5161 } else {
5162 Some((
5163 Location {
5164 buffer: start_buffer,
5165 range: start..end,
5166 },
5167 actions.into(),
5168 ))
5169 };
5170 cx.notify();
5171 })
5172 }));
5173 None
5174 }
5175
5176 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5177 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5178 self.show_git_blame_inline = false;
5179
5180 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5181 cx.background_executor().timer(delay).await;
5182
5183 this.update(&mut cx, |this, cx| {
5184 this.show_git_blame_inline = true;
5185 cx.notify();
5186 })
5187 .log_err();
5188 }));
5189 }
5190 }
5191
5192 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5193 if self.pending_rename.is_some() {
5194 return None;
5195 }
5196
5197 let provider = self.semantics_provider.clone()?;
5198 let buffer = self.buffer.read(cx);
5199 let newest_selection = self.selections.newest_anchor().clone();
5200 let cursor_position = newest_selection.head();
5201 let (cursor_buffer, cursor_buffer_position) =
5202 buffer.text_anchor_for_position(cursor_position, cx)?;
5203 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5204 if cursor_buffer != tail_buffer {
5205 return None;
5206 }
5207
5208 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5209 cx.background_executor()
5210 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5211 .await;
5212
5213 let highlights = if let Some(highlights) = cx
5214 .update(|cx| {
5215 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5216 })
5217 .ok()
5218 .flatten()
5219 {
5220 highlights.await.log_err()
5221 } else {
5222 None
5223 };
5224
5225 if let Some(highlights) = highlights {
5226 this.update(&mut cx, |this, cx| {
5227 if this.pending_rename.is_some() {
5228 return;
5229 }
5230
5231 let buffer_id = cursor_position.buffer_id;
5232 let buffer = this.buffer.read(cx);
5233 if !buffer
5234 .text_anchor_for_position(cursor_position, cx)
5235 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5236 {
5237 return;
5238 }
5239
5240 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5241 let mut write_ranges = Vec::new();
5242 let mut read_ranges = Vec::new();
5243 for highlight in highlights {
5244 for (excerpt_id, excerpt_range) in
5245 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5246 {
5247 let start = highlight
5248 .range
5249 .start
5250 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5251 let end = highlight
5252 .range
5253 .end
5254 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5255 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5256 continue;
5257 }
5258
5259 let range = Anchor {
5260 buffer_id,
5261 excerpt_id,
5262 text_anchor: start,
5263 }..Anchor {
5264 buffer_id,
5265 excerpt_id,
5266 text_anchor: end,
5267 };
5268 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5269 write_ranges.push(range);
5270 } else {
5271 read_ranges.push(range);
5272 }
5273 }
5274 }
5275
5276 this.highlight_background::<DocumentHighlightRead>(
5277 &read_ranges,
5278 |theme| theme.editor_document_highlight_read_background,
5279 cx,
5280 );
5281 this.highlight_background::<DocumentHighlightWrite>(
5282 &write_ranges,
5283 |theme| theme.editor_document_highlight_write_background,
5284 cx,
5285 );
5286 cx.notify();
5287 })
5288 .log_err();
5289 }
5290 }));
5291 None
5292 }
5293
5294 pub fn refresh_inline_completion(
5295 &mut self,
5296 debounce: bool,
5297 user_requested: bool,
5298 cx: &mut ViewContext<Self>,
5299 ) -> Option<()> {
5300 let provider = self.inline_completion_provider()?;
5301 let cursor = self.selections.newest_anchor().head();
5302 let (buffer, cursor_buffer_position) =
5303 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5304
5305 if !user_requested
5306 && (!self.enable_inline_completions
5307 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5308 {
5309 self.discard_inline_completion(false, cx);
5310 return None;
5311 }
5312
5313 self.update_visible_inline_completion(cx);
5314 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5315 Some(())
5316 }
5317
5318 fn cycle_inline_completion(
5319 &mut self,
5320 direction: Direction,
5321 cx: &mut ViewContext<Self>,
5322 ) -> Option<()> {
5323 let provider = self.inline_completion_provider()?;
5324 let cursor = self.selections.newest_anchor().head();
5325 let (buffer, cursor_buffer_position) =
5326 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5327 if !self.enable_inline_completions
5328 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5329 {
5330 return None;
5331 }
5332
5333 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5334 self.update_visible_inline_completion(cx);
5335
5336 Some(())
5337 }
5338
5339 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5340 if !self.has_active_inline_completion(cx) {
5341 self.refresh_inline_completion(false, true, cx);
5342 return;
5343 }
5344
5345 self.update_visible_inline_completion(cx);
5346 }
5347
5348 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5349 self.show_cursor_names(cx);
5350 }
5351
5352 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5353 self.show_cursor_names = true;
5354 cx.notify();
5355 cx.spawn(|this, mut cx| async move {
5356 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5357 this.update(&mut cx, |this, cx| {
5358 this.show_cursor_names = false;
5359 cx.notify()
5360 })
5361 .ok()
5362 })
5363 .detach();
5364 }
5365
5366 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5367 if self.has_active_inline_completion(cx) {
5368 self.cycle_inline_completion(Direction::Next, cx);
5369 } else {
5370 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5371 if is_copilot_disabled {
5372 cx.propagate();
5373 }
5374 }
5375 }
5376
5377 pub fn previous_inline_completion(
5378 &mut self,
5379 _: &PreviousInlineCompletion,
5380 cx: &mut ViewContext<Self>,
5381 ) {
5382 if self.has_active_inline_completion(cx) {
5383 self.cycle_inline_completion(Direction::Prev, cx);
5384 } else {
5385 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5386 if is_copilot_disabled {
5387 cx.propagate();
5388 }
5389 }
5390 }
5391
5392 pub fn accept_inline_completion(
5393 &mut self,
5394 _: &AcceptInlineCompletion,
5395 cx: &mut ViewContext<Self>,
5396 ) {
5397 let Some(completion) = self.take_active_inline_completion(cx) else {
5398 return;
5399 };
5400 if let Some(provider) = self.inline_completion_provider() {
5401 provider.accept(cx);
5402 }
5403
5404 cx.emit(EditorEvent::InputHandled {
5405 utf16_range_to_replace: None,
5406 text: completion.text.to_string().into(),
5407 });
5408
5409 if let Some(range) = completion.delete_range {
5410 self.change_selections(None, cx, |s| s.select_ranges([range]))
5411 }
5412 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5413 self.refresh_inline_completion(true, true, cx);
5414 cx.notify();
5415 }
5416
5417 pub fn accept_partial_inline_completion(
5418 &mut self,
5419 _: &AcceptPartialInlineCompletion,
5420 cx: &mut ViewContext<Self>,
5421 ) {
5422 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5423 if let Some(completion) = self.take_active_inline_completion(cx) {
5424 let mut partial_completion = completion
5425 .text
5426 .chars()
5427 .by_ref()
5428 .take_while(|c| c.is_alphabetic())
5429 .collect::<String>();
5430 if partial_completion.is_empty() {
5431 partial_completion = completion
5432 .text
5433 .chars()
5434 .by_ref()
5435 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5436 .collect::<String>();
5437 }
5438
5439 cx.emit(EditorEvent::InputHandled {
5440 utf16_range_to_replace: None,
5441 text: partial_completion.clone().into(),
5442 });
5443
5444 if let Some(range) = completion.delete_range {
5445 self.change_selections(None, cx, |s| s.select_ranges([range]))
5446 }
5447 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5448
5449 self.refresh_inline_completion(true, true, cx);
5450 cx.notify();
5451 }
5452 }
5453 }
5454
5455 fn discard_inline_completion(
5456 &mut self,
5457 should_report_inline_completion_event: bool,
5458 cx: &mut ViewContext<Self>,
5459 ) -> bool {
5460 if let Some(provider) = self.inline_completion_provider() {
5461 provider.discard(should_report_inline_completion_event, cx);
5462 }
5463
5464 self.take_active_inline_completion(cx).is_some()
5465 }
5466
5467 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5468 if let Some(completion) = self.active_inline_completion.as_ref() {
5469 let buffer = self.buffer.read(cx).read(cx);
5470 completion.position.is_valid(&buffer)
5471 } else {
5472 false
5473 }
5474 }
5475
5476 fn take_active_inline_completion(
5477 &mut self,
5478 cx: &mut ViewContext<Self>,
5479 ) -> Option<CompletionState> {
5480 let completion = self.active_inline_completion.take()?;
5481 let render_inlay_ids = completion.render_inlay_ids.clone();
5482 self.display_map.update(cx, |map, cx| {
5483 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5484 });
5485 let buffer = self.buffer.read(cx).read(cx);
5486
5487 if completion.position.is_valid(&buffer) {
5488 Some(completion)
5489 } else {
5490 None
5491 }
5492 }
5493
5494 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5495 let selection = self.selections.newest_anchor();
5496 let cursor = selection.head();
5497
5498 let excerpt_id = cursor.excerpt_id;
5499
5500 if self.context_menu.read().is_none()
5501 && self.completion_tasks.is_empty()
5502 && selection.start == selection.end
5503 {
5504 if let Some(provider) = self.inline_completion_provider() {
5505 if let Some((buffer, cursor_buffer_position)) =
5506 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5507 {
5508 if let Some(proposal) =
5509 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5510 {
5511 let mut to_remove = Vec::new();
5512 if let Some(completion) = self.active_inline_completion.take() {
5513 to_remove.extend(completion.render_inlay_ids.iter());
5514 }
5515
5516 let to_add = proposal
5517 .inlays
5518 .iter()
5519 .filter_map(|inlay| {
5520 let snapshot = self.buffer.read(cx).snapshot(cx);
5521 let id = post_inc(&mut self.next_inlay_id);
5522 match inlay {
5523 InlayProposal::Hint(position, hint) => {
5524 let position =
5525 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5526 Some(Inlay::hint(id, position, hint))
5527 }
5528 InlayProposal::Suggestion(position, text) => {
5529 let position =
5530 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5531 Some(Inlay::suggestion(id, position, text.clone()))
5532 }
5533 }
5534 })
5535 .collect_vec();
5536
5537 self.active_inline_completion = Some(CompletionState {
5538 position: cursor,
5539 text: proposal.text,
5540 delete_range: proposal.delete_range.and_then(|range| {
5541 let snapshot = self.buffer.read(cx).snapshot(cx);
5542 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5543 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5544 Some(start?..end?)
5545 }),
5546 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5547 });
5548
5549 self.display_map
5550 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5551
5552 cx.notify();
5553 return;
5554 }
5555 }
5556 }
5557 }
5558
5559 self.discard_inline_completion(false, cx);
5560 }
5561
5562 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5563 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5564 }
5565
5566 fn render_code_actions_indicator(
5567 &self,
5568 _style: &EditorStyle,
5569 row: DisplayRow,
5570 is_active: bool,
5571 cx: &mut ViewContext<Self>,
5572 ) -> Option<IconButton> {
5573 if self.available_code_actions.is_some() {
5574 Some(
5575 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5576 .shape(ui::IconButtonShape::Square)
5577 .icon_size(IconSize::XSmall)
5578 .icon_color(Color::Muted)
5579 .selected(is_active)
5580 .tooltip({
5581 let focus_handle = self.focus_handle.clone();
5582 move |cx| {
5583 Tooltip::for_action_in(
5584 "Toggle Code Actions",
5585 &ToggleCodeActions {
5586 deployed_from_indicator: None,
5587 },
5588 &focus_handle,
5589 cx,
5590 )
5591 }
5592 })
5593 .on_click(cx.listener(move |editor, _e, cx| {
5594 editor.focus(cx);
5595 editor.toggle_code_actions(
5596 &ToggleCodeActions {
5597 deployed_from_indicator: Some(row),
5598 },
5599 cx,
5600 );
5601 })),
5602 )
5603 } else {
5604 None
5605 }
5606 }
5607
5608 fn clear_tasks(&mut self) {
5609 self.tasks.clear()
5610 }
5611
5612 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5613 if self.tasks.insert(key, value).is_some() {
5614 // This case should hopefully be rare, but just in case...
5615 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5616 }
5617 }
5618
5619 fn build_tasks_context(
5620 project: &Model<Project>,
5621 buffer: &Model<Buffer>,
5622 buffer_row: u32,
5623 tasks: &Arc<RunnableTasks>,
5624 cx: &mut ViewContext<Self>,
5625 ) -> Task<Option<task::TaskContext>> {
5626 let position = Point::new(buffer_row, tasks.column);
5627 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5628 let location = Location {
5629 buffer: buffer.clone(),
5630 range: range_start..range_start,
5631 };
5632 // Fill in the environmental variables from the tree-sitter captures
5633 let mut captured_task_variables = TaskVariables::default();
5634 for (capture_name, value) in tasks.extra_variables.clone() {
5635 captured_task_variables.insert(
5636 task::VariableName::Custom(capture_name.into()),
5637 value.clone(),
5638 );
5639 }
5640 project.update(cx, |project, cx| {
5641 project.task_store().update(cx, |task_store, cx| {
5642 task_store.task_context_for_location(captured_task_variables, location, cx)
5643 })
5644 })
5645 }
5646
5647 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5648 let Some((workspace, _)) = self.workspace.clone() else {
5649 return;
5650 };
5651 let Some(project) = self.project.clone() else {
5652 return;
5653 };
5654
5655 // Try to find a closest, enclosing node using tree-sitter that has a
5656 // task
5657 let Some((buffer, buffer_row, tasks)) = self
5658 .find_enclosing_node_task(cx)
5659 // Or find the task that's closest in row-distance.
5660 .or_else(|| self.find_closest_task(cx))
5661 else {
5662 return;
5663 };
5664
5665 let reveal_strategy = action.reveal;
5666 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5667 cx.spawn(|_, mut cx| async move {
5668 let context = task_context.await?;
5669 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5670
5671 let resolved = resolved_task.resolved.as_mut()?;
5672 resolved.reveal = reveal_strategy;
5673
5674 workspace
5675 .update(&mut cx, |workspace, cx| {
5676 workspace::tasks::schedule_resolved_task(
5677 workspace,
5678 task_source_kind,
5679 resolved_task,
5680 false,
5681 cx,
5682 );
5683 })
5684 .ok()
5685 })
5686 .detach();
5687 }
5688
5689 fn find_closest_task(
5690 &mut self,
5691 cx: &mut ViewContext<Self>,
5692 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5693 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5694
5695 let ((buffer_id, row), tasks) = self
5696 .tasks
5697 .iter()
5698 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5699
5700 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5701 let tasks = Arc::new(tasks.to_owned());
5702 Some((buffer, *row, tasks))
5703 }
5704
5705 fn find_enclosing_node_task(
5706 &mut self,
5707 cx: &mut ViewContext<Self>,
5708 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5709 let snapshot = self.buffer.read(cx).snapshot(cx);
5710 let offset = self.selections.newest::<usize>(cx).head();
5711 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5712 let buffer_id = excerpt.buffer().remote_id();
5713
5714 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5715 let mut cursor = layer.node().walk();
5716
5717 while cursor.goto_first_child_for_byte(offset).is_some() {
5718 if cursor.node().end_byte() == offset {
5719 cursor.goto_next_sibling();
5720 }
5721 }
5722
5723 // Ascend to the smallest ancestor that contains the range and has a task.
5724 loop {
5725 let node = cursor.node();
5726 let node_range = node.byte_range();
5727 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5728
5729 // Check if this node contains our offset
5730 if node_range.start <= offset && node_range.end >= offset {
5731 // If it contains offset, check for task
5732 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5733 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5734 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5735 }
5736 }
5737
5738 if !cursor.goto_parent() {
5739 break;
5740 }
5741 }
5742 None
5743 }
5744
5745 fn render_run_indicator(
5746 &self,
5747 _style: &EditorStyle,
5748 is_active: bool,
5749 row: DisplayRow,
5750 cx: &mut ViewContext<Self>,
5751 ) -> IconButton {
5752 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5753 .shape(ui::IconButtonShape::Square)
5754 .icon_size(IconSize::XSmall)
5755 .icon_color(Color::Muted)
5756 .selected(is_active)
5757 .on_click(cx.listener(move |editor, _e, cx| {
5758 editor.focus(cx);
5759 editor.toggle_code_actions(
5760 &ToggleCodeActions {
5761 deployed_from_indicator: Some(row),
5762 },
5763 cx,
5764 );
5765 }))
5766 }
5767
5768 pub fn context_menu_visible(&self) -> bool {
5769 self.context_menu
5770 .read()
5771 .as_ref()
5772 .map_or(false, |menu| menu.visible())
5773 }
5774
5775 fn render_context_menu(
5776 &self,
5777 cursor_position: DisplayPoint,
5778 style: &EditorStyle,
5779 max_height: Pixels,
5780 cx: &mut ViewContext<Editor>,
5781 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5782 self.context_menu.read().as_ref().map(|menu| {
5783 menu.render(
5784 cursor_position,
5785 style,
5786 max_height,
5787 self.workspace.as_ref().map(|(w, _)| w.clone()),
5788 cx,
5789 )
5790 })
5791 }
5792
5793 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5794 cx.notify();
5795 self.completion_tasks.clear();
5796 let context_menu = self.context_menu.write().take();
5797 if context_menu.is_some() {
5798 self.update_visible_inline_completion(cx);
5799 }
5800 context_menu
5801 }
5802
5803 fn show_snippet_choices(
5804 &mut self,
5805 choices: &Vec<String>,
5806 selection: Range<Anchor>,
5807 cx: &mut ViewContext<Self>,
5808 ) {
5809 if selection.start.buffer_id.is_none() {
5810 return;
5811 }
5812 let buffer_id = selection.start.buffer_id.unwrap();
5813 let buffer = self.buffer().read(cx).buffer(buffer_id);
5814 let id = post_inc(&mut self.next_completion_id);
5815
5816 if let Some(buffer) = buffer {
5817 *self.context_menu.write() = Some(ContextMenu::Completions(
5818 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5819 .suppress_documentation_resolution(),
5820 ));
5821 }
5822 }
5823
5824 pub fn insert_snippet(
5825 &mut self,
5826 insertion_ranges: &[Range<usize>],
5827 snippet: Snippet,
5828 cx: &mut ViewContext<Self>,
5829 ) -> Result<()> {
5830 struct Tabstop<T> {
5831 is_end_tabstop: bool,
5832 ranges: Vec<Range<T>>,
5833 choices: Option<Vec<String>>,
5834 }
5835
5836 let tabstops = self.buffer.update(cx, |buffer, cx| {
5837 let snippet_text: Arc<str> = snippet.text.clone().into();
5838 buffer.edit(
5839 insertion_ranges
5840 .iter()
5841 .cloned()
5842 .map(|range| (range, snippet_text.clone())),
5843 Some(AutoindentMode::EachLine),
5844 cx,
5845 );
5846
5847 let snapshot = &*buffer.read(cx);
5848 let snippet = &snippet;
5849 snippet
5850 .tabstops
5851 .iter()
5852 .map(|tabstop| {
5853 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5854 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5855 });
5856 let mut tabstop_ranges = tabstop
5857 .ranges
5858 .iter()
5859 .flat_map(|tabstop_range| {
5860 let mut delta = 0_isize;
5861 insertion_ranges.iter().map(move |insertion_range| {
5862 let insertion_start = insertion_range.start as isize + delta;
5863 delta +=
5864 snippet.text.len() as isize - insertion_range.len() as isize;
5865
5866 let start = ((insertion_start + tabstop_range.start) as usize)
5867 .min(snapshot.len());
5868 let end = ((insertion_start + tabstop_range.end) as usize)
5869 .min(snapshot.len());
5870 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5871 })
5872 })
5873 .collect::<Vec<_>>();
5874 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5875
5876 Tabstop {
5877 is_end_tabstop,
5878 ranges: tabstop_ranges,
5879 choices: tabstop.choices.clone(),
5880 }
5881 })
5882 .collect::<Vec<_>>()
5883 });
5884 if let Some(tabstop) = tabstops.first() {
5885 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5886 s.select_ranges(tabstop.ranges.iter().cloned());
5887 });
5888
5889 if let Some(choices) = &tabstop.choices {
5890 if let Some(selection) = tabstop.ranges.first() {
5891 self.show_snippet_choices(choices, selection.clone(), cx)
5892 }
5893 }
5894
5895 // If we're already at the last tabstop and it's at the end of the snippet,
5896 // we're done, we don't need to keep the state around.
5897 if !tabstop.is_end_tabstop {
5898 let choices = tabstops
5899 .iter()
5900 .map(|tabstop| tabstop.choices.clone())
5901 .collect();
5902
5903 let ranges = tabstops
5904 .into_iter()
5905 .map(|tabstop| tabstop.ranges)
5906 .collect::<Vec<_>>();
5907
5908 self.snippet_stack.push(SnippetState {
5909 active_index: 0,
5910 ranges,
5911 choices,
5912 });
5913 }
5914
5915 // Check whether the just-entered snippet ends with an auto-closable bracket.
5916 if self.autoclose_regions.is_empty() {
5917 let snapshot = self.buffer.read(cx).snapshot(cx);
5918 for selection in &mut self.selections.all::<Point>(cx) {
5919 let selection_head = selection.head();
5920 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5921 continue;
5922 };
5923
5924 let mut bracket_pair = None;
5925 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5926 let prev_chars = snapshot
5927 .reversed_chars_at(selection_head)
5928 .collect::<String>();
5929 for (pair, enabled) in scope.brackets() {
5930 if enabled
5931 && pair.close
5932 && prev_chars.starts_with(pair.start.as_str())
5933 && next_chars.starts_with(pair.end.as_str())
5934 {
5935 bracket_pair = Some(pair.clone());
5936 break;
5937 }
5938 }
5939 if let Some(pair) = bracket_pair {
5940 let start = snapshot.anchor_after(selection_head);
5941 let end = snapshot.anchor_after(selection_head);
5942 self.autoclose_regions.push(AutocloseRegion {
5943 selection_id: selection.id,
5944 range: start..end,
5945 pair,
5946 });
5947 }
5948 }
5949 }
5950 }
5951 Ok(())
5952 }
5953
5954 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5955 self.move_to_snippet_tabstop(Bias::Right, cx)
5956 }
5957
5958 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5959 self.move_to_snippet_tabstop(Bias::Left, cx)
5960 }
5961
5962 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5963 if let Some(mut snippet) = self.snippet_stack.pop() {
5964 match bias {
5965 Bias::Left => {
5966 if snippet.active_index > 0 {
5967 snippet.active_index -= 1;
5968 } else {
5969 self.snippet_stack.push(snippet);
5970 return false;
5971 }
5972 }
5973 Bias::Right => {
5974 if snippet.active_index + 1 < snippet.ranges.len() {
5975 snippet.active_index += 1;
5976 } else {
5977 self.snippet_stack.push(snippet);
5978 return false;
5979 }
5980 }
5981 }
5982 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5983 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5984 s.select_anchor_ranges(current_ranges.iter().cloned())
5985 });
5986
5987 if let Some(choices) = &snippet.choices[snippet.active_index] {
5988 if let Some(selection) = current_ranges.first() {
5989 self.show_snippet_choices(&choices, selection.clone(), cx);
5990 }
5991 }
5992
5993 // If snippet state is not at the last tabstop, push it back on the stack
5994 if snippet.active_index + 1 < snippet.ranges.len() {
5995 self.snippet_stack.push(snippet);
5996 }
5997 return true;
5998 }
5999 }
6000
6001 false
6002 }
6003
6004 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
6005 self.transact(cx, |this, cx| {
6006 this.select_all(&SelectAll, cx);
6007 this.insert("", cx);
6008 });
6009 }
6010
6011 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
6012 self.transact(cx, |this, cx| {
6013 this.select_autoclose_pair(cx);
6014 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6015 if !this.linked_edit_ranges.is_empty() {
6016 let selections = this.selections.all::<MultiBufferPoint>(cx);
6017 let snapshot = this.buffer.read(cx).snapshot(cx);
6018
6019 for selection in selections.iter() {
6020 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6021 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6022 if selection_start.buffer_id != selection_end.buffer_id {
6023 continue;
6024 }
6025 if let Some(ranges) =
6026 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6027 {
6028 for (buffer, entries) in ranges {
6029 linked_ranges.entry(buffer).or_default().extend(entries);
6030 }
6031 }
6032 }
6033 }
6034
6035 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6036 if !this.selections.line_mode {
6037 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6038 for selection in &mut selections {
6039 if selection.is_empty() {
6040 let old_head = selection.head();
6041 let mut new_head =
6042 movement::left(&display_map, old_head.to_display_point(&display_map))
6043 .to_point(&display_map);
6044 if let Some((buffer, line_buffer_range)) = display_map
6045 .buffer_snapshot
6046 .buffer_line_for_row(MultiBufferRow(old_head.row))
6047 {
6048 let indent_size =
6049 buffer.indent_size_for_line(line_buffer_range.start.row);
6050 let indent_len = match indent_size.kind {
6051 IndentKind::Space => {
6052 buffer.settings_at(line_buffer_range.start, cx).tab_size
6053 }
6054 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6055 };
6056 if old_head.column <= indent_size.len && old_head.column > 0 {
6057 let indent_len = indent_len.get();
6058 new_head = cmp::min(
6059 new_head,
6060 MultiBufferPoint::new(
6061 old_head.row,
6062 ((old_head.column - 1) / indent_len) * indent_len,
6063 ),
6064 );
6065 }
6066 }
6067
6068 selection.set_head(new_head, SelectionGoal::None);
6069 }
6070 }
6071 }
6072
6073 this.signature_help_state.set_backspace_pressed(true);
6074 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6075 this.insert("", cx);
6076 let empty_str: Arc<str> = Arc::from("");
6077 for (buffer, edits) in linked_ranges {
6078 let snapshot = buffer.read(cx).snapshot();
6079 use text::ToPoint as TP;
6080
6081 let edits = edits
6082 .into_iter()
6083 .map(|range| {
6084 let end_point = TP::to_point(&range.end, &snapshot);
6085 let mut start_point = TP::to_point(&range.start, &snapshot);
6086
6087 if end_point == start_point {
6088 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6089 .saturating_sub(1);
6090 start_point = TP::to_point(&offset, &snapshot);
6091 };
6092
6093 (start_point..end_point, empty_str.clone())
6094 })
6095 .sorted_by_key(|(range, _)| range.start)
6096 .collect::<Vec<_>>();
6097 buffer.update(cx, |this, cx| {
6098 this.edit(edits, None, cx);
6099 })
6100 }
6101 this.refresh_inline_completion(true, false, cx);
6102 linked_editing_ranges::refresh_linked_ranges(this, cx);
6103 });
6104 }
6105
6106 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6107 self.transact(cx, |this, cx| {
6108 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6109 let line_mode = s.line_mode;
6110 s.move_with(|map, selection| {
6111 if selection.is_empty() && !line_mode {
6112 let cursor = movement::right(map, selection.head());
6113 selection.end = cursor;
6114 selection.reversed = true;
6115 selection.goal = SelectionGoal::None;
6116 }
6117 })
6118 });
6119 this.insert("", cx);
6120 this.refresh_inline_completion(true, false, cx);
6121 });
6122 }
6123
6124 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6125 if self.move_to_prev_snippet_tabstop(cx) {
6126 return;
6127 }
6128
6129 self.outdent(&Outdent, cx);
6130 }
6131
6132 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6133 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6134 return;
6135 }
6136
6137 let mut selections = self.selections.all_adjusted(cx);
6138 let buffer = self.buffer.read(cx);
6139 let snapshot = buffer.snapshot(cx);
6140 let rows_iter = selections.iter().map(|s| s.head().row);
6141 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6142
6143 let mut edits = Vec::new();
6144 let mut prev_edited_row = 0;
6145 let mut row_delta = 0;
6146 for selection in &mut selections {
6147 if selection.start.row != prev_edited_row {
6148 row_delta = 0;
6149 }
6150 prev_edited_row = selection.end.row;
6151
6152 // If the selection is non-empty, then increase the indentation of the selected lines.
6153 if !selection.is_empty() {
6154 row_delta =
6155 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6156 continue;
6157 }
6158
6159 // If the selection is empty and the cursor is in the leading whitespace before the
6160 // suggested indentation, then auto-indent the line.
6161 let cursor = selection.head();
6162 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6163 if let Some(suggested_indent) =
6164 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6165 {
6166 if cursor.column < suggested_indent.len
6167 && cursor.column <= current_indent.len
6168 && current_indent.len <= suggested_indent.len
6169 {
6170 selection.start = Point::new(cursor.row, suggested_indent.len);
6171 selection.end = selection.start;
6172 if row_delta == 0 {
6173 edits.extend(Buffer::edit_for_indent_size_adjustment(
6174 cursor.row,
6175 current_indent,
6176 suggested_indent,
6177 ));
6178 row_delta = suggested_indent.len - current_indent.len;
6179 }
6180 continue;
6181 }
6182 }
6183
6184 // Otherwise, insert a hard or soft tab.
6185 let settings = buffer.settings_at(cursor, cx);
6186 let tab_size = if settings.hard_tabs {
6187 IndentSize::tab()
6188 } else {
6189 let tab_size = settings.tab_size.get();
6190 let char_column = snapshot
6191 .text_for_range(Point::new(cursor.row, 0)..cursor)
6192 .flat_map(str::chars)
6193 .count()
6194 + row_delta as usize;
6195 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6196 IndentSize::spaces(chars_to_next_tab_stop)
6197 };
6198 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6199 selection.end = selection.start;
6200 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6201 row_delta += tab_size.len;
6202 }
6203
6204 self.transact(cx, |this, cx| {
6205 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6206 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6207 this.refresh_inline_completion(true, false, cx);
6208 });
6209 }
6210
6211 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6212 if self.read_only(cx) {
6213 return;
6214 }
6215 let mut selections = self.selections.all::<Point>(cx);
6216 let mut prev_edited_row = 0;
6217 let mut row_delta = 0;
6218 let mut edits = Vec::new();
6219 let buffer = self.buffer.read(cx);
6220 let snapshot = buffer.snapshot(cx);
6221 for selection in &mut selections {
6222 if selection.start.row != prev_edited_row {
6223 row_delta = 0;
6224 }
6225 prev_edited_row = selection.end.row;
6226
6227 row_delta =
6228 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6229 }
6230
6231 self.transact(cx, |this, cx| {
6232 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6233 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6234 });
6235 }
6236
6237 fn indent_selection(
6238 buffer: &MultiBuffer,
6239 snapshot: &MultiBufferSnapshot,
6240 selection: &mut Selection<Point>,
6241 edits: &mut Vec<(Range<Point>, String)>,
6242 delta_for_start_row: u32,
6243 cx: &AppContext,
6244 ) -> u32 {
6245 let settings = buffer.settings_at(selection.start, cx);
6246 let tab_size = settings.tab_size.get();
6247 let indent_kind = if settings.hard_tabs {
6248 IndentKind::Tab
6249 } else {
6250 IndentKind::Space
6251 };
6252 let mut start_row = selection.start.row;
6253 let mut end_row = selection.end.row + 1;
6254
6255 // If a selection ends at the beginning of a line, don't indent
6256 // that last line.
6257 if selection.end.column == 0 && selection.end.row > selection.start.row {
6258 end_row -= 1;
6259 }
6260
6261 // Avoid re-indenting a row that has already been indented by a
6262 // previous selection, but still update this selection's column
6263 // to reflect that indentation.
6264 if delta_for_start_row > 0 {
6265 start_row += 1;
6266 selection.start.column += delta_for_start_row;
6267 if selection.end.row == selection.start.row {
6268 selection.end.column += delta_for_start_row;
6269 }
6270 }
6271
6272 let mut delta_for_end_row = 0;
6273 let has_multiple_rows = start_row + 1 != end_row;
6274 for row in start_row..end_row {
6275 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6276 let indent_delta = match (current_indent.kind, indent_kind) {
6277 (IndentKind::Space, IndentKind::Space) => {
6278 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6279 IndentSize::spaces(columns_to_next_tab_stop)
6280 }
6281 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6282 (_, IndentKind::Tab) => IndentSize::tab(),
6283 };
6284
6285 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6286 0
6287 } else {
6288 selection.start.column
6289 };
6290 let row_start = Point::new(row, start);
6291 edits.push((
6292 row_start..row_start,
6293 indent_delta.chars().collect::<String>(),
6294 ));
6295
6296 // Update this selection's endpoints to reflect the indentation.
6297 if row == selection.start.row {
6298 selection.start.column += indent_delta.len;
6299 }
6300 if row == selection.end.row {
6301 selection.end.column += indent_delta.len;
6302 delta_for_end_row = indent_delta.len;
6303 }
6304 }
6305
6306 if selection.start.row == selection.end.row {
6307 delta_for_start_row + delta_for_end_row
6308 } else {
6309 delta_for_end_row
6310 }
6311 }
6312
6313 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6314 if self.read_only(cx) {
6315 return;
6316 }
6317 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6318 let selections = self.selections.all::<Point>(cx);
6319 let mut deletion_ranges = Vec::new();
6320 let mut last_outdent = None;
6321 {
6322 let buffer = self.buffer.read(cx);
6323 let snapshot = buffer.snapshot(cx);
6324 for selection in &selections {
6325 let settings = buffer.settings_at(selection.start, cx);
6326 let tab_size = settings.tab_size.get();
6327 let mut rows = selection.spanned_rows(false, &display_map);
6328
6329 // Avoid re-outdenting a row that has already been outdented by a
6330 // previous selection.
6331 if let Some(last_row) = last_outdent {
6332 if last_row == rows.start {
6333 rows.start = rows.start.next_row();
6334 }
6335 }
6336 let has_multiple_rows = rows.len() > 1;
6337 for row in rows.iter_rows() {
6338 let indent_size = snapshot.indent_size_for_line(row);
6339 if indent_size.len > 0 {
6340 let deletion_len = match indent_size.kind {
6341 IndentKind::Space => {
6342 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6343 if columns_to_prev_tab_stop == 0 {
6344 tab_size
6345 } else {
6346 columns_to_prev_tab_stop
6347 }
6348 }
6349 IndentKind::Tab => 1,
6350 };
6351 let start = if has_multiple_rows
6352 || deletion_len > selection.start.column
6353 || indent_size.len < selection.start.column
6354 {
6355 0
6356 } else {
6357 selection.start.column - deletion_len
6358 };
6359 deletion_ranges.push(
6360 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6361 );
6362 last_outdent = Some(row);
6363 }
6364 }
6365 }
6366 }
6367
6368 self.transact(cx, |this, cx| {
6369 this.buffer.update(cx, |buffer, cx| {
6370 let empty_str: Arc<str> = Arc::default();
6371 buffer.edit(
6372 deletion_ranges
6373 .into_iter()
6374 .map(|range| (range, empty_str.clone())),
6375 None,
6376 cx,
6377 );
6378 });
6379 let selections = this.selections.all::<usize>(cx);
6380 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6381 });
6382 }
6383
6384 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6385 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6386 let selections = self.selections.all::<Point>(cx);
6387
6388 let mut new_cursors = Vec::new();
6389 let mut edit_ranges = Vec::new();
6390 let mut selections = selections.iter().peekable();
6391 while let Some(selection) = selections.next() {
6392 let mut rows = selection.spanned_rows(false, &display_map);
6393 let goal_display_column = selection.head().to_display_point(&display_map).column();
6394
6395 // Accumulate contiguous regions of rows that we want to delete.
6396 while let Some(next_selection) = selections.peek() {
6397 let next_rows = next_selection.spanned_rows(false, &display_map);
6398 if next_rows.start <= rows.end {
6399 rows.end = next_rows.end;
6400 selections.next().unwrap();
6401 } else {
6402 break;
6403 }
6404 }
6405
6406 let buffer = &display_map.buffer_snapshot;
6407 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6408 let edit_end;
6409 let cursor_buffer_row;
6410 if buffer.max_point().row >= rows.end.0 {
6411 // If there's a line after the range, delete the \n from the end of the row range
6412 // and position the cursor on the next line.
6413 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6414 cursor_buffer_row = rows.end;
6415 } else {
6416 // If there isn't a line after the range, delete the \n from the line before the
6417 // start of the row range and position the cursor there.
6418 edit_start = edit_start.saturating_sub(1);
6419 edit_end = buffer.len();
6420 cursor_buffer_row = rows.start.previous_row();
6421 }
6422
6423 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6424 *cursor.column_mut() =
6425 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6426
6427 new_cursors.push((
6428 selection.id,
6429 buffer.anchor_after(cursor.to_point(&display_map)),
6430 ));
6431 edit_ranges.push(edit_start..edit_end);
6432 }
6433
6434 self.transact(cx, |this, cx| {
6435 let buffer = this.buffer.update(cx, |buffer, cx| {
6436 let empty_str: Arc<str> = Arc::default();
6437 buffer.edit(
6438 edit_ranges
6439 .into_iter()
6440 .map(|range| (range, empty_str.clone())),
6441 None,
6442 cx,
6443 );
6444 buffer.snapshot(cx)
6445 });
6446 let new_selections = new_cursors
6447 .into_iter()
6448 .map(|(id, cursor)| {
6449 let cursor = cursor.to_point(&buffer);
6450 Selection {
6451 id,
6452 start: cursor,
6453 end: cursor,
6454 reversed: false,
6455 goal: SelectionGoal::None,
6456 }
6457 })
6458 .collect();
6459
6460 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6461 s.select(new_selections);
6462 });
6463 });
6464 }
6465
6466 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6467 if self.read_only(cx) {
6468 return;
6469 }
6470 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6471 for selection in self.selections.all::<Point>(cx) {
6472 let start = MultiBufferRow(selection.start.row);
6473 // Treat single line selections as if they include the next line. Otherwise this action
6474 // would do nothing for single line selections individual cursors.
6475 let end = if selection.start.row == selection.end.row {
6476 MultiBufferRow(selection.start.row + 1)
6477 } else {
6478 MultiBufferRow(selection.end.row)
6479 };
6480
6481 if let Some(last_row_range) = row_ranges.last_mut() {
6482 if start <= last_row_range.end {
6483 last_row_range.end = end;
6484 continue;
6485 }
6486 }
6487 row_ranges.push(start..end);
6488 }
6489
6490 let snapshot = self.buffer.read(cx).snapshot(cx);
6491 let mut cursor_positions = Vec::new();
6492 for row_range in &row_ranges {
6493 let anchor = snapshot.anchor_before(Point::new(
6494 row_range.end.previous_row().0,
6495 snapshot.line_len(row_range.end.previous_row()),
6496 ));
6497 cursor_positions.push(anchor..anchor);
6498 }
6499
6500 self.transact(cx, |this, cx| {
6501 for row_range in row_ranges.into_iter().rev() {
6502 for row in row_range.iter_rows().rev() {
6503 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6504 let next_line_row = row.next_row();
6505 let indent = snapshot.indent_size_for_line(next_line_row);
6506 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6507
6508 let replace = if snapshot.line_len(next_line_row) > indent.len {
6509 " "
6510 } else {
6511 ""
6512 };
6513
6514 this.buffer.update(cx, |buffer, cx| {
6515 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6516 });
6517 }
6518 }
6519
6520 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6521 s.select_anchor_ranges(cursor_positions)
6522 });
6523 });
6524 }
6525
6526 pub fn sort_lines_case_sensitive(
6527 &mut self,
6528 _: &SortLinesCaseSensitive,
6529 cx: &mut ViewContext<Self>,
6530 ) {
6531 self.manipulate_lines(cx, |lines| lines.sort())
6532 }
6533
6534 pub fn sort_lines_case_insensitive(
6535 &mut self,
6536 _: &SortLinesCaseInsensitive,
6537 cx: &mut ViewContext<Self>,
6538 ) {
6539 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6540 }
6541
6542 pub fn unique_lines_case_insensitive(
6543 &mut self,
6544 _: &UniqueLinesCaseInsensitive,
6545 cx: &mut ViewContext<Self>,
6546 ) {
6547 self.manipulate_lines(cx, |lines| {
6548 let mut seen = HashSet::default();
6549 lines.retain(|line| seen.insert(line.to_lowercase()));
6550 })
6551 }
6552
6553 pub fn unique_lines_case_sensitive(
6554 &mut self,
6555 _: &UniqueLinesCaseSensitive,
6556 cx: &mut ViewContext<Self>,
6557 ) {
6558 self.manipulate_lines(cx, |lines| {
6559 let mut seen = HashSet::default();
6560 lines.retain(|line| seen.insert(*line));
6561 })
6562 }
6563
6564 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6565 let mut revert_changes = HashMap::default();
6566 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6567 for hunk in hunks_for_rows(
6568 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6569 &multi_buffer_snapshot,
6570 ) {
6571 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6572 }
6573 if !revert_changes.is_empty() {
6574 self.transact(cx, |editor, cx| {
6575 editor.revert(revert_changes, cx);
6576 });
6577 }
6578 }
6579
6580 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6581 let Some(project) = self.project.clone() else {
6582 return;
6583 };
6584 self.reload(project, cx).detach_and_notify_err(cx);
6585 }
6586
6587 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6588 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6589 if !revert_changes.is_empty() {
6590 self.transact(cx, |editor, cx| {
6591 editor.revert(revert_changes, cx);
6592 });
6593 }
6594 }
6595
6596 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6597 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6598 let project_path = buffer.read(cx).project_path(cx)?;
6599 let project = self.project.as_ref()?.read(cx);
6600 let entry = project.entry_for_path(&project_path, cx)?;
6601 let parent = match &entry.canonical_path {
6602 Some(canonical_path) => canonical_path.to_path_buf(),
6603 None => project.absolute_path(&project_path, cx)?,
6604 }
6605 .parent()?
6606 .to_path_buf();
6607 Some(parent)
6608 }) {
6609 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6610 }
6611 }
6612
6613 fn gather_revert_changes(
6614 &mut self,
6615 selections: &[Selection<Anchor>],
6616 cx: &mut ViewContext<'_, Editor>,
6617 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6618 let mut revert_changes = HashMap::default();
6619 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6620 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6621 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6622 }
6623 revert_changes
6624 }
6625
6626 pub fn prepare_revert_change(
6627 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6628 multi_buffer: &Model<MultiBuffer>,
6629 hunk: &MultiBufferDiffHunk,
6630 cx: &AppContext,
6631 ) -> Option<()> {
6632 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6633 let buffer = buffer.read(cx);
6634 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6635 let buffer_snapshot = buffer.snapshot();
6636 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6637 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6638 probe
6639 .0
6640 .start
6641 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6642 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6643 }) {
6644 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6645 Some(())
6646 } else {
6647 None
6648 }
6649 }
6650
6651 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6652 self.manipulate_lines(cx, |lines| lines.reverse())
6653 }
6654
6655 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6656 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6657 }
6658
6659 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6660 where
6661 Fn: FnMut(&mut Vec<&str>),
6662 {
6663 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6664 let buffer = self.buffer.read(cx).snapshot(cx);
6665
6666 let mut edits = Vec::new();
6667
6668 let selections = self.selections.all::<Point>(cx);
6669 let mut selections = selections.iter().peekable();
6670 let mut contiguous_row_selections = Vec::new();
6671 let mut new_selections = Vec::new();
6672 let mut added_lines = 0;
6673 let mut removed_lines = 0;
6674
6675 while let Some(selection) = selections.next() {
6676 let (start_row, end_row) = consume_contiguous_rows(
6677 &mut contiguous_row_selections,
6678 selection,
6679 &display_map,
6680 &mut selections,
6681 );
6682
6683 let start_point = Point::new(start_row.0, 0);
6684 let end_point = Point::new(
6685 end_row.previous_row().0,
6686 buffer.line_len(end_row.previous_row()),
6687 );
6688 let text = buffer
6689 .text_for_range(start_point..end_point)
6690 .collect::<String>();
6691
6692 let mut lines = text.split('\n').collect_vec();
6693
6694 let lines_before = lines.len();
6695 callback(&mut lines);
6696 let lines_after = lines.len();
6697
6698 edits.push((start_point..end_point, lines.join("\n")));
6699
6700 // Selections must change based on added and removed line count
6701 let start_row =
6702 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6703 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6704 new_selections.push(Selection {
6705 id: selection.id,
6706 start: start_row,
6707 end: end_row,
6708 goal: SelectionGoal::None,
6709 reversed: selection.reversed,
6710 });
6711
6712 if lines_after > lines_before {
6713 added_lines += lines_after - lines_before;
6714 } else if lines_before > lines_after {
6715 removed_lines += lines_before - lines_after;
6716 }
6717 }
6718
6719 self.transact(cx, |this, cx| {
6720 let buffer = this.buffer.update(cx, |buffer, cx| {
6721 buffer.edit(edits, None, cx);
6722 buffer.snapshot(cx)
6723 });
6724
6725 // Recalculate offsets on newly edited buffer
6726 let new_selections = new_selections
6727 .iter()
6728 .map(|s| {
6729 let start_point = Point::new(s.start.0, 0);
6730 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6731 Selection {
6732 id: s.id,
6733 start: buffer.point_to_offset(start_point),
6734 end: buffer.point_to_offset(end_point),
6735 goal: s.goal,
6736 reversed: s.reversed,
6737 }
6738 })
6739 .collect();
6740
6741 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6742 s.select(new_selections);
6743 });
6744
6745 this.request_autoscroll(Autoscroll::fit(), cx);
6746 });
6747 }
6748
6749 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6750 self.manipulate_text(cx, |text| text.to_uppercase())
6751 }
6752
6753 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6754 self.manipulate_text(cx, |text| text.to_lowercase())
6755 }
6756
6757 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6758 self.manipulate_text(cx, |text| {
6759 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6760 // https://github.com/rutrum/convert-case/issues/16
6761 text.split('\n')
6762 .map(|line| line.to_case(Case::Title))
6763 .join("\n")
6764 })
6765 }
6766
6767 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6768 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6769 }
6770
6771 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6772 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6773 }
6774
6775 pub fn convert_to_upper_camel_case(
6776 &mut self,
6777 _: &ConvertToUpperCamelCase,
6778 cx: &mut ViewContext<Self>,
6779 ) {
6780 self.manipulate_text(cx, |text| {
6781 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6782 // https://github.com/rutrum/convert-case/issues/16
6783 text.split('\n')
6784 .map(|line| line.to_case(Case::UpperCamel))
6785 .join("\n")
6786 })
6787 }
6788
6789 pub fn convert_to_lower_camel_case(
6790 &mut self,
6791 _: &ConvertToLowerCamelCase,
6792 cx: &mut ViewContext<Self>,
6793 ) {
6794 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6795 }
6796
6797 pub fn convert_to_opposite_case(
6798 &mut self,
6799 _: &ConvertToOppositeCase,
6800 cx: &mut ViewContext<Self>,
6801 ) {
6802 self.manipulate_text(cx, |text| {
6803 text.chars()
6804 .fold(String::with_capacity(text.len()), |mut t, c| {
6805 if c.is_uppercase() {
6806 t.extend(c.to_lowercase());
6807 } else {
6808 t.extend(c.to_uppercase());
6809 }
6810 t
6811 })
6812 })
6813 }
6814
6815 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6816 where
6817 Fn: FnMut(&str) -> String,
6818 {
6819 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6820 let buffer = self.buffer.read(cx).snapshot(cx);
6821
6822 let mut new_selections = Vec::new();
6823 let mut edits = Vec::new();
6824 let mut selection_adjustment = 0i32;
6825
6826 for selection in self.selections.all::<usize>(cx) {
6827 let selection_is_empty = selection.is_empty();
6828
6829 let (start, end) = if selection_is_empty {
6830 let word_range = movement::surrounding_word(
6831 &display_map,
6832 selection.start.to_display_point(&display_map),
6833 );
6834 let start = word_range.start.to_offset(&display_map, Bias::Left);
6835 let end = word_range.end.to_offset(&display_map, Bias::Left);
6836 (start, end)
6837 } else {
6838 (selection.start, selection.end)
6839 };
6840
6841 let text = buffer.text_for_range(start..end).collect::<String>();
6842 let old_length = text.len() as i32;
6843 let text = callback(&text);
6844
6845 new_selections.push(Selection {
6846 start: (start as i32 - selection_adjustment) as usize,
6847 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6848 goal: SelectionGoal::None,
6849 ..selection
6850 });
6851
6852 selection_adjustment += old_length - text.len() as i32;
6853
6854 edits.push((start..end, text));
6855 }
6856
6857 self.transact(cx, |this, cx| {
6858 this.buffer.update(cx, |buffer, cx| {
6859 buffer.edit(edits, None, cx);
6860 });
6861
6862 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6863 s.select(new_selections);
6864 });
6865
6866 this.request_autoscroll(Autoscroll::fit(), cx);
6867 });
6868 }
6869
6870 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6872 let buffer = &display_map.buffer_snapshot;
6873 let selections = self.selections.all::<Point>(cx);
6874
6875 let mut edits = Vec::new();
6876 let mut selections_iter = selections.iter().peekable();
6877 while let Some(selection) = selections_iter.next() {
6878 // Avoid duplicating the same lines twice.
6879 let mut rows = selection.spanned_rows(false, &display_map);
6880
6881 while let Some(next_selection) = selections_iter.peek() {
6882 let next_rows = next_selection.spanned_rows(false, &display_map);
6883 if next_rows.start < rows.end {
6884 rows.end = next_rows.end;
6885 selections_iter.next().unwrap();
6886 } else {
6887 break;
6888 }
6889 }
6890
6891 // Copy the text from the selected row region and splice it either at the start
6892 // or end of the region.
6893 let start = Point::new(rows.start.0, 0);
6894 let end = Point::new(
6895 rows.end.previous_row().0,
6896 buffer.line_len(rows.end.previous_row()),
6897 );
6898 let text = buffer
6899 .text_for_range(start..end)
6900 .chain(Some("\n"))
6901 .collect::<String>();
6902 let insert_location = if upwards {
6903 Point::new(rows.end.0, 0)
6904 } else {
6905 start
6906 };
6907 edits.push((insert_location..insert_location, text));
6908 }
6909
6910 self.transact(cx, |this, cx| {
6911 this.buffer.update(cx, |buffer, cx| {
6912 buffer.edit(edits, None, cx);
6913 });
6914
6915 this.request_autoscroll(Autoscroll::fit(), cx);
6916 });
6917 }
6918
6919 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6920 self.duplicate_line(true, cx);
6921 }
6922
6923 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6924 self.duplicate_line(false, cx);
6925 }
6926
6927 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6928 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6929 let buffer = self.buffer.read(cx).snapshot(cx);
6930
6931 let mut edits = Vec::new();
6932 let mut unfold_ranges = Vec::new();
6933 let mut refold_creases = Vec::new();
6934
6935 let selections = self.selections.all::<Point>(cx);
6936 let mut selections = selections.iter().peekable();
6937 let mut contiguous_row_selections = Vec::new();
6938 let mut new_selections = Vec::new();
6939
6940 while let Some(selection) = selections.next() {
6941 // Find all the selections that span a contiguous row range
6942 let (start_row, end_row) = consume_contiguous_rows(
6943 &mut contiguous_row_selections,
6944 selection,
6945 &display_map,
6946 &mut selections,
6947 );
6948
6949 // Move the text spanned by the row range to be before the line preceding the row range
6950 if start_row.0 > 0 {
6951 let range_to_move = Point::new(
6952 start_row.previous_row().0,
6953 buffer.line_len(start_row.previous_row()),
6954 )
6955 ..Point::new(
6956 end_row.previous_row().0,
6957 buffer.line_len(end_row.previous_row()),
6958 );
6959 let insertion_point = display_map
6960 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6961 .0;
6962
6963 // Don't move lines across excerpts
6964 if buffer
6965 .excerpt_boundaries_in_range((
6966 Bound::Excluded(insertion_point),
6967 Bound::Included(range_to_move.end),
6968 ))
6969 .next()
6970 .is_none()
6971 {
6972 let text = buffer
6973 .text_for_range(range_to_move.clone())
6974 .flat_map(|s| s.chars())
6975 .skip(1)
6976 .chain(['\n'])
6977 .collect::<String>();
6978
6979 edits.push((
6980 buffer.anchor_after(range_to_move.start)
6981 ..buffer.anchor_before(range_to_move.end),
6982 String::new(),
6983 ));
6984 let insertion_anchor = buffer.anchor_after(insertion_point);
6985 edits.push((insertion_anchor..insertion_anchor, text));
6986
6987 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6988
6989 // Move selections up
6990 new_selections.extend(contiguous_row_selections.drain(..).map(
6991 |mut selection| {
6992 selection.start.row -= row_delta;
6993 selection.end.row -= row_delta;
6994 selection
6995 },
6996 ));
6997
6998 // Move folds up
6999 unfold_ranges.push(range_to_move.clone());
7000 for fold in display_map.folds_in_range(
7001 buffer.anchor_before(range_to_move.start)
7002 ..buffer.anchor_after(range_to_move.end),
7003 ) {
7004 let mut start = fold.range.start.to_point(&buffer);
7005 let mut end = fold.range.end.to_point(&buffer);
7006 start.row -= row_delta;
7007 end.row -= row_delta;
7008 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7009 }
7010 }
7011 }
7012
7013 // If we didn't move line(s), preserve the existing selections
7014 new_selections.append(&mut contiguous_row_selections);
7015 }
7016
7017 self.transact(cx, |this, cx| {
7018 this.unfold_ranges(&unfold_ranges, true, true, cx);
7019 this.buffer.update(cx, |buffer, cx| {
7020 for (range, text) in edits {
7021 buffer.edit([(range, text)], None, cx);
7022 }
7023 });
7024 this.fold_creases(refold_creases, true, cx);
7025 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7026 s.select(new_selections);
7027 })
7028 });
7029 }
7030
7031 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
7032 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7033 let buffer = self.buffer.read(cx).snapshot(cx);
7034
7035 let mut edits = Vec::new();
7036 let mut unfold_ranges = Vec::new();
7037 let mut refold_creases = Vec::new();
7038
7039 let selections = self.selections.all::<Point>(cx);
7040 let mut selections = selections.iter().peekable();
7041 let mut contiguous_row_selections = Vec::new();
7042 let mut new_selections = Vec::new();
7043
7044 while let Some(selection) = selections.next() {
7045 // Find all the selections that span a contiguous row range
7046 let (start_row, end_row) = consume_contiguous_rows(
7047 &mut contiguous_row_selections,
7048 selection,
7049 &display_map,
7050 &mut selections,
7051 );
7052
7053 // Move the text spanned by the row range to be after the last line of the row range
7054 if end_row.0 <= buffer.max_point().row {
7055 let range_to_move =
7056 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7057 let insertion_point = display_map
7058 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7059 .0;
7060
7061 // Don't move lines across excerpt boundaries
7062 if buffer
7063 .excerpt_boundaries_in_range((
7064 Bound::Excluded(range_to_move.start),
7065 Bound::Included(insertion_point),
7066 ))
7067 .next()
7068 .is_none()
7069 {
7070 let mut text = String::from("\n");
7071 text.extend(buffer.text_for_range(range_to_move.clone()));
7072 text.pop(); // Drop trailing newline
7073 edits.push((
7074 buffer.anchor_after(range_to_move.start)
7075 ..buffer.anchor_before(range_to_move.end),
7076 String::new(),
7077 ));
7078 let insertion_anchor = buffer.anchor_after(insertion_point);
7079 edits.push((insertion_anchor..insertion_anchor, text));
7080
7081 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7082
7083 // Move selections down
7084 new_selections.extend(contiguous_row_selections.drain(..).map(
7085 |mut selection| {
7086 selection.start.row += row_delta;
7087 selection.end.row += row_delta;
7088 selection
7089 },
7090 ));
7091
7092 // Move folds down
7093 unfold_ranges.push(range_to_move.clone());
7094 for fold in display_map.folds_in_range(
7095 buffer.anchor_before(range_to_move.start)
7096 ..buffer.anchor_after(range_to_move.end),
7097 ) {
7098 let mut start = fold.range.start.to_point(&buffer);
7099 let mut end = fold.range.end.to_point(&buffer);
7100 start.row += row_delta;
7101 end.row += row_delta;
7102 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7103 }
7104 }
7105 }
7106
7107 // If we didn't move line(s), preserve the existing selections
7108 new_selections.append(&mut contiguous_row_selections);
7109 }
7110
7111 self.transact(cx, |this, cx| {
7112 this.unfold_ranges(&unfold_ranges, true, true, cx);
7113 this.buffer.update(cx, |buffer, cx| {
7114 for (range, text) in edits {
7115 buffer.edit([(range, text)], None, cx);
7116 }
7117 });
7118 this.fold_creases(refold_creases, true, cx);
7119 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7120 });
7121 }
7122
7123 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7124 let text_layout_details = &self.text_layout_details(cx);
7125 self.transact(cx, |this, cx| {
7126 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7127 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7128 let line_mode = s.line_mode;
7129 s.move_with(|display_map, selection| {
7130 if !selection.is_empty() || line_mode {
7131 return;
7132 }
7133
7134 let mut head = selection.head();
7135 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7136 if head.column() == display_map.line_len(head.row()) {
7137 transpose_offset = display_map
7138 .buffer_snapshot
7139 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7140 }
7141
7142 if transpose_offset == 0 {
7143 return;
7144 }
7145
7146 *head.column_mut() += 1;
7147 head = display_map.clip_point(head, Bias::Right);
7148 let goal = SelectionGoal::HorizontalPosition(
7149 display_map
7150 .x_for_display_point(head, text_layout_details)
7151 .into(),
7152 );
7153 selection.collapse_to(head, goal);
7154
7155 let transpose_start = display_map
7156 .buffer_snapshot
7157 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7158 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7159 let transpose_end = display_map
7160 .buffer_snapshot
7161 .clip_offset(transpose_offset + 1, Bias::Right);
7162 if let Some(ch) =
7163 display_map.buffer_snapshot.chars_at(transpose_start).next()
7164 {
7165 edits.push((transpose_start..transpose_offset, String::new()));
7166 edits.push((transpose_end..transpose_end, ch.to_string()));
7167 }
7168 }
7169 });
7170 edits
7171 });
7172 this.buffer
7173 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7174 let selections = this.selections.all::<usize>(cx);
7175 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7176 s.select(selections);
7177 });
7178 });
7179 }
7180
7181 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7182 self.rewrap_impl(IsVimMode::No, cx)
7183 }
7184
7185 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7186 let buffer = self.buffer.read(cx).snapshot(cx);
7187 let selections = self.selections.all::<Point>(cx);
7188 let mut selections = selections.iter().peekable();
7189
7190 let mut edits = Vec::new();
7191 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7192
7193 while let Some(selection) = selections.next() {
7194 let mut start_row = selection.start.row;
7195 let mut end_row = selection.end.row;
7196
7197 // Skip selections that overlap with a range that has already been rewrapped.
7198 let selection_range = start_row..end_row;
7199 if rewrapped_row_ranges
7200 .iter()
7201 .any(|range| range.overlaps(&selection_range))
7202 {
7203 continue;
7204 }
7205
7206 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7207
7208 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7209 match language_scope.language_name().0.as_ref() {
7210 "Markdown" | "Plain Text" => {
7211 should_rewrap = true;
7212 }
7213 _ => {}
7214 }
7215 }
7216
7217 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7218
7219 // Since not all lines in the selection may be at the same indent
7220 // level, choose the indent size that is the most common between all
7221 // of the lines.
7222 //
7223 // If there is a tie, we use the deepest indent.
7224 let (indent_size, indent_end) = {
7225 let mut indent_size_occurrences = HashMap::default();
7226 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7227
7228 for row in start_row..=end_row {
7229 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7230 rows_by_indent_size.entry(indent).or_default().push(row);
7231 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7232 }
7233
7234 let indent_size = indent_size_occurrences
7235 .into_iter()
7236 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7237 .map(|(indent, _)| indent)
7238 .unwrap_or_default();
7239 let row = rows_by_indent_size[&indent_size][0];
7240 let indent_end = Point::new(row, indent_size.len);
7241
7242 (indent_size, indent_end)
7243 };
7244
7245 let mut line_prefix = indent_size.chars().collect::<String>();
7246
7247 if let Some(comment_prefix) =
7248 buffer
7249 .language_scope_at(selection.head())
7250 .and_then(|language| {
7251 language
7252 .line_comment_prefixes()
7253 .iter()
7254 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7255 .cloned()
7256 })
7257 {
7258 line_prefix.push_str(&comment_prefix);
7259 should_rewrap = true;
7260 }
7261
7262 if !should_rewrap {
7263 continue;
7264 }
7265
7266 if selection.is_empty() {
7267 'expand_upwards: while start_row > 0 {
7268 let prev_row = start_row - 1;
7269 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7270 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7271 {
7272 start_row = prev_row;
7273 } else {
7274 break 'expand_upwards;
7275 }
7276 }
7277
7278 'expand_downwards: while end_row < buffer.max_point().row {
7279 let next_row = end_row + 1;
7280 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7281 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7282 {
7283 end_row = next_row;
7284 } else {
7285 break 'expand_downwards;
7286 }
7287 }
7288 }
7289
7290 let start = Point::new(start_row, 0);
7291 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7292 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7293 let Some(lines_without_prefixes) = selection_text
7294 .lines()
7295 .map(|line| {
7296 line.strip_prefix(&line_prefix)
7297 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7298 .ok_or_else(|| {
7299 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7300 })
7301 })
7302 .collect::<Result<Vec<_>, _>>()
7303 .log_err()
7304 else {
7305 continue;
7306 };
7307
7308 let wrap_column = buffer
7309 .settings_at(Point::new(start_row, 0), cx)
7310 .preferred_line_length as usize;
7311 let wrapped_text = wrap_with_prefix(
7312 line_prefix,
7313 lines_without_prefixes.join(" "),
7314 wrap_column,
7315 tab_size,
7316 );
7317
7318 // TODO: should always use char-based diff while still supporting cursor behavior that
7319 // matches vim.
7320 let diff = match is_vim_mode {
7321 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7322 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7323 };
7324 let mut offset = start.to_offset(&buffer);
7325 let mut moved_since_edit = true;
7326
7327 for change in diff.iter_all_changes() {
7328 let value = change.value();
7329 match change.tag() {
7330 ChangeTag::Equal => {
7331 offset += value.len();
7332 moved_since_edit = true;
7333 }
7334 ChangeTag::Delete => {
7335 let start = buffer.anchor_after(offset);
7336 let end = buffer.anchor_before(offset + value.len());
7337
7338 if moved_since_edit {
7339 edits.push((start..end, String::new()));
7340 } else {
7341 edits.last_mut().unwrap().0.end = end;
7342 }
7343
7344 offset += value.len();
7345 moved_since_edit = false;
7346 }
7347 ChangeTag::Insert => {
7348 if moved_since_edit {
7349 let anchor = buffer.anchor_after(offset);
7350 edits.push((anchor..anchor, value.to_string()));
7351 } else {
7352 edits.last_mut().unwrap().1.push_str(value);
7353 }
7354
7355 moved_since_edit = false;
7356 }
7357 }
7358 }
7359
7360 rewrapped_row_ranges.push(start_row..=end_row);
7361 }
7362
7363 self.buffer
7364 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7365 }
7366
7367 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7368 let mut text = String::new();
7369 let buffer = self.buffer.read(cx).snapshot(cx);
7370 let mut selections = self.selections.all::<Point>(cx);
7371 let mut clipboard_selections = Vec::with_capacity(selections.len());
7372 {
7373 let max_point = buffer.max_point();
7374 let mut is_first = true;
7375 for selection in &mut selections {
7376 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7377 if is_entire_line {
7378 selection.start = Point::new(selection.start.row, 0);
7379 if !selection.is_empty() && selection.end.column == 0 {
7380 selection.end = cmp::min(max_point, selection.end);
7381 } else {
7382 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7383 }
7384 selection.goal = SelectionGoal::None;
7385 }
7386 if is_first {
7387 is_first = false;
7388 } else {
7389 text += "\n";
7390 }
7391 let mut len = 0;
7392 for chunk in buffer.text_for_range(selection.start..selection.end) {
7393 text.push_str(chunk);
7394 len += chunk.len();
7395 }
7396 clipboard_selections.push(ClipboardSelection {
7397 len,
7398 is_entire_line,
7399 first_line_indent: buffer
7400 .indent_size_for_line(MultiBufferRow(selection.start.row))
7401 .len,
7402 });
7403 }
7404 }
7405
7406 self.transact(cx, |this, cx| {
7407 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7408 s.select(selections);
7409 });
7410 this.insert("", cx);
7411 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7412 text,
7413 clipboard_selections,
7414 ));
7415 });
7416 }
7417
7418 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7419 let selections = self.selections.all::<Point>(cx);
7420 let buffer = self.buffer.read(cx).read(cx);
7421 let mut text = String::new();
7422
7423 let mut clipboard_selections = Vec::with_capacity(selections.len());
7424 {
7425 let max_point = buffer.max_point();
7426 let mut is_first = true;
7427 for selection in selections.iter() {
7428 let mut start = selection.start;
7429 let mut end = selection.end;
7430 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7431 if is_entire_line {
7432 start = Point::new(start.row, 0);
7433 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7434 }
7435 if is_first {
7436 is_first = false;
7437 } else {
7438 text += "\n";
7439 }
7440 let mut len = 0;
7441 for chunk in buffer.text_for_range(start..end) {
7442 text.push_str(chunk);
7443 len += chunk.len();
7444 }
7445 clipboard_selections.push(ClipboardSelection {
7446 len,
7447 is_entire_line,
7448 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7449 });
7450 }
7451 }
7452
7453 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7454 text,
7455 clipboard_selections,
7456 ));
7457 }
7458
7459 pub fn do_paste(
7460 &mut self,
7461 text: &String,
7462 clipboard_selections: Option<Vec<ClipboardSelection>>,
7463 handle_entire_lines: bool,
7464 cx: &mut ViewContext<Self>,
7465 ) {
7466 if self.read_only(cx) {
7467 return;
7468 }
7469
7470 let clipboard_text = Cow::Borrowed(text);
7471
7472 self.transact(cx, |this, cx| {
7473 if let Some(mut clipboard_selections) = clipboard_selections {
7474 let old_selections = this.selections.all::<usize>(cx);
7475 let all_selections_were_entire_line =
7476 clipboard_selections.iter().all(|s| s.is_entire_line);
7477 let first_selection_indent_column =
7478 clipboard_selections.first().map(|s| s.first_line_indent);
7479 if clipboard_selections.len() != old_selections.len() {
7480 clipboard_selections.drain(..);
7481 }
7482 let cursor_offset = this.selections.last::<usize>(cx).head();
7483 let mut auto_indent_on_paste = true;
7484
7485 this.buffer.update(cx, |buffer, cx| {
7486 let snapshot = buffer.read(cx);
7487 auto_indent_on_paste =
7488 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7489
7490 let mut start_offset = 0;
7491 let mut edits = Vec::new();
7492 let mut original_indent_columns = Vec::new();
7493 for (ix, selection) in old_selections.iter().enumerate() {
7494 let to_insert;
7495 let entire_line;
7496 let original_indent_column;
7497 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7498 let end_offset = start_offset + clipboard_selection.len;
7499 to_insert = &clipboard_text[start_offset..end_offset];
7500 entire_line = clipboard_selection.is_entire_line;
7501 start_offset = end_offset + 1;
7502 original_indent_column = Some(clipboard_selection.first_line_indent);
7503 } else {
7504 to_insert = clipboard_text.as_str();
7505 entire_line = all_selections_were_entire_line;
7506 original_indent_column = first_selection_indent_column
7507 }
7508
7509 // If the corresponding selection was empty when this slice of the
7510 // clipboard text was written, then the entire line containing the
7511 // selection was copied. If this selection is also currently empty,
7512 // then paste the line before the current line of the buffer.
7513 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7514 let column = selection.start.to_point(&snapshot).column as usize;
7515 let line_start = selection.start - column;
7516 line_start..line_start
7517 } else {
7518 selection.range()
7519 };
7520
7521 edits.push((range, to_insert));
7522 original_indent_columns.extend(original_indent_column);
7523 }
7524 drop(snapshot);
7525
7526 buffer.edit(
7527 edits,
7528 if auto_indent_on_paste {
7529 Some(AutoindentMode::Block {
7530 original_indent_columns,
7531 })
7532 } else {
7533 None
7534 },
7535 cx,
7536 );
7537 });
7538
7539 let selections = this.selections.all::<usize>(cx);
7540 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7541 } else {
7542 this.insert(&clipboard_text, cx);
7543 }
7544 });
7545 }
7546
7547 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7548 if let Some(item) = cx.read_from_clipboard() {
7549 let entries = item.entries();
7550
7551 match entries.first() {
7552 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7553 // of all the pasted entries.
7554 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7555 .do_paste(
7556 clipboard_string.text(),
7557 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7558 true,
7559 cx,
7560 ),
7561 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7562 }
7563 }
7564 }
7565
7566 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7567 if self.read_only(cx) {
7568 return;
7569 }
7570
7571 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7572 if let Some((selections, _)) =
7573 self.selection_history.transaction(transaction_id).cloned()
7574 {
7575 self.change_selections(None, cx, |s| {
7576 s.select_anchors(selections.to_vec());
7577 });
7578 }
7579 self.request_autoscroll(Autoscroll::fit(), cx);
7580 self.unmark_text(cx);
7581 self.refresh_inline_completion(true, false, cx);
7582 cx.emit(EditorEvent::Edited { transaction_id });
7583 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7584 }
7585 }
7586
7587 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7588 if self.read_only(cx) {
7589 return;
7590 }
7591
7592 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7593 if let Some((_, Some(selections))) =
7594 self.selection_history.transaction(transaction_id).cloned()
7595 {
7596 self.change_selections(None, cx, |s| {
7597 s.select_anchors(selections.to_vec());
7598 });
7599 }
7600 self.request_autoscroll(Autoscroll::fit(), cx);
7601 self.unmark_text(cx);
7602 self.refresh_inline_completion(true, false, cx);
7603 cx.emit(EditorEvent::Edited { transaction_id });
7604 }
7605 }
7606
7607 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7608 self.buffer
7609 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7610 }
7611
7612 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7613 self.buffer
7614 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7615 }
7616
7617 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7619 let line_mode = s.line_mode;
7620 s.move_with(|map, selection| {
7621 let cursor = if selection.is_empty() && !line_mode {
7622 movement::left(map, selection.start)
7623 } else {
7624 selection.start
7625 };
7626 selection.collapse_to(cursor, SelectionGoal::None);
7627 });
7628 })
7629 }
7630
7631 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7632 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7633 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7634 })
7635 }
7636
7637 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7638 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7639 let line_mode = s.line_mode;
7640 s.move_with(|map, selection| {
7641 let cursor = if selection.is_empty() && !line_mode {
7642 movement::right(map, selection.end)
7643 } else {
7644 selection.end
7645 };
7646 selection.collapse_to(cursor, SelectionGoal::None)
7647 });
7648 })
7649 }
7650
7651 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7652 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7653 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7654 })
7655 }
7656
7657 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7658 if self.take_rename(true, cx).is_some() {
7659 return;
7660 }
7661
7662 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7663 cx.propagate();
7664 return;
7665 }
7666
7667 let text_layout_details = &self.text_layout_details(cx);
7668 let selection_count = self.selections.count();
7669 let first_selection = self.selections.first_anchor();
7670
7671 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 let line_mode = s.line_mode;
7673 s.move_with(|map, selection| {
7674 if !selection.is_empty() && !line_mode {
7675 selection.goal = SelectionGoal::None;
7676 }
7677 let (cursor, goal) = movement::up(
7678 map,
7679 selection.start,
7680 selection.goal,
7681 false,
7682 text_layout_details,
7683 );
7684 selection.collapse_to(cursor, goal);
7685 });
7686 });
7687
7688 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7689 {
7690 cx.propagate();
7691 }
7692 }
7693
7694 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7695 if self.take_rename(true, cx).is_some() {
7696 return;
7697 }
7698
7699 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7700 cx.propagate();
7701 return;
7702 }
7703
7704 let text_layout_details = &self.text_layout_details(cx);
7705
7706 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7707 let line_mode = s.line_mode;
7708 s.move_with(|map, selection| {
7709 if !selection.is_empty() && !line_mode {
7710 selection.goal = SelectionGoal::None;
7711 }
7712 let (cursor, goal) = movement::up_by_rows(
7713 map,
7714 selection.start,
7715 action.lines,
7716 selection.goal,
7717 false,
7718 text_layout_details,
7719 );
7720 selection.collapse_to(cursor, goal);
7721 });
7722 })
7723 }
7724
7725 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7726 if self.take_rename(true, cx).is_some() {
7727 return;
7728 }
7729
7730 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7731 cx.propagate();
7732 return;
7733 }
7734
7735 let text_layout_details = &self.text_layout_details(cx);
7736
7737 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7738 let line_mode = s.line_mode;
7739 s.move_with(|map, selection| {
7740 if !selection.is_empty() && !line_mode {
7741 selection.goal = SelectionGoal::None;
7742 }
7743 let (cursor, goal) = movement::down_by_rows(
7744 map,
7745 selection.start,
7746 action.lines,
7747 selection.goal,
7748 false,
7749 text_layout_details,
7750 );
7751 selection.collapse_to(cursor, goal);
7752 });
7753 })
7754 }
7755
7756 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7757 let text_layout_details = &self.text_layout_details(cx);
7758 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7759 s.move_heads_with(|map, head, goal| {
7760 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7761 })
7762 })
7763 }
7764
7765 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7766 let text_layout_details = &self.text_layout_details(cx);
7767 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7768 s.move_heads_with(|map, head, goal| {
7769 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7770 })
7771 })
7772 }
7773
7774 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7775 let Some(row_count) = self.visible_row_count() else {
7776 return;
7777 };
7778
7779 let text_layout_details = &self.text_layout_details(cx);
7780
7781 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7782 s.move_heads_with(|map, head, goal| {
7783 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7784 })
7785 })
7786 }
7787
7788 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7789 if self.take_rename(true, cx).is_some() {
7790 return;
7791 }
7792
7793 if self
7794 .context_menu
7795 .write()
7796 .as_mut()
7797 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7798 .unwrap_or(false)
7799 {
7800 return;
7801 }
7802
7803 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7804 cx.propagate();
7805 return;
7806 }
7807
7808 let Some(row_count) = self.visible_row_count() else {
7809 return;
7810 };
7811
7812 let autoscroll = if action.center_cursor {
7813 Autoscroll::center()
7814 } else {
7815 Autoscroll::fit()
7816 };
7817
7818 let text_layout_details = &self.text_layout_details(cx);
7819
7820 self.change_selections(Some(autoscroll), cx, |s| {
7821 let line_mode = s.line_mode;
7822 s.move_with(|map, selection| {
7823 if !selection.is_empty() && !line_mode {
7824 selection.goal = SelectionGoal::None;
7825 }
7826 let (cursor, goal) = movement::up_by_rows(
7827 map,
7828 selection.end,
7829 row_count,
7830 selection.goal,
7831 false,
7832 text_layout_details,
7833 );
7834 selection.collapse_to(cursor, goal);
7835 });
7836 });
7837 }
7838
7839 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7840 let text_layout_details = &self.text_layout_details(cx);
7841 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7842 s.move_heads_with(|map, head, goal| {
7843 movement::up(map, head, goal, false, text_layout_details)
7844 })
7845 })
7846 }
7847
7848 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7849 self.take_rename(true, cx);
7850
7851 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7852 cx.propagate();
7853 return;
7854 }
7855
7856 let text_layout_details = &self.text_layout_details(cx);
7857 let selection_count = self.selections.count();
7858 let first_selection = self.selections.first_anchor();
7859
7860 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7861 let line_mode = s.line_mode;
7862 s.move_with(|map, selection| {
7863 if !selection.is_empty() && !line_mode {
7864 selection.goal = SelectionGoal::None;
7865 }
7866 let (cursor, goal) = movement::down(
7867 map,
7868 selection.end,
7869 selection.goal,
7870 false,
7871 text_layout_details,
7872 );
7873 selection.collapse_to(cursor, goal);
7874 });
7875 });
7876
7877 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7878 {
7879 cx.propagate();
7880 }
7881 }
7882
7883 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7884 let Some(row_count) = self.visible_row_count() else {
7885 return;
7886 };
7887
7888 let text_layout_details = &self.text_layout_details(cx);
7889
7890 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7891 s.move_heads_with(|map, head, goal| {
7892 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7893 })
7894 })
7895 }
7896
7897 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7898 if self.take_rename(true, cx).is_some() {
7899 return;
7900 }
7901
7902 if self
7903 .context_menu
7904 .write()
7905 .as_mut()
7906 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7907 .unwrap_or(false)
7908 {
7909 return;
7910 }
7911
7912 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7913 cx.propagate();
7914 return;
7915 }
7916
7917 let Some(row_count) = self.visible_row_count() else {
7918 return;
7919 };
7920
7921 let autoscroll = if action.center_cursor {
7922 Autoscroll::center()
7923 } else {
7924 Autoscroll::fit()
7925 };
7926
7927 let text_layout_details = &self.text_layout_details(cx);
7928 self.change_selections(Some(autoscroll), cx, |s| {
7929 let line_mode = s.line_mode;
7930 s.move_with(|map, selection| {
7931 if !selection.is_empty() && !line_mode {
7932 selection.goal = SelectionGoal::None;
7933 }
7934 let (cursor, goal) = movement::down_by_rows(
7935 map,
7936 selection.end,
7937 row_count,
7938 selection.goal,
7939 false,
7940 text_layout_details,
7941 );
7942 selection.collapse_to(cursor, goal);
7943 });
7944 });
7945 }
7946
7947 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7948 let text_layout_details = &self.text_layout_details(cx);
7949 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7950 s.move_heads_with(|map, head, goal| {
7951 movement::down(map, head, goal, false, text_layout_details)
7952 })
7953 });
7954 }
7955
7956 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7957 if let Some(context_menu) = self.context_menu.write().as_mut() {
7958 context_menu.select_first(self.completion_provider.as_deref(), cx);
7959 }
7960 }
7961
7962 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7963 if let Some(context_menu) = self.context_menu.write().as_mut() {
7964 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7965 }
7966 }
7967
7968 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7969 if let Some(context_menu) = self.context_menu.write().as_mut() {
7970 context_menu.select_next(self.completion_provider.as_deref(), cx);
7971 }
7972 }
7973
7974 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7975 if let Some(context_menu) = self.context_menu.write().as_mut() {
7976 context_menu.select_last(self.completion_provider.as_deref(), cx);
7977 }
7978 }
7979
7980 pub fn move_to_previous_word_start(
7981 &mut self,
7982 _: &MoveToPreviousWordStart,
7983 cx: &mut ViewContext<Self>,
7984 ) {
7985 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7986 s.move_cursors_with(|map, head, _| {
7987 (
7988 movement::previous_word_start(map, head),
7989 SelectionGoal::None,
7990 )
7991 });
7992 })
7993 }
7994
7995 pub fn move_to_previous_subword_start(
7996 &mut self,
7997 _: &MoveToPreviousSubwordStart,
7998 cx: &mut ViewContext<Self>,
7999 ) {
8000 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8001 s.move_cursors_with(|map, head, _| {
8002 (
8003 movement::previous_subword_start(map, head),
8004 SelectionGoal::None,
8005 )
8006 });
8007 })
8008 }
8009
8010 pub fn select_to_previous_word_start(
8011 &mut self,
8012 _: &SelectToPreviousWordStart,
8013 cx: &mut ViewContext<Self>,
8014 ) {
8015 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8016 s.move_heads_with(|map, head, _| {
8017 (
8018 movement::previous_word_start(map, head),
8019 SelectionGoal::None,
8020 )
8021 });
8022 })
8023 }
8024
8025 pub fn select_to_previous_subword_start(
8026 &mut self,
8027 _: &SelectToPreviousSubwordStart,
8028 cx: &mut ViewContext<Self>,
8029 ) {
8030 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8031 s.move_heads_with(|map, head, _| {
8032 (
8033 movement::previous_subword_start(map, head),
8034 SelectionGoal::None,
8035 )
8036 });
8037 })
8038 }
8039
8040 pub fn delete_to_previous_word_start(
8041 &mut self,
8042 action: &DeleteToPreviousWordStart,
8043 cx: &mut ViewContext<Self>,
8044 ) {
8045 self.transact(cx, |this, cx| {
8046 this.select_autoclose_pair(cx);
8047 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8048 let line_mode = s.line_mode;
8049 s.move_with(|map, selection| {
8050 if selection.is_empty() && !line_mode {
8051 let cursor = if action.ignore_newlines {
8052 movement::previous_word_start(map, selection.head())
8053 } else {
8054 movement::previous_word_start_or_newline(map, selection.head())
8055 };
8056 selection.set_head(cursor, SelectionGoal::None);
8057 }
8058 });
8059 });
8060 this.insert("", cx);
8061 });
8062 }
8063
8064 pub fn delete_to_previous_subword_start(
8065 &mut self,
8066 _: &DeleteToPreviousSubwordStart,
8067 cx: &mut ViewContext<Self>,
8068 ) {
8069 self.transact(cx, |this, cx| {
8070 this.select_autoclose_pair(cx);
8071 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8072 let line_mode = s.line_mode;
8073 s.move_with(|map, selection| {
8074 if selection.is_empty() && !line_mode {
8075 let cursor = movement::previous_subword_start(map, selection.head());
8076 selection.set_head(cursor, SelectionGoal::None);
8077 }
8078 });
8079 });
8080 this.insert("", cx);
8081 });
8082 }
8083
8084 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8085 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8086 s.move_cursors_with(|map, head, _| {
8087 (movement::next_word_end(map, head), SelectionGoal::None)
8088 });
8089 })
8090 }
8091
8092 pub fn move_to_next_subword_end(
8093 &mut self,
8094 _: &MoveToNextSubwordEnd,
8095 cx: &mut ViewContext<Self>,
8096 ) {
8097 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8098 s.move_cursors_with(|map, head, _| {
8099 (movement::next_subword_end(map, head), SelectionGoal::None)
8100 });
8101 })
8102 }
8103
8104 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8105 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8106 s.move_heads_with(|map, head, _| {
8107 (movement::next_word_end(map, head), SelectionGoal::None)
8108 });
8109 })
8110 }
8111
8112 pub fn select_to_next_subword_end(
8113 &mut self,
8114 _: &SelectToNextSubwordEnd,
8115 cx: &mut ViewContext<Self>,
8116 ) {
8117 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8118 s.move_heads_with(|map, head, _| {
8119 (movement::next_subword_end(map, head), SelectionGoal::None)
8120 });
8121 })
8122 }
8123
8124 pub fn delete_to_next_word_end(
8125 &mut self,
8126 action: &DeleteToNextWordEnd,
8127 cx: &mut ViewContext<Self>,
8128 ) {
8129 self.transact(cx, |this, cx| {
8130 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8131 let line_mode = s.line_mode;
8132 s.move_with(|map, selection| {
8133 if selection.is_empty() && !line_mode {
8134 let cursor = if action.ignore_newlines {
8135 movement::next_word_end(map, selection.head())
8136 } else {
8137 movement::next_word_end_or_newline(map, selection.head())
8138 };
8139 selection.set_head(cursor, SelectionGoal::None);
8140 }
8141 });
8142 });
8143 this.insert("", cx);
8144 });
8145 }
8146
8147 pub fn delete_to_next_subword_end(
8148 &mut self,
8149 _: &DeleteToNextSubwordEnd,
8150 cx: &mut ViewContext<Self>,
8151 ) {
8152 self.transact(cx, |this, cx| {
8153 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8154 s.move_with(|map, selection| {
8155 if selection.is_empty() {
8156 let cursor = movement::next_subword_end(map, selection.head());
8157 selection.set_head(cursor, SelectionGoal::None);
8158 }
8159 });
8160 });
8161 this.insert("", cx);
8162 });
8163 }
8164
8165 pub fn move_to_beginning_of_line(
8166 &mut self,
8167 action: &MoveToBeginningOfLine,
8168 cx: &mut ViewContext<Self>,
8169 ) {
8170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8171 s.move_cursors_with(|map, head, _| {
8172 (
8173 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8174 SelectionGoal::None,
8175 )
8176 });
8177 })
8178 }
8179
8180 pub fn select_to_beginning_of_line(
8181 &mut self,
8182 action: &SelectToBeginningOfLine,
8183 cx: &mut ViewContext<Self>,
8184 ) {
8185 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8186 s.move_heads_with(|map, head, _| {
8187 (
8188 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8189 SelectionGoal::None,
8190 )
8191 });
8192 });
8193 }
8194
8195 pub fn delete_to_beginning_of_line(
8196 &mut self,
8197 _: &DeleteToBeginningOfLine,
8198 cx: &mut ViewContext<Self>,
8199 ) {
8200 self.transact(cx, |this, cx| {
8201 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8202 s.move_with(|_, selection| {
8203 selection.reversed = true;
8204 });
8205 });
8206
8207 this.select_to_beginning_of_line(
8208 &SelectToBeginningOfLine {
8209 stop_at_soft_wraps: false,
8210 },
8211 cx,
8212 );
8213 this.backspace(&Backspace, cx);
8214 });
8215 }
8216
8217 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8219 s.move_cursors_with(|map, head, _| {
8220 (
8221 movement::line_end(map, head, action.stop_at_soft_wraps),
8222 SelectionGoal::None,
8223 )
8224 });
8225 })
8226 }
8227
8228 pub fn select_to_end_of_line(
8229 &mut self,
8230 action: &SelectToEndOfLine,
8231 cx: &mut ViewContext<Self>,
8232 ) {
8233 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8234 s.move_heads_with(|map, head, _| {
8235 (
8236 movement::line_end(map, head, action.stop_at_soft_wraps),
8237 SelectionGoal::None,
8238 )
8239 });
8240 })
8241 }
8242
8243 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8244 self.transact(cx, |this, cx| {
8245 this.select_to_end_of_line(
8246 &SelectToEndOfLine {
8247 stop_at_soft_wraps: false,
8248 },
8249 cx,
8250 );
8251 this.delete(&Delete, cx);
8252 });
8253 }
8254
8255 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8256 self.transact(cx, |this, cx| {
8257 this.select_to_end_of_line(
8258 &SelectToEndOfLine {
8259 stop_at_soft_wraps: false,
8260 },
8261 cx,
8262 );
8263 this.cut(&Cut, cx);
8264 });
8265 }
8266
8267 pub fn move_to_start_of_paragraph(
8268 &mut self,
8269 _: &MoveToStartOfParagraph,
8270 cx: &mut ViewContext<Self>,
8271 ) {
8272 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8273 cx.propagate();
8274 return;
8275 }
8276
8277 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8278 s.move_with(|map, selection| {
8279 selection.collapse_to(
8280 movement::start_of_paragraph(map, selection.head(), 1),
8281 SelectionGoal::None,
8282 )
8283 });
8284 })
8285 }
8286
8287 pub fn move_to_end_of_paragraph(
8288 &mut self,
8289 _: &MoveToEndOfParagraph,
8290 cx: &mut ViewContext<Self>,
8291 ) {
8292 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8293 cx.propagate();
8294 return;
8295 }
8296
8297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8298 s.move_with(|map, selection| {
8299 selection.collapse_to(
8300 movement::end_of_paragraph(map, selection.head(), 1),
8301 SelectionGoal::None,
8302 )
8303 });
8304 })
8305 }
8306
8307 pub fn select_to_start_of_paragraph(
8308 &mut self,
8309 _: &SelectToStartOfParagraph,
8310 cx: &mut ViewContext<Self>,
8311 ) {
8312 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8313 cx.propagate();
8314 return;
8315 }
8316
8317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8318 s.move_heads_with(|map, head, _| {
8319 (
8320 movement::start_of_paragraph(map, head, 1),
8321 SelectionGoal::None,
8322 )
8323 });
8324 })
8325 }
8326
8327 pub fn select_to_end_of_paragraph(
8328 &mut self,
8329 _: &SelectToEndOfParagraph,
8330 cx: &mut ViewContext<Self>,
8331 ) {
8332 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8333 cx.propagate();
8334 return;
8335 }
8336
8337 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8338 s.move_heads_with(|map, head, _| {
8339 (
8340 movement::end_of_paragraph(map, head, 1),
8341 SelectionGoal::None,
8342 )
8343 });
8344 })
8345 }
8346
8347 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8348 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8349 cx.propagate();
8350 return;
8351 }
8352
8353 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8354 s.select_ranges(vec![0..0]);
8355 });
8356 }
8357
8358 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8359 let mut selection = self.selections.last::<Point>(cx);
8360 selection.set_head(Point::zero(), SelectionGoal::None);
8361
8362 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8363 s.select(vec![selection]);
8364 });
8365 }
8366
8367 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8368 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8369 cx.propagate();
8370 return;
8371 }
8372
8373 let cursor = self.buffer.read(cx).read(cx).len();
8374 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8375 s.select_ranges(vec![cursor..cursor])
8376 });
8377 }
8378
8379 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8380 self.nav_history = nav_history;
8381 }
8382
8383 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8384 self.nav_history.as_ref()
8385 }
8386
8387 fn push_to_nav_history(
8388 &mut self,
8389 cursor_anchor: Anchor,
8390 new_position: Option<Point>,
8391 cx: &mut ViewContext<Self>,
8392 ) {
8393 if let Some(nav_history) = self.nav_history.as_mut() {
8394 let buffer = self.buffer.read(cx).read(cx);
8395 let cursor_position = cursor_anchor.to_point(&buffer);
8396 let scroll_state = self.scroll_manager.anchor();
8397 let scroll_top_row = scroll_state.top_row(&buffer);
8398 drop(buffer);
8399
8400 if let Some(new_position) = new_position {
8401 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8402 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8403 return;
8404 }
8405 }
8406
8407 nav_history.push(
8408 Some(NavigationData {
8409 cursor_anchor,
8410 cursor_position,
8411 scroll_anchor: scroll_state,
8412 scroll_top_row,
8413 }),
8414 cx,
8415 );
8416 }
8417 }
8418
8419 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8420 let buffer = self.buffer.read(cx).snapshot(cx);
8421 let mut selection = self.selections.first::<usize>(cx);
8422 selection.set_head(buffer.len(), SelectionGoal::None);
8423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8424 s.select(vec![selection]);
8425 });
8426 }
8427
8428 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8429 let end = self.buffer.read(cx).read(cx).len();
8430 self.change_selections(None, cx, |s| {
8431 s.select_ranges(vec![0..end]);
8432 });
8433 }
8434
8435 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8436 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8437 let mut selections = self.selections.all::<Point>(cx);
8438 let max_point = display_map.buffer_snapshot.max_point();
8439 for selection in &mut selections {
8440 let rows = selection.spanned_rows(true, &display_map);
8441 selection.start = Point::new(rows.start.0, 0);
8442 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8443 selection.reversed = false;
8444 }
8445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8446 s.select(selections);
8447 });
8448 }
8449
8450 pub fn split_selection_into_lines(
8451 &mut self,
8452 _: &SplitSelectionIntoLines,
8453 cx: &mut ViewContext<Self>,
8454 ) {
8455 let mut to_unfold = Vec::new();
8456 let mut new_selection_ranges = Vec::new();
8457 {
8458 let selections = self.selections.all::<Point>(cx);
8459 let buffer = self.buffer.read(cx).read(cx);
8460 for selection in selections {
8461 for row in selection.start.row..selection.end.row {
8462 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8463 new_selection_ranges.push(cursor..cursor);
8464 }
8465 new_selection_ranges.push(selection.end..selection.end);
8466 to_unfold.push(selection.start..selection.end);
8467 }
8468 }
8469 self.unfold_ranges(&to_unfold, true, true, cx);
8470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8471 s.select_ranges(new_selection_ranges);
8472 });
8473 }
8474
8475 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8476 self.add_selection(true, cx);
8477 }
8478
8479 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8480 self.add_selection(false, cx);
8481 }
8482
8483 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8484 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8485 let mut selections = self.selections.all::<Point>(cx);
8486 let text_layout_details = self.text_layout_details(cx);
8487 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8488 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8489 let range = oldest_selection.display_range(&display_map).sorted();
8490
8491 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8492 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8493 let positions = start_x.min(end_x)..start_x.max(end_x);
8494
8495 selections.clear();
8496 let mut stack = Vec::new();
8497 for row in range.start.row().0..=range.end.row().0 {
8498 if let Some(selection) = self.selections.build_columnar_selection(
8499 &display_map,
8500 DisplayRow(row),
8501 &positions,
8502 oldest_selection.reversed,
8503 &text_layout_details,
8504 ) {
8505 stack.push(selection.id);
8506 selections.push(selection);
8507 }
8508 }
8509
8510 if above {
8511 stack.reverse();
8512 }
8513
8514 AddSelectionsState { above, stack }
8515 });
8516
8517 let last_added_selection = *state.stack.last().unwrap();
8518 let mut new_selections = Vec::new();
8519 if above == state.above {
8520 let end_row = if above {
8521 DisplayRow(0)
8522 } else {
8523 display_map.max_point().row()
8524 };
8525
8526 'outer: for selection in selections {
8527 if selection.id == last_added_selection {
8528 let range = selection.display_range(&display_map).sorted();
8529 debug_assert_eq!(range.start.row(), range.end.row());
8530 let mut row = range.start.row();
8531 let positions =
8532 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8533 px(start)..px(end)
8534 } else {
8535 let start_x =
8536 display_map.x_for_display_point(range.start, &text_layout_details);
8537 let end_x =
8538 display_map.x_for_display_point(range.end, &text_layout_details);
8539 start_x.min(end_x)..start_x.max(end_x)
8540 };
8541
8542 while row != end_row {
8543 if above {
8544 row.0 -= 1;
8545 } else {
8546 row.0 += 1;
8547 }
8548
8549 if let Some(new_selection) = self.selections.build_columnar_selection(
8550 &display_map,
8551 row,
8552 &positions,
8553 selection.reversed,
8554 &text_layout_details,
8555 ) {
8556 state.stack.push(new_selection.id);
8557 if above {
8558 new_selections.push(new_selection);
8559 new_selections.push(selection);
8560 } else {
8561 new_selections.push(selection);
8562 new_selections.push(new_selection);
8563 }
8564
8565 continue 'outer;
8566 }
8567 }
8568 }
8569
8570 new_selections.push(selection);
8571 }
8572 } else {
8573 new_selections = selections;
8574 new_selections.retain(|s| s.id != last_added_selection);
8575 state.stack.pop();
8576 }
8577
8578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8579 s.select(new_selections);
8580 });
8581 if state.stack.len() > 1 {
8582 self.add_selections_state = Some(state);
8583 }
8584 }
8585
8586 pub fn select_next_match_internal(
8587 &mut self,
8588 display_map: &DisplaySnapshot,
8589 replace_newest: bool,
8590 autoscroll: Option<Autoscroll>,
8591 cx: &mut ViewContext<Self>,
8592 ) -> Result<()> {
8593 fn select_next_match_ranges(
8594 this: &mut Editor,
8595 range: Range<usize>,
8596 replace_newest: bool,
8597 auto_scroll: Option<Autoscroll>,
8598 cx: &mut ViewContext<Editor>,
8599 ) {
8600 this.unfold_ranges(&[range.clone()], false, true, cx);
8601 this.change_selections(auto_scroll, cx, |s| {
8602 if replace_newest {
8603 s.delete(s.newest_anchor().id);
8604 }
8605 s.insert_range(range.clone());
8606 });
8607 }
8608
8609 let buffer = &display_map.buffer_snapshot;
8610 let mut selections = self.selections.all::<usize>(cx);
8611 if let Some(mut select_next_state) = self.select_next_state.take() {
8612 let query = &select_next_state.query;
8613 if !select_next_state.done {
8614 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8615 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8616 let mut next_selected_range = None;
8617
8618 let bytes_after_last_selection =
8619 buffer.bytes_in_range(last_selection.end..buffer.len());
8620 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8621 let query_matches = query
8622 .stream_find_iter(bytes_after_last_selection)
8623 .map(|result| (last_selection.end, result))
8624 .chain(
8625 query
8626 .stream_find_iter(bytes_before_first_selection)
8627 .map(|result| (0, result)),
8628 );
8629
8630 for (start_offset, query_match) in query_matches {
8631 let query_match = query_match.unwrap(); // can only fail due to I/O
8632 let offset_range =
8633 start_offset + query_match.start()..start_offset + query_match.end();
8634 let display_range = offset_range.start.to_display_point(display_map)
8635 ..offset_range.end.to_display_point(display_map);
8636
8637 if !select_next_state.wordwise
8638 || (!movement::is_inside_word(display_map, display_range.start)
8639 && !movement::is_inside_word(display_map, display_range.end))
8640 {
8641 // TODO: This is n^2, because we might check all the selections
8642 if !selections
8643 .iter()
8644 .any(|selection| selection.range().overlaps(&offset_range))
8645 {
8646 next_selected_range = Some(offset_range);
8647 break;
8648 }
8649 }
8650 }
8651
8652 if let Some(next_selected_range) = next_selected_range {
8653 select_next_match_ranges(
8654 self,
8655 next_selected_range,
8656 replace_newest,
8657 autoscroll,
8658 cx,
8659 );
8660 } else {
8661 select_next_state.done = true;
8662 }
8663 }
8664
8665 self.select_next_state = Some(select_next_state);
8666 } else {
8667 let mut only_carets = true;
8668 let mut same_text_selected = true;
8669 let mut selected_text = None;
8670
8671 let mut selections_iter = selections.iter().peekable();
8672 while let Some(selection) = selections_iter.next() {
8673 if selection.start != selection.end {
8674 only_carets = false;
8675 }
8676
8677 if same_text_selected {
8678 if selected_text.is_none() {
8679 selected_text =
8680 Some(buffer.text_for_range(selection.range()).collect::<String>());
8681 }
8682
8683 if let Some(next_selection) = selections_iter.peek() {
8684 if next_selection.range().len() == selection.range().len() {
8685 let next_selected_text = buffer
8686 .text_for_range(next_selection.range())
8687 .collect::<String>();
8688 if Some(next_selected_text) != selected_text {
8689 same_text_selected = false;
8690 selected_text = None;
8691 }
8692 } else {
8693 same_text_selected = false;
8694 selected_text = None;
8695 }
8696 }
8697 }
8698 }
8699
8700 if only_carets {
8701 for selection in &mut selections {
8702 let word_range = movement::surrounding_word(
8703 display_map,
8704 selection.start.to_display_point(display_map),
8705 );
8706 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8707 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8708 selection.goal = SelectionGoal::None;
8709 selection.reversed = false;
8710 select_next_match_ranges(
8711 self,
8712 selection.start..selection.end,
8713 replace_newest,
8714 autoscroll,
8715 cx,
8716 );
8717 }
8718
8719 if selections.len() == 1 {
8720 let selection = selections
8721 .last()
8722 .expect("ensured that there's only one selection");
8723 let query = buffer
8724 .text_for_range(selection.start..selection.end)
8725 .collect::<String>();
8726 let is_empty = query.is_empty();
8727 let select_state = SelectNextState {
8728 query: AhoCorasick::new(&[query])?,
8729 wordwise: true,
8730 done: is_empty,
8731 };
8732 self.select_next_state = Some(select_state);
8733 } else {
8734 self.select_next_state = None;
8735 }
8736 } else if let Some(selected_text) = selected_text {
8737 self.select_next_state = Some(SelectNextState {
8738 query: AhoCorasick::new(&[selected_text])?,
8739 wordwise: false,
8740 done: false,
8741 });
8742 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8743 }
8744 }
8745 Ok(())
8746 }
8747
8748 pub fn select_all_matches(
8749 &mut self,
8750 _action: &SelectAllMatches,
8751 cx: &mut ViewContext<Self>,
8752 ) -> Result<()> {
8753 self.push_to_selection_history();
8754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8755
8756 self.select_next_match_internal(&display_map, false, None, cx)?;
8757 let Some(select_next_state) = self.select_next_state.as_mut() else {
8758 return Ok(());
8759 };
8760 if select_next_state.done {
8761 return Ok(());
8762 }
8763
8764 let mut new_selections = self.selections.all::<usize>(cx);
8765
8766 let buffer = &display_map.buffer_snapshot;
8767 let query_matches = select_next_state
8768 .query
8769 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8770
8771 for query_match in query_matches {
8772 let query_match = query_match.unwrap(); // can only fail due to I/O
8773 let offset_range = query_match.start()..query_match.end();
8774 let display_range = offset_range.start.to_display_point(&display_map)
8775 ..offset_range.end.to_display_point(&display_map);
8776
8777 if !select_next_state.wordwise
8778 || (!movement::is_inside_word(&display_map, display_range.start)
8779 && !movement::is_inside_word(&display_map, display_range.end))
8780 {
8781 self.selections.change_with(cx, |selections| {
8782 new_selections.push(Selection {
8783 id: selections.new_selection_id(),
8784 start: offset_range.start,
8785 end: offset_range.end,
8786 reversed: false,
8787 goal: SelectionGoal::None,
8788 });
8789 });
8790 }
8791 }
8792
8793 new_selections.sort_by_key(|selection| selection.start);
8794 let mut ix = 0;
8795 while ix + 1 < new_selections.len() {
8796 let current_selection = &new_selections[ix];
8797 let next_selection = &new_selections[ix + 1];
8798 if current_selection.range().overlaps(&next_selection.range()) {
8799 if current_selection.id < next_selection.id {
8800 new_selections.remove(ix + 1);
8801 } else {
8802 new_selections.remove(ix);
8803 }
8804 } else {
8805 ix += 1;
8806 }
8807 }
8808
8809 select_next_state.done = true;
8810 self.unfold_ranges(
8811 &new_selections
8812 .iter()
8813 .map(|selection| selection.range())
8814 .collect::<Vec<_>>(),
8815 false,
8816 false,
8817 cx,
8818 );
8819 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8820 selections.select(new_selections)
8821 });
8822
8823 Ok(())
8824 }
8825
8826 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8827 self.push_to_selection_history();
8828 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8829 self.select_next_match_internal(
8830 &display_map,
8831 action.replace_newest,
8832 Some(Autoscroll::newest()),
8833 cx,
8834 )?;
8835 Ok(())
8836 }
8837
8838 pub fn select_previous(
8839 &mut self,
8840 action: &SelectPrevious,
8841 cx: &mut ViewContext<Self>,
8842 ) -> Result<()> {
8843 self.push_to_selection_history();
8844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8845 let buffer = &display_map.buffer_snapshot;
8846 let mut selections = self.selections.all::<usize>(cx);
8847 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8848 let query = &select_prev_state.query;
8849 if !select_prev_state.done {
8850 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8851 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8852 let mut next_selected_range = None;
8853 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8854 let bytes_before_last_selection =
8855 buffer.reversed_bytes_in_range(0..last_selection.start);
8856 let bytes_after_first_selection =
8857 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8858 let query_matches = query
8859 .stream_find_iter(bytes_before_last_selection)
8860 .map(|result| (last_selection.start, result))
8861 .chain(
8862 query
8863 .stream_find_iter(bytes_after_first_selection)
8864 .map(|result| (buffer.len(), result)),
8865 );
8866 for (end_offset, query_match) in query_matches {
8867 let query_match = query_match.unwrap(); // can only fail due to I/O
8868 let offset_range =
8869 end_offset - query_match.end()..end_offset - query_match.start();
8870 let display_range = offset_range.start.to_display_point(&display_map)
8871 ..offset_range.end.to_display_point(&display_map);
8872
8873 if !select_prev_state.wordwise
8874 || (!movement::is_inside_word(&display_map, display_range.start)
8875 && !movement::is_inside_word(&display_map, display_range.end))
8876 {
8877 next_selected_range = Some(offset_range);
8878 break;
8879 }
8880 }
8881
8882 if let Some(next_selected_range) = next_selected_range {
8883 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8884 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8885 if action.replace_newest {
8886 s.delete(s.newest_anchor().id);
8887 }
8888 s.insert_range(next_selected_range);
8889 });
8890 } else {
8891 select_prev_state.done = true;
8892 }
8893 }
8894
8895 self.select_prev_state = Some(select_prev_state);
8896 } else {
8897 let mut only_carets = true;
8898 let mut same_text_selected = true;
8899 let mut selected_text = None;
8900
8901 let mut selections_iter = selections.iter().peekable();
8902 while let Some(selection) = selections_iter.next() {
8903 if selection.start != selection.end {
8904 only_carets = false;
8905 }
8906
8907 if same_text_selected {
8908 if selected_text.is_none() {
8909 selected_text =
8910 Some(buffer.text_for_range(selection.range()).collect::<String>());
8911 }
8912
8913 if let Some(next_selection) = selections_iter.peek() {
8914 if next_selection.range().len() == selection.range().len() {
8915 let next_selected_text = buffer
8916 .text_for_range(next_selection.range())
8917 .collect::<String>();
8918 if Some(next_selected_text) != selected_text {
8919 same_text_selected = false;
8920 selected_text = None;
8921 }
8922 } else {
8923 same_text_selected = false;
8924 selected_text = None;
8925 }
8926 }
8927 }
8928 }
8929
8930 if only_carets {
8931 for selection in &mut selections {
8932 let word_range = movement::surrounding_word(
8933 &display_map,
8934 selection.start.to_display_point(&display_map),
8935 );
8936 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8937 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8938 selection.goal = SelectionGoal::None;
8939 selection.reversed = false;
8940 }
8941 if selections.len() == 1 {
8942 let selection = selections
8943 .last()
8944 .expect("ensured that there's only one selection");
8945 let query = buffer
8946 .text_for_range(selection.start..selection.end)
8947 .collect::<String>();
8948 let is_empty = query.is_empty();
8949 let select_state = SelectNextState {
8950 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8951 wordwise: true,
8952 done: is_empty,
8953 };
8954 self.select_prev_state = Some(select_state);
8955 } else {
8956 self.select_prev_state = None;
8957 }
8958
8959 self.unfold_ranges(
8960 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8961 false,
8962 true,
8963 cx,
8964 );
8965 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8966 s.select(selections);
8967 });
8968 } else if let Some(selected_text) = selected_text {
8969 self.select_prev_state = Some(SelectNextState {
8970 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8971 wordwise: false,
8972 done: false,
8973 });
8974 self.select_previous(action, cx)?;
8975 }
8976 }
8977 Ok(())
8978 }
8979
8980 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8981 if self.read_only(cx) {
8982 return;
8983 }
8984 let text_layout_details = &self.text_layout_details(cx);
8985 self.transact(cx, |this, cx| {
8986 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8987 let mut edits = Vec::new();
8988 let mut selection_edit_ranges = Vec::new();
8989 let mut last_toggled_row = None;
8990 let snapshot = this.buffer.read(cx).read(cx);
8991 let empty_str: Arc<str> = Arc::default();
8992 let mut suffixes_inserted = Vec::new();
8993 let ignore_indent = action.ignore_indent;
8994
8995 fn comment_prefix_range(
8996 snapshot: &MultiBufferSnapshot,
8997 row: MultiBufferRow,
8998 comment_prefix: &str,
8999 comment_prefix_whitespace: &str,
9000 ignore_indent: bool,
9001 ) -> Range<Point> {
9002 let indent_size = if ignore_indent {
9003 0
9004 } else {
9005 snapshot.indent_size_for_line(row).len
9006 };
9007
9008 let start = Point::new(row.0, indent_size);
9009
9010 let mut line_bytes = snapshot
9011 .bytes_in_range(start..snapshot.max_point())
9012 .flatten()
9013 .copied();
9014
9015 // If this line currently begins with the line comment prefix, then record
9016 // the range containing the prefix.
9017 if line_bytes
9018 .by_ref()
9019 .take(comment_prefix.len())
9020 .eq(comment_prefix.bytes())
9021 {
9022 // Include any whitespace that matches the comment prefix.
9023 let matching_whitespace_len = line_bytes
9024 .zip(comment_prefix_whitespace.bytes())
9025 .take_while(|(a, b)| a == b)
9026 .count() as u32;
9027 let end = Point::new(
9028 start.row,
9029 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9030 );
9031 start..end
9032 } else {
9033 start..start
9034 }
9035 }
9036
9037 fn comment_suffix_range(
9038 snapshot: &MultiBufferSnapshot,
9039 row: MultiBufferRow,
9040 comment_suffix: &str,
9041 comment_suffix_has_leading_space: bool,
9042 ) -> Range<Point> {
9043 let end = Point::new(row.0, snapshot.line_len(row));
9044 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9045
9046 let mut line_end_bytes = snapshot
9047 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9048 .flatten()
9049 .copied();
9050
9051 let leading_space_len = if suffix_start_column > 0
9052 && line_end_bytes.next() == Some(b' ')
9053 && comment_suffix_has_leading_space
9054 {
9055 1
9056 } else {
9057 0
9058 };
9059
9060 // If this line currently begins with the line comment prefix, then record
9061 // the range containing the prefix.
9062 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9063 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9064 start..end
9065 } else {
9066 end..end
9067 }
9068 }
9069
9070 // TODO: Handle selections that cross excerpts
9071 for selection in &mut selections {
9072 let start_column = snapshot
9073 .indent_size_for_line(MultiBufferRow(selection.start.row))
9074 .len;
9075 let language = if let Some(language) =
9076 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9077 {
9078 language
9079 } else {
9080 continue;
9081 };
9082
9083 selection_edit_ranges.clear();
9084
9085 // If multiple selections contain a given row, avoid processing that
9086 // row more than once.
9087 let mut start_row = MultiBufferRow(selection.start.row);
9088 if last_toggled_row == Some(start_row) {
9089 start_row = start_row.next_row();
9090 }
9091 let end_row =
9092 if selection.end.row > selection.start.row && selection.end.column == 0 {
9093 MultiBufferRow(selection.end.row - 1)
9094 } else {
9095 MultiBufferRow(selection.end.row)
9096 };
9097 last_toggled_row = Some(end_row);
9098
9099 if start_row > end_row {
9100 continue;
9101 }
9102
9103 // If the language has line comments, toggle those.
9104 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9105
9106 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9107 if ignore_indent {
9108 full_comment_prefixes = full_comment_prefixes
9109 .into_iter()
9110 .map(|s| Arc::from(s.trim_end()))
9111 .collect();
9112 }
9113
9114 if !full_comment_prefixes.is_empty() {
9115 let first_prefix = full_comment_prefixes
9116 .first()
9117 .expect("prefixes is non-empty");
9118 let prefix_trimmed_lengths = full_comment_prefixes
9119 .iter()
9120 .map(|p| p.trim_end_matches(' ').len())
9121 .collect::<SmallVec<[usize; 4]>>();
9122
9123 let mut all_selection_lines_are_comments = true;
9124
9125 for row in start_row.0..=end_row.0 {
9126 let row = MultiBufferRow(row);
9127 if start_row < end_row && snapshot.is_line_blank(row) {
9128 continue;
9129 }
9130
9131 let prefix_range = full_comment_prefixes
9132 .iter()
9133 .zip(prefix_trimmed_lengths.iter().copied())
9134 .map(|(prefix, trimmed_prefix_len)| {
9135 comment_prefix_range(
9136 snapshot.deref(),
9137 row,
9138 &prefix[..trimmed_prefix_len],
9139 &prefix[trimmed_prefix_len..],
9140 ignore_indent,
9141 )
9142 })
9143 .max_by_key(|range| range.end.column - range.start.column)
9144 .expect("prefixes is non-empty");
9145
9146 if prefix_range.is_empty() {
9147 all_selection_lines_are_comments = false;
9148 }
9149
9150 selection_edit_ranges.push(prefix_range);
9151 }
9152
9153 if all_selection_lines_are_comments {
9154 edits.extend(
9155 selection_edit_ranges
9156 .iter()
9157 .cloned()
9158 .map(|range| (range, empty_str.clone())),
9159 );
9160 } else {
9161 let min_column = selection_edit_ranges
9162 .iter()
9163 .map(|range| range.start.column)
9164 .min()
9165 .unwrap_or(0);
9166 edits.extend(selection_edit_ranges.iter().map(|range| {
9167 let position = Point::new(range.start.row, min_column);
9168 (position..position, first_prefix.clone())
9169 }));
9170 }
9171 } else if let Some((full_comment_prefix, comment_suffix)) =
9172 language.block_comment_delimiters()
9173 {
9174 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9175 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9176 let prefix_range = comment_prefix_range(
9177 snapshot.deref(),
9178 start_row,
9179 comment_prefix,
9180 comment_prefix_whitespace,
9181 ignore_indent,
9182 );
9183 let suffix_range = comment_suffix_range(
9184 snapshot.deref(),
9185 end_row,
9186 comment_suffix.trim_start_matches(' '),
9187 comment_suffix.starts_with(' '),
9188 );
9189
9190 if prefix_range.is_empty() || suffix_range.is_empty() {
9191 edits.push((
9192 prefix_range.start..prefix_range.start,
9193 full_comment_prefix.clone(),
9194 ));
9195 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9196 suffixes_inserted.push((end_row, comment_suffix.len()));
9197 } else {
9198 edits.push((prefix_range, empty_str.clone()));
9199 edits.push((suffix_range, empty_str.clone()));
9200 }
9201 } else {
9202 continue;
9203 }
9204 }
9205
9206 drop(snapshot);
9207 this.buffer.update(cx, |buffer, cx| {
9208 buffer.edit(edits, None, cx);
9209 });
9210
9211 // Adjust selections so that they end before any comment suffixes that
9212 // were inserted.
9213 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9214 let mut selections = this.selections.all::<Point>(cx);
9215 let snapshot = this.buffer.read(cx).read(cx);
9216 for selection in &mut selections {
9217 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9218 match row.cmp(&MultiBufferRow(selection.end.row)) {
9219 Ordering::Less => {
9220 suffixes_inserted.next();
9221 continue;
9222 }
9223 Ordering::Greater => break,
9224 Ordering::Equal => {
9225 if selection.end.column == snapshot.line_len(row) {
9226 if selection.is_empty() {
9227 selection.start.column -= suffix_len as u32;
9228 }
9229 selection.end.column -= suffix_len as u32;
9230 }
9231 break;
9232 }
9233 }
9234 }
9235 }
9236
9237 drop(snapshot);
9238 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9239
9240 let selections = this.selections.all::<Point>(cx);
9241 let selections_on_single_row = selections.windows(2).all(|selections| {
9242 selections[0].start.row == selections[1].start.row
9243 && selections[0].end.row == selections[1].end.row
9244 && selections[0].start.row == selections[0].end.row
9245 });
9246 let selections_selecting = selections
9247 .iter()
9248 .any(|selection| selection.start != selection.end);
9249 let advance_downwards = action.advance_downwards
9250 && selections_on_single_row
9251 && !selections_selecting
9252 && !matches!(this.mode, EditorMode::SingleLine { .. });
9253
9254 if advance_downwards {
9255 let snapshot = this.buffer.read(cx).snapshot(cx);
9256
9257 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9258 s.move_cursors_with(|display_snapshot, display_point, _| {
9259 let mut point = display_point.to_point(display_snapshot);
9260 point.row += 1;
9261 point = snapshot.clip_point(point, Bias::Left);
9262 let display_point = point.to_display_point(display_snapshot);
9263 let goal = SelectionGoal::HorizontalPosition(
9264 display_snapshot
9265 .x_for_display_point(display_point, text_layout_details)
9266 .into(),
9267 );
9268 (display_point, goal)
9269 })
9270 });
9271 }
9272 });
9273 }
9274
9275 pub fn select_enclosing_symbol(
9276 &mut self,
9277 _: &SelectEnclosingSymbol,
9278 cx: &mut ViewContext<Self>,
9279 ) {
9280 let buffer = self.buffer.read(cx).snapshot(cx);
9281 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9282
9283 fn update_selection(
9284 selection: &Selection<usize>,
9285 buffer_snap: &MultiBufferSnapshot,
9286 ) -> Option<Selection<usize>> {
9287 let cursor = selection.head();
9288 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9289 for symbol in symbols.iter().rev() {
9290 let start = symbol.range.start.to_offset(buffer_snap);
9291 let end = symbol.range.end.to_offset(buffer_snap);
9292 let new_range = start..end;
9293 if start < selection.start || end > selection.end {
9294 return Some(Selection {
9295 id: selection.id,
9296 start: new_range.start,
9297 end: new_range.end,
9298 goal: SelectionGoal::None,
9299 reversed: selection.reversed,
9300 });
9301 }
9302 }
9303 None
9304 }
9305
9306 let mut selected_larger_symbol = false;
9307 let new_selections = old_selections
9308 .iter()
9309 .map(|selection| match update_selection(selection, &buffer) {
9310 Some(new_selection) => {
9311 if new_selection.range() != selection.range() {
9312 selected_larger_symbol = true;
9313 }
9314 new_selection
9315 }
9316 None => selection.clone(),
9317 })
9318 .collect::<Vec<_>>();
9319
9320 if selected_larger_symbol {
9321 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9322 s.select(new_selections);
9323 });
9324 }
9325 }
9326
9327 pub fn select_larger_syntax_node(
9328 &mut self,
9329 _: &SelectLargerSyntaxNode,
9330 cx: &mut ViewContext<Self>,
9331 ) {
9332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9333 let buffer = self.buffer.read(cx).snapshot(cx);
9334 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9335
9336 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9337 let mut selected_larger_node = false;
9338 let new_selections = old_selections
9339 .iter()
9340 .map(|selection| {
9341 let old_range = selection.start..selection.end;
9342 let mut new_range = old_range.clone();
9343 while let Some(containing_range) =
9344 buffer.range_for_syntax_ancestor(new_range.clone())
9345 {
9346 new_range = containing_range;
9347 if !display_map.intersects_fold(new_range.start)
9348 && !display_map.intersects_fold(new_range.end)
9349 {
9350 break;
9351 }
9352 }
9353
9354 selected_larger_node |= new_range != old_range;
9355 Selection {
9356 id: selection.id,
9357 start: new_range.start,
9358 end: new_range.end,
9359 goal: SelectionGoal::None,
9360 reversed: selection.reversed,
9361 }
9362 })
9363 .collect::<Vec<_>>();
9364
9365 if selected_larger_node {
9366 stack.push(old_selections);
9367 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9368 s.select(new_selections);
9369 });
9370 }
9371 self.select_larger_syntax_node_stack = stack;
9372 }
9373
9374 pub fn select_smaller_syntax_node(
9375 &mut self,
9376 _: &SelectSmallerSyntaxNode,
9377 cx: &mut ViewContext<Self>,
9378 ) {
9379 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9380 if let Some(selections) = stack.pop() {
9381 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9382 s.select(selections.to_vec());
9383 });
9384 }
9385 self.select_larger_syntax_node_stack = stack;
9386 }
9387
9388 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9389 if !EditorSettings::get_global(cx).gutter.runnables {
9390 self.clear_tasks();
9391 return Task::ready(());
9392 }
9393 let project = self.project.as_ref().map(Model::downgrade);
9394 cx.spawn(|this, mut cx| async move {
9395 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9396 let Some(project) = project.and_then(|p| p.upgrade()) else {
9397 return;
9398 };
9399 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9400 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9401 }) else {
9402 return;
9403 };
9404
9405 let hide_runnables = project
9406 .update(&mut cx, |project, cx| {
9407 // Do not display any test indicators in non-dev server remote projects.
9408 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9409 })
9410 .unwrap_or(true);
9411 if hide_runnables {
9412 return;
9413 }
9414 let new_rows =
9415 cx.background_executor()
9416 .spawn({
9417 let snapshot = display_snapshot.clone();
9418 async move {
9419 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9420 }
9421 })
9422 .await;
9423 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9424
9425 this.update(&mut cx, |this, _| {
9426 this.clear_tasks();
9427 for (key, value) in rows {
9428 this.insert_tasks(key, value);
9429 }
9430 })
9431 .ok();
9432 })
9433 }
9434 fn fetch_runnable_ranges(
9435 snapshot: &DisplaySnapshot,
9436 range: Range<Anchor>,
9437 ) -> Vec<language::RunnableRange> {
9438 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9439 }
9440
9441 fn runnable_rows(
9442 project: Model<Project>,
9443 snapshot: DisplaySnapshot,
9444 runnable_ranges: Vec<RunnableRange>,
9445 mut cx: AsyncWindowContext,
9446 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9447 runnable_ranges
9448 .into_iter()
9449 .filter_map(|mut runnable| {
9450 let tasks = cx
9451 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9452 .ok()?;
9453 if tasks.is_empty() {
9454 return None;
9455 }
9456
9457 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9458
9459 let row = snapshot
9460 .buffer_snapshot
9461 .buffer_line_for_row(MultiBufferRow(point.row))?
9462 .1
9463 .start
9464 .row;
9465
9466 let context_range =
9467 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9468 Some((
9469 (runnable.buffer_id, row),
9470 RunnableTasks {
9471 templates: tasks,
9472 offset: MultiBufferOffset(runnable.run_range.start),
9473 context_range,
9474 column: point.column,
9475 extra_variables: runnable.extra_captures,
9476 },
9477 ))
9478 })
9479 .collect()
9480 }
9481
9482 fn templates_with_tags(
9483 project: &Model<Project>,
9484 runnable: &mut Runnable,
9485 cx: &WindowContext<'_>,
9486 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9487 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9488 let (worktree_id, file) = project
9489 .buffer_for_id(runnable.buffer, cx)
9490 .and_then(|buffer| buffer.read(cx).file())
9491 .map(|file| (file.worktree_id(cx), file.clone()))
9492 .unzip();
9493
9494 (
9495 project.task_store().read(cx).task_inventory().cloned(),
9496 worktree_id,
9497 file,
9498 )
9499 });
9500
9501 let tags = mem::take(&mut runnable.tags);
9502 let mut tags: Vec<_> = tags
9503 .into_iter()
9504 .flat_map(|tag| {
9505 let tag = tag.0.clone();
9506 inventory
9507 .as_ref()
9508 .into_iter()
9509 .flat_map(|inventory| {
9510 inventory.read(cx).list_tasks(
9511 file.clone(),
9512 Some(runnable.language.clone()),
9513 worktree_id,
9514 cx,
9515 )
9516 })
9517 .filter(move |(_, template)| {
9518 template.tags.iter().any(|source_tag| source_tag == &tag)
9519 })
9520 })
9521 .sorted_by_key(|(kind, _)| kind.to_owned())
9522 .collect();
9523 if let Some((leading_tag_source, _)) = tags.first() {
9524 // Strongest source wins; if we have worktree tag binding, prefer that to
9525 // global and language bindings;
9526 // if we have a global binding, prefer that to language binding.
9527 let first_mismatch = tags
9528 .iter()
9529 .position(|(tag_source, _)| tag_source != leading_tag_source);
9530 if let Some(index) = first_mismatch {
9531 tags.truncate(index);
9532 }
9533 }
9534
9535 tags
9536 }
9537
9538 pub fn move_to_enclosing_bracket(
9539 &mut self,
9540 _: &MoveToEnclosingBracket,
9541 cx: &mut ViewContext<Self>,
9542 ) {
9543 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9544 s.move_offsets_with(|snapshot, selection| {
9545 let Some(enclosing_bracket_ranges) =
9546 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9547 else {
9548 return;
9549 };
9550
9551 let mut best_length = usize::MAX;
9552 let mut best_inside = false;
9553 let mut best_in_bracket_range = false;
9554 let mut best_destination = None;
9555 for (open, close) in enclosing_bracket_ranges {
9556 let close = close.to_inclusive();
9557 let length = close.end() - open.start;
9558 let inside = selection.start >= open.end && selection.end <= *close.start();
9559 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9560 || close.contains(&selection.head());
9561
9562 // If best is next to a bracket and current isn't, skip
9563 if !in_bracket_range && best_in_bracket_range {
9564 continue;
9565 }
9566
9567 // Prefer smaller lengths unless best is inside and current isn't
9568 if length > best_length && (best_inside || !inside) {
9569 continue;
9570 }
9571
9572 best_length = length;
9573 best_inside = inside;
9574 best_in_bracket_range = in_bracket_range;
9575 best_destination = Some(
9576 if close.contains(&selection.start) && close.contains(&selection.end) {
9577 if inside {
9578 open.end
9579 } else {
9580 open.start
9581 }
9582 } else if inside {
9583 *close.start()
9584 } else {
9585 *close.end()
9586 },
9587 );
9588 }
9589
9590 if let Some(destination) = best_destination {
9591 selection.collapse_to(destination, SelectionGoal::None);
9592 }
9593 })
9594 });
9595 }
9596
9597 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9598 self.end_selection(cx);
9599 self.selection_history.mode = SelectionHistoryMode::Undoing;
9600 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9601 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9602 self.select_next_state = entry.select_next_state;
9603 self.select_prev_state = entry.select_prev_state;
9604 self.add_selections_state = entry.add_selections_state;
9605 self.request_autoscroll(Autoscroll::newest(), cx);
9606 }
9607 self.selection_history.mode = SelectionHistoryMode::Normal;
9608 }
9609
9610 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9611 self.end_selection(cx);
9612 self.selection_history.mode = SelectionHistoryMode::Redoing;
9613 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9614 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9615 self.select_next_state = entry.select_next_state;
9616 self.select_prev_state = entry.select_prev_state;
9617 self.add_selections_state = entry.add_selections_state;
9618 self.request_autoscroll(Autoscroll::newest(), cx);
9619 }
9620 self.selection_history.mode = SelectionHistoryMode::Normal;
9621 }
9622
9623 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9624 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9625 }
9626
9627 pub fn expand_excerpts_down(
9628 &mut self,
9629 action: &ExpandExcerptsDown,
9630 cx: &mut ViewContext<Self>,
9631 ) {
9632 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9633 }
9634
9635 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9636 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9637 }
9638
9639 pub fn expand_excerpts_for_direction(
9640 &mut self,
9641 lines: u32,
9642 direction: ExpandExcerptDirection,
9643 cx: &mut ViewContext<Self>,
9644 ) {
9645 let selections = self.selections.disjoint_anchors();
9646
9647 let lines = if lines == 0 {
9648 EditorSettings::get_global(cx).expand_excerpt_lines
9649 } else {
9650 lines
9651 };
9652
9653 self.buffer.update(cx, |buffer, cx| {
9654 buffer.expand_excerpts(
9655 selections
9656 .iter()
9657 .map(|selection| selection.head().excerpt_id)
9658 .dedup(),
9659 lines,
9660 direction,
9661 cx,
9662 )
9663 })
9664 }
9665
9666 pub fn expand_excerpt(
9667 &mut self,
9668 excerpt: ExcerptId,
9669 direction: ExpandExcerptDirection,
9670 cx: &mut ViewContext<Self>,
9671 ) {
9672 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9673 self.buffer.update(cx, |buffer, cx| {
9674 buffer.expand_excerpts([excerpt], lines, direction, cx)
9675 })
9676 }
9677
9678 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9679 self.go_to_diagnostic_impl(Direction::Next, cx)
9680 }
9681
9682 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9683 self.go_to_diagnostic_impl(Direction::Prev, cx)
9684 }
9685
9686 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9687 let buffer = self.buffer.read(cx).snapshot(cx);
9688 let selection = self.selections.newest::<usize>(cx);
9689
9690 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9691 if direction == Direction::Next {
9692 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9693 let (group_id, jump_to) = popover.activation_info();
9694 if self.activate_diagnostics(group_id, cx) {
9695 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9696 let mut new_selection = s.newest_anchor().clone();
9697 new_selection.collapse_to(jump_to, SelectionGoal::None);
9698 s.select_anchors(vec![new_selection.clone()]);
9699 });
9700 }
9701 return;
9702 }
9703 }
9704
9705 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9706 active_diagnostics
9707 .primary_range
9708 .to_offset(&buffer)
9709 .to_inclusive()
9710 });
9711 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9712 if active_primary_range.contains(&selection.head()) {
9713 *active_primary_range.start()
9714 } else {
9715 selection.head()
9716 }
9717 } else {
9718 selection.head()
9719 };
9720 let snapshot = self.snapshot(cx);
9721 loop {
9722 let diagnostics = if direction == Direction::Prev {
9723 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9724 } else {
9725 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9726 }
9727 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9728 let group = diagnostics
9729 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9730 // be sorted in a stable way
9731 // skip until we are at current active diagnostic, if it exists
9732 .skip_while(|entry| {
9733 (match direction {
9734 Direction::Prev => entry.range.start >= search_start,
9735 Direction::Next => entry.range.start <= search_start,
9736 }) && self
9737 .active_diagnostics
9738 .as_ref()
9739 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9740 })
9741 .find_map(|entry| {
9742 if entry.diagnostic.is_primary
9743 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9744 && !entry.range.is_empty()
9745 // if we match with the active diagnostic, skip it
9746 && Some(entry.diagnostic.group_id)
9747 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9748 {
9749 Some((entry.range, entry.diagnostic.group_id))
9750 } else {
9751 None
9752 }
9753 });
9754
9755 if let Some((primary_range, group_id)) = group {
9756 if self.activate_diagnostics(group_id, cx) {
9757 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9758 s.select(vec![Selection {
9759 id: selection.id,
9760 start: primary_range.start,
9761 end: primary_range.start,
9762 reversed: false,
9763 goal: SelectionGoal::None,
9764 }]);
9765 });
9766 }
9767 break;
9768 } else {
9769 // Cycle around to the start of the buffer, potentially moving back to the start of
9770 // the currently active diagnostic.
9771 active_primary_range.take();
9772 if direction == Direction::Prev {
9773 if search_start == buffer.len() {
9774 break;
9775 } else {
9776 search_start = buffer.len();
9777 }
9778 } else if search_start == 0 {
9779 break;
9780 } else {
9781 search_start = 0;
9782 }
9783 }
9784 }
9785 }
9786
9787 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9788 let snapshot = self
9789 .display_map
9790 .update(cx, |display_map, cx| display_map.snapshot(cx));
9791 let selection = self.selections.newest::<Point>(cx);
9792 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9793 }
9794
9795 fn go_to_hunk_after_position(
9796 &mut self,
9797 snapshot: &DisplaySnapshot,
9798 position: Point,
9799 cx: &mut ViewContext<'_, Editor>,
9800 ) -> Option<MultiBufferDiffHunk> {
9801 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9802 snapshot,
9803 position,
9804 false,
9805 snapshot
9806 .buffer_snapshot
9807 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9808 cx,
9809 ) {
9810 return Some(hunk);
9811 }
9812
9813 let wrapped_point = Point::zero();
9814 self.go_to_next_hunk_in_direction(
9815 snapshot,
9816 wrapped_point,
9817 true,
9818 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9819 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9820 ),
9821 cx,
9822 )
9823 }
9824
9825 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9826 let snapshot = self
9827 .display_map
9828 .update(cx, |display_map, cx| display_map.snapshot(cx));
9829 let selection = self.selections.newest::<Point>(cx);
9830
9831 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9832 }
9833
9834 fn go_to_hunk_before_position(
9835 &mut self,
9836 snapshot: &DisplaySnapshot,
9837 position: Point,
9838 cx: &mut ViewContext<'_, Editor>,
9839 ) -> Option<MultiBufferDiffHunk> {
9840 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9841 snapshot,
9842 position,
9843 false,
9844 snapshot
9845 .buffer_snapshot
9846 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9847 cx,
9848 ) {
9849 return Some(hunk);
9850 }
9851
9852 let wrapped_point = snapshot.buffer_snapshot.max_point();
9853 self.go_to_next_hunk_in_direction(
9854 snapshot,
9855 wrapped_point,
9856 true,
9857 snapshot
9858 .buffer_snapshot
9859 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9860 cx,
9861 )
9862 }
9863
9864 fn go_to_next_hunk_in_direction(
9865 &mut self,
9866 snapshot: &DisplaySnapshot,
9867 initial_point: Point,
9868 is_wrapped: bool,
9869 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9870 cx: &mut ViewContext<Editor>,
9871 ) -> Option<MultiBufferDiffHunk> {
9872 let display_point = initial_point.to_display_point(snapshot);
9873 let mut hunks = hunks
9874 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9875 .filter(|(display_hunk, _)| {
9876 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9877 })
9878 .dedup();
9879
9880 if let Some((display_hunk, hunk)) = hunks.next() {
9881 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9882 let row = display_hunk.start_display_row();
9883 let point = DisplayPoint::new(row, 0);
9884 s.select_display_ranges([point..point]);
9885 });
9886
9887 Some(hunk)
9888 } else {
9889 None
9890 }
9891 }
9892
9893 pub fn go_to_definition(
9894 &mut self,
9895 _: &GoToDefinition,
9896 cx: &mut ViewContext<Self>,
9897 ) -> Task<Result<Navigated>> {
9898 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9899 cx.spawn(|editor, mut cx| async move {
9900 if definition.await? == Navigated::Yes {
9901 return Ok(Navigated::Yes);
9902 }
9903 match editor.update(&mut cx, |editor, cx| {
9904 editor.find_all_references(&FindAllReferences, cx)
9905 })? {
9906 Some(references) => references.await,
9907 None => Ok(Navigated::No),
9908 }
9909 })
9910 }
9911
9912 pub fn go_to_declaration(
9913 &mut self,
9914 _: &GoToDeclaration,
9915 cx: &mut ViewContext<Self>,
9916 ) -> Task<Result<Navigated>> {
9917 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9918 }
9919
9920 pub fn go_to_declaration_split(
9921 &mut self,
9922 _: &GoToDeclaration,
9923 cx: &mut ViewContext<Self>,
9924 ) -> Task<Result<Navigated>> {
9925 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9926 }
9927
9928 pub fn go_to_implementation(
9929 &mut self,
9930 _: &GoToImplementation,
9931 cx: &mut ViewContext<Self>,
9932 ) -> Task<Result<Navigated>> {
9933 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9934 }
9935
9936 pub fn go_to_implementation_split(
9937 &mut self,
9938 _: &GoToImplementationSplit,
9939 cx: &mut ViewContext<Self>,
9940 ) -> Task<Result<Navigated>> {
9941 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9942 }
9943
9944 pub fn go_to_type_definition(
9945 &mut self,
9946 _: &GoToTypeDefinition,
9947 cx: &mut ViewContext<Self>,
9948 ) -> Task<Result<Navigated>> {
9949 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9950 }
9951
9952 pub fn go_to_definition_split(
9953 &mut self,
9954 _: &GoToDefinitionSplit,
9955 cx: &mut ViewContext<Self>,
9956 ) -> Task<Result<Navigated>> {
9957 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9958 }
9959
9960 pub fn go_to_type_definition_split(
9961 &mut self,
9962 _: &GoToTypeDefinitionSplit,
9963 cx: &mut ViewContext<Self>,
9964 ) -> Task<Result<Navigated>> {
9965 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9966 }
9967
9968 fn go_to_definition_of_kind(
9969 &mut self,
9970 kind: GotoDefinitionKind,
9971 split: bool,
9972 cx: &mut ViewContext<Self>,
9973 ) -> Task<Result<Navigated>> {
9974 let Some(provider) = self.semantics_provider.clone() else {
9975 return Task::ready(Ok(Navigated::No));
9976 };
9977 let head = self.selections.newest::<usize>(cx).head();
9978 let buffer = self.buffer.read(cx);
9979 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9980 text_anchor
9981 } else {
9982 return Task::ready(Ok(Navigated::No));
9983 };
9984
9985 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9986 return Task::ready(Ok(Navigated::No));
9987 };
9988
9989 cx.spawn(|editor, mut cx| async move {
9990 let definitions = definitions.await?;
9991 let navigated = editor
9992 .update(&mut cx, |editor, cx| {
9993 editor.navigate_to_hover_links(
9994 Some(kind),
9995 definitions
9996 .into_iter()
9997 .filter(|location| {
9998 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9999 })
10000 .map(HoverLink::Text)
10001 .collect::<Vec<_>>(),
10002 split,
10003 cx,
10004 )
10005 })?
10006 .await?;
10007 anyhow::Ok(navigated)
10008 })
10009 }
10010
10011 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10012 let position = self.selections.newest_anchor().head();
10013 let Some((buffer, buffer_position)) =
10014 self.buffer.read(cx).text_anchor_for_position(position, cx)
10015 else {
10016 return;
10017 };
10018
10019 cx.spawn(|editor, mut cx| async move {
10020 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10021 editor.update(&mut cx, |_, cx| {
10022 cx.open_url(&url);
10023 })
10024 } else {
10025 Ok(())
10026 }
10027 })
10028 .detach();
10029 }
10030
10031 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10032 let Some(workspace) = self.workspace() else {
10033 return;
10034 };
10035
10036 let position = self.selections.newest_anchor().head();
10037
10038 let Some((buffer, buffer_position)) =
10039 self.buffer.read(cx).text_anchor_for_position(position, cx)
10040 else {
10041 return;
10042 };
10043
10044 let project = self.project.clone();
10045
10046 cx.spawn(|_, mut cx| async move {
10047 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10048
10049 if let Some((_, path)) = result {
10050 workspace
10051 .update(&mut cx, |workspace, cx| {
10052 workspace.open_resolved_path(path, cx)
10053 })?
10054 .await?;
10055 }
10056 anyhow::Ok(())
10057 })
10058 .detach();
10059 }
10060
10061 pub(crate) fn navigate_to_hover_links(
10062 &mut self,
10063 kind: Option<GotoDefinitionKind>,
10064 mut definitions: Vec<HoverLink>,
10065 split: bool,
10066 cx: &mut ViewContext<Editor>,
10067 ) -> Task<Result<Navigated>> {
10068 // If there is one definition, just open it directly
10069 if definitions.len() == 1 {
10070 let definition = definitions.pop().unwrap();
10071
10072 enum TargetTaskResult {
10073 Location(Option<Location>),
10074 AlreadyNavigated,
10075 }
10076
10077 let target_task = match definition {
10078 HoverLink::Text(link) => {
10079 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10080 }
10081 HoverLink::InlayHint(lsp_location, server_id) => {
10082 let computation = self.compute_target_location(lsp_location, server_id, cx);
10083 cx.background_executor().spawn(async move {
10084 let location = computation.await?;
10085 Ok(TargetTaskResult::Location(location))
10086 })
10087 }
10088 HoverLink::Url(url) => {
10089 cx.open_url(&url);
10090 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10091 }
10092 HoverLink::File(path) => {
10093 if let Some(workspace) = self.workspace() {
10094 cx.spawn(|_, mut cx| async move {
10095 workspace
10096 .update(&mut cx, |workspace, cx| {
10097 workspace.open_resolved_path(path, cx)
10098 })?
10099 .await
10100 .map(|_| TargetTaskResult::AlreadyNavigated)
10101 })
10102 } else {
10103 Task::ready(Ok(TargetTaskResult::Location(None)))
10104 }
10105 }
10106 };
10107 cx.spawn(|editor, mut cx| async move {
10108 let target = match target_task.await.context("target resolution task")? {
10109 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10110 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10111 TargetTaskResult::Location(Some(target)) => target,
10112 };
10113
10114 editor.update(&mut cx, |editor, cx| {
10115 let Some(workspace) = editor.workspace() else {
10116 return Navigated::No;
10117 };
10118 let pane = workspace.read(cx).active_pane().clone();
10119
10120 let range = target.range.to_offset(target.buffer.read(cx));
10121 let range = editor.range_for_match(&range);
10122
10123 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10124 let buffer = target.buffer.read(cx);
10125 let range = check_multiline_range(buffer, range);
10126 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10127 s.select_ranges([range]);
10128 });
10129 } else {
10130 cx.window_context().defer(move |cx| {
10131 let target_editor: View<Self> =
10132 workspace.update(cx, |workspace, cx| {
10133 let pane = if split {
10134 workspace.adjacent_pane(cx)
10135 } else {
10136 workspace.active_pane().clone()
10137 };
10138
10139 workspace.open_project_item(
10140 pane,
10141 target.buffer.clone(),
10142 true,
10143 true,
10144 cx,
10145 )
10146 });
10147 target_editor.update(cx, |target_editor, cx| {
10148 // When selecting a definition in a different buffer, disable the nav history
10149 // to avoid creating a history entry at the previous cursor location.
10150 pane.update(cx, |pane, _| pane.disable_history());
10151 let buffer = target.buffer.read(cx);
10152 let range = check_multiline_range(buffer, range);
10153 target_editor.change_selections(
10154 Some(Autoscroll::focused()),
10155 cx,
10156 |s| {
10157 s.select_ranges([range]);
10158 },
10159 );
10160 pane.update(cx, |pane, _| pane.enable_history());
10161 });
10162 });
10163 }
10164 Navigated::Yes
10165 })
10166 })
10167 } else if !definitions.is_empty() {
10168 cx.spawn(|editor, mut cx| async move {
10169 let (title, location_tasks, workspace) = editor
10170 .update(&mut cx, |editor, cx| {
10171 let tab_kind = match kind {
10172 Some(GotoDefinitionKind::Implementation) => "Implementations",
10173 _ => "Definitions",
10174 };
10175 let title = definitions
10176 .iter()
10177 .find_map(|definition| match definition {
10178 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10179 let buffer = origin.buffer.read(cx);
10180 format!(
10181 "{} for {}",
10182 tab_kind,
10183 buffer
10184 .text_for_range(origin.range.clone())
10185 .collect::<String>()
10186 )
10187 }),
10188 HoverLink::InlayHint(_, _) => None,
10189 HoverLink::Url(_) => None,
10190 HoverLink::File(_) => None,
10191 })
10192 .unwrap_or(tab_kind.to_string());
10193 let location_tasks = definitions
10194 .into_iter()
10195 .map(|definition| match definition {
10196 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10197 HoverLink::InlayHint(lsp_location, server_id) => {
10198 editor.compute_target_location(lsp_location, server_id, cx)
10199 }
10200 HoverLink::Url(_) => Task::ready(Ok(None)),
10201 HoverLink::File(_) => Task::ready(Ok(None)),
10202 })
10203 .collect::<Vec<_>>();
10204 (title, location_tasks, editor.workspace().clone())
10205 })
10206 .context("location tasks preparation")?;
10207
10208 let locations = future::join_all(location_tasks)
10209 .await
10210 .into_iter()
10211 .filter_map(|location| location.transpose())
10212 .collect::<Result<_>>()
10213 .context("location tasks")?;
10214
10215 let Some(workspace) = workspace else {
10216 return Ok(Navigated::No);
10217 };
10218 let opened = workspace
10219 .update(&mut cx, |workspace, cx| {
10220 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10221 })
10222 .ok();
10223
10224 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10225 })
10226 } else {
10227 Task::ready(Ok(Navigated::No))
10228 }
10229 }
10230
10231 fn compute_target_location(
10232 &self,
10233 lsp_location: lsp::Location,
10234 server_id: LanguageServerId,
10235 cx: &mut ViewContext<Self>,
10236 ) -> Task<anyhow::Result<Option<Location>>> {
10237 let Some(project) = self.project.clone() else {
10238 return Task::Ready(Some(Ok(None)));
10239 };
10240
10241 cx.spawn(move |editor, mut cx| async move {
10242 let location_task = editor.update(&mut cx, |_, cx| {
10243 project.update(cx, |project, cx| {
10244 let language_server_name = project
10245 .language_server_statuses(cx)
10246 .find(|(id, _)| server_id == *id)
10247 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10248 language_server_name.map(|language_server_name| {
10249 project.open_local_buffer_via_lsp(
10250 lsp_location.uri.clone(),
10251 server_id,
10252 language_server_name,
10253 cx,
10254 )
10255 })
10256 })
10257 })?;
10258 let location = match location_task {
10259 Some(task) => Some({
10260 let target_buffer_handle = task.await.context("open local buffer")?;
10261 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10262 let target_start = target_buffer
10263 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10264 let target_end = target_buffer
10265 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10266 target_buffer.anchor_after(target_start)
10267 ..target_buffer.anchor_before(target_end)
10268 })?;
10269 Location {
10270 buffer: target_buffer_handle,
10271 range,
10272 }
10273 }),
10274 None => None,
10275 };
10276 Ok(location)
10277 })
10278 }
10279
10280 pub fn find_all_references(
10281 &mut self,
10282 _: &FindAllReferences,
10283 cx: &mut ViewContext<Self>,
10284 ) -> Option<Task<Result<Navigated>>> {
10285 let selection = self.selections.newest::<usize>(cx);
10286 let multi_buffer = self.buffer.read(cx);
10287 let head = selection.head();
10288
10289 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10290 let head_anchor = multi_buffer_snapshot.anchor_at(
10291 head,
10292 if head < selection.tail() {
10293 Bias::Right
10294 } else {
10295 Bias::Left
10296 },
10297 );
10298
10299 match self
10300 .find_all_references_task_sources
10301 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10302 {
10303 Ok(_) => {
10304 log::info!(
10305 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10306 );
10307 return None;
10308 }
10309 Err(i) => {
10310 self.find_all_references_task_sources.insert(i, head_anchor);
10311 }
10312 }
10313
10314 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10315 let workspace = self.workspace()?;
10316 let project = workspace.read(cx).project().clone();
10317 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10318 Some(cx.spawn(|editor, mut cx| async move {
10319 let _cleanup = defer({
10320 let mut cx = cx.clone();
10321 move || {
10322 let _ = editor.update(&mut cx, |editor, _| {
10323 if let Ok(i) =
10324 editor
10325 .find_all_references_task_sources
10326 .binary_search_by(|anchor| {
10327 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10328 })
10329 {
10330 editor.find_all_references_task_sources.remove(i);
10331 }
10332 });
10333 }
10334 });
10335
10336 let locations = references.await?;
10337 if locations.is_empty() {
10338 return anyhow::Ok(Navigated::No);
10339 }
10340
10341 workspace.update(&mut cx, |workspace, cx| {
10342 let title = locations
10343 .first()
10344 .as_ref()
10345 .map(|location| {
10346 let buffer = location.buffer.read(cx);
10347 format!(
10348 "References to `{}`",
10349 buffer
10350 .text_for_range(location.range.clone())
10351 .collect::<String>()
10352 )
10353 })
10354 .unwrap();
10355 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10356 Navigated::Yes
10357 })
10358 }))
10359 }
10360
10361 /// Opens a multibuffer with the given project locations in it
10362 pub fn open_locations_in_multibuffer(
10363 workspace: &mut Workspace,
10364 mut locations: Vec<Location>,
10365 title: String,
10366 split: bool,
10367 cx: &mut ViewContext<Workspace>,
10368 ) {
10369 // If there are multiple definitions, open them in a multibuffer
10370 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10371 let mut locations = locations.into_iter().peekable();
10372 let mut ranges_to_highlight = Vec::new();
10373 let capability = workspace.project().read(cx).capability();
10374
10375 let excerpt_buffer = cx.new_model(|cx| {
10376 let mut multibuffer = MultiBuffer::new(capability);
10377 while let Some(location) = locations.next() {
10378 let buffer = location.buffer.read(cx);
10379 let mut ranges_for_buffer = Vec::new();
10380 let range = location.range.to_offset(buffer);
10381 ranges_for_buffer.push(range.clone());
10382
10383 while let Some(next_location) = locations.peek() {
10384 if next_location.buffer == location.buffer {
10385 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10386 locations.next();
10387 } else {
10388 break;
10389 }
10390 }
10391
10392 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10393 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10394 location.buffer.clone(),
10395 ranges_for_buffer,
10396 DEFAULT_MULTIBUFFER_CONTEXT,
10397 cx,
10398 ))
10399 }
10400
10401 multibuffer.with_title(title)
10402 });
10403
10404 let editor = cx.new_view(|cx| {
10405 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10406 });
10407 editor.update(cx, |editor, cx| {
10408 if let Some(first_range) = ranges_to_highlight.first() {
10409 editor.change_selections(None, cx, |selections| {
10410 selections.clear_disjoint();
10411 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10412 });
10413 }
10414 editor.highlight_background::<Self>(
10415 &ranges_to_highlight,
10416 |theme| theme.editor_highlighted_line_background,
10417 cx,
10418 );
10419 });
10420
10421 let item = Box::new(editor);
10422 let item_id = item.item_id();
10423
10424 if split {
10425 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10426 } else {
10427 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10428 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10429 pane.close_current_preview_item(cx)
10430 } else {
10431 None
10432 }
10433 });
10434 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10435 }
10436 workspace.active_pane().update(cx, |pane, cx| {
10437 pane.set_preview_item_id(Some(item_id), cx);
10438 });
10439 }
10440
10441 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10442 use language::ToOffset as _;
10443
10444 let provider = self.semantics_provider.clone()?;
10445 let selection = self.selections.newest_anchor().clone();
10446 let (cursor_buffer, cursor_buffer_position) = self
10447 .buffer
10448 .read(cx)
10449 .text_anchor_for_position(selection.head(), cx)?;
10450 let (tail_buffer, cursor_buffer_position_end) = self
10451 .buffer
10452 .read(cx)
10453 .text_anchor_for_position(selection.tail(), cx)?;
10454 if tail_buffer != cursor_buffer {
10455 return None;
10456 }
10457
10458 let snapshot = cursor_buffer.read(cx).snapshot();
10459 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10460 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10461 let prepare_rename = provider
10462 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10463 .unwrap_or_else(|| Task::ready(Ok(None)));
10464 drop(snapshot);
10465
10466 Some(cx.spawn(|this, mut cx| async move {
10467 let rename_range = if let Some(range) = prepare_rename.await? {
10468 Some(range)
10469 } else {
10470 this.update(&mut cx, |this, cx| {
10471 let buffer = this.buffer.read(cx).snapshot(cx);
10472 let mut buffer_highlights = this
10473 .document_highlights_for_position(selection.head(), &buffer)
10474 .filter(|highlight| {
10475 highlight.start.excerpt_id == selection.head().excerpt_id
10476 && highlight.end.excerpt_id == selection.head().excerpt_id
10477 });
10478 buffer_highlights
10479 .next()
10480 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10481 })?
10482 };
10483 if let Some(rename_range) = rename_range {
10484 this.update(&mut cx, |this, cx| {
10485 let snapshot = cursor_buffer.read(cx).snapshot();
10486 let rename_buffer_range = rename_range.to_offset(&snapshot);
10487 let cursor_offset_in_rename_range =
10488 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10489 let cursor_offset_in_rename_range_end =
10490 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10491
10492 this.take_rename(false, cx);
10493 let buffer = this.buffer.read(cx).read(cx);
10494 let cursor_offset = selection.head().to_offset(&buffer);
10495 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10496 let rename_end = rename_start + rename_buffer_range.len();
10497 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10498 let mut old_highlight_id = None;
10499 let old_name: Arc<str> = buffer
10500 .chunks(rename_start..rename_end, true)
10501 .map(|chunk| {
10502 if old_highlight_id.is_none() {
10503 old_highlight_id = chunk.syntax_highlight_id;
10504 }
10505 chunk.text
10506 })
10507 .collect::<String>()
10508 .into();
10509
10510 drop(buffer);
10511
10512 // Position the selection in the rename editor so that it matches the current selection.
10513 this.show_local_selections = false;
10514 let rename_editor = cx.new_view(|cx| {
10515 let mut editor = Editor::single_line(cx);
10516 editor.buffer.update(cx, |buffer, cx| {
10517 buffer.edit([(0..0, old_name.clone())], None, cx)
10518 });
10519 let rename_selection_range = match cursor_offset_in_rename_range
10520 .cmp(&cursor_offset_in_rename_range_end)
10521 {
10522 Ordering::Equal => {
10523 editor.select_all(&SelectAll, cx);
10524 return editor;
10525 }
10526 Ordering::Less => {
10527 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10528 }
10529 Ordering::Greater => {
10530 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10531 }
10532 };
10533 if rename_selection_range.end > old_name.len() {
10534 editor.select_all(&SelectAll, cx);
10535 } else {
10536 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10537 s.select_ranges([rename_selection_range]);
10538 });
10539 }
10540 editor
10541 });
10542 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10543 if e == &EditorEvent::Focused {
10544 cx.emit(EditorEvent::FocusedIn)
10545 }
10546 })
10547 .detach();
10548
10549 let write_highlights =
10550 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10551 let read_highlights =
10552 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10553 let ranges = write_highlights
10554 .iter()
10555 .flat_map(|(_, ranges)| ranges.iter())
10556 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10557 .cloned()
10558 .collect();
10559
10560 this.highlight_text::<Rename>(
10561 ranges,
10562 HighlightStyle {
10563 fade_out: Some(0.6),
10564 ..Default::default()
10565 },
10566 cx,
10567 );
10568 let rename_focus_handle = rename_editor.focus_handle(cx);
10569 cx.focus(&rename_focus_handle);
10570 let block_id = this.insert_blocks(
10571 [BlockProperties {
10572 style: BlockStyle::Flex,
10573 placement: BlockPlacement::Below(range.start),
10574 height: 1,
10575 render: Arc::new({
10576 let rename_editor = rename_editor.clone();
10577 move |cx: &mut BlockContext| {
10578 let mut text_style = cx.editor_style.text.clone();
10579 if let Some(highlight_style) = old_highlight_id
10580 .and_then(|h| h.style(&cx.editor_style.syntax))
10581 {
10582 text_style = text_style.highlight(highlight_style);
10583 }
10584 div()
10585 .block_mouse_down()
10586 .pl(cx.anchor_x)
10587 .child(EditorElement::new(
10588 &rename_editor,
10589 EditorStyle {
10590 background: cx.theme().system().transparent,
10591 local_player: cx.editor_style.local_player,
10592 text: text_style,
10593 scrollbar_width: cx.editor_style.scrollbar_width,
10594 syntax: cx.editor_style.syntax.clone(),
10595 status: cx.editor_style.status.clone(),
10596 inlay_hints_style: HighlightStyle {
10597 font_weight: Some(FontWeight::BOLD),
10598 ..make_inlay_hints_style(cx)
10599 },
10600 suggestions_style: HighlightStyle {
10601 color: Some(cx.theme().status().predictive),
10602 ..HighlightStyle::default()
10603 },
10604 ..EditorStyle::default()
10605 },
10606 ))
10607 .into_any_element()
10608 }
10609 }),
10610 priority: 0,
10611 }],
10612 Some(Autoscroll::fit()),
10613 cx,
10614 )[0];
10615 this.pending_rename = Some(RenameState {
10616 range,
10617 old_name,
10618 editor: rename_editor,
10619 block_id,
10620 });
10621 })?;
10622 }
10623
10624 Ok(())
10625 }))
10626 }
10627
10628 pub fn confirm_rename(
10629 &mut self,
10630 _: &ConfirmRename,
10631 cx: &mut ViewContext<Self>,
10632 ) -> Option<Task<Result<()>>> {
10633 let rename = self.take_rename(false, cx)?;
10634 let workspace = self.workspace()?.downgrade();
10635 let (buffer, start) = self
10636 .buffer
10637 .read(cx)
10638 .text_anchor_for_position(rename.range.start, cx)?;
10639 let (end_buffer, _) = self
10640 .buffer
10641 .read(cx)
10642 .text_anchor_for_position(rename.range.end, cx)?;
10643 if buffer != end_buffer {
10644 return None;
10645 }
10646
10647 let old_name = rename.old_name;
10648 let new_name = rename.editor.read(cx).text(cx);
10649
10650 let rename = self.semantics_provider.as_ref()?.perform_rename(
10651 &buffer,
10652 start,
10653 new_name.clone(),
10654 cx,
10655 )?;
10656
10657 Some(cx.spawn(|editor, mut cx| async move {
10658 let project_transaction = rename.await?;
10659 Self::open_project_transaction(
10660 &editor,
10661 workspace,
10662 project_transaction,
10663 format!("Rename: {} → {}", old_name, new_name),
10664 cx.clone(),
10665 )
10666 .await?;
10667
10668 editor.update(&mut cx, |editor, cx| {
10669 editor.refresh_document_highlights(cx);
10670 })?;
10671 Ok(())
10672 }))
10673 }
10674
10675 fn take_rename(
10676 &mut self,
10677 moving_cursor: bool,
10678 cx: &mut ViewContext<Self>,
10679 ) -> Option<RenameState> {
10680 let rename = self.pending_rename.take()?;
10681 if rename.editor.focus_handle(cx).is_focused(cx) {
10682 cx.focus(&self.focus_handle);
10683 }
10684
10685 self.remove_blocks(
10686 [rename.block_id].into_iter().collect(),
10687 Some(Autoscroll::fit()),
10688 cx,
10689 );
10690 self.clear_highlights::<Rename>(cx);
10691 self.show_local_selections = true;
10692
10693 if moving_cursor {
10694 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10695 editor.selections.newest::<usize>(cx).head()
10696 });
10697
10698 // Update the selection to match the position of the selection inside
10699 // the rename editor.
10700 let snapshot = self.buffer.read(cx).read(cx);
10701 let rename_range = rename.range.to_offset(&snapshot);
10702 let cursor_in_editor = snapshot
10703 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10704 .min(rename_range.end);
10705 drop(snapshot);
10706
10707 self.change_selections(None, cx, |s| {
10708 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10709 });
10710 } else {
10711 self.refresh_document_highlights(cx);
10712 }
10713
10714 Some(rename)
10715 }
10716
10717 pub fn pending_rename(&self) -> Option<&RenameState> {
10718 self.pending_rename.as_ref()
10719 }
10720
10721 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10722 let project = match &self.project {
10723 Some(project) => project.clone(),
10724 None => return None,
10725 };
10726
10727 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10728 }
10729
10730 fn format_selections(
10731 &mut self,
10732 _: &FormatSelections,
10733 cx: &mut ViewContext<Self>,
10734 ) -> Option<Task<Result<()>>> {
10735 let project = match &self.project {
10736 Some(project) => project.clone(),
10737 None => return None,
10738 };
10739
10740 let selections = self
10741 .selections
10742 .all_adjusted(cx)
10743 .into_iter()
10744 .filter(|s| !s.is_empty())
10745 .collect_vec();
10746
10747 Some(self.perform_format(
10748 project,
10749 FormatTrigger::Manual,
10750 FormatTarget::Ranges(selections),
10751 cx,
10752 ))
10753 }
10754
10755 fn perform_format(
10756 &mut self,
10757 project: Model<Project>,
10758 trigger: FormatTrigger,
10759 target: FormatTarget,
10760 cx: &mut ViewContext<Self>,
10761 ) -> Task<Result<()>> {
10762 let buffer = self.buffer().clone();
10763 let mut buffers = buffer.read(cx).all_buffers();
10764 if trigger == FormatTrigger::Save {
10765 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10766 }
10767
10768 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10769 let format = project.update(cx, |project, cx| {
10770 project.format(buffers, true, trigger, target, cx)
10771 });
10772
10773 cx.spawn(|_, mut cx| async move {
10774 let transaction = futures::select_biased! {
10775 () = timeout => {
10776 log::warn!("timed out waiting for formatting");
10777 None
10778 }
10779 transaction = format.log_err().fuse() => transaction,
10780 };
10781
10782 buffer
10783 .update(&mut cx, |buffer, cx| {
10784 if let Some(transaction) = transaction {
10785 if !buffer.is_singleton() {
10786 buffer.push_transaction(&transaction.0, cx);
10787 }
10788 }
10789
10790 cx.notify();
10791 })
10792 .ok();
10793
10794 Ok(())
10795 })
10796 }
10797
10798 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10799 if let Some(project) = self.project.clone() {
10800 self.buffer.update(cx, |multi_buffer, cx| {
10801 project.update(cx, |project, cx| {
10802 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10803 });
10804 })
10805 }
10806 }
10807
10808 fn cancel_language_server_work(
10809 &mut self,
10810 _: &actions::CancelLanguageServerWork,
10811 cx: &mut ViewContext<Self>,
10812 ) {
10813 if let Some(project) = self.project.clone() {
10814 self.buffer.update(cx, |multi_buffer, cx| {
10815 project.update(cx, |project, cx| {
10816 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10817 });
10818 })
10819 }
10820 }
10821
10822 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10823 cx.show_character_palette();
10824 }
10825
10826 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10827 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10828 let buffer = self.buffer.read(cx).snapshot(cx);
10829 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10830 let is_valid = buffer
10831 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10832 .any(|entry| {
10833 entry.diagnostic.is_primary
10834 && !entry.range.is_empty()
10835 && entry.range.start == primary_range_start
10836 && entry.diagnostic.message == active_diagnostics.primary_message
10837 });
10838
10839 if is_valid != active_diagnostics.is_valid {
10840 active_diagnostics.is_valid = is_valid;
10841 let mut new_styles = HashMap::default();
10842 for (block_id, diagnostic) in &active_diagnostics.blocks {
10843 new_styles.insert(
10844 *block_id,
10845 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10846 );
10847 }
10848 self.display_map.update(cx, |display_map, _cx| {
10849 display_map.replace_blocks(new_styles)
10850 });
10851 }
10852 }
10853 }
10854
10855 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10856 self.dismiss_diagnostics(cx);
10857 let snapshot = self.snapshot(cx);
10858 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10859 let buffer = self.buffer.read(cx).snapshot(cx);
10860
10861 let mut primary_range = None;
10862 let mut primary_message = None;
10863 let mut group_end = Point::zero();
10864 let diagnostic_group = buffer
10865 .diagnostic_group::<MultiBufferPoint>(group_id)
10866 .filter_map(|entry| {
10867 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10868 && (entry.range.start.row == entry.range.end.row
10869 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10870 {
10871 return None;
10872 }
10873 if entry.range.end > group_end {
10874 group_end = entry.range.end;
10875 }
10876 if entry.diagnostic.is_primary {
10877 primary_range = Some(entry.range.clone());
10878 primary_message = Some(entry.diagnostic.message.clone());
10879 }
10880 Some(entry)
10881 })
10882 .collect::<Vec<_>>();
10883 let primary_range = primary_range?;
10884 let primary_message = primary_message?;
10885 let primary_range =
10886 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10887
10888 let blocks = display_map
10889 .insert_blocks(
10890 diagnostic_group.iter().map(|entry| {
10891 let diagnostic = entry.diagnostic.clone();
10892 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10893 BlockProperties {
10894 style: BlockStyle::Fixed,
10895 placement: BlockPlacement::Below(
10896 buffer.anchor_after(entry.range.start),
10897 ),
10898 height: message_height,
10899 render: diagnostic_block_renderer(diagnostic, None, true, true),
10900 priority: 0,
10901 }
10902 }),
10903 cx,
10904 )
10905 .into_iter()
10906 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10907 .collect();
10908
10909 Some(ActiveDiagnosticGroup {
10910 primary_range,
10911 primary_message,
10912 group_id,
10913 blocks,
10914 is_valid: true,
10915 })
10916 });
10917 self.active_diagnostics.is_some()
10918 }
10919
10920 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10921 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10922 self.display_map.update(cx, |display_map, cx| {
10923 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10924 });
10925 cx.notify();
10926 }
10927 }
10928
10929 pub fn set_selections_from_remote(
10930 &mut self,
10931 selections: Vec<Selection<Anchor>>,
10932 pending_selection: Option<Selection<Anchor>>,
10933 cx: &mut ViewContext<Self>,
10934 ) {
10935 let old_cursor_position = self.selections.newest_anchor().head();
10936 self.selections.change_with(cx, |s| {
10937 s.select_anchors(selections);
10938 if let Some(pending_selection) = pending_selection {
10939 s.set_pending(pending_selection, SelectMode::Character);
10940 } else {
10941 s.clear_pending();
10942 }
10943 });
10944 self.selections_did_change(false, &old_cursor_position, true, cx);
10945 }
10946
10947 fn push_to_selection_history(&mut self) {
10948 self.selection_history.push(SelectionHistoryEntry {
10949 selections: self.selections.disjoint_anchors(),
10950 select_next_state: self.select_next_state.clone(),
10951 select_prev_state: self.select_prev_state.clone(),
10952 add_selections_state: self.add_selections_state.clone(),
10953 });
10954 }
10955
10956 pub fn transact(
10957 &mut self,
10958 cx: &mut ViewContext<Self>,
10959 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10960 ) -> Option<TransactionId> {
10961 self.start_transaction_at(Instant::now(), cx);
10962 update(self, cx);
10963 self.end_transaction_at(Instant::now(), cx)
10964 }
10965
10966 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10967 self.end_selection(cx);
10968 if let Some(tx_id) = self
10969 .buffer
10970 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10971 {
10972 self.selection_history
10973 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10974 cx.emit(EditorEvent::TransactionBegun {
10975 transaction_id: tx_id,
10976 })
10977 }
10978 }
10979
10980 fn end_transaction_at(
10981 &mut self,
10982 now: Instant,
10983 cx: &mut ViewContext<Self>,
10984 ) -> Option<TransactionId> {
10985 if let Some(transaction_id) = self
10986 .buffer
10987 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10988 {
10989 if let Some((_, end_selections)) =
10990 self.selection_history.transaction_mut(transaction_id)
10991 {
10992 *end_selections = Some(self.selections.disjoint_anchors());
10993 } else {
10994 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10995 }
10996
10997 cx.emit(EditorEvent::Edited { transaction_id });
10998 Some(transaction_id)
10999 } else {
11000 None
11001 }
11002 }
11003
11004 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11005 let selection = self.selections.newest::<Point>(cx);
11006
11007 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11008 let range = if selection.is_empty() {
11009 let point = selection.head().to_display_point(&display_map);
11010 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11011 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11012 .to_point(&display_map);
11013 start..end
11014 } else {
11015 selection.range()
11016 };
11017 if display_map.folds_in_range(range).next().is_some() {
11018 self.unfold_lines(&Default::default(), cx)
11019 } else {
11020 self.fold(&Default::default(), cx)
11021 }
11022 }
11023
11024 pub fn toggle_fold_recursive(
11025 &mut self,
11026 _: &actions::ToggleFoldRecursive,
11027 cx: &mut ViewContext<Self>,
11028 ) {
11029 let selection = self.selections.newest::<Point>(cx);
11030
11031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11032 let range = if selection.is_empty() {
11033 let point = selection.head().to_display_point(&display_map);
11034 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11035 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11036 .to_point(&display_map);
11037 start..end
11038 } else {
11039 selection.range()
11040 };
11041 if display_map.folds_in_range(range).next().is_some() {
11042 self.unfold_recursive(&Default::default(), cx)
11043 } else {
11044 self.fold_recursive(&Default::default(), cx)
11045 }
11046 }
11047
11048 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11049 let mut to_fold = Vec::new();
11050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11051 let selections = self.selections.all_adjusted(cx);
11052
11053 for selection in selections {
11054 let range = selection.range().sorted();
11055 let buffer_start_row = range.start.row;
11056
11057 if range.start.row != range.end.row {
11058 let mut found = false;
11059 let mut row = range.start.row;
11060 while row <= range.end.row {
11061 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11062 found = true;
11063 row = crease.range().end.row + 1;
11064 to_fold.push(crease);
11065 } else {
11066 row += 1
11067 }
11068 }
11069 if found {
11070 continue;
11071 }
11072 }
11073
11074 for row in (0..=range.start.row).rev() {
11075 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11076 if crease.range().end.row >= buffer_start_row {
11077 to_fold.push(crease);
11078 if row <= range.start.row {
11079 break;
11080 }
11081 }
11082 }
11083 }
11084 }
11085
11086 self.fold_creases(to_fold, true, cx);
11087 }
11088
11089 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11090 let fold_at_level = fold_at.level;
11091 let snapshot = self.buffer.read(cx).snapshot(cx);
11092 let mut to_fold = Vec::new();
11093 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11094
11095 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11096 while start_row < end_row {
11097 match self
11098 .snapshot(cx)
11099 .crease_for_buffer_row(MultiBufferRow(start_row))
11100 {
11101 Some(crease) => {
11102 let nested_start_row = crease.range().start.row + 1;
11103 let nested_end_row = crease.range().end.row;
11104
11105 if current_level < fold_at_level {
11106 stack.push((nested_start_row, nested_end_row, current_level + 1));
11107 } else if current_level == fold_at_level {
11108 to_fold.push(crease);
11109 }
11110
11111 start_row = nested_end_row + 1;
11112 }
11113 None => start_row += 1,
11114 }
11115 }
11116 }
11117
11118 self.fold_creases(to_fold, true, cx);
11119 }
11120
11121 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11122 let mut fold_ranges = Vec::new();
11123 let snapshot = self.buffer.read(cx).snapshot(cx);
11124
11125 for row in 0..snapshot.max_buffer_row().0 {
11126 if let Some(foldable_range) =
11127 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11128 {
11129 fold_ranges.push(foldable_range);
11130 }
11131 }
11132
11133 self.fold_creases(fold_ranges, true, cx);
11134 }
11135
11136 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11137 let mut to_fold = Vec::new();
11138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11139 let selections = self.selections.all_adjusted(cx);
11140
11141 for selection in selections {
11142 let range = selection.range().sorted();
11143 let buffer_start_row = range.start.row;
11144
11145 if range.start.row != range.end.row {
11146 let mut found = false;
11147 for row in range.start.row..=range.end.row {
11148 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11149 found = true;
11150 to_fold.push(crease);
11151 }
11152 }
11153 if found {
11154 continue;
11155 }
11156 }
11157
11158 for row in (0..=range.start.row).rev() {
11159 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11160 if crease.range().end.row >= buffer_start_row {
11161 to_fold.push(crease);
11162 } else {
11163 break;
11164 }
11165 }
11166 }
11167 }
11168
11169 self.fold_creases(to_fold, true, cx);
11170 }
11171
11172 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11173 let buffer_row = fold_at.buffer_row;
11174 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11175
11176 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11177 let autoscroll = self
11178 .selections
11179 .all::<Point>(cx)
11180 .iter()
11181 .any(|selection| crease.range().overlaps(&selection.range()));
11182
11183 self.fold_creases(vec![crease], autoscroll, cx);
11184 }
11185 }
11186
11187 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11188 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11189 let buffer = &display_map.buffer_snapshot;
11190 let selections = self.selections.all::<Point>(cx);
11191 let ranges = selections
11192 .iter()
11193 .map(|s| {
11194 let range = s.display_range(&display_map).sorted();
11195 let mut start = range.start.to_point(&display_map);
11196 let mut end = range.end.to_point(&display_map);
11197 start.column = 0;
11198 end.column = buffer.line_len(MultiBufferRow(end.row));
11199 start..end
11200 })
11201 .collect::<Vec<_>>();
11202
11203 self.unfold_ranges(&ranges, true, true, cx);
11204 }
11205
11206 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11207 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11208 let selections = self.selections.all::<Point>(cx);
11209 let ranges = selections
11210 .iter()
11211 .map(|s| {
11212 let mut range = s.display_range(&display_map).sorted();
11213 *range.start.column_mut() = 0;
11214 *range.end.column_mut() = display_map.line_len(range.end.row());
11215 let start = range.start.to_point(&display_map);
11216 let end = range.end.to_point(&display_map);
11217 start..end
11218 })
11219 .collect::<Vec<_>>();
11220
11221 self.unfold_ranges(&ranges, true, true, cx);
11222 }
11223
11224 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11225 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11226
11227 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11228 ..Point::new(
11229 unfold_at.buffer_row.0,
11230 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11231 );
11232
11233 let autoscroll = self
11234 .selections
11235 .all::<Point>(cx)
11236 .iter()
11237 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11238
11239 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11240 }
11241
11242 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11243 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11244 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11245 }
11246
11247 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11248 let selections = self.selections.all::<Point>(cx);
11249 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11250 let line_mode = self.selections.line_mode;
11251 let ranges = selections
11252 .into_iter()
11253 .map(|s| {
11254 if line_mode {
11255 let start = Point::new(s.start.row, 0);
11256 let end = Point::new(
11257 s.end.row,
11258 display_map
11259 .buffer_snapshot
11260 .line_len(MultiBufferRow(s.end.row)),
11261 );
11262 Crease::simple(start..end, display_map.fold_placeholder.clone())
11263 } else {
11264 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11265 }
11266 })
11267 .collect::<Vec<_>>();
11268 self.fold_creases(ranges, true, cx);
11269 }
11270
11271 pub fn fold_creases<T: ToOffset + Clone>(
11272 &mut self,
11273 creases: Vec<Crease<T>>,
11274 auto_scroll: bool,
11275 cx: &mut ViewContext<Self>,
11276 ) {
11277 if creases.is_empty() {
11278 return;
11279 }
11280
11281 let mut buffers_affected = HashMap::default();
11282 let multi_buffer = self.buffer().read(cx);
11283 for crease in &creases {
11284 if let Some((_, buffer, _)) =
11285 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11286 {
11287 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11288 };
11289 }
11290
11291 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11292
11293 if auto_scroll {
11294 self.request_autoscroll(Autoscroll::fit(), cx);
11295 }
11296
11297 for buffer in buffers_affected.into_values() {
11298 self.sync_expanded_diff_hunks(buffer, cx);
11299 }
11300
11301 cx.notify();
11302
11303 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11304 // Clear diagnostics block when folding a range that contains it.
11305 let snapshot = self.snapshot(cx);
11306 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11307 drop(snapshot);
11308 self.active_diagnostics = Some(active_diagnostics);
11309 self.dismiss_diagnostics(cx);
11310 } else {
11311 self.active_diagnostics = Some(active_diagnostics);
11312 }
11313 }
11314
11315 self.scrollbar_marker_state.dirty = true;
11316 }
11317
11318 /// Removes any folds whose ranges intersect any of the given ranges.
11319 pub fn unfold_ranges<T: ToOffset + Clone>(
11320 &mut self,
11321 ranges: &[Range<T>],
11322 inclusive: bool,
11323 auto_scroll: bool,
11324 cx: &mut ViewContext<Self>,
11325 ) {
11326 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11327 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11328 });
11329 }
11330
11331 /// Removes any folds with the given ranges.
11332 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11333 &mut self,
11334 ranges: &[Range<T>],
11335 type_id: TypeId,
11336 auto_scroll: bool,
11337 cx: &mut ViewContext<Self>,
11338 ) {
11339 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11340 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11341 });
11342 }
11343
11344 fn remove_folds_with<T: ToOffset + Clone>(
11345 &mut self,
11346 ranges: &[Range<T>],
11347 auto_scroll: bool,
11348 cx: &mut ViewContext<Self>,
11349 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11350 ) {
11351 if ranges.is_empty() {
11352 return;
11353 }
11354
11355 let mut buffers_affected = HashMap::default();
11356 let multi_buffer = self.buffer().read(cx);
11357 for range in ranges {
11358 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11359 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11360 };
11361 }
11362
11363 self.display_map.update(cx, update);
11364
11365 if auto_scroll {
11366 self.request_autoscroll(Autoscroll::fit(), cx);
11367 }
11368
11369 for buffer in buffers_affected.into_values() {
11370 self.sync_expanded_diff_hunks(buffer, cx);
11371 }
11372
11373 cx.notify();
11374 self.scrollbar_marker_state.dirty = true;
11375 self.active_indent_guides_state.dirty = true;
11376 }
11377
11378 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11379 self.display_map.read(cx).fold_placeholder.clone()
11380 }
11381
11382 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11383 if hovered != self.gutter_hovered {
11384 self.gutter_hovered = hovered;
11385 cx.notify();
11386 }
11387 }
11388
11389 pub fn insert_blocks(
11390 &mut self,
11391 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11392 autoscroll: Option<Autoscroll>,
11393 cx: &mut ViewContext<Self>,
11394 ) -> Vec<CustomBlockId> {
11395 let blocks = self
11396 .display_map
11397 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11398 if let Some(autoscroll) = autoscroll {
11399 self.request_autoscroll(autoscroll, cx);
11400 }
11401 cx.notify();
11402 blocks
11403 }
11404
11405 pub fn resize_blocks(
11406 &mut self,
11407 heights: HashMap<CustomBlockId, u32>,
11408 autoscroll: Option<Autoscroll>,
11409 cx: &mut ViewContext<Self>,
11410 ) {
11411 self.display_map
11412 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11413 if let Some(autoscroll) = autoscroll {
11414 self.request_autoscroll(autoscroll, cx);
11415 }
11416 cx.notify();
11417 }
11418
11419 pub fn replace_blocks(
11420 &mut self,
11421 renderers: HashMap<CustomBlockId, RenderBlock>,
11422 autoscroll: Option<Autoscroll>,
11423 cx: &mut ViewContext<Self>,
11424 ) {
11425 self.display_map
11426 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11427 if let Some(autoscroll) = autoscroll {
11428 self.request_autoscroll(autoscroll, cx);
11429 }
11430 cx.notify();
11431 }
11432
11433 pub fn remove_blocks(
11434 &mut self,
11435 block_ids: HashSet<CustomBlockId>,
11436 autoscroll: Option<Autoscroll>,
11437 cx: &mut ViewContext<Self>,
11438 ) {
11439 self.display_map.update(cx, |display_map, cx| {
11440 display_map.remove_blocks(block_ids, cx)
11441 });
11442 if let Some(autoscroll) = autoscroll {
11443 self.request_autoscroll(autoscroll, cx);
11444 }
11445 cx.notify();
11446 }
11447
11448 pub fn row_for_block(
11449 &self,
11450 block_id: CustomBlockId,
11451 cx: &mut ViewContext<Self>,
11452 ) -> Option<DisplayRow> {
11453 self.display_map
11454 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11455 }
11456
11457 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11458 self.focused_block = Some(focused_block);
11459 }
11460
11461 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11462 self.focused_block.take()
11463 }
11464
11465 pub fn insert_creases(
11466 &mut self,
11467 creases: impl IntoIterator<Item = Crease<Anchor>>,
11468 cx: &mut ViewContext<Self>,
11469 ) -> Vec<CreaseId> {
11470 self.display_map
11471 .update(cx, |map, cx| map.insert_creases(creases, cx))
11472 }
11473
11474 pub fn remove_creases(
11475 &mut self,
11476 ids: impl IntoIterator<Item = CreaseId>,
11477 cx: &mut ViewContext<Self>,
11478 ) {
11479 self.display_map
11480 .update(cx, |map, cx| map.remove_creases(ids, cx));
11481 }
11482
11483 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11484 self.display_map
11485 .update(cx, |map, cx| map.snapshot(cx))
11486 .longest_row()
11487 }
11488
11489 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11490 self.display_map
11491 .update(cx, |map, cx| map.snapshot(cx))
11492 .max_point()
11493 }
11494
11495 pub fn text(&self, cx: &AppContext) -> String {
11496 self.buffer.read(cx).read(cx).text()
11497 }
11498
11499 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11500 let text = self.text(cx);
11501 let text = text.trim();
11502
11503 if text.is_empty() {
11504 return None;
11505 }
11506
11507 Some(text.to_string())
11508 }
11509
11510 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11511 self.transact(cx, |this, cx| {
11512 this.buffer
11513 .read(cx)
11514 .as_singleton()
11515 .expect("you can only call set_text on editors for singleton buffers")
11516 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11517 });
11518 }
11519
11520 pub fn display_text(&self, cx: &mut AppContext) -> String {
11521 self.display_map
11522 .update(cx, |map, cx| map.snapshot(cx))
11523 .text()
11524 }
11525
11526 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11527 let mut wrap_guides = smallvec::smallvec![];
11528
11529 if self.show_wrap_guides == Some(false) {
11530 return wrap_guides;
11531 }
11532
11533 let settings = self.buffer.read(cx).settings_at(0, cx);
11534 if settings.show_wrap_guides {
11535 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11536 wrap_guides.push((soft_wrap as usize, true));
11537 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11538 wrap_guides.push((soft_wrap as usize, true));
11539 }
11540 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11541 }
11542
11543 wrap_guides
11544 }
11545
11546 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11547 let settings = self.buffer.read(cx).settings_at(0, cx);
11548 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11549 match mode {
11550 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11551 SoftWrap::None
11552 }
11553 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11554 language_settings::SoftWrap::PreferredLineLength => {
11555 SoftWrap::Column(settings.preferred_line_length)
11556 }
11557 language_settings::SoftWrap::Bounded => {
11558 SoftWrap::Bounded(settings.preferred_line_length)
11559 }
11560 }
11561 }
11562
11563 pub fn set_soft_wrap_mode(
11564 &mut self,
11565 mode: language_settings::SoftWrap,
11566 cx: &mut ViewContext<Self>,
11567 ) {
11568 self.soft_wrap_mode_override = Some(mode);
11569 cx.notify();
11570 }
11571
11572 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11573 self.text_style_refinement = Some(style);
11574 }
11575
11576 /// called by the Element so we know what style we were most recently rendered with.
11577 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11578 let rem_size = cx.rem_size();
11579 self.display_map.update(cx, |map, cx| {
11580 map.set_font(
11581 style.text.font(),
11582 style.text.font_size.to_pixels(rem_size),
11583 cx,
11584 )
11585 });
11586 self.style = Some(style);
11587 }
11588
11589 pub fn style(&self) -> Option<&EditorStyle> {
11590 self.style.as_ref()
11591 }
11592
11593 // Called by the element. This method is not designed to be called outside of the editor
11594 // element's layout code because it does not notify when rewrapping is computed synchronously.
11595 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11596 self.display_map
11597 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11598 }
11599
11600 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11601 if self.soft_wrap_mode_override.is_some() {
11602 self.soft_wrap_mode_override.take();
11603 } else {
11604 let soft_wrap = match self.soft_wrap_mode(cx) {
11605 SoftWrap::GitDiff => return,
11606 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11607 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11608 language_settings::SoftWrap::None
11609 }
11610 };
11611 self.soft_wrap_mode_override = Some(soft_wrap);
11612 }
11613 cx.notify();
11614 }
11615
11616 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11617 let Some(workspace) = self.workspace() else {
11618 return;
11619 };
11620 let fs = workspace.read(cx).app_state().fs.clone();
11621 let current_show = TabBarSettings::get_global(cx).show;
11622 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11623 setting.show = Some(!current_show);
11624 });
11625 }
11626
11627 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11628 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11629 self.buffer
11630 .read(cx)
11631 .settings_at(0, cx)
11632 .indent_guides
11633 .enabled
11634 });
11635 self.show_indent_guides = Some(!currently_enabled);
11636 cx.notify();
11637 }
11638
11639 fn should_show_indent_guides(&self) -> Option<bool> {
11640 self.show_indent_guides
11641 }
11642
11643 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11644 let mut editor_settings = EditorSettings::get_global(cx).clone();
11645 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11646 EditorSettings::override_global(editor_settings, cx);
11647 }
11648
11649 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11650 self.use_relative_line_numbers
11651 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11652 }
11653
11654 pub fn toggle_relative_line_numbers(
11655 &mut self,
11656 _: &ToggleRelativeLineNumbers,
11657 cx: &mut ViewContext<Self>,
11658 ) {
11659 let is_relative = self.should_use_relative_line_numbers(cx);
11660 self.set_relative_line_number(Some(!is_relative), cx)
11661 }
11662
11663 pub fn set_relative_line_number(
11664 &mut self,
11665 is_relative: Option<bool>,
11666 cx: &mut ViewContext<Self>,
11667 ) {
11668 self.use_relative_line_numbers = is_relative;
11669 cx.notify();
11670 }
11671
11672 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11673 self.show_gutter = show_gutter;
11674 cx.notify();
11675 }
11676
11677 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11678 self.show_line_numbers = Some(show_line_numbers);
11679 cx.notify();
11680 }
11681
11682 pub fn set_show_git_diff_gutter(
11683 &mut self,
11684 show_git_diff_gutter: bool,
11685 cx: &mut ViewContext<Self>,
11686 ) {
11687 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11688 cx.notify();
11689 }
11690
11691 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11692 self.show_code_actions = Some(show_code_actions);
11693 cx.notify();
11694 }
11695
11696 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11697 self.show_runnables = Some(show_runnables);
11698 cx.notify();
11699 }
11700
11701 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11702 if self.display_map.read(cx).masked != masked {
11703 self.display_map.update(cx, |map, _| map.masked = masked);
11704 }
11705 cx.notify()
11706 }
11707
11708 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11709 self.show_wrap_guides = Some(show_wrap_guides);
11710 cx.notify();
11711 }
11712
11713 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11714 self.show_indent_guides = Some(show_indent_guides);
11715 cx.notify();
11716 }
11717
11718 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11719 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11720 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11721 if let Some(dir) = file.abs_path(cx).parent() {
11722 return Some(dir.to_owned());
11723 }
11724 }
11725
11726 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11727 return Some(project_path.path.to_path_buf());
11728 }
11729 }
11730
11731 None
11732 }
11733
11734 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11735 self.active_excerpt(cx)?
11736 .1
11737 .read(cx)
11738 .file()
11739 .and_then(|f| f.as_local())
11740 }
11741
11742 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11743 if let Some(target) = self.target_file(cx) {
11744 cx.reveal_path(&target.abs_path(cx));
11745 }
11746 }
11747
11748 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11749 if let Some(file) = self.target_file(cx) {
11750 if let Some(path) = file.abs_path(cx).to_str() {
11751 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11752 }
11753 }
11754 }
11755
11756 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11757 if let Some(file) = self.target_file(cx) {
11758 if let Some(path) = file.path().to_str() {
11759 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11760 }
11761 }
11762 }
11763
11764 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11765 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11766
11767 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11768 self.start_git_blame(true, cx);
11769 }
11770
11771 cx.notify();
11772 }
11773
11774 pub fn toggle_git_blame_inline(
11775 &mut self,
11776 _: &ToggleGitBlameInline,
11777 cx: &mut ViewContext<Self>,
11778 ) {
11779 self.toggle_git_blame_inline_internal(true, cx);
11780 cx.notify();
11781 }
11782
11783 pub fn git_blame_inline_enabled(&self) -> bool {
11784 self.git_blame_inline_enabled
11785 }
11786
11787 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11788 self.show_selection_menu = self
11789 .show_selection_menu
11790 .map(|show_selections_menu| !show_selections_menu)
11791 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11792
11793 cx.notify();
11794 }
11795
11796 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11797 self.show_selection_menu
11798 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11799 }
11800
11801 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11802 if let Some(project) = self.project.as_ref() {
11803 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11804 return;
11805 };
11806
11807 if buffer.read(cx).file().is_none() {
11808 return;
11809 }
11810
11811 let focused = self.focus_handle(cx).contains_focused(cx);
11812
11813 let project = project.clone();
11814 let blame =
11815 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11816 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11817 self.blame = Some(blame);
11818 }
11819 }
11820
11821 fn toggle_git_blame_inline_internal(
11822 &mut self,
11823 user_triggered: bool,
11824 cx: &mut ViewContext<Self>,
11825 ) {
11826 if self.git_blame_inline_enabled {
11827 self.git_blame_inline_enabled = false;
11828 self.show_git_blame_inline = false;
11829 self.show_git_blame_inline_delay_task.take();
11830 } else {
11831 self.git_blame_inline_enabled = true;
11832 self.start_git_blame_inline(user_triggered, cx);
11833 }
11834
11835 cx.notify();
11836 }
11837
11838 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11839 self.start_git_blame(user_triggered, cx);
11840
11841 if ProjectSettings::get_global(cx)
11842 .git
11843 .inline_blame_delay()
11844 .is_some()
11845 {
11846 self.start_inline_blame_timer(cx);
11847 } else {
11848 self.show_git_blame_inline = true
11849 }
11850 }
11851
11852 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11853 self.blame.as_ref()
11854 }
11855
11856 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11857 self.show_git_blame_gutter && self.has_blame_entries(cx)
11858 }
11859
11860 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11861 self.show_git_blame_inline
11862 && self.focus_handle.is_focused(cx)
11863 && !self.newest_selection_head_on_empty_line(cx)
11864 && self.has_blame_entries(cx)
11865 }
11866
11867 pub fn render_active_line_trailer(
11868 &mut self,
11869 style: &EditorStyle,
11870 cx: &mut WindowContext,
11871 ) -> Option<AnyElement> {
11872 let selection = self.selections.newest::<Point>(cx);
11873 if !selection.is_empty() {
11874 return None;
11875 };
11876
11877 let snapshot = self.buffer.read(cx).snapshot(cx);
11878 let buffer_row = MultiBufferRow(selection.head().row);
11879
11880 if snapshot.line_len(buffer_row) != 0 || self.has_active_inline_completion(cx) {
11881 return None;
11882 }
11883
11884 let focus_handle = self.focus_handle.clone();
11885 self.active_line_trailer_provider
11886 .as_mut()?
11887 .render_active_line_trailer(style, &focus_handle, cx)
11888 }
11889
11890 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11891 self.blame()
11892 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11893 }
11894
11895 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11896 let cursor_anchor = self.selections.newest_anchor().head();
11897
11898 let snapshot = self.buffer.read(cx).snapshot(cx);
11899 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11900
11901 snapshot.line_len(buffer_row) == 0
11902 }
11903
11904 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11905 let buffer_and_selection = maybe!({
11906 let selection = self.selections.newest::<Point>(cx);
11907 let selection_range = selection.range();
11908
11909 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11910 (buffer, selection_range.start.row..selection_range.end.row)
11911 } else {
11912 let buffer_ranges = self
11913 .buffer()
11914 .read(cx)
11915 .range_to_buffer_ranges(selection_range, cx);
11916
11917 let (buffer, range, _) = if selection.reversed {
11918 buffer_ranges.first()
11919 } else {
11920 buffer_ranges.last()
11921 }?;
11922
11923 let snapshot = buffer.read(cx).snapshot();
11924 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11925 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11926 (buffer.clone(), selection)
11927 };
11928
11929 Some((buffer, selection))
11930 });
11931
11932 let Some((buffer, selection)) = buffer_and_selection else {
11933 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11934 };
11935
11936 let Some(project) = self.project.as_ref() else {
11937 return Task::ready(Err(anyhow!("editor does not have project")));
11938 };
11939
11940 project.update(cx, |project, cx| {
11941 project.get_permalink_to_line(&buffer, selection, cx)
11942 })
11943 }
11944
11945 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11946 let permalink_task = self.get_permalink_to_line(cx);
11947 let workspace = self.workspace();
11948
11949 cx.spawn(|_, mut cx| async move {
11950 match permalink_task.await {
11951 Ok(permalink) => {
11952 cx.update(|cx| {
11953 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11954 })
11955 .ok();
11956 }
11957 Err(err) => {
11958 let message = format!("Failed to copy permalink: {err}");
11959
11960 Err::<(), anyhow::Error>(err).log_err();
11961
11962 if let Some(workspace) = workspace {
11963 workspace
11964 .update(&mut cx, |workspace, cx| {
11965 struct CopyPermalinkToLine;
11966
11967 workspace.show_toast(
11968 Toast::new(
11969 NotificationId::unique::<CopyPermalinkToLine>(),
11970 message,
11971 ),
11972 cx,
11973 )
11974 })
11975 .ok();
11976 }
11977 }
11978 }
11979 })
11980 .detach();
11981 }
11982
11983 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11984 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11985 if let Some(file) = self.target_file(cx) {
11986 if let Some(path) = file.path().to_str() {
11987 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11988 }
11989 }
11990 }
11991
11992 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11993 let permalink_task = self.get_permalink_to_line(cx);
11994 let workspace = self.workspace();
11995
11996 cx.spawn(|_, mut cx| async move {
11997 match permalink_task.await {
11998 Ok(permalink) => {
11999 cx.update(|cx| {
12000 cx.open_url(permalink.as_ref());
12001 })
12002 .ok();
12003 }
12004 Err(err) => {
12005 let message = format!("Failed to open permalink: {err}");
12006
12007 Err::<(), anyhow::Error>(err).log_err();
12008
12009 if let Some(workspace) = workspace {
12010 workspace
12011 .update(&mut cx, |workspace, cx| {
12012 struct OpenPermalinkToLine;
12013
12014 workspace.show_toast(
12015 Toast::new(
12016 NotificationId::unique::<OpenPermalinkToLine>(),
12017 message,
12018 ),
12019 cx,
12020 )
12021 })
12022 .ok();
12023 }
12024 }
12025 }
12026 })
12027 .detach();
12028 }
12029
12030 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12031 /// last highlight added will be used.
12032 ///
12033 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12034 pub fn highlight_rows<T: 'static>(
12035 &mut self,
12036 range: Range<Anchor>,
12037 color: Hsla,
12038 should_autoscroll: bool,
12039 cx: &mut ViewContext<Self>,
12040 ) {
12041 let snapshot = self.buffer().read(cx).snapshot(cx);
12042 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12043 let ix = row_highlights.binary_search_by(|highlight| {
12044 Ordering::Equal
12045 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12046 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12047 });
12048
12049 if let Err(mut ix) = ix {
12050 let index = post_inc(&mut self.highlight_order);
12051
12052 // If this range intersects with the preceding highlight, then merge it with
12053 // the preceding highlight. Otherwise insert a new highlight.
12054 let mut merged = false;
12055 if ix > 0 {
12056 let prev_highlight = &mut row_highlights[ix - 1];
12057 if prev_highlight
12058 .range
12059 .end
12060 .cmp(&range.start, &snapshot)
12061 .is_ge()
12062 {
12063 ix -= 1;
12064 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12065 prev_highlight.range.end = range.end;
12066 }
12067 merged = true;
12068 prev_highlight.index = index;
12069 prev_highlight.color = color;
12070 prev_highlight.should_autoscroll = should_autoscroll;
12071 }
12072 }
12073
12074 if !merged {
12075 row_highlights.insert(
12076 ix,
12077 RowHighlight {
12078 range: range.clone(),
12079 index,
12080 color,
12081 should_autoscroll,
12082 },
12083 );
12084 }
12085
12086 // If any of the following highlights intersect with this one, merge them.
12087 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12088 let highlight = &row_highlights[ix];
12089 if next_highlight
12090 .range
12091 .start
12092 .cmp(&highlight.range.end, &snapshot)
12093 .is_le()
12094 {
12095 if next_highlight
12096 .range
12097 .end
12098 .cmp(&highlight.range.end, &snapshot)
12099 .is_gt()
12100 {
12101 row_highlights[ix].range.end = next_highlight.range.end;
12102 }
12103 row_highlights.remove(ix + 1);
12104 } else {
12105 break;
12106 }
12107 }
12108 }
12109 }
12110
12111 /// Remove any highlighted row ranges of the given type that intersect the
12112 /// given ranges.
12113 pub fn remove_highlighted_rows<T: 'static>(
12114 &mut self,
12115 ranges_to_remove: Vec<Range<Anchor>>,
12116 cx: &mut ViewContext<Self>,
12117 ) {
12118 let snapshot = self.buffer().read(cx).snapshot(cx);
12119 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12120 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12121 row_highlights.retain(|highlight| {
12122 while let Some(range_to_remove) = ranges_to_remove.peek() {
12123 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12124 Ordering::Less | Ordering::Equal => {
12125 ranges_to_remove.next();
12126 }
12127 Ordering::Greater => {
12128 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12129 Ordering::Less | Ordering::Equal => {
12130 return false;
12131 }
12132 Ordering::Greater => break,
12133 }
12134 }
12135 }
12136 }
12137
12138 true
12139 })
12140 }
12141
12142 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12143 pub fn clear_row_highlights<T: 'static>(&mut self) {
12144 self.highlighted_rows.remove(&TypeId::of::<T>());
12145 }
12146
12147 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12148 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12149 self.highlighted_rows
12150 .get(&TypeId::of::<T>())
12151 .map_or(&[] as &[_], |vec| vec.as_slice())
12152 .iter()
12153 .map(|highlight| (highlight.range.clone(), highlight.color))
12154 }
12155
12156 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12157 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12158 /// Allows to ignore certain kinds of highlights.
12159 pub fn highlighted_display_rows(
12160 &mut self,
12161 cx: &mut WindowContext,
12162 ) -> BTreeMap<DisplayRow, Hsla> {
12163 let snapshot = self.snapshot(cx);
12164 let mut used_highlight_orders = HashMap::default();
12165 self.highlighted_rows
12166 .iter()
12167 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12168 .fold(
12169 BTreeMap::<DisplayRow, Hsla>::new(),
12170 |mut unique_rows, highlight| {
12171 let start = highlight.range.start.to_display_point(&snapshot);
12172 let end = highlight.range.end.to_display_point(&snapshot);
12173 let start_row = start.row().0;
12174 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12175 && end.column() == 0
12176 {
12177 end.row().0.saturating_sub(1)
12178 } else {
12179 end.row().0
12180 };
12181 for row in start_row..=end_row {
12182 let used_index =
12183 used_highlight_orders.entry(row).or_insert(highlight.index);
12184 if highlight.index >= *used_index {
12185 *used_index = highlight.index;
12186 unique_rows.insert(DisplayRow(row), highlight.color);
12187 }
12188 }
12189 unique_rows
12190 },
12191 )
12192 }
12193
12194 pub fn highlighted_display_row_for_autoscroll(
12195 &self,
12196 snapshot: &DisplaySnapshot,
12197 ) -> Option<DisplayRow> {
12198 self.highlighted_rows
12199 .values()
12200 .flat_map(|highlighted_rows| highlighted_rows.iter())
12201 .filter_map(|highlight| {
12202 if highlight.should_autoscroll {
12203 Some(highlight.range.start.to_display_point(snapshot).row())
12204 } else {
12205 None
12206 }
12207 })
12208 .min()
12209 }
12210
12211 pub fn set_search_within_ranges(
12212 &mut self,
12213 ranges: &[Range<Anchor>],
12214 cx: &mut ViewContext<Self>,
12215 ) {
12216 self.highlight_background::<SearchWithinRange>(
12217 ranges,
12218 |colors| colors.editor_document_highlight_read_background,
12219 cx,
12220 )
12221 }
12222
12223 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12224 self.breadcrumb_header = Some(new_header);
12225 }
12226
12227 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12228 self.clear_background_highlights::<SearchWithinRange>(cx);
12229 }
12230
12231 pub fn highlight_background<T: 'static>(
12232 &mut self,
12233 ranges: &[Range<Anchor>],
12234 color_fetcher: fn(&ThemeColors) -> Hsla,
12235 cx: &mut ViewContext<Self>,
12236 ) {
12237 self.background_highlights
12238 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12239 self.scrollbar_marker_state.dirty = true;
12240 cx.notify();
12241 }
12242
12243 pub fn clear_background_highlights<T: 'static>(
12244 &mut self,
12245 cx: &mut ViewContext<Self>,
12246 ) -> Option<BackgroundHighlight> {
12247 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12248 if !text_highlights.1.is_empty() {
12249 self.scrollbar_marker_state.dirty = true;
12250 cx.notify();
12251 }
12252 Some(text_highlights)
12253 }
12254
12255 pub fn highlight_gutter<T: 'static>(
12256 &mut self,
12257 ranges: &[Range<Anchor>],
12258 color_fetcher: fn(&AppContext) -> Hsla,
12259 cx: &mut ViewContext<Self>,
12260 ) {
12261 self.gutter_highlights
12262 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12263 cx.notify();
12264 }
12265
12266 pub fn clear_gutter_highlights<T: 'static>(
12267 &mut self,
12268 cx: &mut ViewContext<Self>,
12269 ) -> Option<GutterHighlight> {
12270 cx.notify();
12271 self.gutter_highlights.remove(&TypeId::of::<T>())
12272 }
12273
12274 #[cfg(feature = "test-support")]
12275 pub fn all_text_background_highlights(
12276 &mut self,
12277 cx: &mut ViewContext<Self>,
12278 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12279 let snapshot = self.snapshot(cx);
12280 let buffer = &snapshot.buffer_snapshot;
12281 let start = buffer.anchor_before(0);
12282 let end = buffer.anchor_after(buffer.len());
12283 let theme = cx.theme().colors();
12284 self.background_highlights_in_range(start..end, &snapshot, theme)
12285 }
12286
12287 #[cfg(feature = "test-support")]
12288 pub fn search_background_highlights(
12289 &mut self,
12290 cx: &mut ViewContext<Self>,
12291 ) -> Vec<Range<Point>> {
12292 let snapshot = self.buffer().read(cx).snapshot(cx);
12293
12294 let highlights = self
12295 .background_highlights
12296 .get(&TypeId::of::<items::BufferSearchHighlights>());
12297
12298 if let Some((_color, ranges)) = highlights {
12299 ranges
12300 .iter()
12301 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12302 .collect_vec()
12303 } else {
12304 vec![]
12305 }
12306 }
12307
12308 fn document_highlights_for_position<'a>(
12309 &'a self,
12310 position: Anchor,
12311 buffer: &'a MultiBufferSnapshot,
12312 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12313 let read_highlights = self
12314 .background_highlights
12315 .get(&TypeId::of::<DocumentHighlightRead>())
12316 .map(|h| &h.1);
12317 let write_highlights = self
12318 .background_highlights
12319 .get(&TypeId::of::<DocumentHighlightWrite>())
12320 .map(|h| &h.1);
12321 let left_position = position.bias_left(buffer);
12322 let right_position = position.bias_right(buffer);
12323 read_highlights
12324 .into_iter()
12325 .chain(write_highlights)
12326 .flat_map(move |ranges| {
12327 let start_ix = match ranges.binary_search_by(|probe| {
12328 let cmp = probe.end.cmp(&left_position, buffer);
12329 if cmp.is_ge() {
12330 Ordering::Greater
12331 } else {
12332 Ordering::Less
12333 }
12334 }) {
12335 Ok(i) | Err(i) => i,
12336 };
12337
12338 ranges[start_ix..]
12339 .iter()
12340 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12341 })
12342 }
12343
12344 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12345 self.background_highlights
12346 .get(&TypeId::of::<T>())
12347 .map_or(false, |(_, highlights)| !highlights.is_empty())
12348 }
12349
12350 pub fn background_highlights_in_range(
12351 &self,
12352 search_range: Range<Anchor>,
12353 display_snapshot: &DisplaySnapshot,
12354 theme: &ThemeColors,
12355 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12356 let mut results = Vec::new();
12357 for (color_fetcher, ranges) in self.background_highlights.values() {
12358 let color = color_fetcher(theme);
12359 let start_ix = match ranges.binary_search_by(|probe| {
12360 let cmp = probe
12361 .end
12362 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12363 if cmp.is_gt() {
12364 Ordering::Greater
12365 } else {
12366 Ordering::Less
12367 }
12368 }) {
12369 Ok(i) | Err(i) => i,
12370 };
12371 for range in &ranges[start_ix..] {
12372 if range
12373 .start
12374 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12375 .is_ge()
12376 {
12377 break;
12378 }
12379
12380 let start = range.start.to_display_point(display_snapshot);
12381 let end = range.end.to_display_point(display_snapshot);
12382 results.push((start..end, color))
12383 }
12384 }
12385 results
12386 }
12387
12388 pub fn background_highlight_row_ranges<T: 'static>(
12389 &self,
12390 search_range: Range<Anchor>,
12391 display_snapshot: &DisplaySnapshot,
12392 count: usize,
12393 ) -> Vec<RangeInclusive<DisplayPoint>> {
12394 let mut results = Vec::new();
12395 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12396 return vec![];
12397 };
12398
12399 let start_ix = match ranges.binary_search_by(|probe| {
12400 let cmp = probe
12401 .end
12402 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12403 if cmp.is_gt() {
12404 Ordering::Greater
12405 } else {
12406 Ordering::Less
12407 }
12408 }) {
12409 Ok(i) | Err(i) => i,
12410 };
12411 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12412 if let (Some(start_display), Some(end_display)) = (start, end) {
12413 results.push(
12414 start_display.to_display_point(display_snapshot)
12415 ..=end_display.to_display_point(display_snapshot),
12416 );
12417 }
12418 };
12419 let mut start_row: Option<Point> = None;
12420 let mut end_row: Option<Point> = None;
12421 if ranges.len() > count {
12422 return Vec::new();
12423 }
12424 for range in &ranges[start_ix..] {
12425 if range
12426 .start
12427 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12428 .is_ge()
12429 {
12430 break;
12431 }
12432 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12433 if let Some(current_row) = &end_row {
12434 if end.row == current_row.row {
12435 continue;
12436 }
12437 }
12438 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12439 if start_row.is_none() {
12440 assert_eq!(end_row, None);
12441 start_row = Some(start);
12442 end_row = Some(end);
12443 continue;
12444 }
12445 if let Some(current_end) = end_row.as_mut() {
12446 if start.row > current_end.row + 1 {
12447 push_region(start_row, end_row);
12448 start_row = Some(start);
12449 end_row = Some(end);
12450 } else {
12451 // Merge two hunks.
12452 *current_end = end;
12453 }
12454 } else {
12455 unreachable!();
12456 }
12457 }
12458 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12459 push_region(start_row, end_row);
12460 results
12461 }
12462
12463 pub fn gutter_highlights_in_range(
12464 &self,
12465 search_range: Range<Anchor>,
12466 display_snapshot: &DisplaySnapshot,
12467 cx: &AppContext,
12468 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12469 let mut results = Vec::new();
12470 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12471 let color = color_fetcher(cx);
12472 let start_ix = match ranges.binary_search_by(|probe| {
12473 let cmp = probe
12474 .end
12475 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12476 if cmp.is_gt() {
12477 Ordering::Greater
12478 } else {
12479 Ordering::Less
12480 }
12481 }) {
12482 Ok(i) | Err(i) => i,
12483 };
12484 for range in &ranges[start_ix..] {
12485 if range
12486 .start
12487 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12488 .is_ge()
12489 {
12490 break;
12491 }
12492
12493 let start = range.start.to_display_point(display_snapshot);
12494 let end = range.end.to_display_point(display_snapshot);
12495 results.push((start..end, color))
12496 }
12497 }
12498 results
12499 }
12500
12501 /// Get the text ranges corresponding to the redaction query
12502 pub fn redacted_ranges(
12503 &self,
12504 search_range: Range<Anchor>,
12505 display_snapshot: &DisplaySnapshot,
12506 cx: &WindowContext,
12507 ) -> Vec<Range<DisplayPoint>> {
12508 display_snapshot
12509 .buffer_snapshot
12510 .redacted_ranges(search_range, |file| {
12511 if let Some(file) = file {
12512 file.is_private()
12513 && EditorSettings::get(
12514 Some(SettingsLocation {
12515 worktree_id: file.worktree_id(cx),
12516 path: file.path().as_ref(),
12517 }),
12518 cx,
12519 )
12520 .redact_private_values
12521 } else {
12522 false
12523 }
12524 })
12525 .map(|range| {
12526 range.start.to_display_point(display_snapshot)
12527 ..range.end.to_display_point(display_snapshot)
12528 })
12529 .collect()
12530 }
12531
12532 pub fn highlight_text<T: 'static>(
12533 &mut self,
12534 ranges: Vec<Range<Anchor>>,
12535 style: HighlightStyle,
12536 cx: &mut ViewContext<Self>,
12537 ) {
12538 self.display_map.update(cx, |map, _| {
12539 map.highlight_text(TypeId::of::<T>(), ranges, style)
12540 });
12541 cx.notify();
12542 }
12543
12544 pub(crate) fn highlight_inlays<T: 'static>(
12545 &mut self,
12546 highlights: Vec<InlayHighlight>,
12547 style: HighlightStyle,
12548 cx: &mut ViewContext<Self>,
12549 ) {
12550 self.display_map.update(cx, |map, _| {
12551 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12552 });
12553 cx.notify();
12554 }
12555
12556 pub fn text_highlights<'a, T: 'static>(
12557 &'a self,
12558 cx: &'a AppContext,
12559 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12560 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12561 }
12562
12563 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12564 let cleared = self
12565 .display_map
12566 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12567 if cleared {
12568 cx.notify();
12569 }
12570 }
12571
12572 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12573 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12574 && self.focus_handle.is_focused(cx)
12575 }
12576
12577 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12578 self.show_cursor_when_unfocused = is_enabled;
12579 cx.notify();
12580 }
12581
12582 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12583 cx.notify();
12584 }
12585
12586 fn on_buffer_event(
12587 &mut self,
12588 multibuffer: Model<MultiBuffer>,
12589 event: &multi_buffer::Event,
12590 cx: &mut ViewContext<Self>,
12591 ) {
12592 match event {
12593 multi_buffer::Event::Edited {
12594 singleton_buffer_edited,
12595 } => {
12596 self.scrollbar_marker_state.dirty = true;
12597 self.active_indent_guides_state.dirty = true;
12598 self.refresh_active_diagnostics(cx);
12599 self.refresh_code_actions(cx);
12600 if self.has_active_inline_completion(cx) {
12601 self.update_visible_inline_completion(cx);
12602 }
12603 cx.emit(EditorEvent::BufferEdited);
12604 cx.emit(SearchEvent::MatchesInvalidated);
12605 if *singleton_buffer_edited {
12606 if let Some(project) = &self.project {
12607 let project = project.read(cx);
12608 #[allow(clippy::mutable_key_type)]
12609 let languages_affected = multibuffer
12610 .read(cx)
12611 .all_buffers()
12612 .into_iter()
12613 .filter_map(|buffer| {
12614 let buffer = buffer.read(cx);
12615 let language = buffer.language()?;
12616 if project.is_local()
12617 && project.language_servers_for_buffer(buffer, cx).count() == 0
12618 {
12619 None
12620 } else {
12621 Some(language)
12622 }
12623 })
12624 .cloned()
12625 .collect::<HashSet<_>>();
12626 if !languages_affected.is_empty() {
12627 self.refresh_inlay_hints(
12628 InlayHintRefreshReason::BufferEdited(languages_affected),
12629 cx,
12630 );
12631 }
12632 }
12633 }
12634
12635 let Some(project) = &self.project else { return };
12636 let (telemetry, is_via_ssh) = {
12637 let project = project.read(cx);
12638 let telemetry = project.client().telemetry().clone();
12639 let is_via_ssh = project.is_via_ssh();
12640 (telemetry, is_via_ssh)
12641 };
12642 refresh_linked_ranges(self, cx);
12643 telemetry.log_edit_event("editor", is_via_ssh);
12644 }
12645 multi_buffer::Event::ExcerptsAdded {
12646 buffer,
12647 predecessor,
12648 excerpts,
12649 } => {
12650 self.tasks_update_task = Some(self.refresh_runnables(cx));
12651 cx.emit(EditorEvent::ExcerptsAdded {
12652 buffer: buffer.clone(),
12653 predecessor: *predecessor,
12654 excerpts: excerpts.clone(),
12655 });
12656 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12657 }
12658 multi_buffer::Event::ExcerptsRemoved { ids } => {
12659 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12660 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12661 }
12662 multi_buffer::Event::ExcerptsEdited { ids } => {
12663 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12664 }
12665 multi_buffer::Event::ExcerptsExpanded { ids } => {
12666 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12667 }
12668 multi_buffer::Event::Reparsed(buffer_id) => {
12669 self.tasks_update_task = Some(self.refresh_runnables(cx));
12670
12671 cx.emit(EditorEvent::Reparsed(*buffer_id));
12672 }
12673 multi_buffer::Event::LanguageChanged(buffer_id) => {
12674 linked_editing_ranges::refresh_linked_ranges(self, cx);
12675 cx.emit(EditorEvent::Reparsed(*buffer_id));
12676 cx.notify();
12677 }
12678 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12679 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12680 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12681 cx.emit(EditorEvent::TitleChanged)
12682 }
12683 multi_buffer::Event::DiffBaseChanged => {
12684 self.scrollbar_marker_state.dirty = true;
12685 cx.emit(EditorEvent::DiffBaseChanged);
12686 cx.notify();
12687 }
12688 multi_buffer::Event::DiffUpdated { buffer } => {
12689 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12690 cx.notify();
12691 }
12692 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12693 multi_buffer::Event::DiagnosticsUpdated => {
12694 self.refresh_active_diagnostics(cx);
12695 self.scrollbar_marker_state.dirty = true;
12696 cx.notify();
12697 }
12698 _ => {}
12699 };
12700 }
12701
12702 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12703 cx.notify();
12704 }
12705
12706 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12707 self.tasks_update_task = Some(self.refresh_runnables(cx));
12708 self.refresh_inline_completion(true, false, cx);
12709 self.refresh_inlay_hints(
12710 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12711 self.selections.newest_anchor().head(),
12712 &self.buffer.read(cx).snapshot(cx),
12713 cx,
12714 )),
12715 cx,
12716 );
12717
12718 let old_cursor_shape = self.cursor_shape;
12719
12720 {
12721 let editor_settings = EditorSettings::get_global(cx);
12722 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12723 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12724 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12725 }
12726
12727 if old_cursor_shape != self.cursor_shape {
12728 cx.emit(EditorEvent::CursorShapeChanged);
12729 }
12730
12731 let project_settings = ProjectSettings::get_global(cx);
12732 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12733
12734 if self.mode == EditorMode::Full {
12735 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12736 if self.git_blame_inline_enabled != inline_blame_enabled {
12737 self.toggle_git_blame_inline_internal(false, cx);
12738 }
12739 }
12740
12741 cx.notify();
12742 }
12743
12744 pub fn set_searchable(&mut self, searchable: bool) {
12745 self.searchable = searchable;
12746 }
12747
12748 pub fn searchable(&self) -> bool {
12749 self.searchable
12750 }
12751
12752 fn open_proposed_changes_editor(
12753 &mut self,
12754 _: &OpenProposedChangesEditor,
12755 cx: &mut ViewContext<Self>,
12756 ) {
12757 let Some(workspace) = self.workspace() else {
12758 cx.propagate();
12759 return;
12760 };
12761
12762 let selections = self.selections.all::<usize>(cx);
12763 let buffer = self.buffer.read(cx);
12764 let mut new_selections_by_buffer = HashMap::default();
12765 for selection in selections {
12766 for (buffer, range, _) in
12767 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12768 {
12769 let mut range = range.to_point(buffer.read(cx));
12770 range.start.column = 0;
12771 range.end.column = buffer.read(cx).line_len(range.end.row);
12772 new_selections_by_buffer
12773 .entry(buffer)
12774 .or_insert(Vec::new())
12775 .push(range)
12776 }
12777 }
12778
12779 let proposed_changes_buffers = new_selections_by_buffer
12780 .into_iter()
12781 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12782 .collect::<Vec<_>>();
12783 let proposed_changes_editor = cx.new_view(|cx| {
12784 ProposedChangesEditor::new(
12785 "Proposed changes",
12786 proposed_changes_buffers,
12787 self.project.clone(),
12788 cx,
12789 )
12790 });
12791
12792 cx.window_context().defer(move |cx| {
12793 workspace.update(cx, |workspace, cx| {
12794 workspace.active_pane().update(cx, |pane, cx| {
12795 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12796 });
12797 });
12798 });
12799 }
12800
12801 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12802 self.open_excerpts_common(None, true, cx)
12803 }
12804
12805 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12806 self.open_excerpts_common(None, false, cx)
12807 }
12808
12809 fn open_excerpts_common(
12810 &mut self,
12811 jump_data: Option<JumpData>,
12812 split: bool,
12813 cx: &mut ViewContext<Self>,
12814 ) {
12815 let Some(workspace) = self.workspace() else {
12816 cx.propagate();
12817 return;
12818 };
12819
12820 if self.buffer.read(cx).is_singleton() {
12821 cx.propagate();
12822 return;
12823 }
12824
12825 let mut new_selections_by_buffer = HashMap::default();
12826 match &jump_data {
12827 Some(jump_data) => {
12828 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12829 if let Some(buffer) = multi_buffer_snapshot
12830 .buffer_id_for_excerpt(jump_data.excerpt_id)
12831 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12832 {
12833 let buffer_snapshot = buffer.read(cx).snapshot();
12834 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12835 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12836 } else {
12837 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12838 };
12839 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12840 new_selections_by_buffer.insert(
12841 buffer,
12842 (
12843 vec![jump_to_offset..jump_to_offset],
12844 Some(jump_data.line_offset_from_top),
12845 ),
12846 );
12847 }
12848 }
12849 None => {
12850 let selections = self.selections.all::<usize>(cx);
12851 let buffer = self.buffer.read(cx);
12852 for selection in selections {
12853 for (mut buffer_handle, mut range, _) in
12854 buffer.range_to_buffer_ranges(selection.range(), cx)
12855 {
12856 // When editing branch buffers, jump to the corresponding location
12857 // in their base buffer.
12858 let buffer = buffer_handle.read(cx);
12859 if let Some(base_buffer) = buffer.diff_base_buffer() {
12860 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12861 buffer_handle = base_buffer;
12862 }
12863
12864 if selection.reversed {
12865 mem::swap(&mut range.start, &mut range.end);
12866 }
12867 new_selections_by_buffer
12868 .entry(buffer_handle)
12869 .or_insert((Vec::new(), None))
12870 .0
12871 .push(range)
12872 }
12873 }
12874 }
12875 }
12876
12877 if new_selections_by_buffer.is_empty() {
12878 return;
12879 }
12880
12881 // We defer the pane interaction because we ourselves are a workspace item
12882 // and activating a new item causes the pane to call a method on us reentrantly,
12883 // which panics if we're on the stack.
12884 cx.window_context().defer(move |cx| {
12885 workspace.update(cx, |workspace, cx| {
12886 let pane = if split {
12887 workspace.adjacent_pane(cx)
12888 } else {
12889 workspace.active_pane().clone()
12890 };
12891
12892 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12893 let editor =
12894 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12895 editor.update(cx, |editor, cx| {
12896 let autoscroll = match scroll_offset {
12897 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12898 None => Autoscroll::newest(),
12899 };
12900 let nav_history = editor.nav_history.take();
12901 editor.change_selections(Some(autoscroll), cx, |s| {
12902 s.select_ranges(ranges);
12903 });
12904 editor.nav_history = nav_history;
12905 });
12906 }
12907 })
12908 });
12909 }
12910
12911 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12912 let snapshot = self.buffer.read(cx).read(cx);
12913 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12914 Some(
12915 ranges
12916 .iter()
12917 .map(move |range| {
12918 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12919 })
12920 .collect(),
12921 )
12922 }
12923
12924 fn selection_replacement_ranges(
12925 &self,
12926 range: Range<OffsetUtf16>,
12927 cx: &mut AppContext,
12928 ) -> Vec<Range<OffsetUtf16>> {
12929 let selections = self.selections.all::<OffsetUtf16>(cx);
12930 let newest_selection = selections
12931 .iter()
12932 .max_by_key(|selection| selection.id)
12933 .unwrap();
12934 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12935 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12936 let snapshot = self.buffer.read(cx).read(cx);
12937 selections
12938 .into_iter()
12939 .map(|mut selection| {
12940 selection.start.0 =
12941 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12942 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12943 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12944 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12945 })
12946 .collect()
12947 }
12948
12949 fn report_editor_event(
12950 &self,
12951 operation: &'static str,
12952 file_extension: Option<String>,
12953 cx: &AppContext,
12954 ) {
12955 if cfg!(any(test, feature = "test-support")) {
12956 return;
12957 }
12958
12959 let Some(project) = &self.project else { return };
12960
12961 // If None, we are in a file without an extension
12962 let file = self
12963 .buffer
12964 .read(cx)
12965 .as_singleton()
12966 .and_then(|b| b.read(cx).file());
12967 let file_extension = file_extension.or(file
12968 .as_ref()
12969 .and_then(|file| Path::new(file.file_name(cx)).extension())
12970 .and_then(|e| e.to_str())
12971 .map(|a| a.to_string()));
12972
12973 let vim_mode = cx
12974 .global::<SettingsStore>()
12975 .raw_user_settings()
12976 .get("vim_mode")
12977 == Some(&serde_json::Value::Bool(true));
12978
12979 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12980 == language::language_settings::InlineCompletionProvider::Copilot;
12981 let copilot_enabled_for_language = self
12982 .buffer
12983 .read(cx)
12984 .settings_at(0, cx)
12985 .show_inline_completions;
12986
12987 let project = project.read(cx);
12988 let telemetry = project.client().telemetry().clone();
12989 telemetry.report_editor_event(
12990 file_extension,
12991 vim_mode,
12992 operation,
12993 copilot_enabled,
12994 copilot_enabled_for_language,
12995 project.is_via_ssh(),
12996 )
12997 }
12998
12999 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13000 /// with each line being an array of {text, highlight} objects.
13001 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13002 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13003 return;
13004 };
13005
13006 #[derive(Serialize)]
13007 struct Chunk<'a> {
13008 text: String,
13009 highlight: Option<&'a str>,
13010 }
13011
13012 let snapshot = buffer.read(cx).snapshot();
13013 let range = self
13014 .selected_text_range(false, cx)
13015 .and_then(|selection| {
13016 if selection.range.is_empty() {
13017 None
13018 } else {
13019 Some(selection.range)
13020 }
13021 })
13022 .unwrap_or_else(|| 0..snapshot.len());
13023
13024 let chunks = snapshot.chunks(range, true);
13025 let mut lines = Vec::new();
13026 let mut line: VecDeque<Chunk> = VecDeque::new();
13027
13028 let Some(style) = self.style.as_ref() else {
13029 return;
13030 };
13031
13032 for chunk in chunks {
13033 let highlight = chunk
13034 .syntax_highlight_id
13035 .and_then(|id| id.name(&style.syntax));
13036 let mut chunk_lines = chunk.text.split('\n').peekable();
13037 while let Some(text) = chunk_lines.next() {
13038 let mut merged_with_last_token = false;
13039 if let Some(last_token) = line.back_mut() {
13040 if last_token.highlight == highlight {
13041 last_token.text.push_str(text);
13042 merged_with_last_token = true;
13043 }
13044 }
13045
13046 if !merged_with_last_token {
13047 line.push_back(Chunk {
13048 text: text.into(),
13049 highlight,
13050 });
13051 }
13052
13053 if chunk_lines.peek().is_some() {
13054 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13055 line.pop_front();
13056 }
13057 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13058 line.pop_back();
13059 }
13060
13061 lines.push(mem::take(&mut line));
13062 }
13063 }
13064 }
13065
13066 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13067 return;
13068 };
13069 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13070 }
13071
13072 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13073 &self.inlay_hint_cache
13074 }
13075
13076 pub fn replay_insert_event(
13077 &mut self,
13078 text: &str,
13079 relative_utf16_range: Option<Range<isize>>,
13080 cx: &mut ViewContext<Self>,
13081 ) {
13082 if !self.input_enabled {
13083 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13084 return;
13085 }
13086 if let Some(relative_utf16_range) = relative_utf16_range {
13087 let selections = self.selections.all::<OffsetUtf16>(cx);
13088 self.change_selections(None, cx, |s| {
13089 let new_ranges = selections.into_iter().map(|range| {
13090 let start = OffsetUtf16(
13091 range
13092 .head()
13093 .0
13094 .saturating_add_signed(relative_utf16_range.start),
13095 );
13096 let end = OffsetUtf16(
13097 range
13098 .head()
13099 .0
13100 .saturating_add_signed(relative_utf16_range.end),
13101 );
13102 start..end
13103 });
13104 s.select_ranges(new_ranges);
13105 });
13106 }
13107
13108 self.handle_input(text, cx);
13109 }
13110
13111 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13112 let Some(provider) = self.semantics_provider.as_ref() else {
13113 return false;
13114 };
13115
13116 let mut supports = false;
13117 self.buffer().read(cx).for_each_buffer(|buffer| {
13118 supports |= provider.supports_inlay_hints(buffer, cx);
13119 });
13120 supports
13121 }
13122
13123 pub fn focus(&self, cx: &mut WindowContext) {
13124 cx.focus(&self.focus_handle)
13125 }
13126
13127 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13128 self.focus_handle.is_focused(cx)
13129 }
13130
13131 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13132 cx.emit(EditorEvent::Focused);
13133
13134 if let Some(descendant) = self
13135 .last_focused_descendant
13136 .take()
13137 .and_then(|descendant| descendant.upgrade())
13138 {
13139 cx.focus(&descendant);
13140 } else {
13141 if let Some(blame) = self.blame.as_ref() {
13142 blame.update(cx, GitBlame::focus)
13143 }
13144
13145 self.blink_manager.update(cx, BlinkManager::enable);
13146 self.show_cursor_names(cx);
13147 self.buffer.update(cx, |buffer, cx| {
13148 buffer.finalize_last_transaction(cx);
13149 if self.leader_peer_id.is_none() {
13150 buffer.set_active_selections(
13151 &self.selections.disjoint_anchors(),
13152 self.selections.line_mode,
13153 self.cursor_shape,
13154 cx,
13155 );
13156 }
13157 });
13158 }
13159 }
13160
13161 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13162 cx.emit(EditorEvent::FocusedIn)
13163 }
13164
13165 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13166 if event.blurred != self.focus_handle {
13167 self.last_focused_descendant = Some(event.blurred);
13168 }
13169 }
13170
13171 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13172 self.blink_manager.update(cx, BlinkManager::disable);
13173 self.buffer
13174 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13175
13176 if let Some(blame) = self.blame.as_ref() {
13177 blame.update(cx, GitBlame::blur)
13178 }
13179 if !self.hover_state.focused(cx) {
13180 hide_hover(self, cx);
13181 }
13182
13183 self.hide_context_menu(cx);
13184 cx.emit(EditorEvent::Blurred);
13185 cx.notify();
13186 }
13187
13188 pub fn register_action<A: Action>(
13189 &mut self,
13190 listener: impl Fn(&A, &mut WindowContext) + 'static,
13191 ) -> Subscription {
13192 let id = self.next_editor_action_id.post_inc();
13193 let listener = Arc::new(listener);
13194 self.editor_actions.borrow_mut().insert(
13195 id,
13196 Box::new(move |cx| {
13197 let cx = cx.window_context();
13198 let listener = listener.clone();
13199 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13200 let action = action.downcast_ref().unwrap();
13201 if phase == DispatchPhase::Bubble {
13202 listener(action, cx)
13203 }
13204 })
13205 }),
13206 );
13207
13208 let editor_actions = self.editor_actions.clone();
13209 Subscription::new(move || {
13210 editor_actions.borrow_mut().remove(&id);
13211 })
13212 }
13213
13214 pub fn file_header_size(&self) -> u32 {
13215 FILE_HEADER_HEIGHT
13216 }
13217
13218 pub fn revert(
13219 &mut self,
13220 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13221 cx: &mut ViewContext<Self>,
13222 ) {
13223 self.buffer().update(cx, |multi_buffer, cx| {
13224 for (buffer_id, changes) in revert_changes {
13225 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13226 buffer.update(cx, |buffer, cx| {
13227 buffer.edit(
13228 changes.into_iter().map(|(range, text)| {
13229 (range, text.to_string().map(Arc::<str>::from))
13230 }),
13231 None,
13232 cx,
13233 );
13234 });
13235 }
13236 }
13237 });
13238 self.change_selections(None, cx, |selections| selections.refresh());
13239 }
13240
13241 pub fn to_pixel_point(
13242 &mut self,
13243 source: multi_buffer::Anchor,
13244 editor_snapshot: &EditorSnapshot,
13245 cx: &mut ViewContext<Self>,
13246 ) -> Option<gpui::Point<Pixels>> {
13247 let source_point = source.to_display_point(editor_snapshot);
13248 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13249 }
13250
13251 pub fn display_to_pixel_point(
13252 &mut self,
13253 source: DisplayPoint,
13254 editor_snapshot: &EditorSnapshot,
13255 cx: &mut ViewContext<Self>,
13256 ) -> Option<gpui::Point<Pixels>> {
13257 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13258 let text_layout_details = self.text_layout_details(cx);
13259 let scroll_top = text_layout_details
13260 .scroll_anchor
13261 .scroll_position(editor_snapshot)
13262 .y;
13263
13264 if source.row().as_f32() < scroll_top.floor() {
13265 return None;
13266 }
13267 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13268 let source_y = line_height * (source.row().as_f32() - scroll_top);
13269 Some(gpui::Point::new(source_x, source_y))
13270 }
13271
13272 pub fn has_active_completions_menu(&self) -> bool {
13273 self.context_menu.read().as_ref().map_or(false, |menu| {
13274 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13275 })
13276 }
13277
13278 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13279 self.addons
13280 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13281 }
13282
13283 pub fn unregister_addon<T: Addon>(&mut self) {
13284 self.addons.remove(&std::any::TypeId::of::<T>());
13285 }
13286
13287 pub fn addon<T: Addon>(&self) -> Option<&T> {
13288 let type_id = std::any::TypeId::of::<T>();
13289 self.addons
13290 .get(&type_id)
13291 .and_then(|item| item.to_any().downcast_ref::<T>())
13292 }
13293}
13294
13295fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13296 let tab_size = tab_size.get() as usize;
13297 let mut width = offset;
13298
13299 for ch in text.chars() {
13300 width += if ch == '\t' {
13301 tab_size - (width % tab_size)
13302 } else {
13303 1
13304 };
13305 }
13306
13307 width - offset
13308}
13309
13310#[cfg(test)]
13311mod tests {
13312 use super::*;
13313
13314 #[test]
13315 fn test_string_size_with_expanded_tabs() {
13316 let nz = |val| NonZeroU32::new(val).unwrap();
13317 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13318 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13319 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13320 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13321 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13322 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13323 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13324 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13325 }
13326}
13327
13328/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13329struct WordBreakingTokenizer<'a> {
13330 input: &'a str,
13331}
13332
13333impl<'a> WordBreakingTokenizer<'a> {
13334 fn new(input: &'a str) -> Self {
13335 Self { input }
13336 }
13337}
13338
13339fn is_char_ideographic(ch: char) -> bool {
13340 use unicode_script::Script::*;
13341 use unicode_script::UnicodeScript;
13342 matches!(ch.script(), Han | Tangut | Yi)
13343}
13344
13345fn is_grapheme_ideographic(text: &str) -> bool {
13346 text.chars().any(is_char_ideographic)
13347}
13348
13349fn is_grapheme_whitespace(text: &str) -> bool {
13350 text.chars().any(|x| x.is_whitespace())
13351}
13352
13353fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13354 text.chars().next().map_or(false, |ch| {
13355 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13356 })
13357}
13358
13359#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13360struct WordBreakToken<'a> {
13361 token: &'a str,
13362 grapheme_len: usize,
13363 is_whitespace: bool,
13364}
13365
13366impl<'a> Iterator for WordBreakingTokenizer<'a> {
13367 /// Yields a span, the count of graphemes in the token, and whether it was
13368 /// whitespace. Note that it also breaks at word boundaries.
13369 type Item = WordBreakToken<'a>;
13370
13371 fn next(&mut self) -> Option<Self::Item> {
13372 use unicode_segmentation::UnicodeSegmentation;
13373 if self.input.is_empty() {
13374 return None;
13375 }
13376
13377 let mut iter = self.input.graphemes(true).peekable();
13378 let mut offset = 0;
13379 let mut graphemes = 0;
13380 if let Some(first_grapheme) = iter.next() {
13381 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13382 offset += first_grapheme.len();
13383 graphemes += 1;
13384 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13385 if let Some(grapheme) = iter.peek().copied() {
13386 if should_stay_with_preceding_ideograph(grapheme) {
13387 offset += grapheme.len();
13388 graphemes += 1;
13389 }
13390 }
13391 } else {
13392 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13393 let mut next_word_bound = words.peek().copied();
13394 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13395 next_word_bound = words.next();
13396 }
13397 while let Some(grapheme) = iter.peek().copied() {
13398 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13399 break;
13400 };
13401 if is_grapheme_whitespace(grapheme) != is_whitespace {
13402 break;
13403 };
13404 offset += grapheme.len();
13405 graphemes += 1;
13406 iter.next();
13407 }
13408 }
13409 let token = &self.input[..offset];
13410 self.input = &self.input[offset..];
13411 if is_whitespace {
13412 Some(WordBreakToken {
13413 token: " ",
13414 grapheme_len: 1,
13415 is_whitespace: true,
13416 })
13417 } else {
13418 Some(WordBreakToken {
13419 token,
13420 grapheme_len: graphemes,
13421 is_whitespace: false,
13422 })
13423 }
13424 } else {
13425 None
13426 }
13427 }
13428}
13429
13430#[test]
13431fn test_word_breaking_tokenizer() {
13432 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13433 ("", &[]),
13434 (" ", &[(" ", 1, true)]),
13435 ("Ʒ", &[("Ʒ", 1, false)]),
13436 ("Ǽ", &[("Ǽ", 1, false)]),
13437 ("⋑", &[("⋑", 1, false)]),
13438 ("⋑⋑", &[("⋑⋑", 2, false)]),
13439 (
13440 "原理,进而",
13441 &[
13442 ("原", 1, false),
13443 ("理,", 2, false),
13444 ("进", 1, false),
13445 ("而", 1, false),
13446 ],
13447 ),
13448 (
13449 "hello world",
13450 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13451 ),
13452 (
13453 "hello, world",
13454 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13455 ),
13456 (
13457 " hello world",
13458 &[
13459 (" ", 1, true),
13460 ("hello", 5, false),
13461 (" ", 1, true),
13462 ("world", 5, false),
13463 ],
13464 ),
13465 (
13466 "这是什么 \n 钢笔",
13467 &[
13468 ("这", 1, false),
13469 ("是", 1, false),
13470 ("什", 1, false),
13471 ("么", 1, false),
13472 (" ", 1, true),
13473 ("钢", 1, false),
13474 ("笔", 1, false),
13475 ],
13476 ),
13477 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13478 ];
13479
13480 for (input, result) in tests {
13481 assert_eq!(
13482 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13483 result
13484 .iter()
13485 .copied()
13486 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13487 token,
13488 grapheme_len,
13489 is_whitespace,
13490 })
13491 .collect::<Vec<_>>()
13492 );
13493 }
13494}
13495
13496fn wrap_with_prefix(
13497 line_prefix: String,
13498 unwrapped_text: String,
13499 wrap_column: usize,
13500 tab_size: NonZeroU32,
13501) -> String {
13502 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13503 let mut wrapped_text = String::new();
13504 let mut current_line = line_prefix.clone();
13505
13506 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13507 let mut current_line_len = line_prefix_len;
13508 for WordBreakToken {
13509 token,
13510 grapheme_len,
13511 is_whitespace,
13512 } in tokenizer
13513 {
13514 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13515 wrapped_text.push_str(current_line.trim_end());
13516 wrapped_text.push('\n');
13517 current_line.truncate(line_prefix.len());
13518 current_line_len = line_prefix_len;
13519 if !is_whitespace {
13520 current_line.push_str(token);
13521 current_line_len += grapheme_len;
13522 }
13523 } else if !is_whitespace {
13524 current_line.push_str(token);
13525 current_line_len += grapheme_len;
13526 } else if current_line_len != line_prefix_len {
13527 current_line.push(' ');
13528 current_line_len += 1;
13529 }
13530 }
13531
13532 if !current_line.is_empty() {
13533 wrapped_text.push_str(¤t_line);
13534 }
13535 wrapped_text
13536}
13537
13538#[test]
13539fn test_wrap_with_prefix() {
13540 assert_eq!(
13541 wrap_with_prefix(
13542 "# ".to_string(),
13543 "abcdefg".to_string(),
13544 4,
13545 NonZeroU32::new(4).unwrap()
13546 ),
13547 "# abcdefg"
13548 );
13549 assert_eq!(
13550 wrap_with_prefix(
13551 "".to_string(),
13552 "\thello world".to_string(),
13553 8,
13554 NonZeroU32::new(4).unwrap()
13555 ),
13556 "hello\nworld"
13557 );
13558 assert_eq!(
13559 wrap_with_prefix(
13560 "// ".to_string(),
13561 "xx \nyy zz aa bb cc".to_string(),
13562 12,
13563 NonZeroU32::new(4).unwrap()
13564 ),
13565 "// xx yy zz\n// aa bb cc"
13566 );
13567 assert_eq!(
13568 wrap_with_prefix(
13569 String::new(),
13570 "这是什么 \n 钢笔".to_string(),
13571 3,
13572 NonZeroU32::new(4).unwrap()
13573 ),
13574 "这是什\n么 钢\n笔"
13575 );
13576}
13577
13578fn hunks_for_selections(
13579 multi_buffer_snapshot: &MultiBufferSnapshot,
13580 selections: &[Selection<Anchor>],
13581) -> Vec<MultiBufferDiffHunk> {
13582 let buffer_rows_for_selections = selections.iter().map(|selection| {
13583 let head = selection.head();
13584 let tail = selection.tail();
13585 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13586 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13587 if start > end {
13588 end..start
13589 } else {
13590 start..end
13591 }
13592 });
13593
13594 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13595}
13596
13597pub fn hunks_for_rows(
13598 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13599 multi_buffer_snapshot: &MultiBufferSnapshot,
13600) -> Vec<MultiBufferDiffHunk> {
13601 let mut hunks = Vec::new();
13602 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13603 HashMap::default();
13604 for selected_multi_buffer_rows in rows {
13605 let query_rows =
13606 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13607 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13608 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13609 // when the caret is just above or just below the deleted hunk.
13610 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13611 let related_to_selection = if allow_adjacent {
13612 hunk.row_range.overlaps(&query_rows)
13613 || hunk.row_range.start == query_rows.end
13614 || hunk.row_range.end == query_rows.start
13615 } else {
13616 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13617 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13618 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13619 || selected_multi_buffer_rows.end == hunk.row_range.start
13620 };
13621 if related_to_selection {
13622 if !processed_buffer_rows
13623 .entry(hunk.buffer_id)
13624 .or_default()
13625 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13626 {
13627 continue;
13628 }
13629 hunks.push(hunk);
13630 }
13631 }
13632 }
13633
13634 hunks
13635}
13636
13637pub trait CollaborationHub {
13638 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13639 fn user_participant_indices<'a>(
13640 &self,
13641 cx: &'a AppContext,
13642 ) -> &'a HashMap<u64, ParticipantIndex>;
13643 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13644}
13645
13646impl CollaborationHub for Model<Project> {
13647 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13648 self.read(cx).collaborators()
13649 }
13650
13651 fn user_participant_indices<'a>(
13652 &self,
13653 cx: &'a AppContext,
13654 ) -> &'a HashMap<u64, ParticipantIndex> {
13655 self.read(cx).user_store().read(cx).participant_indices()
13656 }
13657
13658 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13659 let this = self.read(cx);
13660 let user_ids = this.collaborators().values().map(|c| c.user_id);
13661 this.user_store().read_with(cx, |user_store, cx| {
13662 user_store.participant_names(user_ids, cx)
13663 })
13664 }
13665}
13666
13667pub trait SemanticsProvider {
13668 fn hover(
13669 &self,
13670 buffer: &Model<Buffer>,
13671 position: text::Anchor,
13672 cx: &mut AppContext,
13673 ) -> Option<Task<Vec<project::Hover>>>;
13674
13675 fn inlay_hints(
13676 &self,
13677 buffer_handle: Model<Buffer>,
13678 range: Range<text::Anchor>,
13679 cx: &mut AppContext,
13680 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13681
13682 fn resolve_inlay_hint(
13683 &self,
13684 hint: InlayHint,
13685 buffer_handle: Model<Buffer>,
13686 server_id: LanguageServerId,
13687 cx: &mut AppContext,
13688 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13689
13690 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13691
13692 fn document_highlights(
13693 &self,
13694 buffer: &Model<Buffer>,
13695 position: text::Anchor,
13696 cx: &mut AppContext,
13697 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13698
13699 fn definitions(
13700 &self,
13701 buffer: &Model<Buffer>,
13702 position: text::Anchor,
13703 kind: GotoDefinitionKind,
13704 cx: &mut AppContext,
13705 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13706
13707 fn range_for_rename(
13708 &self,
13709 buffer: &Model<Buffer>,
13710 position: text::Anchor,
13711 cx: &mut AppContext,
13712 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13713
13714 fn perform_rename(
13715 &self,
13716 buffer: &Model<Buffer>,
13717 position: text::Anchor,
13718 new_name: String,
13719 cx: &mut AppContext,
13720 ) -> Option<Task<Result<ProjectTransaction>>>;
13721}
13722
13723pub trait CompletionProvider {
13724 fn completions(
13725 &self,
13726 buffer: &Model<Buffer>,
13727 buffer_position: text::Anchor,
13728 trigger: CompletionContext,
13729 cx: &mut ViewContext<Editor>,
13730 ) -> Task<Result<Vec<Completion>>>;
13731
13732 fn resolve_completions(
13733 &self,
13734 buffer: Model<Buffer>,
13735 completion_indices: Vec<usize>,
13736 completions: Arc<RwLock<Box<[Completion]>>>,
13737 cx: &mut ViewContext<Editor>,
13738 ) -> Task<Result<bool>>;
13739
13740 fn apply_additional_edits_for_completion(
13741 &self,
13742 buffer: Model<Buffer>,
13743 completion: Completion,
13744 push_to_history: bool,
13745 cx: &mut ViewContext<Editor>,
13746 ) -> Task<Result<Option<language::Transaction>>>;
13747
13748 fn is_completion_trigger(
13749 &self,
13750 buffer: &Model<Buffer>,
13751 position: language::Anchor,
13752 text: &str,
13753 trigger_in_words: bool,
13754 cx: &mut ViewContext<Editor>,
13755 ) -> bool;
13756
13757 fn sort_completions(&self) -> bool {
13758 true
13759 }
13760}
13761
13762pub trait CodeActionProvider {
13763 fn code_actions(
13764 &self,
13765 buffer: &Model<Buffer>,
13766 range: Range<text::Anchor>,
13767 cx: &mut WindowContext,
13768 ) -> Task<Result<Vec<CodeAction>>>;
13769
13770 fn apply_code_action(
13771 &self,
13772 buffer_handle: Model<Buffer>,
13773 action: CodeAction,
13774 excerpt_id: ExcerptId,
13775 push_to_history: bool,
13776 cx: &mut WindowContext,
13777 ) -> Task<Result<ProjectTransaction>>;
13778}
13779
13780impl CodeActionProvider for Model<Project> {
13781 fn code_actions(
13782 &self,
13783 buffer: &Model<Buffer>,
13784 range: Range<text::Anchor>,
13785 cx: &mut WindowContext,
13786 ) -> Task<Result<Vec<CodeAction>>> {
13787 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13788 }
13789
13790 fn apply_code_action(
13791 &self,
13792 buffer_handle: Model<Buffer>,
13793 action: CodeAction,
13794 _excerpt_id: ExcerptId,
13795 push_to_history: bool,
13796 cx: &mut WindowContext,
13797 ) -> Task<Result<ProjectTransaction>> {
13798 self.update(cx, |project, cx| {
13799 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13800 })
13801 }
13802}
13803
13804fn snippet_completions(
13805 project: &Project,
13806 buffer: &Model<Buffer>,
13807 buffer_position: text::Anchor,
13808 cx: &mut AppContext,
13809) -> Vec<Completion> {
13810 let language = buffer.read(cx).language_at(buffer_position);
13811 let language_name = language.as_ref().map(|language| language.lsp_id());
13812 let snippet_store = project.snippets().read(cx);
13813 let snippets = snippet_store.snippets_for(language_name, cx);
13814
13815 if snippets.is_empty() {
13816 return vec![];
13817 }
13818 let snapshot = buffer.read(cx).text_snapshot();
13819 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13820
13821 let scope = language.map(|language| language.default_scope());
13822 let classifier = CharClassifier::new(scope).for_completion(true);
13823 let mut last_word = chars
13824 .take_while(|c| classifier.is_word(*c))
13825 .collect::<String>();
13826 last_word = last_word.chars().rev().collect();
13827 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13828 let to_lsp = |point: &text::Anchor| {
13829 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13830 point_to_lsp(end)
13831 };
13832 let lsp_end = to_lsp(&buffer_position);
13833 snippets
13834 .into_iter()
13835 .filter_map(|snippet| {
13836 let matching_prefix = snippet
13837 .prefix
13838 .iter()
13839 .find(|prefix| prefix.starts_with(&last_word))?;
13840 let start = as_offset - last_word.len();
13841 let start = snapshot.anchor_before(start);
13842 let range = start..buffer_position;
13843 let lsp_start = to_lsp(&start);
13844 let lsp_range = lsp::Range {
13845 start: lsp_start,
13846 end: lsp_end,
13847 };
13848 Some(Completion {
13849 old_range: range,
13850 new_text: snippet.body.clone(),
13851 label: CodeLabel {
13852 text: matching_prefix.clone(),
13853 runs: vec![],
13854 filter_range: 0..matching_prefix.len(),
13855 },
13856 server_id: LanguageServerId(usize::MAX),
13857 documentation: snippet.description.clone().map(Documentation::SingleLine),
13858 lsp_completion: lsp::CompletionItem {
13859 label: snippet.prefix.first().unwrap().clone(),
13860 kind: Some(CompletionItemKind::SNIPPET),
13861 label_details: snippet.description.as_ref().map(|description| {
13862 lsp::CompletionItemLabelDetails {
13863 detail: Some(description.clone()),
13864 description: None,
13865 }
13866 }),
13867 insert_text_format: Some(InsertTextFormat::SNIPPET),
13868 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13869 lsp::InsertReplaceEdit {
13870 new_text: snippet.body.clone(),
13871 insert: lsp_range,
13872 replace: lsp_range,
13873 },
13874 )),
13875 filter_text: Some(snippet.body.clone()),
13876 sort_text: Some(char::MAX.to_string()),
13877 ..Default::default()
13878 },
13879 confirm: None,
13880 })
13881 })
13882 .collect()
13883}
13884
13885impl CompletionProvider for Model<Project> {
13886 fn completions(
13887 &self,
13888 buffer: &Model<Buffer>,
13889 buffer_position: text::Anchor,
13890 options: CompletionContext,
13891 cx: &mut ViewContext<Editor>,
13892 ) -> Task<Result<Vec<Completion>>> {
13893 self.update(cx, |project, cx| {
13894 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13895 let project_completions = project.completions(buffer, buffer_position, options, cx);
13896 cx.background_executor().spawn(async move {
13897 let mut completions = project_completions.await?;
13898 //let snippets = snippets.into_iter().;
13899 completions.extend(snippets);
13900 Ok(completions)
13901 })
13902 })
13903 }
13904
13905 fn resolve_completions(
13906 &self,
13907 buffer: Model<Buffer>,
13908 completion_indices: Vec<usize>,
13909 completions: Arc<RwLock<Box<[Completion]>>>,
13910 cx: &mut ViewContext<Editor>,
13911 ) -> Task<Result<bool>> {
13912 self.update(cx, |project, cx| {
13913 project.resolve_completions(buffer, completion_indices, completions, cx)
13914 })
13915 }
13916
13917 fn apply_additional_edits_for_completion(
13918 &self,
13919 buffer: Model<Buffer>,
13920 completion: Completion,
13921 push_to_history: bool,
13922 cx: &mut ViewContext<Editor>,
13923 ) -> Task<Result<Option<language::Transaction>>> {
13924 self.update(cx, |project, cx| {
13925 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13926 })
13927 }
13928
13929 fn is_completion_trigger(
13930 &self,
13931 buffer: &Model<Buffer>,
13932 position: language::Anchor,
13933 text: &str,
13934 trigger_in_words: bool,
13935 cx: &mut ViewContext<Editor>,
13936 ) -> bool {
13937 if !EditorSettings::get_global(cx).show_completions_on_input {
13938 return false;
13939 }
13940
13941 let mut chars = text.chars();
13942 let char = if let Some(char) = chars.next() {
13943 char
13944 } else {
13945 return false;
13946 };
13947 if chars.next().is_some() {
13948 return false;
13949 }
13950
13951 let buffer = buffer.read(cx);
13952 let classifier = buffer
13953 .snapshot()
13954 .char_classifier_at(position)
13955 .for_completion(true);
13956 if trigger_in_words && classifier.is_word(char) {
13957 return true;
13958 }
13959
13960 buffer.completion_triggers().contains(text)
13961 }
13962}
13963
13964impl SemanticsProvider for Model<Project> {
13965 fn hover(
13966 &self,
13967 buffer: &Model<Buffer>,
13968 position: text::Anchor,
13969 cx: &mut AppContext,
13970 ) -> Option<Task<Vec<project::Hover>>> {
13971 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13972 }
13973
13974 fn document_highlights(
13975 &self,
13976 buffer: &Model<Buffer>,
13977 position: text::Anchor,
13978 cx: &mut AppContext,
13979 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13980 Some(self.update(cx, |project, cx| {
13981 project.document_highlights(buffer, position, cx)
13982 }))
13983 }
13984
13985 fn definitions(
13986 &self,
13987 buffer: &Model<Buffer>,
13988 position: text::Anchor,
13989 kind: GotoDefinitionKind,
13990 cx: &mut AppContext,
13991 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13992 Some(self.update(cx, |project, cx| match kind {
13993 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13994 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13995 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13996 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13997 }))
13998 }
13999
14000 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14001 // TODO: make this work for remote projects
14002 self.read(cx)
14003 .language_servers_for_buffer(buffer.read(cx), cx)
14004 .any(
14005 |(_, server)| match server.capabilities().inlay_hint_provider {
14006 Some(lsp::OneOf::Left(enabled)) => enabled,
14007 Some(lsp::OneOf::Right(_)) => true,
14008 None => false,
14009 },
14010 )
14011 }
14012
14013 fn inlay_hints(
14014 &self,
14015 buffer_handle: Model<Buffer>,
14016 range: Range<text::Anchor>,
14017 cx: &mut AppContext,
14018 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14019 Some(self.update(cx, |project, cx| {
14020 project.inlay_hints(buffer_handle, range, cx)
14021 }))
14022 }
14023
14024 fn resolve_inlay_hint(
14025 &self,
14026 hint: InlayHint,
14027 buffer_handle: Model<Buffer>,
14028 server_id: LanguageServerId,
14029 cx: &mut AppContext,
14030 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14031 Some(self.update(cx, |project, cx| {
14032 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14033 }))
14034 }
14035
14036 fn range_for_rename(
14037 &self,
14038 buffer: &Model<Buffer>,
14039 position: text::Anchor,
14040 cx: &mut AppContext,
14041 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14042 Some(self.update(cx, |project, cx| {
14043 project.prepare_rename(buffer.clone(), position, cx)
14044 }))
14045 }
14046
14047 fn perform_rename(
14048 &self,
14049 buffer: &Model<Buffer>,
14050 position: text::Anchor,
14051 new_name: String,
14052 cx: &mut AppContext,
14053 ) -> Option<Task<Result<ProjectTransaction>>> {
14054 Some(self.update(cx, |project, cx| {
14055 project.perform_rename(buffer.clone(), position, new_name, cx)
14056 }))
14057 }
14058}
14059
14060fn inlay_hint_settings(
14061 location: Anchor,
14062 snapshot: &MultiBufferSnapshot,
14063 cx: &mut ViewContext<'_, Editor>,
14064) -> InlayHintSettings {
14065 let file = snapshot.file_at(location);
14066 let language = snapshot.language_at(location).map(|l| l.name());
14067 language_settings(language, file, cx).inlay_hints
14068}
14069
14070fn consume_contiguous_rows(
14071 contiguous_row_selections: &mut Vec<Selection<Point>>,
14072 selection: &Selection<Point>,
14073 display_map: &DisplaySnapshot,
14074 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14075) -> (MultiBufferRow, MultiBufferRow) {
14076 contiguous_row_selections.push(selection.clone());
14077 let start_row = MultiBufferRow(selection.start.row);
14078 let mut end_row = ending_row(selection, display_map);
14079
14080 while let Some(next_selection) = selections.peek() {
14081 if next_selection.start.row <= end_row.0 {
14082 end_row = ending_row(next_selection, display_map);
14083 contiguous_row_selections.push(selections.next().unwrap().clone());
14084 } else {
14085 break;
14086 }
14087 }
14088 (start_row, end_row)
14089}
14090
14091fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14092 if next_selection.end.column > 0 || next_selection.is_empty() {
14093 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14094 } else {
14095 MultiBufferRow(next_selection.end.row)
14096 }
14097}
14098
14099impl EditorSnapshot {
14100 pub fn remote_selections_in_range<'a>(
14101 &'a self,
14102 range: &'a Range<Anchor>,
14103 collaboration_hub: &dyn CollaborationHub,
14104 cx: &'a AppContext,
14105 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14106 let participant_names = collaboration_hub.user_names(cx);
14107 let participant_indices = collaboration_hub.user_participant_indices(cx);
14108 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14109 let collaborators_by_replica_id = collaborators_by_peer_id
14110 .iter()
14111 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14112 .collect::<HashMap<_, _>>();
14113 self.buffer_snapshot
14114 .selections_in_range(range, false)
14115 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14116 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14117 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14118 let user_name = participant_names.get(&collaborator.user_id).cloned();
14119 Some(RemoteSelection {
14120 replica_id,
14121 selection,
14122 cursor_shape,
14123 line_mode,
14124 participant_index,
14125 peer_id: collaborator.peer_id,
14126 user_name,
14127 })
14128 })
14129 }
14130
14131 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14132 self.display_snapshot.buffer_snapshot.language_at(position)
14133 }
14134
14135 pub fn is_focused(&self) -> bool {
14136 self.is_focused
14137 }
14138
14139 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14140 self.placeholder_text.as_ref()
14141 }
14142
14143 pub fn scroll_position(&self) -> gpui::Point<f32> {
14144 self.scroll_anchor.scroll_position(&self.display_snapshot)
14145 }
14146
14147 fn gutter_dimensions(
14148 &self,
14149 font_id: FontId,
14150 font_size: Pixels,
14151 em_width: Pixels,
14152 em_advance: Pixels,
14153 max_line_number_width: Pixels,
14154 cx: &AppContext,
14155 ) -> GutterDimensions {
14156 if !self.show_gutter {
14157 return GutterDimensions::default();
14158 }
14159 let descent = cx.text_system().descent(font_id, font_size);
14160
14161 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14162 matches!(
14163 ProjectSettings::get_global(cx).git.git_gutter,
14164 Some(GitGutterSetting::TrackedFiles)
14165 )
14166 });
14167 let gutter_settings = EditorSettings::get_global(cx).gutter;
14168 let show_line_numbers = self
14169 .show_line_numbers
14170 .unwrap_or(gutter_settings.line_numbers);
14171 let line_gutter_width = if show_line_numbers {
14172 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14173 let min_width_for_number_on_gutter = em_advance * 4.0;
14174 max_line_number_width.max(min_width_for_number_on_gutter)
14175 } else {
14176 0.0.into()
14177 };
14178
14179 let show_code_actions = self
14180 .show_code_actions
14181 .unwrap_or(gutter_settings.code_actions);
14182
14183 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14184
14185 let git_blame_entries_width =
14186 self.git_blame_gutter_max_author_length
14187 .map(|max_author_length| {
14188 // Length of the author name, but also space for the commit hash,
14189 // the spacing and the timestamp.
14190 let max_char_count = max_author_length
14191 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14192 + 7 // length of commit sha
14193 + 14 // length of max relative timestamp ("60 minutes ago")
14194 + 4; // gaps and margins
14195
14196 em_advance * max_char_count
14197 });
14198
14199 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14200 left_padding += if show_code_actions || show_runnables {
14201 em_width * 3.0
14202 } else if show_git_gutter && show_line_numbers {
14203 em_width * 2.0
14204 } else if show_git_gutter || show_line_numbers {
14205 em_width
14206 } else {
14207 px(0.)
14208 };
14209
14210 let right_padding = if gutter_settings.folds && show_line_numbers {
14211 em_width * 4.0
14212 } else if gutter_settings.folds {
14213 em_width * 3.0
14214 } else if show_line_numbers {
14215 em_width
14216 } else {
14217 px(0.)
14218 };
14219
14220 GutterDimensions {
14221 left_padding,
14222 right_padding,
14223 width: line_gutter_width + left_padding + right_padding,
14224 margin: -descent,
14225 git_blame_entries_width,
14226 }
14227 }
14228
14229 pub fn render_crease_toggle(
14230 &self,
14231 buffer_row: MultiBufferRow,
14232 row_contains_cursor: bool,
14233 editor: View<Editor>,
14234 cx: &mut WindowContext,
14235 ) -> Option<AnyElement> {
14236 let folded = self.is_line_folded(buffer_row);
14237 let mut is_foldable = false;
14238
14239 if let Some(crease) = self
14240 .crease_snapshot
14241 .query_row(buffer_row, &self.buffer_snapshot)
14242 {
14243 is_foldable = true;
14244 match crease {
14245 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14246 if let Some(render_toggle) = render_toggle {
14247 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14248 if folded {
14249 editor.update(cx, |editor, cx| {
14250 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14251 });
14252 } else {
14253 editor.update(cx, |editor, cx| {
14254 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14255 });
14256 }
14257 });
14258 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14259 }
14260 }
14261 }
14262 }
14263
14264 is_foldable |= self.starts_indent(buffer_row);
14265
14266 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14267 Some(
14268 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14269 .selected(folded)
14270 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14271 if folded {
14272 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14273 } else {
14274 this.fold_at(&FoldAt { buffer_row }, cx);
14275 }
14276 }))
14277 .into_any_element(),
14278 )
14279 } else {
14280 None
14281 }
14282 }
14283
14284 pub fn render_crease_trailer(
14285 &self,
14286 buffer_row: MultiBufferRow,
14287 cx: &mut WindowContext,
14288 ) -> Option<AnyElement> {
14289 let folded = self.is_line_folded(buffer_row);
14290 if let Crease::Inline { render_trailer, .. } = self
14291 .crease_snapshot
14292 .query_row(buffer_row, &self.buffer_snapshot)?
14293 {
14294 let render_trailer = render_trailer.as_ref()?;
14295 Some(render_trailer(buffer_row, folded, cx))
14296 } else {
14297 None
14298 }
14299 }
14300}
14301
14302impl Deref for EditorSnapshot {
14303 type Target = DisplaySnapshot;
14304
14305 fn deref(&self) -> &Self::Target {
14306 &self.display_snapshot
14307 }
14308}
14309
14310#[derive(Clone, Debug, PartialEq, Eq)]
14311pub enum EditorEvent {
14312 InputIgnored {
14313 text: Arc<str>,
14314 },
14315 InputHandled {
14316 utf16_range_to_replace: Option<Range<isize>>,
14317 text: Arc<str>,
14318 },
14319 ExcerptsAdded {
14320 buffer: Model<Buffer>,
14321 predecessor: ExcerptId,
14322 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14323 },
14324 ExcerptsRemoved {
14325 ids: Vec<ExcerptId>,
14326 },
14327 ExcerptsEdited {
14328 ids: Vec<ExcerptId>,
14329 },
14330 ExcerptsExpanded {
14331 ids: Vec<ExcerptId>,
14332 },
14333 BufferEdited,
14334 Edited {
14335 transaction_id: clock::Lamport,
14336 },
14337 Reparsed(BufferId),
14338 Focused,
14339 FocusedIn,
14340 Blurred,
14341 DirtyChanged,
14342 Saved,
14343 TitleChanged,
14344 DiffBaseChanged,
14345 SelectionsChanged {
14346 local: bool,
14347 },
14348 ScrollPositionChanged {
14349 local: bool,
14350 autoscroll: bool,
14351 },
14352 Closed,
14353 TransactionUndone {
14354 transaction_id: clock::Lamport,
14355 },
14356 TransactionBegun {
14357 transaction_id: clock::Lamport,
14358 },
14359 Reloaded,
14360 CursorShapeChanged,
14361}
14362
14363impl EventEmitter<EditorEvent> for Editor {}
14364
14365impl FocusableView for Editor {
14366 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14367 self.focus_handle.clone()
14368 }
14369}
14370
14371impl Render for Editor {
14372 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14373 let settings = ThemeSettings::get_global(cx);
14374
14375 let mut text_style = match self.mode {
14376 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14377 color: cx.theme().colors().editor_foreground,
14378 font_family: settings.ui_font.family.clone(),
14379 font_features: settings.ui_font.features.clone(),
14380 font_fallbacks: settings.ui_font.fallbacks.clone(),
14381 font_size: rems(0.875).into(),
14382 font_weight: settings.ui_font.weight,
14383 line_height: relative(settings.buffer_line_height.value()),
14384 ..Default::default()
14385 },
14386 EditorMode::Full => TextStyle {
14387 color: cx.theme().colors().editor_foreground,
14388 font_family: settings.buffer_font.family.clone(),
14389 font_features: settings.buffer_font.features.clone(),
14390 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14391 font_size: settings.buffer_font_size(cx).into(),
14392 font_weight: settings.buffer_font.weight,
14393 line_height: relative(settings.buffer_line_height.value()),
14394 ..Default::default()
14395 },
14396 };
14397 if let Some(text_style_refinement) = &self.text_style_refinement {
14398 text_style.refine(text_style_refinement)
14399 }
14400
14401 let background = match self.mode {
14402 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14403 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14404 EditorMode::Full => cx.theme().colors().editor_background,
14405 };
14406
14407 EditorElement::new(
14408 cx.view(),
14409 EditorStyle {
14410 background,
14411 local_player: cx.theme().players().local(),
14412 text: text_style,
14413 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14414 syntax: cx.theme().syntax().clone(),
14415 status: cx.theme().status().clone(),
14416 inlay_hints_style: make_inlay_hints_style(cx),
14417 suggestions_style: HighlightStyle {
14418 color: Some(cx.theme().status().predictive),
14419 ..HighlightStyle::default()
14420 },
14421 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14422 },
14423 )
14424 }
14425}
14426
14427impl ViewInputHandler for Editor {
14428 fn text_for_range(
14429 &mut self,
14430 range_utf16: Range<usize>,
14431 adjusted_range: &mut Option<Range<usize>>,
14432 cx: &mut ViewContext<Self>,
14433 ) -> Option<String> {
14434 let snapshot = self.buffer.read(cx).read(cx);
14435 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14436 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14437 if (start.0..end.0) != range_utf16 {
14438 adjusted_range.replace(start.0..end.0);
14439 }
14440 Some(snapshot.text_for_range(start..end).collect())
14441 }
14442
14443 fn selected_text_range(
14444 &mut self,
14445 ignore_disabled_input: bool,
14446 cx: &mut ViewContext<Self>,
14447 ) -> Option<UTF16Selection> {
14448 // Prevent the IME menu from appearing when holding down an alphabetic key
14449 // while input is disabled.
14450 if !ignore_disabled_input && !self.input_enabled {
14451 return None;
14452 }
14453
14454 let selection = self.selections.newest::<OffsetUtf16>(cx);
14455 let range = selection.range();
14456
14457 Some(UTF16Selection {
14458 range: range.start.0..range.end.0,
14459 reversed: selection.reversed,
14460 })
14461 }
14462
14463 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14464 let snapshot = self.buffer.read(cx).read(cx);
14465 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14466 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14467 }
14468
14469 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14470 self.clear_highlights::<InputComposition>(cx);
14471 self.ime_transaction.take();
14472 }
14473
14474 fn replace_text_in_range(
14475 &mut self,
14476 range_utf16: Option<Range<usize>>,
14477 text: &str,
14478 cx: &mut ViewContext<Self>,
14479 ) {
14480 if !self.input_enabled {
14481 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14482 return;
14483 }
14484
14485 self.transact(cx, |this, cx| {
14486 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14487 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14488 Some(this.selection_replacement_ranges(range_utf16, cx))
14489 } else {
14490 this.marked_text_ranges(cx)
14491 };
14492
14493 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14494 let newest_selection_id = this.selections.newest_anchor().id;
14495 this.selections
14496 .all::<OffsetUtf16>(cx)
14497 .iter()
14498 .zip(ranges_to_replace.iter())
14499 .find_map(|(selection, range)| {
14500 if selection.id == newest_selection_id {
14501 Some(
14502 (range.start.0 as isize - selection.head().0 as isize)
14503 ..(range.end.0 as isize - selection.head().0 as isize),
14504 )
14505 } else {
14506 None
14507 }
14508 })
14509 });
14510
14511 cx.emit(EditorEvent::InputHandled {
14512 utf16_range_to_replace: range_to_replace,
14513 text: text.into(),
14514 });
14515
14516 if let Some(new_selected_ranges) = new_selected_ranges {
14517 this.change_selections(None, cx, |selections| {
14518 selections.select_ranges(new_selected_ranges)
14519 });
14520 this.backspace(&Default::default(), cx);
14521 }
14522
14523 this.handle_input(text, cx);
14524 });
14525
14526 if let Some(transaction) = self.ime_transaction {
14527 self.buffer.update(cx, |buffer, cx| {
14528 buffer.group_until_transaction(transaction, cx);
14529 });
14530 }
14531
14532 self.unmark_text(cx);
14533 }
14534
14535 fn replace_and_mark_text_in_range(
14536 &mut self,
14537 range_utf16: Option<Range<usize>>,
14538 text: &str,
14539 new_selected_range_utf16: Option<Range<usize>>,
14540 cx: &mut ViewContext<Self>,
14541 ) {
14542 if !self.input_enabled {
14543 return;
14544 }
14545
14546 let transaction = self.transact(cx, |this, cx| {
14547 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14548 let snapshot = this.buffer.read(cx).read(cx);
14549 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14550 for marked_range in &mut marked_ranges {
14551 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14552 marked_range.start.0 += relative_range_utf16.start;
14553 marked_range.start =
14554 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14555 marked_range.end =
14556 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14557 }
14558 }
14559 Some(marked_ranges)
14560 } else if let Some(range_utf16) = range_utf16 {
14561 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14562 Some(this.selection_replacement_ranges(range_utf16, cx))
14563 } else {
14564 None
14565 };
14566
14567 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14568 let newest_selection_id = this.selections.newest_anchor().id;
14569 this.selections
14570 .all::<OffsetUtf16>(cx)
14571 .iter()
14572 .zip(ranges_to_replace.iter())
14573 .find_map(|(selection, range)| {
14574 if selection.id == newest_selection_id {
14575 Some(
14576 (range.start.0 as isize - selection.head().0 as isize)
14577 ..(range.end.0 as isize - selection.head().0 as isize),
14578 )
14579 } else {
14580 None
14581 }
14582 })
14583 });
14584
14585 cx.emit(EditorEvent::InputHandled {
14586 utf16_range_to_replace: range_to_replace,
14587 text: text.into(),
14588 });
14589
14590 if let Some(ranges) = ranges_to_replace {
14591 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14592 }
14593
14594 let marked_ranges = {
14595 let snapshot = this.buffer.read(cx).read(cx);
14596 this.selections
14597 .disjoint_anchors()
14598 .iter()
14599 .map(|selection| {
14600 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14601 })
14602 .collect::<Vec<_>>()
14603 };
14604
14605 if text.is_empty() {
14606 this.unmark_text(cx);
14607 } else {
14608 this.highlight_text::<InputComposition>(
14609 marked_ranges.clone(),
14610 HighlightStyle {
14611 underline: Some(UnderlineStyle {
14612 thickness: px(1.),
14613 color: None,
14614 wavy: false,
14615 }),
14616 ..Default::default()
14617 },
14618 cx,
14619 );
14620 }
14621
14622 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14623 let use_autoclose = this.use_autoclose;
14624 let use_auto_surround = this.use_auto_surround;
14625 this.set_use_autoclose(false);
14626 this.set_use_auto_surround(false);
14627 this.handle_input(text, cx);
14628 this.set_use_autoclose(use_autoclose);
14629 this.set_use_auto_surround(use_auto_surround);
14630
14631 if let Some(new_selected_range) = new_selected_range_utf16 {
14632 let snapshot = this.buffer.read(cx).read(cx);
14633 let new_selected_ranges = marked_ranges
14634 .into_iter()
14635 .map(|marked_range| {
14636 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14637 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14638 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14639 snapshot.clip_offset_utf16(new_start, Bias::Left)
14640 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14641 })
14642 .collect::<Vec<_>>();
14643
14644 drop(snapshot);
14645 this.change_selections(None, cx, |selections| {
14646 selections.select_ranges(new_selected_ranges)
14647 });
14648 }
14649 });
14650
14651 self.ime_transaction = self.ime_transaction.or(transaction);
14652 if let Some(transaction) = self.ime_transaction {
14653 self.buffer.update(cx, |buffer, cx| {
14654 buffer.group_until_transaction(transaction, cx);
14655 });
14656 }
14657
14658 if self.text_highlights::<InputComposition>(cx).is_none() {
14659 self.ime_transaction.take();
14660 }
14661 }
14662
14663 fn bounds_for_range(
14664 &mut self,
14665 range_utf16: Range<usize>,
14666 element_bounds: gpui::Bounds<Pixels>,
14667 cx: &mut ViewContext<Self>,
14668 ) -> Option<gpui::Bounds<Pixels>> {
14669 let text_layout_details = self.text_layout_details(cx);
14670 let style = &text_layout_details.editor_style;
14671 let font_id = cx.text_system().resolve_font(&style.text.font());
14672 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14673 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14674
14675 let em_width = cx
14676 .text_system()
14677 .typographic_bounds(font_id, font_size, 'm')
14678 .unwrap()
14679 .size
14680 .width;
14681
14682 let snapshot = self.snapshot(cx);
14683 let scroll_position = snapshot.scroll_position();
14684 let scroll_left = scroll_position.x * em_width;
14685
14686 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14687 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14688 + self.gutter_dimensions.width;
14689 let y = line_height * (start.row().as_f32() - scroll_position.y);
14690
14691 Some(Bounds {
14692 origin: element_bounds.origin + point(x, y),
14693 size: size(em_width, line_height),
14694 })
14695 }
14696}
14697
14698trait SelectionExt {
14699 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14700 fn spanned_rows(
14701 &self,
14702 include_end_if_at_line_start: bool,
14703 map: &DisplaySnapshot,
14704 ) -> Range<MultiBufferRow>;
14705}
14706
14707impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14708 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14709 let start = self
14710 .start
14711 .to_point(&map.buffer_snapshot)
14712 .to_display_point(map);
14713 let end = self
14714 .end
14715 .to_point(&map.buffer_snapshot)
14716 .to_display_point(map);
14717 if self.reversed {
14718 end..start
14719 } else {
14720 start..end
14721 }
14722 }
14723
14724 fn spanned_rows(
14725 &self,
14726 include_end_if_at_line_start: bool,
14727 map: &DisplaySnapshot,
14728 ) -> Range<MultiBufferRow> {
14729 let start = self.start.to_point(&map.buffer_snapshot);
14730 let mut end = self.end.to_point(&map.buffer_snapshot);
14731 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14732 end.row -= 1;
14733 }
14734
14735 let buffer_start = map.prev_line_boundary(start).0;
14736 let buffer_end = map.next_line_boundary(end).0;
14737 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14738 }
14739}
14740
14741impl<T: InvalidationRegion> InvalidationStack<T> {
14742 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14743 where
14744 S: Clone + ToOffset,
14745 {
14746 while let Some(region) = self.last() {
14747 let all_selections_inside_invalidation_ranges =
14748 if selections.len() == region.ranges().len() {
14749 selections
14750 .iter()
14751 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14752 .all(|(selection, invalidation_range)| {
14753 let head = selection.head().to_offset(buffer);
14754 invalidation_range.start <= head && invalidation_range.end >= head
14755 })
14756 } else {
14757 false
14758 };
14759
14760 if all_selections_inside_invalidation_ranges {
14761 break;
14762 } else {
14763 self.pop();
14764 }
14765 }
14766 }
14767}
14768
14769impl<T> Default for InvalidationStack<T> {
14770 fn default() -> Self {
14771 Self(Default::default())
14772 }
14773}
14774
14775impl<T> Deref for InvalidationStack<T> {
14776 type Target = Vec<T>;
14777
14778 fn deref(&self) -> &Self::Target {
14779 &self.0
14780 }
14781}
14782
14783impl<T> DerefMut for InvalidationStack<T> {
14784 fn deref_mut(&mut self) -> &mut Self::Target {
14785 &mut self.0
14786 }
14787}
14788
14789impl InvalidationRegion for SnippetState {
14790 fn ranges(&self) -> &[Range<Anchor>] {
14791 &self.ranges[self.active_index]
14792 }
14793}
14794
14795pub fn diagnostic_block_renderer(
14796 diagnostic: Diagnostic,
14797 max_message_rows: Option<u8>,
14798 allow_closing: bool,
14799 _is_valid: bool,
14800) -> RenderBlock {
14801 let (text_without_backticks, code_ranges) =
14802 highlight_diagnostic_message(&diagnostic, max_message_rows);
14803
14804 Arc::new(move |cx: &mut BlockContext| {
14805 let group_id: SharedString = cx.block_id.to_string().into();
14806
14807 let mut text_style = cx.text_style().clone();
14808 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14809 let theme_settings = ThemeSettings::get_global(cx);
14810 text_style.font_family = theme_settings.buffer_font.family.clone();
14811 text_style.font_style = theme_settings.buffer_font.style;
14812 text_style.font_features = theme_settings.buffer_font.features.clone();
14813 text_style.font_weight = theme_settings.buffer_font.weight;
14814
14815 let multi_line_diagnostic = diagnostic.message.contains('\n');
14816
14817 let buttons = |diagnostic: &Diagnostic| {
14818 if multi_line_diagnostic {
14819 v_flex()
14820 } else {
14821 h_flex()
14822 }
14823 .when(allow_closing, |div| {
14824 div.children(diagnostic.is_primary.then(|| {
14825 IconButton::new("close-block", IconName::XCircle)
14826 .icon_color(Color::Muted)
14827 .size(ButtonSize::Compact)
14828 .style(ButtonStyle::Transparent)
14829 .visible_on_hover(group_id.clone())
14830 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14831 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14832 }))
14833 })
14834 .child(
14835 IconButton::new("copy-block", IconName::Copy)
14836 .icon_color(Color::Muted)
14837 .size(ButtonSize::Compact)
14838 .style(ButtonStyle::Transparent)
14839 .visible_on_hover(group_id.clone())
14840 .on_click({
14841 let message = diagnostic.message.clone();
14842 move |_click, cx| {
14843 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14844 }
14845 })
14846 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14847 )
14848 };
14849
14850 let icon_size = buttons(&diagnostic)
14851 .into_any_element()
14852 .layout_as_root(AvailableSpace::min_size(), cx);
14853
14854 h_flex()
14855 .id(cx.block_id)
14856 .group(group_id.clone())
14857 .relative()
14858 .size_full()
14859 .block_mouse_down()
14860 .pl(cx.gutter_dimensions.width)
14861 .w(cx.max_width - cx.gutter_dimensions.full_width())
14862 .child(
14863 div()
14864 .flex()
14865 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14866 .flex_shrink(),
14867 )
14868 .child(buttons(&diagnostic))
14869 .child(div().flex().flex_shrink_0().child(
14870 StyledText::new(text_without_backticks.clone()).with_highlights(
14871 &text_style,
14872 code_ranges.iter().map(|range| {
14873 (
14874 range.clone(),
14875 HighlightStyle {
14876 font_weight: Some(FontWeight::BOLD),
14877 ..Default::default()
14878 },
14879 )
14880 }),
14881 ),
14882 ))
14883 .into_any_element()
14884 })
14885}
14886
14887pub fn highlight_diagnostic_message(
14888 diagnostic: &Diagnostic,
14889 mut max_message_rows: Option<u8>,
14890) -> (SharedString, Vec<Range<usize>>) {
14891 let mut text_without_backticks = String::new();
14892 let mut code_ranges = Vec::new();
14893
14894 if let Some(source) = &diagnostic.source {
14895 text_without_backticks.push_str(source);
14896 code_ranges.push(0..source.len());
14897 text_without_backticks.push_str(": ");
14898 }
14899
14900 let mut prev_offset = 0;
14901 let mut in_code_block = false;
14902 let has_row_limit = max_message_rows.is_some();
14903 let mut newline_indices = diagnostic
14904 .message
14905 .match_indices('\n')
14906 .filter(|_| has_row_limit)
14907 .map(|(ix, _)| ix)
14908 .fuse()
14909 .peekable();
14910
14911 for (quote_ix, _) in diagnostic
14912 .message
14913 .match_indices('`')
14914 .chain([(diagnostic.message.len(), "")])
14915 {
14916 let mut first_newline_ix = None;
14917 let mut last_newline_ix = None;
14918 while let Some(newline_ix) = newline_indices.peek() {
14919 if *newline_ix < quote_ix {
14920 if first_newline_ix.is_none() {
14921 first_newline_ix = Some(*newline_ix);
14922 }
14923 last_newline_ix = Some(*newline_ix);
14924
14925 if let Some(rows_left) = &mut max_message_rows {
14926 if *rows_left == 0 {
14927 break;
14928 } else {
14929 *rows_left -= 1;
14930 }
14931 }
14932 let _ = newline_indices.next();
14933 } else {
14934 break;
14935 }
14936 }
14937 let prev_len = text_without_backticks.len();
14938 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14939 text_without_backticks.push_str(new_text);
14940 if in_code_block {
14941 code_ranges.push(prev_len..text_without_backticks.len());
14942 }
14943 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14944 in_code_block = !in_code_block;
14945 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14946 text_without_backticks.push_str("...");
14947 break;
14948 }
14949 }
14950
14951 (text_without_backticks.into(), code_ranges)
14952}
14953
14954fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14955 match severity {
14956 DiagnosticSeverity::ERROR => colors.error,
14957 DiagnosticSeverity::WARNING => colors.warning,
14958 DiagnosticSeverity::INFORMATION => colors.info,
14959 DiagnosticSeverity::HINT => colors.info,
14960 _ => colors.ignored,
14961 }
14962}
14963
14964pub fn styled_runs_for_code_label<'a>(
14965 label: &'a CodeLabel,
14966 syntax_theme: &'a theme::SyntaxTheme,
14967) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14968 let fade_out = HighlightStyle {
14969 fade_out: Some(0.35),
14970 ..Default::default()
14971 };
14972
14973 let mut prev_end = label.filter_range.end;
14974 label
14975 .runs
14976 .iter()
14977 .enumerate()
14978 .flat_map(move |(ix, (range, highlight_id))| {
14979 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14980 style
14981 } else {
14982 return Default::default();
14983 };
14984 let mut muted_style = style;
14985 muted_style.highlight(fade_out);
14986
14987 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14988 if range.start >= label.filter_range.end {
14989 if range.start > prev_end {
14990 runs.push((prev_end..range.start, fade_out));
14991 }
14992 runs.push((range.clone(), muted_style));
14993 } else if range.end <= label.filter_range.end {
14994 runs.push((range.clone(), style));
14995 } else {
14996 runs.push((range.start..label.filter_range.end, style));
14997 runs.push((label.filter_range.end..range.end, muted_style));
14998 }
14999 prev_end = cmp::max(prev_end, range.end);
15000
15001 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15002 runs.push((prev_end..label.text.len(), fade_out));
15003 }
15004
15005 runs
15006 })
15007}
15008
15009pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15010 let mut prev_index = 0;
15011 let mut prev_codepoint: Option<char> = None;
15012 text.char_indices()
15013 .chain([(text.len(), '\0')])
15014 .filter_map(move |(index, codepoint)| {
15015 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15016 let is_boundary = index == text.len()
15017 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15018 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15019 if is_boundary {
15020 let chunk = &text[prev_index..index];
15021 prev_index = index;
15022 Some(chunk)
15023 } else {
15024 None
15025 }
15026 })
15027}
15028
15029pub trait RangeToAnchorExt: Sized {
15030 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15031
15032 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15033 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15034 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15035 }
15036}
15037
15038impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15039 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15040 let start_offset = self.start.to_offset(snapshot);
15041 let end_offset = self.end.to_offset(snapshot);
15042 if start_offset == end_offset {
15043 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15044 } else {
15045 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15046 }
15047 }
15048}
15049
15050pub trait RowExt {
15051 fn as_f32(&self) -> f32;
15052
15053 fn next_row(&self) -> Self;
15054
15055 fn previous_row(&self) -> Self;
15056
15057 fn minus(&self, other: Self) -> u32;
15058}
15059
15060impl RowExt for DisplayRow {
15061 fn as_f32(&self) -> f32 {
15062 self.0 as f32
15063 }
15064
15065 fn next_row(&self) -> Self {
15066 Self(self.0 + 1)
15067 }
15068
15069 fn previous_row(&self) -> Self {
15070 Self(self.0.saturating_sub(1))
15071 }
15072
15073 fn minus(&self, other: Self) -> u32 {
15074 self.0 - other.0
15075 }
15076}
15077
15078impl RowExt for MultiBufferRow {
15079 fn as_f32(&self) -> f32 {
15080 self.0 as f32
15081 }
15082
15083 fn next_row(&self) -> Self {
15084 Self(self.0 + 1)
15085 }
15086
15087 fn previous_row(&self) -> Self {
15088 Self(self.0.saturating_sub(1))
15089 }
15090
15091 fn minus(&self, other: Self) -> u32 {
15092 self.0 - other.0
15093 }
15094}
15095
15096trait RowRangeExt {
15097 type Row;
15098
15099 fn len(&self) -> usize;
15100
15101 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15102}
15103
15104impl RowRangeExt for Range<MultiBufferRow> {
15105 type Row = MultiBufferRow;
15106
15107 fn len(&self) -> usize {
15108 (self.end.0 - self.start.0) as usize
15109 }
15110
15111 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15112 (self.start.0..self.end.0).map(MultiBufferRow)
15113 }
15114}
15115
15116impl RowRangeExt for Range<DisplayRow> {
15117 type Row = DisplayRow;
15118
15119 fn len(&self) -> usize {
15120 (self.end.0 - self.start.0) as usize
15121 }
15122
15123 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15124 (self.start.0..self.end.0).map(DisplayRow)
15125 }
15126}
15127
15128fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15129 if hunk.diff_base_byte_range.is_empty() {
15130 DiffHunkStatus::Added
15131 } else if hunk.row_range.is_empty() {
15132 DiffHunkStatus::Removed
15133 } else {
15134 DiffHunkStatus::Modified
15135 }
15136}
15137
15138/// If select range has more than one line, we
15139/// just point the cursor to range.start.
15140fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15141 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15142 range
15143 } else {
15144 range.start..range.start
15145 }
15146}
15147
15148const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);