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, Global, 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, Location, LocationLink,
129 Project, ProjectItem, 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 git::project_diff::init(cx);
331}
332
333pub struct SearchWithinRange;
334
335trait InvalidationRegion {
336 fn ranges(&self) -> &[Range<Anchor>];
337}
338
339#[derive(Clone, Debug, PartialEq)]
340pub enum SelectPhase {
341 Begin {
342 position: DisplayPoint,
343 add: bool,
344 click_count: usize,
345 },
346 BeginColumnar {
347 position: DisplayPoint,
348 reset: bool,
349 goal_column: u32,
350 },
351 Extend {
352 position: DisplayPoint,
353 click_count: usize,
354 },
355 Update {
356 position: DisplayPoint,
357 goal_column: u32,
358 scroll_delta: gpui::Point<f32>,
359 },
360 End,
361}
362
363#[derive(Clone, Debug)]
364pub enum SelectMode {
365 Character,
366 Word(Range<Anchor>),
367 Line(Range<Anchor>),
368 All,
369}
370
371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
372pub enum EditorMode {
373 SingleLine { auto_width: bool },
374 AutoHeight { max_lines: usize },
375 Full,
376}
377
378#[derive(Copy, Clone, Debug)]
379pub enum SoftWrap {
380 /// Prefer not to wrap at all.
381 ///
382 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
383 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
384 GitDiff,
385 /// Prefer a single line generally, unless an overly long line is encountered.
386 None,
387 /// Soft wrap lines that exceed the editor width.
388 EditorWidth,
389 /// Soft wrap lines at the preferred line length.
390 Column(u32),
391 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
392 Bounded(u32),
393}
394
395#[derive(Clone)]
396pub struct EditorStyle {
397 pub background: Hsla,
398 pub local_player: PlayerColor,
399 pub text: TextStyle,
400 pub scrollbar_width: Pixels,
401 pub syntax: Arc<SyntaxTheme>,
402 pub status: StatusColors,
403 pub inlay_hints_style: HighlightStyle,
404 pub suggestions_style: HighlightStyle,
405 pub unnecessary_code_fade: f32,
406}
407
408impl Default for EditorStyle {
409 fn default() -> Self {
410 Self {
411 background: Hsla::default(),
412 local_player: PlayerColor::default(),
413 text: TextStyle::default(),
414 scrollbar_width: Pixels::default(),
415 syntax: Default::default(),
416 // HACK: Status colors don't have a real default.
417 // We should look into removing the status colors from the editor
418 // style and retrieve them directly from the theme.
419 status: StatusColors::dark(),
420 inlay_hints_style: HighlightStyle::default(),
421 suggestions_style: HighlightStyle::default(),
422 unnecessary_code_fade: Default::default(),
423 }
424 }
425}
426
427pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
428 let show_background = language_settings::language_settings(None, None, cx)
429 .inlay_hints
430 .show_background;
431
432 HighlightStyle {
433 color: Some(cx.theme().status().hint),
434 background_color: show_background.then(|| cx.theme().status().hint_background),
435 ..HighlightStyle::default()
436 }
437}
438
439type CompletionId = usize;
440
441#[derive(Clone, Debug)]
442struct CompletionState {
443 // render_inlay_ids represents the inlay hints that are inserted
444 // for rendering the inline completions. They may be discontinuous
445 // in the event that the completion provider returns some intersection
446 // with the existing content.
447 render_inlay_ids: Vec<InlayId>,
448 // text is the resulting rope that is inserted when the user accepts a completion.
449 text: Rope,
450 // position is the position of the cursor when the completion was triggered.
451 position: multi_buffer::Anchor,
452 // delete_range is the range of text that this completion state covers.
453 // if the completion is accepted, this range should be deleted.
454 delete_range: Option<Range<multi_buffer::Anchor>>,
455}
456
457#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
458struct EditorActionId(usize);
459
460impl EditorActionId {
461 pub fn post_inc(&mut self) -> Self {
462 let answer = self.0;
463
464 *self = Self(answer + 1);
465
466 Self(answer)
467 }
468}
469
470// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
471// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
472
473type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
474type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
475
476#[derive(Default)]
477struct ScrollbarMarkerState {
478 scrollbar_size: Size<Pixels>,
479 dirty: bool,
480 markers: Arc<[PaintQuad]>,
481 pending_refresh: Option<Task<Result<()>>>,
482}
483
484impl ScrollbarMarkerState {
485 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
486 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
487 }
488}
489
490#[derive(Clone, Debug)]
491struct RunnableTasks {
492 templates: Vec<(TaskSourceKind, TaskTemplate)>,
493 offset: MultiBufferOffset,
494 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
495 column: u32,
496 // Values of all named captures, including those starting with '_'
497 extra_variables: HashMap<String, String>,
498 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
499 context_range: Range<BufferOffset>,
500}
501
502impl RunnableTasks {
503 fn resolve<'a>(
504 &'a self,
505 cx: &'a task::TaskContext,
506 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
507 self.templates.iter().filter_map(|(kind, template)| {
508 template
509 .resolve_task(&kind.to_id_base(), cx)
510 .map(|task| (kind.clone(), task))
511 })
512 }
513}
514
515#[derive(Clone)]
516struct ResolvedTasks {
517 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
518 position: Anchor,
519}
520#[derive(Copy, Clone, Debug)]
521struct MultiBufferOffset(usize);
522#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
523struct BufferOffset(usize);
524
525// Addons allow storing per-editor state in other crates (e.g. Vim)
526pub trait Addon: 'static {
527 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
528
529 fn to_any(&self) -> &dyn std::any::Any;
530}
531
532#[derive(Debug, Copy, Clone, PartialEq, Eq)]
533pub enum IsVimMode {
534 Yes,
535 No,
536}
537
538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
539///
540/// See the [module level documentation](self) for more information.
541pub struct Editor {
542 focus_handle: FocusHandle,
543 last_focused_descendant: Option<WeakFocusHandle>,
544 /// The text buffer being edited
545 buffer: Model<MultiBuffer>,
546 /// Map of how text in the buffer should be displayed.
547 /// Handles soft wraps, folds, fake inlay text insertions, etc.
548 pub display_map: Model<DisplayMap>,
549 pub selections: SelectionsCollection,
550 pub scroll_manager: ScrollManager,
551 /// When inline assist editors are linked, they all render cursors because
552 /// typing enters text into each of them, even the ones that aren't focused.
553 pub(crate) show_cursor_when_unfocused: bool,
554 columnar_selection_tail: Option<Anchor>,
555 add_selections_state: Option<AddSelectionsState>,
556 select_next_state: Option<SelectNextState>,
557 select_prev_state: Option<SelectNextState>,
558 selection_history: SelectionHistory,
559 autoclose_regions: Vec<AutocloseRegion>,
560 snippet_stack: InvalidationStack<SnippetState>,
561 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
562 ime_transaction: Option<TransactionId>,
563 active_diagnostics: Option<ActiveDiagnosticGroup>,
564 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
565
566 project: Option<Model<Project>>,
567 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
568 completion_provider: Option<Box<dyn CompletionProvider>>,
569 collaboration_hub: Option<Box<dyn CollaborationHub>>,
570 blink_manager: Model<BlinkManager>,
571 show_cursor_names: bool,
572 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
573 pub show_local_selections: bool,
574 mode: EditorMode,
575 show_breadcrumbs: bool,
576 show_gutter: bool,
577 show_line_numbers: Option<bool>,
578 use_relative_line_numbers: Option<bool>,
579 show_git_diff_gutter: Option<bool>,
580 show_code_actions: Option<bool>,
581 show_runnables: Option<bool>,
582 show_wrap_guides: Option<bool>,
583 show_indent_guides: Option<bool>,
584 placeholder_text: Option<Arc<str>>,
585 highlight_order: usize,
586 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
587 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
588 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
589 scrollbar_marker_state: ScrollbarMarkerState,
590 active_indent_guides_state: ActiveIndentGuidesState,
591 nav_history: Option<ItemNavHistory>,
592 context_menu: RwLock<Option<ContextMenu>>,
593 mouse_context_menu: Option<MouseContextMenu>,
594 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
595 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
596 signature_help_state: SignatureHelpState,
597 auto_signature_help: Option<bool>,
598 find_all_references_task_sources: Vec<Anchor>,
599 next_completion_id: CompletionId,
600 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
601 code_actions_task: Option<Task<Result<()>>>,
602 document_highlights_task: Option<Task<()>>,
603 linked_editing_range_task: Option<Task<Option<()>>>,
604 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
605 pending_rename: Option<RenameState>,
606 searchable: bool,
607 cursor_shape: CursorShape,
608 current_line_highlight: Option<CurrentLineHighlight>,
609 collapse_matches: bool,
610 autoindent_mode: Option<AutoindentMode>,
611 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
612 input_enabled: bool,
613 use_modal_editing: bool,
614 read_only: bool,
615 leader_peer_id: Option<PeerId>,
616 remote_id: Option<ViewId>,
617 hover_state: HoverState,
618 gutter_hovered: bool,
619 hovered_link_state: Option<HoveredLinkState>,
620 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
621 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
622 active_inline_completion: Option<CompletionState>,
623 // enable_inline_completions is a switch that Vim can use to disable
624 // inline completions based on its mode.
625 enable_inline_completions: bool,
626 show_inline_completions_override: Option<bool>,
627 inlay_hint_cache: InlayHintCache,
628 expanded_hunks: ExpandedHunks,
629 next_inlay_id: usize,
630 _subscriptions: Vec<Subscription>,
631 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
632 gutter_dimensions: GutterDimensions,
633 style: Option<EditorStyle>,
634 text_style_refinement: Option<TextStyleRefinement>,
635 next_editor_action_id: EditorActionId,
636 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
637 use_autoclose: bool,
638 use_auto_surround: bool,
639 auto_replace_emoji_shortcode: bool,
640 show_git_blame_gutter: bool,
641 show_git_blame_inline: bool,
642 show_git_blame_inline_delay_task: Option<Task<()>>,
643 git_blame_inline_enabled: bool,
644 serialize_dirty_buffers: bool,
645 show_selection_menu: Option<bool>,
646 blame: Option<Model<GitBlame>>,
647 blame_subscription: Option<Subscription>,
648 custom_context_menu: Option<
649 Box<
650 dyn 'static
651 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
652 >,
653 >,
654 last_bounds: Option<Bounds<Pixels>>,
655 expect_bounds_change: Option<Bounds<Pixels>>,
656 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
657 tasks_update_task: Option<Task<()>>,
658 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
659 breadcrumb_header: Option<String>,
660 focused_block: Option<FocusedBlock>,
661 next_scroll_position: NextScrollCursorCenterTopBottom,
662 addons: HashMap<TypeId, Box<dyn Addon>>,
663 _scroll_cursor_center_top_bottom_task: Task<()>,
664}
665
666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
667enum NextScrollCursorCenterTopBottom {
668 #[default]
669 Center,
670 Top,
671 Bottom,
672}
673
674impl NextScrollCursorCenterTopBottom {
675 fn next(&self) -> Self {
676 match self {
677 Self::Center => Self::Top,
678 Self::Top => Self::Bottom,
679 Self::Bottom => Self::Center,
680 }
681 }
682}
683
684#[derive(Clone)]
685pub struct EditorSnapshot {
686 pub mode: EditorMode,
687 show_gutter: bool,
688 show_line_numbers: Option<bool>,
689 show_git_diff_gutter: Option<bool>,
690 show_code_actions: Option<bool>,
691 show_runnables: Option<bool>,
692 git_blame_gutter_max_author_length: Option<usize>,
693 pub display_snapshot: DisplaySnapshot,
694 pub placeholder_text: Option<Arc<str>>,
695 is_focused: bool,
696 scroll_anchor: ScrollAnchor,
697 ongoing_scroll: OngoingScroll,
698 current_line_highlight: CurrentLineHighlight,
699 gutter_hovered: bool,
700}
701
702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
703
704#[derive(Default, Debug, Clone, Copy)]
705pub struct GutterDimensions {
706 pub left_padding: Pixels,
707 pub right_padding: Pixels,
708 pub width: Pixels,
709 pub margin: Pixels,
710 pub git_blame_entries_width: Option<Pixels>,
711}
712
713impl GutterDimensions {
714 /// The full width of the space taken up by the gutter.
715 pub fn full_width(&self) -> Pixels {
716 self.margin + self.width
717 }
718
719 /// The width of the space reserved for the fold indicators,
720 /// use alongside 'justify_end' and `gutter_width` to
721 /// right align content with the line numbers
722 pub fn fold_area_width(&self) -> Pixels {
723 self.margin + self.right_padding
724 }
725}
726
727#[derive(Debug)]
728pub struct RemoteSelection {
729 pub replica_id: ReplicaId,
730 pub selection: Selection<Anchor>,
731 pub cursor_shape: CursorShape,
732 pub peer_id: PeerId,
733 pub line_mode: bool,
734 pub participant_index: Option<ParticipantIndex>,
735 pub user_name: Option<SharedString>,
736}
737
738#[derive(Clone, Debug)]
739struct SelectionHistoryEntry {
740 selections: Arc<[Selection<Anchor>]>,
741 select_next_state: Option<SelectNextState>,
742 select_prev_state: Option<SelectNextState>,
743 add_selections_state: Option<AddSelectionsState>,
744}
745
746enum SelectionHistoryMode {
747 Normal,
748 Undoing,
749 Redoing,
750}
751
752#[derive(Clone, PartialEq, Eq, Hash)]
753struct HoveredCursor {
754 replica_id: u16,
755 selection_id: usize,
756}
757
758impl Default for SelectionHistoryMode {
759 fn default() -> Self {
760 Self::Normal
761 }
762}
763
764#[derive(Default)]
765struct SelectionHistory {
766 #[allow(clippy::type_complexity)]
767 selections_by_transaction:
768 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
769 mode: SelectionHistoryMode,
770 undo_stack: VecDeque<SelectionHistoryEntry>,
771 redo_stack: VecDeque<SelectionHistoryEntry>,
772}
773
774impl SelectionHistory {
775 fn insert_transaction(
776 &mut self,
777 transaction_id: TransactionId,
778 selections: Arc<[Selection<Anchor>]>,
779 ) {
780 self.selections_by_transaction
781 .insert(transaction_id, (selections, None));
782 }
783
784 #[allow(clippy::type_complexity)]
785 fn transaction(
786 &self,
787 transaction_id: TransactionId,
788 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
789 self.selections_by_transaction.get(&transaction_id)
790 }
791
792 #[allow(clippy::type_complexity)]
793 fn transaction_mut(
794 &mut self,
795 transaction_id: TransactionId,
796 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
797 self.selections_by_transaction.get_mut(&transaction_id)
798 }
799
800 fn push(&mut self, entry: SelectionHistoryEntry) {
801 if !entry.selections.is_empty() {
802 match self.mode {
803 SelectionHistoryMode::Normal => {
804 self.push_undo(entry);
805 self.redo_stack.clear();
806 }
807 SelectionHistoryMode::Undoing => self.push_redo(entry),
808 SelectionHistoryMode::Redoing => self.push_undo(entry),
809 }
810 }
811 }
812
813 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
814 if self
815 .undo_stack
816 .back()
817 .map_or(true, |e| e.selections != entry.selections)
818 {
819 self.undo_stack.push_back(entry);
820 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
821 self.undo_stack.pop_front();
822 }
823 }
824 }
825
826 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
827 if self
828 .redo_stack
829 .back()
830 .map_or(true, |e| e.selections != entry.selections)
831 {
832 self.redo_stack.push_back(entry);
833 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
834 self.redo_stack.pop_front();
835 }
836 }
837 }
838}
839
840struct RowHighlight {
841 index: usize,
842 range: Range<Anchor>,
843 color: Hsla,
844 should_autoscroll: bool,
845}
846
847#[derive(Clone, Debug)]
848struct AddSelectionsState {
849 above: bool,
850 stack: Vec<usize>,
851}
852
853#[derive(Clone)]
854struct SelectNextState {
855 query: AhoCorasick,
856 wordwise: bool,
857 done: bool,
858}
859
860impl std::fmt::Debug for SelectNextState {
861 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
862 f.debug_struct(std::any::type_name::<Self>())
863 .field("wordwise", &self.wordwise)
864 .field("done", &self.done)
865 .finish()
866 }
867}
868
869#[derive(Debug)]
870struct AutocloseRegion {
871 selection_id: usize,
872 range: Range<Anchor>,
873 pair: BracketPair,
874}
875
876#[derive(Debug)]
877struct SnippetState {
878 ranges: Vec<Vec<Range<Anchor>>>,
879 active_index: usize,
880 choices: Vec<Option<Vec<String>>>,
881}
882
883#[doc(hidden)]
884pub struct RenameState {
885 pub range: Range<Anchor>,
886 pub old_name: Arc<str>,
887 pub editor: View<Editor>,
888 block_id: CustomBlockId,
889}
890
891struct InvalidationStack<T>(Vec<T>);
892
893struct RegisteredInlineCompletionProvider {
894 provider: Arc<dyn InlineCompletionProviderHandle>,
895 _subscription: Subscription,
896}
897
898enum ContextMenu {
899 Completions(CompletionsMenu),
900 CodeActions(CodeActionsMenu),
901}
902
903impl ContextMenu {
904 fn select_first(
905 &mut self,
906 provider: Option<&dyn CompletionProvider>,
907 cx: &mut ViewContext<Editor>,
908 ) -> bool {
909 if self.visible() {
910 match self {
911 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
912 ContextMenu::CodeActions(menu) => menu.select_first(cx),
913 }
914 true
915 } else {
916 false
917 }
918 }
919
920 fn select_prev(
921 &mut self,
922 provider: Option<&dyn CompletionProvider>,
923 cx: &mut ViewContext<Editor>,
924 ) -> bool {
925 if self.visible() {
926 match self {
927 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
928 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
929 }
930 true
931 } else {
932 false
933 }
934 }
935
936 fn select_next(
937 &mut self,
938 provider: Option<&dyn CompletionProvider>,
939 cx: &mut ViewContext<Editor>,
940 ) -> bool {
941 if self.visible() {
942 match self {
943 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
944 ContextMenu::CodeActions(menu) => menu.select_next(cx),
945 }
946 true
947 } else {
948 false
949 }
950 }
951
952 fn select_last(
953 &mut self,
954 provider: Option<&dyn CompletionProvider>,
955 cx: &mut ViewContext<Editor>,
956 ) -> bool {
957 if self.visible() {
958 match self {
959 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
960 ContextMenu::CodeActions(menu) => menu.select_last(cx),
961 }
962 true
963 } else {
964 false
965 }
966 }
967
968 fn visible(&self) -> bool {
969 match self {
970 ContextMenu::Completions(menu) => menu.visible(),
971 ContextMenu::CodeActions(menu) => menu.visible(),
972 }
973 }
974
975 fn render(
976 &self,
977 cursor_position: DisplayPoint,
978 style: &EditorStyle,
979 max_height: Pixels,
980 workspace: Option<WeakView<Workspace>>,
981 cx: &mut ViewContext<Editor>,
982 ) -> (ContextMenuOrigin, AnyElement) {
983 match self {
984 ContextMenu::Completions(menu) => (
985 ContextMenuOrigin::EditorPoint(cursor_position),
986 menu.render(style, max_height, workspace, cx),
987 ),
988 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
989 }
990 }
991}
992
993enum ContextMenuOrigin {
994 EditorPoint(DisplayPoint),
995 GutterIndicator(DisplayRow),
996}
997
998#[derive(Clone, Debug)]
999struct CompletionsMenu {
1000 id: CompletionId,
1001 sort_completions: bool,
1002 initial_position: Anchor,
1003 buffer: Model<Buffer>,
1004 completions: Arc<RwLock<Box<[Completion]>>>,
1005 match_candidates: Arc<[StringMatchCandidate]>,
1006 matches: Arc<[StringMatch]>,
1007 selected_item: usize,
1008 scroll_handle: UniformListScrollHandle,
1009 selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
1010}
1011
1012impl CompletionsMenu {
1013 fn new(
1014 id: CompletionId,
1015 sort_completions: bool,
1016 initial_position: Anchor,
1017 buffer: Model<Buffer>,
1018 completions: Box<[Completion]>,
1019 ) -> Self {
1020 let match_candidates = completions
1021 .iter()
1022 .enumerate()
1023 .map(|(id, completion)| {
1024 StringMatchCandidate::new(
1025 id,
1026 completion.label.text[completion.label.filter_range.clone()].into(),
1027 )
1028 })
1029 .collect();
1030
1031 Self {
1032 id,
1033 sort_completions,
1034 initial_position,
1035 buffer,
1036 completions: Arc::new(RwLock::new(completions)),
1037 match_candidates,
1038 matches: Vec::new().into(),
1039 selected_item: 0,
1040 scroll_handle: UniformListScrollHandle::new(),
1041 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1042 }
1043 }
1044
1045 fn new_snippet_choices(
1046 id: CompletionId,
1047 sort_completions: bool,
1048 choices: &Vec<String>,
1049 selection: Range<Anchor>,
1050 buffer: Model<Buffer>,
1051 ) -> Self {
1052 let completions = choices
1053 .iter()
1054 .map(|choice| Completion {
1055 old_range: selection.start.text_anchor..selection.end.text_anchor,
1056 new_text: choice.to_string(),
1057 label: CodeLabel {
1058 text: choice.to_string(),
1059 runs: Default::default(),
1060 filter_range: Default::default(),
1061 },
1062 server_id: LanguageServerId(usize::MAX),
1063 documentation: None,
1064 lsp_completion: Default::default(),
1065 confirm: None,
1066 })
1067 .collect();
1068
1069 let match_candidates = choices
1070 .iter()
1071 .enumerate()
1072 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1073 .collect();
1074 let matches = choices
1075 .iter()
1076 .enumerate()
1077 .map(|(id, completion)| StringMatch {
1078 candidate_id: id,
1079 score: 1.,
1080 positions: vec![],
1081 string: completion.clone(),
1082 })
1083 .collect();
1084 Self {
1085 id,
1086 sort_completions,
1087 initial_position: selection.start,
1088 buffer,
1089 completions: Arc::new(RwLock::new(completions)),
1090 match_candidates,
1091 matches,
1092 selected_item: 0,
1093 scroll_handle: UniformListScrollHandle::new(),
1094 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1095 }
1096 }
1097
1098 fn suppress_documentation_resolution(mut self) -> Self {
1099 self.selected_completion_resolve_debounce.take();
1100 self
1101 }
1102
1103 fn select_first(
1104 &mut self,
1105 provider: Option<&dyn CompletionProvider>,
1106 cx: &mut ViewContext<Editor>,
1107 ) {
1108 self.selected_item = 0;
1109 self.scroll_handle
1110 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1111 self.resolve_selected_completion(provider, cx);
1112 cx.notify();
1113 }
1114
1115 fn select_prev(
1116 &mut self,
1117 provider: Option<&dyn CompletionProvider>,
1118 cx: &mut ViewContext<Editor>,
1119 ) {
1120 if self.selected_item > 0 {
1121 self.selected_item -= 1;
1122 } else {
1123 self.selected_item = self.matches.len() - 1;
1124 }
1125 self.scroll_handle
1126 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1127 self.resolve_selected_completion(provider, cx);
1128 cx.notify();
1129 }
1130
1131 fn select_next(
1132 &mut self,
1133 provider: Option<&dyn CompletionProvider>,
1134 cx: &mut ViewContext<Editor>,
1135 ) {
1136 if self.selected_item + 1 < self.matches.len() {
1137 self.selected_item += 1;
1138 } else {
1139 self.selected_item = 0;
1140 }
1141 self.scroll_handle
1142 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1143 self.resolve_selected_completion(provider, cx);
1144 cx.notify();
1145 }
1146
1147 fn select_last(
1148 &mut self,
1149 provider: Option<&dyn CompletionProvider>,
1150 cx: &mut ViewContext<Editor>,
1151 ) {
1152 self.selected_item = self.matches.len() - 1;
1153 self.scroll_handle
1154 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1155 self.resolve_selected_completion(provider, cx);
1156 cx.notify();
1157 }
1158
1159 fn resolve_selected_completion(
1160 &mut self,
1161 provider: Option<&dyn CompletionProvider>,
1162 cx: &mut ViewContext<Editor>,
1163 ) {
1164 let completion_index = self.matches[self.selected_item].candidate_id;
1165 let Some(provider) = provider else {
1166 return;
1167 };
1168 let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
1169 return;
1170 };
1171
1172 let resolve_task = provider.resolve_completions(
1173 self.buffer.clone(),
1174 vec![completion_index],
1175 self.completions.clone(),
1176 cx,
1177 );
1178
1179 let delay_ms =
1180 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1181 let delay = Duration::from_millis(delay_ms);
1182
1183 completion_resolve.lock().fire_new(delay, cx, |_, cx| {
1184 cx.spawn(move |editor, mut cx| async move {
1185 if let Some(true) = resolve_task.await.log_err() {
1186 editor.update(&mut cx, |_, cx| cx.notify()).ok();
1187 }
1188 })
1189 });
1190 }
1191
1192 fn visible(&self) -> bool {
1193 !self.matches.is_empty()
1194 }
1195
1196 fn render(
1197 &self,
1198 style: &EditorStyle,
1199 max_height: Pixels,
1200 workspace: Option<WeakView<Workspace>>,
1201 cx: &mut ViewContext<Editor>,
1202 ) -> AnyElement {
1203 let settings = EditorSettings::get_global(cx);
1204 let show_completion_documentation = settings.show_completion_documentation;
1205
1206 let widest_completion_ix = self
1207 .matches
1208 .iter()
1209 .enumerate()
1210 .max_by_key(|(_, mat)| {
1211 let completions = self.completions.read();
1212 let completion = &completions[mat.candidate_id];
1213 let documentation = &completion.documentation;
1214
1215 let mut len = completion.label.text.chars().count();
1216 if let Some(Documentation::SingleLine(text)) = documentation {
1217 if show_completion_documentation {
1218 len += text.chars().count();
1219 }
1220 }
1221
1222 len
1223 })
1224 .map(|(ix, _)| ix);
1225
1226 let completions = self.completions.clone();
1227 let matches = self.matches.clone();
1228 let selected_item = self.selected_item;
1229 let style = style.clone();
1230
1231 let multiline_docs = if show_completion_documentation {
1232 let mat = &self.matches[selected_item];
1233 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1234 Some(Documentation::MultiLinePlainText(text)) => {
1235 Some(div().child(SharedString::from(text.clone())))
1236 }
1237 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1238 Some(div().child(render_parsed_markdown(
1239 "completions_markdown",
1240 parsed,
1241 &style,
1242 workspace,
1243 cx,
1244 )))
1245 }
1246 _ => None,
1247 };
1248 multiline_docs.map(|div| {
1249 div.id("multiline_docs")
1250 .max_h(max_height)
1251 .flex_1()
1252 .px_1p5()
1253 .py_1()
1254 .min_w(px(260.))
1255 .max_w(px(640.))
1256 .w(px(500.))
1257 .overflow_y_scroll()
1258 .occlude()
1259 })
1260 } else {
1261 None
1262 };
1263
1264 let list = uniform_list(
1265 cx.view().clone(),
1266 "completions",
1267 matches.len(),
1268 move |_editor, range, cx| {
1269 let start_ix = range.start;
1270 let completions_guard = completions.read();
1271
1272 matches[range]
1273 .iter()
1274 .enumerate()
1275 .map(|(ix, mat)| {
1276 let item_ix = start_ix + ix;
1277 let candidate_id = mat.candidate_id;
1278 let completion = &completions_guard[candidate_id];
1279
1280 let documentation = if show_completion_documentation {
1281 &completion.documentation
1282 } else {
1283 &None
1284 };
1285
1286 let highlights = gpui::combine_highlights(
1287 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1288 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1289 |(range, mut highlight)| {
1290 // Ignore font weight for syntax highlighting, as we'll use it
1291 // for fuzzy matches.
1292 highlight.font_weight = None;
1293
1294 if completion.lsp_completion.deprecated.unwrap_or(false) {
1295 highlight.strikethrough = Some(StrikethroughStyle {
1296 thickness: 1.0.into(),
1297 ..Default::default()
1298 });
1299 highlight.color = Some(cx.theme().colors().text_muted);
1300 }
1301
1302 (range, highlight)
1303 },
1304 ),
1305 );
1306 let completion_label = StyledText::new(completion.label.text.clone())
1307 .with_highlights(&style.text, highlights);
1308 let documentation_label =
1309 if let Some(Documentation::SingleLine(text)) = documentation {
1310 if text.trim().is_empty() {
1311 None
1312 } else {
1313 Some(
1314 Label::new(text.clone())
1315 .ml_4()
1316 .size(LabelSize::Small)
1317 .color(Color::Muted),
1318 )
1319 }
1320 } else {
1321 None
1322 };
1323
1324 let color_swatch = completion
1325 .color()
1326 .map(|color| div().size_4().bg(color).rounded_sm());
1327
1328 div().min_w(px(220.)).max_w(px(540.)).child(
1329 ListItem::new(mat.candidate_id)
1330 .inset(true)
1331 .selected(item_ix == selected_item)
1332 .on_click(cx.listener(move |editor, _event, cx| {
1333 cx.stop_propagation();
1334 if let Some(task) = editor.confirm_completion(
1335 &ConfirmCompletion {
1336 item_ix: Some(item_ix),
1337 },
1338 cx,
1339 ) {
1340 task.detach_and_log_err(cx)
1341 }
1342 }))
1343 .start_slot::<Div>(color_swatch)
1344 .child(h_flex().overflow_hidden().child(completion_label))
1345 .end_slot::<Label>(documentation_label),
1346 )
1347 })
1348 .collect()
1349 },
1350 )
1351 .occlude()
1352 .max_h(max_height)
1353 .track_scroll(self.scroll_handle.clone())
1354 .with_width_from_item(widest_completion_ix)
1355 .with_sizing_behavior(ListSizingBehavior::Infer);
1356
1357 Popover::new()
1358 .child(list)
1359 .when_some(multiline_docs, |popover, multiline_docs| {
1360 popover.aside(multiline_docs)
1361 })
1362 .into_any_element()
1363 }
1364
1365 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1366 let mut matches = if let Some(query) = query {
1367 fuzzy::match_strings(
1368 &self.match_candidates,
1369 query,
1370 query.chars().any(|c| c.is_uppercase()),
1371 100,
1372 &Default::default(),
1373 executor,
1374 )
1375 .await
1376 } else {
1377 self.match_candidates
1378 .iter()
1379 .enumerate()
1380 .map(|(candidate_id, candidate)| StringMatch {
1381 candidate_id,
1382 score: Default::default(),
1383 positions: Default::default(),
1384 string: candidate.string.clone(),
1385 })
1386 .collect()
1387 };
1388
1389 // Remove all candidates where the query's start does not match the start of any word in the candidate
1390 if let Some(query) = query {
1391 if let Some(query_start) = query.chars().next() {
1392 matches.retain(|string_match| {
1393 split_words(&string_match.string).any(|word| {
1394 // Check that the first codepoint of the word as lowercase matches the first
1395 // codepoint of the query as lowercase
1396 word.chars()
1397 .flat_map(|codepoint| codepoint.to_lowercase())
1398 .zip(query_start.to_lowercase())
1399 .all(|(word_cp, query_cp)| word_cp == query_cp)
1400 })
1401 });
1402 }
1403 }
1404
1405 let completions = self.completions.read();
1406 if self.sort_completions {
1407 matches.sort_unstable_by_key(|mat| {
1408 // We do want to strike a balance here between what the language server tells us
1409 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1410 // `Creat` and there is a local variable called `CreateComponent`).
1411 // So what we do is: we bucket all matches into two buckets
1412 // - Strong matches
1413 // - Weak matches
1414 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1415 // and the Weak matches are the rest.
1416 //
1417 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1418 // matches, we prefer language-server sort_text first.
1419 //
1420 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1421 // Rest of the matches(weak) can be sorted as language-server expects.
1422
1423 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1424 enum MatchScore<'a> {
1425 Strong {
1426 score: Reverse<OrderedFloat<f64>>,
1427 sort_text: Option<&'a str>,
1428 sort_key: (usize, &'a str),
1429 },
1430 Weak {
1431 sort_text: Option<&'a str>,
1432 score: Reverse<OrderedFloat<f64>>,
1433 sort_key: (usize, &'a str),
1434 },
1435 }
1436
1437 let completion = &completions[mat.candidate_id];
1438 let sort_key = completion.sort_key();
1439 let sort_text = completion.lsp_completion.sort_text.as_deref();
1440 let score = Reverse(OrderedFloat(mat.score));
1441
1442 if mat.score >= 0.2 {
1443 MatchScore::Strong {
1444 score,
1445 sort_text,
1446 sort_key,
1447 }
1448 } else {
1449 MatchScore::Weak {
1450 sort_text,
1451 score,
1452 sort_key,
1453 }
1454 }
1455 });
1456 }
1457
1458 for mat in &mut matches {
1459 let completion = &completions[mat.candidate_id];
1460 mat.string.clone_from(&completion.label.text);
1461 for position in &mut mat.positions {
1462 *position += completion.label.filter_range.start;
1463 }
1464 }
1465 drop(completions);
1466
1467 self.matches = matches.into();
1468 self.selected_item = 0;
1469 }
1470}
1471
1472#[derive(Clone)]
1473struct AvailableCodeAction {
1474 excerpt_id: ExcerptId,
1475 action: CodeAction,
1476 provider: Arc<dyn CodeActionProvider>,
1477}
1478
1479#[derive(Clone)]
1480struct CodeActionContents {
1481 tasks: Option<Arc<ResolvedTasks>>,
1482 actions: Option<Arc<[AvailableCodeAction]>>,
1483}
1484
1485impl CodeActionContents {
1486 fn len(&self) -> usize {
1487 match (&self.tasks, &self.actions) {
1488 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1489 (Some(tasks), None) => tasks.templates.len(),
1490 (None, Some(actions)) => actions.len(),
1491 (None, None) => 0,
1492 }
1493 }
1494
1495 fn is_empty(&self) -> bool {
1496 match (&self.tasks, &self.actions) {
1497 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1498 (Some(tasks), None) => tasks.templates.is_empty(),
1499 (None, Some(actions)) => actions.is_empty(),
1500 (None, None) => true,
1501 }
1502 }
1503
1504 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1505 self.tasks
1506 .iter()
1507 .flat_map(|tasks| {
1508 tasks
1509 .templates
1510 .iter()
1511 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1512 })
1513 .chain(self.actions.iter().flat_map(|actions| {
1514 actions.iter().map(|available| CodeActionsItem::CodeAction {
1515 excerpt_id: available.excerpt_id,
1516 action: available.action.clone(),
1517 provider: available.provider.clone(),
1518 })
1519 }))
1520 }
1521 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1522 match (&self.tasks, &self.actions) {
1523 (Some(tasks), Some(actions)) => {
1524 if index < tasks.templates.len() {
1525 tasks
1526 .templates
1527 .get(index)
1528 .cloned()
1529 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1530 } else {
1531 actions.get(index - tasks.templates.len()).map(|available| {
1532 CodeActionsItem::CodeAction {
1533 excerpt_id: available.excerpt_id,
1534 action: available.action.clone(),
1535 provider: available.provider.clone(),
1536 }
1537 })
1538 }
1539 }
1540 (Some(tasks), None) => tasks
1541 .templates
1542 .get(index)
1543 .cloned()
1544 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1545 (None, Some(actions)) => {
1546 actions
1547 .get(index)
1548 .map(|available| CodeActionsItem::CodeAction {
1549 excerpt_id: available.excerpt_id,
1550 action: available.action.clone(),
1551 provider: available.provider.clone(),
1552 })
1553 }
1554 (None, None) => None,
1555 }
1556 }
1557}
1558
1559#[allow(clippy::large_enum_variant)]
1560#[derive(Clone)]
1561enum CodeActionsItem {
1562 Task(TaskSourceKind, ResolvedTask),
1563 CodeAction {
1564 excerpt_id: ExcerptId,
1565 action: CodeAction,
1566 provider: Arc<dyn CodeActionProvider>,
1567 },
1568}
1569
1570impl CodeActionsItem {
1571 fn as_task(&self) -> Option<&ResolvedTask> {
1572 let Self::Task(_, task) = self else {
1573 return None;
1574 };
1575 Some(task)
1576 }
1577 fn as_code_action(&self) -> Option<&CodeAction> {
1578 let Self::CodeAction { action, .. } = self else {
1579 return None;
1580 };
1581 Some(action)
1582 }
1583 fn label(&self) -> String {
1584 match self {
1585 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1586 Self::Task(_, task) => task.resolved_label.clone(),
1587 }
1588 }
1589}
1590
1591struct CodeActionsMenu {
1592 actions: CodeActionContents,
1593 buffer: Model<Buffer>,
1594 selected_item: usize,
1595 scroll_handle: UniformListScrollHandle,
1596 deployed_from_indicator: Option<DisplayRow>,
1597}
1598
1599impl CodeActionsMenu {
1600 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1601 self.selected_item = 0;
1602 self.scroll_handle
1603 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1604 cx.notify()
1605 }
1606
1607 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1608 if self.selected_item > 0 {
1609 self.selected_item -= 1;
1610 } else {
1611 self.selected_item = self.actions.len() - 1;
1612 }
1613 self.scroll_handle
1614 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1615 cx.notify();
1616 }
1617
1618 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1619 if self.selected_item + 1 < self.actions.len() {
1620 self.selected_item += 1;
1621 } else {
1622 self.selected_item = 0;
1623 }
1624 self.scroll_handle
1625 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1626 cx.notify();
1627 }
1628
1629 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1630 self.selected_item = self.actions.len() - 1;
1631 self.scroll_handle
1632 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1633 cx.notify()
1634 }
1635
1636 fn visible(&self) -> bool {
1637 !self.actions.is_empty()
1638 }
1639
1640 fn render(
1641 &self,
1642 cursor_position: DisplayPoint,
1643 _style: &EditorStyle,
1644 max_height: Pixels,
1645 cx: &mut ViewContext<Editor>,
1646 ) -> (ContextMenuOrigin, AnyElement) {
1647 let actions = self.actions.clone();
1648 let selected_item = self.selected_item;
1649 let element = uniform_list(
1650 cx.view().clone(),
1651 "code_actions_menu",
1652 self.actions.len(),
1653 move |_this, range, cx| {
1654 actions
1655 .iter()
1656 .skip(range.start)
1657 .take(range.end - range.start)
1658 .enumerate()
1659 .map(|(ix, action)| {
1660 let item_ix = range.start + ix;
1661 let selected = selected_item == item_ix;
1662 let colors = cx.theme().colors();
1663 div()
1664 .px_1()
1665 .rounded_md()
1666 .text_color(colors.text)
1667 .when(selected, |style| {
1668 style
1669 .bg(colors.element_active)
1670 .text_color(colors.text_accent)
1671 })
1672 .hover(|style| {
1673 style
1674 .bg(colors.element_hover)
1675 .text_color(colors.text_accent)
1676 })
1677 .whitespace_nowrap()
1678 .when_some(action.as_code_action(), |this, action| {
1679 this.on_mouse_down(
1680 MouseButton::Left,
1681 cx.listener(move |editor, _, cx| {
1682 cx.stop_propagation();
1683 if let Some(task) = editor.confirm_code_action(
1684 &ConfirmCodeAction {
1685 item_ix: Some(item_ix),
1686 },
1687 cx,
1688 ) {
1689 task.detach_and_log_err(cx)
1690 }
1691 }),
1692 )
1693 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1694 .child(SharedString::from(
1695 action.lsp_action.title.replace("\n", ""),
1696 ))
1697 })
1698 .when_some(action.as_task(), |this, task| {
1699 this.on_mouse_down(
1700 MouseButton::Left,
1701 cx.listener(move |editor, _, cx| {
1702 cx.stop_propagation();
1703 if let Some(task) = editor.confirm_code_action(
1704 &ConfirmCodeAction {
1705 item_ix: Some(item_ix),
1706 },
1707 cx,
1708 ) {
1709 task.detach_and_log_err(cx)
1710 }
1711 }),
1712 )
1713 .child(SharedString::from(task.resolved_label.replace("\n", "")))
1714 })
1715 })
1716 .collect()
1717 },
1718 )
1719 .elevation_1(cx)
1720 .p_1()
1721 .max_h(max_height)
1722 .occlude()
1723 .track_scroll(self.scroll_handle.clone())
1724 .with_width_from_item(
1725 self.actions
1726 .iter()
1727 .enumerate()
1728 .max_by_key(|(_, action)| match action {
1729 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1730 CodeActionsItem::CodeAction { action, .. } => {
1731 action.lsp_action.title.chars().count()
1732 }
1733 })
1734 .map(|(ix, _)| ix),
1735 )
1736 .with_sizing_behavior(ListSizingBehavior::Infer)
1737 .into_any_element();
1738
1739 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1740 ContextMenuOrigin::GutterIndicator(row)
1741 } else {
1742 ContextMenuOrigin::EditorPoint(cursor_position)
1743 };
1744
1745 (cursor_position, element)
1746 }
1747}
1748
1749#[derive(Debug)]
1750struct ActiveDiagnosticGroup {
1751 primary_range: Range<Anchor>,
1752 primary_message: String,
1753 group_id: usize,
1754 blocks: HashMap<CustomBlockId, Diagnostic>,
1755 is_valid: bool,
1756}
1757
1758#[derive(Serialize, Deserialize, Clone, Debug)]
1759pub struct ClipboardSelection {
1760 pub len: usize,
1761 pub is_entire_line: bool,
1762 pub first_line_indent: u32,
1763}
1764
1765#[derive(Debug)]
1766pub(crate) struct NavigationData {
1767 cursor_anchor: Anchor,
1768 cursor_position: Point,
1769 scroll_anchor: ScrollAnchor,
1770 scroll_top_row: u32,
1771}
1772
1773#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1774pub enum GotoDefinitionKind {
1775 Symbol,
1776 Declaration,
1777 Type,
1778 Implementation,
1779}
1780
1781#[derive(Debug, Clone)]
1782enum InlayHintRefreshReason {
1783 Toggle(bool),
1784 SettingsChange(InlayHintSettings),
1785 NewLinesShown,
1786 BufferEdited(HashSet<Arc<Language>>),
1787 RefreshRequested,
1788 ExcerptsRemoved(Vec<ExcerptId>),
1789}
1790
1791impl InlayHintRefreshReason {
1792 fn description(&self) -> &'static str {
1793 match self {
1794 Self::Toggle(_) => "toggle",
1795 Self::SettingsChange(_) => "settings change",
1796 Self::NewLinesShown => "new lines shown",
1797 Self::BufferEdited(_) => "buffer edited",
1798 Self::RefreshRequested => "refresh requested",
1799 Self::ExcerptsRemoved(_) => "excerpts removed",
1800 }
1801 }
1802}
1803
1804pub(crate) struct FocusedBlock {
1805 id: BlockId,
1806 focus_handle: WeakFocusHandle,
1807}
1808
1809#[derive(Clone)]
1810struct JumpData {
1811 excerpt_id: ExcerptId,
1812 position: Point,
1813 anchor: text::Anchor,
1814 path: Option<project::ProjectPath>,
1815 line_offset_from_top: u32,
1816}
1817
1818impl Editor {
1819 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1820 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1821 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1822 Self::new(
1823 EditorMode::SingleLine { auto_width: false },
1824 buffer,
1825 None,
1826 false,
1827 cx,
1828 )
1829 }
1830
1831 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1832 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1833 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1834 Self::new(EditorMode::Full, buffer, None, false, cx)
1835 }
1836
1837 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1838 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1839 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1840 Self::new(
1841 EditorMode::SingleLine { auto_width: true },
1842 buffer,
1843 None,
1844 false,
1845 cx,
1846 )
1847 }
1848
1849 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1850 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1851 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1852 Self::new(
1853 EditorMode::AutoHeight { max_lines },
1854 buffer,
1855 None,
1856 false,
1857 cx,
1858 )
1859 }
1860
1861 pub fn for_buffer(
1862 buffer: Model<Buffer>,
1863 project: Option<Model<Project>>,
1864 cx: &mut ViewContext<Self>,
1865 ) -> Self {
1866 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1867 Self::new(EditorMode::Full, buffer, project, false, cx)
1868 }
1869
1870 pub fn for_multibuffer(
1871 buffer: Model<MultiBuffer>,
1872 project: Option<Model<Project>>,
1873 show_excerpt_controls: bool,
1874 cx: &mut ViewContext<Self>,
1875 ) -> Self {
1876 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1877 }
1878
1879 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1880 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1881 let mut clone = Self::new(
1882 self.mode,
1883 self.buffer.clone(),
1884 self.project.clone(),
1885 show_excerpt_controls,
1886 cx,
1887 );
1888 self.display_map.update(cx, |display_map, cx| {
1889 let snapshot = display_map.snapshot(cx);
1890 clone.display_map.update(cx, |display_map, cx| {
1891 display_map.set_state(&snapshot, cx);
1892 });
1893 });
1894 clone.selections.clone_state(&self.selections);
1895 clone.scroll_manager.clone_state(&self.scroll_manager);
1896 clone.searchable = self.searchable;
1897 clone
1898 }
1899
1900 pub fn new(
1901 mode: EditorMode,
1902 buffer: Model<MultiBuffer>,
1903 project: Option<Model<Project>>,
1904 show_excerpt_controls: bool,
1905 cx: &mut ViewContext<Self>,
1906 ) -> Self {
1907 let style = cx.text_style();
1908 let font_size = style.font_size.to_pixels(cx.rem_size());
1909 let editor = cx.view().downgrade();
1910 let fold_placeholder = FoldPlaceholder {
1911 constrain_width: true,
1912 render: Arc::new(move |fold_id, fold_range, cx| {
1913 let editor = editor.clone();
1914 div()
1915 .id(fold_id)
1916 .bg(cx.theme().colors().ghost_element_background)
1917 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1918 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1919 .rounded_sm()
1920 .size_full()
1921 .cursor_pointer()
1922 .child("⋯")
1923 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1924 .on_click(move |_, cx| {
1925 editor
1926 .update(cx, |editor, cx| {
1927 editor.unfold_ranges(
1928 &[fold_range.start..fold_range.end],
1929 true,
1930 false,
1931 cx,
1932 );
1933 cx.stop_propagation();
1934 })
1935 .ok();
1936 })
1937 .into_any()
1938 }),
1939 merge_adjacent: true,
1940 ..Default::default()
1941 };
1942 let display_map = cx.new_model(|cx| {
1943 DisplayMap::new(
1944 buffer.clone(),
1945 style.font(),
1946 font_size,
1947 None,
1948 show_excerpt_controls,
1949 FILE_HEADER_HEIGHT,
1950 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1951 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1952 fold_placeholder,
1953 cx,
1954 )
1955 });
1956
1957 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1958
1959 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1960
1961 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1962 .then(|| language_settings::SoftWrap::None);
1963
1964 let mut project_subscriptions = Vec::new();
1965 if mode == EditorMode::Full {
1966 if let Some(project) = project.as_ref() {
1967 if buffer.read(cx).is_singleton() {
1968 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1969 cx.emit(EditorEvent::TitleChanged);
1970 }));
1971 }
1972 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1973 if let project::Event::RefreshInlayHints = event {
1974 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1975 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1976 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1977 let focus_handle = editor.focus_handle(cx);
1978 if focus_handle.is_focused(cx) {
1979 let snapshot = buffer.read(cx).snapshot();
1980 for (range, snippet) in snippet_edits {
1981 let editor_range =
1982 language::range_from_lsp(*range).to_offset(&snapshot);
1983 editor
1984 .insert_snippet(&[editor_range], snippet.clone(), cx)
1985 .ok();
1986 }
1987 }
1988 }
1989 }
1990 }));
1991 if let Some(task_inventory) = project
1992 .read(cx)
1993 .task_store()
1994 .read(cx)
1995 .task_inventory()
1996 .cloned()
1997 {
1998 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1999 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
2000 }));
2001 }
2002 }
2003 }
2004
2005 let inlay_hint_settings = inlay_hint_settings(
2006 selections.newest_anchor().head(),
2007 &buffer.read(cx).snapshot(cx),
2008 cx,
2009 );
2010 let focus_handle = cx.focus_handle();
2011 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2012 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2013 .detach();
2014 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2015 .detach();
2016 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2017
2018 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2019 Some(false)
2020 } else {
2021 None
2022 };
2023
2024 let mut code_action_providers = Vec::new();
2025 if let Some(project) = project.clone() {
2026 code_action_providers.push(Arc::new(project) as Arc<_>);
2027 }
2028
2029 let mut this = Self {
2030 focus_handle,
2031 show_cursor_when_unfocused: false,
2032 last_focused_descendant: None,
2033 buffer: buffer.clone(),
2034 display_map: display_map.clone(),
2035 selections,
2036 scroll_manager: ScrollManager::new(cx),
2037 columnar_selection_tail: None,
2038 add_selections_state: None,
2039 select_next_state: None,
2040 select_prev_state: None,
2041 selection_history: Default::default(),
2042 autoclose_regions: Default::default(),
2043 snippet_stack: Default::default(),
2044 select_larger_syntax_node_stack: Vec::new(),
2045 ime_transaction: Default::default(),
2046 active_diagnostics: None,
2047 soft_wrap_mode_override,
2048 completion_provider: project.clone().map(|project| Box::new(project) as _),
2049 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2050 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2051 project,
2052 blink_manager: blink_manager.clone(),
2053 show_local_selections: true,
2054 mode,
2055 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2056 show_gutter: mode == EditorMode::Full,
2057 show_line_numbers: None,
2058 use_relative_line_numbers: None,
2059 show_git_diff_gutter: None,
2060 show_code_actions: None,
2061 show_runnables: None,
2062 show_wrap_guides: None,
2063 show_indent_guides,
2064 placeholder_text: None,
2065 highlight_order: 0,
2066 highlighted_rows: HashMap::default(),
2067 background_highlights: Default::default(),
2068 gutter_highlights: TreeMap::default(),
2069 scrollbar_marker_state: ScrollbarMarkerState::default(),
2070 active_indent_guides_state: ActiveIndentGuidesState::default(),
2071 nav_history: None,
2072 context_menu: RwLock::new(None),
2073 mouse_context_menu: None,
2074 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2075 completion_tasks: Default::default(),
2076 signature_help_state: SignatureHelpState::default(),
2077 auto_signature_help: None,
2078 find_all_references_task_sources: Vec::new(),
2079 next_completion_id: 0,
2080 next_inlay_id: 0,
2081 code_action_providers,
2082 available_code_actions: Default::default(),
2083 code_actions_task: Default::default(),
2084 document_highlights_task: Default::default(),
2085 linked_editing_range_task: Default::default(),
2086 pending_rename: Default::default(),
2087 searchable: true,
2088 cursor_shape: EditorSettings::get_global(cx)
2089 .cursor_shape
2090 .unwrap_or_default(),
2091 current_line_highlight: None,
2092 autoindent_mode: Some(AutoindentMode::EachLine),
2093 collapse_matches: false,
2094 workspace: None,
2095 input_enabled: true,
2096 use_modal_editing: mode == EditorMode::Full,
2097 read_only: false,
2098 use_autoclose: true,
2099 use_auto_surround: true,
2100 auto_replace_emoji_shortcode: false,
2101 leader_peer_id: None,
2102 remote_id: None,
2103 hover_state: Default::default(),
2104 hovered_link_state: Default::default(),
2105 inline_completion_provider: None,
2106 active_inline_completion: None,
2107 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2108 expanded_hunks: ExpandedHunks::default(),
2109 gutter_hovered: false,
2110 pixel_position_of_newest_cursor: None,
2111 last_bounds: None,
2112 expect_bounds_change: None,
2113 gutter_dimensions: GutterDimensions::default(),
2114 style: None,
2115 show_cursor_names: false,
2116 hovered_cursors: Default::default(),
2117 next_editor_action_id: EditorActionId::default(),
2118 editor_actions: Rc::default(),
2119 show_inline_completions_override: None,
2120 enable_inline_completions: true,
2121 custom_context_menu: None,
2122 show_git_blame_gutter: false,
2123 show_git_blame_inline: false,
2124 show_selection_menu: None,
2125 show_git_blame_inline_delay_task: None,
2126 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2127 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2128 .session
2129 .restore_unsaved_buffers,
2130 blame: None,
2131 blame_subscription: None,
2132 tasks: Default::default(),
2133 _subscriptions: vec![
2134 cx.observe(&buffer, Self::on_buffer_changed),
2135 cx.subscribe(&buffer, Self::on_buffer_event),
2136 cx.observe(&display_map, Self::on_display_map_changed),
2137 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2138 cx.observe_global::<SettingsStore>(Self::settings_changed),
2139 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2140 cx.observe_window_activation(|editor, cx| {
2141 let active = cx.is_window_active();
2142 editor.blink_manager.update(cx, |blink_manager, cx| {
2143 if active {
2144 blink_manager.enable(cx);
2145 } else {
2146 blink_manager.disable(cx);
2147 }
2148 });
2149 }),
2150 ],
2151 tasks_update_task: None,
2152 linked_edit_ranges: Default::default(),
2153 previous_search_ranges: None,
2154 breadcrumb_header: None,
2155 focused_block: None,
2156 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2157 addons: HashMap::default(),
2158 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2159 text_style_refinement: None,
2160 };
2161 this.tasks_update_task = Some(this.refresh_runnables(cx));
2162 this._subscriptions.extend(project_subscriptions);
2163
2164 this.end_selection(cx);
2165 this.scroll_manager.show_scrollbar(cx);
2166
2167 if mode == EditorMode::Full {
2168 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2169 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2170
2171 if this.git_blame_inline_enabled {
2172 this.git_blame_inline_enabled = true;
2173 this.start_git_blame_inline(false, cx);
2174 }
2175 }
2176
2177 this.report_editor_event("open", None, cx);
2178 this
2179 }
2180
2181 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2182 self.mouse_context_menu
2183 .as_ref()
2184 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2185 }
2186
2187 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2188 let mut key_context = KeyContext::new_with_defaults();
2189 key_context.add("Editor");
2190 let mode = match self.mode {
2191 EditorMode::SingleLine { .. } => "single_line",
2192 EditorMode::AutoHeight { .. } => "auto_height",
2193 EditorMode::Full => "full",
2194 };
2195
2196 if EditorSettings::jupyter_enabled(cx) {
2197 key_context.add("jupyter");
2198 }
2199
2200 key_context.set("mode", mode);
2201 if self.pending_rename.is_some() {
2202 key_context.add("renaming");
2203 }
2204 if self.context_menu_visible() {
2205 match self.context_menu.read().as_ref() {
2206 Some(ContextMenu::Completions(_)) => {
2207 key_context.add("menu");
2208 key_context.add("showing_completions")
2209 }
2210 Some(ContextMenu::CodeActions(_)) => {
2211 key_context.add("menu");
2212 key_context.add("showing_code_actions")
2213 }
2214 None => {}
2215 }
2216 }
2217
2218 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2219 if !self.focus_handle(cx).contains_focused(cx)
2220 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2221 {
2222 for addon in self.addons.values() {
2223 addon.extend_key_context(&mut key_context, cx)
2224 }
2225 }
2226
2227 if let Some(extension) = self
2228 .buffer
2229 .read(cx)
2230 .as_singleton()
2231 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2232 {
2233 key_context.set("extension", extension.to_string());
2234 }
2235
2236 if self.has_active_inline_completion(cx) {
2237 key_context.add("copilot_suggestion");
2238 key_context.add("inline_completion");
2239 }
2240
2241 key_context
2242 }
2243
2244 pub fn new_file(
2245 workspace: &mut Workspace,
2246 _: &workspace::NewFile,
2247 cx: &mut ViewContext<Workspace>,
2248 ) {
2249 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2250 "Failed to create buffer",
2251 cx,
2252 |e, _| match e.error_code() {
2253 ErrorCode::RemoteUpgradeRequired => Some(format!(
2254 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2255 e.error_tag("required").unwrap_or("the latest version")
2256 )),
2257 _ => None,
2258 },
2259 );
2260 }
2261
2262 pub fn new_in_workspace(
2263 workspace: &mut Workspace,
2264 cx: &mut ViewContext<Workspace>,
2265 ) -> Task<Result<View<Editor>>> {
2266 let project = workspace.project().clone();
2267 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2268
2269 cx.spawn(|workspace, mut cx| async move {
2270 let buffer = create.await?;
2271 workspace.update(&mut cx, |workspace, cx| {
2272 let editor =
2273 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2274 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2275 editor
2276 })
2277 })
2278 }
2279
2280 fn new_file_vertical(
2281 workspace: &mut Workspace,
2282 _: &workspace::NewFileSplitVertical,
2283 cx: &mut ViewContext<Workspace>,
2284 ) {
2285 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2286 }
2287
2288 fn new_file_horizontal(
2289 workspace: &mut Workspace,
2290 _: &workspace::NewFileSplitHorizontal,
2291 cx: &mut ViewContext<Workspace>,
2292 ) {
2293 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2294 }
2295
2296 fn new_file_in_direction(
2297 workspace: &mut Workspace,
2298 direction: SplitDirection,
2299 cx: &mut ViewContext<Workspace>,
2300 ) {
2301 let project = workspace.project().clone();
2302 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2303
2304 cx.spawn(|workspace, mut cx| async move {
2305 let buffer = create.await?;
2306 workspace.update(&mut cx, move |workspace, cx| {
2307 workspace.split_item(
2308 direction,
2309 Box::new(
2310 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2311 ),
2312 cx,
2313 )
2314 })?;
2315 anyhow::Ok(())
2316 })
2317 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2318 ErrorCode::RemoteUpgradeRequired => Some(format!(
2319 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2320 e.error_tag("required").unwrap_or("the latest version")
2321 )),
2322 _ => None,
2323 });
2324 }
2325
2326 pub fn leader_peer_id(&self) -> Option<PeerId> {
2327 self.leader_peer_id
2328 }
2329
2330 pub fn buffer(&self) -> &Model<MultiBuffer> {
2331 &self.buffer
2332 }
2333
2334 pub fn workspace(&self) -> Option<View<Workspace>> {
2335 self.workspace.as_ref()?.0.upgrade()
2336 }
2337
2338 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2339 self.buffer().read(cx).title(cx)
2340 }
2341
2342 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2343 let git_blame_gutter_max_author_length = self
2344 .render_git_blame_gutter(cx)
2345 .then(|| {
2346 if let Some(blame) = self.blame.as_ref() {
2347 let max_author_length =
2348 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2349 Some(max_author_length)
2350 } else {
2351 None
2352 }
2353 })
2354 .flatten();
2355
2356 EditorSnapshot {
2357 mode: self.mode,
2358 show_gutter: self.show_gutter,
2359 show_line_numbers: self.show_line_numbers,
2360 show_git_diff_gutter: self.show_git_diff_gutter,
2361 show_code_actions: self.show_code_actions,
2362 show_runnables: self.show_runnables,
2363 git_blame_gutter_max_author_length,
2364 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2365 scroll_anchor: self.scroll_manager.anchor(),
2366 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2367 placeholder_text: self.placeholder_text.clone(),
2368 is_focused: self.focus_handle.is_focused(cx),
2369 current_line_highlight: self
2370 .current_line_highlight
2371 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2372 gutter_hovered: self.gutter_hovered,
2373 }
2374 }
2375
2376 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2377 self.buffer.read(cx).language_at(point, cx)
2378 }
2379
2380 pub fn file_at<T: ToOffset>(
2381 &self,
2382 point: T,
2383 cx: &AppContext,
2384 ) -> Option<Arc<dyn language::File>> {
2385 self.buffer.read(cx).read(cx).file_at(point).cloned()
2386 }
2387
2388 pub fn active_excerpt(
2389 &self,
2390 cx: &AppContext,
2391 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2392 self.buffer
2393 .read(cx)
2394 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2395 }
2396
2397 pub fn mode(&self) -> EditorMode {
2398 self.mode
2399 }
2400
2401 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2402 self.collaboration_hub.as_deref()
2403 }
2404
2405 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2406 self.collaboration_hub = Some(hub);
2407 }
2408
2409 pub fn set_custom_context_menu(
2410 &mut self,
2411 f: impl 'static
2412 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2413 ) {
2414 self.custom_context_menu = Some(Box::new(f))
2415 }
2416
2417 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2418 self.completion_provider = provider;
2419 }
2420
2421 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2422 self.semantics_provider.clone()
2423 }
2424
2425 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2426 self.semantics_provider = provider;
2427 }
2428
2429 pub fn set_inline_completion_provider<T>(
2430 &mut self,
2431 provider: Option<Model<T>>,
2432 cx: &mut ViewContext<Self>,
2433 ) where
2434 T: InlineCompletionProvider,
2435 {
2436 self.inline_completion_provider =
2437 provider.map(|provider| RegisteredInlineCompletionProvider {
2438 _subscription: cx.observe(&provider, |this, _, cx| {
2439 if this.focus_handle.is_focused(cx) {
2440 this.update_visible_inline_completion(cx);
2441 }
2442 }),
2443 provider: Arc::new(provider),
2444 });
2445 self.refresh_inline_completion(false, false, cx);
2446 }
2447
2448 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2449 self.placeholder_text.as_deref()
2450 }
2451
2452 pub fn set_placeholder_text(
2453 &mut self,
2454 placeholder_text: impl Into<Arc<str>>,
2455 cx: &mut ViewContext<Self>,
2456 ) {
2457 let placeholder_text = Some(placeholder_text.into());
2458 if self.placeholder_text != placeholder_text {
2459 self.placeholder_text = placeholder_text;
2460 cx.notify();
2461 }
2462 }
2463
2464 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2465 self.cursor_shape = cursor_shape;
2466
2467 // Disrupt blink for immediate user feedback that the cursor shape has changed
2468 self.blink_manager.update(cx, BlinkManager::show_cursor);
2469
2470 cx.notify();
2471 }
2472
2473 pub fn set_current_line_highlight(
2474 &mut self,
2475 current_line_highlight: Option<CurrentLineHighlight>,
2476 ) {
2477 self.current_line_highlight = current_line_highlight;
2478 }
2479
2480 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2481 self.collapse_matches = collapse_matches;
2482 }
2483
2484 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2485 if self.collapse_matches {
2486 return range.start..range.start;
2487 }
2488 range.clone()
2489 }
2490
2491 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2492 if self.display_map.read(cx).clip_at_line_ends != clip {
2493 self.display_map
2494 .update(cx, |map, _| map.clip_at_line_ends = clip);
2495 }
2496 }
2497
2498 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2499 self.input_enabled = input_enabled;
2500 }
2501
2502 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2503 self.enable_inline_completions = enabled;
2504 }
2505
2506 pub fn set_autoindent(&mut self, autoindent: bool) {
2507 if autoindent {
2508 self.autoindent_mode = Some(AutoindentMode::EachLine);
2509 } else {
2510 self.autoindent_mode = None;
2511 }
2512 }
2513
2514 pub fn read_only(&self, cx: &AppContext) -> bool {
2515 self.read_only || self.buffer.read(cx).read_only()
2516 }
2517
2518 pub fn set_read_only(&mut self, read_only: bool) {
2519 self.read_only = read_only;
2520 }
2521
2522 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2523 self.use_autoclose = autoclose;
2524 }
2525
2526 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2527 self.use_auto_surround = auto_surround;
2528 }
2529
2530 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2531 self.auto_replace_emoji_shortcode = auto_replace;
2532 }
2533
2534 pub fn toggle_inline_completions(
2535 &mut self,
2536 _: &ToggleInlineCompletions,
2537 cx: &mut ViewContext<Self>,
2538 ) {
2539 if self.show_inline_completions_override.is_some() {
2540 self.set_show_inline_completions(None, cx);
2541 } else {
2542 let cursor = self.selections.newest_anchor().head();
2543 if let Some((buffer, cursor_buffer_position)) =
2544 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2545 {
2546 let show_inline_completions =
2547 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2548 self.set_show_inline_completions(Some(show_inline_completions), cx);
2549 }
2550 }
2551 }
2552
2553 pub fn set_show_inline_completions(
2554 &mut self,
2555 show_inline_completions: Option<bool>,
2556 cx: &mut ViewContext<Self>,
2557 ) {
2558 self.show_inline_completions_override = show_inline_completions;
2559 self.refresh_inline_completion(false, true, cx);
2560 }
2561
2562 fn should_show_inline_completions(
2563 &self,
2564 buffer: &Model<Buffer>,
2565 buffer_position: language::Anchor,
2566 cx: &AppContext,
2567 ) -> bool {
2568 if !self.snippet_stack.is_empty() {
2569 return false;
2570 }
2571
2572 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2573 return false;
2574 }
2575
2576 if let Some(provider) = self.inline_completion_provider() {
2577 if let Some(show_inline_completions) = self.show_inline_completions_override {
2578 show_inline_completions
2579 } else {
2580 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2581 }
2582 } else {
2583 false
2584 }
2585 }
2586
2587 fn inline_completions_disabled_in_scope(
2588 &self,
2589 buffer: &Model<Buffer>,
2590 buffer_position: language::Anchor,
2591 cx: &AppContext,
2592 ) -> bool {
2593 let snapshot = buffer.read(cx).snapshot();
2594 let settings = snapshot.settings_at(buffer_position, cx);
2595
2596 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2597 return false;
2598 };
2599
2600 scope.override_name().map_or(false, |scope_name| {
2601 settings
2602 .inline_completions_disabled_in
2603 .iter()
2604 .any(|s| s == scope_name)
2605 })
2606 }
2607
2608 pub fn set_use_modal_editing(&mut self, to: bool) {
2609 self.use_modal_editing = to;
2610 }
2611
2612 pub fn use_modal_editing(&self) -> bool {
2613 self.use_modal_editing
2614 }
2615
2616 fn selections_did_change(
2617 &mut self,
2618 local: bool,
2619 old_cursor_position: &Anchor,
2620 show_completions: bool,
2621 cx: &mut ViewContext<Self>,
2622 ) {
2623 cx.invalidate_character_coordinates();
2624
2625 // Copy selections to primary selection buffer
2626 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2627 if local {
2628 let selections = self.selections.all::<usize>(cx);
2629 let buffer_handle = self.buffer.read(cx).read(cx);
2630
2631 let mut text = String::new();
2632 for (index, selection) in selections.iter().enumerate() {
2633 let text_for_selection = buffer_handle
2634 .text_for_range(selection.start..selection.end)
2635 .collect::<String>();
2636
2637 text.push_str(&text_for_selection);
2638 if index != selections.len() - 1 {
2639 text.push('\n');
2640 }
2641 }
2642
2643 if !text.is_empty() {
2644 cx.write_to_primary(ClipboardItem::new_string(text));
2645 }
2646 }
2647
2648 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2649 self.buffer.update(cx, |buffer, cx| {
2650 buffer.set_active_selections(
2651 &self.selections.disjoint_anchors(),
2652 self.selections.line_mode,
2653 self.cursor_shape,
2654 cx,
2655 )
2656 });
2657 }
2658 let display_map = self
2659 .display_map
2660 .update(cx, |display_map, cx| display_map.snapshot(cx));
2661 let buffer = &display_map.buffer_snapshot;
2662 self.add_selections_state = None;
2663 self.select_next_state = None;
2664 self.select_prev_state = None;
2665 self.select_larger_syntax_node_stack.clear();
2666 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2667 self.snippet_stack
2668 .invalidate(&self.selections.disjoint_anchors(), buffer);
2669 self.take_rename(false, cx);
2670
2671 let new_cursor_position = self.selections.newest_anchor().head();
2672
2673 self.push_to_nav_history(
2674 *old_cursor_position,
2675 Some(new_cursor_position.to_point(buffer)),
2676 cx,
2677 );
2678
2679 if local {
2680 let new_cursor_position = self.selections.newest_anchor().head();
2681 let mut context_menu = self.context_menu.write();
2682 let completion_menu = match context_menu.as_ref() {
2683 Some(ContextMenu::Completions(menu)) => Some(menu),
2684
2685 _ => {
2686 *context_menu = None;
2687 None
2688 }
2689 };
2690
2691 if let Some(completion_menu) = completion_menu {
2692 let cursor_position = new_cursor_position.to_offset(buffer);
2693 let (word_range, kind) =
2694 buffer.surrounding_word(completion_menu.initial_position, true);
2695 if kind == Some(CharKind::Word)
2696 && word_range.to_inclusive().contains(&cursor_position)
2697 {
2698 let mut completion_menu = completion_menu.clone();
2699 drop(context_menu);
2700
2701 let query = Self::completion_query(buffer, cursor_position);
2702 cx.spawn(move |this, mut cx| async move {
2703 completion_menu
2704 .filter(query.as_deref(), cx.background_executor().clone())
2705 .await;
2706
2707 this.update(&mut cx, |this, cx| {
2708 let mut context_menu = this.context_menu.write();
2709 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2710 return;
2711 };
2712
2713 if menu.id > completion_menu.id {
2714 return;
2715 }
2716
2717 *context_menu = Some(ContextMenu::Completions(completion_menu));
2718 drop(context_menu);
2719 cx.notify();
2720 })
2721 })
2722 .detach();
2723
2724 if show_completions {
2725 self.show_completions(&ShowCompletions { trigger: None }, cx);
2726 }
2727 } else {
2728 drop(context_menu);
2729 self.hide_context_menu(cx);
2730 }
2731 } else {
2732 drop(context_menu);
2733 }
2734
2735 hide_hover(self, cx);
2736
2737 if old_cursor_position.to_display_point(&display_map).row()
2738 != new_cursor_position.to_display_point(&display_map).row()
2739 {
2740 self.available_code_actions.take();
2741 }
2742 self.refresh_code_actions(cx);
2743 self.refresh_document_highlights(cx);
2744 refresh_matching_bracket_highlights(self, cx);
2745 self.discard_inline_completion(false, cx);
2746 linked_editing_ranges::refresh_linked_ranges(self, cx);
2747 if self.git_blame_inline_enabled {
2748 self.start_inline_blame_timer(cx);
2749 }
2750 }
2751
2752 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2753 cx.emit(EditorEvent::SelectionsChanged { local });
2754
2755 if self.selections.disjoint_anchors().len() == 1 {
2756 cx.emit(SearchEvent::ActiveMatchChanged)
2757 }
2758 cx.notify();
2759 }
2760
2761 pub fn change_selections<R>(
2762 &mut self,
2763 autoscroll: Option<Autoscroll>,
2764 cx: &mut ViewContext<Self>,
2765 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2766 ) -> R {
2767 self.change_selections_inner(autoscroll, true, cx, change)
2768 }
2769
2770 pub fn change_selections_inner<R>(
2771 &mut self,
2772 autoscroll: Option<Autoscroll>,
2773 request_completions: bool,
2774 cx: &mut ViewContext<Self>,
2775 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2776 ) -> R {
2777 let old_cursor_position = self.selections.newest_anchor().head();
2778 self.push_to_selection_history();
2779
2780 let (changed, result) = self.selections.change_with(cx, change);
2781
2782 if changed {
2783 if let Some(autoscroll) = autoscroll {
2784 self.request_autoscroll(autoscroll, cx);
2785 }
2786 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2787
2788 if self.should_open_signature_help_automatically(
2789 &old_cursor_position,
2790 self.signature_help_state.backspace_pressed(),
2791 cx,
2792 ) {
2793 self.show_signature_help(&ShowSignatureHelp, cx);
2794 }
2795 self.signature_help_state.set_backspace_pressed(false);
2796 }
2797
2798 result
2799 }
2800
2801 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2802 where
2803 I: IntoIterator<Item = (Range<S>, T)>,
2804 S: ToOffset,
2805 T: Into<Arc<str>>,
2806 {
2807 if self.read_only(cx) {
2808 return;
2809 }
2810
2811 self.buffer
2812 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2813 }
2814
2815 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2816 where
2817 I: IntoIterator<Item = (Range<S>, T)>,
2818 S: ToOffset,
2819 T: Into<Arc<str>>,
2820 {
2821 if self.read_only(cx) {
2822 return;
2823 }
2824
2825 self.buffer.update(cx, |buffer, cx| {
2826 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2827 });
2828 }
2829
2830 pub fn edit_with_block_indent<I, S, T>(
2831 &mut self,
2832 edits: I,
2833 original_indent_columns: Vec<u32>,
2834 cx: &mut ViewContext<Self>,
2835 ) where
2836 I: IntoIterator<Item = (Range<S>, T)>,
2837 S: ToOffset,
2838 T: Into<Arc<str>>,
2839 {
2840 if self.read_only(cx) {
2841 return;
2842 }
2843
2844 self.buffer.update(cx, |buffer, cx| {
2845 buffer.edit(
2846 edits,
2847 Some(AutoindentMode::Block {
2848 original_indent_columns,
2849 }),
2850 cx,
2851 )
2852 });
2853 }
2854
2855 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2856 self.hide_context_menu(cx);
2857
2858 match phase {
2859 SelectPhase::Begin {
2860 position,
2861 add,
2862 click_count,
2863 } => self.begin_selection(position, add, click_count, cx),
2864 SelectPhase::BeginColumnar {
2865 position,
2866 goal_column,
2867 reset,
2868 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2869 SelectPhase::Extend {
2870 position,
2871 click_count,
2872 } => self.extend_selection(position, click_count, cx),
2873 SelectPhase::Update {
2874 position,
2875 goal_column,
2876 scroll_delta,
2877 } => self.update_selection(position, goal_column, scroll_delta, cx),
2878 SelectPhase::End => self.end_selection(cx),
2879 }
2880 }
2881
2882 fn extend_selection(
2883 &mut self,
2884 position: DisplayPoint,
2885 click_count: usize,
2886 cx: &mut ViewContext<Self>,
2887 ) {
2888 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2889 let tail = self.selections.newest::<usize>(cx).tail();
2890 self.begin_selection(position, false, click_count, cx);
2891
2892 let position = position.to_offset(&display_map, Bias::Left);
2893 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2894
2895 let mut pending_selection = self
2896 .selections
2897 .pending_anchor()
2898 .expect("extend_selection not called with pending selection");
2899 if position >= tail {
2900 pending_selection.start = tail_anchor;
2901 } else {
2902 pending_selection.end = tail_anchor;
2903 pending_selection.reversed = true;
2904 }
2905
2906 let mut pending_mode = self.selections.pending_mode().unwrap();
2907 match &mut pending_mode {
2908 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2909 _ => {}
2910 }
2911
2912 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2913 s.set_pending(pending_selection, pending_mode)
2914 });
2915 }
2916
2917 fn begin_selection(
2918 &mut self,
2919 position: DisplayPoint,
2920 add: bool,
2921 click_count: usize,
2922 cx: &mut ViewContext<Self>,
2923 ) {
2924 if !self.focus_handle.is_focused(cx) {
2925 self.last_focused_descendant = None;
2926 cx.focus(&self.focus_handle);
2927 }
2928
2929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2930 let buffer = &display_map.buffer_snapshot;
2931 let newest_selection = self.selections.newest_anchor().clone();
2932 let position = display_map.clip_point(position, Bias::Left);
2933
2934 let start;
2935 let end;
2936 let mode;
2937 let mut auto_scroll;
2938 match click_count {
2939 1 => {
2940 start = buffer.anchor_before(position.to_point(&display_map));
2941 end = start;
2942 mode = SelectMode::Character;
2943 auto_scroll = true;
2944 }
2945 2 => {
2946 let range = movement::surrounding_word(&display_map, position);
2947 start = buffer.anchor_before(range.start.to_point(&display_map));
2948 end = buffer.anchor_before(range.end.to_point(&display_map));
2949 mode = SelectMode::Word(start..end);
2950 auto_scroll = true;
2951 }
2952 3 => {
2953 let position = display_map
2954 .clip_point(position, Bias::Left)
2955 .to_point(&display_map);
2956 let line_start = display_map.prev_line_boundary(position).0;
2957 let next_line_start = buffer.clip_point(
2958 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2959 Bias::Left,
2960 );
2961 start = buffer.anchor_before(line_start);
2962 end = buffer.anchor_before(next_line_start);
2963 mode = SelectMode::Line(start..end);
2964 auto_scroll = true;
2965 }
2966 _ => {
2967 start = buffer.anchor_before(0);
2968 end = buffer.anchor_before(buffer.len());
2969 mode = SelectMode::All;
2970 auto_scroll = false;
2971 }
2972 }
2973 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2974
2975 let point_to_delete: Option<usize> = {
2976 let selected_points: Vec<Selection<Point>> =
2977 self.selections.disjoint_in_range(start..end, cx);
2978
2979 if !add || click_count > 1 {
2980 None
2981 } else if !selected_points.is_empty() {
2982 Some(selected_points[0].id)
2983 } else {
2984 let clicked_point_already_selected =
2985 self.selections.disjoint.iter().find(|selection| {
2986 selection.start.to_point(buffer) == start.to_point(buffer)
2987 || selection.end.to_point(buffer) == end.to_point(buffer)
2988 });
2989
2990 clicked_point_already_selected.map(|selection| selection.id)
2991 }
2992 };
2993
2994 let selections_count = self.selections.count();
2995
2996 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2997 if let Some(point_to_delete) = point_to_delete {
2998 s.delete(point_to_delete);
2999
3000 if selections_count == 1 {
3001 s.set_pending_anchor_range(start..end, mode);
3002 }
3003 } else {
3004 if !add {
3005 s.clear_disjoint();
3006 } else if click_count > 1 {
3007 s.delete(newest_selection.id)
3008 }
3009
3010 s.set_pending_anchor_range(start..end, mode);
3011 }
3012 });
3013 }
3014
3015 fn begin_columnar_selection(
3016 &mut self,
3017 position: DisplayPoint,
3018 goal_column: u32,
3019 reset: bool,
3020 cx: &mut ViewContext<Self>,
3021 ) {
3022 if !self.focus_handle.is_focused(cx) {
3023 self.last_focused_descendant = None;
3024 cx.focus(&self.focus_handle);
3025 }
3026
3027 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3028
3029 if reset {
3030 let pointer_position = display_map
3031 .buffer_snapshot
3032 .anchor_before(position.to_point(&display_map));
3033
3034 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3035 s.clear_disjoint();
3036 s.set_pending_anchor_range(
3037 pointer_position..pointer_position,
3038 SelectMode::Character,
3039 );
3040 });
3041 }
3042
3043 let tail = self.selections.newest::<Point>(cx).tail();
3044 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3045
3046 if !reset {
3047 self.select_columns(
3048 tail.to_display_point(&display_map),
3049 position,
3050 goal_column,
3051 &display_map,
3052 cx,
3053 );
3054 }
3055 }
3056
3057 fn update_selection(
3058 &mut self,
3059 position: DisplayPoint,
3060 goal_column: u32,
3061 scroll_delta: gpui::Point<f32>,
3062 cx: &mut ViewContext<Self>,
3063 ) {
3064 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3065
3066 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3067 let tail = tail.to_display_point(&display_map);
3068 self.select_columns(tail, position, goal_column, &display_map, cx);
3069 } else if let Some(mut pending) = self.selections.pending_anchor() {
3070 let buffer = self.buffer.read(cx).snapshot(cx);
3071 let head;
3072 let tail;
3073 let mode = self.selections.pending_mode().unwrap();
3074 match &mode {
3075 SelectMode::Character => {
3076 head = position.to_point(&display_map);
3077 tail = pending.tail().to_point(&buffer);
3078 }
3079 SelectMode::Word(original_range) => {
3080 let original_display_range = original_range.start.to_display_point(&display_map)
3081 ..original_range.end.to_display_point(&display_map);
3082 let original_buffer_range = original_display_range.start.to_point(&display_map)
3083 ..original_display_range.end.to_point(&display_map);
3084 if movement::is_inside_word(&display_map, position)
3085 || original_display_range.contains(&position)
3086 {
3087 let word_range = movement::surrounding_word(&display_map, position);
3088 if word_range.start < original_display_range.start {
3089 head = word_range.start.to_point(&display_map);
3090 } else {
3091 head = word_range.end.to_point(&display_map);
3092 }
3093 } else {
3094 head = position.to_point(&display_map);
3095 }
3096
3097 if head <= original_buffer_range.start {
3098 tail = original_buffer_range.end;
3099 } else {
3100 tail = original_buffer_range.start;
3101 }
3102 }
3103 SelectMode::Line(original_range) => {
3104 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3105
3106 let position = display_map
3107 .clip_point(position, Bias::Left)
3108 .to_point(&display_map);
3109 let line_start = display_map.prev_line_boundary(position).0;
3110 let next_line_start = buffer.clip_point(
3111 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3112 Bias::Left,
3113 );
3114
3115 if line_start < original_range.start {
3116 head = line_start
3117 } else {
3118 head = next_line_start
3119 }
3120
3121 if head <= original_range.start {
3122 tail = original_range.end;
3123 } else {
3124 tail = original_range.start;
3125 }
3126 }
3127 SelectMode::All => {
3128 return;
3129 }
3130 };
3131
3132 if head < tail {
3133 pending.start = buffer.anchor_before(head);
3134 pending.end = buffer.anchor_before(tail);
3135 pending.reversed = true;
3136 } else {
3137 pending.start = buffer.anchor_before(tail);
3138 pending.end = buffer.anchor_before(head);
3139 pending.reversed = false;
3140 }
3141
3142 self.change_selections(None, cx, |s| {
3143 s.set_pending(pending, mode);
3144 });
3145 } else {
3146 log::error!("update_selection dispatched with no pending selection");
3147 return;
3148 }
3149
3150 self.apply_scroll_delta(scroll_delta, cx);
3151 cx.notify();
3152 }
3153
3154 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3155 self.columnar_selection_tail.take();
3156 if self.selections.pending_anchor().is_some() {
3157 let selections = self.selections.all::<usize>(cx);
3158 self.change_selections(None, cx, |s| {
3159 s.select(selections);
3160 s.clear_pending();
3161 });
3162 }
3163 }
3164
3165 fn select_columns(
3166 &mut self,
3167 tail: DisplayPoint,
3168 head: DisplayPoint,
3169 goal_column: u32,
3170 display_map: &DisplaySnapshot,
3171 cx: &mut ViewContext<Self>,
3172 ) {
3173 let start_row = cmp::min(tail.row(), head.row());
3174 let end_row = cmp::max(tail.row(), head.row());
3175 let start_column = cmp::min(tail.column(), goal_column);
3176 let end_column = cmp::max(tail.column(), goal_column);
3177 let reversed = start_column < tail.column();
3178
3179 let selection_ranges = (start_row.0..=end_row.0)
3180 .map(DisplayRow)
3181 .filter_map(|row| {
3182 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3183 let start = display_map
3184 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3185 .to_point(display_map);
3186 let end = display_map
3187 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3188 .to_point(display_map);
3189 if reversed {
3190 Some(end..start)
3191 } else {
3192 Some(start..end)
3193 }
3194 } else {
3195 None
3196 }
3197 })
3198 .collect::<Vec<_>>();
3199
3200 self.change_selections(None, cx, |s| {
3201 s.select_ranges(selection_ranges);
3202 });
3203 cx.notify();
3204 }
3205
3206 pub fn has_pending_nonempty_selection(&self) -> bool {
3207 let pending_nonempty_selection = match self.selections.pending_anchor() {
3208 Some(Selection { start, end, .. }) => start != end,
3209 None => false,
3210 };
3211
3212 pending_nonempty_selection
3213 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3214 }
3215
3216 pub fn has_pending_selection(&self) -> bool {
3217 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3218 }
3219
3220 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3221 if self.clear_expanded_diff_hunks(cx) {
3222 cx.notify();
3223 return;
3224 }
3225 if self.dismiss_menus_and_popups(true, cx) {
3226 return;
3227 }
3228
3229 if self.mode == EditorMode::Full
3230 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3231 {
3232 return;
3233 }
3234
3235 cx.propagate();
3236 }
3237
3238 pub fn dismiss_menus_and_popups(
3239 &mut self,
3240 should_report_inline_completion_event: bool,
3241 cx: &mut ViewContext<Self>,
3242 ) -> bool {
3243 if self.take_rename(false, cx).is_some() {
3244 return true;
3245 }
3246
3247 if hide_hover(self, cx) {
3248 return true;
3249 }
3250
3251 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3252 return true;
3253 }
3254
3255 if self.hide_context_menu(cx).is_some() {
3256 return true;
3257 }
3258
3259 if self.mouse_context_menu.take().is_some() {
3260 return true;
3261 }
3262
3263 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3264 return true;
3265 }
3266
3267 if self.snippet_stack.pop().is_some() {
3268 return true;
3269 }
3270
3271 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3272 self.dismiss_diagnostics(cx);
3273 return true;
3274 }
3275
3276 false
3277 }
3278
3279 fn linked_editing_ranges_for(
3280 &self,
3281 selection: Range<text::Anchor>,
3282 cx: &AppContext,
3283 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3284 if self.linked_edit_ranges.is_empty() {
3285 return None;
3286 }
3287 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3288 selection.end.buffer_id.and_then(|end_buffer_id| {
3289 if selection.start.buffer_id != Some(end_buffer_id) {
3290 return None;
3291 }
3292 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3293 let snapshot = buffer.read(cx).snapshot();
3294 self.linked_edit_ranges
3295 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3296 .map(|ranges| (ranges, snapshot, buffer))
3297 })?;
3298 use text::ToOffset as TO;
3299 // find offset from the start of current range to current cursor position
3300 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3301
3302 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3303 let start_difference = start_offset - start_byte_offset;
3304 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3305 let end_difference = end_offset - start_byte_offset;
3306 // Current range has associated linked ranges.
3307 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3308 for range in linked_ranges.iter() {
3309 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3310 let end_offset = start_offset + end_difference;
3311 let start_offset = start_offset + start_difference;
3312 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3313 continue;
3314 }
3315 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3316 if s.start.buffer_id != selection.start.buffer_id
3317 || s.end.buffer_id != selection.end.buffer_id
3318 {
3319 return false;
3320 }
3321 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3322 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3323 }) {
3324 continue;
3325 }
3326 let start = buffer_snapshot.anchor_after(start_offset);
3327 let end = buffer_snapshot.anchor_after(end_offset);
3328 linked_edits
3329 .entry(buffer.clone())
3330 .or_default()
3331 .push(start..end);
3332 }
3333 Some(linked_edits)
3334 }
3335
3336 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3337 let text: Arc<str> = text.into();
3338
3339 if self.read_only(cx) {
3340 return;
3341 }
3342
3343 let selections = self.selections.all_adjusted(cx);
3344 let mut bracket_inserted = false;
3345 let mut edits = Vec::new();
3346 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3347 let mut new_selections = Vec::with_capacity(selections.len());
3348 let mut new_autoclose_regions = Vec::new();
3349 let snapshot = self.buffer.read(cx).read(cx);
3350
3351 for (selection, autoclose_region) in
3352 self.selections_with_autoclose_regions(selections, &snapshot)
3353 {
3354 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3355 // Determine if the inserted text matches the opening or closing
3356 // bracket of any of this language's bracket pairs.
3357 let mut bracket_pair = None;
3358 let mut is_bracket_pair_start = false;
3359 let mut is_bracket_pair_end = false;
3360 if !text.is_empty() {
3361 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3362 // and they are removing the character that triggered IME popup.
3363 for (pair, enabled) in scope.brackets() {
3364 if !pair.close && !pair.surround {
3365 continue;
3366 }
3367
3368 if enabled && pair.start.ends_with(text.as_ref()) {
3369 let prefix_len = pair.start.len() - text.len();
3370 let preceding_text_matches_prefix = prefix_len == 0
3371 || (selection.start.column >= (prefix_len as u32)
3372 && snapshot.contains_str_at(
3373 Point::new(
3374 selection.start.row,
3375 selection.start.column - (prefix_len as u32),
3376 ),
3377 &pair.start[..prefix_len],
3378 ));
3379 if preceding_text_matches_prefix {
3380 bracket_pair = Some(pair.clone());
3381 is_bracket_pair_start = true;
3382 break;
3383 }
3384 }
3385 if pair.end.as_str() == text.as_ref() {
3386 bracket_pair = Some(pair.clone());
3387 is_bracket_pair_end = true;
3388 break;
3389 }
3390 }
3391 }
3392
3393 if let Some(bracket_pair) = bracket_pair {
3394 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3395 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3396 let auto_surround =
3397 self.use_auto_surround && snapshot_settings.use_auto_surround;
3398 if selection.is_empty() {
3399 if is_bracket_pair_start {
3400 // If the inserted text is a suffix of an opening bracket and the
3401 // selection is preceded by the rest of the opening bracket, then
3402 // insert the closing bracket.
3403 let following_text_allows_autoclose = snapshot
3404 .chars_at(selection.start)
3405 .next()
3406 .map_or(true, |c| scope.should_autoclose_before(c));
3407
3408 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3409 && bracket_pair.start.len() == 1
3410 {
3411 let target = bracket_pair.start.chars().next().unwrap();
3412 let current_line_count = snapshot
3413 .reversed_chars_at(selection.start)
3414 .take_while(|&c| c != '\n')
3415 .filter(|&c| c == target)
3416 .count();
3417 current_line_count % 2 == 1
3418 } else {
3419 false
3420 };
3421
3422 if autoclose
3423 && bracket_pair.close
3424 && following_text_allows_autoclose
3425 && !is_closing_quote
3426 {
3427 let anchor = snapshot.anchor_before(selection.end);
3428 new_selections.push((selection.map(|_| anchor), text.len()));
3429 new_autoclose_regions.push((
3430 anchor,
3431 text.len(),
3432 selection.id,
3433 bracket_pair.clone(),
3434 ));
3435 edits.push((
3436 selection.range(),
3437 format!("{}{}", text, bracket_pair.end).into(),
3438 ));
3439 bracket_inserted = true;
3440 continue;
3441 }
3442 }
3443
3444 if let Some(region) = autoclose_region {
3445 // If the selection is followed by an auto-inserted closing bracket,
3446 // then don't insert that closing bracket again; just move the selection
3447 // past the closing bracket.
3448 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3449 && text.as_ref() == region.pair.end.as_str();
3450 if should_skip {
3451 let anchor = snapshot.anchor_after(selection.end);
3452 new_selections
3453 .push((selection.map(|_| anchor), region.pair.end.len()));
3454 continue;
3455 }
3456 }
3457
3458 let always_treat_brackets_as_autoclosed = snapshot
3459 .settings_at(selection.start, cx)
3460 .always_treat_brackets_as_autoclosed;
3461 if always_treat_brackets_as_autoclosed
3462 && is_bracket_pair_end
3463 && snapshot.contains_str_at(selection.end, text.as_ref())
3464 {
3465 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3466 // and the inserted text is a closing bracket and the selection is followed
3467 // by the closing bracket then move the selection past the closing bracket.
3468 let anchor = snapshot.anchor_after(selection.end);
3469 new_selections.push((selection.map(|_| anchor), text.len()));
3470 continue;
3471 }
3472 }
3473 // If an opening bracket is 1 character long and is typed while
3474 // text is selected, then surround that text with the bracket pair.
3475 else if auto_surround
3476 && bracket_pair.surround
3477 && is_bracket_pair_start
3478 && bracket_pair.start.chars().count() == 1
3479 {
3480 edits.push((selection.start..selection.start, text.clone()));
3481 edits.push((
3482 selection.end..selection.end,
3483 bracket_pair.end.as_str().into(),
3484 ));
3485 bracket_inserted = true;
3486 new_selections.push((
3487 Selection {
3488 id: selection.id,
3489 start: snapshot.anchor_after(selection.start),
3490 end: snapshot.anchor_before(selection.end),
3491 reversed: selection.reversed,
3492 goal: selection.goal,
3493 },
3494 0,
3495 ));
3496 continue;
3497 }
3498 }
3499 }
3500
3501 if self.auto_replace_emoji_shortcode
3502 && selection.is_empty()
3503 && text.as_ref().ends_with(':')
3504 {
3505 if let Some(possible_emoji_short_code) =
3506 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3507 {
3508 if !possible_emoji_short_code.is_empty() {
3509 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3510 let emoji_shortcode_start = Point::new(
3511 selection.start.row,
3512 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3513 );
3514
3515 // Remove shortcode from buffer
3516 edits.push((
3517 emoji_shortcode_start..selection.start,
3518 "".to_string().into(),
3519 ));
3520 new_selections.push((
3521 Selection {
3522 id: selection.id,
3523 start: snapshot.anchor_after(emoji_shortcode_start),
3524 end: snapshot.anchor_before(selection.start),
3525 reversed: selection.reversed,
3526 goal: selection.goal,
3527 },
3528 0,
3529 ));
3530
3531 // Insert emoji
3532 let selection_start_anchor = snapshot.anchor_after(selection.start);
3533 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3534 edits.push((selection.start..selection.end, emoji.to_string().into()));
3535
3536 continue;
3537 }
3538 }
3539 }
3540 }
3541
3542 // If not handling any auto-close operation, then just replace the selected
3543 // text with the given input and move the selection to the end of the
3544 // newly inserted text.
3545 let anchor = snapshot.anchor_after(selection.end);
3546 if !self.linked_edit_ranges.is_empty() {
3547 let start_anchor = snapshot.anchor_before(selection.start);
3548
3549 let is_word_char = text.chars().next().map_or(true, |char| {
3550 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3551 classifier.is_word(char)
3552 });
3553
3554 if is_word_char {
3555 if let Some(ranges) = self
3556 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3557 {
3558 for (buffer, edits) in ranges {
3559 linked_edits
3560 .entry(buffer.clone())
3561 .or_default()
3562 .extend(edits.into_iter().map(|range| (range, text.clone())));
3563 }
3564 }
3565 }
3566 }
3567
3568 new_selections.push((selection.map(|_| anchor), 0));
3569 edits.push((selection.start..selection.end, text.clone()));
3570 }
3571
3572 drop(snapshot);
3573
3574 self.transact(cx, |this, cx| {
3575 this.buffer.update(cx, |buffer, cx| {
3576 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3577 });
3578 for (buffer, edits) in linked_edits {
3579 buffer.update(cx, |buffer, cx| {
3580 let snapshot = buffer.snapshot();
3581 let edits = edits
3582 .into_iter()
3583 .map(|(range, text)| {
3584 use text::ToPoint as TP;
3585 let end_point = TP::to_point(&range.end, &snapshot);
3586 let start_point = TP::to_point(&range.start, &snapshot);
3587 (start_point..end_point, text)
3588 })
3589 .sorted_by_key(|(range, _)| range.start)
3590 .collect::<Vec<_>>();
3591 buffer.edit(edits, None, cx);
3592 })
3593 }
3594 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3595 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3596 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3597 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3598 .zip(new_selection_deltas)
3599 .map(|(selection, delta)| Selection {
3600 id: selection.id,
3601 start: selection.start + delta,
3602 end: selection.end + delta,
3603 reversed: selection.reversed,
3604 goal: SelectionGoal::None,
3605 })
3606 .collect::<Vec<_>>();
3607
3608 let mut i = 0;
3609 for (position, delta, selection_id, pair) in new_autoclose_regions {
3610 let position = position.to_offset(&map.buffer_snapshot) + delta;
3611 let start = map.buffer_snapshot.anchor_before(position);
3612 let end = map.buffer_snapshot.anchor_after(position);
3613 while let Some(existing_state) = this.autoclose_regions.get(i) {
3614 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3615 Ordering::Less => i += 1,
3616 Ordering::Greater => break,
3617 Ordering::Equal => {
3618 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3619 Ordering::Less => i += 1,
3620 Ordering::Equal => break,
3621 Ordering::Greater => break,
3622 }
3623 }
3624 }
3625 }
3626 this.autoclose_regions.insert(
3627 i,
3628 AutocloseRegion {
3629 selection_id,
3630 range: start..end,
3631 pair,
3632 },
3633 );
3634 }
3635
3636 let had_active_inline_completion = this.has_active_inline_completion(cx);
3637 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3638 s.select(new_selections)
3639 });
3640
3641 if !bracket_inserted {
3642 if let Some(on_type_format_task) =
3643 this.trigger_on_type_formatting(text.to_string(), cx)
3644 {
3645 on_type_format_task.detach_and_log_err(cx);
3646 }
3647 }
3648
3649 let editor_settings = EditorSettings::get_global(cx);
3650 if bracket_inserted
3651 && (editor_settings.auto_signature_help
3652 || editor_settings.show_signature_help_after_edits)
3653 {
3654 this.show_signature_help(&ShowSignatureHelp, cx);
3655 }
3656
3657 let trigger_in_words = !had_active_inline_completion;
3658 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3659 linked_editing_ranges::refresh_linked_ranges(this, cx);
3660 this.refresh_inline_completion(true, false, cx);
3661 });
3662 }
3663
3664 fn find_possible_emoji_shortcode_at_position(
3665 snapshot: &MultiBufferSnapshot,
3666 position: Point,
3667 ) -> Option<String> {
3668 let mut chars = Vec::new();
3669 let mut found_colon = false;
3670 for char in snapshot.reversed_chars_at(position).take(100) {
3671 // Found a possible emoji shortcode in the middle of the buffer
3672 if found_colon {
3673 if char.is_whitespace() {
3674 chars.reverse();
3675 return Some(chars.iter().collect());
3676 }
3677 // If the previous character is not a whitespace, we are in the middle of a word
3678 // and we only want to complete the shortcode if the word is made up of other emojis
3679 let mut containing_word = String::new();
3680 for ch in snapshot
3681 .reversed_chars_at(position)
3682 .skip(chars.len() + 1)
3683 .take(100)
3684 {
3685 if ch.is_whitespace() {
3686 break;
3687 }
3688 containing_word.push(ch);
3689 }
3690 let containing_word = containing_word.chars().rev().collect::<String>();
3691 if util::word_consists_of_emojis(containing_word.as_str()) {
3692 chars.reverse();
3693 return Some(chars.iter().collect());
3694 }
3695 }
3696
3697 if char.is_whitespace() || !char.is_ascii() {
3698 return None;
3699 }
3700 if char == ':' {
3701 found_colon = true;
3702 } else {
3703 chars.push(char);
3704 }
3705 }
3706 // Found a possible emoji shortcode at the beginning of the buffer
3707 chars.reverse();
3708 Some(chars.iter().collect())
3709 }
3710
3711 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3712 self.transact(cx, |this, cx| {
3713 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3714 let selections = this.selections.all::<usize>(cx);
3715 let multi_buffer = this.buffer.read(cx);
3716 let buffer = multi_buffer.snapshot(cx);
3717 selections
3718 .iter()
3719 .map(|selection| {
3720 let start_point = selection.start.to_point(&buffer);
3721 let mut indent =
3722 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3723 indent.len = cmp::min(indent.len, start_point.column);
3724 let start = selection.start;
3725 let end = selection.end;
3726 let selection_is_empty = start == end;
3727 let language_scope = buffer.language_scope_at(start);
3728 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3729 &language_scope
3730 {
3731 let leading_whitespace_len = buffer
3732 .reversed_chars_at(start)
3733 .take_while(|c| c.is_whitespace() && *c != '\n')
3734 .map(|c| c.len_utf8())
3735 .sum::<usize>();
3736
3737 let trailing_whitespace_len = buffer
3738 .chars_at(end)
3739 .take_while(|c| c.is_whitespace() && *c != '\n')
3740 .map(|c| c.len_utf8())
3741 .sum::<usize>();
3742
3743 let insert_extra_newline =
3744 language.brackets().any(|(pair, enabled)| {
3745 let pair_start = pair.start.trim_end();
3746 let pair_end = pair.end.trim_start();
3747
3748 enabled
3749 && pair.newline
3750 && buffer.contains_str_at(
3751 end + trailing_whitespace_len,
3752 pair_end,
3753 )
3754 && buffer.contains_str_at(
3755 (start - leading_whitespace_len)
3756 .saturating_sub(pair_start.len()),
3757 pair_start,
3758 )
3759 });
3760
3761 // Comment extension on newline is allowed only for cursor selections
3762 let comment_delimiter = maybe!({
3763 if !selection_is_empty {
3764 return None;
3765 }
3766
3767 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3768 return None;
3769 }
3770
3771 let delimiters = language.line_comment_prefixes();
3772 let max_len_of_delimiter =
3773 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3774 let (snapshot, range) =
3775 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3776
3777 let mut index_of_first_non_whitespace = 0;
3778 let comment_candidate = snapshot
3779 .chars_for_range(range)
3780 .skip_while(|c| {
3781 let should_skip = c.is_whitespace();
3782 if should_skip {
3783 index_of_first_non_whitespace += 1;
3784 }
3785 should_skip
3786 })
3787 .take(max_len_of_delimiter)
3788 .collect::<String>();
3789 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3790 comment_candidate.starts_with(comment_prefix.as_ref())
3791 })?;
3792 let cursor_is_placed_after_comment_marker =
3793 index_of_first_non_whitespace + comment_prefix.len()
3794 <= start_point.column as usize;
3795 if cursor_is_placed_after_comment_marker {
3796 Some(comment_prefix.clone())
3797 } else {
3798 None
3799 }
3800 });
3801 (comment_delimiter, insert_extra_newline)
3802 } else {
3803 (None, false)
3804 };
3805
3806 let capacity_for_delimiter = comment_delimiter
3807 .as_deref()
3808 .map(str::len)
3809 .unwrap_or_default();
3810 let mut new_text =
3811 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3812 new_text.push('\n');
3813 new_text.extend(indent.chars());
3814 if let Some(delimiter) = &comment_delimiter {
3815 new_text.push_str(delimiter);
3816 }
3817 if insert_extra_newline {
3818 new_text = new_text.repeat(2);
3819 }
3820
3821 let anchor = buffer.anchor_after(end);
3822 let new_selection = selection.map(|_| anchor);
3823 (
3824 (start..end, new_text),
3825 (insert_extra_newline, new_selection),
3826 )
3827 })
3828 .unzip()
3829 };
3830
3831 this.edit_with_autoindent(edits, cx);
3832 let buffer = this.buffer.read(cx).snapshot(cx);
3833 let new_selections = selection_fixup_info
3834 .into_iter()
3835 .map(|(extra_newline_inserted, new_selection)| {
3836 let mut cursor = new_selection.end.to_point(&buffer);
3837 if extra_newline_inserted {
3838 cursor.row -= 1;
3839 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3840 }
3841 new_selection.map(|_| cursor)
3842 })
3843 .collect();
3844
3845 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3846 this.refresh_inline_completion(true, false, cx);
3847 });
3848 }
3849
3850 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3851 let buffer = self.buffer.read(cx);
3852 let snapshot = buffer.snapshot(cx);
3853
3854 let mut edits = Vec::new();
3855 let mut rows = Vec::new();
3856
3857 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3858 let cursor = selection.head();
3859 let row = cursor.row;
3860
3861 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3862
3863 let newline = "\n".to_string();
3864 edits.push((start_of_line..start_of_line, newline));
3865
3866 rows.push(row + rows_inserted as u32);
3867 }
3868
3869 self.transact(cx, |editor, cx| {
3870 editor.edit(edits, cx);
3871
3872 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3873 let mut index = 0;
3874 s.move_cursors_with(|map, _, _| {
3875 let row = rows[index];
3876 index += 1;
3877
3878 let point = Point::new(row, 0);
3879 let boundary = map.next_line_boundary(point).1;
3880 let clipped = map.clip_point(boundary, Bias::Left);
3881
3882 (clipped, SelectionGoal::None)
3883 });
3884 });
3885
3886 let mut indent_edits = Vec::new();
3887 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3888 for row in rows {
3889 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3890 for (row, indent) in indents {
3891 if indent.len == 0 {
3892 continue;
3893 }
3894
3895 let text = match indent.kind {
3896 IndentKind::Space => " ".repeat(indent.len as usize),
3897 IndentKind::Tab => "\t".repeat(indent.len as usize),
3898 };
3899 let point = Point::new(row.0, 0);
3900 indent_edits.push((point..point, text));
3901 }
3902 }
3903 editor.edit(indent_edits, cx);
3904 });
3905 }
3906
3907 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3908 let buffer = self.buffer.read(cx);
3909 let snapshot = buffer.snapshot(cx);
3910
3911 let mut edits = Vec::new();
3912 let mut rows = Vec::new();
3913 let mut rows_inserted = 0;
3914
3915 for selection in self.selections.all_adjusted(cx) {
3916 let cursor = selection.head();
3917 let row = cursor.row;
3918
3919 let point = Point::new(row + 1, 0);
3920 let start_of_line = snapshot.clip_point(point, Bias::Left);
3921
3922 let newline = "\n".to_string();
3923 edits.push((start_of_line..start_of_line, newline));
3924
3925 rows_inserted += 1;
3926 rows.push(row + rows_inserted);
3927 }
3928
3929 self.transact(cx, |editor, cx| {
3930 editor.edit(edits, cx);
3931
3932 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3933 let mut index = 0;
3934 s.move_cursors_with(|map, _, _| {
3935 let row = rows[index];
3936 index += 1;
3937
3938 let point = Point::new(row, 0);
3939 let boundary = map.next_line_boundary(point).1;
3940 let clipped = map.clip_point(boundary, Bias::Left);
3941
3942 (clipped, SelectionGoal::None)
3943 });
3944 });
3945
3946 let mut indent_edits = Vec::new();
3947 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3948 for row in rows {
3949 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3950 for (row, indent) in indents {
3951 if indent.len == 0 {
3952 continue;
3953 }
3954
3955 let text = match indent.kind {
3956 IndentKind::Space => " ".repeat(indent.len as usize),
3957 IndentKind::Tab => "\t".repeat(indent.len as usize),
3958 };
3959 let point = Point::new(row.0, 0);
3960 indent_edits.push((point..point, text));
3961 }
3962 }
3963 editor.edit(indent_edits, cx);
3964 });
3965 }
3966
3967 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3968 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3969 original_indent_columns: Vec::new(),
3970 });
3971 self.insert_with_autoindent_mode(text, autoindent, cx);
3972 }
3973
3974 fn insert_with_autoindent_mode(
3975 &mut self,
3976 text: &str,
3977 autoindent_mode: Option<AutoindentMode>,
3978 cx: &mut ViewContext<Self>,
3979 ) {
3980 if self.read_only(cx) {
3981 return;
3982 }
3983
3984 let text: Arc<str> = text.into();
3985 self.transact(cx, |this, cx| {
3986 let old_selections = this.selections.all_adjusted(cx);
3987 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3988 let anchors = {
3989 let snapshot = buffer.read(cx);
3990 old_selections
3991 .iter()
3992 .map(|s| {
3993 let anchor = snapshot.anchor_after(s.head());
3994 s.map(|_| anchor)
3995 })
3996 .collect::<Vec<_>>()
3997 };
3998 buffer.edit(
3999 old_selections
4000 .iter()
4001 .map(|s| (s.start..s.end, text.clone())),
4002 autoindent_mode,
4003 cx,
4004 );
4005 anchors
4006 });
4007
4008 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4009 s.select_anchors(selection_anchors);
4010 })
4011 });
4012 }
4013
4014 fn trigger_completion_on_input(
4015 &mut self,
4016 text: &str,
4017 trigger_in_words: bool,
4018 cx: &mut ViewContext<Self>,
4019 ) {
4020 if self.is_completion_trigger(text, trigger_in_words, cx) {
4021 self.show_completions(
4022 &ShowCompletions {
4023 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4024 },
4025 cx,
4026 );
4027 } else {
4028 self.hide_context_menu(cx);
4029 }
4030 }
4031
4032 fn is_completion_trigger(
4033 &self,
4034 text: &str,
4035 trigger_in_words: bool,
4036 cx: &mut ViewContext<Self>,
4037 ) -> bool {
4038 let position = self.selections.newest_anchor().head();
4039 let multibuffer = self.buffer.read(cx);
4040 let Some(buffer) = position
4041 .buffer_id
4042 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4043 else {
4044 return false;
4045 };
4046
4047 if let Some(completion_provider) = &self.completion_provider {
4048 completion_provider.is_completion_trigger(
4049 &buffer,
4050 position.text_anchor,
4051 text,
4052 trigger_in_words,
4053 cx,
4054 )
4055 } else {
4056 false
4057 }
4058 }
4059
4060 /// If any empty selections is touching the start of its innermost containing autoclose
4061 /// region, expand it to select the brackets.
4062 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4063 let selections = self.selections.all::<usize>(cx);
4064 let buffer = self.buffer.read(cx).read(cx);
4065 let new_selections = self
4066 .selections_with_autoclose_regions(selections, &buffer)
4067 .map(|(mut selection, region)| {
4068 if !selection.is_empty() {
4069 return selection;
4070 }
4071
4072 if let Some(region) = region {
4073 let mut range = region.range.to_offset(&buffer);
4074 if selection.start == range.start && range.start >= region.pair.start.len() {
4075 range.start -= region.pair.start.len();
4076 if buffer.contains_str_at(range.start, ®ion.pair.start)
4077 && buffer.contains_str_at(range.end, ®ion.pair.end)
4078 {
4079 range.end += region.pair.end.len();
4080 selection.start = range.start;
4081 selection.end = range.end;
4082
4083 return selection;
4084 }
4085 }
4086 }
4087
4088 let always_treat_brackets_as_autoclosed = buffer
4089 .settings_at(selection.start, cx)
4090 .always_treat_brackets_as_autoclosed;
4091
4092 if !always_treat_brackets_as_autoclosed {
4093 return selection;
4094 }
4095
4096 if let Some(scope) = buffer.language_scope_at(selection.start) {
4097 for (pair, enabled) in scope.brackets() {
4098 if !enabled || !pair.close {
4099 continue;
4100 }
4101
4102 if buffer.contains_str_at(selection.start, &pair.end) {
4103 let pair_start_len = pair.start.len();
4104 if buffer.contains_str_at(
4105 selection.start.saturating_sub(pair_start_len),
4106 &pair.start,
4107 ) {
4108 selection.start -= pair_start_len;
4109 selection.end += pair.end.len();
4110
4111 return selection;
4112 }
4113 }
4114 }
4115 }
4116
4117 selection
4118 })
4119 .collect();
4120
4121 drop(buffer);
4122 self.change_selections(None, cx, |selections| selections.select(new_selections));
4123 }
4124
4125 /// Iterate the given selections, and for each one, find the smallest surrounding
4126 /// autoclose region. This uses the ordering of the selections and the autoclose
4127 /// regions to avoid repeated comparisons.
4128 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4129 &'a self,
4130 selections: impl IntoIterator<Item = Selection<D>>,
4131 buffer: &'a MultiBufferSnapshot,
4132 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4133 let mut i = 0;
4134 let mut regions = self.autoclose_regions.as_slice();
4135 selections.into_iter().map(move |selection| {
4136 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4137
4138 let mut enclosing = None;
4139 while let Some(pair_state) = regions.get(i) {
4140 if pair_state.range.end.to_offset(buffer) < range.start {
4141 regions = ®ions[i + 1..];
4142 i = 0;
4143 } else if pair_state.range.start.to_offset(buffer) > range.end {
4144 break;
4145 } else {
4146 if pair_state.selection_id == selection.id {
4147 enclosing = Some(pair_state);
4148 }
4149 i += 1;
4150 }
4151 }
4152
4153 (selection, enclosing)
4154 })
4155 }
4156
4157 /// Remove any autoclose regions that no longer contain their selection.
4158 fn invalidate_autoclose_regions(
4159 &mut self,
4160 mut selections: &[Selection<Anchor>],
4161 buffer: &MultiBufferSnapshot,
4162 ) {
4163 self.autoclose_regions.retain(|state| {
4164 let mut i = 0;
4165 while let Some(selection) = selections.get(i) {
4166 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4167 selections = &selections[1..];
4168 continue;
4169 }
4170 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4171 break;
4172 }
4173 if selection.id == state.selection_id {
4174 return true;
4175 } else {
4176 i += 1;
4177 }
4178 }
4179 false
4180 });
4181 }
4182
4183 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4184 let offset = position.to_offset(buffer);
4185 let (word_range, kind) = buffer.surrounding_word(offset, true);
4186 if offset > word_range.start && kind == Some(CharKind::Word) {
4187 Some(
4188 buffer
4189 .text_for_range(word_range.start..offset)
4190 .collect::<String>(),
4191 )
4192 } else {
4193 None
4194 }
4195 }
4196
4197 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4198 self.refresh_inlay_hints(
4199 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4200 cx,
4201 );
4202 }
4203
4204 pub fn inlay_hints_enabled(&self) -> bool {
4205 self.inlay_hint_cache.enabled
4206 }
4207
4208 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4209 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4210 return;
4211 }
4212
4213 let reason_description = reason.description();
4214 let ignore_debounce = matches!(
4215 reason,
4216 InlayHintRefreshReason::SettingsChange(_)
4217 | InlayHintRefreshReason::Toggle(_)
4218 | InlayHintRefreshReason::ExcerptsRemoved(_)
4219 );
4220 let (invalidate_cache, required_languages) = match reason {
4221 InlayHintRefreshReason::Toggle(enabled) => {
4222 self.inlay_hint_cache.enabled = enabled;
4223 if enabled {
4224 (InvalidationStrategy::RefreshRequested, None)
4225 } else {
4226 self.inlay_hint_cache.clear();
4227 self.splice_inlays(
4228 self.visible_inlay_hints(cx)
4229 .iter()
4230 .map(|inlay| inlay.id)
4231 .collect(),
4232 Vec::new(),
4233 cx,
4234 );
4235 return;
4236 }
4237 }
4238 InlayHintRefreshReason::SettingsChange(new_settings) => {
4239 match self.inlay_hint_cache.update_settings(
4240 &self.buffer,
4241 new_settings,
4242 self.visible_inlay_hints(cx),
4243 cx,
4244 ) {
4245 ControlFlow::Break(Some(InlaySplice {
4246 to_remove,
4247 to_insert,
4248 })) => {
4249 self.splice_inlays(to_remove, to_insert, cx);
4250 return;
4251 }
4252 ControlFlow::Break(None) => return,
4253 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4254 }
4255 }
4256 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4257 if let Some(InlaySplice {
4258 to_remove,
4259 to_insert,
4260 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4261 {
4262 self.splice_inlays(to_remove, to_insert, cx);
4263 }
4264 return;
4265 }
4266 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4267 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4268 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4269 }
4270 InlayHintRefreshReason::RefreshRequested => {
4271 (InvalidationStrategy::RefreshRequested, None)
4272 }
4273 };
4274
4275 if let Some(InlaySplice {
4276 to_remove,
4277 to_insert,
4278 }) = self.inlay_hint_cache.spawn_hint_refresh(
4279 reason_description,
4280 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4281 invalidate_cache,
4282 ignore_debounce,
4283 cx,
4284 ) {
4285 self.splice_inlays(to_remove, to_insert, cx);
4286 }
4287 }
4288
4289 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4290 self.display_map
4291 .read(cx)
4292 .current_inlays()
4293 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4294 .cloned()
4295 .collect()
4296 }
4297
4298 pub fn excerpts_for_inlay_hints_query(
4299 &self,
4300 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4301 cx: &mut ViewContext<Editor>,
4302 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4303 let Some(project) = self.project.as_ref() else {
4304 return HashMap::default();
4305 };
4306 let project = project.read(cx);
4307 let multi_buffer = self.buffer().read(cx);
4308 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4309 let multi_buffer_visible_start = self
4310 .scroll_manager
4311 .anchor()
4312 .anchor
4313 .to_point(&multi_buffer_snapshot);
4314 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4315 multi_buffer_visible_start
4316 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4317 Bias::Left,
4318 );
4319 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4320 multi_buffer
4321 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4322 .into_iter()
4323 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4324 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4325 let buffer = buffer_handle.read(cx);
4326 let buffer_file = project::File::from_dyn(buffer.file())?;
4327 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4328 let worktree_entry = buffer_worktree
4329 .read(cx)
4330 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4331 if worktree_entry.is_ignored {
4332 return None;
4333 }
4334
4335 let language = buffer.language()?;
4336 if let Some(restrict_to_languages) = restrict_to_languages {
4337 if !restrict_to_languages.contains(language) {
4338 return None;
4339 }
4340 }
4341 Some((
4342 excerpt_id,
4343 (
4344 buffer_handle,
4345 buffer.version().clone(),
4346 excerpt_visible_range,
4347 ),
4348 ))
4349 })
4350 .collect()
4351 }
4352
4353 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4354 TextLayoutDetails {
4355 text_system: cx.text_system().clone(),
4356 editor_style: self.style.clone().unwrap(),
4357 rem_size: cx.rem_size(),
4358 scroll_anchor: self.scroll_manager.anchor(),
4359 visible_rows: self.visible_line_count(),
4360 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4361 }
4362 }
4363
4364 fn splice_inlays(
4365 &self,
4366 to_remove: Vec<InlayId>,
4367 to_insert: Vec<Inlay>,
4368 cx: &mut ViewContext<Self>,
4369 ) {
4370 self.display_map.update(cx, |display_map, cx| {
4371 display_map.splice_inlays(to_remove, to_insert, cx);
4372 });
4373 cx.notify();
4374 }
4375
4376 fn trigger_on_type_formatting(
4377 &self,
4378 input: String,
4379 cx: &mut ViewContext<Self>,
4380 ) -> Option<Task<Result<()>>> {
4381 if input.len() != 1 {
4382 return None;
4383 }
4384
4385 let project = self.project.as_ref()?;
4386 let position = self.selections.newest_anchor().head();
4387 let (buffer, buffer_position) = self
4388 .buffer
4389 .read(cx)
4390 .text_anchor_for_position(position, cx)?;
4391
4392 let settings = language_settings::language_settings(
4393 buffer
4394 .read(cx)
4395 .language_at(buffer_position)
4396 .map(|l| l.name()),
4397 buffer.read(cx).file(),
4398 cx,
4399 );
4400 if !settings.use_on_type_format {
4401 return None;
4402 }
4403
4404 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4405 // hence we do LSP request & edit on host side only — add formats to host's history.
4406 let push_to_lsp_host_history = true;
4407 // If this is not the host, append its history with new edits.
4408 let push_to_client_history = project.read(cx).is_via_collab();
4409
4410 let on_type_formatting = project.update(cx, |project, cx| {
4411 project.on_type_format(
4412 buffer.clone(),
4413 buffer_position,
4414 input,
4415 push_to_lsp_host_history,
4416 cx,
4417 )
4418 });
4419 Some(cx.spawn(|editor, mut cx| async move {
4420 if let Some(transaction) = on_type_formatting.await? {
4421 if push_to_client_history {
4422 buffer
4423 .update(&mut cx, |buffer, _| {
4424 buffer.push_transaction(transaction, Instant::now());
4425 })
4426 .ok();
4427 }
4428 editor.update(&mut cx, |editor, cx| {
4429 editor.refresh_document_highlights(cx);
4430 })?;
4431 }
4432 Ok(())
4433 }))
4434 }
4435
4436 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4437 if self.pending_rename.is_some() {
4438 return;
4439 }
4440
4441 let Some(provider) = self.completion_provider.as_ref() else {
4442 return;
4443 };
4444
4445 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4446 return;
4447 }
4448
4449 let position = self.selections.newest_anchor().head();
4450 let (buffer, buffer_position) =
4451 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4452 output
4453 } else {
4454 return;
4455 };
4456
4457 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4458 let is_followup_invoke = {
4459 let context_menu_state = self.context_menu.read();
4460 matches!(
4461 context_menu_state.deref(),
4462 Some(ContextMenu::Completions(_))
4463 )
4464 };
4465 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4466 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4467 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4468 CompletionTriggerKind::TRIGGER_CHARACTER
4469 }
4470
4471 _ => CompletionTriggerKind::INVOKED,
4472 };
4473 let completion_context = CompletionContext {
4474 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4475 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4476 Some(String::from(trigger))
4477 } else {
4478 None
4479 }
4480 }),
4481 trigger_kind,
4482 };
4483 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4484 let sort_completions = provider.sort_completions();
4485
4486 let id = post_inc(&mut self.next_completion_id);
4487 let task = cx.spawn(|editor, mut cx| {
4488 async move {
4489 editor.update(&mut cx, |this, _| {
4490 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4491 })?;
4492 let completions = completions.await.log_err();
4493 let menu = if let Some(completions) = completions {
4494 let mut menu = CompletionsMenu::new(
4495 id,
4496 sort_completions,
4497 position,
4498 buffer.clone(),
4499 completions.into(),
4500 );
4501 menu.filter(query.as_deref(), cx.background_executor().clone())
4502 .await;
4503
4504 if menu.matches.is_empty() {
4505 None
4506 } else {
4507 Some(menu)
4508 }
4509 } else {
4510 None
4511 };
4512
4513 editor.update(&mut cx, |editor, cx| {
4514 let mut context_menu = editor.context_menu.write();
4515 match context_menu.as_ref() {
4516 None => {}
4517
4518 Some(ContextMenu::Completions(prev_menu)) => {
4519 if prev_menu.id > id {
4520 return;
4521 }
4522 }
4523
4524 _ => return,
4525 }
4526
4527 if editor.focus_handle.is_focused(cx) && menu.is_some() {
4528 let mut menu = menu.unwrap();
4529 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
4530 *context_menu = Some(ContextMenu::Completions(menu));
4531 drop(context_menu);
4532 editor.discard_inline_completion(false, cx);
4533 cx.notify();
4534 } else if editor.completion_tasks.len() <= 1 {
4535 // If there are no more completion tasks and the last menu was
4536 // empty, we should hide it. If it was already hidden, we should
4537 // also show the copilot completion when available.
4538 drop(context_menu);
4539 if editor.hide_context_menu(cx).is_none() {
4540 editor.update_visible_inline_completion(cx);
4541 }
4542 }
4543 })?;
4544
4545 Ok::<_, anyhow::Error>(())
4546 }
4547 .log_err()
4548 });
4549
4550 self.completion_tasks.push((id, task));
4551 }
4552
4553 pub fn confirm_completion(
4554 &mut self,
4555 action: &ConfirmCompletion,
4556 cx: &mut ViewContext<Self>,
4557 ) -> Option<Task<Result<()>>> {
4558 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4559 }
4560
4561 pub fn compose_completion(
4562 &mut self,
4563 action: &ComposeCompletion,
4564 cx: &mut ViewContext<Self>,
4565 ) -> Option<Task<Result<()>>> {
4566 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4567 }
4568
4569 fn do_completion(
4570 &mut self,
4571 item_ix: Option<usize>,
4572 intent: CompletionIntent,
4573 cx: &mut ViewContext<Editor>,
4574 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4575 use language::ToOffset as _;
4576
4577 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4578 menu
4579 } else {
4580 return None;
4581 };
4582
4583 let mat = completions_menu
4584 .matches
4585 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4586 let buffer_handle = completions_menu.buffer;
4587 let completions = completions_menu.completions.read();
4588 let completion = completions.get(mat.candidate_id)?;
4589 cx.stop_propagation();
4590
4591 let snippet;
4592 let text;
4593
4594 if completion.is_snippet() {
4595 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4596 text = snippet.as_ref().unwrap().text.clone();
4597 } else {
4598 snippet = None;
4599 text = completion.new_text.clone();
4600 };
4601 let selections = self.selections.all::<usize>(cx);
4602 let buffer = buffer_handle.read(cx);
4603 let old_range = completion.old_range.to_offset(buffer);
4604 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4605
4606 let newest_selection = self.selections.newest_anchor();
4607 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4608 return None;
4609 }
4610
4611 let lookbehind = newest_selection
4612 .start
4613 .text_anchor
4614 .to_offset(buffer)
4615 .saturating_sub(old_range.start);
4616 let lookahead = old_range
4617 .end
4618 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4619 let mut common_prefix_len = old_text
4620 .bytes()
4621 .zip(text.bytes())
4622 .take_while(|(a, b)| a == b)
4623 .count();
4624
4625 let snapshot = self.buffer.read(cx).snapshot(cx);
4626 let mut range_to_replace: Option<Range<isize>> = None;
4627 let mut ranges = Vec::new();
4628 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4629 for selection in &selections {
4630 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4631 let start = selection.start.saturating_sub(lookbehind);
4632 let end = selection.end + lookahead;
4633 if selection.id == newest_selection.id {
4634 range_to_replace = Some(
4635 ((start + common_prefix_len) as isize - selection.start as isize)
4636 ..(end as isize - selection.start as isize),
4637 );
4638 }
4639 ranges.push(start + common_prefix_len..end);
4640 } else {
4641 common_prefix_len = 0;
4642 ranges.clear();
4643 ranges.extend(selections.iter().map(|s| {
4644 if s.id == newest_selection.id {
4645 range_to_replace = Some(
4646 old_range.start.to_offset_utf16(&snapshot).0 as isize
4647 - selection.start as isize
4648 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4649 - selection.start as isize,
4650 );
4651 old_range.clone()
4652 } else {
4653 s.start..s.end
4654 }
4655 }));
4656 break;
4657 }
4658 if !self.linked_edit_ranges.is_empty() {
4659 let start_anchor = snapshot.anchor_before(selection.head());
4660 let end_anchor = snapshot.anchor_after(selection.tail());
4661 if let Some(ranges) = self
4662 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4663 {
4664 for (buffer, edits) in ranges {
4665 linked_edits.entry(buffer.clone()).or_default().extend(
4666 edits
4667 .into_iter()
4668 .map(|range| (range, text[common_prefix_len..].to_owned())),
4669 );
4670 }
4671 }
4672 }
4673 }
4674 let text = &text[common_prefix_len..];
4675
4676 cx.emit(EditorEvent::InputHandled {
4677 utf16_range_to_replace: range_to_replace,
4678 text: text.into(),
4679 });
4680
4681 self.transact(cx, |this, cx| {
4682 if let Some(mut snippet) = snippet {
4683 snippet.text = text.to_string();
4684 for tabstop in snippet
4685 .tabstops
4686 .iter_mut()
4687 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4688 {
4689 tabstop.start -= common_prefix_len as isize;
4690 tabstop.end -= common_prefix_len as isize;
4691 }
4692
4693 this.insert_snippet(&ranges, snippet, cx).log_err();
4694 } else {
4695 this.buffer.update(cx, |buffer, cx| {
4696 buffer.edit(
4697 ranges.iter().map(|range| (range.clone(), text)),
4698 this.autoindent_mode.clone(),
4699 cx,
4700 );
4701 });
4702 }
4703 for (buffer, edits) in linked_edits {
4704 buffer.update(cx, |buffer, cx| {
4705 let snapshot = buffer.snapshot();
4706 let edits = edits
4707 .into_iter()
4708 .map(|(range, text)| {
4709 use text::ToPoint as TP;
4710 let end_point = TP::to_point(&range.end, &snapshot);
4711 let start_point = TP::to_point(&range.start, &snapshot);
4712 (start_point..end_point, text)
4713 })
4714 .sorted_by_key(|(range, _)| range.start)
4715 .collect::<Vec<_>>();
4716 buffer.edit(edits, None, cx);
4717 })
4718 }
4719
4720 this.refresh_inline_completion(true, false, cx);
4721 });
4722
4723 let show_new_completions_on_confirm = completion
4724 .confirm
4725 .as_ref()
4726 .map_or(false, |confirm| confirm(intent, cx));
4727 if show_new_completions_on_confirm {
4728 self.show_completions(&ShowCompletions { trigger: None }, cx);
4729 }
4730
4731 let provider = self.completion_provider.as_ref()?;
4732 let apply_edits = provider.apply_additional_edits_for_completion(
4733 buffer_handle,
4734 completion.clone(),
4735 true,
4736 cx,
4737 );
4738
4739 let editor_settings = EditorSettings::get_global(cx);
4740 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4741 // After the code completion is finished, users often want to know what signatures are needed.
4742 // so we should automatically call signature_help
4743 self.show_signature_help(&ShowSignatureHelp, cx);
4744 }
4745
4746 Some(cx.foreground_executor().spawn(async move {
4747 apply_edits.await?;
4748 Ok(())
4749 }))
4750 }
4751
4752 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4753 let mut context_menu = self.context_menu.write();
4754 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4755 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4756 // Toggle if we're selecting the same one
4757 *context_menu = None;
4758 cx.notify();
4759 return;
4760 } else {
4761 // Otherwise, clear it and start a new one
4762 *context_menu = None;
4763 cx.notify();
4764 }
4765 }
4766 drop(context_menu);
4767 let snapshot = self.snapshot(cx);
4768 let deployed_from_indicator = action.deployed_from_indicator;
4769 let mut task = self.code_actions_task.take();
4770 let action = action.clone();
4771 cx.spawn(|editor, mut cx| async move {
4772 while let Some(prev_task) = task {
4773 prev_task.await.log_err();
4774 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4775 }
4776
4777 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4778 if editor.focus_handle.is_focused(cx) {
4779 let multibuffer_point = action
4780 .deployed_from_indicator
4781 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4782 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4783 let (buffer, buffer_row) = snapshot
4784 .buffer_snapshot
4785 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4786 .and_then(|(buffer_snapshot, range)| {
4787 editor
4788 .buffer
4789 .read(cx)
4790 .buffer(buffer_snapshot.remote_id())
4791 .map(|buffer| (buffer, range.start.row))
4792 })?;
4793 let (_, code_actions) = editor
4794 .available_code_actions
4795 .clone()
4796 .and_then(|(location, code_actions)| {
4797 let snapshot = location.buffer.read(cx).snapshot();
4798 let point_range = location.range.to_point(&snapshot);
4799 let point_range = point_range.start.row..=point_range.end.row;
4800 if point_range.contains(&buffer_row) {
4801 Some((location, code_actions))
4802 } else {
4803 None
4804 }
4805 })
4806 .unzip();
4807 let buffer_id = buffer.read(cx).remote_id();
4808 let tasks = editor
4809 .tasks
4810 .get(&(buffer_id, buffer_row))
4811 .map(|t| Arc::new(t.to_owned()));
4812 if tasks.is_none() && code_actions.is_none() {
4813 return None;
4814 }
4815
4816 editor.completion_tasks.clear();
4817 editor.discard_inline_completion(false, cx);
4818 let task_context =
4819 tasks
4820 .as_ref()
4821 .zip(editor.project.clone())
4822 .map(|(tasks, project)| {
4823 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4824 });
4825
4826 Some(cx.spawn(|editor, mut cx| async move {
4827 let task_context = match task_context {
4828 Some(task_context) => task_context.await,
4829 None => None,
4830 };
4831 let resolved_tasks =
4832 tasks.zip(task_context).map(|(tasks, task_context)| {
4833 Arc::new(ResolvedTasks {
4834 templates: tasks.resolve(&task_context).collect(),
4835 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4836 multibuffer_point.row,
4837 tasks.column,
4838 )),
4839 })
4840 });
4841 let spawn_straight_away = resolved_tasks
4842 .as_ref()
4843 .map_or(false, |tasks| tasks.templates.len() == 1)
4844 && code_actions
4845 .as_ref()
4846 .map_or(true, |actions| actions.is_empty());
4847 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4848 *editor.context_menu.write() =
4849 Some(ContextMenu::CodeActions(CodeActionsMenu {
4850 buffer,
4851 actions: CodeActionContents {
4852 tasks: resolved_tasks,
4853 actions: code_actions,
4854 },
4855 selected_item: Default::default(),
4856 scroll_handle: UniformListScrollHandle::default(),
4857 deployed_from_indicator,
4858 }));
4859 if spawn_straight_away {
4860 if let Some(task) = editor.confirm_code_action(
4861 &ConfirmCodeAction { item_ix: Some(0) },
4862 cx,
4863 ) {
4864 cx.notify();
4865 return task;
4866 }
4867 }
4868 cx.notify();
4869 Task::ready(Ok(()))
4870 }) {
4871 task.await
4872 } else {
4873 Ok(())
4874 }
4875 }))
4876 } else {
4877 Some(Task::ready(Ok(())))
4878 }
4879 })?;
4880 if let Some(task) = spawned_test_task {
4881 task.await?;
4882 }
4883
4884 Ok::<_, anyhow::Error>(())
4885 })
4886 .detach_and_log_err(cx);
4887 }
4888
4889 pub fn confirm_code_action(
4890 &mut self,
4891 action: &ConfirmCodeAction,
4892 cx: &mut ViewContext<Self>,
4893 ) -> Option<Task<Result<()>>> {
4894 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4895 menu
4896 } else {
4897 return None;
4898 };
4899 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4900 let action = actions_menu.actions.get(action_ix)?;
4901 let title = action.label();
4902 let buffer = actions_menu.buffer;
4903 let workspace = self.workspace()?;
4904
4905 match action {
4906 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4907 workspace.update(cx, |workspace, cx| {
4908 workspace::tasks::schedule_resolved_task(
4909 workspace,
4910 task_source_kind,
4911 resolved_task,
4912 false,
4913 cx,
4914 );
4915
4916 Some(Task::ready(Ok(())))
4917 })
4918 }
4919 CodeActionsItem::CodeAction {
4920 excerpt_id,
4921 action,
4922 provider,
4923 } => {
4924 let apply_code_action =
4925 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4926 let workspace = workspace.downgrade();
4927 Some(cx.spawn(|editor, cx| async move {
4928 let project_transaction = apply_code_action.await?;
4929 Self::open_project_transaction(
4930 &editor,
4931 workspace,
4932 project_transaction,
4933 title,
4934 cx,
4935 )
4936 .await
4937 }))
4938 }
4939 }
4940 }
4941
4942 pub async fn open_project_transaction(
4943 this: &WeakView<Editor>,
4944 workspace: WeakView<Workspace>,
4945 transaction: ProjectTransaction,
4946 title: String,
4947 mut cx: AsyncWindowContext,
4948 ) -> Result<()> {
4949 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4950 cx.update(|cx| {
4951 entries.sort_unstable_by_key(|(buffer, _)| {
4952 buffer.read(cx).file().map(|f| f.path().clone())
4953 });
4954 })?;
4955
4956 // If the project transaction's edits are all contained within this editor, then
4957 // avoid opening a new editor to display them.
4958
4959 if let Some((buffer, transaction)) = entries.first() {
4960 if entries.len() == 1 {
4961 let excerpt = this.update(&mut cx, |editor, cx| {
4962 editor
4963 .buffer()
4964 .read(cx)
4965 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4966 })?;
4967 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4968 if excerpted_buffer == *buffer {
4969 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4970 let excerpt_range = excerpt_range.to_offset(buffer);
4971 buffer
4972 .edited_ranges_for_transaction::<usize>(transaction)
4973 .all(|range| {
4974 excerpt_range.start <= range.start
4975 && excerpt_range.end >= range.end
4976 })
4977 })?;
4978
4979 if all_edits_within_excerpt {
4980 return Ok(());
4981 }
4982 }
4983 }
4984 }
4985 } else {
4986 return Ok(());
4987 }
4988
4989 let mut ranges_to_highlight = Vec::new();
4990 let excerpt_buffer = cx.new_model(|cx| {
4991 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4992 for (buffer_handle, transaction) in &entries {
4993 let buffer = buffer_handle.read(cx);
4994 ranges_to_highlight.extend(
4995 multibuffer.push_excerpts_with_context_lines(
4996 buffer_handle.clone(),
4997 buffer
4998 .edited_ranges_for_transaction::<usize>(transaction)
4999 .collect(),
5000 DEFAULT_MULTIBUFFER_CONTEXT,
5001 cx,
5002 ),
5003 );
5004 }
5005 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5006 multibuffer
5007 })?;
5008
5009 workspace.update(&mut cx, |workspace, cx| {
5010 let project = workspace.project().clone();
5011 let editor =
5012 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5013 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5014 editor.update(cx, |editor, cx| {
5015 editor.highlight_background::<Self>(
5016 &ranges_to_highlight,
5017 |theme| theme.editor_highlighted_line_background,
5018 cx,
5019 );
5020 });
5021 })?;
5022
5023 Ok(())
5024 }
5025
5026 pub fn clear_code_action_providers(&mut self) {
5027 self.code_action_providers.clear();
5028 self.available_code_actions.take();
5029 }
5030
5031 pub fn push_code_action_provider(
5032 &mut self,
5033 provider: Arc<dyn CodeActionProvider>,
5034 cx: &mut ViewContext<Self>,
5035 ) {
5036 self.code_action_providers.push(provider);
5037 self.refresh_code_actions(cx);
5038 }
5039
5040 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5041 let buffer = self.buffer.read(cx);
5042 let newest_selection = self.selections.newest_anchor().clone();
5043 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5044 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5045 if start_buffer != end_buffer {
5046 return None;
5047 }
5048
5049 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5050 cx.background_executor()
5051 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5052 .await;
5053
5054 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5055 let providers = this.code_action_providers.clone();
5056 let tasks = this
5057 .code_action_providers
5058 .iter()
5059 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5060 .collect::<Vec<_>>();
5061 (providers, tasks)
5062 })?;
5063
5064 let mut actions = Vec::new();
5065 for (provider, provider_actions) in
5066 providers.into_iter().zip(future::join_all(tasks).await)
5067 {
5068 if let Some(provider_actions) = provider_actions.log_err() {
5069 actions.extend(provider_actions.into_iter().map(|action| {
5070 AvailableCodeAction {
5071 excerpt_id: newest_selection.start.excerpt_id,
5072 action,
5073 provider: provider.clone(),
5074 }
5075 }));
5076 }
5077 }
5078
5079 this.update(&mut cx, |this, cx| {
5080 this.available_code_actions = if actions.is_empty() {
5081 None
5082 } else {
5083 Some((
5084 Location {
5085 buffer: start_buffer,
5086 range: start..end,
5087 },
5088 actions.into(),
5089 ))
5090 };
5091 cx.notify();
5092 })
5093 }));
5094 None
5095 }
5096
5097 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5098 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5099 self.show_git_blame_inline = false;
5100
5101 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5102 cx.background_executor().timer(delay).await;
5103
5104 this.update(&mut cx, |this, cx| {
5105 this.show_git_blame_inline = true;
5106 cx.notify();
5107 })
5108 .log_err();
5109 }));
5110 }
5111 }
5112
5113 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5114 if self.pending_rename.is_some() {
5115 return None;
5116 }
5117
5118 let provider = self.semantics_provider.clone()?;
5119 let buffer = self.buffer.read(cx);
5120 let newest_selection = self.selections.newest_anchor().clone();
5121 let cursor_position = newest_selection.head();
5122 let (cursor_buffer, cursor_buffer_position) =
5123 buffer.text_anchor_for_position(cursor_position, cx)?;
5124 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5125 if cursor_buffer != tail_buffer {
5126 return None;
5127 }
5128
5129 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5130 cx.background_executor()
5131 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5132 .await;
5133
5134 let highlights = if let Some(highlights) = cx
5135 .update(|cx| {
5136 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5137 })
5138 .ok()
5139 .flatten()
5140 {
5141 highlights.await.log_err()
5142 } else {
5143 None
5144 };
5145
5146 if let Some(highlights) = highlights {
5147 this.update(&mut cx, |this, cx| {
5148 if this.pending_rename.is_some() {
5149 return;
5150 }
5151
5152 let buffer_id = cursor_position.buffer_id;
5153 let buffer = this.buffer.read(cx);
5154 if !buffer
5155 .text_anchor_for_position(cursor_position, cx)
5156 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5157 {
5158 return;
5159 }
5160
5161 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5162 let mut write_ranges = Vec::new();
5163 let mut read_ranges = Vec::new();
5164 for highlight in highlights {
5165 for (excerpt_id, excerpt_range) in
5166 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5167 {
5168 let start = highlight
5169 .range
5170 .start
5171 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5172 let end = highlight
5173 .range
5174 .end
5175 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5176 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5177 continue;
5178 }
5179
5180 let range = Anchor {
5181 buffer_id,
5182 excerpt_id,
5183 text_anchor: start,
5184 }..Anchor {
5185 buffer_id,
5186 excerpt_id,
5187 text_anchor: end,
5188 };
5189 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5190 write_ranges.push(range);
5191 } else {
5192 read_ranges.push(range);
5193 }
5194 }
5195 }
5196
5197 this.highlight_background::<DocumentHighlightRead>(
5198 &read_ranges,
5199 |theme| theme.editor_document_highlight_read_background,
5200 cx,
5201 );
5202 this.highlight_background::<DocumentHighlightWrite>(
5203 &write_ranges,
5204 |theme| theme.editor_document_highlight_write_background,
5205 cx,
5206 );
5207 cx.notify();
5208 })
5209 .log_err();
5210 }
5211 }));
5212 None
5213 }
5214
5215 pub fn refresh_inline_completion(
5216 &mut self,
5217 debounce: bool,
5218 user_requested: bool,
5219 cx: &mut ViewContext<Self>,
5220 ) -> Option<()> {
5221 let provider = self.inline_completion_provider()?;
5222 let cursor = self.selections.newest_anchor().head();
5223 let (buffer, cursor_buffer_position) =
5224 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5225
5226 if !user_requested
5227 && (!self.enable_inline_completions
5228 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5229 {
5230 self.discard_inline_completion(false, cx);
5231 return None;
5232 }
5233
5234 self.update_visible_inline_completion(cx);
5235 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5236 Some(())
5237 }
5238
5239 fn cycle_inline_completion(
5240 &mut self,
5241 direction: Direction,
5242 cx: &mut ViewContext<Self>,
5243 ) -> Option<()> {
5244 let provider = self.inline_completion_provider()?;
5245 let cursor = self.selections.newest_anchor().head();
5246 let (buffer, cursor_buffer_position) =
5247 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5248 if !self.enable_inline_completions
5249 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5250 {
5251 return None;
5252 }
5253
5254 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5255 self.update_visible_inline_completion(cx);
5256
5257 Some(())
5258 }
5259
5260 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5261 if !self.has_active_inline_completion(cx) {
5262 self.refresh_inline_completion(false, true, cx);
5263 return;
5264 }
5265
5266 self.update_visible_inline_completion(cx);
5267 }
5268
5269 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5270 self.show_cursor_names(cx);
5271 }
5272
5273 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5274 self.show_cursor_names = true;
5275 cx.notify();
5276 cx.spawn(|this, mut cx| async move {
5277 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5278 this.update(&mut cx, |this, cx| {
5279 this.show_cursor_names = false;
5280 cx.notify()
5281 })
5282 .ok()
5283 })
5284 .detach();
5285 }
5286
5287 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5288 if self.has_active_inline_completion(cx) {
5289 self.cycle_inline_completion(Direction::Next, cx);
5290 } else {
5291 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5292 if is_copilot_disabled {
5293 cx.propagate();
5294 }
5295 }
5296 }
5297
5298 pub fn previous_inline_completion(
5299 &mut self,
5300 _: &PreviousInlineCompletion,
5301 cx: &mut ViewContext<Self>,
5302 ) {
5303 if self.has_active_inline_completion(cx) {
5304 self.cycle_inline_completion(Direction::Prev, cx);
5305 } else {
5306 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5307 if is_copilot_disabled {
5308 cx.propagate();
5309 }
5310 }
5311 }
5312
5313 pub fn accept_inline_completion(
5314 &mut self,
5315 _: &AcceptInlineCompletion,
5316 cx: &mut ViewContext<Self>,
5317 ) {
5318 let Some(completion) = self.take_active_inline_completion(cx) else {
5319 return;
5320 };
5321 if let Some(provider) = self.inline_completion_provider() {
5322 provider.accept(cx);
5323 }
5324
5325 cx.emit(EditorEvent::InputHandled {
5326 utf16_range_to_replace: None,
5327 text: completion.text.to_string().into(),
5328 });
5329
5330 if let Some(range) = completion.delete_range {
5331 self.change_selections(None, cx, |s| s.select_ranges([range]))
5332 }
5333 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5334 self.refresh_inline_completion(true, true, cx);
5335 cx.notify();
5336 }
5337
5338 pub fn accept_partial_inline_completion(
5339 &mut self,
5340 _: &AcceptPartialInlineCompletion,
5341 cx: &mut ViewContext<Self>,
5342 ) {
5343 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5344 if let Some(completion) = self.take_active_inline_completion(cx) {
5345 let mut partial_completion = completion
5346 .text
5347 .chars()
5348 .by_ref()
5349 .take_while(|c| c.is_alphabetic())
5350 .collect::<String>();
5351 if partial_completion.is_empty() {
5352 partial_completion = completion
5353 .text
5354 .chars()
5355 .by_ref()
5356 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5357 .collect::<String>();
5358 }
5359
5360 cx.emit(EditorEvent::InputHandled {
5361 utf16_range_to_replace: None,
5362 text: partial_completion.clone().into(),
5363 });
5364
5365 if let Some(range) = completion.delete_range {
5366 self.change_selections(None, cx, |s| s.select_ranges([range]))
5367 }
5368 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5369
5370 self.refresh_inline_completion(true, true, cx);
5371 cx.notify();
5372 }
5373 }
5374 }
5375
5376 fn discard_inline_completion(
5377 &mut self,
5378 should_report_inline_completion_event: bool,
5379 cx: &mut ViewContext<Self>,
5380 ) -> bool {
5381 if let Some(provider) = self.inline_completion_provider() {
5382 provider.discard(should_report_inline_completion_event, cx);
5383 }
5384
5385 self.take_active_inline_completion(cx).is_some()
5386 }
5387
5388 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5389 if let Some(completion) = self.active_inline_completion.as_ref() {
5390 let buffer = self.buffer.read(cx).read(cx);
5391 completion.position.is_valid(&buffer)
5392 } else {
5393 false
5394 }
5395 }
5396
5397 fn take_active_inline_completion(
5398 &mut self,
5399 cx: &mut ViewContext<Self>,
5400 ) -> Option<CompletionState> {
5401 let completion = self.active_inline_completion.take()?;
5402 let render_inlay_ids = completion.render_inlay_ids.clone();
5403 self.display_map.update(cx, |map, cx| {
5404 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5405 });
5406 let buffer = self.buffer.read(cx).read(cx);
5407
5408 if completion.position.is_valid(&buffer) {
5409 Some(completion)
5410 } else {
5411 None
5412 }
5413 }
5414
5415 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5416 let selection = self.selections.newest_anchor();
5417 let cursor = selection.head();
5418
5419 let excerpt_id = cursor.excerpt_id;
5420
5421 if self.context_menu.read().is_none()
5422 && self.completion_tasks.is_empty()
5423 && selection.start == selection.end
5424 {
5425 if let Some(provider) = self.inline_completion_provider() {
5426 if let Some((buffer, cursor_buffer_position)) =
5427 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5428 {
5429 if let Some(proposal) =
5430 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5431 {
5432 let mut to_remove = Vec::new();
5433 if let Some(completion) = self.active_inline_completion.take() {
5434 to_remove.extend(completion.render_inlay_ids.iter());
5435 }
5436
5437 let to_add = proposal
5438 .inlays
5439 .iter()
5440 .filter_map(|inlay| {
5441 let snapshot = self.buffer.read(cx).snapshot(cx);
5442 let id = post_inc(&mut self.next_inlay_id);
5443 match inlay {
5444 InlayProposal::Hint(position, hint) => {
5445 let position =
5446 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5447 Some(Inlay::hint(id, position, hint))
5448 }
5449 InlayProposal::Suggestion(position, text) => {
5450 let position =
5451 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5452 Some(Inlay::suggestion(id, position, text.clone()))
5453 }
5454 }
5455 })
5456 .collect_vec();
5457
5458 self.active_inline_completion = Some(CompletionState {
5459 position: cursor,
5460 text: proposal.text,
5461 delete_range: proposal.delete_range.and_then(|range| {
5462 let snapshot = self.buffer.read(cx).snapshot(cx);
5463 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5464 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5465 Some(start?..end?)
5466 }),
5467 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5468 });
5469
5470 self.display_map
5471 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5472
5473 cx.notify();
5474 return;
5475 }
5476 }
5477 }
5478 }
5479
5480 self.discard_inline_completion(false, cx);
5481 }
5482
5483 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5484 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5485 }
5486
5487 fn render_code_actions_indicator(
5488 &self,
5489 _style: &EditorStyle,
5490 row: DisplayRow,
5491 is_active: bool,
5492 cx: &mut ViewContext<Self>,
5493 ) -> Option<IconButton> {
5494 if self.available_code_actions.is_some() {
5495 Some(
5496 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5497 .shape(ui::IconButtonShape::Square)
5498 .icon_size(IconSize::XSmall)
5499 .icon_color(Color::Muted)
5500 .selected(is_active)
5501 .tooltip({
5502 let focus_handle = self.focus_handle.clone();
5503 move |cx| {
5504 Tooltip::for_action_in(
5505 "Toggle Code Actions",
5506 &ToggleCodeActions {
5507 deployed_from_indicator: None,
5508 },
5509 &focus_handle,
5510 cx,
5511 )
5512 }
5513 })
5514 .on_click(cx.listener(move |editor, _e, cx| {
5515 editor.focus(cx);
5516 editor.toggle_code_actions(
5517 &ToggleCodeActions {
5518 deployed_from_indicator: Some(row),
5519 },
5520 cx,
5521 );
5522 })),
5523 )
5524 } else {
5525 None
5526 }
5527 }
5528
5529 fn clear_tasks(&mut self) {
5530 self.tasks.clear()
5531 }
5532
5533 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5534 if self.tasks.insert(key, value).is_some() {
5535 // This case should hopefully be rare, but just in case...
5536 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5537 }
5538 }
5539
5540 fn build_tasks_context(
5541 project: &Model<Project>,
5542 buffer: &Model<Buffer>,
5543 buffer_row: u32,
5544 tasks: &Arc<RunnableTasks>,
5545 cx: &mut ViewContext<Self>,
5546 ) -> Task<Option<task::TaskContext>> {
5547 let position = Point::new(buffer_row, tasks.column);
5548 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5549 let location = Location {
5550 buffer: buffer.clone(),
5551 range: range_start..range_start,
5552 };
5553 // Fill in the environmental variables from the tree-sitter captures
5554 let mut captured_task_variables = TaskVariables::default();
5555 for (capture_name, value) in tasks.extra_variables.clone() {
5556 captured_task_variables.insert(
5557 task::VariableName::Custom(capture_name.into()),
5558 value.clone(),
5559 );
5560 }
5561 project.update(cx, |project, cx| {
5562 project.task_store().update(cx, |task_store, cx| {
5563 task_store.task_context_for_location(captured_task_variables, location, cx)
5564 })
5565 })
5566 }
5567
5568 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5569 let Some((workspace, _)) = self.workspace.clone() else {
5570 return;
5571 };
5572 let Some(project) = self.project.clone() else {
5573 return;
5574 };
5575
5576 // Try to find a closest, enclosing node using tree-sitter that has a
5577 // task
5578 let Some((buffer, buffer_row, tasks)) = self
5579 .find_enclosing_node_task(cx)
5580 // Or find the task that's closest in row-distance.
5581 .or_else(|| self.find_closest_task(cx))
5582 else {
5583 return;
5584 };
5585
5586 let reveal_strategy = action.reveal;
5587 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5588 cx.spawn(|_, mut cx| async move {
5589 let context = task_context.await?;
5590 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5591
5592 let resolved = resolved_task.resolved.as_mut()?;
5593 resolved.reveal = reveal_strategy;
5594
5595 workspace
5596 .update(&mut cx, |workspace, cx| {
5597 workspace::tasks::schedule_resolved_task(
5598 workspace,
5599 task_source_kind,
5600 resolved_task,
5601 false,
5602 cx,
5603 );
5604 })
5605 .ok()
5606 })
5607 .detach();
5608 }
5609
5610 fn find_closest_task(
5611 &mut self,
5612 cx: &mut ViewContext<Self>,
5613 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5614 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5615
5616 let ((buffer_id, row), tasks) = self
5617 .tasks
5618 .iter()
5619 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5620
5621 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5622 let tasks = Arc::new(tasks.to_owned());
5623 Some((buffer, *row, tasks))
5624 }
5625
5626 fn find_enclosing_node_task(
5627 &mut self,
5628 cx: &mut ViewContext<Self>,
5629 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5630 let snapshot = self.buffer.read(cx).snapshot(cx);
5631 let offset = self.selections.newest::<usize>(cx).head();
5632 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5633 let buffer_id = excerpt.buffer().remote_id();
5634
5635 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5636 let mut cursor = layer.node().walk();
5637
5638 while cursor.goto_first_child_for_byte(offset).is_some() {
5639 if cursor.node().end_byte() == offset {
5640 cursor.goto_next_sibling();
5641 }
5642 }
5643
5644 // Ascend to the smallest ancestor that contains the range and has a task.
5645 loop {
5646 let node = cursor.node();
5647 let node_range = node.byte_range();
5648 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5649
5650 // Check if this node contains our offset
5651 if node_range.start <= offset && node_range.end >= offset {
5652 // If it contains offset, check for task
5653 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5654 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5655 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5656 }
5657 }
5658
5659 if !cursor.goto_parent() {
5660 break;
5661 }
5662 }
5663 None
5664 }
5665
5666 fn render_run_indicator(
5667 &self,
5668 _style: &EditorStyle,
5669 is_active: bool,
5670 row: DisplayRow,
5671 cx: &mut ViewContext<Self>,
5672 ) -> IconButton {
5673 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5674 .shape(ui::IconButtonShape::Square)
5675 .icon_size(IconSize::XSmall)
5676 .icon_color(Color::Muted)
5677 .selected(is_active)
5678 .on_click(cx.listener(move |editor, _e, cx| {
5679 editor.focus(cx);
5680 editor.toggle_code_actions(
5681 &ToggleCodeActions {
5682 deployed_from_indicator: Some(row),
5683 },
5684 cx,
5685 );
5686 }))
5687 }
5688
5689 pub fn context_menu_visible(&self) -> bool {
5690 self.context_menu
5691 .read()
5692 .as_ref()
5693 .map_or(false, |menu| menu.visible())
5694 }
5695
5696 fn render_context_menu(
5697 &self,
5698 cursor_position: DisplayPoint,
5699 style: &EditorStyle,
5700 max_height: Pixels,
5701 cx: &mut ViewContext<Editor>,
5702 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5703 self.context_menu.read().as_ref().map(|menu| {
5704 menu.render(
5705 cursor_position,
5706 style,
5707 max_height,
5708 self.workspace.as_ref().map(|(w, _)| w.clone()),
5709 cx,
5710 )
5711 })
5712 }
5713
5714 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5715 cx.notify();
5716 self.completion_tasks.clear();
5717 let context_menu = self.context_menu.write().take();
5718 if context_menu.is_some() {
5719 self.update_visible_inline_completion(cx);
5720 }
5721 context_menu
5722 }
5723
5724 fn show_snippet_choices(
5725 &mut self,
5726 choices: &Vec<String>,
5727 selection: Range<Anchor>,
5728 cx: &mut ViewContext<Self>,
5729 ) {
5730 if selection.start.buffer_id.is_none() {
5731 return;
5732 }
5733 let buffer_id = selection.start.buffer_id.unwrap();
5734 let buffer = self.buffer().read(cx).buffer(buffer_id);
5735 let id = post_inc(&mut self.next_completion_id);
5736
5737 if let Some(buffer) = buffer {
5738 *self.context_menu.write() = Some(ContextMenu::Completions(
5739 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5740 .suppress_documentation_resolution(),
5741 ));
5742 }
5743 }
5744
5745 pub fn insert_snippet(
5746 &mut self,
5747 insertion_ranges: &[Range<usize>],
5748 snippet: Snippet,
5749 cx: &mut ViewContext<Self>,
5750 ) -> Result<()> {
5751 struct Tabstop<T> {
5752 is_end_tabstop: bool,
5753 ranges: Vec<Range<T>>,
5754 choices: Option<Vec<String>>,
5755 }
5756
5757 let tabstops = self.buffer.update(cx, |buffer, cx| {
5758 let snippet_text: Arc<str> = snippet.text.clone().into();
5759 buffer.edit(
5760 insertion_ranges
5761 .iter()
5762 .cloned()
5763 .map(|range| (range, snippet_text.clone())),
5764 Some(AutoindentMode::EachLine),
5765 cx,
5766 );
5767
5768 let snapshot = &*buffer.read(cx);
5769 let snippet = &snippet;
5770 snippet
5771 .tabstops
5772 .iter()
5773 .map(|tabstop| {
5774 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5775 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5776 });
5777 let mut tabstop_ranges = tabstop
5778 .ranges
5779 .iter()
5780 .flat_map(|tabstop_range| {
5781 let mut delta = 0_isize;
5782 insertion_ranges.iter().map(move |insertion_range| {
5783 let insertion_start = insertion_range.start as isize + delta;
5784 delta +=
5785 snippet.text.len() as isize - insertion_range.len() as isize;
5786
5787 let start = ((insertion_start + tabstop_range.start) as usize)
5788 .min(snapshot.len());
5789 let end = ((insertion_start + tabstop_range.end) as usize)
5790 .min(snapshot.len());
5791 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5792 })
5793 })
5794 .collect::<Vec<_>>();
5795 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5796
5797 Tabstop {
5798 is_end_tabstop,
5799 ranges: tabstop_ranges,
5800 choices: tabstop.choices.clone(),
5801 }
5802 })
5803 .collect::<Vec<_>>()
5804 });
5805 if let Some(tabstop) = tabstops.first() {
5806 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5807 s.select_ranges(tabstop.ranges.iter().cloned());
5808 });
5809
5810 if let Some(choices) = &tabstop.choices {
5811 if let Some(selection) = tabstop.ranges.first() {
5812 self.show_snippet_choices(choices, selection.clone(), cx)
5813 }
5814 }
5815
5816 // If we're already at the last tabstop and it's at the end of the snippet,
5817 // we're done, we don't need to keep the state around.
5818 if !tabstop.is_end_tabstop {
5819 let choices = tabstops
5820 .iter()
5821 .map(|tabstop| tabstop.choices.clone())
5822 .collect();
5823
5824 let ranges = tabstops
5825 .into_iter()
5826 .map(|tabstop| tabstop.ranges)
5827 .collect::<Vec<_>>();
5828
5829 self.snippet_stack.push(SnippetState {
5830 active_index: 0,
5831 ranges,
5832 choices,
5833 });
5834 }
5835
5836 // Check whether the just-entered snippet ends with an auto-closable bracket.
5837 if self.autoclose_regions.is_empty() {
5838 let snapshot = self.buffer.read(cx).snapshot(cx);
5839 for selection in &mut self.selections.all::<Point>(cx) {
5840 let selection_head = selection.head();
5841 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5842 continue;
5843 };
5844
5845 let mut bracket_pair = None;
5846 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5847 let prev_chars = snapshot
5848 .reversed_chars_at(selection_head)
5849 .collect::<String>();
5850 for (pair, enabled) in scope.brackets() {
5851 if enabled
5852 && pair.close
5853 && prev_chars.starts_with(pair.start.as_str())
5854 && next_chars.starts_with(pair.end.as_str())
5855 {
5856 bracket_pair = Some(pair.clone());
5857 break;
5858 }
5859 }
5860 if let Some(pair) = bracket_pair {
5861 let start = snapshot.anchor_after(selection_head);
5862 let end = snapshot.anchor_after(selection_head);
5863 self.autoclose_regions.push(AutocloseRegion {
5864 selection_id: selection.id,
5865 range: start..end,
5866 pair,
5867 });
5868 }
5869 }
5870 }
5871 }
5872 Ok(())
5873 }
5874
5875 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5876 self.move_to_snippet_tabstop(Bias::Right, cx)
5877 }
5878
5879 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5880 self.move_to_snippet_tabstop(Bias::Left, cx)
5881 }
5882
5883 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5884 if let Some(mut snippet) = self.snippet_stack.pop() {
5885 match bias {
5886 Bias::Left => {
5887 if snippet.active_index > 0 {
5888 snippet.active_index -= 1;
5889 } else {
5890 self.snippet_stack.push(snippet);
5891 return false;
5892 }
5893 }
5894 Bias::Right => {
5895 if snippet.active_index + 1 < snippet.ranges.len() {
5896 snippet.active_index += 1;
5897 } else {
5898 self.snippet_stack.push(snippet);
5899 return false;
5900 }
5901 }
5902 }
5903 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5904 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5905 s.select_anchor_ranges(current_ranges.iter().cloned())
5906 });
5907
5908 if let Some(choices) = &snippet.choices[snippet.active_index] {
5909 if let Some(selection) = current_ranges.first() {
5910 self.show_snippet_choices(&choices, selection.clone(), cx);
5911 }
5912 }
5913
5914 // If snippet state is not at the last tabstop, push it back on the stack
5915 if snippet.active_index + 1 < snippet.ranges.len() {
5916 self.snippet_stack.push(snippet);
5917 }
5918 return true;
5919 }
5920 }
5921
5922 false
5923 }
5924
5925 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5926 self.transact(cx, |this, cx| {
5927 this.select_all(&SelectAll, cx);
5928 this.insert("", cx);
5929 });
5930 }
5931
5932 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5933 self.transact(cx, |this, cx| {
5934 this.select_autoclose_pair(cx);
5935 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5936 if !this.linked_edit_ranges.is_empty() {
5937 let selections = this.selections.all::<MultiBufferPoint>(cx);
5938 let snapshot = this.buffer.read(cx).snapshot(cx);
5939
5940 for selection in selections.iter() {
5941 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5942 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5943 if selection_start.buffer_id != selection_end.buffer_id {
5944 continue;
5945 }
5946 if let Some(ranges) =
5947 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5948 {
5949 for (buffer, entries) in ranges {
5950 linked_ranges.entry(buffer).or_default().extend(entries);
5951 }
5952 }
5953 }
5954 }
5955
5956 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5957 if !this.selections.line_mode {
5958 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5959 for selection in &mut selections {
5960 if selection.is_empty() {
5961 let old_head = selection.head();
5962 let mut new_head =
5963 movement::left(&display_map, old_head.to_display_point(&display_map))
5964 .to_point(&display_map);
5965 if let Some((buffer, line_buffer_range)) = display_map
5966 .buffer_snapshot
5967 .buffer_line_for_row(MultiBufferRow(old_head.row))
5968 {
5969 let indent_size =
5970 buffer.indent_size_for_line(line_buffer_range.start.row);
5971 let indent_len = match indent_size.kind {
5972 IndentKind::Space => {
5973 buffer.settings_at(line_buffer_range.start, cx).tab_size
5974 }
5975 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5976 };
5977 if old_head.column <= indent_size.len && old_head.column > 0 {
5978 let indent_len = indent_len.get();
5979 new_head = cmp::min(
5980 new_head,
5981 MultiBufferPoint::new(
5982 old_head.row,
5983 ((old_head.column - 1) / indent_len) * indent_len,
5984 ),
5985 );
5986 }
5987 }
5988
5989 selection.set_head(new_head, SelectionGoal::None);
5990 }
5991 }
5992 }
5993
5994 this.signature_help_state.set_backspace_pressed(true);
5995 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5996 this.insert("", cx);
5997 let empty_str: Arc<str> = Arc::from("");
5998 for (buffer, edits) in linked_ranges {
5999 let snapshot = buffer.read(cx).snapshot();
6000 use text::ToPoint as TP;
6001
6002 let edits = edits
6003 .into_iter()
6004 .map(|range| {
6005 let end_point = TP::to_point(&range.end, &snapshot);
6006 let mut start_point = TP::to_point(&range.start, &snapshot);
6007
6008 if end_point == start_point {
6009 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6010 .saturating_sub(1);
6011 start_point = TP::to_point(&offset, &snapshot);
6012 };
6013
6014 (start_point..end_point, empty_str.clone())
6015 })
6016 .sorted_by_key(|(range, _)| range.start)
6017 .collect::<Vec<_>>();
6018 buffer.update(cx, |this, cx| {
6019 this.edit(edits, None, cx);
6020 })
6021 }
6022 this.refresh_inline_completion(true, false, cx);
6023 linked_editing_ranges::refresh_linked_ranges(this, cx);
6024 });
6025 }
6026
6027 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6028 self.transact(cx, |this, cx| {
6029 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6030 let line_mode = s.line_mode;
6031 s.move_with(|map, selection| {
6032 if selection.is_empty() && !line_mode {
6033 let cursor = movement::right(map, selection.head());
6034 selection.end = cursor;
6035 selection.reversed = true;
6036 selection.goal = SelectionGoal::None;
6037 }
6038 })
6039 });
6040 this.insert("", cx);
6041 this.refresh_inline_completion(true, false, cx);
6042 });
6043 }
6044
6045 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6046 if self.move_to_prev_snippet_tabstop(cx) {
6047 return;
6048 }
6049
6050 self.outdent(&Outdent, cx);
6051 }
6052
6053 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6054 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6055 return;
6056 }
6057
6058 let mut selections = self.selections.all_adjusted(cx);
6059 let buffer = self.buffer.read(cx);
6060 let snapshot = buffer.snapshot(cx);
6061 let rows_iter = selections.iter().map(|s| s.head().row);
6062 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6063
6064 let mut edits = Vec::new();
6065 let mut prev_edited_row = 0;
6066 let mut row_delta = 0;
6067 for selection in &mut selections {
6068 if selection.start.row != prev_edited_row {
6069 row_delta = 0;
6070 }
6071 prev_edited_row = selection.end.row;
6072
6073 // If the selection is non-empty, then increase the indentation of the selected lines.
6074 if !selection.is_empty() {
6075 row_delta =
6076 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6077 continue;
6078 }
6079
6080 // If the selection is empty and the cursor is in the leading whitespace before the
6081 // suggested indentation, then auto-indent the line.
6082 let cursor = selection.head();
6083 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6084 if let Some(suggested_indent) =
6085 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6086 {
6087 if cursor.column < suggested_indent.len
6088 && cursor.column <= current_indent.len
6089 && current_indent.len <= suggested_indent.len
6090 {
6091 selection.start = Point::new(cursor.row, suggested_indent.len);
6092 selection.end = selection.start;
6093 if row_delta == 0 {
6094 edits.extend(Buffer::edit_for_indent_size_adjustment(
6095 cursor.row,
6096 current_indent,
6097 suggested_indent,
6098 ));
6099 row_delta = suggested_indent.len - current_indent.len;
6100 }
6101 continue;
6102 }
6103 }
6104
6105 // Otherwise, insert a hard or soft tab.
6106 let settings = buffer.settings_at(cursor, cx);
6107 let tab_size = if settings.hard_tabs {
6108 IndentSize::tab()
6109 } else {
6110 let tab_size = settings.tab_size.get();
6111 let char_column = snapshot
6112 .text_for_range(Point::new(cursor.row, 0)..cursor)
6113 .flat_map(str::chars)
6114 .count()
6115 + row_delta as usize;
6116 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6117 IndentSize::spaces(chars_to_next_tab_stop)
6118 };
6119 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6120 selection.end = selection.start;
6121 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6122 row_delta += tab_size.len;
6123 }
6124
6125 self.transact(cx, |this, cx| {
6126 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6127 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6128 this.refresh_inline_completion(true, false, cx);
6129 });
6130 }
6131
6132 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6133 if self.read_only(cx) {
6134 return;
6135 }
6136 let mut selections = self.selections.all::<Point>(cx);
6137 let mut prev_edited_row = 0;
6138 let mut row_delta = 0;
6139 let mut edits = Vec::new();
6140 let buffer = self.buffer.read(cx);
6141 let snapshot = buffer.snapshot(cx);
6142 for selection in &mut selections {
6143 if selection.start.row != prev_edited_row {
6144 row_delta = 0;
6145 }
6146 prev_edited_row = selection.end.row;
6147
6148 row_delta =
6149 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6150 }
6151
6152 self.transact(cx, |this, cx| {
6153 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6154 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6155 });
6156 }
6157
6158 fn indent_selection(
6159 buffer: &MultiBuffer,
6160 snapshot: &MultiBufferSnapshot,
6161 selection: &mut Selection<Point>,
6162 edits: &mut Vec<(Range<Point>, String)>,
6163 delta_for_start_row: u32,
6164 cx: &AppContext,
6165 ) -> u32 {
6166 let settings = buffer.settings_at(selection.start, cx);
6167 let tab_size = settings.tab_size.get();
6168 let indent_kind = if settings.hard_tabs {
6169 IndentKind::Tab
6170 } else {
6171 IndentKind::Space
6172 };
6173 let mut start_row = selection.start.row;
6174 let mut end_row = selection.end.row + 1;
6175
6176 // If a selection ends at the beginning of a line, don't indent
6177 // that last line.
6178 if selection.end.column == 0 && selection.end.row > selection.start.row {
6179 end_row -= 1;
6180 }
6181
6182 // Avoid re-indenting a row that has already been indented by a
6183 // previous selection, but still update this selection's column
6184 // to reflect that indentation.
6185 if delta_for_start_row > 0 {
6186 start_row += 1;
6187 selection.start.column += delta_for_start_row;
6188 if selection.end.row == selection.start.row {
6189 selection.end.column += delta_for_start_row;
6190 }
6191 }
6192
6193 let mut delta_for_end_row = 0;
6194 let has_multiple_rows = start_row + 1 != end_row;
6195 for row in start_row..end_row {
6196 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6197 let indent_delta = match (current_indent.kind, indent_kind) {
6198 (IndentKind::Space, IndentKind::Space) => {
6199 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6200 IndentSize::spaces(columns_to_next_tab_stop)
6201 }
6202 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6203 (_, IndentKind::Tab) => IndentSize::tab(),
6204 };
6205
6206 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6207 0
6208 } else {
6209 selection.start.column
6210 };
6211 let row_start = Point::new(row, start);
6212 edits.push((
6213 row_start..row_start,
6214 indent_delta.chars().collect::<String>(),
6215 ));
6216
6217 // Update this selection's endpoints to reflect the indentation.
6218 if row == selection.start.row {
6219 selection.start.column += indent_delta.len;
6220 }
6221 if row == selection.end.row {
6222 selection.end.column += indent_delta.len;
6223 delta_for_end_row = indent_delta.len;
6224 }
6225 }
6226
6227 if selection.start.row == selection.end.row {
6228 delta_for_start_row + delta_for_end_row
6229 } else {
6230 delta_for_end_row
6231 }
6232 }
6233
6234 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6235 if self.read_only(cx) {
6236 return;
6237 }
6238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6239 let selections = self.selections.all::<Point>(cx);
6240 let mut deletion_ranges = Vec::new();
6241 let mut last_outdent = None;
6242 {
6243 let buffer = self.buffer.read(cx);
6244 let snapshot = buffer.snapshot(cx);
6245 for selection in &selections {
6246 let settings = buffer.settings_at(selection.start, cx);
6247 let tab_size = settings.tab_size.get();
6248 let mut rows = selection.spanned_rows(false, &display_map);
6249
6250 // Avoid re-outdenting a row that has already been outdented by a
6251 // previous selection.
6252 if let Some(last_row) = last_outdent {
6253 if last_row == rows.start {
6254 rows.start = rows.start.next_row();
6255 }
6256 }
6257 let has_multiple_rows = rows.len() > 1;
6258 for row in rows.iter_rows() {
6259 let indent_size = snapshot.indent_size_for_line(row);
6260 if indent_size.len > 0 {
6261 let deletion_len = match indent_size.kind {
6262 IndentKind::Space => {
6263 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6264 if columns_to_prev_tab_stop == 0 {
6265 tab_size
6266 } else {
6267 columns_to_prev_tab_stop
6268 }
6269 }
6270 IndentKind::Tab => 1,
6271 };
6272 let start = if has_multiple_rows
6273 || deletion_len > selection.start.column
6274 || indent_size.len < selection.start.column
6275 {
6276 0
6277 } else {
6278 selection.start.column - deletion_len
6279 };
6280 deletion_ranges.push(
6281 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6282 );
6283 last_outdent = Some(row);
6284 }
6285 }
6286 }
6287 }
6288
6289 self.transact(cx, |this, cx| {
6290 this.buffer.update(cx, |buffer, cx| {
6291 let empty_str: Arc<str> = Arc::default();
6292 buffer.edit(
6293 deletion_ranges
6294 .into_iter()
6295 .map(|range| (range, empty_str.clone())),
6296 None,
6297 cx,
6298 );
6299 });
6300 let selections = this.selections.all::<usize>(cx);
6301 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6302 });
6303 }
6304
6305 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
6306 if self.read_only(cx) {
6307 return;
6308 }
6309 let selections = self
6310 .selections
6311 .all::<usize>(cx)
6312 .into_iter()
6313 .map(|s| s.range());
6314
6315 self.transact(cx, |this, cx| {
6316 this.buffer.update(cx, |buffer, cx| {
6317 buffer.autoindent_ranges(selections, cx);
6318 });
6319 let selections = this.selections.all::<usize>(cx);
6320 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6321 });
6322 }
6323
6324 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6325 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6326 let selections = self.selections.all::<Point>(cx);
6327
6328 let mut new_cursors = Vec::new();
6329 let mut edit_ranges = Vec::new();
6330 let mut selections = selections.iter().peekable();
6331 while let Some(selection) = selections.next() {
6332 let mut rows = selection.spanned_rows(false, &display_map);
6333 let goal_display_column = selection.head().to_display_point(&display_map).column();
6334
6335 // Accumulate contiguous regions of rows that we want to delete.
6336 while let Some(next_selection) = selections.peek() {
6337 let next_rows = next_selection.spanned_rows(false, &display_map);
6338 if next_rows.start <= rows.end {
6339 rows.end = next_rows.end;
6340 selections.next().unwrap();
6341 } else {
6342 break;
6343 }
6344 }
6345
6346 let buffer = &display_map.buffer_snapshot;
6347 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6348 let edit_end;
6349 let cursor_buffer_row;
6350 if buffer.max_point().row >= rows.end.0 {
6351 // If there's a line after the range, delete the \n from the end of the row range
6352 // and position the cursor on the next line.
6353 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6354 cursor_buffer_row = rows.end;
6355 } else {
6356 // If there isn't a line after the range, delete the \n from the line before the
6357 // start of the row range and position the cursor there.
6358 edit_start = edit_start.saturating_sub(1);
6359 edit_end = buffer.len();
6360 cursor_buffer_row = rows.start.previous_row();
6361 }
6362
6363 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6364 *cursor.column_mut() =
6365 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6366
6367 new_cursors.push((
6368 selection.id,
6369 buffer.anchor_after(cursor.to_point(&display_map)),
6370 ));
6371 edit_ranges.push(edit_start..edit_end);
6372 }
6373
6374 self.transact(cx, |this, cx| {
6375 let buffer = this.buffer.update(cx, |buffer, cx| {
6376 let empty_str: Arc<str> = Arc::default();
6377 buffer.edit(
6378 edit_ranges
6379 .into_iter()
6380 .map(|range| (range, empty_str.clone())),
6381 None,
6382 cx,
6383 );
6384 buffer.snapshot(cx)
6385 });
6386 let new_selections = new_cursors
6387 .into_iter()
6388 .map(|(id, cursor)| {
6389 let cursor = cursor.to_point(&buffer);
6390 Selection {
6391 id,
6392 start: cursor,
6393 end: cursor,
6394 reversed: false,
6395 goal: SelectionGoal::None,
6396 }
6397 })
6398 .collect();
6399
6400 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6401 s.select(new_selections);
6402 });
6403 });
6404 }
6405
6406 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6407 if self.read_only(cx) {
6408 return;
6409 }
6410 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6411 for selection in self.selections.all::<Point>(cx) {
6412 let start = MultiBufferRow(selection.start.row);
6413 // Treat single line selections as if they include the next line. Otherwise this action
6414 // would do nothing for single line selections individual cursors.
6415 let end = if selection.start.row == selection.end.row {
6416 MultiBufferRow(selection.start.row + 1)
6417 } else {
6418 MultiBufferRow(selection.end.row)
6419 };
6420
6421 if let Some(last_row_range) = row_ranges.last_mut() {
6422 if start <= last_row_range.end {
6423 last_row_range.end = end;
6424 continue;
6425 }
6426 }
6427 row_ranges.push(start..end);
6428 }
6429
6430 let snapshot = self.buffer.read(cx).snapshot(cx);
6431 let mut cursor_positions = Vec::new();
6432 for row_range in &row_ranges {
6433 let anchor = snapshot.anchor_before(Point::new(
6434 row_range.end.previous_row().0,
6435 snapshot.line_len(row_range.end.previous_row()),
6436 ));
6437 cursor_positions.push(anchor..anchor);
6438 }
6439
6440 self.transact(cx, |this, cx| {
6441 for row_range in row_ranges.into_iter().rev() {
6442 for row in row_range.iter_rows().rev() {
6443 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6444 let next_line_row = row.next_row();
6445 let indent = snapshot.indent_size_for_line(next_line_row);
6446 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6447
6448 let replace = if snapshot.line_len(next_line_row) > indent.len {
6449 " "
6450 } else {
6451 ""
6452 };
6453
6454 this.buffer.update(cx, |buffer, cx| {
6455 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6456 });
6457 }
6458 }
6459
6460 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6461 s.select_anchor_ranges(cursor_positions)
6462 });
6463 });
6464 }
6465
6466 pub fn sort_lines_case_sensitive(
6467 &mut self,
6468 _: &SortLinesCaseSensitive,
6469 cx: &mut ViewContext<Self>,
6470 ) {
6471 self.manipulate_lines(cx, |lines| lines.sort())
6472 }
6473
6474 pub fn sort_lines_case_insensitive(
6475 &mut self,
6476 _: &SortLinesCaseInsensitive,
6477 cx: &mut ViewContext<Self>,
6478 ) {
6479 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6480 }
6481
6482 pub fn unique_lines_case_insensitive(
6483 &mut self,
6484 _: &UniqueLinesCaseInsensitive,
6485 cx: &mut ViewContext<Self>,
6486 ) {
6487 self.manipulate_lines(cx, |lines| {
6488 let mut seen = HashSet::default();
6489 lines.retain(|line| seen.insert(line.to_lowercase()));
6490 })
6491 }
6492
6493 pub fn unique_lines_case_sensitive(
6494 &mut self,
6495 _: &UniqueLinesCaseSensitive,
6496 cx: &mut ViewContext<Self>,
6497 ) {
6498 self.manipulate_lines(cx, |lines| {
6499 let mut seen = HashSet::default();
6500 lines.retain(|line| seen.insert(*line));
6501 })
6502 }
6503
6504 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6505 let mut revert_changes = HashMap::default();
6506 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6507 for hunk in hunks_for_rows(
6508 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_row()).into_iter(),
6509 &multi_buffer_snapshot,
6510 ) {
6511 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6512 }
6513 if !revert_changes.is_empty() {
6514 self.transact(cx, |editor, cx| {
6515 editor.revert(revert_changes, cx);
6516 });
6517 }
6518 }
6519
6520 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6521 let Some(project) = self.project.clone() else {
6522 return;
6523 };
6524 self.reload(project, cx).detach_and_notify_err(cx);
6525 }
6526
6527 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6528 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6529 if !revert_changes.is_empty() {
6530 self.transact(cx, |editor, cx| {
6531 editor.revert(revert_changes, cx);
6532 });
6533 }
6534 }
6535
6536 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6537 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6538 let project_path = buffer.read(cx).project_path(cx)?;
6539 let project = self.project.as_ref()?.read(cx);
6540 let entry = project.entry_for_path(&project_path, cx)?;
6541 let parent = match &entry.canonical_path {
6542 Some(canonical_path) => canonical_path.to_path_buf(),
6543 None => project.absolute_path(&project_path, cx)?,
6544 }
6545 .parent()?
6546 .to_path_buf();
6547 Some(parent)
6548 }) {
6549 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6550 }
6551 }
6552
6553 fn gather_revert_changes(
6554 &mut self,
6555 selections: &[Selection<Anchor>],
6556 cx: &mut ViewContext<'_, Editor>,
6557 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6558 let mut revert_changes = HashMap::default();
6559 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6560 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6561 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6562 }
6563 revert_changes
6564 }
6565
6566 pub fn prepare_revert_change(
6567 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6568 multi_buffer: &Model<MultiBuffer>,
6569 hunk: &MultiBufferDiffHunk,
6570 cx: &AppContext,
6571 ) -> Option<()> {
6572 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6573 let buffer = buffer.read(cx);
6574 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6575 let buffer_snapshot = buffer.snapshot();
6576 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6577 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6578 probe
6579 .0
6580 .start
6581 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6582 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6583 }) {
6584 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6585 Some(())
6586 } else {
6587 None
6588 }
6589 }
6590
6591 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6592 self.manipulate_lines(cx, |lines| lines.reverse())
6593 }
6594
6595 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6596 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6597 }
6598
6599 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6600 where
6601 Fn: FnMut(&mut Vec<&str>),
6602 {
6603 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6604 let buffer = self.buffer.read(cx).snapshot(cx);
6605
6606 let mut edits = Vec::new();
6607
6608 let selections = self.selections.all::<Point>(cx);
6609 let mut selections = selections.iter().peekable();
6610 let mut contiguous_row_selections = Vec::new();
6611 let mut new_selections = Vec::new();
6612 let mut added_lines = 0;
6613 let mut removed_lines = 0;
6614
6615 while let Some(selection) = selections.next() {
6616 let (start_row, end_row) = consume_contiguous_rows(
6617 &mut contiguous_row_selections,
6618 selection,
6619 &display_map,
6620 &mut selections,
6621 );
6622
6623 let start_point = Point::new(start_row.0, 0);
6624 let end_point = Point::new(
6625 end_row.previous_row().0,
6626 buffer.line_len(end_row.previous_row()),
6627 );
6628 let text = buffer
6629 .text_for_range(start_point..end_point)
6630 .collect::<String>();
6631
6632 let mut lines = text.split('\n').collect_vec();
6633
6634 let lines_before = lines.len();
6635 callback(&mut lines);
6636 let lines_after = lines.len();
6637
6638 edits.push((start_point..end_point, lines.join("\n")));
6639
6640 // Selections must change based on added and removed line count
6641 let start_row =
6642 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6643 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6644 new_selections.push(Selection {
6645 id: selection.id,
6646 start: start_row,
6647 end: end_row,
6648 goal: SelectionGoal::None,
6649 reversed: selection.reversed,
6650 });
6651
6652 if lines_after > lines_before {
6653 added_lines += lines_after - lines_before;
6654 } else if lines_before > lines_after {
6655 removed_lines += lines_before - lines_after;
6656 }
6657 }
6658
6659 self.transact(cx, |this, cx| {
6660 let buffer = this.buffer.update(cx, |buffer, cx| {
6661 buffer.edit(edits, None, cx);
6662 buffer.snapshot(cx)
6663 });
6664
6665 // Recalculate offsets on newly edited buffer
6666 let new_selections = new_selections
6667 .iter()
6668 .map(|s| {
6669 let start_point = Point::new(s.start.0, 0);
6670 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6671 Selection {
6672 id: s.id,
6673 start: buffer.point_to_offset(start_point),
6674 end: buffer.point_to_offset(end_point),
6675 goal: s.goal,
6676 reversed: s.reversed,
6677 }
6678 })
6679 .collect();
6680
6681 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6682 s.select(new_selections);
6683 });
6684
6685 this.request_autoscroll(Autoscroll::fit(), cx);
6686 });
6687 }
6688
6689 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6690 self.manipulate_text(cx, |text| text.to_uppercase())
6691 }
6692
6693 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6694 self.manipulate_text(cx, |text| text.to_lowercase())
6695 }
6696
6697 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6698 self.manipulate_text(cx, |text| {
6699 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6700 // https://github.com/rutrum/convert-case/issues/16
6701 text.split('\n')
6702 .map(|line| line.to_case(Case::Title))
6703 .join("\n")
6704 })
6705 }
6706
6707 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6708 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6709 }
6710
6711 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6712 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6713 }
6714
6715 pub fn convert_to_upper_camel_case(
6716 &mut self,
6717 _: &ConvertToUpperCamelCase,
6718 cx: &mut ViewContext<Self>,
6719 ) {
6720 self.manipulate_text(cx, |text| {
6721 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6722 // https://github.com/rutrum/convert-case/issues/16
6723 text.split('\n')
6724 .map(|line| line.to_case(Case::UpperCamel))
6725 .join("\n")
6726 })
6727 }
6728
6729 pub fn convert_to_lower_camel_case(
6730 &mut self,
6731 _: &ConvertToLowerCamelCase,
6732 cx: &mut ViewContext<Self>,
6733 ) {
6734 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6735 }
6736
6737 pub fn convert_to_opposite_case(
6738 &mut self,
6739 _: &ConvertToOppositeCase,
6740 cx: &mut ViewContext<Self>,
6741 ) {
6742 self.manipulate_text(cx, |text| {
6743 text.chars()
6744 .fold(String::with_capacity(text.len()), |mut t, c| {
6745 if c.is_uppercase() {
6746 t.extend(c.to_lowercase());
6747 } else {
6748 t.extend(c.to_uppercase());
6749 }
6750 t
6751 })
6752 })
6753 }
6754
6755 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6756 where
6757 Fn: FnMut(&str) -> String,
6758 {
6759 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6760 let buffer = self.buffer.read(cx).snapshot(cx);
6761
6762 let mut new_selections = Vec::new();
6763 let mut edits = Vec::new();
6764 let mut selection_adjustment = 0i32;
6765
6766 for selection in self.selections.all::<usize>(cx) {
6767 let selection_is_empty = selection.is_empty();
6768
6769 let (start, end) = if selection_is_empty {
6770 let word_range = movement::surrounding_word(
6771 &display_map,
6772 selection.start.to_display_point(&display_map),
6773 );
6774 let start = word_range.start.to_offset(&display_map, Bias::Left);
6775 let end = word_range.end.to_offset(&display_map, Bias::Left);
6776 (start, end)
6777 } else {
6778 (selection.start, selection.end)
6779 };
6780
6781 let text = buffer.text_for_range(start..end).collect::<String>();
6782 let old_length = text.len() as i32;
6783 let text = callback(&text);
6784
6785 new_selections.push(Selection {
6786 start: (start as i32 - selection_adjustment) as usize,
6787 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6788 goal: SelectionGoal::None,
6789 ..selection
6790 });
6791
6792 selection_adjustment += old_length - text.len() as i32;
6793
6794 edits.push((start..end, text));
6795 }
6796
6797 self.transact(cx, |this, cx| {
6798 this.buffer.update(cx, |buffer, cx| {
6799 buffer.edit(edits, None, cx);
6800 });
6801
6802 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6803 s.select(new_selections);
6804 });
6805
6806 this.request_autoscroll(Autoscroll::fit(), cx);
6807 });
6808 }
6809
6810 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6812 let buffer = &display_map.buffer_snapshot;
6813 let selections = self.selections.all::<Point>(cx);
6814
6815 let mut edits = Vec::new();
6816 let mut selections_iter = selections.iter().peekable();
6817 while let Some(selection) = selections_iter.next() {
6818 // Avoid duplicating the same lines twice.
6819 let mut rows = selection.spanned_rows(false, &display_map);
6820
6821 while let Some(next_selection) = selections_iter.peek() {
6822 let next_rows = next_selection.spanned_rows(false, &display_map);
6823 if next_rows.start < rows.end {
6824 rows.end = next_rows.end;
6825 selections_iter.next().unwrap();
6826 } else {
6827 break;
6828 }
6829 }
6830
6831 // Copy the text from the selected row region and splice it either at the start
6832 // or end of the region.
6833 let start = Point::new(rows.start.0, 0);
6834 let end = Point::new(
6835 rows.end.previous_row().0,
6836 buffer.line_len(rows.end.previous_row()),
6837 );
6838 let text = buffer
6839 .text_for_range(start..end)
6840 .chain(Some("\n"))
6841 .collect::<String>();
6842 let insert_location = if upwards {
6843 Point::new(rows.end.0, 0)
6844 } else {
6845 start
6846 };
6847 edits.push((insert_location..insert_location, text));
6848 }
6849
6850 self.transact(cx, |this, cx| {
6851 this.buffer.update(cx, |buffer, cx| {
6852 buffer.edit(edits, None, cx);
6853 });
6854
6855 this.request_autoscroll(Autoscroll::fit(), cx);
6856 });
6857 }
6858
6859 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6860 self.duplicate_line(true, cx);
6861 }
6862
6863 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6864 self.duplicate_line(false, cx);
6865 }
6866
6867 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6868 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6869 let buffer = self.buffer.read(cx).snapshot(cx);
6870
6871 let mut edits = Vec::new();
6872 let mut unfold_ranges = Vec::new();
6873 let mut refold_creases = Vec::new();
6874
6875 let selections = self.selections.all::<Point>(cx);
6876 let mut selections = selections.iter().peekable();
6877 let mut contiguous_row_selections = Vec::new();
6878 let mut new_selections = Vec::new();
6879
6880 while let Some(selection) = selections.next() {
6881 // Find all the selections that span a contiguous row range
6882 let (start_row, end_row) = consume_contiguous_rows(
6883 &mut contiguous_row_selections,
6884 selection,
6885 &display_map,
6886 &mut selections,
6887 );
6888
6889 // Move the text spanned by the row range to be before the line preceding the row range
6890 if start_row.0 > 0 {
6891 let range_to_move = Point::new(
6892 start_row.previous_row().0,
6893 buffer.line_len(start_row.previous_row()),
6894 )
6895 ..Point::new(
6896 end_row.previous_row().0,
6897 buffer.line_len(end_row.previous_row()),
6898 );
6899 let insertion_point = display_map
6900 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6901 .0;
6902
6903 // Don't move lines across excerpts
6904 if buffer
6905 .excerpt_boundaries_in_range((
6906 Bound::Excluded(insertion_point),
6907 Bound::Included(range_to_move.end),
6908 ))
6909 .next()
6910 .is_none()
6911 {
6912 let text = buffer
6913 .text_for_range(range_to_move.clone())
6914 .flat_map(|s| s.chars())
6915 .skip(1)
6916 .chain(['\n'])
6917 .collect::<String>();
6918
6919 edits.push((
6920 buffer.anchor_after(range_to_move.start)
6921 ..buffer.anchor_before(range_to_move.end),
6922 String::new(),
6923 ));
6924 let insertion_anchor = buffer.anchor_after(insertion_point);
6925 edits.push((insertion_anchor..insertion_anchor, text));
6926
6927 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6928
6929 // Move selections up
6930 new_selections.extend(contiguous_row_selections.drain(..).map(
6931 |mut selection| {
6932 selection.start.row -= row_delta;
6933 selection.end.row -= row_delta;
6934 selection
6935 },
6936 ));
6937
6938 // Move folds up
6939 unfold_ranges.push(range_to_move.clone());
6940 for fold in display_map.folds_in_range(
6941 buffer.anchor_before(range_to_move.start)
6942 ..buffer.anchor_after(range_to_move.end),
6943 ) {
6944 let mut start = fold.range.start.to_point(&buffer);
6945 let mut end = fold.range.end.to_point(&buffer);
6946 start.row -= row_delta;
6947 end.row -= row_delta;
6948 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6949 }
6950 }
6951 }
6952
6953 // If we didn't move line(s), preserve the existing selections
6954 new_selections.append(&mut contiguous_row_selections);
6955 }
6956
6957 self.transact(cx, |this, cx| {
6958 this.unfold_ranges(&unfold_ranges, true, true, cx);
6959 this.buffer.update(cx, |buffer, cx| {
6960 for (range, text) in edits {
6961 buffer.edit([(range, text)], None, cx);
6962 }
6963 });
6964 this.fold_creases(refold_creases, true, cx);
6965 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6966 s.select(new_selections);
6967 })
6968 });
6969 }
6970
6971 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6973 let buffer = self.buffer.read(cx).snapshot(cx);
6974
6975 let mut edits = Vec::new();
6976 let mut unfold_ranges = Vec::new();
6977 let mut refold_creases = Vec::new();
6978
6979 let selections = self.selections.all::<Point>(cx);
6980 let mut selections = selections.iter().peekable();
6981 let mut contiguous_row_selections = Vec::new();
6982 let mut new_selections = Vec::new();
6983
6984 while let Some(selection) = selections.next() {
6985 // Find all the selections that span a contiguous row range
6986 let (start_row, end_row) = consume_contiguous_rows(
6987 &mut contiguous_row_selections,
6988 selection,
6989 &display_map,
6990 &mut selections,
6991 );
6992
6993 // Move the text spanned by the row range to be after the last line of the row range
6994 if end_row.0 <= buffer.max_point().row {
6995 let range_to_move =
6996 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6997 let insertion_point = display_map
6998 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6999 .0;
7000
7001 // Don't move lines across excerpt boundaries
7002 if buffer
7003 .excerpt_boundaries_in_range((
7004 Bound::Excluded(range_to_move.start),
7005 Bound::Included(insertion_point),
7006 ))
7007 .next()
7008 .is_none()
7009 {
7010 let mut text = String::from("\n");
7011 text.extend(buffer.text_for_range(range_to_move.clone()));
7012 text.pop(); // Drop trailing newline
7013 edits.push((
7014 buffer.anchor_after(range_to_move.start)
7015 ..buffer.anchor_before(range_to_move.end),
7016 String::new(),
7017 ));
7018 let insertion_anchor = buffer.anchor_after(insertion_point);
7019 edits.push((insertion_anchor..insertion_anchor, text));
7020
7021 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7022
7023 // Move selections down
7024 new_selections.extend(contiguous_row_selections.drain(..).map(
7025 |mut selection| {
7026 selection.start.row += row_delta;
7027 selection.end.row += row_delta;
7028 selection
7029 },
7030 ));
7031
7032 // Move folds down
7033 unfold_ranges.push(range_to_move.clone());
7034 for fold in display_map.folds_in_range(
7035 buffer.anchor_before(range_to_move.start)
7036 ..buffer.anchor_after(range_to_move.end),
7037 ) {
7038 let mut start = fold.range.start.to_point(&buffer);
7039 let mut end = fold.range.end.to_point(&buffer);
7040 start.row += row_delta;
7041 end.row += row_delta;
7042 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7043 }
7044 }
7045 }
7046
7047 // If we didn't move line(s), preserve the existing selections
7048 new_selections.append(&mut contiguous_row_selections);
7049 }
7050
7051 self.transact(cx, |this, cx| {
7052 this.unfold_ranges(&unfold_ranges, true, true, cx);
7053 this.buffer.update(cx, |buffer, cx| {
7054 for (range, text) in edits {
7055 buffer.edit([(range, text)], None, cx);
7056 }
7057 });
7058 this.fold_creases(refold_creases, true, cx);
7059 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7060 });
7061 }
7062
7063 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7064 let text_layout_details = &self.text_layout_details(cx);
7065 self.transact(cx, |this, cx| {
7066 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7067 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7068 let line_mode = s.line_mode;
7069 s.move_with(|display_map, selection| {
7070 if !selection.is_empty() || line_mode {
7071 return;
7072 }
7073
7074 let mut head = selection.head();
7075 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7076 if head.column() == display_map.line_len(head.row()) {
7077 transpose_offset = display_map
7078 .buffer_snapshot
7079 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7080 }
7081
7082 if transpose_offset == 0 {
7083 return;
7084 }
7085
7086 *head.column_mut() += 1;
7087 head = display_map.clip_point(head, Bias::Right);
7088 let goal = SelectionGoal::HorizontalPosition(
7089 display_map
7090 .x_for_display_point(head, text_layout_details)
7091 .into(),
7092 );
7093 selection.collapse_to(head, goal);
7094
7095 let transpose_start = display_map
7096 .buffer_snapshot
7097 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7098 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7099 let transpose_end = display_map
7100 .buffer_snapshot
7101 .clip_offset(transpose_offset + 1, Bias::Right);
7102 if let Some(ch) =
7103 display_map.buffer_snapshot.chars_at(transpose_start).next()
7104 {
7105 edits.push((transpose_start..transpose_offset, String::new()));
7106 edits.push((transpose_end..transpose_end, ch.to_string()));
7107 }
7108 }
7109 });
7110 edits
7111 });
7112 this.buffer
7113 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7114 let selections = this.selections.all::<usize>(cx);
7115 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7116 s.select(selections);
7117 });
7118 });
7119 }
7120
7121 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7122 self.rewrap_impl(IsVimMode::No, cx)
7123 }
7124
7125 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7126 let buffer = self.buffer.read(cx).snapshot(cx);
7127 let selections = self.selections.all::<Point>(cx);
7128 let mut selections = selections.iter().peekable();
7129
7130 let mut edits = Vec::new();
7131 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7132
7133 while let Some(selection) = selections.next() {
7134 let mut start_row = selection.start.row;
7135 let mut end_row = selection.end.row;
7136
7137 // Skip selections that overlap with a range that has already been rewrapped.
7138 let selection_range = start_row..end_row;
7139 if rewrapped_row_ranges
7140 .iter()
7141 .any(|range| range.overlaps(&selection_range))
7142 {
7143 continue;
7144 }
7145
7146 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7147
7148 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7149 match language_scope.language_name().0.as_ref() {
7150 "Markdown" | "Plain Text" => {
7151 should_rewrap = true;
7152 }
7153 _ => {}
7154 }
7155 }
7156
7157 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7158
7159 // Since not all lines in the selection may be at the same indent
7160 // level, choose the indent size that is the most common between all
7161 // of the lines.
7162 //
7163 // If there is a tie, we use the deepest indent.
7164 let (indent_size, indent_end) = {
7165 let mut indent_size_occurrences = HashMap::default();
7166 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7167
7168 for row in start_row..=end_row {
7169 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7170 rows_by_indent_size.entry(indent).or_default().push(row);
7171 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7172 }
7173
7174 let indent_size = indent_size_occurrences
7175 .into_iter()
7176 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7177 .map(|(indent, _)| indent)
7178 .unwrap_or_default();
7179 let row = rows_by_indent_size[&indent_size][0];
7180 let indent_end = Point::new(row, indent_size.len);
7181
7182 (indent_size, indent_end)
7183 };
7184
7185 let mut line_prefix = indent_size.chars().collect::<String>();
7186
7187 if let Some(comment_prefix) =
7188 buffer
7189 .language_scope_at(selection.head())
7190 .and_then(|language| {
7191 language
7192 .line_comment_prefixes()
7193 .iter()
7194 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7195 .cloned()
7196 })
7197 {
7198 line_prefix.push_str(&comment_prefix);
7199 should_rewrap = true;
7200 }
7201
7202 if !should_rewrap {
7203 continue;
7204 }
7205
7206 if selection.is_empty() {
7207 'expand_upwards: while start_row > 0 {
7208 let prev_row = start_row - 1;
7209 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7210 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7211 {
7212 start_row = prev_row;
7213 } else {
7214 break 'expand_upwards;
7215 }
7216 }
7217
7218 'expand_downwards: while end_row < buffer.max_point().row {
7219 let next_row = end_row + 1;
7220 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7221 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7222 {
7223 end_row = next_row;
7224 } else {
7225 break 'expand_downwards;
7226 }
7227 }
7228 }
7229
7230 let start = Point::new(start_row, 0);
7231 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7232 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7233 let Some(lines_without_prefixes) = selection_text
7234 .lines()
7235 .map(|line| {
7236 line.strip_prefix(&line_prefix)
7237 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7238 .ok_or_else(|| {
7239 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7240 })
7241 })
7242 .collect::<Result<Vec<_>, _>>()
7243 .log_err()
7244 else {
7245 continue;
7246 };
7247
7248 let wrap_column = buffer
7249 .settings_at(Point::new(start_row, 0), cx)
7250 .preferred_line_length as usize;
7251 let wrapped_text = wrap_with_prefix(
7252 line_prefix,
7253 lines_without_prefixes.join(" "),
7254 wrap_column,
7255 tab_size,
7256 );
7257
7258 // TODO: should always use char-based diff while still supporting cursor behavior that
7259 // matches vim.
7260 let diff = match is_vim_mode {
7261 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7262 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7263 };
7264 let mut offset = start.to_offset(&buffer);
7265 let mut moved_since_edit = true;
7266
7267 for change in diff.iter_all_changes() {
7268 let value = change.value();
7269 match change.tag() {
7270 ChangeTag::Equal => {
7271 offset += value.len();
7272 moved_since_edit = true;
7273 }
7274 ChangeTag::Delete => {
7275 let start = buffer.anchor_after(offset);
7276 let end = buffer.anchor_before(offset + value.len());
7277
7278 if moved_since_edit {
7279 edits.push((start..end, String::new()));
7280 } else {
7281 edits.last_mut().unwrap().0.end = end;
7282 }
7283
7284 offset += value.len();
7285 moved_since_edit = false;
7286 }
7287 ChangeTag::Insert => {
7288 if moved_since_edit {
7289 let anchor = buffer.anchor_after(offset);
7290 edits.push((anchor..anchor, value.to_string()));
7291 } else {
7292 edits.last_mut().unwrap().1.push_str(value);
7293 }
7294
7295 moved_since_edit = false;
7296 }
7297 }
7298 }
7299
7300 rewrapped_row_ranges.push(start_row..=end_row);
7301 }
7302
7303 self.buffer
7304 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7305 }
7306
7307 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
7308 let mut text = String::new();
7309 let buffer = self.buffer.read(cx).snapshot(cx);
7310 let mut selections = self.selections.all::<Point>(cx);
7311 let mut clipboard_selections = Vec::with_capacity(selections.len());
7312 {
7313 let max_point = buffer.max_point();
7314 let mut is_first = true;
7315 for selection in &mut selections {
7316 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7317 if is_entire_line {
7318 selection.start = Point::new(selection.start.row, 0);
7319 if !selection.is_empty() && selection.end.column == 0 {
7320 selection.end = cmp::min(max_point, selection.end);
7321 } else {
7322 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7323 }
7324 selection.goal = SelectionGoal::None;
7325 }
7326 if is_first {
7327 is_first = false;
7328 } else {
7329 text += "\n";
7330 }
7331 let mut len = 0;
7332 for chunk in buffer.text_for_range(selection.start..selection.end) {
7333 text.push_str(chunk);
7334 len += chunk.len();
7335 }
7336 clipboard_selections.push(ClipboardSelection {
7337 len,
7338 is_entire_line,
7339 first_line_indent: buffer
7340 .indent_size_for_line(MultiBufferRow(selection.start.row))
7341 .len,
7342 });
7343 }
7344 }
7345
7346 self.transact(cx, |this, cx| {
7347 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7348 s.select(selections);
7349 });
7350 this.insert("", cx);
7351 });
7352 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7353 }
7354
7355 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7356 let item = self.cut_common(cx);
7357 cx.write_to_clipboard(item);
7358 }
7359
7360 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
7361 self.change_selections(None, cx, |s| {
7362 s.move_with(|snapshot, sel| {
7363 if sel.is_empty() {
7364 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7365 }
7366 });
7367 });
7368 let item = self.cut_common(cx);
7369 cx.set_global(KillRing(item))
7370 }
7371
7372 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7373 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7374 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7375 (kill_ring.text().to_string(), kill_ring.metadata_json())
7376 } else {
7377 return;
7378 }
7379 } else {
7380 return;
7381 };
7382 self.do_paste(&text, metadata, false, cx);
7383 }
7384
7385 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7386 let selections = self.selections.all::<Point>(cx);
7387 let buffer = self.buffer.read(cx).read(cx);
7388 let mut text = String::new();
7389
7390 let mut clipboard_selections = Vec::with_capacity(selections.len());
7391 {
7392 let max_point = buffer.max_point();
7393 let mut is_first = true;
7394 for selection in selections.iter() {
7395 let mut start = selection.start;
7396 let mut end = selection.end;
7397 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7398 if is_entire_line {
7399 start = Point::new(start.row, 0);
7400 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7401 }
7402 if is_first {
7403 is_first = false;
7404 } else {
7405 text += "\n";
7406 }
7407 let mut len = 0;
7408 for chunk in buffer.text_for_range(start..end) {
7409 text.push_str(chunk);
7410 len += chunk.len();
7411 }
7412 clipboard_selections.push(ClipboardSelection {
7413 len,
7414 is_entire_line,
7415 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7416 });
7417 }
7418 }
7419
7420 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7421 text,
7422 clipboard_selections,
7423 ));
7424 }
7425
7426 pub fn do_paste(
7427 &mut self,
7428 text: &String,
7429 clipboard_selections: Option<Vec<ClipboardSelection>>,
7430 handle_entire_lines: bool,
7431 cx: &mut ViewContext<Self>,
7432 ) {
7433 if self.read_only(cx) {
7434 return;
7435 }
7436
7437 let clipboard_text = Cow::Borrowed(text);
7438
7439 self.transact(cx, |this, cx| {
7440 if let Some(mut clipboard_selections) = clipboard_selections {
7441 let old_selections = this.selections.all::<usize>(cx);
7442 let all_selections_were_entire_line =
7443 clipboard_selections.iter().all(|s| s.is_entire_line);
7444 let first_selection_indent_column =
7445 clipboard_selections.first().map(|s| s.first_line_indent);
7446 if clipboard_selections.len() != old_selections.len() {
7447 clipboard_selections.drain(..);
7448 }
7449 let cursor_offset = this.selections.last::<usize>(cx).head();
7450 let mut auto_indent_on_paste = true;
7451
7452 this.buffer.update(cx, |buffer, cx| {
7453 let snapshot = buffer.read(cx);
7454 auto_indent_on_paste =
7455 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7456
7457 let mut start_offset = 0;
7458 let mut edits = Vec::new();
7459 let mut original_indent_columns = Vec::new();
7460 for (ix, selection) in old_selections.iter().enumerate() {
7461 let to_insert;
7462 let entire_line;
7463 let original_indent_column;
7464 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7465 let end_offset = start_offset + clipboard_selection.len;
7466 to_insert = &clipboard_text[start_offset..end_offset];
7467 entire_line = clipboard_selection.is_entire_line;
7468 start_offset = end_offset + 1;
7469 original_indent_column = Some(clipboard_selection.first_line_indent);
7470 } else {
7471 to_insert = clipboard_text.as_str();
7472 entire_line = all_selections_were_entire_line;
7473 original_indent_column = first_selection_indent_column
7474 }
7475
7476 // If the corresponding selection was empty when this slice of the
7477 // clipboard text was written, then the entire line containing the
7478 // selection was copied. If this selection is also currently empty,
7479 // then paste the line before the current line of the buffer.
7480 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7481 let column = selection.start.to_point(&snapshot).column as usize;
7482 let line_start = selection.start - column;
7483 line_start..line_start
7484 } else {
7485 selection.range()
7486 };
7487
7488 edits.push((range, to_insert));
7489 original_indent_columns.extend(original_indent_column);
7490 }
7491 drop(snapshot);
7492
7493 buffer.edit(
7494 edits,
7495 if auto_indent_on_paste {
7496 Some(AutoindentMode::Block {
7497 original_indent_columns,
7498 })
7499 } else {
7500 None
7501 },
7502 cx,
7503 );
7504 });
7505
7506 let selections = this.selections.all::<usize>(cx);
7507 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7508 } else {
7509 this.insert(&clipboard_text, cx);
7510 }
7511 });
7512 }
7513
7514 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7515 if let Some(item) = cx.read_from_clipboard() {
7516 let entries = item.entries();
7517
7518 match entries.first() {
7519 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7520 // of all the pasted entries.
7521 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7522 .do_paste(
7523 clipboard_string.text(),
7524 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7525 true,
7526 cx,
7527 ),
7528 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7529 }
7530 }
7531 }
7532
7533 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7534 if self.read_only(cx) {
7535 return;
7536 }
7537
7538 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7539 if let Some((selections, _)) =
7540 self.selection_history.transaction(transaction_id).cloned()
7541 {
7542 self.change_selections(None, cx, |s| {
7543 s.select_anchors(selections.to_vec());
7544 });
7545 }
7546 self.request_autoscroll(Autoscroll::fit(), cx);
7547 self.unmark_text(cx);
7548 self.refresh_inline_completion(true, false, cx);
7549 cx.emit(EditorEvent::Edited { transaction_id });
7550 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7551 }
7552 }
7553
7554 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7555 if self.read_only(cx) {
7556 return;
7557 }
7558
7559 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7560 if let Some((_, Some(selections))) =
7561 self.selection_history.transaction(transaction_id).cloned()
7562 {
7563 self.change_selections(None, cx, |s| {
7564 s.select_anchors(selections.to_vec());
7565 });
7566 }
7567 self.request_autoscroll(Autoscroll::fit(), cx);
7568 self.unmark_text(cx);
7569 self.refresh_inline_completion(true, false, cx);
7570 cx.emit(EditorEvent::Edited { transaction_id });
7571 }
7572 }
7573
7574 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7575 self.buffer
7576 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7577 }
7578
7579 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7580 self.buffer
7581 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7582 }
7583
7584 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7585 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7586 let line_mode = s.line_mode;
7587 s.move_with(|map, selection| {
7588 let cursor = if selection.is_empty() && !line_mode {
7589 movement::left(map, selection.start)
7590 } else {
7591 selection.start
7592 };
7593 selection.collapse_to(cursor, SelectionGoal::None);
7594 });
7595 })
7596 }
7597
7598 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7599 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7600 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7601 })
7602 }
7603
7604 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 let line_mode = s.line_mode;
7607 s.move_with(|map, selection| {
7608 let cursor = if selection.is_empty() && !line_mode {
7609 movement::right(map, selection.end)
7610 } else {
7611 selection.end
7612 };
7613 selection.collapse_to(cursor, SelectionGoal::None)
7614 });
7615 })
7616 }
7617
7618 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7619 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7620 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7621 })
7622 }
7623
7624 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7625 if self.take_rename(true, cx).is_some() {
7626 return;
7627 }
7628
7629 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7630 cx.propagate();
7631 return;
7632 }
7633
7634 let text_layout_details = &self.text_layout_details(cx);
7635 let selection_count = self.selections.count();
7636 let first_selection = self.selections.first_anchor();
7637
7638 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7639 let line_mode = s.line_mode;
7640 s.move_with(|map, selection| {
7641 if !selection.is_empty() && !line_mode {
7642 selection.goal = SelectionGoal::None;
7643 }
7644 let (cursor, goal) = movement::up(
7645 map,
7646 selection.start,
7647 selection.goal,
7648 false,
7649 text_layout_details,
7650 );
7651 selection.collapse_to(cursor, goal);
7652 });
7653 });
7654
7655 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7656 {
7657 cx.propagate();
7658 }
7659 }
7660
7661 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7662 if self.take_rename(true, cx).is_some() {
7663 return;
7664 }
7665
7666 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7667 cx.propagate();
7668 return;
7669 }
7670
7671 let text_layout_details = &self.text_layout_details(cx);
7672
7673 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7674 let line_mode = s.line_mode;
7675 s.move_with(|map, selection| {
7676 if !selection.is_empty() && !line_mode {
7677 selection.goal = SelectionGoal::None;
7678 }
7679 let (cursor, goal) = movement::up_by_rows(
7680 map,
7681 selection.start,
7682 action.lines,
7683 selection.goal,
7684 false,
7685 text_layout_details,
7686 );
7687 selection.collapse_to(cursor, goal);
7688 });
7689 })
7690 }
7691
7692 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7693 if self.take_rename(true, cx).is_some() {
7694 return;
7695 }
7696
7697 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7698 cx.propagate();
7699 return;
7700 }
7701
7702 let text_layout_details = &self.text_layout_details(cx);
7703
7704 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7705 let line_mode = s.line_mode;
7706 s.move_with(|map, selection| {
7707 if !selection.is_empty() && !line_mode {
7708 selection.goal = SelectionGoal::None;
7709 }
7710 let (cursor, goal) = movement::down_by_rows(
7711 map,
7712 selection.start,
7713 action.lines,
7714 selection.goal,
7715 false,
7716 text_layout_details,
7717 );
7718 selection.collapse_to(cursor, goal);
7719 });
7720 })
7721 }
7722
7723 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7724 let text_layout_details = &self.text_layout_details(cx);
7725 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7726 s.move_heads_with(|map, head, goal| {
7727 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7728 })
7729 })
7730 }
7731
7732 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7733 let text_layout_details = &self.text_layout_details(cx);
7734 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7735 s.move_heads_with(|map, head, goal| {
7736 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7737 })
7738 })
7739 }
7740
7741 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7742 let Some(row_count) = self.visible_row_count() else {
7743 return;
7744 };
7745
7746 let text_layout_details = &self.text_layout_details(cx);
7747
7748 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7749 s.move_heads_with(|map, head, goal| {
7750 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7751 })
7752 })
7753 }
7754
7755 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7756 if self.take_rename(true, cx).is_some() {
7757 return;
7758 }
7759
7760 if self
7761 .context_menu
7762 .write()
7763 .as_mut()
7764 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7765 .unwrap_or(false)
7766 {
7767 return;
7768 }
7769
7770 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7771 cx.propagate();
7772 return;
7773 }
7774
7775 let Some(row_count) = self.visible_row_count() else {
7776 return;
7777 };
7778
7779 let autoscroll = if action.center_cursor {
7780 Autoscroll::center()
7781 } else {
7782 Autoscroll::fit()
7783 };
7784
7785 let text_layout_details = &self.text_layout_details(cx);
7786
7787 self.change_selections(Some(autoscroll), cx, |s| {
7788 let line_mode = s.line_mode;
7789 s.move_with(|map, selection| {
7790 if !selection.is_empty() && !line_mode {
7791 selection.goal = SelectionGoal::None;
7792 }
7793 let (cursor, goal) = movement::up_by_rows(
7794 map,
7795 selection.end,
7796 row_count,
7797 selection.goal,
7798 false,
7799 text_layout_details,
7800 );
7801 selection.collapse_to(cursor, goal);
7802 });
7803 });
7804 }
7805
7806 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7807 let text_layout_details = &self.text_layout_details(cx);
7808 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7809 s.move_heads_with(|map, head, goal| {
7810 movement::up(map, head, goal, false, text_layout_details)
7811 })
7812 })
7813 }
7814
7815 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7816 self.take_rename(true, cx);
7817
7818 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7819 cx.propagate();
7820 return;
7821 }
7822
7823 let text_layout_details = &self.text_layout_details(cx);
7824 let selection_count = self.selections.count();
7825 let first_selection = self.selections.first_anchor();
7826
7827 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7828 let line_mode = s.line_mode;
7829 s.move_with(|map, selection| {
7830 if !selection.is_empty() && !line_mode {
7831 selection.goal = SelectionGoal::None;
7832 }
7833 let (cursor, goal) = movement::down(
7834 map,
7835 selection.end,
7836 selection.goal,
7837 false,
7838 text_layout_details,
7839 );
7840 selection.collapse_to(cursor, goal);
7841 });
7842 });
7843
7844 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7845 {
7846 cx.propagate();
7847 }
7848 }
7849
7850 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7851 let Some(row_count) = self.visible_row_count() else {
7852 return;
7853 };
7854
7855 let text_layout_details = &self.text_layout_details(cx);
7856
7857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7858 s.move_heads_with(|map, head, goal| {
7859 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7860 })
7861 })
7862 }
7863
7864 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7865 if self.take_rename(true, cx).is_some() {
7866 return;
7867 }
7868
7869 if self
7870 .context_menu
7871 .write()
7872 .as_mut()
7873 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7874 .unwrap_or(false)
7875 {
7876 return;
7877 }
7878
7879 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7880 cx.propagate();
7881 return;
7882 }
7883
7884 let Some(row_count) = self.visible_row_count() else {
7885 return;
7886 };
7887
7888 let autoscroll = if action.center_cursor {
7889 Autoscroll::center()
7890 } else {
7891 Autoscroll::fit()
7892 };
7893
7894 let text_layout_details = &self.text_layout_details(cx);
7895 self.change_selections(Some(autoscroll), cx, |s| {
7896 let line_mode = s.line_mode;
7897 s.move_with(|map, selection| {
7898 if !selection.is_empty() && !line_mode {
7899 selection.goal = SelectionGoal::None;
7900 }
7901 let (cursor, goal) = movement::down_by_rows(
7902 map,
7903 selection.end,
7904 row_count,
7905 selection.goal,
7906 false,
7907 text_layout_details,
7908 );
7909 selection.collapse_to(cursor, goal);
7910 });
7911 });
7912 }
7913
7914 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7915 let text_layout_details = &self.text_layout_details(cx);
7916 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7917 s.move_heads_with(|map, head, goal| {
7918 movement::down(map, head, goal, false, text_layout_details)
7919 })
7920 });
7921 }
7922
7923 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7924 if let Some(context_menu) = self.context_menu.write().as_mut() {
7925 context_menu.select_first(self.completion_provider.as_deref(), cx);
7926 }
7927 }
7928
7929 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7930 if let Some(context_menu) = self.context_menu.write().as_mut() {
7931 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7932 }
7933 }
7934
7935 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7936 if let Some(context_menu) = self.context_menu.write().as_mut() {
7937 context_menu.select_next(self.completion_provider.as_deref(), cx);
7938 }
7939 }
7940
7941 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7942 if let Some(context_menu) = self.context_menu.write().as_mut() {
7943 context_menu.select_last(self.completion_provider.as_deref(), cx);
7944 }
7945 }
7946
7947 pub fn move_to_previous_word_start(
7948 &mut self,
7949 _: &MoveToPreviousWordStart,
7950 cx: &mut ViewContext<Self>,
7951 ) {
7952 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7953 s.move_cursors_with(|map, head, _| {
7954 (
7955 movement::previous_word_start(map, head),
7956 SelectionGoal::None,
7957 )
7958 });
7959 })
7960 }
7961
7962 pub fn move_to_previous_subword_start(
7963 &mut self,
7964 _: &MoveToPreviousSubwordStart,
7965 cx: &mut ViewContext<Self>,
7966 ) {
7967 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7968 s.move_cursors_with(|map, head, _| {
7969 (
7970 movement::previous_subword_start(map, head),
7971 SelectionGoal::None,
7972 )
7973 });
7974 })
7975 }
7976
7977 pub fn select_to_previous_word_start(
7978 &mut self,
7979 _: &SelectToPreviousWordStart,
7980 cx: &mut ViewContext<Self>,
7981 ) {
7982 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7983 s.move_heads_with(|map, head, _| {
7984 (
7985 movement::previous_word_start(map, head),
7986 SelectionGoal::None,
7987 )
7988 });
7989 })
7990 }
7991
7992 pub fn select_to_previous_subword_start(
7993 &mut self,
7994 _: &SelectToPreviousSubwordStart,
7995 cx: &mut ViewContext<Self>,
7996 ) {
7997 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7998 s.move_heads_with(|map, head, _| {
7999 (
8000 movement::previous_subword_start(map, head),
8001 SelectionGoal::None,
8002 )
8003 });
8004 })
8005 }
8006
8007 pub fn delete_to_previous_word_start(
8008 &mut self,
8009 action: &DeleteToPreviousWordStart,
8010 cx: &mut ViewContext<Self>,
8011 ) {
8012 self.transact(cx, |this, cx| {
8013 this.select_autoclose_pair(cx);
8014 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8015 let line_mode = s.line_mode;
8016 s.move_with(|map, selection| {
8017 if selection.is_empty() && !line_mode {
8018 let cursor = if action.ignore_newlines {
8019 movement::previous_word_start(map, selection.head())
8020 } else {
8021 movement::previous_word_start_or_newline(map, selection.head())
8022 };
8023 selection.set_head(cursor, SelectionGoal::None);
8024 }
8025 });
8026 });
8027 this.insert("", cx);
8028 });
8029 }
8030
8031 pub fn delete_to_previous_subword_start(
8032 &mut self,
8033 _: &DeleteToPreviousSubwordStart,
8034 cx: &mut ViewContext<Self>,
8035 ) {
8036 self.transact(cx, |this, cx| {
8037 this.select_autoclose_pair(cx);
8038 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8039 let line_mode = s.line_mode;
8040 s.move_with(|map, selection| {
8041 if selection.is_empty() && !line_mode {
8042 let cursor = movement::previous_subword_start(map, selection.head());
8043 selection.set_head(cursor, SelectionGoal::None);
8044 }
8045 });
8046 });
8047 this.insert("", cx);
8048 });
8049 }
8050
8051 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8052 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8053 s.move_cursors_with(|map, head, _| {
8054 (movement::next_word_end(map, head), SelectionGoal::None)
8055 });
8056 })
8057 }
8058
8059 pub fn move_to_next_subword_end(
8060 &mut self,
8061 _: &MoveToNextSubwordEnd,
8062 cx: &mut ViewContext<Self>,
8063 ) {
8064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8065 s.move_cursors_with(|map, head, _| {
8066 (movement::next_subword_end(map, head), SelectionGoal::None)
8067 });
8068 })
8069 }
8070
8071 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8072 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8073 s.move_heads_with(|map, head, _| {
8074 (movement::next_word_end(map, head), SelectionGoal::None)
8075 });
8076 })
8077 }
8078
8079 pub fn select_to_next_subword_end(
8080 &mut self,
8081 _: &SelectToNextSubwordEnd,
8082 cx: &mut ViewContext<Self>,
8083 ) {
8084 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8085 s.move_heads_with(|map, head, _| {
8086 (movement::next_subword_end(map, head), SelectionGoal::None)
8087 });
8088 })
8089 }
8090
8091 pub fn delete_to_next_word_end(
8092 &mut self,
8093 action: &DeleteToNextWordEnd,
8094 cx: &mut ViewContext<Self>,
8095 ) {
8096 self.transact(cx, |this, cx| {
8097 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8098 let line_mode = s.line_mode;
8099 s.move_with(|map, selection| {
8100 if selection.is_empty() && !line_mode {
8101 let cursor = if action.ignore_newlines {
8102 movement::next_word_end(map, selection.head())
8103 } else {
8104 movement::next_word_end_or_newline(map, selection.head())
8105 };
8106 selection.set_head(cursor, SelectionGoal::None);
8107 }
8108 });
8109 });
8110 this.insert("", cx);
8111 });
8112 }
8113
8114 pub fn delete_to_next_subword_end(
8115 &mut self,
8116 _: &DeleteToNextSubwordEnd,
8117 cx: &mut ViewContext<Self>,
8118 ) {
8119 self.transact(cx, |this, cx| {
8120 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8121 s.move_with(|map, selection| {
8122 if selection.is_empty() {
8123 let cursor = movement::next_subword_end(map, selection.head());
8124 selection.set_head(cursor, SelectionGoal::None);
8125 }
8126 });
8127 });
8128 this.insert("", cx);
8129 });
8130 }
8131
8132 pub fn move_to_beginning_of_line(
8133 &mut self,
8134 action: &MoveToBeginningOfLine,
8135 cx: &mut ViewContext<Self>,
8136 ) {
8137 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8138 s.move_cursors_with(|map, head, _| {
8139 (
8140 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8141 SelectionGoal::None,
8142 )
8143 });
8144 })
8145 }
8146
8147 pub fn select_to_beginning_of_line(
8148 &mut self,
8149 action: &SelectToBeginningOfLine,
8150 cx: &mut ViewContext<Self>,
8151 ) {
8152 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8153 s.move_heads_with(|map, head, _| {
8154 (
8155 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8156 SelectionGoal::None,
8157 )
8158 });
8159 });
8160 }
8161
8162 pub fn delete_to_beginning_of_line(
8163 &mut self,
8164 _: &DeleteToBeginningOfLine,
8165 cx: &mut ViewContext<Self>,
8166 ) {
8167 self.transact(cx, |this, cx| {
8168 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8169 s.move_with(|_, selection| {
8170 selection.reversed = true;
8171 });
8172 });
8173
8174 this.select_to_beginning_of_line(
8175 &SelectToBeginningOfLine {
8176 stop_at_soft_wraps: false,
8177 },
8178 cx,
8179 );
8180 this.backspace(&Backspace, cx);
8181 });
8182 }
8183
8184 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8185 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8186 s.move_cursors_with(|map, head, _| {
8187 (
8188 movement::line_end(map, head, action.stop_at_soft_wraps),
8189 SelectionGoal::None,
8190 )
8191 });
8192 })
8193 }
8194
8195 pub fn select_to_end_of_line(
8196 &mut self,
8197 action: &SelectToEndOfLine,
8198 cx: &mut ViewContext<Self>,
8199 ) {
8200 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8201 s.move_heads_with(|map, head, _| {
8202 (
8203 movement::line_end(map, head, action.stop_at_soft_wraps),
8204 SelectionGoal::None,
8205 )
8206 });
8207 })
8208 }
8209
8210 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8211 self.transact(cx, |this, cx| {
8212 this.select_to_end_of_line(
8213 &SelectToEndOfLine {
8214 stop_at_soft_wraps: false,
8215 },
8216 cx,
8217 );
8218 this.delete(&Delete, cx);
8219 });
8220 }
8221
8222 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8223 self.transact(cx, |this, cx| {
8224 this.select_to_end_of_line(
8225 &SelectToEndOfLine {
8226 stop_at_soft_wraps: false,
8227 },
8228 cx,
8229 );
8230 this.cut(&Cut, cx);
8231 });
8232 }
8233
8234 pub fn move_to_start_of_paragraph(
8235 &mut self,
8236 _: &MoveToStartOfParagraph,
8237 cx: &mut ViewContext<Self>,
8238 ) {
8239 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8240 cx.propagate();
8241 return;
8242 }
8243
8244 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8245 s.move_with(|map, selection| {
8246 selection.collapse_to(
8247 movement::start_of_paragraph(map, selection.head(), 1),
8248 SelectionGoal::None,
8249 )
8250 });
8251 })
8252 }
8253
8254 pub fn move_to_end_of_paragraph(
8255 &mut self,
8256 _: &MoveToEndOfParagraph,
8257 cx: &mut ViewContext<Self>,
8258 ) {
8259 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8260 cx.propagate();
8261 return;
8262 }
8263
8264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8265 s.move_with(|map, selection| {
8266 selection.collapse_to(
8267 movement::end_of_paragraph(map, selection.head(), 1),
8268 SelectionGoal::None,
8269 )
8270 });
8271 })
8272 }
8273
8274 pub fn select_to_start_of_paragraph(
8275 &mut self,
8276 _: &SelectToStartOfParagraph,
8277 cx: &mut ViewContext<Self>,
8278 ) {
8279 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8280 cx.propagate();
8281 return;
8282 }
8283
8284 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8285 s.move_heads_with(|map, head, _| {
8286 (
8287 movement::start_of_paragraph(map, head, 1),
8288 SelectionGoal::None,
8289 )
8290 });
8291 })
8292 }
8293
8294 pub fn select_to_end_of_paragraph(
8295 &mut self,
8296 _: &SelectToEndOfParagraph,
8297 cx: &mut ViewContext<Self>,
8298 ) {
8299 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8300 cx.propagate();
8301 return;
8302 }
8303
8304 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8305 s.move_heads_with(|map, head, _| {
8306 (
8307 movement::end_of_paragraph(map, head, 1),
8308 SelectionGoal::None,
8309 )
8310 });
8311 })
8312 }
8313
8314 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8315 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8316 cx.propagate();
8317 return;
8318 }
8319
8320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8321 s.select_ranges(vec![0..0]);
8322 });
8323 }
8324
8325 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8326 let mut selection = self.selections.last::<Point>(cx);
8327 selection.set_head(Point::zero(), SelectionGoal::None);
8328
8329 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8330 s.select(vec![selection]);
8331 });
8332 }
8333
8334 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8335 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8336 cx.propagate();
8337 return;
8338 }
8339
8340 let cursor = self.buffer.read(cx).read(cx).len();
8341 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8342 s.select_ranges(vec![cursor..cursor])
8343 });
8344 }
8345
8346 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8347 self.nav_history = nav_history;
8348 }
8349
8350 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8351 self.nav_history.as_ref()
8352 }
8353
8354 fn push_to_nav_history(
8355 &mut self,
8356 cursor_anchor: Anchor,
8357 new_position: Option<Point>,
8358 cx: &mut ViewContext<Self>,
8359 ) {
8360 if let Some(nav_history) = self.nav_history.as_mut() {
8361 let buffer = self.buffer.read(cx).read(cx);
8362 let cursor_position = cursor_anchor.to_point(&buffer);
8363 let scroll_state = self.scroll_manager.anchor();
8364 let scroll_top_row = scroll_state.top_row(&buffer);
8365 drop(buffer);
8366
8367 if let Some(new_position) = new_position {
8368 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8369 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8370 return;
8371 }
8372 }
8373
8374 nav_history.push(
8375 Some(NavigationData {
8376 cursor_anchor,
8377 cursor_position,
8378 scroll_anchor: scroll_state,
8379 scroll_top_row,
8380 }),
8381 cx,
8382 );
8383 }
8384 }
8385
8386 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8387 let buffer = self.buffer.read(cx).snapshot(cx);
8388 let mut selection = self.selections.first::<usize>(cx);
8389 selection.set_head(buffer.len(), SelectionGoal::None);
8390 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8391 s.select(vec![selection]);
8392 });
8393 }
8394
8395 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8396 let end = self.buffer.read(cx).read(cx).len();
8397 self.change_selections(None, cx, |s| {
8398 s.select_ranges(vec![0..end]);
8399 });
8400 }
8401
8402 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8403 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8404 let mut selections = self.selections.all::<Point>(cx);
8405 let max_point = display_map.buffer_snapshot.max_point();
8406 for selection in &mut selections {
8407 let rows = selection.spanned_rows(true, &display_map);
8408 selection.start = Point::new(rows.start.0, 0);
8409 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8410 selection.reversed = false;
8411 }
8412 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8413 s.select(selections);
8414 });
8415 }
8416
8417 pub fn split_selection_into_lines(
8418 &mut self,
8419 _: &SplitSelectionIntoLines,
8420 cx: &mut ViewContext<Self>,
8421 ) {
8422 let mut to_unfold = Vec::new();
8423 let mut new_selection_ranges = Vec::new();
8424 {
8425 let selections = self.selections.all::<Point>(cx);
8426 let buffer = self.buffer.read(cx).read(cx);
8427 for selection in selections {
8428 for row in selection.start.row..selection.end.row {
8429 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8430 new_selection_ranges.push(cursor..cursor);
8431 }
8432 new_selection_ranges.push(selection.end..selection.end);
8433 to_unfold.push(selection.start..selection.end);
8434 }
8435 }
8436 self.unfold_ranges(&to_unfold, true, true, cx);
8437 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8438 s.select_ranges(new_selection_ranges);
8439 });
8440 }
8441
8442 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8443 self.add_selection(true, cx);
8444 }
8445
8446 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8447 self.add_selection(false, cx);
8448 }
8449
8450 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8452 let mut selections = self.selections.all::<Point>(cx);
8453 let text_layout_details = self.text_layout_details(cx);
8454 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8455 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8456 let range = oldest_selection.display_range(&display_map).sorted();
8457
8458 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8459 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8460 let positions = start_x.min(end_x)..start_x.max(end_x);
8461
8462 selections.clear();
8463 let mut stack = Vec::new();
8464 for row in range.start.row().0..=range.end.row().0 {
8465 if let Some(selection) = self.selections.build_columnar_selection(
8466 &display_map,
8467 DisplayRow(row),
8468 &positions,
8469 oldest_selection.reversed,
8470 &text_layout_details,
8471 ) {
8472 stack.push(selection.id);
8473 selections.push(selection);
8474 }
8475 }
8476
8477 if above {
8478 stack.reverse();
8479 }
8480
8481 AddSelectionsState { above, stack }
8482 });
8483
8484 let last_added_selection = *state.stack.last().unwrap();
8485 let mut new_selections = Vec::new();
8486 if above == state.above {
8487 let end_row = if above {
8488 DisplayRow(0)
8489 } else {
8490 display_map.max_point().row()
8491 };
8492
8493 'outer: for selection in selections {
8494 if selection.id == last_added_selection {
8495 let range = selection.display_range(&display_map).sorted();
8496 debug_assert_eq!(range.start.row(), range.end.row());
8497 let mut row = range.start.row();
8498 let positions =
8499 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8500 px(start)..px(end)
8501 } else {
8502 let start_x =
8503 display_map.x_for_display_point(range.start, &text_layout_details);
8504 let end_x =
8505 display_map.x_for_display_point(range.end, &text_layout_details);
8506 start_x.min(end_x)..start_x.max(end_x)
8507 };
8508
8509 while row != end_row {
8510 if above {
8511 row.0 -= 1;
8512 } else {
8513 row.0 += 1;
8514 }
8515
8516 if let Some(new_selection) = self.selections.build_columnar_selection(
8517 &display_map,
8518 row,
8519 &positions,
8520 selection.reversed,
8521 &text_layout_details,
8522 ) {
8523 state.stack.push(new_selection.id);
8524 if above {
8525 new_selections.push(new_selection);
8526 new_selections.push(selection);
8527 } else {
8528 new_selections.push(selection);
8529 new_selections.push(new_selection);
8530 }
8531
8532 continue 'outer;
8533 }
8534 }
8535 }
8536
8537 new_selections.push(selection);
8538 }
8539 } else {
8540 new_selections = selections;
8541 new_selections.retain(|s| s.id != last_added_selection);
8542 state.stack.pop();
8543 }
8544
8545 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8546 s.select(new_selections);
8547 });
8548 if state.stack.len() > 1 {
8549 self.add_selections_state = Some(state);
8550 }
8551 }
8552
8553 pub fn select_next_match_internal(
8554 &mut self,
8555 display_map: &DisplaySnapshot,
8556 replace_newest: bool,
8557 autoscroll: Option<Autoscroll>,
8558 cx: &mut ViewContext<Self>,
8559 ) -> Result<()> {
8560 fn select_next_match_ranges(
8561 this: &mut Editor,
8562 range: Range<usize>,
8563 replace_newest: bool,
8564 auto_scroll: Option<Autoscroll>,
8565 cx: &mut ViewContext<Editor>,
8566 ) {
8567 this.unfold_ranges(&[range.clone()], false, true, cx);
8568 this.change_selections(auto_scroll, cx, |s| {
8569 if replace_newest {
8570 s.delete(s.newest_anchor().id);
8571 }
8572 s.insert_range(range.clone());
8573 });
8574 }
8575
8576 let buffer = &display_map.buffer_snapshot;
8577 let mut selections = self.selections.all::<usize>(cx);
8578 if let Some(mut select_next_state) = self.select_next_state.take() {
8579 let query = &select_next_state.query;
8580 if !select_next_state.done {
8581 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8582 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8583 let mut next_selected_range = None;
8584
8585 let bytes_after_last_selection =
8586 buffer.bytes_in_range(last_selection.end..buffer.len());
8587 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8588 let query_matches = query
8589 .stream_find_iter(bytes_after_last_selection)
8590 .map(|result| (last_selection.end, result))
8591 .chain(
8592 query
8593 .stream_find_iter(bytes_before_first_selection)
8594 .map(|result| (0, result)),
8595 );
8596
8597 for (start_offset, query_match) in query_matches {
8598 let query_match = query_match.unwrap(); // can only fail due to I/O
8599 let offset_range =
8600 start_offset + query_match.start()..start_offset + query_match.end();
8601 let display_range = offset_range.start.to_display_point(display_map)
8602 ..offset_range.end.to_display_point(display_map);
8603
8604 if !select_next_state.wordwise
8605 || (!movement::is_inside_word(display_map, display_range.start)
8606 && !movement::is_inside_word(display_map, display_range.end))
8607 {
8608 // TODO: This is n^2, because we might check all the selections
8609 if !selections
8610 .iter()
8611 .any(|selection| selection.range().overlaps(&offset_range))
8612 {
8613 next_selected_range = Some(offset_range);
8614 break;
8615 }
8616 }
8617 }
8618
8619 if let Some(next_selected_range) = next_selected_range {
8620 select_next_match_ranges(
8621 self,
8622 next_selected_range,
8623 replace_newest,
8624 autoscroll,
8625 cx,
8626 );
8627 } else {
8628 select_next_state.done = true;
8629 }
8630 }
8631
8632 self.select_next_state = Some(select_next_state);
8633 } else {
8634 let mut only_carets = true;
8635 let mut same_text_selected = true;
8636 let mut selected_text = None;
8637
8638 let mut selections_iter = selections.iter().peekable();
8639 while let Some(selection) = selections_iter.next() {
8640 if selection.start != selection.end {
8641 only_carets = false;
8642 }
8643
8644 if same_text_selected {
8645 if selected_text.is_none() {
8646 selected_text =
8647 Some(buffer.text_for_range(selection.range()).collect::<String>());
8648 }
8649
8650 if let Some(next_selection) = selections_iter.peek() {
8651 if next_selection.range().len() == selection.range().len() {
8652 let next_selected_text = buffer
8653 .text_for_range(next_selection.range())
8654 .collect::<String>();
8655 if Some(next_selected_text) != selected_text {
8656 same_text_selected = false;
8657 selected_text = None;
8658 }
8659 } else {
8660 same_text_selected = false;
8661 selected_text = None;
8662 }
8663 }
8664 }
8665 }
8666
8667 if only_carets {
8668 for selection in &mut selections {
8669 let word_range = movement::surrounding_word(
8670 display_map,
8671 selection.start.to_display_point(display_map),
8672 );
8673 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8674 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8675 selection.goal = SelectionGoal::None;
8676 selection.reversed = false;
8677 select_next_match_ranges(
8678 self,
8679 selection.start..selection.end,
8680 replace_newest,
8681 autoscroll,
8682 cx,
8683 );
8684 }
8685
8686 if selections.len() == 1 {
8687 let selection = selections
8688 .last()
8689 .expect("ensured that there's only one selection");
8690 let query = buffer
8691 .text_for_range(selection.start..selection.end)
8692 .collect::<String>();
8693 let is_empty = query.is_empty();
8694 let select_state = SelectNextState {
8695 query: AhoCorasick::new(&[query])?,
8696 wordwise: true,
8697 done: is_empty,
8698 };
8699 self.select_next_state = Some(select_state);
8700 } else {
8701 self.select_next_state = None;
8702 }
8703 } else if let Some(selected_text) = selected_text {
8704 self.select_next_state = Some(SelectNextState {
8705 query: AhoCorasick::new(&[selected_text])?,
8706 wordwise: false,
8707 done: false,
8708 });
8709 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8710 }
8711 }
8712 Ok(())
8713 }
8714
8715 pub fn select_all_matches(
8716 &mut self,
8717 _action: &SelectAllMatches,
8718 cx: &mut ViewContext<Self>,
8719 ) -> Result<()> {
8720 self.push_to_selection_history();
8721 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8722
8723 self.select_next_match_internal(&display_map, false, None, cx)?;
8724 let Some(select_next_state) = self.select_next_state.as_mut() else {
8725 return Ok(());
8726 };
8727 if select_next_state.done {
8728 return Ok(());
8729 }
8730
8731 let mut new_selections = self.selections.all::<usize>(cx);
8732
8733 let buffer = &display_map.buffer_snapshot;
8734 let query_matches = select_next_state
8735 .query
8736 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8737
8738 for query_match in query_matches {
8739 let query_match = query_match.unwrap(); // can only fail due to I/O
8740 let offset_range = query_match.start()..query_match.end();
8741 let display_range = offset_range.start.to_display_point(&display_map)
8742 ..offset_range.end.to_display_point(&display_map);
8743
8744 if !select_next_state.wordwise
8745 || (!movement::is_inside_word(&display_map, display_range.start)
8746 && !movement::is_inside_word(&display_map, display_range.end))
8747 {
8748 self.selections.change_with(cx, |selections| {
8749 new_selections.push(Selection {
8750 id: selections.new_selection_id(),
8751 start: offset_range.start,
8752 end: offset_range.end,
8753 reversed: false,
8754 goal: SelectionGoal::None,
8755 });
8756 });
8757 }
8758 }
8759
8760 new_selections.sort_by_key(|selection| selection.start);
8761 let mut ix = 0;
8762 while ix + 1 < new_selections.len() {
8763 let current_selection = &new_selections[ix];
8764 let next_selection = &new_selections[ix + 1];
8765 if current_selection.range().overlaps(&next_selection.range()) {
8766 if current_selection.id < next_selection.id {
8767 new_selections.remove(ix + 1);
8768 } else {
8769 new_selections.remove(ix);
8770 }
8771 } else {
8772 ix += 1;
8773 }
8774 }
8775
8776 select_next_state.done = true;
8777 self.unfold_ranges(
8778 &new_selections
8779 .iter()
8780 .map(|selection| selection.range())
8781 .collect::<Vec<_>>(),
8782 false,
8783 false,
8784 cx,
8785 );
8786 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8787 selections.select(new_selections)
8788 });
8789
8790 Ok(())
8791 }
8792
8793 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8794 self.push_to_selection_history();
8795 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8796 self.select_next_match_internal(
8797 &display_map,
8798 action.replace_newest,
8799 Some(Autoscroll::newest()),
8800 cx,
8801 )?;
8802 Ok(())
8803 }
8804
8805 pub fn select_previous(
8806 &mut self,
8807 action: &SelectPrevious,
8808 cx: &mut ViewContext<Self>,
8809 ) -> Result<()> {
8810 self.push_to_selection_history();
8811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8812 let buffer = &display_map.buffer_snapshot;
8813 let mut selections = self.selections.all::<usize>(cx);
8814 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8815 let query = &select_prev_state.query;
8816 if !select_prev_state.done {
8817 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8818 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8819 let mut next_selected_range = None;
8820 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8821 let bytes_before_last_selection =
8822 buffer.reversed_bytes_in_range(0..last_selection.start);
8823 let bytes_after_first_selection =
8824 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8825 let query_matches = query
8826 .stream_find_iter(bytes_before_last_selection)
8827 .map(|result| (last_selection.start, result))
8828 .chain(
8829 query
8830 .stream_find_iter(bytes_after_first_selection)
8831 .map(|result| (buffer.len(), result)),
8832 );
8833 for (end_offset, query_match) in query_matches {
8834 let query_match = query_match.unwrap(); // can only fail due to I/O
8835 let offset_range =
8836 end_offset - query_match.end()..end_offset - query_match.start();
8837 let display_range = offset_range.start.to_display_point(&display_map)
8838 ..offset_range.end.to_display_point(&display_map);
8839
8840 if !select_prev_state.wordwise
8841 || (!movement::is_inside_word(&display_map, display_range.start)
8842 && !movement::is_inside_word(&display_map, display_range.end))
8843 {
8844 next_selected_range = Some(offset_range);
8845 break;
8846 }
8847 }
8848
8849 if let Some(next_selected_range) = next_selected_range {
8850 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8851 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8852 if action.replace_newest {
8853 s.delete(s.newest_anchor().id);
8854 }
8855 s.insert_range(next_selected_range);
8856 });
8857 } else {
8858 select_prev_state.done = true;
8859 }
8860 }
8861
8862 self.select_prev_state = Some(select_prev_state);
8863 } else {
8864 let mut only_carets = true;
8865 let mut same_text_selected = true;
8866 let mut selected_text = None;
8867
8868 let mut selections_iter = selections.iter().peekable();
8869 while let Some(selection) = selections_iter.next() {
8870 if selection.start != selection.end {
8871 only_carets = false;
8872 }
8873
8874 if same_text_selected {
8875 if selected_text.is_none() {
8876 selected_text =
8877 Some(buffer.text_for_range(selection.range()).collect::<String>());
8878 }
8879
8880 if let Some(next_selection) = selections_iter.peek() {
8881 if next_selection.range().len() == selection.range().len() {
8882 let next_selected_text = buffer
8883 .text_for_range(next_selection.range())
8884 .collect::<String>();
8885 if Some(next_selected_text) != selected_text {
8886 same_text_selected = false;
8887 selected_text = None;
8888 }
8889 } else {
8890 same_text_selected = false;
8891 selected_text = None;
8892 }
8893 }
8894 }
8895 }
8896
8897 if only_carets {
8898 for selection in &mut selections {
8899 let word_range = movement::surrounding_word(
8900 &display_map,
8901 selection.start.to_display_point(&display_map),
8902 );
8903 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8904 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8905 selection.goal = SelectionGoal::None;
8906 selection.reversed = false;
8907 }
8908 if selections.len() == 1 {
8909 let selection = selections
8910 .last()
8911 .expect("ensured that there's only one selection");
8912 let query = buffer
8913 .text_for_range(selection.start..selection.end)
8914 .collect::<String>();
8915 let is_empty = query.is_empty();
8916 let select_state = SelectNextState {
8917 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8918 wordwise: true,
8919 done: is_empty,
8920 };
8921 self.select_prev_state = Some(select_state);
8922 } else {
8923 self.select_prev_state = None;
8924 }
8925
8926 self.unfold_ranges(
8927 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8928 false,
8929 true,
8930 cx,
8931 );
8932 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8933 s.select(selections);
8934 });
8935 } else if let Some(selected_text) = selected_text {
8936 self.select_prev_state = Some(SelectNextState {
8937 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8938 wordwise: false,
8939 done: false,
8940 });
8941 self.select_previous(action, cx)?;
8942 }
8943 }
8944 Ok(())
8945 }
8946
8947 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8948 if self.read_only(cx) {
8949 return;
8950 }
8951 let text_layout_details = &self.text_layout_details(cx);
8952 self.transact(cx, |this, cx| {
8953 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8954 let mut edits = Vec::new();
8955 let mut selection_edit_ranges = Vec::new();
8956 let mut last_toggled_row = None;
8957 let snapshot = this.buffer.read(cx).read(cx);
8958 let empty_str: Arc<str> = Arc::default();
8959 let mut suffixes_inserted = Vec::new();
8960 let ignore_indent = action.ignore_indent;
8961
8962 fn comment_prefix_range(
8963 snapshot: &MultiBufferSnapshot,
8964 row: MultiBufferRow,
8965 comment_prefix: &str,
8966 comment_prefix_whitespace: &str,
8967 ignore_indent: bool,
8968 ) -> Range<Point> {
8969 let indent_size = if ignore_indent {
8970 0
8971 } else {
8972 snapshot.indent_size_for_line(row).len
8973 };
8974
8975 let start = Point::new(row.0, indent_size);
8976
8977 let mut line_bytes = snapshot
8978 .bytes_in_range(start..snapshot.max_point())
8979 .flatten()
8980 .copied();
8981
8982 // If this line currently begins with the line comment prefix, then record
8983 // the range containing the prefix.
8984 if line_bytes
8985 .by_ref()
8986 .take(comment_prefix.len())
8987 .eq(comment_prefix.bytes())
8988 {
8989 // Include any whitespace that matches the comment prefix.
8990 let matching_whitespace_len = line_bytes
8991 .zip(comment_prefix_whitespace.bytes())
8992 .take_while(|(a, b)| a == b)
8993 .count() as u32;
8994 let end = Point::new(
8995 start.row,
8996 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8997 );
8998 start..end
8999 } else {
9000 start..start
9001 }
9002 }
9003
9004 fn comment_suffix_range(
9005 snapshot: &MultiBufferSnapshot,
9006 row: MultiBufferRow,
9007 comment_suffix: &str,
9008 comment_suffix_has_leading_space: bool,
9009 ) -> Range<Point> {
9010 let end = Point::new(row.0, snapshot.line_len(row));
9011 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9012
9013 let mut line_end_bytes = snapshot
9014 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9015 .flatten()
9016 .copied();
9017
9018 let leading_space_len = if suffix_start_column > 0
9019 && line_end_bytes.next() == Some(b' ')
9020 && comment_suffix_has_leading_space
9021 {
9022 1
9023 } else {
9024 0
9025 };
9026
9027 // If this line currently begins with the line comment prefix, then record
9028 // the range containing the prefix.
9029 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9030 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9031 start..end
9032 } else {
9033 end..end
9034 }
9035 }
9036
9037 // TODO: Handle selections that cross excerpts
9038 for selection in &mut selections {
9039 let start_column = snapshot
9040 .indent_size_for_line(MultiBufferRow(selection.start.row))
9041 .len;
9042 let language = if let Some(language) =
9043 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9044 {
9045 language
9046 } else {
9047 continue;
9048 };
9049
9050 selection_edit_ranges.clear();
9051
9052 // If multiple selections contain a given row, avoid processing that
9053 // row more than once.
9054 let mut start_row = MultiBufferRow(selection.start.row);
9055 if last_toggled_row == Some(start_row) {
9056 start_row = start_row.next_row();
9057 }
9058 let end_row =
9059 if selection.end.row > selection.start.row && selection.end.column == 0 {
9060 MultiBufferRow(selection.end.row - 1)
9061 } else {
9062 MultiBufferRow(selection.end.row)
9063 };
9064 last_toggled_row = Some(end_row);
9065
9066 if start_row > end_row {
9067 continue;
9068 }
9069
9070 // If the language has line comments, toggle those.
9071 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9072
9073 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9074 if ignore_indent {
9075 full_comment_prefixes = full_comment_prefixes
9076 .into_iter()
9077 .map(|s| Arc::from(s.trim_end()))
9078 .collect();
9079 }
9080
9081 if !full_comment_prefixes.is_empty() {
9082 let first_prefix = full_comment_prefixes
9083 .first()
9084 .expect("prefixes is non-empty");
9085 let prefix_trimmed_lengths = full_comment_prefixes
9086 .iter()
9087 .map(|p| p.trim_end_matches(' ').len())
9088 .collect::<SmallVec<[usize; 4]>>();
9089
9090 let mut all_selection_lines_are_comments = true;
9091
9092 for row in start_row.0..=end_row.0 {
9093 let row = MultiBufferRow(row);
9094 if start_row < end_row && snapshot.is_line_blank(row) {
9095 continue;
9096 }
9097
9098 let prefix_range = full_comment_prefixes
9099 .iter()
9100 .zip(prefix_trimmed_lengths.iter().copied())
9101 .map(|(prefix, trimmed_prefix_len)| {
9102 comment_prefix_range(
9103 snapshot.deref(),
9104 row,
9105 &prefix[..trimmed_prefix_len],
9106 &prefix[trimmed_prefix_len..],
9107 ignore_indent,
9108 )
9109 })
9110 .max_by_key(|range| range.end.column - range.start.column)
9111 .expect("prefixes is non-empty");
9112
9113 if prefix_range.is_empty() {
9114 all_selection_lines_are_comments = false;
9115 }
9116
9117 selection_edit_ranges.push(prefix_range);
9118 }
9119
9120 if all_selection_lines_are_comments {
9121 edits.extend(
9122 selection_edit_ranges
9123 .iter()
9124 .cloned()
9125 .map(|range| (range, empty_str.clone())),
9126 );
9127 } else {
9128 let min_column = selection_edit_ranges
9129 .iter()
9130 .map(|range| range.start.column)
9131 .min()
9132 .unwrap_or(0);
9133 edits.extend(selection_edit_ranges.iter().map(|range| {
9134 let position = Point::new(range.start.row, min_column);
9135 (position..position, first_prefix.clone())
9136 }));
9137 }
9138 } else if let Some((full_comment_prefix, comment_suffix)) =
9139 language.block_comment_delimiters()
9140 {
9141 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9142 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9143 let prefix_range = comment_prefix_range(
9144 snapshot.deref(),
9145 start_row,
9146 comment_prefix,
9147 comment_prefix_whitespace,
9148 ignore_indent,
9149 );
9150 let suffix_range = comment_suffix_range(
9151 snapshot.deref(),
9152 end_row,
9153 comment_suffix.trim_start_matches(' '),
9154 comment_suffix.starts_with(' '),
9155 );
9156
9157 if prefix_range.is_empty() || suffix_range.is_empty() {
9158 edits.push((
9159 prefix_range.start..prefix_range.start,
9160 full_comment_prefix.clone(),
9161 ));
9162 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9163 suffixes_inserted.push((end_row, comment_suffix.len()));
9164 } else {
9165 edits.push((prefix_range, empty_str.clone()));
9166 edits.push((suffix_range, empty_str.clone()));
9167 }
9168 } else {
9169 continue;
9170 }
9171 }
9172
9173 drop(snapshot);
9174 this.buffer.update(cx, |buffer, cx| {
9175 buffer.edit(edits, None, cx);
9176 });
9177
9178 // Adjust selections so that they end before any comment suffixes that
9179 // were inserted.
9180 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9181 let mut selections = this.selections.all::<Point>(cx);
9182 let snapshot = this.buffer.read(cx).read(cx);
9183 for selection in &mut selections {
9184 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9185 match row.cmp(&MultiBufferRow(selection.end.row)) {
9186 Ordering::Less => {
9187 suffixes_inserted.next();
9188 continue;
9189 }
9190 Ordering::Greater => break,
9191 Ordering::Equal => {
9192 if selection.end.column == snapshot.line_len(row) {
9193 if selection.is_empty() {
9194 selection.start.column -= suffix_len as u32;
9195 }
9196 selection.end.column -= suffix_len as u32;
9197 }
9198 break;
9199 }
9200 }
9201 }
9202 }
9203
9204 drop(snapshot);
9205 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9206
9207 let selections = this.selections.all::<Point>(cx);
9208 let selections_on_single_row = selections.windows(2).all(|selections| {
9209 selections[0].start.row == selections[1].start.row
9210 && selections[0].end.row == selections[1].end.row
9211 && selections[0].start.row == selections[0].end.row
9212 });
9213 let selections_selecting = selections
9214 .iter()
9215 .any(|selection| selection.start != selection.end);
9216 let advance_downwards = action.advance_downwards
9217 && selections_on_single_row
9218 && !selections_selecting
9219 && !matches!(this.mode, EditorMode::SingleLine { .. });
9220
9221 if advance_downwards {
9222 let snapshot = this.buffer.read(cx).snapshot(cx);
9223
9224 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9225 s.move_cursors_with(|display_snapshot, display_point, _| {
9226 let mut point = display_point.to_point(display_snapshot);
9227 point.row += 1;
9228 point = snapshot.clip_point(point, Bias::Left);
9229 let display_point = point.to_display_point(display_snapshot);
9230 let goal = SelectionGoal::HorizontalPosition(
9231 display_snapshot
9232 .x_for_display_point(display_point, text_layout_details)
9233 .into(),
9234 );
9235 (display_point, goal)
9236 })
9237 });
9238 }
9239 });
9240 }
9241
9242 pub fn select_enclosing_symbol(
9243 &mut self,
9244 _: &SelectEnclosingSymbol,
9245 cx: &mut ViewContext<Self>,
9246 ) {
9247 let buffer = self.buffer.read(cx).snapshot(cx);
9248 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9249
9250 fn update_selection(
9251 selection: &Selection<usize>,
9252 buffer_snap: &MultiBufferSnapshot,
9253 ) -> Option<Selection<usize>> {
9254 let cursor = selection.head();
9255 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9256 for symbol in symbols.iter().rev() {
9257 let start = symbol.range.start.to_offset(buffer_snap);
9258 let end = symbol.range.end.to_offset(buffer_snap);
9259 let new_range = start..end;
9260 if start < selection.start || end > selection.end {
9261 return Some(Selection {
9262 id: selection.id,
9263 start: new_range.start,
9264 end: new_range.end,
9265 goal: SelectionGoal::None,
9266 reversed: selection.reversed,
9267 });
9268 }
9269 }
9270 None
9271 }
9272
9273 let mut selected_larger_symbol = false;
9274 let new_selections = old_selections
9275 .iter()
9276 .map(|selection| match update_selection(selection, &buffer) {
9277 Some(new_selection) => {
9278 if new_selection.range() != selection.range() {
9279 selected_larger_symbol = true;
9280 }
9281 new_selection
9282 }
9283 None => selection.clone(),
9284 })
9285 .collect::<Vec<_>>();
9286
9287 if selected_larger_symbol {
9288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9289 s.select(new_selections);
9290 });
9291 }
9292 }
9293
9294 pub fn select_larger_syntax_node(
9295 &mut self,
9296 _: &SelectLargerSyntaxNode,
9297 cx: &mut ViewContext<Self>,
9298 ) {
9299 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9300 let buffer = self.buffer.read(cx).snapshot(cx);
9301 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9302
9303 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9304 let mut selected_larger_node = false;
9305 let new_selections = old_selections
9306 .iter()
9307 .map(|selection| {
9308 let old_range = selection.start..selection.end;
9309 let mut new_range = old_range.clone();
9310 while let Some(containing_range) =
9311 buffer.range_for_syntax_ancestor(new_range.clone())
9312 {
9313 new_range = containing_range;
9314 if !display_map.intersects_fold(new_range.start)
9315 && !display_map.intersects_fold(new_range.end)
9316 {
9317 break;
9318 }
9319 }
9320
9321 selected_larger_node |= new_range != old_range;
9322 Selection {
9323 id: selection.id,
9324 start: new_range.start,
9325 end: new_range.end,
9326 goal: SelectionGoal::None,
9327 reversed: selection.reversed,
9328 }
9329 })
9330 .collect::<Vec<_>>();
9331
9332 if selected_larger_node {
9333 stack.push(old_selections);
9334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9335 s.select(new_selections);
9336 });
9337 }
9338 self.select_larger_syntax_node_stack = stack;
9339 }
9340
9341 pub fn select_smaller_syntax_node(
9342 &mut self,
9343 _: &SelectSmallerSyntaxNode,
9344 cx: &mut ViewContext<Self>,
9345 ) {
9346 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9347 if let Some(selections) = stack.pop() {
9348 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9349 s.select(selections.to_vec());
9350 });
9351 }
9352 self.select_larger_syntax_node_stack = stack;
9353 }
9354
9355 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9356 if !EditorSettings::get_global(cx).gutter.runnables {
9357 self.clear_tasks();
9358 return Task::ready(());
9359 }
9360 let project = self.project.as_ref().map(Model::downgrade);
9361 cx.spawn(|this, mut cx| async move {
9362 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9363 let Some(project) = project.and_then(|p| p.upgrade()) else {
9364 return;
9365 };
9366 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9367 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9368 }) else {
9369 return;
9370 };
9371
9372 let hide_runnables = project
9373 .update(&mut cx, |project, cx| {
9374 // Do not display any test indicators in non-dev server remote projects.
9375 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9376 })
9377 .unwrap_or(true);
9378 if hide_runnables {
9379 return;
9380 }
9381 let new_rows =
9382 cx.background_executor()
9383 .spawn({
9384 let snapshot = display_snapshot.clone();
9385 async move {
9386 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9387 }
9388 })
9389 .await;
9390 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9391
9392 this.update(&mut cx, |this, _| {
9393 this.clear_tasks();
9394 for (key, value) in rows {
9395 this.insert_tasks(key, value);
9396 }
9397 })
9398 .ok();
9399 })
9400 }
9401 fn fetch_runnable_ranges(
9402 snapshot: &DisplaySnapshot,
9403 range: Range<Anchor>,
9404 ) -> Vec<language::RunnableRange> {
9405 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9406 }
9407
9408 fn runnable_rows(
9409 project: Model<Project>,
9410 snapshot: DisplaySnapshot,
9411 runnable_ranges: Vec<RunnableRange>,
9412 mut cx: AsyncWindowContext,
9413 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9414 runnable_ranges
9415 .into_iter()
9416 .filter_map(|mut runnable| {
9417 let tasks = cx
9418 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9419 .ok()?;
9420 if tasks.is_empty() {
9421 return None;
9422 }
9423
9424 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9425
9426 let row = snapshot
9427 .buffer_snapshot
9428 .buffer_line_for_row(MultiBufferRow(point.row))?
9429 .1
9430 .start
9431 .row;
9432
9433 let context_range =
9434 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9435 Some((
9436 (runnable.buffer_id, row),
9437 RunnableTasks {
9438 templates: tasks,
9439 offset: MultiBufferOffset(runnable.run_range.start),
9440 context_range,
9441 column: point.column,
9442 extra_variables: runnable.extra_captures,
9443 },
9444 ))
9445 })
9446 .collect()
9447 }
9448
9449 fn templates_with_tags(
9450 project: &Model<Project>,
9451 runnable: &mut Runnable,
9452 cx: &WindowContext<'_>,
9453 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9454 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9455 let (worktree_id, file) = project
9456 .buffer_for_id(runnable.buffer, cx)
9457 .and_then(|buffer| buffer.read(cx).file())
9458 .map(|file| (file.worktree_id(cx), file.clone()))
9459 .unzip();
9460
9461 (
9462 project.task_store().read(cx).task_inventory().cloned(),
9463 worktree_id,
9464 file,
9465 )
9466 });
9467
9468 let tags = mem::take(&mut runnable.tags);
9469 let mut tags: Vec<_> = tags
9470 .into_iter()
9471 .flat_map(|tag| {
9472 let tag = tag.0.clone();
9473 inventory
9474 .as_ref()
9475 .into_iter()
9476 .flat_map(|inventory| {
9477 inventory.read(cx).list_tasks(
9478 file.clone(),
9479 Some(runnable.language.clone()),
9480 worktree_id,
9481 cx,
9482 )
9483 })
9484 .filter(move |(_, template)| {
9485 template.tags.iter().any(|source_tag| source_tag == &tag)
9486 })
9487 })
9488 .sorted_by_key(|(kind, _)| kind.to_owned())
9489 .collect();
9490 if let Some((leading_tag_source, _)) = tags.first() {
9491 // Strongest source wins; if we have worktree tag binding, prefer that to
9492 // global and language bindings;
9493 // if we have a global binding, prefer that to language binding.
9494 let first_mismatch = tags
9495 .iter()
9496 .position(|(tag_source, _)| tag_source != leading_tag_source);
9497 if let Some(index) = first_mismatch {
9498 tags.truncate(index);
9499 }
9500 }
9501
9502 tags
9503 }
9504
9505 pub fn move_to_enclosing_bracket(
9506 &mut self,
9507 _: &MoveToEnclosingBracket,
9508 cx: &mut ViewContext<Self>,
9509 ) {
9510 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9511 s.move_offsets_with(|snapshot, selection| {
9512 let Some(enclosing_bracket_ranges) =
9513 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9514 else {
9515 return;
9516 };
9517
9518 let mut best_length = usize::MAX;
9519 let mut best_inside = false;
9520 let mut best_in_bracket_range = false;
9521 let mut best_destination = None;
9522 for (open, close) in enclosing_bracket_ranges {
9523 let close = close.to_inclusive();
9524 let length = close.end() - open.start;
9525 let inside = selection.start >= open.end && selection.end <= *close.start();
9526 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9527 || close.contains(&selection.head());
9528
9529 // If best is next to a bracket and current isn't, skip
9530 if !in_bracket_range && best_in_bracket_range {
9531 continue;
9532 }
9533
9534 // Prefer smaller lengths unless best is inside and current isn't
9535 if length > best_length && (best_inside || !inside) {
9536 continue;
9537 }
9538
9539 best_length = length;
9540 best_inside = inside;
9541 best_in_bracket_range = in_bracket_range;
9542 best_destination = Some(
9543 if close.contains(&selection.start) && close.contains(&selection.end) {
9544 if inside {
9545 open.end
9546 } else {
9547 open.start
9548 }
9549 } else if inside {
9550 *close.start()
9551 } else {
9552 *close.end()
9553 },
9554 );
9555 }
9556
9557 if let Some(destination) = best_destination {
9558 selection.collapse_to(destination, SelectionGoal::None);
9559 }
9560 })
9561 });
9562 }
9563
9564 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9565 self.end_selection(cx);
9566 self.selection_history.mode = SelectionHistoryMode::Undoing;
9567 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9568 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9569 self.select_next_state = entry.select_next_state;
9570 self.select_prev_state = entry.select_prev_state;
9571 self.add_selections_state = entry.add_selections_state;
9572 self.request_autoscroll(Autoscroll::newest(), cx);
9573 }
9574 self.selection_history.mode = SelectionHistoryMode::Normal;
9575 }
9576
9577 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9578 self.end_selection(cx);
9579 self.selection_history.mode = SelectionHistoryMode::Redoing;
9580 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9581 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9582 self.select_next_state = entry.select_next_state;
9583 self.select_prev_state = entry.select_prev_state;
9584 self.add_selections_state = entry.add_selections_state;
9585 self.request_autoscroll(Autoscroll::newest(), cx);
9586 }
9587 self.selection_history.mode = SelectionHistoryMode::Normal;
9588 }
9589
9590 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9591 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9592 }
9593
9594 pub fn expand_excerpts_down(
9595 &mut self,
9596 action: &ExpandExcerptsDown,
9597 cx: &mut ViewContext<Self>,
9598 ) {
9599 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9600 }
9601
9602 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9603 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9604 }
9605
9606 pub fn expand_excerpts_for_direction(
9607 &mut self,
9608 lines: u32,
9609 direction: ExpandExcerptDirection,
9610 cx: &mut ViewContext<Self>,
9611 ) {
9612 let selections = self.selections.disjoint_anchors();
9613
9614 let lines = if lines == 0 {
9615 EditorSettings::get_global(cx).expand_excerpt_lines
9616 } else {
9617 lines
9618 };
9619
9620 self.buffer.update(cx, |buffer, cx| {
9621 buffer.expand_excerpts(
9622 selections
9623 .iter()
9624 .map(|selection| selection.head().excerpt_id)
9625 .dedup(),
9626 lines,
9627 direction,
9628 cx,
9629 )
9630 })
9631 }
9632
9633 pub fn expand_excerpt(
9634 &mut self,
9635 excerpt: ExcerptId,
9636 direction: ExpandExcerptDirection,
9637 cx: &mut ViewContext<Self>,
9638 ) {
9639 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9640 self.buffer.update(cx, |buffer, cx| {
9641 buffer.expand_excerpts([excerpt], lines, direction, cx)
9642 })
9643 }
9644
9645 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9646 self.go_to_diagnostic_impl(Direction::Next, cx)
9647 }
9648
9649 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9650 self.go_to_diagnostic_impl(Direction::Prev, cx)
9651 }
9652
9653 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9654 let buffer = self.buffer.read(cx).snapshot(cx);
9655 let selection = self.selections.newest::<usize>(cx);
9656
9657 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9658 if direction == Direction::Next {
9659 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9660 let (group_id, jump_to) = popover.activation_info();
9661 if self.activate_diagnostics(group_id, cx) {
9662 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9663 let mut new_selection = s.newest_anchor().clone();
9664 new_selection.collapse_to(jump_to, SelectionGoal::None);
9665 s.select_anchors(vec![new_selection.clone()]);
9666 });
9667 }
9668 return;
9669 }
9670 }
9671
9672 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9673 active_diagnostics
9674 .primary_range
9675 .to_offset(&buffer)
9676 .to_inclusive()
9677 });
9678 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9679 if active_primary_range.contains(&selection.head()) {
9680 *active_primary_range.start()
9681 } else {
9682 selection.head()
9683 }
9684 } else {
9685 selection.head()
9686 };
9687 let snapshot = self.snapshot(cx);
9688 loop {
9689 let diagnostics = if direction == Direction::Prev {
9690 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9691 } else {
9692 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9693 }
9694 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9695 let group = diagnostics
9696 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9697 // be sorted in a stable way
9698 // skip until we are at current active diagnostic, if it exists
9699 .skip_while(|entry| {
9700 (match direction {
9701 Direction::Prev => entry.range.start >= search_start,
9702 Direction::Next => entry.range.start <= search_start,
9703 }) && self
9704 .active_diagnostics
9705 .as_ref()
9706 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9707 })
9708 .find_map(|entry| {
9709 if entry.diagnostic.is_primary
9710 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9711 && !entry.range.is_empty()
9712 // if we match with the active diagnostic, skip it
9713 && Some(entry.diagnostic.group_id)
9714 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9715 {
9716 Some((entry.range, entry.diagnostic.group_id))
9717 } else {
9718 None
9719 }
9720 });
9721
9722 if let Some((primary_range, group_id)) = group {
9723 if self.activate_diagnostics(group_id, cx) {
9724 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9725 s.select(vec![Selection {
9726 id: selection.id,
9727 start: primary_range.start,
9728 end: primary_range.start,
9729 reversed: false,
9730 goal: SelectionGoal::None,
9731 }]);
9732 });
9733 }
9734 break;
9735 } else {
9736 // Cycle around to the start of the buffer, potentially moving back to the start of
9737 // the currently active diagnostic.
9738 active_primary_range.take();
9739 if direction == Direction::Prev {
9740 if search_start == buffer.len() {
9741 break;
9742 } else {
9743 search_start = buffer.len();
9744 }
9745 } else if search_start == 0 {
9746 break;
9747 } else {
9748 search_start = 0;
9749 }
9750 }
9751 }
9752 }
9753
9754 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9755 let snapshot = self
9756 .display_map
9757 .update(cx, |display_map, cx| display_map.snapshot(cx));
9758 let selection = self.selections.newest::<Point>(cx);
9759 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9760 }
9761
9762 fn go_to_hunk_after_position(
9763 &mut self,
9764 snapshot: &DisplaySnapshot,
9765 position: Point,
9766 cx: &mut ViewContext<'_, Editor>,
9767 ) -> Option<MultiBufferDiffHunk> {
9768 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9769 snapshot,
9770 position,
9771 false,
9772 snapshot
9773 .buffer_snapshot
9774 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9775 cx,
9776 ) {
9777 return Some(hunk);
9778 }
9779
9780 let wrapped_point = Point::zero();
9781 self.go_to_next_hunk_in_direction(
9782 snapshot,
9783 wrapped_point,
9784 true,
9785 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9786 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9787 ),
9788 cx,
9789 )
9790 }
9791
9792 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9793 let snapshot = self
9794 .display_map
9795 .update(cx, |display_map, cx| display_map.snapshot(cx));
9796 let selection = self.selections.newest::<Point>(cx);
9797
9798 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9799 }
9800
9801 fn go_to_hunk_before_position(
9802 &mut self,
9803 snapshot: &DisplaySnapshot,
9804 position: Point,
9805 cx: &mut ViewContext<'_, Editor>,
9806 ) -> Option<MultiBufferDiffHunk> {
9807 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9808 snapshot,
9809 position,
9810 false,
9811 snapshot
9812 .buffer_snapshot
9813 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9814 cx,
9815 ) {
9816 return Some(hunk);
9817 }
9818
9819 let wrapped_point = snapshot.buffer_snapshot.max_point();
9820 self.go_to_next_hunk_in_direction(
9821 snapshot,
9822 wrapped_point,
9823 true,
9824 snapshot
9825 .buffer_snapshot
9826 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9827 cx,
9828 )
9829 }
9830
9831 fn go_to_next_hunk_in_direction(
9832 &mut self,
9833 snapshot: &DisplaySnapshot,
9834 initial_point: Point,
9835 is_wrapped: bool,
9836 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9837 cx: &mut ViewContext<Editor>,
9838 ) -> Option<MultiBufferDiffHunk> {
9839 let display_point = initial_point.to_display_point(snapshot);
9840 let mut hunks = hunks
9841 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9842 .filter(|(display_hunk, _)| {
9843 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9844 })
9845 .dedup();
9846
9847 if let Some((display_hunk, hunk)) = hunks.next() {
9848 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9849 let row = display_hunk.start_display_row();
9850 let point = DisplayPoint::new(row, 0);
9851 s.select_display_ranges([point..point]);
9852 });
9853
9854 Some(hunk)
9855 } else {
9856 None
9857 }
9858 }
9859
9860 pub fn go_to_definition(
9861 &mut self,
9862 _: &GoToDefinition,
9863 cx: &mut ViewContext<Self>,
9864 ) -> Task<Result<Navigated>> {
9865 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9866 cx.spawn(|editor, mut cx| async move {
9867 if definition.await? == Navigated::Yes {
9868 return Ok(Navigated::Yes);
9869 }
9870 match editor.update(&mut cx, |editor, cx| {
9871 editor.find_all_references(&FindAllReferences, cx)
9872 })? {
9873 Some(references) => references.await,
9874 None => Ok(Navigated::No),
9875 }
9876 })
9877 }
9878
9879 pub fn go_to_declaration(
9880 &mut self,
9881 _: &GoToDeclaration,
9882 cx: &mut ViewContext<Self>,
9883 ) -> Task<Result<Navigated>> {
9884 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9885 }
9886
9887 pub fn go_to_declaration_split(
9888 &mut self,
9889 _: &GoToDeclaration,
9890 cx: &mut ViewContext<Self>,
9891 ) -> Task<Result<Navigated>> {
9892 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9893 }
9894
9895 pub fn go_to_implementation(
9896 &mut self,
9897 _: &GoToImplementation,
9898 cx: &mut ViewContext<Self>,
9899 ) -> Task<Result<Navigated>> {
9900 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9901 }
9902
9903 pub fn go_to_implementation_split(
9904 &mut self,
9905 _: &GoToImplementationSplit,
9906 cx: &mut ViewContext<Self>,
9907 ) -> Task<Result<Navigated>> {
9908 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9909 }
9910
9911 pub fn go_to_type_definition(
9912 &mut self,
9913 _: &GoToTypeDefinition,
9914 cx: &mut ViewContext<Self>,
9915 ) -> Task<Result<Navigated>> {
9916 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9917 }
9918
9919 pub fn go_to_definition_split(
9920 &mut self,
9921 _: &GoToDefinitionSplit,
9922 cx: &mut ViewContext<Self>,
9923 ) -> Task<Result<Navigated>> {
9924 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9925 }
9926
9927 pub fn go_to_type_definition_split(
9928 &mut self,
9929 _: &GoToTypeDefinitionSplit,
9930 cx: &mut ViewContext<Self>,
9931 ) -> Task<Result<Navigated>> {
9932 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9933 }
9934
9935 fn go_to_definition_of_kind(
9936 &mut self,
9937 kind: GotoDefinitionKind,
9938 split: bool,
9939 cx: &mut ViewContext<Self>,
9940 ) -> Task<Result<Navigated>> {
9941 let Some(provider) = self.semantics_provider.clone() else {
9942 return Task::ready(Ok(Navigated::No));
9943 };
9944 let head = self.selections.newest::<usize>(cx).head();
9945 let buffer = self.buffer.read(cx);
9946 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9947 text_anchor
9948 } else {
9949 return Task::ready(Ok(Navigated::No));
9950 };
9951
9952 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9953 return Task::ready(Ok(Navigated::No));
9954 };
9955
9956 cx.spawn(|editor, mut cx| async move {
9957 let definitions = definitions.await?;
9958 let navigated = editor
9959 .update(&mut cx, |editor, cx| {
9960 editor.navigate_to_hover_links(
9961 Some(kind),
9962 definitions
9963 .into_iter()
9964 .filter(|location| {
9965 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9966 })
9967 .map(HoverLink::Text)
9968 .collect::<Vec<_>>(),
9969 split,
9970 cx,
9971 )
9972 })?
9973 .await?;
9974 anyhow::Ok(navigated)
9975 })
9976 }
9977
9978 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9979 let position = self.selections.newest_anchor().head();
9980 let Some((buffer, buffer_position)) =
9981 self.buffer.read(cx).text_anchor_for_position(position, cx)
9982 else {
9983 return;
9984 };
9985
9986 cx.spawn(|editor, mut cx| async move {
9987 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9988 editor.update(&mut cx, |_, cx| {
9989 cx.open_url(&url);
9990 })
9991 } else {
9992 Ok(())
9993 }
9994 })
9995 .detach();
9996 }
9997
9998 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9999 let Some(workspace) = self.workspace() else {
10000 return;
10001 };
10002
10003 let position = self.selections.newest_anchor().head();
10004
10005 let Some((buffer, buffer_position)) =
10006 self.buffer.read(cx).text_anchor_for_position(position, cx)
10007 else {
10008 return;
10009 };
10010
10011 let project = self.project.clone();
10012
10013 cx.spawn(|_, mut cx| async move {
10014 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10015
10016 if let Some((_, path)) = result {
10017 workspace
10018 .update(&mut cx, |workspace, cx| {
10019 workspace.open_resolved_path(path, cx)
10020 })?
10021 .await?;
10022 }
10023 anyhow::Ok(())
10024 })
10025 .detach();
10026 }
10027
10028 pub(crate) fn navigate_to_hover_links(
10029 &mut self,
10030 kind: Option<GotoDefinitionKind>,
10031 mut definitions: Vec<HoverLink>,
10032 split: bool,
10033 cx: &mut ViewContext<Editor>,
10034 ) -> Task<Result<Navigated>> {
10035 // If there is one definition, just open it directly
10036 if definitions.len() == 1 {
10037 let definition = definitions.pop().unwrap();
10038
10039 enum TargetTaskResult {
10040 Location(Option<Location>),
10041 AlreadyNavigated,
10042 }
10043
10044 let target_task = match definition {
10045 HoverLink::Text(link) => {
10046 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10047 }
10048 HoverLink::InlayHint(lsp_location, server_id) => {
10049 let computation = self.compute_target_location(lsp_location, server_id, cx);
10050 cx.background_executor().spawn(async move {
10051 let location = computation.await?;
10052 Ok(TargetTaskResult::Location(location))
10053 })
10054 }
10055 HoverLink::Url(url) => {
10056 cx.open_url(&url);
10057 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10058 }
10059 HoverLink::File(path) => {
10060 if let Some(workspace) = self.workspace() {
10061 cx.spawn(|_, mut cx| async move {
10062 workspace
10063 .update(&mut cx, |workspace, cx| {
10064 workspace.open_resolved_path(path, cx)
10065 })?
10066 .await
10067 .map(|_| TargetTaskResult::AlreadyNavigated)
10068 })
10069 } else {
10070 Task::ready(Ok(TargetTaskResult::Location(None)))
10071 }
10072 }
10073 };
10074 cx.spawn(|editor, mut cx| async move {
10075 let target = match target_task.await.context("target resolution task")? {
10076 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10077 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10078 TargetTaskResult::Location(Some(target)) => target,
10079 };
10080
10081 editor.update(&mut cx, |editor, cx| {
10082 let Some(workspace) = editor.workspace() else {
10083 return Navigated::No;
10084 };
10085 let pane = workspace.read(cx).active_pane().clone();
10086
10087 let range = target.range.to_offset(target.buffer.read(cx));
10088 let range = editor.range_for_match(&range);
10089
10090 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10091 let buffer = target.buffer.read(cx);
10092 let range = check_multiline_range(buffer, range);
10093 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10094 s.select_ranges([range]);
10095 });
10096 } else {
10097 cx.window_context().defer(move |cx| {
10098 let target_editor: View<Self> =
10099 workspace.update(cx, |workspace, cx| {
10100 let pane = if split {
10101 workspace.adjacent_pane(cx)
10102 } else {
10103 workspace.active_pane().clone()
10104 };
10105
10106 workspace.open_project_item(
10107 pane,
10108 target.buffer.clone(),
10109 true,
10110 true,
10111 cx,
10112 )
10113 });
10114 target_editor.update(cx, |target_editor, cx| {
10115 // When selecting a definition in a different buffer, disable the nav history
10116 // to avoid creating a history entry at the previous cursor location.
10117 pane.update(cx, |pane, _| pane.disable_history());
10118 let buffer = target.buffer.read(cx);
10119 let range = check_multiline_range(buffer, range);
10120 target_editor.change_selections(
10121 Some(Autoscroll::focused()),
10122 cx,
10123 |s| {
10124 s.select_ranges([range]);
10125 },
10126 );
10127 pane.update(cx, |pane, _| pane.enable_history());
10128 });
10129 });
10130 }
10131 Navigated::Yes
10132 })
10133 })
10134 } else if !definitions.is_empty() {
10135 cx.spawn(|editor, mut cx| async move {
10136 let (title, location_tasks, workspace) = editor
10137 .update(&mut cx, |editor, cx| {
10138 let tab_kind = match kind {
10139 Some(GotoDefinitionKind::Implementation) => "Implementations",
10140 _ => "Definitions",
10141 };
10142 let title = definitions
10143 .iter()
10144 .find_map(|definition| match definition {
10145 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10146 let buffer = origin.buffer.read(cx);
10147 format!(
10148 "{} for {}",
10149 tab_kind,
10150 buffer
10151 .text_for_range(origin.range.clone())
10152 .collect::<String>()
10153 )
10154 }),
10155 HoverLink::InlayHint(_, _) => None,
10156 HoverLink::Url(_) => None,
10157 HoverLink::File(_) => None,
10158 })
10159 .unwrap_or(tab_kind.to_string());
10160 let location_tasks = definitions
10161 .into_iter()
10162 .map(|definition| match definition {
10163 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10164 HoverLink::InlayHint(lsp_location, server_id) => {
10165 editor.compute_target_location(lsp_location, server_id, cx)
10166 }
10167 HoverLink::Url(_) => Task::ready(Ok(None)),
10168 HoverLink::File(_) => Task::ready(Ok(None)),
10169 })
10170 .collect::<Vec<_>>();
10171 (title, location_tasks, editor.workspace().clone())
10172 })
10173 .context("location tasks preparation")?;
10174
10175 let locations = future::join_all(location_tasks)
10176 .await
10177 .into_iter()
10178 .filter_map(|location| location.transpose())
10179 .collect::<Result<_>>()
10180 .context("location tasks")?;
10181
10182 let Some(workspace) = workspace else {
10183 return Ok(Navigated::No);
10184 };
10185 let opened = workspace
10186 .update(&mut cx, |workspace, cx| {
10187 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10188 })
10189 .ok();
10190
10191 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10192 })
10193 } else {
10194 Task::ready(Ok(Navigated::No))
10195 }
10196 }
10197
10198 fn compute_target_location(
10199 &self,
10200 lsp_location: lsp::Location,
10201 server_id: LanguageServerId,
10202 cx: &mut ViewContext<Self>,
10203 ) -> Task<anyhow::Result<Option<Location>>> {
10204 let Some(project) = self.project.clone() else {
10205 return Task::Ready(Some(Ok(None)));
10206 };
10207
10208 cx.spawn(move |editor, mut cx| async move {
10209 let location_task = editor.update(&mut cx, |_, cx| {
10210 project.update(cx, |project, cx| {
10211 let language_server_name = project
10212 .language_server_statuses(cx)
10213 .find(|(id, _)| server_id == *id)
10214 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10215 language_server_name.map(|language_server_name| {
10216 project.open_local_buffer_via_lsp(
10217 lsp_location.uri.clone(),
10218 server_id,
10219 language_server_name,
10220 cx,
10221 )
10222 })
10223 })
10224 })?;
10225 let location = match location_task {
10226 Some(task) => Some({
10227 let target_buffer_handle = task.await.context("open local buffer")?;
10228 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10229 let target_start = target_buffer
10230 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10231 let target_end = target_buffer
10232 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10233 target_buffer.anchor_after(target_start)
10234 ..target_buffer.anchor_before(target_end)
10235 })?;
10236 Location {
10237 buffer: target_buffer_handle,
10238 range,
10239 }
10240 }),
10241 None => None,
10242 };
10243 Ok(location)
10244 })
10245 }
10246
10247 pub fn find_all_references(
10248 &mut self,
10249 _: &FindAllReferences,
10250 cx: &mut ViewContext<Self>,
10251 ) -> Option<Task<Result<Navigated>>> {
10252 let selection = self.selections.newest::<usize>(cx);
10253 let multi_buffer = self.buffer.read(cx);
10254 let head = selection.head();
10255
10256 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10257 let head_anchor = multi_buffer_snapshot.anchor_at(
10258 head,
10259 if head < selection.tail() {
10260 Bias::Right
10261 } else {
10262 Bias::Left
10263 },
10264 );
10265
10266 match self
10267 .find_all_references_task_sources
10268 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10269 {
10270 Ok(_) => {
10271 log::info!(
10272 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10273 );
10274 return None;
10275 }
10276 Err(i) => {
10277 self.find_all_references_task_sources.insert(i, head_anchor);
10278 }
10279 }
10280
10281 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10282 let workspace = self.workspace()?;
10283 let project = workspace.read(cx).project().clone();
10284 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10285 Some(cx.spawn(|editor, mut cx| async move {
10286 let _cleanup = defer({
10287 let mut cx = cx.clone();
10288 move || {
10289 let _ = editor.update(&mut cx, |editor, _| {
10290 if let Ok(i) =
10291 editor
10292 .find_all_references_task_sources
10293 .binary_search_by(|anchor| {
10294 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10295 })
10296 {
10297 editor.find_all_references_task_sources.remove(i);
10298 }
10299 });
10300 }
10301 });
10302
10303 let locations = references.await?;
10304 if locations.is_empty() {
10305 return anyhow::Ok(Navigated::No);
10306 }
10307
10308 workspace.update(&mut cx, |workspace, cx| {
10309 let title = locations
10310 .first()
10311 .as_ref()
10312 .map(|location| {
10313 let buffer = location.buffer.read(cx);
10314 format!(
10315 "References to `{}`",
10316 buffer
10317 .text_for_range(location.range.clone())
10318 .collect::<String>()
10319 )
10320 })
10321 .unwrap();
10322 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10323 Navigated::Yes
10324 })
10325 }))
10326 }
10327
10328 /// Opens a multibuffer with the given project locations in it
10329 pub fn open_locations_in_multibuffer(
10330 workspace: &mut Workspace,
10331 mut locations: Vec<Location>,
10332 title: String,
10333 split: bool,
10334 cx: &mut ViewContext<Workspace>,
10335 ) {
10336 // If there are multiple definitions, open them in a multibuffer
10337 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10338 let mut locations = locations.into_iter().peekable();
10339 let mut ranges_to_highlight = Vec::new();
10340 let capability = workspace.project().read(cx).capability();
10341
10342 let excerpt_buffer = cx.new_model(|cx| {
10343 let mut multibuffer = MultiBuffer::new(capability);
10344 while let Some(location) = locations.next() {
10345 let buffer = location.buffer.read(cx);
10346 let mut ranges_for_buffer = Vec::new();
10347 let range = location.range.to_offset(buffer);
10348 ranges_for_buffer.push(range.clone());
10349
10350 while let Some(next_location) = locations.peek() {
10351 if next_location.buffer == location.buffer {
10352 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10353 locations.next();
10354 } else {
10355 break;
10356 }
10357 }
10358
10359 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10360 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10361 location.buffer.clone(),
10362 ranges_for_buffer,
10363 DEFAULT_MULTIBUFFER_CONTEXT,
10364 cx,
10365 ))
10366 }
10367
10368 multibuffer.with_title(title)
10369 });
10370
10371 let editor = cx.new_view(|cx| {
10372 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10373 });
10374 editor.update(cx, |editor, cx| {
10375 if let Some(first_range) = ranges_to_highlight.first() {
10376 editor.change_selections(None, cx, |selections| {
10377 selections.clear_disjoint();
10378 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10379 });
10380 }
10381 editor.highlight_background::<Self>(
10382 &ranges_to_highlight,
10383 |theme| theme.editor_highlighted_line_background,
10384 cx,
10385 );
10386 });
10387
10388 let item = Box::new(editor);
10389 let item_id = item.item_id();
10390
10391 if split {
10392 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10393 } else {
10394 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10395 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10396 pane.close_current_preview_item(cx)
10397 } else {
10398 None
10399 }
10400 });
10401 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10402 }
10403 workspace.active_pane().update(cx, |pane, cx| {
10404 pane.set_preview_item_id(Some(item_id), cx);
10405 });
10406 }
10407
10408 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10409 use language::ToOffset as _;
10410
10411 let provider = self.semantics_provider.clone()?;
10412 let selection = self.selections.newest_anchor().clone();
10413 let (cursor_buffer, cursor_buffer_position) = self
10414 .buffer
10415 .read(cx)
10416 .text_anchor_for_position(selection.head(), cx)?;
10417 let (tail_buffer, cursor_buffer_position_end) = self
10418 .buffer
10419 .read(cx)
10420 .text_anchor_for_position(selection.tail(), cx)?;
10421 if tail_buffer != cursor_buffer {
10422 return None;
10423 }
10424
10425 let snapshot = cursor_buffer.read(cx).snapshot();
10426 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10427 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10428 let prepare_rename = provider
10429 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10430 .unwrap_or_else(|| Task::ready(Ok(None)));
10431 drop(snapshot);
10432
10433 Some(cx.spawn(|this, mut cx| async move {
10434 let rename_range = if let Some(range) = prepare_rename.await? {
10435 Some(range)
10436 } else {
10437 this.update(&mut cx, |this, cx| {
10438 let buffer = this.buffer.read(cx).snapshot(cx);
10439 let mut buffer_highlights = this
10440 .document_highlights_for_position(selection.head(), &buffer)
10441 .filter(|highlight| {
10442 highlight.start.excerpt_id == selection.head().excerpt_id
10443 && highlight.end.excerpt_id == selection.head().excerpt_id
10444 });
10445 buffer_highlights
10446 .next()
10447 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10448 })?
10449 };
10450 if let Some(rename_range) = rename_range {
10451 this.update(&mut cx, |this, cx| {
10452 let snapshot = cursor_buffer.read(cx).snapshot();
10453 let rename_buffer_range = rename_range.to_offset(&snapshot);
10454 let cursor_offset_in_rename_range =
10455 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10456 let cursor_offset_in_rename_range_end =
10457 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10458
10459 this.take_rename(false, cx);
10460 let buffer = this.buffer.read(cx).read(cx);
10461 let cursor_offset = selection.head().to_offset(&buffer);
10462 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10463 let rename_end = rename_start + rename_buffer_range.len();
10464 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10465 let mut old_highlight_id = None;
10466 let old_name: Arc<str> = buffer
10467 .chunks(rename_start..rename_end, true)
10468 .map(|chunk| {
10469 if old_highlight_id.is_none() {
10470 old_highlight_id = chunk.syntax_highlight_id;
10471 }
10472 chunk.text
10473 })
10474 .collect::<String>()
10475 .into();
10476
10477 drop(buffer);
10478
10479 // Position the selection in the rename editor so that it matches the current selection.
10480 this.show_local_selections = false;
10481 let rename_editor = cx.new_view(|cx| {
10482 let mut editor = Editor::single_line(cx);
10483 editor.buffer.update(cx, |buffer, cx| {
10484 buffer.edit([(0..0, old_name.clone())], None, cx)
10485 });
10486 let rename_selection_range = match cursor_offset_in_rename_range
10487 .cmp(&cursor_offset_in_rename_range_end)
10488 {
10489 Ordering::Equal => {
10490 editor.select_all(&SelectAll, cx);
10491 return editor;
10492 }
10493 Ordering::Less => {
10494 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10495 }
10496 Ordering::Greater => {
10497 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10498 }
10499 };
10500 if rename_selection_range.end > old_name.len() {
10501 editor.select_all(&SelectAll, cx);
10502 } else {
10503 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10504 s.select_ranges([rename_selection_range]);
10505 });
10506 }
10507 editor
10508 });
10509 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10510 if e == &EditorEvent::Focused {
10511 cx.emit(EditorEvent::FocusedIn)
10512 }
10513 })
10514 .detach();
10515
10516 let write_highlights =
10517 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10518 let read_highlights =
10519 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10520 let ranges = write_highlights
10521 .iter()
10522 .flat_map(|(_, ranges)| ranges.iter())
10523 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10524 .cloned()
10525 .collect();
10526
10527 this.highlight_text::<Rename>(
10528 ranges,
10529 HighlightStyle {
10530 fade_out: Some(0.6),
10531 ..Default::default()
10532 },
10533 cx,
10534 );
10535 let rename_focus_handle = rename_editor.focus_handle(cx);
10536 cx.focus(&rename_focus_handle);
10537 let block_id = this.insert_blocks(
10538 [BlockProperties {
10539 style: BlockStyle::Flex,
10540 placement: BlockPlacement::Below(range.start),
10541 height: 1,
10542 render: Arc::new({
10543 let rename_editor = rename_editor.clone();
10544 move |cx: &mut BlockContext| {
10545 let mut text_style = cx.editor_style.text.clone();
10546 if let Some(highlight_style) = old_highlight_id
10547 .and_then(|h| h.style(&cx.editor_style.syntax))
10548 {
10549 text_style = text_style.highlight(highlight_style);
10550 }
10551 div()
10552 .block_mouse_down()
10553 .pl(cx.anchor_x)
10554 .child(EditorElement::new(
10555 &rename_editor,
10556 EditorStyle {
10557 background: cx.theme().system().transparent,
10558 local_player: cx.editor_style.local_player,
10559 text: text_style,
10560 scrollbar_width: cx.editor_style.scrollbar_width,
10561 syntax: cx.editor_style.syntax.clone(),
10562 status: cx.editor_style.status.clone(),
10563 inlay_hints_style: HighlightStyle {
10564 font_weight: Some(FontWeight::BOLD),
10565 ..make_inlay_hints_style(cx)
10566 },
10567 suggestions_style: HighlightStyle {
10568 color: Some(cx.theme().status().predictive),
10569 ..HighlightStyle::default()
10570 },
10571 ..EditorStyle::default()
10572 },
10573 ))
10574 .into_any_element()
10575 }
10576 }),
10577 priority: 0,
10578 }],
10579 Some(Autoscroll::fit()),
10580 cx,
10581 )[0];
10582 this.pending_rename = Some(RenameState {
10583 range,
10584 old_name,
10585 editor: rename_editor,
10586 block_id,
10587 });
10588 })?;
10589 }
10590
10591 Ok(())
10592 }))
10593 }
10594
10595 pub fn confirm_rename(
10596 &mut self,
10597 _: &ConfirmRename,
10598 cx: &mut ViewContext<Self>,
10599 ) -> Option<Task<Result<()>>> {
10600 let rename = self.take_rename(false, cx)?;
10601 let workspace = self.workspace()?.downgrade();
10602 let (buffer, start) = self
10603 .buffer
10604 .read(cx)
10605 .text_anchor_for_position(rename.range.start, cx)?;
10606 let (end_buffer, _) = self
10607 .buffer
10608 .read(cx)
10609 .text_anchor_for_position(rename.range.end, cx)?;
10610 if buffer != end_buffer {
10611 return None;
10612 }
10613
10614 let old_name = rename.old_name;
10615 let new_name = rename.editor.read(cx).text(cx);
10616
10617 let rename = self.semantics_provider.as_ref()?.perform_rename(
10618 &buffer,
10619 start,
10620 new_name.clone(),
10621 cx,
10622 )?;
10623
10624 Some(cx.spawn(|editor, mut cx| async move {
10625 let project_transaction = rename.await?;
10626 Self::open_project_transaction(
10627 &editor,
10628 workspace,
10629 project_transaction,
10630 format!("Rename: {} → {}", old_name, new_name),
10631 cx.clone(),
10632 )
10633 .await?;
10634
10635 editor.update(&mut cx, |editor, cx| {
10636 editor.refresh_document_highlights(cx);
10637 })?;
10638 Ok(())
10639 }))
10640 }
10641
10642 fn take_rename(
10643 &mut self,
10644 moving_cursor: bool,
10645 cx: &mut ViewContext<Self>,
10646 ) -> Option<RenameState> {
10647 let rename = self.pending_rename.take()?;
10648 if rename.editor.focus_handle(cx).is_focused(cx) {
10649 cx.focus(&self.focus_handle);
10650 }
10651
10652 self.remove_blocks(
10653 [rename.block_id].into_iter().collect(),
10654 Some(Autoscroll::fit()),
10655 cx,
10656 );
10657 self.clear_highlights::<Rename>(cx);
10658 self.show_local_selections = true;
10659
10660 if moving_cursor {
10661 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10662 editor.selections.newest::<usize>(cx).head()
10663 });
10664
10665 // Update the selection to match the position of the selection inside
10666 // the rename editor.
10667 let snapshot = self.buffer.read(cx).read(cx);
10668 let rename_range = rename.range.to_offset(&snapshot);
10669 let cursor_in_editor = snapshot
10670 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10671 .min(rename_range.end);
10672 drop(snapshot);
10673
10674 self.change_selections(None, cx, |s| {
10675 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10676 });
10677 } else {
10678 self.refresh_document_highlights(cx);
10679 }
10680
10681 Some(rename)
10682 }
10683
10684 pub fn pending_rename(&self) -> Option<&RenameState> {
10685 self.pending_rename.as_ref()
10686 }
10687
10688 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10689 let project = match &self.project {
10690 Some(project) => project.clone(),
10691 None => return None,
10692 };
10693
10694 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10695 }
10696
10697 fn format_selections(
10698 &mut self,
10699 _: &FormatSelections,
10700 cx: &mut ViewContext<Self>,
10701 ) -> Option<Task<Result<()>>> {
10702 let project = match &self.project {
10703 Some(project) => project.clone(),
10704 None => return None,
10705 };
10706
10707 let selections = self
10708 .selections
10709 .all_adjusted(cx)
10710 .into_iter()
10711 .filter(|s| !s.is_empty())
10712 .collect_vec();
10713
10714 Some(self.perform_format(
10715 project,
10716 FormatTrigger::Manual,
10717 FormatTarget::Ranges(selections),
10718 cx,
10719 ))
10720 }
10721
10722 fn perform_format(
10723 &mut self,
10724 project: Model<Project>,
10725 trigger: FormatTrigger,
10726 target: FormatTarget,
10727 cx: &mut ViewContext<Self>,
10728 ) -> Task<Result<()>> {
10729 let buffer = self.buffer().clone();
10730 let mut buffers = buffer.read(cx).all_buffers();
10731 if trigger == FormatTrigger::Save {
10732 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10733 }
10734
10735 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10736 let format = project.update(cx, |project, cx| {
10737 project.format(buffers, true, trigger, target, cx)
10738 });
10739
10740 cx.spawn(|_, mut cx| async move {
10741 let transaction = futures::select_biased! {
10742 () = timeout => {
10743 log::warn!("timed out waiting for formatting");
10744 None
10745 }
10746 transaction = format.log_err().fuse() => transaction,
10747 };
10748
10749 buffer
10750 .update(&mut cx, |buffer, cx| {
10751 if let Some(transaction) = transaction {
10752 if !buffer.is_singleton() {
10753 buffer.push_transaction(&transaction.0, cx);
10754 }
10755 }
10756
10757 cx.notify();
10758 })
10759 .ok();
10760
10761 Ok(())
10762 })
10763 }
10764
10765 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10766 if let Some(project) = self.project.clone() {
10767 self.buffer.update(cx, |multi_buffer, cx| {
10768 project.update(cx, |project, cx| {
10769 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10770 });
10771 })
10772 }
10773 }
10774
10775 fn cancel_language_server_work(
10776 &mut self,
10777 _: &actions::CancelLanguageServerWork,
10778 cx: &mut ViewContext<Self>,
10779 ) {
10780 if let Some(project) = self.project.clone() {
10781 self.buffer.update(cx, |multi_buffer, cx| {
10782 project.update(cx, |project, cx| {
10783 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10784 });
10785 })
10786 }
10787 }
10788
10789 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10790 cx.show_character_palette();
10791 }
10792
10793 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10794 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10795 let buffer = self.buffer.read(cx).snapshot(cx);
10796 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10797 let is_valid = buffer
10798 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10799 .any(|entry| {
10800 entry.diagnostic.is_primary
10801 && !entry.range.is_empty()
10802 && entry.range.start == primary_range_start
10803 && entry.diagnostic.message == active_diagnostics.primary_message
10804 });
10805
10806 if is_valid != active_diagnostics.is_valid {
10807 active_diagnostics.is_valid = is_valid;
10808 let mut new_styles = HashMap::default();
10809 for (block_id, diagnostic) in &active_diagnostics.blocks {
10810 new_styles.insert(
10811 *block_id,
10812 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10813 );
10814 }
10815 self.display_map.update(cx, |display_map, _cx| {
10816 display_map.replace_blocks(new_styles)
10817 });
10818 }
10819 }
10820 }
10821
10822 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10823 self.dismiss_diagnostics(cx);
10824 let snapshot = self.snapshot(cx);
10825 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10826 let buffer = self.buffer.read(cx).snapshot(cx);
10827
10828 let mut primary_range = None;
10829 let mut primary_message = None;
10830 let mut group_end = Point::zero();
10831 let diagnostic_group = buffer
10832 .diagnostic_group::<MultiBufferPoint>(group_id)
10833 .filter_map(|entry| {
10834 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10835 && (entry.range.start.row == entry.range.end.row
10836 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10837 {
10838 return None;
10839 }
10840 if entry.range.end > group_end {
10841 group_end = entry.range.end;
10842 }
10843 if entry.diagnostic.is_primary {
10844 primary_range = Some(entry.range.clone());
10845 primary_message = Some(entry.diagnostic.message.clone());
10846 }
10847 Some(entry)
10848 })
10849 .collect::<Vec<_>>();
10850 let primary_range = primary_range?;
10851 let primary_message = primary_message?;
10852 let primary_range =
10853 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10854
10855 let blocks = display_map
10856 .insert_blocks(
10857 diagnostic_group.iter().map(|entry| {
10858 let diagnostic = entry.diagnostic.clone();
10859 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10860 BlockProperties {
10861 style: BlockStyle::Fixed,
10862 placement: BlockPlacement::Below(
10863 buffer.anchor_after(entry.range.start),
10864 ),
10865 height: message_height,
10866 render: diagnostic_block_renderer(diagnostic, None, true, true),
10867 priority: 0,
10868 }
10869 }),
10870 cx,
10871 )
10872 .into_iter()
10873 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10874 .collect();
10875
10876 Some(ActiveDiagnosticGroup {
10877 primary_range,
10878 primary_message,
10879 group_id,
10880 blocks,
10881 is_valid: true,
10882 })
10883 });
10884 self.active_diagnostics.is_some()
10885 }
10886
10887 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10888 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10889 self.display_map.update(cx, |display_map, cx| {
10890 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10891 });
10892 cx.notify();
10893 }
10894 }
10895
10896 pub fn set_selections_from_remote(
10897 &mut self,
10898 selections: Vec<Selection<Anchor>>,
10899 pending_selection: Option<Selection<Anchor>>,
10900 cx: &mut ViewContext<Self>,
10901 ) {
10902 let old_cursor_position = self.selections.newest_anchor().head();
10903 self.selections.change_with(cx, |s| {
10904 s.select_anchors(selections);
10905 if let Some(pending_selection) = pending_selection {
10906 s.set_pending(pending_selection, SelectMode::Character);
10907 } else {
10908 s.clear_pending();
10909 }
10910 });
10911 self.selections_did_change(false, &old_cursor_position, true, cx);
10912 }
10913
10914 fn push_to_selection_history(&mut self) {
10915 self.selection_history.push(SelectionHistoryEntry {
10916 selections: self.selections.disjoint_anchors(),
10917 select_next_state: self.select_next_state.clone(),
10918 select_prev_state: self.select_prev_state.clone(),
10919 add_selections_state: self.add_selections_state.clone(),
10920 });
10921 }
10922
10923 pub fn transact(
10924 &mut self,
10925 cx: &mut ViewContext<Self>,
10926 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10927 ) -> Option<TransactionId> {
10928 self.start_transaction_at(Instant::now(), cx);
10929 update(self, cx);
10930 self.end_transaction_at(Instant::now(), cx)
10931 }
10932
10933 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10934 self.end_selection(cx);
10935 if let Some(tx_id) = self
10936 .buffer
10937 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10938 {
10939 self.selection_history
10940 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10941 cx.emit(EditorEvent::TransactionBegun {
10942 transaction_id: tx_id,
10943 })
10944 }
10945 }
10946
10947 fn end_transaction_at(
10948 &mut self,
10949 now: Instant,
10950 cx: &mut ViewContext<Self>,
10951 ) -> Option<TransactionId> {
10952 if let Some(transaction_id) = self
10953 .buffer
10954 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10955 {
10956 if let Some((_, end_selections)) =
10957 self.selection_history.transaction_mut(transaction_id)
10958 {
10959 *end_selections = Some(self.selections.disjoint_anchors());
10960 } else {
10961 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10962 }
10963
10964 cx.emit(EditorEvent::Edited { transaction_id });
10965 Some(transaction_id)
10966 } else {
10967 None
10968 }
10969 }
10970
10971 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10972 let selection = self.selections.newest::<Point>(cx);
10973
10974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10975 let range = if selection.is_empty() {
10976 let point = selection.head().to_display_point(&display_map);
10977 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10978 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10979 .to_point(&display_map);
10980 start..end
10981 } else {
10982 selection.range()
10983 };
10984 if display_map.folds_in_range(range).next().is_some() {
10985 self.unfold_lines(&Default::default(), cx)
10986 } else {
10987 self.fold(&Default::default(), cx)
10988 }
10989 }
10990
10991 pub fn toggle_fold_recursive(
10992 &mut self,
10993 _: &actions::ToggleFoldRecursive,
10994 cx: &mut ViewContext<Self>,
10995 ) {
10996 let selection = self.selections.newest::<Point>(cx);
10997
10998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10999 let range = if selection.is_empty() {
11000 let point = selection.head().to_display_point(&display_map);
11001 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11002 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11003 .to_point(&display_map);
11004 start..end
11005 } else {
11006 selection.range()
11007 };
11008 if display_map.folds_in_range(range).next().is_some() {
11009 self.unfold_recursive(&Default::default(), cx)
11010 } else {
11011 self.fold_recursive(&Default::default(), cx)
11012 }
11013 }
11014
11015 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11016 let mut to_fold = Vec::new();
11017 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11018 let selections = self.selections.all_adjusted(cx);
11019
11020 for selection in selections {
11021 let range = selection.range().sorted();
11022 let buffer_start_row = range.start.row;
11023
11024 if range.start.row != range.end.row {
11025 let mut found = false;
11026 let mut row = range.start.row;
11027 while row <= range.end.row {
11028 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11029 found = true;
11030 row = crease.range().end.row + 1;
11031 to_fold.push(crease);
11032 } else {
11033 row += 1
11034 }
11035 }
11036 if found {
11037 continue;
11038 }
11039 }
11040
11041 for row in (0..=range.start.row).rev() {
11042 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11043 if crease.range().end.row >= buffer_start_row {
11044 to_fold.push(crease);
11045 if row <= range.start.row {
11046 break;
11047 }
11048 }
11049 }
11050 }
11051 }
11052
11053 self.fold_creases(to_fold, true, cx);
11054 }
11055
11056 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11057 if !self.buffer.read(cx).is_singleton() {
11058 return;
11059 }
11060
11061 let fold_at_level = fold_at.level;
11062 let snapshot = self.buffer.read(cx).snapshot(cx);
11063 let mut to_fold = Vec::new();
11064 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11065
11066 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11067 while start_row < end_row {
11068 match self
11069 .snapshot(cx)
11070 .crease_for_buffer_row(MultiBufferRow(start_row))
11071 {
11072 Some(crease) => {
11073 let nested_start_row = crease.range().start.row + 1;
11074 let nested_end_row = crease.range().end.row;
11075
11076 if current_level < fold_at_level {
11077 stack.push((nested_start_row, nested_end_row, current_level + 1));
11078 } else if current_level == fold_at_level {
11079 to_fold.push(crease);
11080 }
11081
11082 start_row = nested_end_row + 1;
11083 }
11084 None => start_row += 1,
11085 }
11086 }
11087 }
11088
11089 self.fold_creases(to_fold, true, cx);
11090 }
11091
11092 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11093 if !self.buffer.read(cx).is_singleton() {
11094 return;
11095 }
11096
11097 let mut fold_ranges = Vec::new();
11098 let snapshot = self.buffer.read(cx).snapshot(cx);
11099
11100 for row in 0..snapshot.max_row().0 {
11101 if let Some(foldable_range) =
11102 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11103 {
11104 fold_ranges.push(foldable_range);
11105 }
11106 }
11107
11108 self.fold_creases(fold_ranges, true, cx);
11109 }
11110
11111 pub fn fold_function_bodies(
11112 &mut self,
11113 _: &actions::FoldFunctionBodies,
11114 cx: &mut ViewContext<Self>,
11115 ) {
11116 let snapshot = self.buffer.read(cx).snapshot(cx);
11117 let Some((_, _, buffer)) = snapshot.as_singleton() else {
11118 return;
11119 };
11120 let creases = buffer
11121 .function_body_fold_ranges(0..buffer.len())
11122 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11123 .collect();
11124
11125 self.fold_creases(creases, true, cx);
11126 }
11127
11128 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11129 let mut to_fold = Vec::new();
11130 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11131 let selections = self.selections.all_adjusted(cx);
11132
11133 for selection in selections {
11134 let range = selection.range().sorted();
11135 let buffer_start_row = range.start.row;
11136
11137 if range.start.row != range.end.row {
11138 let mut found = false;
11139 for row in range.start.row..=range.end.row {
11140 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11141 found = true;
11142 to_fold.push(crease);
11143 }
11144 }
11145 if found {
11146 continue;
11147 }
11148 }
11149
11150 for row in (0..=range.start.row).rev() {
11151 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11152 if crease.range().end.row >= buffer_start_row {
11153 to_fold.push(crease);
11154 } else {
11155 break;
11156 }
11157 }
11158 }
11159 }
11160
11161 self.fold_creases(to_fold, true, cx);
11162 }
11163
11164 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11165 let buffer_row = fold_at.buffer_row;
11166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11167
11168 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11169 let autoscroll = self
11170 .selections
11171 .all::<Point>(cx)
11172 .iter()
11173 .any(|selection| crease.range().overlaps(&selection.range()));
11174
11175 self.fold_creases(vec![crease], autoscroll, cx);
11176 }
11177 }
11178
11179 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11180 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11181 let buffer = &display_map.buffer_snapshot;
11182 let selections = self.selections.all::<Point>(cx);
11183 let ranges = selections
11184 .iter()
11185 .map(|s| {
11186 let range = s.display_range(&display_map).sorted();
11187 let mut start = range.start.to_point(&display_map);
11188 let mut end = range.end.to_point(&display_map);
11189 start.column = 0;
11190 end.column = buffer.line_len(MultiBufferRow(end.row));
11191 start..end
11192 })
11193 .collect::<Vec<_>>();
11194
11195 self.unfold_ranges(&ranges, true, true, cx);
11196 }
11197
11198 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11200 let selections = self.selections.all::<Point>(cx);
11201 let ranges = selections
11202 .iter()
11203 .map(|s| {
11204 let mut range = s.display_range(&display_map).sorted();
11205 *range.start.column_mut() = 0;
11206 *range.end.column_mut() = display_map.line_len(range.end.row());
11207 let start = range.start.to_point(&display_map);
11208 let end = range.end.to_point(&display_map);
11209 start..end
11210 })
11211 .collect::<Vec<_>>();
11212
11213 self.unfold_ranges(&ranges, true, true, cx);
11214 }
11215
11216 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11217 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11218
11219 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11220 ..Point::new(
11221 unfold_at.buffer_row.0,
11222 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11223 );
11224
11225 let autoscroll = self
11226 .selections
11227 .all::<Point>(cx)
11228 .iter()
11229 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11230
11231 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11232 }
11233
11234 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11235 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11236 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11237 }
11238
11239 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11240 let selections = self.selections.all::<Point>(cx);
11241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11242 let line_mode = self.selections.line_mode;
11243 let ranges = selections
11244 .into_iter()
11245 .map(|s| {
11246 if line_mode {
11247 let start = Point::new(s.start.row, 0);
11248 let end = Point::new(
11249 s.end.row,
11250 display_map
11251 .buffer_snapshot
11252 .line_len(MultiBufferRow(s.end.row)),
11253 );
11254 Crease::simple(start..end, display_map.fold_placeholder.clone())
11255 } else {
11256 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11257 }
11258 })
11259 .collect::<Vec<_>>();
11260 self.fold_creases(ranges, true, cx);
11261 }
11262
11263 pub fn fold_creases<T: ToOffset + Clone>(
11264 &mut self,
11265 creases: Vec<Crease<T>>,
11266 auto_scroll: bool,
11267 cx: &mut ViewContext<Self>,
11268 ) {
11269 if creases.is_empty() {
11270 return;
11271 }
11272
11273 let mut buffers_affected = HashMap::default();
11274 let multi_buffer = self.buffer().read(cx);
11275 for crease in &creases {
11276 if let Some((_, buffer, _)) =
11277 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11278 {
11279 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11280 };
11281 }
11282
11283 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11284
11285 if auto_scroll {
11286 self.request_autoscroll(Autoscroll::fit(), cx);
11287 }
11288
11289 for buffer in buffers_affected.into_values() {
11290 self.sync_expanded_diff_hunks(buffer, cx);
11291 }
11292
11293 cx.notify();
11294
11295 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11296 // Clear diagnostics block when folding a range that contains it.
11297 let snapshot = self.snapshot(cx);
11298 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11299 drop(snapshot);
11300 self.active_diagnostics = Some(active_diagnostics);
11301 self.dismiss_diagnostics(cx);
11302 } else {
11303 self.active_diagnostics = Some(active_diagnostics);
11304 }
11305 }
11306
11307 self.scrollbar_marker_state.dirty = true;
11308 }
11309
11310 /// Removes any folds whose ranges intersect any of the given ranges.
11311 pub fn unfold_ranges<T: ToOffset + Clone>(
11312 &mut self,
11313 ranges: &[Range<T>],
11314 inclusive: bool,
11315 auto_scroll: bool,
11316 cx: &mut ViewContext<Self>,
11317 ) {
11318 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11319 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11320 });
11321 }
11322
11323 /// Removes any folds with the given ranges.
11324 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11325 &mut self,
11326 ranges: &[Range<T>],
11327 type_id: TypeId,
11328 auto_scroll: bool,
11329 cx: &mut ViewContext<Self>,
11330 ) {
11331 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11332 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11333 });
11334 }
11335
11336 fn remove_folds_with<T: ToOffset + Clone>(
11337 &mut self,
11338 ranges: &[Range<T>],
11339 auto_scroll: bool,
11340 cx: &mut ViewContext<Self>,
11341 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11342 ) {
11343 if ranges.is_empty() {
11344 return;
11345 }
11346
11347 let mut buffers_affected = HashMap::default();
11348 let multi_buffer = self.buffer().read(cx);
11349 for range in ranges {
11350 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11351 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11352 };
11353 }
11354
11355 self.display_map.update(cx, update);
11356
11357 if auto_scroll {
11358 self.request_autoscroll(Autoscroll::fit(), cx);
11359 }
11360
11361 for buffer in buffers_affected.into_values() {
11362 self.sync_expanded_diff_hunks(buffer, cx);
11363 }
11364
11365 cx.notify();
11366 self.scrollbar_marker_state.dirty = true;
11367 self.active_indent_guides_state.dirty = true;
11368 }
11369
11370 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11371 self.display_map.read(cx).fold_placeholder.clone()
11372 }
11373
11374 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11375 if hovered != self.gutter_hovered {
11376 self.gutter_hovered = hovered;
11377 cx.notify();
11378 }
11379 }
11380
11381 pub fn insert_blocks(
11382 &mut self,
11383 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11384 autoscroll: Option<Autoscroll>,
11385 cx: &mut ViewContext<Self>,
11386 ) -> Vec<CustomBlockId> {
11387 let blocks = self
11388 .display_map
11389 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11390 if let Some(autoscroll) = autoscroll {
11391 self.request_autoscroll(autoscroll, cx);
11392 }
11393 cx.notify();
11394 blocks
11395 }
11396
11397 pub fn resize_blocks(
11398 &mut self,
11399 heights: HashMap<CustomBlockId, u32>,
11400 autoscroll: Option<Autoscroll>,
11401 cx: &mut ViewContext<Self>,
11402 ) {
11403 self.display_map
11404 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11405 if let Some(autoscroll) = autoscroll {
11406 self.request_autoscroll(autoscroll, cx);
11407 }
11408 cx.notify();
11409 }
11410
11411 pub fn replace_blocks(
11412 &mut self,
11413 renderers: HashMap<CustomBlockId, RenderBlock>,
11414 autoscroll: Option<Autoscroll>,
11415 cx: &mut ViewContext<Self>,
11416 ) {
11417 self.display_map
11418 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11419 if let Some(autoscroll) = autoscroll {
11420 self.request_autoscroll(autoscroll, cx);
11421 }
11422 cx.notify();
11423 }
11424
11425 pub fn remove_blocks(
11426 &mut self,
11427 block_ids: HashSet<CustomBlockId>,
11428 autoscroll: Option<Autoscroll>,
11429 cx: &mut ViewContext<Self>,
11430 ) {
11431 self.display_map.update(cx, |display_map, cx| {
11432 display_map.remove_blocks(block_ids, cx)
11433 });
11434 if let Some(autoscroll) = autoscroll {
11435 self.request_autoscroll(autoscroll, cx);
11436 }
11437 cx.notify();
11438 }
11439
11440 pub fn row_for_block(
11441 &self,
11442 block_id: CustomBlockId,
11443 cx: &mut ViewContext<Self>,
11444 ) -> Option<DisplayRow> {
11445 self.display_map
11446 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11447 }
11448
11449 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11450 self.focused_block = Some(focused_block);
11451 }
11452
11453 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11454 self.focused_block.take()
11455 }
11456
11457 pub fn insert_creases(
11458 &mut self,
11459 creases: impl IntoIterator<Item = Crease<Anchor>>,
11460 cx: &mut ViewContext<Self>,
11461 ) -> Vec<CreaseId> {
11462 self.display_map
11463 .update(cx, |map, cx| map.insert_creases(creases, cx))
11464 }
11465
11466 pub fn remove_creases(
11467 &mut self,
11468 ids: impl IntoIterator<Item = CreaseId>,
11469 cx: &mut ViewContext<Self>,
11470 ) {
11471 self.display_map
11472 .update(cx, |map, cx| map.remove_creases(ids, cx));
11473 }
11474
11475 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11476 self.display_map
11477 .update(cx, |map, cx| map.snapshot(cx))
11478 .longest_row()
11479 }
11480
11481 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11482 self.display_map
11483 .update(cx, |map, cx| map.snapshot(cx))
11484 .max_point()
11485 }
11486
11487 pub fn text(&self, cx: &AppContext) -> String {
11488 self.buffer.read(cx).read(cx).text()
11489 }
11490
11491 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11492 let text = self.text(cx);
11493 let text = text.trim();
11494
11495 if text.is_empty() {
11496 return None;
11497 }
11498
11499 Some(text.to_string())
11500 }
11501
11502 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11503 self.transact(cx, |this, cx| {
11504 this.buffer
11505 .read(cx)
11506 .as_singleton()
11507 .expect("you can only call set_text on editors for singleton buffers")
11508 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11509 });
11510 }
11511
11512 pub fn display_text(&self, cx: &mut AppContext) -> String {
11513 self.display_map
11514 .update(cx, |map, cx| map.snapshot(cx))
11515 .text()
11516 }
11517
11518 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11519 let mut wrap_guides = smallvec::smallvec![];
11520
11521 if self.show_wrap_guides == Some(false) {
11522 return wrap_guides;
11523 }
11524
11525 let settings = self.buffer.read(cx).settings_at(0, cx);
11526 if settings.show_wrap_guides {
11527 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11528 wrap_guides.push((soft_wrap as usize, true));
11529 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11530 wrap_guides.push((soft_wrap as usize, true));
11531 }
11532 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11533 }
11534
11535 wrap_guides
11536 }
11537
11538 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11539 let settings = self.buffer.read(cx).settings_at(0, cx);
11540 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11541 match mode {
11542 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11543 SoftWrap::None
11544 }
11545 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11546 language_settings::SoftWrap::PreferredLineLength => {
11547 SoftWrap::Column(settings.preferred_line_length)
11548 }
11549 language_settings::SoftWrap::Bounded => {
11550 SoftWrap::Bounded(settings.preferred_line_length)
11551 }
11552 }
11553 }
11554
11555 pub fn set_soft_wrap_mode(
11556 &mut self,
11557 mode: language_settings::SoftWrap,
11558 cx: &mut ViewContext<Self>,
11559 ) {
11560 self.soft_wrap_mode_override = Some(mode);
11561 cx.notify();
11562 }
11563
11564 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11565 self.text_style_refinement = Some(style);
11566 }
11567
11568 /// called by the Element so we know what style we were most recently rendered with.
11569 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11570 let rem_size = cx.rem_size();
11571 self.display_map.update(cx, |map, cx| {
11572 map.set_font(
11573 style.text.font(),
11574 style.text.font_size.to_pixels(rem_size),
11575 cx,
11576 )
11577 });
11578 self.style = Some(style);
11579 }
11580
11581 pub fn style(&self) -> Option<&EditorStyle> {
11582 self.style.as_ref()
11583 }
11584
11585 // Called by the element. This method is not designed to be called outside of the editor
11586 // element's layout code because it does not notify when rewrapping is computed synchronously.
11587 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11588 self.display_map
11589 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11590 }
11591
11592 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11593 if self.soft_wrap_mode_override.is_some() {
11594 self.soft_wrap_mode_override.take();
11595 } else {
11596 let soft_wrap = match self.soft_wrap_mode(cx) {
11597 SoftWrap::GitDiff => return,
11598 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11599 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11600 language_settings::SoftWrap::None
11601 }
11602 };
11603 self.soft_wrap_mode_override = Some(soft_wrap);
11604 }
11605 cx.notify();
11606 }
11607
11608 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11609 let Some(workspace) = self.workspace() else {
11610 return;
11611 };
11612 let fs = workspace.read(cx).app_state().fs.clone();
11613 let current_show = TabBarSettings::get_global(cx).show;
11614 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11615 setting.show = Some(!current_show);
11616 });
11617 }
11618
11619 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11620 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11621 self.buffer
11622 .read(cx)
11623 .settings_at(0, cx)
11624 .indent_guides
11625 .enabled
11626 });
11627 self.show_indent_guides = Some(!currently_enabled);
11628 cx.notify();
11629 }
11630
11631 fn should_show_indent_guides(&self) -> Option<bool> {
11632 self.show_indent_guides
11633 }
11634
11635 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11636 let mut editor_settings = EditorSettings::get_global(cx).clone();
11637 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11638 EditorSettings::override_global(editor_settings, cx);
11639 }
11640
11641 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11642 self.use_relative_line_numbers
11643 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11644 }
11645
11646 pub fn toggle_relative_line_numbers(
11647 &mut self,
11648 _: &ToggleRelativeLineNumbers,
11649 cx: &mut ViewContext<Self>,
11650 ) {
11651 let is_relative = self.should_use_relative_line_numbers(cx);
11652 self.set_relative_line_number(Some(!is_relative), cx)
11653 }
11654
11655 pub fn set_relative_line_number(
11656 &mut self,
11657 is_relative: Option<bool>,
11658 cx: &mut ViewContext<Self>,
11659 ) {
11660 self.use_relative_line_numbers = is_relative;
11661 cx.notify();
11662 }
11663
11664 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11665 self.show_gutter = show_gutter;
11666 cx.notify();
11667 }
11668
11669 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11670 self.show_line_numbers = Some(show_line_numbers);
11671 cx.notify();
11672 }
11673
11674 pub fn set_show_git_diff_gutter(
11675 &mut self,
11676 show_git_diff_gutter: bool,
11677 cx: &mut ViewContext<Self>,
11678 ) {
11679 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11680 cx.notify();
11681 }
11682
11683 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11684 self.show_code_actions = Some(show_code_actions);
11685 cx.notify();
11686 }
11687
11688 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11689 self.show_runnables = Some(show_runnables);
11690 cx.notify();
11691 }
11692
11693 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11694 if self.display_map.read(cx).masked != masked {
11695 self.display_map.update(cx, |map, _| map.masked = masked);
11696 }
11697 cx.notify()
11698 }
11699
11700 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11701 self.show_wrap_guides = Some(show_wrap_guides);
11702 cx.notify();
11703 }
11704
11705 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11706 self.show_indent_guides = Some(show_indent_guides);
11707 cx.notify();
11708 }
11709
11710 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11711 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11712 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11713 if let Some(dir) = file.abs_path(cx).parent() {
11714 return Some(dir.to_owned());
11715 }
11716 }
11717
11718 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11719 return Some(project_path.path.to_path_buf());
11720 }
11721 }
11722
11723 None
11724 }
11725
11726 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11727 self.active_excerpt(cx)?
11728 .1
11729 .read(cx)
11730 .file()
11731 .and_then(|f| f.as_local())
11732 }
11733
11734 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11735 if let Some(target) = self.target_file(cx) {
11736 cx.reveal_path(&target.abs_path(cx));
11737 }
11738 }
11739
11740 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11741 if let Some(file) = self.target_file(cx) {
11742 if let Some(path) = file.abs_path(cx).to_str() {
11743 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11744 }
11745 }
11746 }
11747
11748 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11749 if let Some(file) = self.target_file(cx) {
11750 if let Some(path) = file.path().to_str() {
11751 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11752 }
11753 }
11754 }
11755
11756 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11757 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11758
11759 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11760 self.start_git_blame(true, cx);
11761 }
11762
11763 cx.notify();
11764 }
11765
11766 pub fn toggle_git_blame_inline(
11767 &mut self,
11768 _: &ToggleGitBlameInline,
11769 cx: &mut ViewContext<Self>,
11770 ) {
11771 self.toggle_git_blame_inline_internal(true, cx);
11772 cx.notify();
11773 }
11774
11775 pub fn git_blame_inline_enabled(&self) -> bool {
11776 self.git_blame_inline_enabled
11777 }
11778
11779 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11780 self.show_selection_menu = self
11781 .show_selection_menu
11782 .map(|show_selections_menu| !show_selections_menu)
11783 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11784
11785 cx.notify();
11786 }
11787
11788 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11789 self.show_selection_menu
11790 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11791 }
11792
11793 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11794 if let Some(project) = self.project.as_ref() {
11795 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11796 return;
11797 };
11798
11799 if buffer.read(cx).file().is_none() {
11800 return;
11801 }
11802
11803 let focused = self.focus_handle(cx).contains_focused(cx);
11804
11805 let project = project.clone();
11806 let blame =
11807 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11808 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11809 self.blame = Some(blame);
11810 }
11811 }
11812
11813 fn toggle_git_blame_inline_internal(
11814 &mut self,
11815 user_triggered: bool,
11816 cx: &mut ViewContext<Self>,
11817 ) {
11818 if self.git_blame_inline_enabled {
11819 self.git_blame_inline_enabled = false;
11820 self.show_git_blame_inline = false;
11821 self.show_git_blame_inline_delay_task.take();
11822 } else {
11823 self.git_blame_inline_enabled = true;
11824 self.start_git_blame_inline(user_triggered, cx);
11825 }
11826
11827 cx.notify();
11828 }
11829
11830 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11831 self.start_git_blame(user_triggered, cx);
11832
11833 if ProjectSettings::get_global(cx)
11834 .git
11835 .inline_blame_delay()
11836 .is_some()
11837 {
11838 self.start_inline_blame_timer(cx);
11839 } else {
11840 self.show_git_blame_inline = true
11841 }
11842 }
11843
11844 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11845 self.blame.as_ref()
11846 }
11847
11848 pub fn show_git_blame_gutter(&self) -> bool {
11849 self.show_git_blame_gutter
11850 }
11851
11852 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11853 self.show_git_blame_gutter && self.has_blame_entries(cx)
11854 }
11855
11856 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11857 self.show_git_blame_inline
11858 && self.focus_handle.is_focused(cx)
11859 && !self.newest_selection_head_on_empty_line(cx)
11860 && self.has_blame_entries(cx)
11861 }
11862
11863 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11864 self.blame()
11865 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11866 }
11867
11868 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11869 let cursor_anchor = self.selections.newest_anchor().head();
11870
11871 let snapshot = self.buffer.read(cx).snapshot(cx);
11872 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11873
11874 snapshot.line_len(buffer_row) == 0
11875 }
11876
11877 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11878 let buffer_and_selection = maybe!({
11879 let selection = self.selections.newest::<Point>(cx);
11880 let selection_range = selection.range();
11881
11882 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11883 (buffer, selection_range.start.row..selection_range.end.row)
11884 } else {
11885 let buffer_ranges = self
11886 .buffer()
11887 .read(cx)
11888 .range_to_buffer_ranges(selection_range, cx);
11889
11890 let (buffer, range, _) = if selection.reversed {
11891 buffer_ranges.first()
11892 } else {
11893 buffer_ranges.last()
11894 }?;
11895
11896 let snapshot = buffer.read(cx).snapshot();
11897 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11898 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11899 (buffer.clone(), selection)
11900 };
11901
11902 Some((buffer, selection))
11903 });
11904
11905 let Some((buffer, selection)) = buffer_and_selection else {
11906 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11907 };
11908
11909 let Some(project) = self.project.as_ref() else {
11910 return Task::ready(Err(anyhow!("editor does not have project")));
11911 };
11912
11913 project.update(cx, |project, cx| {
11914 project.get_permalink_to_line(&buffer, selection, cx)
11915 })
11916 }
11917
11918 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11919 let permalink_task = self.get_permalink_to_line(cx);
11920 let workspace = self.workspace();
11921
11922 cx.spawn(|_, mut cx| async move {
11923 match permalink_task.await {
11924 Ok(permalink) => {
11925 cx.update(|cx| {
11926 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11927 })
11928 .ok();
11929 }
11930 Err(err) => {
11931 let message = format!("Failed to copy permalink: {err}");
11932
11933 Err::<(), anyhow::Error>(err).log_err();
11934
11935 if let Some(workspace) = workspace {
11936 workspace
11937 .update(&mut cx, |workspace, cx| {
11938 struct CopyPermalinkToLine;
11939
11940 workspace.show_toast(
11941 Toast::new(
11942 NotificationId::unique::<CopyPermalinkToLine>(),
11943 message,
11944 ),
11945 cx,
11946 )
11947 })
11948 .ok();
11949 }
11950 }
11951 }
11952 })
11953 .detach();
11954 }
11955
11956 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11957 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11958 if let Some(file) = self.target_file(cx) {
11959 if let Some(path) = file.path().to_str() {
11960 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11961 }
11962 }
11963 }
11964
11965 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11966 let permalink_task = self.get_permalink_to_line(cx);
11967 let workspace = self.workspace();
11968
11969 cx.spawn(|_, mut cx| async move {
11970 match permalink_task.await {
11971 Ok(permalink) => {
11972 cx.update(|cx| {
11973 cx.open_url(permalink.as_ref());
11974 })
11975 .ok();
11976 }
11977 Err(err) => {
11978 let message = format!("Failed to open permalink: {err}");
11979
11980 Err::<(), anyhow::Error>(err).log_err();
11981
11982 if let Some(workspace) = workspace {
11983 workspace
11984 .update(&mut cx, |workspace, cx| {
11985 struct OpenPermalinkToLine;
11986
11987 workspace.show_toast(
11988 Toast::new(
11989 NotificationId::unique::<OpenPermalinkToLine>(),
11990 message,
11991 ),
11992 cx,
11993 )
11994 })
11995 .ok();
11996 }
11997 }
11998 }
11999 })
12000 .detach();
12001 }
12002
12003 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12004 /// last highlight added will be used.
12005 ///
12006 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12007 pub fn highlight_rows<T: 'static>(
12008 &mut self,
12009 range: Range<Anchor>,
12010 color: Hsla,
12011 should_autoscroll: bool,
12012 cx: &mut ViewContext<Self>,
12013 ) {
12014 let snapshot = self.buffer().read(cx).snapshot(cx);
12015 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12016 let ix = row_highlights.binary_search_by(|highlight| {
12017 Ordering::Equal
12018 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12019 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12020 });
12021
12022 if let Err(mut ix) = ix {
12023 let index = post_inc(&mut self.highlight_order);
12024
12025 // If this range intersects with the preceding highlight, then merge it with
12026 // the preceding highlight. Otherwise insert a new highlight.
12027 let mut merged = false;
12028 if ix > 0 {
12029 let prev_highlight = &mut row_highlights[ix - 1];
12030 if prev_highlight
12031 .range
12032 .end
12033 .cmp(&range.start, &snapshot)
12034 .is_ge()
12035 {
12036 ix -= 1;
12037 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12038 prev_highlight.range.end = range.end;
12039 }
12040 merged = true;
12041 prev_highlight.index = index;
12042 prev_highlight.color = color;
12043 prev_highlight.should_autoscroll = should_autoscroll;
12044 }
12045 }
12046
12047 if !merged {
12048 row_highlights.insert(
12049 ix,
12050 RowHighlight {
12051 range: range.clone(),
12052 index,
12053 color,
12054 should_autoscroll,
12055 },
12056 );
12057 }
12058
12059 // If any of the following highlights intersect with this one, merge them.
12060 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12061 let highlight = &row_highlights[ix];
12062 if next_highlight
12063 .range
12064 .start
12065 .cmp(&highlight.range.end, &snapshot)
12066 .is_le()
12067 {
12068 if next_highlight
12069 .range
12070 .end
12071 .cmp(&highlight.range.end, &snapshot)
12072 .is_gt()
12073 {
12074 row_highlights[ix].range.end = next_highlight.range.end;
12075 }
12076 row_highlights.remove(ix + 1);
12077 } else {
12078 break;
12079 }
12080 }
12081 }
12082 }
12083
12084 /// Remove any highlighted row ranges of the given type that intersect the
12085 /// given ranges.
12086 pub fn remove_highlighted_rows<T: 'static>(
12087 &mut self,
12088 ranges_to_remove: Vec<Range<Anchor>>,
12089 cx: &mut ViewContext<Self>,
12090 ) {
12091 let snapshot = self.buffer().read(cx).snapshot(cx);
12092 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12093 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12094 row_highlights.retain(|highlight| {
12095 while let Some(range_to_remove) = ranges_to_remove.peek() {
12096 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12097 Ordering::Less | Ordering::Equal => {
12098 ranges_to_remove.next();
12099 }
12100 Ordering::Greater => {
12101 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12102 Ordering::Less | Ordering::Equal => {
12103 return false;
12104 }
12105 Ordering::Greater => break,
12106 }
12107 }
12108 }
12109 }
12110
12111 true
12112 })
12113 }
12114
12115 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12116 pub fn clear_row_highlights<T: 'static>(&mut self) {
12117 self.highlighted_rows.remove(&TypeId::of::<T>());
12118 }
12119
12120 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12121 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12122 self.highlighted_rows
12123 .get(&TypeId::of::<T>())
12124 .map_or(&[] as &[_], |vec| vec.as_slice())
12125 .iter()
12126 .map(|highlight| (highlight.range.clone(), highlight.color))
12127 }
12128
12129 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12130 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12131 /// Allows to ignore certain kinds of highlights.
12132 pub fn highlighted_display_rows(
12133 &mut self,
12134 cx: &mut WindowContext,
12135 ) -> BTreeMap<DisplayRow, Hsla> {
12136 let snapshot = self.snapshot(cx);
12137 let mut used_highlight_orders = HashMap::default();
12138 self.highlighted_rows
12139 .iter()
12140 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12141 .fold(
12142 BTreeMap::<DisplayRow, Hsla>::new(),
12143 |mut unique_rows, highlight| {
12144 let start = highlight.range.start.to_display_point(&snapshot);
12145 let end = highlight.range.end.to_display_point(&snapshot);
12146 let start_row = start.row().0;
12147 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12148 && end.column() == 0
12149 {
12150 end.row().0.saturating_sub(1)
12151 } else {
12152 end.row().0
12153 };
12154 for row in start_row..=end_row {
12155 let used_index =
12156 used_highlight_orders.entry(row).or_insert(highlight.index);
12157 if highlight.index >= *used_index {
12158 *used_index = highlight.index;
12159 unique_rows.insert(DisplayRow(row), highlight.color);
12160 }
12161 }
12162 unique_rows
12163 },
12164 )
12165 }
12166
12167 pub fn highlighted_display_row_for_autoscroll(
12168 &self,
12169 snapshot: &DisplaySnapshot,
12170 ) -> Option<DisplayRow> {
12171 self.highlighted_rows
12172 .values()
12173 .flat_map(|highlighted_rows| highlighted_rows.iter())
12174 .filter_map(|highlight| {
12175 if highlight.should_autoscroll {
12176 Some(highlight.range.start.to_display_point(snapshot).row())
12177 } else {
12178 None
12179 }
12180 })
12181 .min()
12182 }
12183
12184 pub fn set_search_within_ranges(
12185 &mut self,
12186 ranges: &[Range<Anchor>],
12187 cx: &mut ViewContext<Self>,
12188 ) {
12189 self.highlight_background::<SearchWithinRange>(
12190 ranges,
12191 |colors| colors.editor_document_highlight_read_background,
12192 cx,
12193 )
12194 }
12195
12196 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12197 self.breadcrumb_header = Some(new_header);
12198 }
12199
12200 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12201 self.clear_background_highlights::<SearchWithinRange>(cx);
12202 }
12203
12204 pub fn highlight_background<T: 'static>(
12205 &mut self,
12206 ranges: &[Range<Anchor>],
12207 color_fetcher: fn(&ThemeColors) -> Hsla,
12208 cx: &mut ViewContext<Self>,
12209 ) {
12210 self.background_highlights
12211 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12212 self.scrollbar_marker_state.dirty = true;
12213 cx.notify();
12214 }
12215
12216 pub fn clear_background_highlights<T: 'static>(
12217 &mut self,
12218 cx: &mut ViewContext<Self>,
12219 ) -> Option<BackgroundHighlight> {
12220 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12221 if !text_highlights.1.is_empty() {
12222 self.scrollbar_marker_state.dirty = true;
12223 cx.notify();
12224 }
12225 Some(text_highlights)
12226 }
12227
12228 pub fn highlight_gutter<T: 'static>(
12229 &mut self,
12230 ranges: &[Range<Anchor>],
12231 color_fetcher: fn(&AppContext) -> Hsla,
12232 cx: &mut ViewContext<Self>,
12233 ) {
12234 self.gutter_highlights
12235 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12236 cx.notify();
12237 }
12238
12239 pub fn clear_gutter_highlights<T: 'static>(
12240 &mut self,
12241 cx: &mut ViewContext<Self>,
12242 ) -> Option<GutterHighlight> {
12243 cx.notify();
12244 self.gutter_highlights.remove(&TypeId::of::<T>())
12245 }
12246
12247 #[cfg(feature = "test-support")]
12248 pub fn all_text_background_highlights(
12249 &mut self,
12250 cx: &mut ViewContext<Self>,
12251 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12252 let snapshot = self.snapshot(cx);
12253 let buffer = &snapshot.buffer_snapshot;
12254 let start = buffer.anchor_before(0);
12255 let end = buffer.anchor_after(buffer.len());
12256 let theme = cx.theme().colors();
12257 self.background_highlights_in_range(start..end, &snapshot, theme)
12258 }
12259
12260 #[cfg(feature = "test-support")]
12261 pub fn search_background_highlights(
12262 &mut self,
12263 cx: &mut ViewContext<Self>,
12264 ) -> Vec<Range<Point>> {
12265 let snapshot = self.buffer().read(cx).snapshot(cx);
12266
12267 let highlights = self
12268 .background_highlights
12269 .get(&TypeId::of::<items::BufferSearchHighlights>());
12270
12271 if let Some((_color, ranges)) = highlights {
12272 ranges
12273 .iter()
12274 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12275 .collect_vec()
12276 } else {
12277 vec![]
12278 }
12279 }
12280
12281 fn document_highlights_for_position<'a>(
12282 &'a self,
12283 position: Anchor,
12284 buffer: &'a MultiBufferSnapshot,
12285 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12286 let read_highlights = self
12287 .background_highlights
12288 .get(&TypeId::of::<DocumentHighlightRead>())
12289 .map(|h| &h.1);
12290 let write_highlights = self
12291 .background_highlights
12292 .get(&TypeId::of::<DocumentHighlightWrite>())
12293 .map(|h| &h.1);
12294 let left_position = position.bias_left(buffer);
12295 let right_position = position.bias_right(buffer);
12296 read_highlights
12297 .into_iter()
12298 .chain(write_highlights)
12299 .flat_map(move |ranges| {
12300 let start_ix = match ranges.binary_search_by(|probe| {
12301 let cmp = probe.end.cmp(&left_position, buffer);
12302 if cmp.is_ge() {
12303 Ordering::Greater
12304 } else {
12305 Ordering::Less
12306 }
12307 }) {
12308 Ok(i) | Err(i) => i,
12309 };
12310
12311 ranges[start_ix..]
12312 .iter()
12313 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12314 })
12315 }
12316
12317 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12318 self.background_highlights
12319 .get(&TypeId::of::<T>())
12320 .map_or(false, |(_, highlights)| !highlights.is_empty())
12321 }
12322
12323 pub fn background_highlights_in_range(
12324 &self,
12325 search_range: Range<Anchor>,
12326 display_snapshot: &DisplaySnapshot,
12327 theme: &ThemeColors,
12328 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12329 let mut results = Vec::new();
12330 for (color_fetcher, ranges) in self.background_highlights.values() {
12331 let color = color_fetcher(theme);
12332 let start_ix = match ranges.binary_search_by(|probe| {
12333 let cmp = probe
12334 .end
12335 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12336 if cmp.is_gt() {
12337 Ordering::Greater
12338 } else {
12339 Ordering::Less
12340 }
12341 }) {
12342 Ok(i) | Err(i) => i,
12343 };
12344 for range in &ranges[start_ix..] {
12345 if range
12346 .start
12347 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12348 .is_ge()
12349 {
12350 break;
12351 }
12352
12353 let start = range.start.to_display_point(display_snapshot);
12354 let end = range.end.to_display_point(display_snapshot);
12355 results.push((start..end, color))
12356 }
12357 }
12358 results
12359 }
12360
12361 pub fn background_highlight_row_ranges<T: 'static>(
12362 &self,
12363 search_range: Range<Anchor>,
12364 display_snapshot: &DisplaySnapshot,
12365 count: usize,
12366 ) -> Vec<RangeInclusive<DisplayPoint>> {
12367 let mut results = Vec::new();
12368 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12369 return vec![];
12370 };
12371
12372 let start_ix = match ranges.binary_search_by(|probe| {
12373 let cmp = probe
12374 .end
12375 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12376 if cmp.is_gt() {
12377 Ordering::Greater
12378 } else {
12379 Ordering::Less
12380 }
12381 }) {
12382 Ok(i) | Err(i) => i,
12383 };
12384 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12385 if let (Some(start_display), Some(end_display)) = (start, end) {
12386 results.push(
12387 start_display.to_display_point(display_snapshot)
12388 ..=end_display.to_display_point(display_snapshot),
12389 );
12390 }
12391 };
12392 let mut start_row: Option<Point> = None;
12393 let mut end_row: Option<Point> = None;
12394 if ranges.len() > count {
12395 return Vec::new();
12396 }
12397 for range in &ranges[start_ix..] {
12398 if range
12399 .start
12400 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12401 .is_ge()
12402 {
12403 break;
12404 }
12405 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12406 if let Some(current_row) = &end_row {
12407 if end.row == current_row.row {
12408 continue;
12409 }
12410 }
12411 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12412 if start_row.is_none() {
12413 assert_eq!(end_row, None);
12414 start_row = Some(start);
12415 end_row = Some(end);
12416 continue;
12417 }
12418 if let Some(current_end) = end_row.as_mut() {
12419 if start.row > current_end.row + 1 {
12420 push_region(start_row, end_row);
12421 start_row = Some(start);
12422 end_row = Some(end);
12423 } else {
12424 // Merge two hunks.
12425 *current_end = end;
12426 }
12427 } else {
12428 unreachable!();
12429 }
12430 }
12431 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12432 push_region(start_row, end_row);
12433 results
12434 }
12435
12436 pub fn gutter_highlights_in_range(
12437 &self,
12438 search_range: Range<Anchor>,
12439 display_snapshot: &DisplaySnapshot,
12440 cx: &AppContext,
12441 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12442 let mut results = Vec::new();
12443 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12444 let color = color_fetcher(cx);
12445 let start_ix = match ranges.binary_search_by(|probe| {
12446 let cmp = probe
12447 .end
12448 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12449 if cmp.is_gt() {
12450 Ordering::Greater
12451 } else {
12452 Ordering::Less
12453 }
12454 }) {
12455 Ok(i) | Err(i) => i,
12456 };
12457 for range in &ranges[start_ix..] {
12458 if range
12459 .start
12460 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12461 .is_ge()
12462 {
12463 break;
12464 }
12465
12466 let start = range.start.to_display_point(display_snapshot);
12467 let end = range.end.to_display_point(display_snapshot);
12468 results.push((start..end, color))
12469 }
12470 }
12471 results
12472 }
12473
12474 /// Get the text ranges corresponding to the redaction query
12475 pub fn redacted_ranges(
12476 &self,
12477 search_range: Range<Anchor>,
12478 display_snapshot: &DisplaySnapshot,
12479 cx: &WindowContext,
12480 ) -> Vec<Range<DisplayPoint>> {
12481 display_snapshot
12482 .buffer_snapshot
12483 .redacted_ranges(search_range, |file| {
12484 if let Some(file) = file {
12485 file.is_private()
12486 && EditorSettings::get(
12487 Some(SettingsLocation {
12488 worktree_id: file.worktree_id(cx),
12489 path: file.path().as_ref(),
12490 }),
12491 cx,
12492 )
12493 .redact_private_values
12494 } else {
12495 false
12496 }
12497 })
12498 .map(|range| {
12499 range.start.to_display_point(display_snapshot)
12500 ..range.end.to_display_point(display_snapshot)
12501 })
12502 .collect()
12503 }
12504
12505 pub fn highlight_text<T: 'static>(
12506 &mut self,
12507 ranges: Vec<Range<Anchor>>,
12508 style: HighlightStyle,
12509 cx: &mut ViewContext<Self>,
12510 ) {
12511 self.display_map.update(cx, |map, _| {
12512 map.highlight_text(TypeId::of::<T>(), ranges, style)
12513 });
12514 cx.notify();
12515 }
12516
12517 pub(crate) fn highlight_inlays<T: 'static>(
12518 &mut self,
12519 highlights: Vec<InlayHighlight>,
12520 style: HighlightStyle,
12521 cx: &mut ViewContext<Self>,
12522 ) {
12523 self.display_map.update(cx, |map, _| {
12524 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12525 });
12526 cx.notify();
12527 }
12528
12529 pub fn text_highlights<'a, T: 'static>(
12530 &'a self,
12531 cx: &'a AppContext,
12532 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12533 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12534 }
12535
12536 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12537 let cleared = self
12538 .display_map
12539 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12540 if cleared {
12541 cx.notify();
12542 }
12543 }
12544
12545 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12546 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12547 && self.focus_handle.is_focused(cx)
12548 }
12549
12550 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12551 self.show_cursor_when_unfocused = is_enabled;
12552 cx.notify();
12553 }
12554
12555 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12556 cx.notify();
12557 }
12558
12559 fn on_buffer_event(
12560 &mut self,
12561 multibuffer: Model<MultiBuffer>,
12562 event: &multi_buffer::Event,
12563 cx: &mut ViewContext<Self>,
12564 ) {
12565 match event {
12566 multi_buffer::Event::Edited {
12567 singleton_buffer_edited,
12568 } => {
12569 self.scrollbar_marker_state.dirty = true;
12570 self.active_indent_guides_state.dirty = true;
12571 self.refresh_active_diagnostics(cx);
12572 self.refresh_code_actions(cx);
12573 if self.has_active_inline_completion(cx) {
12574 self.update_visible_inline_completion(cx);
12575 }
12576 cx.emit(EditorEvent::BufferEdited);
12577 cx.emit(SearchEvent::MatchesInvalidated);
12578 if *singleton_buffer_edited {
12579 if let Some(project) = &self.project {
12580 let project = project.read(cx);
12581 #[allow(clippy::mutable_key_type)]
12582 let languages_affected = multibuffer
12583 .read(cx)
12584 .all_buffers()
12585 .into_iter()
12586 .filter_map(|buffer| {
12587 let buffer = buffer.read(cx);
12588 let language = buffer.language()?;
12589 if project.is_local()
12590 && project.language_servers_for_buffer(buffer, cx).count() == 0
12591 {
12592 None
12593 } else {
12594 Some(language)
12595 }
12596 })
12597 .cloned()
12598 .collect::<HashSet<_>>();
12599 if !languages_affected.is_empty() {
12600 self.refresh_inlay_hints(
12601 InlayHintRefreshReason::BufferEdited(languages_affected),
12602 cx,
12603 );
12604 }
12605 }
12606 }
12607
12608 let Some(project) = &self.project else { return };
12609 let (telemetry, is_via_ssh) = {
12610 let project = project.read(cx);
12611 let telemetry = project.client().telemetry().clone();
12612 let is_via_ssh = project.is_via_ssh();
12613 (telemetry, is_via_ssh)
12614 };
12615 refresh_linked_ranges(self, cx);
12616 telemetry.log_edit_event("editor", is_via_ssh);
12617 }
12618 multi_buffer::Event::ExcerptsAdded {
12619 buffer,
12620 predecessor,
12621 excerpts,
12622 } => {
12623 self.tasks_update_task = Some(self.refresh_runnables(cx));
12624 cx.emit(EditorEvent::ExcerptsAdded {
12625 buffer: buffer.clone(),
12626 predecessor: *predecessor,
12627 excerpts: excerpts.clone(),
12628 });
12629 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12630 }
12631 multi_buffer::Event::ExcerptsRemoved { ids } => {
12632 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12633 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12634 }
12635 multi_buffer::Event::ExcerptsEdited { ids } => {
12636 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12637 }
12638 multi_buffer::Event::ExcerptsExpanded { ids } => {
12639 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12640 }
12641 multi_buffer::Event::Reparsed(buffer_id) => {
12642 self.tasks_update_task = Some(self.refresh_runnables(cx));
12643
12644 cx.emit(EditorEvent::Reparsed(*buffer_id));
12645 }
12646 multi_buffer::Event::LanguageChanged(buffer_id) => {
12647 linked_editing_ranges::refresh_linked_ranges(self, cx);
12648 cx.emit(EditorEvent::Reparsed(*buffer_id));
12649 cx.notify();
12650 }
12651 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12652 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12653 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12654 cx.emit(EditorEvent::TitleChanged)
12655 }
12656 multi_buffer::Event::DiffBaseChanged => {
12657 self.scrollbar_marker_state.dirty = true;
12658 cx.emit(EditorEvent::DiffBaseChanged);
12659 cx.notify();
12660 }
12661 multi_buffer::Event::DiffUpdated { buffer } => {
12662 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12663 cx.notify();
12664 }
12665 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12666 multi_buffer::Event::DiagnosticsUpdated => {
12667 self.refresh_active_diagnostics(cx);
12668 self.scrollbar_marker_state.dirty = true;
12669 cx.notify();
12670 }
12671 _ => {}
12672 };
12673 }
12674
12675 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12676 cx.notify();
12677 }
12678
12679 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12680 self.tasks_update_task = Some(self.refresh_runnables(cx));
12681 self.refresh_inline_completion(true, false, cx);
12682 self.refresh_inlay_hints(
12683 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12684 self.selections.newest_anchor().head(),
12685 &self.buffer.read(cx).snapshot(cx),
12686 cx,
12687 )),
12688 cx,
12689 );
12690
12691 let old_cursor_shape = self.cursor_shape;
12692
12693 {
12694 let editor_settings = EditorSettings::get_global(cx);
12695 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12696 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12697 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12698 }
12699
12700 if old_cursor_shape != self.cursor_shape {
12701 cx.emit(EditorEvent::CursorShapeChanged);
12702 }
12703
12704 let project_settings = ProjectSettings::get_global(cx);
12705 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12706
12707 if self.mode == EditorMode::Full {
12708 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12709 if self.git_blame_inline_enabled != inline_blame_enabled {
12710 self.toggle_git_blame_inline_internal(false, cx);
12711 }
12712 }
12713
12714 cx.notify();
12715 }
12716
12717 pub fn set_searchable(&mut self, searchable: bool) {
12718 self.searchable = searchable;
12719 }
12720
12721 pub fn searchable(&self) -> bool {
12722 self.searchable
12723 }
12724
12725 fn open_proposed_changes_editor(
12726 &mut self,
12727 _: &OpenProposedChangesEditor,
12728 cx: &mut ViewContext<Self>,
12729 ) {
12730 let Some(workspace) = self.workspace() else {
12731 cx.propagate();
12732 return;
12733 };
12734
12735 let selections = self.selections.all::<usize>(cx);
12736 let buffer = self.buffer.read(cx);
12737 let mut new_selections_by_buffer = HashMap::default();
12738 for selection in selections {
12739 for (buffer, range, _) in
12740 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12741 {
12742 let mut range = range.to_point(buffer.read(cx));
12743 range.start.column = 0;
12744 range.end.column = buffer.read(cx).line_len(range.end.row);
12745 new_selections_by_buffer
12746 .entry(buffer)
12747 .or_insert(Vec::new())
12748 .push(range)
12749 }
12750 }
12751
12752 let proposed_changes_buffers = new_selections_by_buffer
12753 .into_iter()
12754 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12755 .collect::<Vec<_>>();
12756 let proposed_changes_editor = cx.new_view(|cx| {
12757 ProposedChangesEditor::new(
12758 "Proposed changes",
12759 proposed_changes_buffers,
12760 self.project.clone(),
12761 cx,
12762 )
12763 });
12764
12765 cx.window_context().defer(move |cx| {
12766 workspace.update(cx, |workspace, cx| {
12767 workspace.active_pane().update(cx, |pane, cx| {
12768 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12769 });
12770 });
12771 });
12772 }
12773
12774 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12775 self.open_excerpts_common(None, true, cx)
12776 }
12777
12778 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12779 self.open_excerpts_common(None, false, cx)
12780 }
12781
12782 fn open_excerpts_common(
12783 &mut self,
12784 jump_data: Option<JumpData>,
12785 split: bool,
12786 cx: &mut ViewContext<Self>,
12787 ) {
12788 let Some(workspace) = self.workspace() else {
12789 cx.propagate();
12790 return;
12791 };
12792
12793 if self.buffer.read(cx).is_singleton() {
12794 cx.propagate();
12795 return;
12796 }
12797
12798 let mut new_selections_by_buffer = HashMap::default();
12799 match &jump_data {
12800 Some(jump_data) => {
12801 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12802 if let Some(buffer) = multi_buffer_snapshot
12803 .buffer_id_for_excerpt(jump_data.excerpt_id)
12804 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12805 {
12806 let buffer_snapshot = buffer.read(cx).snapshot();
12807 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12808 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12809 } else {
12810 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12811 };
12812 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12813 new_selections_by_buffer.insert(
12814 buffer,
12815 (
12816 vec![jump_to_offset..jump_to_offset],
12817 Some(jump_data.line_offset_from_top),
12818 ),
12819 );
12820 }
12821 }
12822 None => {
12823 let selections = self.selections.all::<usize>(cx);
12824 let buffer = self.buffer.read(cx);
12825 for selection in selections {
12826 for (mut buffer_handle, mut range, _) in
12827 buffer.range_to_buffer_ranges(selection.range(), cx)
12828 {
12829 // When editing branch buffers, jump to the corresponding location
12830 // in their base buffer.
12831 let buffer = buffer_handle.read(cx);
12832 if let Some(base_buffer) = buffer.diff_base_buffer() {
12833 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12834 buffer_handle = base_buffer;
12835 }
12836
12837 if selection.reversed {
12838 mem::swap(&mut range.start, &mut range.end);
12839 }
12840 new_selections_by_buffer
12841 .entry(buffer_handle)
12842 .or_insert((Vec::new(), None))
12843 .0
12844 .push(range)
12845 }
12846 }
12847 }
12848 }
12849
12850 if new_selections_by_buffer.is_empty() {
12851 return;
12852 }
12853
12854 // We defer the pane interaction because we ourselves are a workspace item
12855 // and activating a new item causes the pane to call a method on us reentrantly,
12856 // which panics if we're on the stack.
12857 cx.window_context().defer(move |cx| {
12858 workspace.update(cx, |workspace, cx| {
12859 let pane = if split {
12860 workspace.adjacent_pane(cx)
12861 } else {
12862 workspace.active_pane().clone()
12863 };
12864
12865 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12866 let editor = buffer
12867 .read(cx)
12868 .file()
12869 .is_none()
12870 .then(|| {
12871 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12872 // so `workspace.open_project_item` will never find them, always opening a new editor.
12873 // Instead, we try to activate the existing editor in the pane first.
12874 let (editor, pane_item_index) =
12875 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12876 let editor = item.downcast::<Editor>()?;
12877 let singleton_buffer =
12878 editor.read(cx).buffer().read(cx).as_singleton()?;
12879 if singleton_buffer == buffer {
12880 Some((editor, i))
12881 } else {
12882 None
12883 }
12884 })?;
12885 pane.update(cx, |pane, cx| {
12886 pane.activate_item(pane_item_index, true, true, cx)
12887 });
12888 Some(editor)
12889 })
12890 .flatten()
12891 .unwrap_or_else(|| {
12892 workspace.open_project_item::<Self>(
12893 pane.clone(),
12894 buffer,
12895 true,
12896 true,
12897 cx,
12898 )
12899 });
12900
12901 editor.update(cx, |editor, cx| {
12902 let autoscroll = match scroll_offset {
12903 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12904 None => Autoscroll::newest(),
12905 };
12906 let nav_history = editor.nav_history.take();
12907 editor.unfold_ranges(&ranges, false, true, cx);
12908 editor.change_selections(Some(autoscroll), cx, |s| {
12909 s.select_ranges(ranges);
12910 });
12911 editor.nav_history = nav_history;
12912 });
12913 }
12914 })
12915 });
12916 }
12917
12918 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12919 let snapshot = self.buffer.read(cx).read(cx);
12920 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12921 Some(
12922 ranges
12923 .iter()
12924 .map(move |range| {
12925 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12926 })
12927 .collect(),
12928 )
12929 }
12930
12931 fn selection_replacement_ranges(
12932 &self,
12933 range: Range<OffsetUtf16>,
12934 cx: &mut AppContext,
12935 ) -> Vec<Range<OffsetUtf16>> {
12936 let selections = self.selections.all::<OffsetUtf16>(cx);
12937 let newest_selection = selections
12938 .iter()
12939 .max_by_key(|selection| selection.id)
12940 .unwrap();
12941 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12942 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12943 let snapshot = self.buffer.read(cx).read(cx);
12944 selections
12945 .into_iter()
12946 .map(|mut selection| {
12947 selection.start.0 =
12948 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12949 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12950 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12951 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12952 })
12953 .collect()
12954 }
12955
12956 fn report_editor_event(
12957 &self,
12958 operation: &'static str,
12959 file_extension: Option<String>,
12960 cx: &AppContext,
12961 ) {
12962 if cfg!(any(test, feature = "test-support")) {
12963 return;
12964 }
12965
12966 let Some(project) = &self.project else { return };
12967
12968 // If None, we are in a file without an extension
12969 let file = self
12970 .buffer
12971 .read(cx)
12972 .as_singleton()
12973 .and_then(|b| b.read(cx).file());
12974 let file_extension = file_extension.or(file
12975 .as_ref()
12976 .and_then(|file| Path::new(file.file_name(cx)).extension())
12977 .and_then(|e| e.to_str())
12978 .map(|a| a.to_string()));
12979
12980 let vim_mode = cx
12981 .global::<SettingsStore>()
12982 .raw_user_settings()
12983 .get("vim_mode")
12984 == Some(&serde_json::Value::Bool(true));
12985
12986 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12987 == language::language_settings::InlineCompletionProvider::Copilot;
12988 let copilot_enabled_for_language = self
12989 .buffer
12990 .read(cx)
12991 .settings_at(0, cx)
12992 .show_inline_completions;
12993
12994 let project = project.read(cx);
12995 let telemetry = project.client().telemetry().clone();
12996 telemetry.report_editor_event(
12997 file_extension,
12998 vim_mode,
12999 operation,
13000 copilot_enabled,
13001 copilot_enabled_for_language,
13002 project.is_via_ssh(),
13003 )
13004 }
13005
13006 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13007 /// with each line being an array of {text, highlight} objects.
13008 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13009 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13010 return;
13011 };
13012
13013 #[derive(Serialize)]
13014 struct Chunk<'a> {
13015 text: String,
13016 highlight: Option<&'a str>,
13017 }
13018
13019 let snapshot = buffer.read(cx).snapshot();
13020 let range = self
13021 .selected_text_range(false, cx)
13022 .and_then(|selection| {
13023 if selection.range.is_empty() {
13024 None
13025 } else {
13026 Some(selection.range)
13027 }
13028 })
13029 .unwrap_or_else(|| 0..snapshot.len());
13030
13031 let chunks = snapshot.chunks(range, true);
13032 let mut lines = Vec::new();
13033 let mut line: VecDeque<Chunk> = VecDeque::new();
13034
13035 let Some(style) = self.style.as_ref() else {
13036 return;
13037 };
13038
13039 for chunk in chunks {
13040 let highlight = chunk
13041 .syntax_highlight_id
13042 .and_then(|id| id.name(&style.syntax));
13043 let mut chunk_lines = chunk.text.split('\n').peekable();
13044 while let Some(text) = chunk_lines.next() {
13045 let mut merged_with_last_token = false;
13046 if let Some(last_token) = line.back_mut() {
13047 if last_token.highlight == highlight {
13048 last_token.text.push_str(text);
13049 merged_with_last_token = true;
13050 }
13051 }
13052
13053 if !merged_with_last_token {
13054 line.push_back(Chunk {
13055 text: text.into(),
13056 highlight,
13057 });
13058 }
13059
13060 if chunk_lines.peek().is_some() {
13061 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13062 line.pop_front();
13063 }
13064 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13065 line.pop_back();
13066 }
13067
13068 lines.push(mem::take(&mut line));
13069 }
13070 }
13071 }
13072
13073 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13074 return;
13075 };
13076 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13077 }
13078
13079 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13080 self.request_autoscroll(Autoscroll::newest(), cx);
13081 let position = self.selections.newest_display(cx).start;
13082 mouse_context_menu::deploy_context_menu(self, None, position, cx);
13083 }
13084
13085 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13086 &self.inlay_hint_cache
13087 }
13088
13089 pub fn replay_insert_event(
13090 &mut self,
13091 text: &str,
13092 relative_utf16_range: Option<Range<isize>>,
13093 cx: &mut ViewContext<Self>,
13094 ) {
13095 if !self.input_enabled {
13096 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13097 return;
13098 }
13099 if let Some(relative_utf16_range) = relative_utf16_range {
13100 let selections = self.selections.all::<OffsetUtf16>(cx);
13101 self.change_selections(None, cx, |s| {
13102 let new_ranges = selections.into_iter().map(|range| {
13103 let start = OffsetUtf16(
13104 range
13105 .head()
13106 .0
13107 .saturating_add_signed(relative_utf16_range.start),
13108 );
13109 let end = OffsetUtf16(
13110 range
13111 .head()
13112 .0
13113 .saturating_add_signed(relative_utf16_range.end),
13114 );
13115 start..end
13116 });
13117 s.select_ranges(new_ranges);
13118 });
13119 }
13120
13121 self.handle_input(text, cx);
13122 }
13123
13124 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13125 let Some(provider) = self.semantics_provider.as_ref() else {
13126 return false;
13127 };
13128
13129 let mut supports = false;
13130 self.buffer().read(cx).for_each_buffer(|buffer| {
13131 supports |= provider.supports_inlay_hints(buffer, cx);
13132 });
13133 supports
13134 }
13135
13136 pub fn focus(&self, cx: &mut WindowContext) {
13137 cx.focus(&self.focus_handle)
13138 }
13139
13140 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13141 self.focus_handle.is_focused(cx)
13142 }
13143
13144 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13145 cx.emit(EditorEvent::Focused);
13146
13147 if let Some(descendant) = self
13148 .last_focused_descendant
13149 .take()
13150 .and_then(|descendant| descendant.upgrade())
13151 {
13152 cx.focus(&descendant);
13153 } else {
13154 if let Some(blame) = self.blame.as_ref() {
13155 blame.update(cx, GitBlame::focus)
13156 }
13157
13158 self.blink_manager.update(cx, BlinkManager::enable);
13159 self.show_cursor_names(cx);
13160 self.buffer.update(cx, |buffer, cx| {
13161 buffer.finalize_last_transaction(cx);
13162 if self.leader_peer_id.is_none() {
13163 buffer.set_active_selections(
13164 &self.selections.disjoint_anchors(),
13165 self.selections.line_mode,
13166 self.cursor_shape,
13167 cx,
13168 );
13169 }
13170 });
13171 }
13172 }
13173
13174 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13175 cx.emit(EditorEvent::FocusedIn)
13176 }
13177
13178 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13179 if event.blurred != self.focus_handle {
13180 self.last_focused_descendant = Some(event.blurred);
13181 }
13182 }
13183
13184 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13185 self.blink_manager.update(cx, BlinkManager::disable);
13186 self.buffer
13187 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13188
13189 if let Some(blame) = self.blame.as_ref() {
13190 blame.update(cx, GitBlame::blur)
13191 }
13192 if !self.hover_state.focused(cx) {
13193 hide_hover(self, cx);
13194 }
13195
13196 self.hide_context_menu(cx);
13197 cx.emit(EditorEvent::Blurred);
13198 cx.notify();
13199 }
13200
13201 pub fn register_action<A: Action>(
13202 &mut self,
13203 listener: impl Fn(&A, &mut WindowContext) + 'static,
13204 ) -> Subscription {
13205 let id = self.next_editor_action_id.post_inc();
13206 let listener = Arc::new(listener);
13207 self.editor_actions.borrow_mut().insert(
13208 id,
13209 Box::new(move |cx| {
13210 let cx = cx.window_context();
13211 let listener = listener.clone();
13212 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13213 let action = action.downcast_ref().unwrap();
13214 if phase == DispatchPhase::Bubble {
13215 listener(action, cx)
13216 }
13217 })
13218 }),
13219 );
13220
13221 let editor_actions = self.editor_actions.clone();
13222 Subscription::new(move || {
13223 editor_actions.borrow_mut().remove(&id);
13224 })
13225 }
13226
13227 pub fn file_header_size(&self) -> u32 {
13228 FILE_HEADER_HEIGHT
13229 }
13230
13231 pub fn revert(
13232 &mut self,
13233 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13234 cx: &mut ViewContext<Self>,
13235 ) {
13236 self.buffer().update(cx, |multi_buffer, cx| {
13237 for (buffer_id, changes) in revert_changes {
13238 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13239 buffer.update(cx, |buffer, cx| {
13240 buffer.edit(
13241 changes.into_iter().map(|(range, text)| {
13242 (range, text.to_string().map(Arc::<str>::from))
13243 }),
13244 None,
13245 cx,
13246 );
13247 });
13248 }
13249 }
13250 });
13251 self.change_selections(None, cx, |selections| selections.refresh());
13252 }
13253
13254 pub fn to_pixel_point(
13255 &mut self,
13256 source: multi_buffer::Anchor,
13257 editor_snapshot: &EditorSnapshot,
13258 cx: &mut ViewContext<Self>,
13259 ) -> Option<gpui::Point<Pixels>> {
13260 let source_point = source.to_display_point(editor_snapshot);
13261 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13262 }
13263
13264 pub fn display_to_pixel_point(
13265 &mut self,
13266 source: DisplayPoint,
13267 editor_snapshot: &EditorSnapshot,
13268 cx: &mut ViewContext<Self>,
13269 ) -> Option<gpui::Point<Pixels>> {
13270 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13271 let text_layout_details = self.text_layout_details(cx);
13272 let scroll_top = text_layout_details
13273 .scroll_anchor
13274 .scroll_position(editor_snapshot)
13275 .y;
13276
13277 if source.row().as_f32() < scroll_top.floor() {
13278 return None;
13279 }
13280 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13281 let source_y = line_height * (source.row().as_f32() - scroll_top);
13282 Some(gpui::Point::new(source_x, source_y))
13283 }
13284
13285 pub fn has_active_completions_menu(&self) -> bool {
13286 self.context_menu.read().as_ref().map_or(false, |menu| {
13287 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13288 })
13289 }
13290
13291 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13292 self.addons
13293 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13294 }
13295
13296 pub fn unregister_addon<T: Addon>(&mut self) {
13297 self.addons.remove(&std::any::TypeId::of::<T>());
13298 }
13299
13300 pub fn addon<T: Addon>(&self) -> Option<&T> {
13301 let type_id = std::any::TypeId::of::<T>();
13302 self.addons
13303 .get(&type_id)
13304 .and_then(|item| item.to_any().downcast_ref::<T>())
13305 }
13306
13307 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13308 let text_layout_details = self.text_layout_details(cx);
13309 let style = &text_layout_details.editor_style;
13310 let font_id = cx.text_system().resolve_font(&style.text.font());
13311 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13312 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13313
13314 let em_width = cx
13315 .text_system()
13316 .typographic_bounds(font_id, font_size, 'm')
13317 .unwrap()
13318 .size
13319 .width;
13320
13321 gpui::Point::new(em_width, line_height)
13322 }
13323}
13324
13325fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13326 let tab_size = tab_size.get() as usize;
13327 let mut width = offset;
13328
13329 for ch in text.chars() {
13330 width += if ch == '\t' {
13331 tab_size - (width % tab_size)
13332 } else {
13333 1
13334 };
13335 }
13336
13337 width - offset
13338}
13339
13340#[cfg(test)]
13341mod tests {
13342 use super::*;
13343
13344 #[test]
13345 fn test_string_size_with_expanded_tabs() {
13346 let nz = |val| NonZeroU32::new(val).unwrap();
13347 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13348 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13349 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13350 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13351 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13352 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13353 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13354 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13355 }
13356}
13357
13358/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13359struct WordBreakingTokenizer<'a> {
13360 input: &'a str,
13361}
13362
13363impl<'a> WordBreakingTokenizer<'a> {
13364 fn new(input: &'a str) -> Self {
13365 Self { input }
13366 }
13367}
13368
13369fn is_char_ideographic(ch: char) -> bool {
13370 use unicode_script::Script::*;
13371 use unicode_script::UnicodeScript;
13372 matches!(ch.script(), Han | Tangut | Yi)
13373}
13374
13375fn is_grapheme_ideographic(text: &str) -> bool {
13376 text.chars().any(is_char_ideographic)
13377}
13378
13379fn is_grapheme_whitespace(text: &str) -> bool {
13380 text.chars().any(|x| x.is_whitespace())
13381}
13382
13383fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13384 text.chars().next().map_or(false, |ch| {
13385 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13386 })
13387}
13388
13389#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13390struct WordBreakToken<'a> {
13391 token: &'a str,
13392 grapheme_len: usize,
13393 is_whitespace: bool,
13394}
13395
13396impl<'a> Iterator for WordBreakingTokenizer<'a> {
13397 /// Yields a span, the count of graphemes in the token, and whether it was
13398 /// whitespace. Note that it also breaks at word boundaries.
13399 type Item = WordBreakToken<'a>;
13400
13401 fn next(&mut self) -> Option<Self::Item> {
13402 use unicode_segmentation::UnicodeSegmentation;
13403 if self.input.is_empty() {
13404 return None;
13405 }
13406
13407 let mut iter = self.input.graphemes(true).peekable();
13408 let mut offset = 0;
13409 let mut graphemes = 0;
13410 if let Some(first_grapheme) = iter.next() {
13411 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13412 offset += first_grapheme.len();
13413 graphemes += 1;
13414 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13415 if let Some(grapheme) = iter.peek().copied() {
13416 if should_stay_with_preceding_ideograph(grapheme) {
13417 offset += grapheme.len();
13418 graphemes += 1;
13419 }
13420 }
13421 } else {
13422 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13423 let mut next_word_bound = words.peek().copied();
13424 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13425 next_word_bound = words.next();
13426 }
13427 while let Some(grapheme) = iter.peek().copied() {
13428 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13429 break;
13430 };
13431 if is_grapheme_whitespace(grapheme) != is_whitespace {
13432 break;
13433 };
13434 offset += grapheme.len();
13435 graphemes += 1;
13436 iter.next();
13437 }
13438 }
13439 let token = &self.input[..offset];
13440 self.input = &self.input[offset..];
13441 if is_whitespace {
13442 Some(WordBreakToken {
13443 token: " ",
13444 grapheme_len: 1,
13445 is_whitespace: true,
13446 })
13447 } else {
13448 Some(WordBreakToken {
13449 token,
13450 grapheme_len: graphemes,
13451 is_whitespace: false,
13452 })
13453 }
13454 } else {
13455 None
13456 }
13457 }
13458}
13459
13460#[test]
13461fn test_word_breaking_tokenizer() {
13462 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13463 ("", &[]),
13464 (" ", &[(" ", 1, true)]),
13465 ("Ʒ", &[("Ʒ", 1, false)]),
13466 ("Ǽ", &[("Ǽ", 1, false)]),
13467 ("⋑", &[("⋑", 1, false)]),
13468 ("⋑⋑", &[("⋑⋑", 2, false)]),
13469 (
13470 "原理,进而",
13471 &[
13472 ("原", 1, false),
13473 ("理,", 2, false),
13474 ("进", 1, false),
13475 ("而", 1, false),
13476 ],
13477 ),
13478 (
13479 "hello world",
13480 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13481 ),
13482 (
13483 "hello, world",
13484 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13485 ),
13486 (
13487 " hello world",
13488 &[
13489 (" ", 1, true),
13490 ("hello", 5, false),
13491 (" ", 1, true),
13492 ("world", 5, false),
13493 ],
13494 ),
13495 (
13496 "这是什么 \n 钢笔",
13497 &[
13498 ("这", 1, false),
13499 ("是", 1, false),
13500 ("什", 1, false),
13501 ("么", 1, false),
13502 (" ", 1, true),
13503 ("钢", 1, false),
13504 ("笔", 1, false),
13505 ],
13506 ),
13507 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13508 ];
13509
13510 for (input, result) in tests {
13511 assert_eq!(
13512 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13513 result
13514 .iter()
13515 .copied()
13516 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13517 token,
13518 grapheme_len,
13519 is_whitespace,
13520 })
13521 .collect::<Vec<_>>()
13522 );
13523 }
13524}
13525
13526fn wrap_with_prefix(
13527 line_prefix: String,
13528 unwrapped_text: String,
13529 wrap_column: usize,
13530 tab_size: NonZeroU32,
13531) -> String {
13532 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13533 let mut wrapped_text = String::new();
13534 let mut current_line = line_prefix.clone();
13535
13536 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13537 let mut current_line_len = line_prefix_len;
13538 for WordBreakToken {
13539 token,
13540 grapheme_len,
13541 is_whitespace,
13542 } in tokenizer
13543 {
13544 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13545 wrapped_text.push_str(current_line.trim_end());
13546 wrapped_text.push('\n');
13547 current_line.truncate(line_prefix.len());
13548 current_line_len = line_prefix_len;
13549 if !is_whitespace {
13550 current_line.push_str(token);
13551 current_line_len += grapheme_len;
13552 }
13553 } else if !is_whitespace {
13554 current_line.push_str(token);
13555 current_line_len += grapheme_len;
13556 } else if current_line_len != line_prefix_len {
13557 current_line.push(' ');
13558 current_line_len += 1;
13559 }
13560 }
13561
13562 if !current_line.is_empty() {
13563 wrapped_text.push_str(¤t_line);
13564 }
13565 wrapped_text
13566}
13567
13568#[test]
13569fn test_wrap_with_prefix() {
13570 assert_eq!(
13571 wrap_with_prefix(
13572 "# ".to_string(),
13573 "abcdefg".to_string(),
13574 4,
13575 NonZeroU32::new(4).unwrap()
13576 ),
13577 "# abcdefg"
13578 );
13579 assert_eq!(
13580 wrap_with_prefix(
13581 "".to_string(),
13582 "\thello world".to_string(),
13583 8,
13584 NonZeroU32::new(4).unwrap()
13585 ),
13586 "hello\nworld"
13587 );
13588 assert_eq!(
13589 wrap_with_prefix(
13590 "// ".to_string(),
13591 "xx \nyy zz aa bb cc".to_string(),
13592 12,
13593 NonZeroU32::new(4).unwrap()
13594 ),
13595 "// xx yy zz\n// aa bb cc"
13596 );
13597 assert_eq!(
13598 wrap_with_prefix(
13599 String::new(),
13600 "这是什么 \n 钢笔".to_string(),
13601 3,
13602 NonZeroU32::new(4).unwrap()
13603 ),
13604 "这是什\n么 钢\n笔"
13605 );
13606}
13607
13608fn hunks_for_selections(
13609 multi_buffer_snapshot: &MultiBufferSnapshot,
13610 selections: &[Selection<Anchor>],
13611) -> Vec<MultiBufferDiffHunk> {
13612 let buffer_rows_for_selections = selections.iter().map(|selection| {
13613 let head = selection.head();
13614 let tail = selection.tail();
13615 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13616 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13617 if start > end {
13618 end..start
13619 } else {
13620 start..end
13621 }
13622 });
13623
13624 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13625}
13626
13627pub fn hunks_for_rows(
13628 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13629 multi_buffer_snapshot: &MultiBufferSnapshot,
13630) -> Vec<MultiBufferDiffHunk> {
13631 let mut hunks = Vec::new();
13632 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13633 HashMap::default();
13634 for selected_multi_buffer_rows in rows {
13635 let query_rows =
13636 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13637 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13638 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13639 // when the caret is just above or just below the deleted hunk.
13640 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13641 let related_to_selection = if allow_adjacent {
13642 hunk.row_range.overlaps(&query_rows)
13643 || hunk.row_range.start == query_rows.end
13644 || hunk.row_range.end == query_rows.start
13645 } else {
13646 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13647 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13648 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13649 || selected_multi_buffer_rows.end == hunk.row_range.start
13650 };
13651 if related_to_selection {
13652 if !processed_buffer_rows
13653 .entry(hunk.buffer_id)
13654 .or_default()
13655 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13656 {
13657 continue;
13658 }
13659 hunks.push(hunk);
13660 }
13661 }
13662 }
13663
13664 hunks
13665}
13666
13667pub trait CollaborationHub {
13668 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13669 fn user_participant_indices<'a>(
13670 &self,
13671 cx: &'a AppContext,
13672 ) -> &'a HashMap<u64, ParticipantIndex>;
13673 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13674}
13675
13676impl CollaborationHub for Model<Project> {
13677 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13678 self.read(cx).collaborators()
13679 }
13680
13681 fn user_participant_indices<'a>(
13682 &self,
13683 cx: &'a AppContext,
13684 ) -> &'a HashMap<u64, ParticipantIndex> {
13685 self.read(cx).user_store().read(cx).participant_indices()
13686 }
13687
13688 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13689 let this = self.read(cx);
13690 let user_ids = this.collaborators().values().map(|c| c.user_id);
13691 this.user_store().read_with(cx, |user_store, cx| {
13692 user_store.participant_names(user_ids, cx)
13693 })
13694 }
13695}
13696
13697pub trait SemanticsProvider {
13698 fn hover(
13699 &self,
13700 buffer: &Model<Buffer>,
13701 position: text::Anchor,
13702 cx: &mut AppContext,
13703 ) -> Option<Task<Vec<project::Hover>>>;
13704
13705 fn inlay_hints(
13706 &self,
13707 buffer_handle: Model<Buffer>,
13708 range: Range<text::Anchor>,
13709 cx: &mut AppContext,
13710 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13711
13712 fn resolve_inlay_hint(
13713 &self,
13714 hint: InlayHint,
13715 buffer_handle: Model<Buffer>,
13716 server_id: LanguageServerId,
13717 cx: &mut AppContext,
13718 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13719
13720 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13721
13722 fn document_highlights(
13723 &self,
13724 buffer: &Model<Buffer>,
13725 position: text::Anchor,
13726 cx: &mut AppContext,
13727 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13728
13729 fn definitions(
13730 &self,
13731 buffer: &Model<Buffer>,
13732 position: text::Anchor,
13733 kind: GotoDefinitionKind,
13734 cx: &mut AppContext,
13735 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13736
13737 fn range_for_rename(
13738 &self,
13739 buffer: &Model<Buffer>,
13740 position: text::Anchor,
13741 cx: &mut AppContext,
13742 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13743
13744 fn perform_rename(
13745 &self,
13746 buffer: &Model<Buffer>,
13747 position: text::Anchor,
13748 new_name: String,
13749 cx: &mut AppContext,
13750 ) -> Option<Task<Result<ProjectTransaction>>>;
13751}
13752
13753pub trait CompletionProvider {
13754 fn completions(
13755 &self,
13756 buffer: &Model<Buffer>,
13757 buffer_position: text::Anchor,
13758 trigger: CompletionContext,
13759 cx: &mut ViewContext<Editor>,
13760 ) -> Task<Result<Vec<Completion>>>;
13761
13762 fn resolve_completions(
13763 &self,
13764 buffer: Model<Buffer>,
13765 completion_indices: Vec<usize>,
13766 completions: Arc<RwLock<Box<[Completion]>>>,
13767 cx: &mut ViewContext<Editor>,
13768 ) -> Task<Result<bool>>;
13769
13770 fn apply_additional_edits_for_completion(
13771 &self,
13772 buffer: Model<Buffer>,
13773 completion: Completion,
13774 push_to_history: bool,
13775 cx: &mut ViewContext<Editor>,
13776 ) -> Task<Result<Option<language::Transaction>>>;
13777
13778 fn is_completion_trigger(
13779 &self,
13780 buffer: &Model<Buffer>,
13781 position: language::Anchor,
13782 text: &str,
13783 trigger_in_words: bool,
13784 cx: &mut ViewContext<Editor>,
13785 ) -> bool;
13786
13787 fn sort_completions(&self) -> bool {
13788 true
13789 }
13790}
13791
13792pub trait CodeActionProvider {
13793 fn code_actions(
13794 &self,
13795 buffer: &Model<Buffer>,
13796 range: Range<text::Anchor>,
13797 cx: &mut WindowContext,
13798 ) -> Task<Result<Vec<CodeAction>>>;
13799
13800 fn apply_code_action(
13801 &self,
13802 buffer_handle: Model<Buffer>,
13803 action: CodeAction,
13804 excerpt_id: ExcerptId,
13805 push_to_history: bool,
13806 cx: &mut WindowContext,
13807 ) -> Task<Result<ProjectTransaction>>;
13808}
13809
13810impl CodeActionProvider for Model<Project> {
13811 fn code_actions(
13812 &self,
13813 buffer: &Model<Buffer>,
13814 range: Range<text::Anchor>,
13815 cx: &mut WindowContext,
13816 ) -> Task<Result<Vec<CodeAction>>> {
13817 self.update(cx, |project, cx| {
13818 project.code_actions(buffer, range, None, cx)
13819 })
13820 }
13821
13822 fn apply_code_action(
13823 &self,
13824 buffer_handle: Model<Buffer>,
13825 action: CodeAction,
13826 _excerpt_id: ExcerptId,
13827 push_to_history: bool,
13828 cx: &mut WindowContext,
13829 ) -> Task<Result<ProjectTransaction>> {
13830 self.update(cx, |project, cx| {
13831 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13832 })
13833 }
13834}
13835
13836fn snippet_completions(
13837 project: &Project,
13838 buffer: &Model<Buffer>,
13839 buffer_position: text::Anchor,
13840 cx: &mut AppContext,
13841) -> Task<Result<Vec<Completion>>> {
13842 let language = buffer.read(cx).language_at(buffer_position);
13843 let language_name = language.as_ref().map(|language| language.lsp_id());
13844 let snippet_store = project.snippets().read(cx);
13845 let snippets = snippet_store.snippets_for(language_name, cx);
13846
13847 if snippets.is_empty() {
13848 return Task::ready(Ok(vec![]));
13849 }
13850 let snapshot = buffer.read(cx).text_snapshot();
13851 let chars: String = snapshot
13852 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13853 .collect();
13854
13855 let scope = language.map(|language| language.default_scope());
13856 let executor = cx.background_executor().clone();
13857
13858 cx.background_executor().spawn(async move {
13859 let classifier = CharClassifier::new(scope).for_completion(true);
13860 let mut last_word = chars
13861 .chars()
13862 .take_while(|c| classifier.is_word(*c))
13863 .collect::<String>();
13864 last_word = last_word.chars().rev().collect();
13865 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13866 let to_lsp = |point: &text::Anchor| {
13867 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13868 point_to_lsp(end)
13869 };
13870 let lsp_end = to_lsp(&buffer_position);
13871
13872 let candidates = snippets
13873 .iter()
13874 .enumerate()
13875 .flat_map(|(ix, snippet)| {
13876 snippet
13877 .prefix
13878 .iter()
13879 .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13880 })
13881 .collect::<Vec<StringMatchCandidate>>();
13882
13883 let mut matches = fuzzy::match_strings(
13884 &candidates,
13885 &last_word,
13886 last_word.chars().any(|c| c.is_uppercase()),
13887 100,
13888 &Default::default(),
13889 executor,
13890 )
13891 .await;
13892
13893 // Remove all candidates where the query's start does not match the start of any word in the candidate
13894 if let Some(query_start) = last_word.chars().next() {
13895 matches.retain(|string_match| {
13896 split_words(&string_match.string).any(|word| {
13897 // Check that the first codepoint of the word as lowercase matches the first
13898 // codepoint of the query as lowercase
13899 word.chars()
13900 .flat_map(|codepoint| codepoint.to_lowercase())
13901 .zip(query_start.to_lowercase())
13902 .all(|(word_cp, query_cp)| word_cp == query_cp)
13903 })
13904 });
13905 }
13906
13907 let matched_strings = matches
13908 .into_iter()
13909 .map(|m| m.string)
13910 .collect::<HashSet<_>>();
13911
13912 let result: Vec<Completion> = snippets
13913 .into_iter()
13914 .filter_map(|snippet| {
13915 let matching_prefix = snippet
13916 .prefix
13917 .iter()
13918 .find(|prefix| matched_strings.contains(*prefix))?;
13919 let start = as_offset - last_word.len();
13920 let start = snapshot.anchor_before(start);
13921 let range = start..buffer_position;
13922 let lsp_start = to_lsp(&start);
13923 let lsp_range = lsp::Range {
13924 start: lsp_start,
13925 end: lsp_end,
13926 };
13927 Some(Completion {
13928 old_range: range,
13929 new_text: snippet.body.clone(),
13930 label: CodeLabel {
13931 text: matching_prefix.clone(),
13932 runs: vec![],
13933 filter_range: 0..matching_prefix.len(),
13934 },
13935 server_id: LanguageServerId(usize::MAX),
13936 documentation: snippet.description.clone().map(Documentation::SingleLine),
13937 lsp_completion: lsp::CompletionItem {
13938 label: snippet.prefix.first().unwrap().clone(),
13939 kind: Some(CompletionItemKind::SNIPPET),
13940 label_details: snippet.description.as_ref().map(|description| {
13941 lsp::CompletionItemLabelDetails {
13942 detail: Some(description.clone()),
13943 description: None,
13944 }
13945 }),
13946 insert_text_format: Some(InsertTextFormat::SNIPPET),
13947 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13948 lsp::InsertReplaceEdit {
13949 new_text: snippet.body.clone(),
13950 insert: lsp_range,
13951 replace: lsp_range,
13952 },
13953 )),
13954 filter_text: Some(snippet.body.clone()),
13955 sort_text: Some(char::MAX.to_string()),
13956 ..Default::default()
13957 },
13958 confirm: None,
13959 })
13960 })
13961 .collect();
13962
13963 Ok(result)
13964 })
13965}
13966
13967impl CompletionProvider for Model<Project> {
13968 fn completions(
13969 &self,
13970 buffer: &Model<Buffer>,
13971 buffer_position: text::Anchor,
13972 options: CompletionContext,
13973 cx: &mut ViewContext<Editor>,
13974 ) -> Task<Result<Vec<Completion>>> {
13975 self.update(cx, |project, cx| {
13976 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13977 let project_completions = project.completions(buffer, buffer_position, options, cx);
13978 cx.background_executor().spawn(async move {
13979 let mut completions = project_completions.await?;
13980 let snippets_completions = snippets.await?;
13981 completions.extend(snippets_completions);
13982 Ok(completions)
13983 })
13984 })
13985 }
13986
13987 fn resolve_completions(
13988 &self,
13989 buffer: Model<Buffer>,
13990 completion_indices: Vec<usize>,
13991 completions: Arc<RwLock<Box<[Completion]>>>,
13992 cx: &mut ViewContext<Editor>,
13993 ) -> Task<Result<bool>> {
13994 self.update(cx, |project, cx| {
13995 project.resolve_completions(buffer, completion_indices, completions, cx)
13996 })
13997 }
13998
13999 fn apply_additional_edits_for_completion(
14000 &self,
14001 buffer: Model<Buffer>,
14002 completion: Completion,
14003 push_to_history: bool,
14004 cx: &mut ViewContext<Editor>,
14005 ) -> Task<Result<Option<language::Transaction>>> {
14006 self.update(cx, |project, cx| {
14007 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
14008 })
14009 }
14010
14011 fn is_completion_trigger(
14012 &self,
14013 buffer: &Model<Buffer>,
14014 position: language::Anchor,
14015 text: &str,
14016 trigger_in_words: bool,
14017 cx: &mut ViewContext<Editor>,
14018 ) -> bool {
14019 if !EditorSettings::get_global(cx).show_completions_on_input {
14020 return false;
14021 }
14022
14023 let mut chars = text.chars();
14024 let char = if let Some(char) = chars.next() {
14025 char
14026 } else {
14027 return false;
14028 };
14029 if chars.next().is_some() {
14030 return false;
14031 }
14032
14033 let buffer = buffer.read(cx);
14034 let classifier = buffer
14035 .snapshot()
14036 .char_classifier_at(position)
14037 .for_completion(true);
14038 if trigger_in_words && classifier.is_word(char) {
14039 return true;
14040 }
14041
14042 buffer.completion_triggers().contains(text)
14043 }
14044}
14045
14046impl SemanticsProvider for Model<Project> {
14047 fn hover(
14048 &self,
14049 buffer: &Model<Buffer>,
14050 position: text::Anchor,
14051 cx: &mut AppContext,
14052 ) -> Option<Task<Vec<project::Hover>>> {
14053 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14054 }
14055
14056 fn document_highlights(
14057 &self,
14058 buffer: &Model<Buffer>,
14059 position: text::Anchor,
14060 cx: &mut AppContext,
14061 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14062 Some(self.update(cx, |project, cx| {
14063 project.document_highlights(buffer, position, cx)
14064 }))
14065 }
14066
14067 fn definitions(
14068 &self,
14069 buffer: &Model<Buffer>,
14070 position: text::Anchor,
14071 kind: GotoDefinitionKind,
14072 cx: &mut AppContext,
14073 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14074 Some(self.update(cx, |project, cx| match kind {
14075 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14076 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14077 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14078 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14079 }))
14080 }
14081
14082 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14083 // TODO: make this work for remote projects
14084 self.read(cx)
14085 .language_servers_for_buffer(buffer.read(cx), cx)
14086 .any(
14087 |(_, server)| match server.capabilities().inlay_hint_provider {
14088 Some(lsp::OneOf::Left(enabled)) => enabled,
14089 Some(lsp::OneOf::Right(_)) => true,
14090 None => false,
14091 },
14092 )
14093 }
14094
14095 fn inlay_hints(
14096 &self,
14097 buffer_handle: Model<Buffer>,
14098 range: Range<text::Anchor>,
14099 cx: &mut AppContext,
14100 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14101 Some(self.update(cx, |project, cx| {
14102 project.inlay_hints(buffer_handle, range, cx)
14103 }))
14104 }
14105
14106 fn resolve_inlay_hint(
14107 &self,
14108 hint: InlayHint,
14109 buffer_handle: Model<Buffer>,
14110 server_id: LanguageServerId,
14111 cx: &mut AppContext,
14112 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14113 Some(self.update(cx, |project, cx| {
14114 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14115 }))
14116 }
14117
14118 fn range_for_rename(
14119 &self,
14120 buffer: &Model<Buffer>,
14121 position: text::Anchor,
14122 cx: &mut AppContext,
14123 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14124 Some(self.update(cx, |project, cx| {
14125 project.prepare_rename(buffer.clone(), position, cx)
14126 }))
14127 }
14128
14129 fn perform_rename(
14130 &self,
14131 buffer: &Model<Buffer>,
14132 position: text::Anchor,
14133 new_name: String,
14134 cx: &mut AppContext,
14135 ) -> Option<Task<Result<ProjectTransaction>>> {
14136 Some(self.update(cx, |project, cx| {
14137 project.perform_rename(buffer.clone(), position, new_name, cx)
14138 }))
14139 }
14140}
14141
14142fn inlay_hint_settings(
14143 location: Anchor,
14144 snapshot: &MultiBufferSnapshot,
14145 cx: &mut ViewContext<'_, Editor>,
14146) -> InlayHintSettings {
14147 let file = snapshot.file_at(location);
14148 let language = snapshot.language_at(location).map(|l| l.name());
14149 language_settings(language, file, cx).inlay_hints
14150}
14151
14152fn consume_contiguous_rows(
14153 contiguous_row_selections: &mut Vec<Selection<Point>>,
14154 selection: &Selection<Point>,
14155 display_map: &DisplaySnapshot,
14156 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14157) -> (MultiBufferRow, MultiBufferRow) {
14158 contiguous_row_selections.push(selection.clone());
14159 let start_row = MultiBufferRow(selection.start.row);
14160 let mut end_row = ending_row(selection, display_map);
14161
14162 while let Some(next_selection) = selections.peek() {
14163 if next_selection.start.row <= end_row.0 {
14164 end_row = ending_row(next_selection, display_map);
14165 contiguous_row_selections.push(selections.next().unwrap().clone());
14166 } else {
14167 break;
14168 }
14169 }
14170 (start_row, end_row)
14171}
14172
14173fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14174 if next_selection.end.column > 0 || next_selection.is_empty() {
14175 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14176 } else {
14177 MultiBufferRow(next_selection.end.row)
14178 }
14179}
14180
14181impl EditorSnapshot {
14182 pub fn remote_selections_in_range<'a>(
14183 &'a self,
14184 range: &'a Range<Anchor>,
14185 collaboration_hub: &dyn CollaborationHub,
14186 cx: &'a AppContext,
14187 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14188 let participant_names = collaboration_hub.user_names(cx);
14189 let participant_indices = collaboration_hub.user_participant_indices(cx);
14190 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14191 let collaborators_by_replica_id = collaborators_by_peer_id
14192 .iter()
14193 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14194 .collect::<HashMap<_, _>>();
14195 self.buffer_snapshot
14196 .selections_in_range(range, false)
14197 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14198 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14199 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14200 let user_name = participant_names.get(&collaborator.user_id).cloned();
14201 Some(RemoteSelection {
14202 replica_id,
14203 selection,
14204 cursor_shape,
14205 line_mode,
14206 participant_index,
14207 peer_id: collaborator.peer_id,
14208 user_name,
14209 })
14210 })
14211 }
14212
14213 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14214 self.display_snapshot.buffer_snapshot.language_at(position)
14215 }
14216
14217 pub fn is_focused(&self) -> bool {
14218 self.is_focused
14219 }
14220
14221 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14222 self.placeholder_text.as_ref()
14223 }
14224
14225 pub fn scroll_position(&self) -> gpui::Point<f32> {
14226 self.scroll_anchor.scroll_position(&self.display_snapshot)
14227 }
14228
14229 fn gutter_dimensions(
14230 &self,
14231 font_id: FontId,
14232 font_size: Pixels,
14233 em_width: Pixels,
14234 em_advance: Pixels,
14235 max_line_number_width: Pixels,
14236 cx: &AppContext,
14237 ) -> GutterDimensions {
14238 if !self.show_gutter {
14239 return GutterDimensions::default();
14240 }
14241 let descent = cx.text_system().descent(font_id, font_size);
14242
14243 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14244 matches!(
14245 ProjectSettings::get_global(cx).git.git_gutter,
14246 Some(GitGutterSetting::TrackedFiles)
14247 )
14248 });
14249 let gutter_settings = EditorSettings::get_global(cx).gutter;
14250 let show_line_numbers = self
14251 .show_line_numbers
14252 .unwrap_or(gutter_settings.line_numbers);
14253 let line_gutter_width = if show_line_numbers {
14254 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14255 let min_width_for_number_on_gutter = em_advance * 4.0;
14256 max_line_number_width.max(min_width_for_number_on_gutter)
14257 } else {
14258 0.0.into()
14259 };
14260
14261 let show_code_actions = self
14262 .show_code_actions
14263 .unwrap_or(gutter_settings.code_actions);
14264
14265 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14266
14267 let git_blame_entries_width =
14268 self.git_blame_gutter_max_author_length
14269 .map(|max_author_length| {
14270 // Length of the author name, but also space for the commit hash,
14271 // the spacing and the timestamp.
14272 let max_char_count = max_author_length
14273 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14274 + 7 // length of commit sha
14275 + 14 // length of max relative timestamp ("60 minutes ago")
14276 + 4; // gaps and margins
14277
14278 em_advance * max_char_count
14279 });
14280
14281 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14282 left_padding += if show_code_actions || show_runnables {
14283 em_width * 3.0
14284 } else if show_git_gutter && show_line_numbers {
14285 em_width * 2.0
14286 } else if show_git_gutter || show_line_numbers {
14287 em_width
14288 } else {
14289 px(0.)
14290 };
14291
14292 let right_padding = if gutter_settings.folds && show_line_numbers {
14293 em_width * 4.0
14294 } else if gutter_settings.folds {
14295 em_width * 3.0
14296 } else if show_line_numbers {
14297 em_width
14298 } else {
14299 px(0.)
14300 };
14301
14302 GutterDimensions {
14303 left_padding,
14304 right_padding,
14305 width: line_gutter_width + left_padding + right_padding,
14306 margin: -descent,
14307 git_blame_entries_width,
14308 }
14309 }
14310
14311 pub fn render_crease_toggle(
14312 &self,
14313 buffer_row: MultiBufferRow,
14314 row_contains_cursor: bool,
14315 editor: View<Editor>,
14316 cx: &mut WindowContext,
14317 ) -> Option<AnyElement> {
14318 let folded = self.is_line_folded(buffer_row);
14319 let mut is_foldable = false;
14320
14321 if let Some(crease) = self
14322 .crease_snapshot
14323 .query_row(buffer_row, &self.buffer_snapshot)
14324 {
14325 is_foldable = true;
14326 match crease {
14327 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14328 if let Some(render_toggle) = render_toggle {
14329 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14330 if folded {
14331 editor.update(cx, |editor, cx| {
14332 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14333 });
14334 } else {
14335 editor.update(cx, |editor, cx| {
14336 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14337 });
14338 }
14339 });
14340 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14341 }
14342 }
14343 }
14344 }
14345
14346 is_foldable |= self.starts_indent(buffer_row);
14347
14348 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14349 Some(
14350 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14351 .selected(folded)
14352 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14353 if folded {
14354 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14355 } else {
14356 this.fold_at(&FoldAt { buffer_row }, cx);
14357 }
14358 }))
14359 .into_any_element(),
14360 )
14361 } else {
14362 None
14363 }
14364 }
14365
14366 pub fn render_crease_trailer(
14367 &self,
14368 buffer_row: MultiBufferRow,
14369 cx: &mut WindowContext,
14370 ) -> Option<AnyElement> {
14371 let folded = self.is_line_folded(buffer_row);
14372 if let Crease::Inline { render_trailer, .. } = self
14373 .crease_snapshot
14374 .query_row(buffer_row, &self.buffer_snapshot)?
14375 {
14376 let render_trailer = render_trailer.as_ref()?;
14377 Some(render_trailer(buffer_row, folded, cx))
14378 } else {
14379 None
14380 }
14381 }
14382}
14383
14384impl Deref for EditorSnapshot {
14385 type Target = DisplaySnapshot;
14386
14387 fn deref(&self) -> &Self::Target {
14388 &self.display_snapshot
14389 }
14390}
14391
14392#[derive(Clone, Debug, PartialEq, Eq)]
14393pub enum EditorEvent {
14394 InputIgnored {
14395 text: Arc<str>,
14396 },
14397 InputHandled {
14398 utf16_range_to_replace: Option<Range<isize>>,
14399 text: Arc<str>,
14400 },
14401 ExcerptsAdded {
14402 buffer: Model<Buffer>,
14403 predecessor: ExcerptId,
14404 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14405 },
14406 ExcerptsRemoved {
14407 ids: Vec<ExcerptId>,
14408 },
14409 ExcerptsEdited {
14410 ids: Vec<ExcerptId>,
14411 },
14412 ExcerptsExpanded {
14413 ids: Vec<ExcerptId>,
14414 },
14415 BufferEdited,
14416 Edited {
14417 transaction_id: clock::Lamport,
14418 },
14419 Reparsed(BufferId),
14420 Focused,
14421 FocusedIn,
14422 Blurred,
14423 DirtyChanged,
14424 Saved,
14425 TitleChanged,
14426 DiffBaseChanged,
14427 SelectionsChanged {
14428 local: bool,
14429 },
14430 ScrollPositionChanged {
14431 local: bool,
14432 autoscroll: bool,
14433 },
14434 Closed,
14435 TransactionUndone {
14436 transaction_id: clock::Lamport,
14437 },
14438 TransactionBegun {
14439 transaction_id: clock::Lamport,
14440 },
14441 Reloaded,
14442 CursorShapeChanged,
14443}
14444
14445impl EventEmitter<EditorEvent> for Editor {}
14446
14447impl FocusableView for Editor {
14448 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14449 self.focus_handle.clone()
14450 }
14451}
14452
14453impl Render for Editor {
14454 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14455 let settings = ThemeSettings::get_global(cx);
14456
14457 let mut text_style = match self.mode {
14458 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14459 color: cx.theme().colors().editor_foreground,
14460 font_family: settings.ui_font.family.clone(),
14461 font_features: settings.ui_font.features.clone(),
14462 font_fallbacks: settings.ui_font.fallbacks.clone(),
14463 font_size: rems(0.875).into(),
14464 font_weight: settings.ui_font.weight,
14465 line_height: relative(settings.buffer_line_height.value()),
14466 ..Default::default()
14467 },
14468 EditorMode::Full => TextStyle {
14469 color: cx.theme().colors().editor_foreground,
14470 font_family: settings.buffer_font.family.clone(),
14471 font_features: settings.buffer_font.features.clone(),
14472 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14473 font_size: settings.buffer_font_size(cx).into(),
14474 font_weight: settings.buffer_font.weight,
14475 line_height: relative(settings.buffer_line_height.value()),
14476 ..Default::default()
14477 },
14478 };
14479 if let Some(text_style_refinement) = &self.text_style_refinement {
14480 text_style.refine(text_style_refinement)
14481 }
14482
14483 let background = match self.mode {
14484 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14485 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14486 EditorMode::Full => cx.theme().colors().editor_background,
14487 };
14488
14489 EditorElement::new(
14490 cx.view(),
14491 EditorStyle {
14492 background,
14493 local_player: cx.theme().players().local(),
14494 text: text_style,
14495 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14496 syntax: cx.theme().syntax().clone(),
14497 status: cx.theme().status().clone(),
14498 inlay_hints_style: make_inlay_hints_style(cx),
14499 suggestions_style: HighlightStyle {
14500 color: Some(cx.theme().status().predictive),
14501 ..HighlightStyle::default()
14502 },
14503 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14504 },
14505 )
14506 }
14507}
14508
14509impl ViewInputHandler for Editor {
14510 fn text_for_range(
14511 &mut self,
14512 range_utf16: Range<usize>,
14513 adjusted_range: &mut Option<Range<usize>>,
14514 cx: &mut ViewContext<Self>,
14515 ) -> Option<String> {
14516 let snapshot = self.buffer.read(cx).read(cx);
14517 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14518 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14519 if (start.0..end.0) != range_utf16 {
14520 adjusted_range.replace(start.0..end.0);
14521 }
14522 Some(snapshot.text_for_range(start..end).collect())
14523 }
14524
14525 fn selected_text_range(
14526 &mut self,
14527 ignore_disabled_input: bool,
14528 cx: &mut ViewContext<Self>,
14529 ) -> Option<UTF16Selection> {
14530 // Prevent the IME menu from appearing when holding down an alphabetic key
14531 // while input is disabled.
14532 if !ignore_disabled_input && !self.input_enabled {
14533 return None;
14534 }
14535
14536 let selection = self.selections.newest::<OffsetUtf16>(cx);
14537 let range = selection.range();
14538
14539 Some(UTF16Selection {
14540 range: range.start.0..range.end.0,
14541 reversed: selection.reversed,
14542 })
14543 }
14544
14545 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14546 let snapshot = self.buffer.read(cx).read(cx);
14547 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14548 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14549 }
14550
14551 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14552 self.clear_highlights::<InputComposition>(cx);
14553 self.ime_transaction.take();
14554 }
14555
14556 fn replace_text_in_range(
14557 &mut self,
14558 range_utf16: Option<Range<usize>>,
14559 text: &str,
14560 cx: &mut ViewContext<Self>,
14561 ) {
14562 if !self.input_enabled {
14563 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14564 return;
14565 }
14566
14567 self.transact(cx, |this, cx| {
14568 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14569 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14570 Some(this.selection_replacement_ranges(range_utf16, cx))
14571 } else {
14572 this.marked_text_ranges(cx)
14573 };
14574
14575 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14576 let newest_selection_id = this.selections.newest_anchor().id;
14577 this.selections
14578 .all::<OffsetUtf16>(cx)
14579 .iter()
14580 .zip(ranges_to_replace.iter())
14581 .find_map(|(selection, range)| {
14582 if selection.id == newest_selection_id {
14583 Some(
14584 (range.start.0 as isize - selection.head().0 as isize)
14585 ..(range.end.0 as isize - selection.head().0 as isize),
14586 )
14587 } else {
14588 None
14589 }
14590 })
14591 });
14592
14593 cx.emit(EditorEvent::InputHandled {
14594 utf16_range_to_replace: range_to_replace,
14595 text: text.into(),
14596 });
14597
14598 if let Some(new_selected_ranges) = new_selected_ranges {
14599 this.change_selections(None, cx, |selections| {
14600 selections.select_ranges(new_selected_ranges)
14601 });
14602 this.backspace(&Default::default(), cx);
14603 }
14604
14605 this.handle_input(text, cx);
14606 });
14607
14608 if let Some(transaction) = self.ime_transaction {
14609 self.buffer.update(cx, |buffer, cx| {
14610 buffer.group_until_transaction(transaction, cx);
14611 });
14612 }
14613
14614 self.unmark_text(cx);
14615 }
14616
14617 fn replace_and_mark_text_in_range(
14618 &mut self,
14619 range_utf16: Option<Range<usize>>,
14620 text: &str,
14621 new_selected_range_utf16: Option<Range<usize>>,
14622 cx: &mut ViewContext<Self>,
14623 ) {
14624 if !self.input_enabled {
14625 return;
14626 }
14627
14628 let transaction = self.transact(cx, |this, cx| {
14629 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14630 let snapshot = this.buffer.read(cx).read(cx);
14631 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14632 for marked_range in &mut marked_ranges {
14633 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14634 marked_range.start.0 += relative_range_utf16.start;
14635 marked_range.start =
14636 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14637 marked_range.end =
14638 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14639 }
14640 }
14641 Some(marked_ranges)
14642 } else if let Some(range_utf16) = range_utf16 {
14643 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14644 Some(this.selection_replacement_ranges(range_utf16, cx))
14645 } else {
14646 None
14647 };
14648
14649 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14650 let newest_selection_id = this.selections.newest_anchor().id;
14651 this.selections
14652 .all::<OffsetUtf16>(cx)
14653 .iter()
14654 .zip(ranges_to_replace.iter())
14655 .find_map(|(selection, range)| {
14656 if selection.id == newest_selection_id {
14657 Some(
14658 (range.start.0 as isize - selection.head().0 as isize)
14659 ..(range.end.0 as isize - selection.head().0 as isize),
14660 )
14661 } else {
14662 None
14663 }
14664 })
14665 });
14666
14667 cx.emit(EditorEvent::InputHandled {
14668 utf16_range_to_replace: range_to_replace,
14669 text: text.into(),
14670 });
14671
14672 if let Some(ranges) = ranges_to_replace {
14673 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14674 }
14675
14676 let marked_ranges = {
14677 let snapshot = this.buffer.read(cx).read(cx);
14678 this.selections
14679 .disjoint_anchors()
14680 .iter()
14681 .map(|selection| {
14682 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14683 })
14684 .collect::<Vec<_>>()
14685 };
14686
14687 if text.is_empty() {
14688 this.unmark_text(cx);
14689 } else {
14690 this.highlight_text::<InputComposition>(
14691 marked_ranges.clone(),
14692 HighlightStyle {
14693 underline: Some(UnderlineStyle {
14694 thickness: px(1.),
14695 color: None,
14696 wavy: false,
14697 }),
14698 ..Default::default()
14699 },
14700 cx,
14701 );
14702 }
14703
14704 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14705 let use_autoclose = this.use_autoclose;
14706 let use_auto_surround = this.use_auto_surround;
14707 this.set_use_autoclose(false);
14708 this.set_use_auto_surround(false);
14709 this.handle_input(text, cx);
14710 this.set_use_autoclose(use_autoclose);
14711 this.set_use_auto_surround(use_auto_surround);
14712
14713 if let Some(new_selected_range) = new_selected_range_utf16 {
14714 let snapshot = this.buffer.read(cx).read(cx);
14715 let new_selected_ranges = marked_ranges
14716 .into_iter()
14717 .map(|marked_range| {
14718 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14719 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14720 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14721 snapshot.clip_offset_utf16(new_start, Bias::Left)
14722 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14723 })
14724 .collect::<Vec<_>>();
14725
14726 drop(snapshot);
14727 this.change_selections(None, cx, |selections| {
14728 selections.select_ranges(new_selected_ranges)
14729 });
14730 }
14731 });
14732
14733 self.ime_transaction = self.ime_transaction.or(transaction);
14734 if let Some(transaction) = self.ime_transaction {
14735 self.buffer.update(cx, |buffer, cx| {
14736 buffer.group_until_transaction(transaction, cx);
14737 });
14738 }
14739
14740 if self.text_highlights::<InputComposition>(cx).is_none() {
14741 self.ime_transaction.take();
14742 }
14743 }
14744
14745 fn bounds_for_range(
14746 &mut self,
14747 range_utf16: Range<usize>,
14748 element_bounds: gpui::Bounds<Pixels>,
14749 cx: &mut ViewContext<Self>,
14750 ) -> Option<gpui::Bounds<Pixels>> {
14751 let text_layout_details = self.text_layout_details(cx);
14752 let gpui::Point {
14753 x: em_width,
14754 y: line_height,
14755 } = self.character_size(cx);
14756
14757 let snapshot = self.snapshot(cx);
14758 let scroll_position = snapshot.scroll_position();
14759 let scroll_left = scroll_position.x * em_width;
14760
14761 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14762 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14763 + self.gutter_dimensions.width
14764 + self.gutter_dimensions.margin;
14765 let y = line_height * (start.row().as_f32() - scroll_position.y);
14766
14767 Some(Bounds {
14768 origin: element_bounds.origin + point(x, y),
14769 size: size(em_width, line_height),
14770 })
14771 }
14772}
14773
14774trait SelectionExt {
14775 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14776 fn spanned_rows(
14777 &self,
14778 include_end_if_at_line_start: bool,
14779 map: &DisplaySnapshot,
14780 ) -> Range<MultiBufferRow>;
14781}
14782
14783impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14784 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14785 let start = self
14786 .start
14787 .to_point(&map.buffer_snapshot)
14788 .to_display_point(map);
14789 let end = self
14790 .end
14791 .to_point(&map.buffer_snapshot)
14792 .to_display_point(map);
14793 if self.reversed {
14794 end..start
14795 } else {
14796 start..end
14797 }
14798 }
14799
14800 fn spanned_rows(
14801 &self,
14802 include_end_if_at_line_start: bool,
14803 map: &DisplaySnapshot,
14804 ) -> Range<MultiBufferRow> {
14805 let start = self.start.to_point(&map.buffer_snapshot);
14806 let mut end = self.end.to_point(&map.buffer_snapshot);
14807 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14808 end.row -= 1;
14809 }
14810
14811 let buffer_start = map.prev_line_boundary(start).0;
14812 let buffer_end = map.next_line_boundary(end).0;
14813 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14814 }
14815}
14816
14817impl<T: InvalidationRegion> InvalidationStack<T> {
14818 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14819 where
14820 S: Clone + ToOffset,
14821 {
14822 while let Some(region) = self.last() {
14823 let all_selections_inside_invalidation_ranges =
14824 if selections.len() == region.ranges().len() {
14825 selections
14826 .iter()
14827 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14828 .all(|(selection, invalidation_range)| {
14829 let head = selection.head().to_offset(buffer);
14830 invalidation_range.start <= head && invalidation_range.end >= head
14831 })
14832 } else {
14833 false
14834 };
14835
14836 if all_selections_inside_invalidation_ranges {
14837 break;
14838 } else {
14839 self.pop();
14840 }
14841 }
14842 }
14843}
14844
14845impl<T> Default for InvalidationStack<T> {
14846 fn default() -> Self {
14847 Self(Default::default())
14848 }
14849}
14850
14851impl<T> Deref for InvalidationStack<T> {
14852 type Target = Vec<T>;
14853
14854 fn deref(&self) -> &Self::Target {
14855 &self.0
14856 }
14857}
14858
14859impl<T> DerefMut for InvalidationStack<T> {
14860 fn deref_mut(&mut self) -> &mut Self::Target {
14861 &mut self.0
14862 }
14863}
14864
14865impl InvalidationRegion for SnippetState {
14866 fn ranges(&self) -> &[Range<Anchor>] {
14867 &self.ranges[self.active_index]
14868 }
14869}
14870
14871pub fn diagnostic_block_renderer(
14872 diagnostic: Diagnostic,
14873 max_message_rows: Option<u8>,
14874 allow_closing: bool,
14875 _is_valid: bool,
14876) -> RenderBlock {
14877 let (text_without_backticks, code_ranges) =
14878 highlight_diagnostic_message(&diagnostic, max_message_rows);
14879
14880 Arc::new(move |cx: &mut BlockContext| {
14881 let group_id: SharedString = cx.block_id.to_string().into();
14882
14883 let mut text_style = cx.text_style().clone();
14884 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14885 let theme_settings = ThemeSettings::get_global(cx);
14886 text_style.font_family = theme_settings.buffer_font.family.clone();
14887 text_style.font_style = theme_settings.buffer_font.style;
14888 text_style.font_features = theme_settings.buffer_font.features.clone();
14889 text_style.font_weight = theme_settings.buffer_font.weight;
14890
14891 let multi_line_diagnostic = diagnostic.message.contains('\n');
14892
14893 let buttons = |diagnostic: &Diagnostic| {
14894 if multi_line_diagnostic {
14895 v_flex()
14896 } else {
14897 h_flex()
14898 }
14899 .when(allow_closing, |div| {
14900 div.children(diagnostic.is_primary.then(|| {
14901 IconButton::new("close-block", IconName::XCircle)
14902 .icon_color(Color::Muted)
14903 .size(ButtonSize::Compact)
14904 .style(ButtonStyle::Transparent)
14905 .visible_on_hover(group_id.clone())
14906 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14907 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14908 }))
14909 })
14910 .child(
14911 IconButton::new("copy-block", IconName::Copy)
14912 .icon_color(Color::Muted)
14913 .size(ButtonSize::Compact)
14914 .style(ButtonStyle::Transparent)
14915 .visible_on_hover(group_id.clone())
14916 .on_click({
14917 let message = diagnostic.message.clone();
14918 move |_click, cx| {
14919 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14920 }
14921 })
14922 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14923 )
14924 };
14925
14926 let icon_size = buttons(&diagnostic)
14927 .into_any_element()
14928 .layout_as_root(AvailableSpace::min_size(), cx);
14929
14930 h_flex()
14931 .id(cx.block_id)
14932 .group(group_id.clone())
14933 .relative()
14934 .size_full()
14935 .block_mouse_down()
14936 .pl(cx.gutter_dimensions.width)
14937 .w(cx.max_width - cx.gutter_dimensions.full_width())
14938 .child(
14939 div()
14940 .flex()
14941 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14942 .flex_shrink(),
14943 )
14944 .child(buttons(&diagnostic))
14945 .child(div().flex().flex_shrink_0().child(
14946 StyledText::new(text_without_backticks.clone()).with_highlights(
14947 &text_style,
14948 code_ranges.iter().map(|range| {
14949 (
14950 range.clone(),
14951 HighlightStyle {
14952 font_weight: Some(FontWeight::BOLD),
14953 ..Default::default()
14954 },
14955 )
14956 }),
14957 ),
14958 ))
14959 .into_any_element()
14960 })
14961}
14962
14963pub fn highlight_diagnostic_message(
14964 diagnostic: &Diagnostic,
14965 mut max_message_rows: Option<u8>,
14966) -> (SharedString, Vec<Range<usize>>) {
14967 let mut text_without_backticks = String::new();
14968 let mut code_ranges = Vec::new();
14969
14970 if let Some(source) = &diagnostic.source {
14971 text_without_backticks.push_str(source);
14972 code_ranges.push(0..source.len());
14973 text_without_backticks.push_str(": ");
14974 }
14975
14976 let mut prev_offset = 0;
14977 let mut in_code_block = false;
14978 let has_row_limit = max_message_rows.is_some();
14979 let mut newline_indices = diagnostic
14980 .message
14981 .match_indices('\n')
14982 .filter(|_| has_row_limit)
14983 .map(|(ix, _)| ix)
14984 .fuse()
14985 .peekable();
14986
14987 for (quote_ix, _) in diagnostic
14988 .message
14989 .match_indices('`')
14990 .chain([(diagnostic.message.len(), "")])
14991 {
14992 let mut first_newline_ix = None;
14993 let mut last_newline_ix = None;
14994 while let Some(newline_ix) = newline_indices.peek() {
14995 if *newline_ix < quote_ix {
14996 if first_newline_ix.is_none() {
14997 first_newline_ix = Some(*newline_ix);
14998 }
14999 last_newline_ix = Some(*newline_ix);
15000
15001 if let Some(rows_left) = &mut max_message_rows {
15002 if *rows_left == 0 {
15003 break;
15004 } else {
15005 *rows_left -= 1;
15006 }
15007 }
15008 let _ = newline_indices.next();
15009 } else {
15010 break;
15011 }
15012 }
15013 let prev_len = text_without_backticks.len();
15014 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15015 text_without_backticks.push_str(new_text);
15016 if in_code_block {
15017 code_ranges.push(prev_len..text_without_backticks.len());
15018 }
15019 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15020 in_code_block = !in_code_block;
15021 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15022 text_without_backticks.push_str("...");
15023 break;
15024 }
15025 }
15026
15027 (text_without_backticks.into(), code_ranges)
15028}
15029
15030fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15031 match severity {
15032 DiagnosticSeverity::ERROR => colors.error,
15033 DiagnosticSeverity::WARNING => colors.warning,
15034 DiagnosticSeverity::INFORMATION => colors.info,
15035 DiagnosticSeverity::HINT => colors.info,
15036 _ => colors.ignored,
15037 }
15038}
15039
15040pub fn styled_runs_for_code_label<'a>(
15041 label: &'a CodeLabel,
15042 syntax_theme: &'a theme::SyntaxTheme,
15043) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15044 let fade_out = HighlightStyle {
15045 fade_out: Some(0.35),
15046 ..Default::default()
15047 };
15048
15049 let mut prev_end = label.filter_range.end;
15050 label
15051 .runs
15052 .iter()
15053 .enumerate()
15054 .flat_map(move |(ix, (range, highlight_id))| {
15055 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15056 style
15057 } else {
15058 return Default::default();
15059 };
15060 let mut muted_style = style;
15061 muted_style.highlight(fade_out);
15062
15063 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15064 if range.start >= label.filter_range.end {
15065 if range.start > prev_end {
15066 runs.push((prev_end..range.start, fade_out));
15067 }
15068 runs.push((range.clone(), muted_style));
15069 } else if range.end <= label.filter_range.end {
15070 runs.push((range.clone(), style));
15071 } else {
15072 runs.push((range.start..label.filter_range.end, style));
15073 runs.push((label.filter_range.end..range.end, muted_style));
15074 }
15075 prev_end = cmp::max(prev_end, range.end);
15076
15077 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15078 runs.push((prev_end..label.text.len(), fade_out));
15079 }
15080
15081 runs
15082 })
15083}
15084
15085pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15086 let mut prev_index = 0;
15087 let mut prev_codepoint: Option<char> = None;
15088 text.char_indices()
15089 .chain([(text.len(), '\0')])
15090 .filter_map(move |(index, codepoint)| {
15091 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15092 let is_boundary = index == text.len()
15093 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15094 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15095 if is_boundary {
15096 let chunk = &text[prev_index..index];
15097 prev_index = index;
15098 Some(chunk)
15099 } else {
15100 None
15101 }
15102 })
15103}
15104
15105pub trait RangeToAnchorExt: Sized {
15106 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15107
15108 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15109 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15110 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15111 }
15112}
15113
15114impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15115 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15116 let start_offset = self.start.to_offset(snapshot);
15117 let end_offset = self.end.to_offset(snapshot);
15118 if start_offset == end_offset {
15119 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15120 } else {
15121 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15122 }
15123 }
15124}
15125
15126pub trait RowExt {
15127 fn as_f32(&self) -> f32;
15128
15129 fn next_row(&self) -> Self;
15130
15131 fn previous_row(&self) -> Self;
15132
15133 fn minus(&self, other: Self) -> u32;
15134}
15135
15136impl RowExt for DisplayRow {
15137 fn as_f32(&self) -> f32 {
15138 self.0 as f32
15139 }
15140
15141 fn next_row(&self) -> Self {
15142 Self(self.0 + 1)
15143 }
15144
15145 fn previous_row(&self) -> Self {
15146 Self(self.0.saturating_sub(1))
15147 }
15148
15149 fn minus(&self, other: Self) -> u32 {
15150 self.0 - other.0
15151 }
15152}
15153
15154impl RowExt for MultiBufferRow {
15155 fn as_f32(&self) -> f32 {
15156 self.0 as f32
15157 }
15158
15159 fn next_row(&self) -> Self {
15160 Self(self.0 + 1)
15161 }
15162
15163 fn previous_row(&self) -> Self {
15164 Self(self.0.saturating_sub(1))
15165 }
15166
15167 fn minus(&self, other: Self) -> u32 {
15168 self.0 - other.0
15169 }
15170}
15171
15172trait RowRangeExt {
15173 type Row;
15174
15175 fn len(&self) -> usize;
15176
15177 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15178}
15179
15180impl RowRangeExt for Range<MultiBufferRow> {
15181 type Row = MultiBufferRow;
15182
15183 fn len(&self) -> usize {
15184 (self.end.0 - self.start.0) as usize
15185 }
15186
15187 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15188 (self.start.0..self.end.0).map(MultiBufferRow)
15189 }
15190}
15191
15192impl RowRangeExt for Range<DisplayRow> {
15193 type Row = DisplayRow;
15194
15195 fn len(&self) -> usize {
15196 (self.end.0 - self.start.0) as usize
15197 }
15198
15199 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15200 (self.start.0..self.end.0).map(DisplayRow)
15201 }
15202}
15203
15204fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15205 if hunk.diff_base_byte_range.is_empty() {
15206 DiffHunkStatus::Added
15207 } else if hunk.row_range.is_empty() {
15208 DiffHunkStatus::Removed
15209 } else {
15210 DiffHunkStatus::Modified
15211 }
15212}
15213
15214/// If select range has more than one line, we
15215/// just point the cursor to range.start.
15216fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15217 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15218 range
15219 } else {
15220 range.start..range.start
15221 }
15222}
15223
15224pub struct KillRing(ClipboardItem);
15225impl Global for KillRing {}
15226
15227const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);