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, Item, Location,
129 LocationLink, Project, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{
135 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
136};
137use serde::{Deserialize, Serialize};
138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
139use smallvec::SmallVec;
140use snippet::Snippet;
141use std::{
142 any::TypeId,
143 borrow::Cow,
144 cell::RefCell,
145 cmp::{self, Ordering, Reverse},
146 mem,
147 num::NonZeroU32,
148 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
149 path::{Path, PathBuf},
150 rc::Rc,
151 sync::Arc,
152 time::{Duration, Instant},
153};
154pub use sum_tree::Bias;
155use sum_tree::TreeMap;
156use text::{BufferId, OffsetUtf16, Rope};
157use theme::{
158 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
159 ThemeColors, ThemeSettings,
160};
161use ui::{
162 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
163 ListItem, Popover, PopoverMenuHandle, Tooltip,
164};
165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
166use workspace::item::{ItemHandle, PreviewTabsSettings};
167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
168use workspace::{
169 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
170};
171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
172
173use crate::hover_links::find_url;
174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
175
176pub const FILE_HEADER_HEIGHT: u32 = 2;
177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
181const MAX_LINE_LEN: usize = 1024;
182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
185#[doc(hidden)]
186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
187#[doc(hidden)]
188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakView<Workspace>>,
198 cx: &mut WindowContext,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(link_ranges, move |clicked_range_ix, cx| {
243 match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace.open_abs_path(path.clone(), false, cx).detach();
249 });
250 }
251 }
252 }
253 })
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
257pub(crate) enum InlayId {
258 Suggestion(usize),
259 Hint(usize),
260}
261
262impl InlayId {
263 fn id(&self) -> usize {
264 match self {
265 Self::Suggestion(id) => *id,
266 Self::Hint(id) => *id,
267 }
268 }
269}
270
271enum DiffRowHighlight {}
272enum DocumentHighlightRead {}
273enum DocumentHighlightWrite {}
274enum InputComposition {}
275
276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
277pub enum Navigated {
278 Yes,
279 No,
280}
281
282impl Navigated {
283 pub fn from_bool(yes: bool) -> Navigated {
284 if yes {
285 Navigated::Yes
286 } else {
287 Navigated::No
288 }
289 }
290}
291
292pub fn init_settings(cx: &mut AppContext) {
293 EditorSettings::register(cx);
294}
295
296pub fn init(cx: &mut AppContext) {
297 init_settings(cx);
298
299 workspace::register_project_item::<Editor>(cx);
300 workspace::FollowableViewRegistry::register::<Editor>(cx);
301 workspace::register_serializable_item::<Editor>(cx);
302
303 cx.observe_new_views(
304 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
305 workspace.register_action(Editor::new_file);
306 workspace.register_action(Editor::new_file_vertical);
307 workspace.register_action(Editor::new_file_horizontal);
308 },
309 )
310 .detach();
311
312 cx.on_action(move |_: &workspace::NewFile, cx| {
313 let app_state = workspace::AppState::global(cx);
314 if let Some(app_state) = app_state.upgrade() {
315 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
316 Editor::new_file(workspace, &Default::default(), cx)
317 })
318 .detach();
319 }
320 });
321 cx.on_action(move |_: &workspace::NewWindow, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
325 Editor::new_file(workspace, &Default::default(), cx)
326 })
327 .detach();
328 }
329 });
330}
331
332pub struct SearchWithinRange;
333
334trait InvalidationRegion {
335 fn ranges(&self) -> &[Range<Anchor>];
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub enum SelectPhase {
340 Begin {
341 position: DisplayPoint,
342 add: bool,
343 click_count: usize,
344 },
345 BeginColumnar {
346 position: DisplayPoint,
347 reset: bool,
348 goal_column: u32,
349 },
350 Extend {
351 position: DisplayPoint,
352 click_count: usize,
353 },
354 Update {
355 position: DisplayPoint,
356 goal_column: u32,
357 scroll_delta: gpui::Point<f32>,
358 },
359 End,
360}
361
362#[derive(Clone, Debug)]
363pub enum SelectMode {
364 Character,
365 Word(Range<Anchor>),
366 Line(Range<Anchor>),
367 All,
368}
369
370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
371pub enum EditorMode {
372 SingleLine { auto_width: bool },
373 AutoHeight { max_lines: usize },
374 Full,
375}
376
377#[derive(Copy, Clone, Debug)]
378pub enum SoftWrap {
379 /// Prefer not to wrap at all.
380 ///
381 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
382 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
383 GitDiff,
384 /// Prefer a single line generally, unless an overly long line is encountered.
385 None,
386 /// Soft wrap lines that exceed the editor width.
387 EditorWidth,
388 /// Soft wrap lines at the preferred line length.
389 Column(u32),
390 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
391 Bounded(u32),
392}
393
394#[derive(Clone)]
395pub struct EditorStyle {
396 pub background: Hsla,
397 pub local_player: PlayerColor,
398 pub text: TextStyle,
399 pub scrollbar_width: Pixels,
400 pub syntax: Arc<SyntaxTheme>,
401 pub status: StatusColors,
402 pub inlay_hints_style: HighlightStyle,
403 pub suggestions_style: HighlightStyle,
404 pub unnecessary_code_fade: f32,
405}
406
407impl Default for EditorStyle {
408 fn default() -> Self {
409 Self {
410 background: Hsla::default(),
411 local_player: PlayerColor::default(),
412 text: TextStyle::default(),
413 scrollbar_width: Pixels::default(),
414 syntax: Default::default(),
415 // HACK: Status colors don't have a real default.
416 // We should look into removing the status colors from the editor
417 // style and retrieve them directly from the theme.
418 status: StatusColors::dark(),
419 inlay_hints_style: HighlightStyle::default(),
420 suggestions_style: HighlightStyle::default(),
421 unnecessary_code_fade: Default::default(),
422 }
423 }
424}
425
426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
427 let show_background = language_settings::language_settings(None, None, cx)
428 .inlay_hints
429 .show_background;
430
431 HighlightStyle {
432 color: Some(cx.theme().status().hint),
433 background_color: show_background.then(|| cx.theme().status().hint_background),
434 ..HighlightStyle::default()
435 }
436}
437
438type CompletionId = usize;
439
440#[derive(Clone, Debug)]
441struct CompletionState {
442 // render_inlay_ids represents the inlay hints that are inserted
443 // for rendering the inline completions. They may be discontinuous
444 // in the event that the completion provider returns some intersection
445 // with the existing content.
446 render_inlay_ids: Vec<InlayId>,
447 // text is the resulting rope that is inserted when the user accepts a completion.
448 text: Rope,
449 // position is the position of the cursor when the completion was triggered.
450 position: multi_buffer::Anchor,
451 // delete_range is the range of text that this completion state covers.
452 // if the completion is accepted, this range should be deleted.
453 delete_range: Option<Range<multi_buffer::Anchor>>,
454}
455
456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
457struct EditorActionId(usize);
458
459impl EditorActionId {
460 pub fn post_inc(&mut self) -> Self {
461 let answer = self.0;
462
463 *self = Self(answer + 1);
464
465 Self(answer)
466 }
467}
468
469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
471
472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
474
475#[derive(Default)]
476struct ScrollbarMarkerState {
477 scrollbar_size: Size<Pixels>,
478 dirty: bool,
479 markers: Arc<[PaintQuad]>,
480 pending_refresh: Option<Task<Result<()>>>,
481}
482
483impl ScrollbarMarkerState {
484 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
485 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
486 }
487}
488
489#[derive(Clone, Debug)]
490struct RunnableTasks {
491 templates: Vec<(TaskSourceKind, TaskTemplate)>,
492 offset: MultiBufferOffset,
493 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
494 column: u32,
495 // Values of all named captures, including those starting with '_'
496 extra_variables: HashMap<String, String>,
497 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
498 context_range: Range<BufferOffset>,
499}
500
501impl RunnableTasks {
502 fn resolve<'a>(
503 &'a self,
504 cx: &'a task::TaskContext,
505 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
506 self.templates.iter().filter_map(|(kind, template)| {
507 template
508 .resolve_task(&kind.to_id_base(), cx)
509 .map(|task| (kind.clone(), task))
510 })
511 }
512}
513
514#[derive(Clone)]
515struct ResolvedTasks {
516 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
517 position: Anchor,
518}
519#[derive(Copy, Clone, Debug)]
520struct MultiBufferOffset(usize);
521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
522struct BufferOffset(usize);
523
524// Addons allow storing per-editor state in other crates (e.g. Vim)
525pub trait Addon: 'static {
526 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
527
528 fn to_any(&self) -> &dyn std::any::Any;
529}
530
531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
532pub enum IsVimMode {
533 Yes,
534 No,
535}
536
537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
538///
539/// See the [module level documentation](self) for more information.
540pub struct Editor {
541 focus_handle: FocusHandle,
542 last_focused_descendant: Option<WeakFocusHandle>,
543 /// The text buffer being edited
544 buffer: Model<MultiBuffer>,
545 /// Map of how text in the buffer should be displayed.
546 /// Handles soft wraps, folds, fake inlay text insertions, etc.
547 pub display_map: Model<DisplayMap>,
548 pub selections: SelectionsCollection,
549 pub scroll_manager: ScrollManager,
550 /// When inline assist editors are linked, they all render cursors because
551 /// typing enters text into each of them, even the ones that aren't focused.
552 pub(crate) show_cursor_when_unfocused: bool,
553 columnar_selection_tail: Option<Anchor>,
554 add_selections_state: Option<AddSelectionsState>,
555 select_next_state: Option<SelectNextState>,
556 select_prev_state: Option<SelectNextState>,
557 selection_history: SelectionHistory,
558 autoclose_regions: Vec<AutocloseRegion>,
559 snippet_stack: InvalidationStack<SnippetState>,
560 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
561 ime_transaction: Option<TransactionId>,
562 active_diagnostics: Option<ActiveDiagnosticGroup>,
563 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
564
565 project: Option<Model<Project>>,
566 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
567 completion_provider: Option<Box<dyn CompletionProvider>>,
568 collaboration_hub: Option<Box<dyn CollaborationHub>>,
569 blink_manager: Model<BlinkManager>,
570 show_cursor_names: bool,
571 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
572 pub show_local_selections: bool,
573 mode: EditorMode,
574 show_breadcrumbs: bool,
575 show_gutter: bool,
576 show_line_numbers: Option<bool>,
577 use_relative_line_numbers: Option<bool>,
578 show_git_diff_gutter: Option<bool>,
579 show_code_actions: Option<bool>,
580 show_runnables: Option<bool>,
581 show_wrap_guides: Option<bool>,
582 show_indent_guides: Option<bool>,
583 placeholder_text: Option<Arc<str>>,
584 highlight_order: usize,
585 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
586 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
587 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
588 scrollbar_marker_state: ScrollbarMarkerState,
589 active_indent_guides_state: ActiveIndentGuidesState,
590 nav_history: Option<ItemNavHistory>,
591 context_menu: RwLock<Option<ContextMenu>>,
592 mouse_context_menu: Option<MouseContextMenu>,
593 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
594 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
595 signature_help_state: SignatureHelpState,
596 auto_signature_help: Option<bool>,
597 find_all_references_task_sources: Vec<Anchor>,
598 next_completion_id: CompletionId,
599 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
600 code_actions_task: Option<Task<Result<()>>>,
601 document_highlights_task: Option<Task<()>>,
602 linked_editing_range_task: Option<Task<Option<()>>>,
603 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
604 pending_rename: Option<RenameState>,
605 searchable: bool,
606 cursor_shape: CursorShape,
607 current_line_highlight: Option<CurrentLineHighlight>,
608 collapse_matches: bool,
609 autoindent_mode: Option<AutoindentMode>,
610 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
611 input_enabled: bool,
612 use_modal_editing: bool,
613 read_only: bool,
614 leader_peer_id: Option<PeerId>,
615 remote_id: Option<ViewId>,
616 hover_state: HoverState,
617 gutter_hovered: bool,
618 hovered_link_state: Option<HoveredLinkState>,
619 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
620 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
621 active_inline_completion: Option<CompletionState>,
622 // enable_inline_completions is a switch that Vim can use to disable
623 // inline completions based on its mode.
624 enable_inline_completions: bool,
625 show_inline_completions_override: Option<bool>,
626 inlay_hint_cache: InlayHintCache,
627 expanded_hunks: ExpandedHunks,
628 next_inlay_id: usize,
629 _subscriptions: Vec<Subscription>,
630 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
631 gutter_dimensions: GutterDimensions,
632 style: Option<EditorStyle>,
633 text_style_refinement: Option<TextStyleRefinement>,
634 next_editor_action_id: EditorActionId,
635 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
636 use_autoclose: bool,
637 use_auto_surround: bool,
638 auto_replace_emoji_shortcode: bool,
639 show_git_blame_gutter: bool,
640 show_git_blame_inline: bool,
641 show_git_blame_inline_delay_task: Option<Task<()>>,
642 git_blame_inline_enabled: bool,
643 serialize_dirty_buffers: bool,
644 show_selection_menu: Option<bool>,
645 blame: Option<Model<GitBlame>>,
646 blame_subscription: Option<Subscription>,
647 custom_context_menu: Option<
648 Box<
649 dyn 'static
650 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
651 >,
652 >,
653 last_bounds: Option<Bounds<Pixels>>,
654 expect_bounds_change: Option<Bounds<Pixels>>,
655 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
656 tasks_update_task: Option<Task<()>>,
657 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
658 breadcrumb_header: Option<String>,
659 focused_block: Option<FocusedBlock>,
660 next_scroll_position: NextScrollCursorCenterTopBottom,
661 addons: HashMap<TypeId, Box<dyn Addon>>,
662 _scroll_cursor_center_top_bottom_task: Task<()>,
663}
664
665#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
666enum NextScrollCursorCenterTopBottom {
667 #[default]
668 Center,
669 Top,
670 Bottom,
671}
672
673impl NextScrollCursorCenterTopBottom {
674 fn next(&self) -> Self {
675 match self {
676 Self::Center => Self::Top,
677 Self::Top => Self::Bottom,
678 Self::Bottom => Self::Center,
679 }
680 }
681}
682
683#[derive(Clone)]
684pub struct EditorSnapshot {
685 pub mode: EditorMode,
686 show_gutter: bool,
687 show_line_numbers: Option<bool>,
688 show_git_diff_gutter: Option<bool>,
689 show_code_actions: Option<bool>,
690 show_runnables: Option<bool>,
691 git_blame_gutter_max_author_length: Option<usize>,
692 pub display_snapshot: DisplaySnapshot,
693 pub placeholder_text: Option<Arc<str>>,
694 is_focused: bool,
695 scroll_anchor: ScrollAnchor,
696 ongoing_scroll: OngoingScroll,
697 current_line_highlight: CurrentLineHighlight,
698 gutter_hovered: bool,
699}
700
701const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
702
703#[derive(Default, Debug, Clone, Copy)]
704pub struct GutterDimensions {
705 pub left_padding: Pixels,
706 pub right_padding: Pixels,
707 pub width: Pixels,
708 pub margin: Pixels,
709 pub git_blame_entries_width: Option<Pixels>,
710}
711
712impl GutterDimensions {
713 /// The full width of the space taken up by the gutter.
714 pub fn full_width(&self) -> Pixels {
715 self.margin + self.width
716 }
717
718 /// The width of the space reserved for the fold indicators,
719 /// use alongside 'justify_end' and `gutter_width` to
720 /// right align content with the line numbers
721 pub fn fold_area_width(&self) -> Pixels {
722 self.margin + self.right_padding
723 }
724}
725
726#[derive(Debug)]
727pub struct RemoteSelection {
728 pub replica_id: ReplicaId,
729 pub selection: Selection<Anchor>,
730 pub cursor_shape: CursorShape,
731 pub peer_id: PeerId,
732 pub line_mode: bool,
733 pub participant_index: Option<ParticipantIndex>,
734 pub user_name: Option<SharedString>,
735}
736
737#[derive(Clone, Debug)]
738struct SelectionHistoryEntry {
739 selections: Arc<[Selection<Anchor>]>,
740 select_next_state: Option<SelectNextState>,
741 select_prev_state: Option<SelectNextState>,
742 add_selections_state: Option<AddSelectionsState>,
743}
744
745enum SelectionHistoryMode {
746 Normal,
747 Undoing,
748 Redoing,
749}
750
751#[derive(Clone, PartialEq, Eq, Hash)]
752struct HoveredCursor {
753 replica_id: u16,
754 selection_id: usize,
755}
756
757impl Default for SelectionHistoryMode {
758 fn default() -> Self {
759 Self::Normal
760 }
761}
762
763#[derive(Default)]
764struct SelectionHistory {
765 #[allow(clippy::type_complexity)]
766 selections_by_transaction:
767 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
768 mode: SelectionHistoryMode,
769 undo_stack: VecDeque<SelectionHistoryEntry>,
770 redo_stack: VecDeque<SelectionHistoryEntry>,
771}
772
773impl SelectionHistory {
774 fn insert_transaction(
775 &mut self,
776 transaction_id: TransactionId,
777 selections: Arc<[Selection<Anchor>]>,
778 ) {
779 self.selections_by_transaction
780 .insert(transaction_id, (selections, None));
781 }
782
783 #[allow(clippy::type_complexity)]
784 fn transaction(
785 &self,
786 transaction_id: TransactionId,
787 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
788 self.selections_by_transaction.get(&transaction_id)
789 }
790
791 #[allow(clippy::type_complexity)]
792 fn transaction_mut(
793 &mut self,
794 transaction_id: TransactionId,
795 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
796 self.selections_by_transaction.get_mut(&transaction_id)
797 }
798
799 fn push(&mut self, entry: SelectionHistoryEntry) {
800 if !entry.selections.is_empty() {
801 match self.mode {
802 SelectionHistoryMode::Normal => {
803 self.push_undo(entry);
804 self.redo_stack.clear();
805 }
806 SelectionHistoryMode::Undoing => self.push_redo(entry),
807 SelectionHistoryMode::Redoing => self.push_undo(entry),
808 }
809 }
810 }
811
812 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
813 if self
814 .undo_stack
815 .back()
816 .map_or(true, |e| e.selections != entry.selections)
817 {
818 self.undo_stack.push_back(entry);
819 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
820 self.undo_stack.pop_front();
821 }
822 }
823 }
824
825 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
826 if self
827 .redo_stack
828 .back()
829 .map_or(true, |e| e.selections != entry.selections)
830 {
831 self.redo_stack.push_back(entry);
832 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
833 self.redo_stack.pop_front();
834 }
835 }
836 }
837}
838
839struct RowHighlight {
840 index: usize,
841 range: Range<Anchor>,
842 color: Hsla,
843 should_autoscroll: bool,
844}
845
846#[derive(Clone, Debug)]
847struct AddSelectionsState {
848 above: bool,
849 stack: Vec<usize>,
850}
851
852#[derive(Clone)]
853struct SelectNextState {
854 query: AhoCorasick,
855 wordwise: bool,
856 done: bool,
857}
858
859impl std::fmt::Debug for SelectNextState {
860 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
861 f.debug_struct(std::any::type_name::<Self>())
862 .field("wordwise", &self.wordwise)
863 .field("done", &self.done)
864 .finish()
865 }
866}
867
868#[derive(Debug)]
869struct AutocloseRegion {
870 selection_id: usize,
871 range: Range<Anchor>,
872 pair: BracketPair,
873}
874
875#[derive(Debug)]
876struct SnippetState {
877 ranges: Vec<Vec<Range<Anchor>>>,
878 active_index: usize,
879 choices: Vec<Option<Vec<String>>>,
880}
881
882#[doc(hidden)]
883pub struct RenameState {
884 pub range: Range<Anchor>,
885 pub old_name: Arc<str>,
886 pub editor: View<Editor>,
887 block_id: CustomBlockId,
888}
889
890struct InvalidationStack<T>(Vec<T>);
891
892struct RegisteredInlineCompletionProvider {
893 provider: Arc<dyn InlineCompletionProviderHandle>,
894 _subscription: Subscription,
895}
896
897enum ContextMenu {
898 Completions(CompletionsMenu),
899 CodeActions(CodeActionsMenu),
900}
901
902impl ContextMenu {
903 fn select_first(
904 &mut self,
905 provider: Option<&dyn CompletionProvider>,
906 cx: &mut ViewContext<Editor>,
907 ) -> bool {
908 if self.visible() {
909 match self {
910 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
911 ContextMenu::CodeActions(menu) => menu.select_first(cx),
912 }
913 true
914 } else {
915 false
916 }
917 }
918
919 fn select_prev(
920 &mut self,
921 provider: Option<&dyn CompletionProvider>,
922 cx: &mut ViewContext<Editor>,
923 ) -> bool {
924 if self.visible() {
925 match self {
926 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
927 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
928 }
929 true
930 } else {
931 false
932 }
933 }
934
935 fn select_next(
936 &mut self,
937 provider: Option<&dyn CompletionProvider>,
938 cx: &mut ViewContext<Editor>,
939 ) -> bool {
940 if self.visible() {
941 match self {
942 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
943 ContextMenu::CodeActions(menu) => menu.select_next(cx),
944 }
945 true
946 } else {
947 false
948 }
949 }
950
951 fn select_last(
952 &mut self,
953 provider: Option<&dyn CompletionProvider>,
954 cx: &mut ViewContext<Editor>,
955 ) -> bool {
956 if self.visible() {
957 match self {
958 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
959 ContextMenu::CodeActions(menu) => menu.select_last(cx),
960 }
961 true
962 } else {
963 false
964 }
965 }
966
967 fn visible(&self) -> bool {
968 match self {
969 ContextMenu::Completions(menu) => menu.visible(),
970 ContextMenu::CodeActions(menu) => menu.visible(),
971 }
972 }
973
974 fn render(
975 &self,
976 cursor_position: DisplayPoint,
977 style: &EditorStyle,
978 max_height: Pixels,
979 workspace: Option<WeakView<Workspace>>,
980 cx: &mut ViewContext<Editor>,
981 ) -> (ContextMenuOrigin, AnyElement) {
982 match self {
983 ContextMenu::Completions(menu) => (
984 ContextMenuOrigin::EditorPoint(cursor_position),
985 menu.render(style, max_height, workspace, cx),
986 ),
987 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
988 }
989 }
990}
991
992enum ContextMenuOrigin {
993 EditorPoint(DisplayPoint),
994 GutterIndicator(DisplayRow),
995}
996
997#[derive(Clone, Debug)]
998struct CompletionsMenu {
999 id: CompletionId,
1000 sort_completions: bool,
1001 initial_position: Anchor,
1002 buffer: Model<Buffer>,
1003 completions: Arc<RwLock<Box<[Completion]>>>,
1004 match_candidates: Arc<[StringMatchCandidate]>,
1005 matches: Arc<[StringMatch]>,
1006 selected_item: usize,
1007 scroll_handle: UniformListScrollHandle,
1008 selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
1009}
1010
1011impl CompletionsMenu {
1012 fn new(
1013 id: CompletionId,
1014 sort_completions: bool,
1015 initial_position: Anchor,
1016 buffer: Model<Buffer>,
1017 completions: Box<[Completion]>,
1018 ) -> Self {
1019 let match_candidates = completions
1020 .iter()
1021 .enumerate()
1022 .map(|(id, completion)| {
1023 StringMatchCandidate::new(
1024 id,
1025 completion.label.text[completion.label.filter_range.clone()].into(),
1026 )
1027 })
1028 .collect();
1029
1030 Self {
1031 id,
1032 sort_completions,
1033 initial_position,
1034 buffer,
1035 completions: Arc::new(RwLock::new(completions)),
1036 match_candidates,
1037 matches: Vec::new().into(),
1038 selected_item: 0,
1039 scroll_handle: UniformListScrollHandle::new(),
1040 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1041 }
1042 }
1043
1044 fn new_snippet_choices(
1045 id: CompletionId,
1046 sort_completions: bool,
1047 choices: &Vec<String>,
1048 selection: Range<Anchor>,
1049 buffer: Model<Buffer>,
1050 ) -> Self {
1051 let completions = choices
1052 .iter()
1053 .map(|choice| Completion {
1054 old_range: selection.start.text_anchor..selection.end.text_anchor,
1055 new_text: choice.to_string(),
1056 label: CodeLabel {
1057 text: choice.to_string(),
1058 runs: Default::default(),
1059 filter_range: Default::default(),
1060 },
1061 server_id: LanguageServerId(usize::MAX),
1062 documentation: None,
1063 lsp_completion: Default::default(),
1064 confirm: None,
1065 })
1066 .collect();
1067
1068 let match_candidates = choices
1069 .iter()
1070 .enumerate()
1071 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1072 .collect();
1073 let matches = choices
1074 .iter()
1075 .enumerate()
1076 .map(|(id, completion)| StringMatch {
1077 candidate_id: id,
1078 score: 1.,
1079 positions: vec![],
1080 string: completion.clone(),
1081 })
1082 .collect();
1083 Self {
1084 id,
1085 sort_completions,
1086 initial_position: selection.start,
1087 buffer,
1088 completions: Arc::new(RwLock::new(completions)),
1089 match_candidates,
1090 matches,
1091 selected_item: 0,
1092 scroll_handle: UniformListScrollHandle::new(),
1093 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1094 }
1095 }
1096
1097 fn suppress_documentation_resolution(mut self) -> Self {
1098 self.selected_completion_resolve_debounce.take();
1099 self
1100 }
1101
1102 fn select_first(
1103 &mut self,
1104 provider: Option<&dyn CompletionProvider>,
1105 cx: &mut ViewContext<Editor>,
1106 ) {
1107 self.selected_item = 0;
1108 self.scroll_handle
1109 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1110 self.resolve_selected_completion(provider, cx);
1111 cx.notify();
1112 }
1113
1114 fn select_prev(
1115 &mut self,
1116 provider: Option<&dyn CompletionProvider>,
1117 cx: &mut ViewContext<Editor>,
1118 ) {
1119 if self.selected_item > 0 {
1120 self.selected_item -= 1;
1121 } else {
1122 self.selected_item = self.matches.len() - 1;
1123 }
1124 self.scroll_handle
1125 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1126 self.resolve_selected_completion(provider, cx);
1127 cx.notify();
1128 }
1129
1130 fn select_next(
1131 &mut self,
1132 provider: Option<&dyn CompletionProvider>,
1133 cx: &mut ViewContext<Editor>,
1134 ) {
1135 if self.selected_item + 1 < self.matches.len() {
1136 self.selected_item += 1;
1137 } else {
1138 self.selected_item = 0;
1139 }
1140 self.scroll_handle
1141 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1142 self.resolve_selected_completion(provider, cx);
1143 cx.notify();
1144 }
1145
1146 fn select_last(
1147 &mut self,
1148 provider: Option<&dyn CompletionProvider>,
1149 cx: &mut ViewContext<Editor>,
1150 ) {
1151 self.selected_item = self.matches.len() - 1;
1152 self.scroll_handle
1153 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1154 self.resolve_selected_completion(provider, cx);
1155 cx.notify();
1156 }
1157
1158 fn resolve_selected_completion(
1159 &mut self,
1160 provider: Option<&dyn CompletionProvider>,
1161 cx: &mut ViewContext<Editor>,
1162 ) {
1163 let completion_index = self.matches[self.selected_item].candidate_id;
1164 let Some(provider) = provider else {
1165 return;
1166 };
1167 let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
1168 return;
1169 };
1170
1171 let resolve_task = provider.resolve_completions(
1172 self.buffer.clone(),
1173 vec![completion_index],
1174 self.completions.clone(),
1175 cx,
1176 );
1177
1178 let delay_ms =
1179 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1180 let delay = Duration::from_millis(delay_ms);
1181
1182 completion_resolve.lock().fire_new(delay, cx, |_, cx| {
1183 cx.spawn(move |this, mut cx| async move {
1184 if let Some(true) = resolve_task.await.log_err() {
1185 this.update(&mut cx, |_, cx| cx.notify()).ok();
1186 }
1187 })
1188 });
1189 }
1190
1191 fn visible(&self) -> bool {
1192 !self.matches.is_empty()
1193 }
1194
1195 fn render(
1196 &self,
1197 style: &EditorStyle,
1198 max_height: Pixels,
1199 workspace: Option<WeakView<Workspace>>,
1200 cx: &mut ViewContext<Editor>,
1201 ) -> AnyElement {
1202 let settings = EditorSettings::get_global(cx);
1203 let show_completion_documentation = settings.show_completion_documentation;
1204
1205 let widest_completion_ix = self
1206 .matches
1207 .iter()
1208 .enumerate()
1209 .max_by_key(|(_, mat)| {
1210 let completions = self.completions.read();
1211 let completion = &completions[mat.candidate_id];
1212 let documentation = &completion.documentation;
1213
1214 let mut len = completion.label.text.chars().count();
1215 if let Some(Documentation::SingleLine(text)) = documentation {
1216 if show_completion_documentation {
1217 len += text.chars().count();
1218 }
1219 }
1220
1221 len
1222 })
1223 .map(|(ix, _)| ix);
1224
1225 let completions = self.completions.clone();
1226 let matches = self.matches.clone();
1227 let selected_item = self.selected_item;
1228 let style = style.clone();
1229
1230 let multiline_docs = if show_completion_documentation {
1231 let mat = &self.matches[selected_item];
1232 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1233 Some(Documentation::MultiLinePlainText(text)) => {
1234 Some(div().child(SharedString::from(text.clone())))
1235 }
1236 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1237 Some(div().child(render_parsed_markdown(
1238 "completions_markdown",
1239 parsed,
1240 &style,
1241 workspace,
1242 cx,
1243 )))
1244 }
1245 _ => None,
1246 };
1247 multiline_docs.map(|div| {
1248 div.id("multiline_docs")
1249 .max_h(max_height)
1250 .flex_1()
1251 .px_1p5()
1252 .py_1()
1253 .min_w(px(260.))
1254 .max_w(px(640.))
1255 .w(px(500.))
1256 .overflow_y_scroll()
1257 .occlude()
1258 })
1259 } else {
1260 None
1261 };
1262
1263 let list = uniform_list(
1264 cx.view().clone(),
1265 "completions",
1266 matches.len(),
1267 move |_editor, range, cx| {
1268 let start_ix = range.start;
1269 let completions_guard = completions.read();
1270
1271 matches[range]
1272 .iter()
1273 .enumerate()
1274 .map(|(ix, mat)| {
1275 let item_ix = start_ix + ix;
1276 let candidate_id = mat.candidate_id;
1277 let completion = &completions_guard[candidate_id];
1278
1279 let documentation = if show_completion_documentation {
1280 &completion.documentation
1281 } else {
1282 &None
1283 };
1284
1285 let highlights = gpui::combine_highlights(
1286 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1287 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1288 |(range, mut highlight)| {
1289 // Ignore font weight for syntax highlighting, as we'll use it
1290 // for fuzzy matches.
1291 highlight.font_weight = None;
1292
1293 if completion.lsp_completion.deprecated.unwrap_or(false) {
1294 highlight.strikethrough = Some(StrikethroughStyle {
1295 thickness: 1.0.into(),
1296 ..Default::default()
1297 });
1298 highlight.color = Some(cx.theme().colors().text_muted);
1299 }
1300
1301 (range, highlight)
1302 },
1303 ),
1304 );
1305 let completion_label = StyledText::new(completion.label.text.clone())
1306 .with_highlights(&style.text, highlights);
1307 let documentation_label =
1308 if let Some(Documentation::SingleLine(text)) = documentation {
1309 if text.trim().is_empty() {
1310 None
1311 } else {
1312 Some(
1313 Label::new(text.clone())
1314 .ml_4()
1315 .size(LabelSize::Small)
1316 .color(Color::Muted),
1317 )
1318 }
1319 } else {
1320 None
1321 };
1322
1323 let color_swatch = completion
1324 .color()
1325 .map(|color| div().size_4().bg(color).rounded_sm());
1326
1327 div().min_w(px(220.)).max_w(px(540.)).child(
1328 ListItem::new(mat.candidate_id)
1329 .inset(true)
1330 .selected(item_ix == selected_item)
1331 .on_click(cx.listener(move |editor, _event, cx| {
1332 cx.stop_propagation();
1333 if let Some(task) = editor.confirm_completion(
1334 &ConfirmCompletion {
1335 item_ix: Some(item_ix),
1336 },
1337 cx,
1338 ) {
1339 task.detach_and_log_err(cx)
1340 }
1341 }))
1342 .start_slot::<Div>(color_swatch)
1343 .child(h_flex().overflow_hidden().child(completion_label))
1344 .end_slot::<Label>(documentation_label),
1345 )
1346 })
1347 .collect()
1348 },
1349 )
1350 .occlude()
1351 .max_h(max_height)
1352 .track_scroll(self.scroll_handle.clone())
1353 .with_width_from_item(widest_completion_ix)
1354 .with_sizing_behavior(ListSizingBehavior::Infer);
1355
1356 Popover::new()
1357 .child(list)
1358 .when_some(multiline_docs, |popover, multiline_docs| {
1359 popover.aside(multiline_docs)
1360 })
1361 .into_any_element()
1362 }
1363
1364 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1365 let mut matches = if let Some(query) = query {
1366 fuzzy::match_strings(
1367 &self.match_candidates,
1368 query,
1369 query.chars().any(|c| c.is_uppercase()),
1370 100,
1371 &Default::default(),
1372 executor,
1373 )
1374 .await
1375 } else {
1376 self.match_candidates
1377 .iter()
1378 .enumerate()
1379 .map(|(candidate_id, candidate)| StringMatch {
1380 candidate_id,
1381 score: Default::default(),
1382 positions: Default::default(),
1383 string: candidate.string.clone(),
1384 })
1385 .collect()
1386 };
1387
1388 // Remove all candidates where the query's start does not match the start of any word in the candidate
1389 if let Some(query) = query {
1390 if let Some(query_start) = query.chars().next() {
1391 matches.retain(|string_match| {
1392 split_words(&string_match.string).any(|word| {
1393 // Check that the first codepoint of the word as lowercase matches the first
1394 // codepoint of the query as lowercase
1395 word.chars()
1396 .flat_map(|codepoint| codepoint.to_lowercase())
1397 .zip(query_start.to_lowercase())
1398 .all(|(word_cp, query_cp)| word_cp == query_cp)
1399 })
1400 });
1401 }
1402 }
1403
1404 let completions = self.completions.read();
1405 if self.sort_completions {
1406 matches.sort_unstable_by_key(|mat| {
1407 // We do want to strike a balance here between what the language server tells us
1408 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1409 // `Creat` and there is a local variable called `CreateComponent`).
1410 // So what we do is: we bucket all matches into two buckets
1411 // - Strong matches
1412 // - Weak matches
1413 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1414 // and the Weak matches are the rest.
1415 //
1416 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1417 // matches, we prefer language-server sort_text first.
1418 //
1419 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1420 // Rest of the matches(weak) can be sorted as language-server expects.
1421
1422 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1423 enum MatchScore<'a> {
1424 Strong {
1425 score: Reverse<OrderedFloat<f64>>,
1426 sort_text: Option<&'a str>,
1427 sort_key: (usize, &'a str),
1428 },
1429 Weak {
1430 sort_text: Option<&'a str>,
1431 score: Reverse<OrderedFloat<f64>>,
1432 sort_key: (usize, &'a str),
1433 },
1434 }
1435
1436 let completion = &completions[mat.candidate_id];
1437 let sort_key = completion.sort_key();
1438 let sort_text = completion.lsp_completion.sort_text.as_deref();
1439 let score = Reverse(OrderedFloat(mat.score));
1440
1441 if mat.score >= 0.2 {
1442 MatchScore::Strong {
1443 score,
1444 sort_text,
1445 sort_key,
1446 }
1447 } else {
1448 MatchScore::Weak {
1449 sort_text,
1450 score,
1451 sort_key,
1452 }
1453 }
1454 });
1455 }
1456
1457 for mat in &mut matches {
1458 let completion = &completions[mat.candidate_id];
1459 mat.string.clone_from(&completion.label.text);
1460 for position in &mut mat.positions {
1461 *position += completion.label.filter_range.start;
1462 }
1463 }
1464 drop(completions);
1465
1466 self.matches = matches.into();
1467 self.selected_item = 0;
1468 }
1469}
1470
1471#[derive(Clone)]
1472struct AvailableCodeAction {
1473 excerpt_id: ExcerptId,
1474 action: CodeAction,
1475 provider: Arc<dyn CodeActionProvider>,
1476}
1477
1478#[derive(Clone)]
1479struct CodeActionContents {
1480 tasks: Option<Arc<ResolvedTasks>>,
1481 actions: Option<Arc<[AvailableCodeAction]>>,
1482}
1483
1484impl CodeActionContents {
1485 fn len(&self) -> usize {
1486 match (&self.tasks, &self.actions) {
1487 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1488 (Some(tasks), None) => tasks.templates.len(),
1489 (None, Some(actions)) => actions.len(),
1490 (None, None) => 0,
1491 }
1492 }
1493
1494 fn is_empty(&self) -> bool {
1495 match (&self.tasks, &self.actions) {
1496 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1497 (Some(tasks), None) => tasks.templates.is_empty(),
1498 (None, Some(actions)) => actions.is_empty(),
1499 (None, None) => true,
1500 }
1501 }
1502
1503 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1504 self.tasks
1505 .iter()
1506 .flat_map(|tasks| {
1507 tasks
1508 .templates
1509 .iter()
1510 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1511 })
1512 .chain(self.actions.iter().flat_map(|actions| {
1513 actions.iter().map(|available| CodeActionsItem::CodeAction {
1514 excerpt_id: available.excerpt_id,
1515 action: available.action.clone(),
1516 provider: available.provider.clone(),
1517 })
1518 }))
1519 }
1520 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1521 match (&self.tasks, &self.actions) {
1522 (Some(tasks), Some(actions)) => {
1523 if index < tasks.templates.len() {
1524 tasks
1525 .templates
1526 .get(index)
1527 .cloned()
1528 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1529 } else {
1530 actions.get(index - tasks.templates.len()).map(|available| {
1531 CodeActionsItem::CodeAction {
1532 excerpt_id: available.excerpt_id,
1533 action: available.action.clone(),
1534 provider: available.provider.clone(),
1535 }
1536 })
1537 }
1538 }
1539 (Some(tasks), None) => tasks
1540 .templates
1541 .get(index)
1542 .cloned()
1543 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1544 (None, Some(actions)) => {
1545 actions
1546 .get(index)
1547 .map(|available| CodeActionsItem::CodeAction {
1548 excerpt_id: available.excerpt_id,
1549 action: available.action.clone(),
1550 provider: available.provider.clone(),
1551 })
1552 }
1553 (None, None) => None,
1554 }
1555 }
1556}
1557
1558#[allow(clippy::large_enum_variant)]
1559#[derive(Clone)]
1560enum CodeActionsItem {
1561 Task(TaskSourceKind, ResolvedTask),
1562 CodeAction {
1563 excerpt_id: ExcerptId,
1564 action: CodeAction,
1565 provider: Arc<dyn CodeActionProvider>,
1566 },
1567}
1568
1569impl CodeActionsItem {
1570 fn as_task(&self) -> Option<&ResolvedTask> {
1571 let Self::Task(_, task) = self else {
1572 return None;
1573 };
1574 Some(task)
1575 }
1576 fn as_code_action(&self) -> Option<&CodeAction> {
1577 let Self::CodeAction { action, .. } = self else {
1578 return None;
1579 };
1580 Some(action)
1581 }
1582 fn label(&self) -> String {
1583 match self {
1584 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1585 Self::Task(_, task) => task.resolved_label.clone(),
1586 }
1587 }
1588}
1589
1590struct CodeActionsMenu {
1591 actions: CodeActionContents,
1592 buffer: Model<Buffer>,
1593 selected_item: usize,
1594 scroll_handle: UniformListScrollHandle,
1595 deployed_from_indicator: Option<DisplayRow>,
1596}
1597
1598impl CodeActionsMenu {
1599 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1600 self.selected_item = 0;
1601 self.scroll_handle
1602 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1603 cx.notify()
1604 }
1605
1606 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1607 if self.selected_item > 0 {
1608 self.selected_item -= 1;
1609 } else {
1610 self.selected_item = self.actions.len() - 1;
1611 }
1612 self.scroll_handle
1613 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1614 cx.notify();
1615 }
1616
1617 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1618 if self.selected_item + 1 < self.actions.len() {
1619 self.selected_item += 1;
1620 } else {
1621 self.selected_item = 0;
1622 }
1623 self.scroll_handle
1624 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1625 cx.notify();
1626 }
1627
1628 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1629 self.selected_item = self.actions.len() - 1;
1630 self.scroll_handle
1631 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1632 cx.notify()
1633 }
1634
1635 fn visible(&self) -> bool {
1636 !self.actions.is_empty()
1637 }
1638
1639 fn render(
1640 &self,
1641 cursor_position: DisplayPoint,
1642 _style: &EditorStyle,
1643 max_height: Pixels,
1644 cx: &mut ViewContext<Editor>,
1645 ) -> (ContextMenuOrigin, AnyElement) {
1646 let actions = self.actions.clone();
1647 let selected_item = self.selected_item;
1648 let element = uniform_list(
1649 cx.view().clone(),
1650 "code_actions_menu",
1651 self.actions.len(),
1652 move |_this, range, cx| {
1653 actions
1654 .iter()
1655 .skip(range.start)
1656 .take(range.end - range.start)
1657 .enumerate()
1658 .map(|(ix, action)| {
1659 let item_ix = range.start + ix;
1660 let selected = selected_item == item_ix;
1661 let colors = cx.theme().colors();
1662 div()
1663 .px_1()
1664 .rounded_md()
1665 .text_color(colors.text)
1666 .when(selected, |style| {
1667 style
1668 .bg(colors.element_active)
1669 .text_color(colors.text_accent)
1670 })
1671 .hover(|style| {
1672 style
1673 .bg(colors.element_hover)
1674 .text_color(colors.text_accent)
1675 })
1676 .whitespace_nowrap()
1677 .when_some(action.as_code_action(), |this, action| {
1678 this.on_mouse_down(
1679 MouseButton::Left,
1680 cx.listener(move |editor, _, cx| {
1681 cx.stop_propagation();
1682 if let Some(task) = editor.confirm_code_action(
1683 &ConfirmCodeAction {
1684 item_ix: Some(item_ix),
1685 },
1686 cx,
1687 ) {
1688 task.detach_and_log_err(cx)
1689 }
1690 }),
1691 )
1692 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1693 .child(SharedString::from(action.lsp_action.title.clone()))
1694 })
1695 .when_some(action.as_task(), |this, task| {
1696 this.on_mouse_down(
1697 MouseButton::Left,
1698 cx.listener(move |editor, _, cx| {
1699 cx.stop_propagation();
1700 if let Some(task) = editor.confirm_code_action(
1701 &ConfirmCodeAction {
1702 item_ix: Some(item_ix),
1703 },
1704 cx,
1705 ) {
1706 task.detach_and_log_err(cx)
1707 }
1708 }),
1709 )
1710 .child(SharedString::from(task.resolved_label.clone()))
1711 })
1712 })
1713 .collect()
1714 },
1715 )
1716 .elevation_1(cx)
1717 .p_1()
1718 .max_h(max_height)
1719 .occlude()
1720 .track_scroll(self.scroll_handle.clone())
1721 .with_width_from_item(
1722 self.actions
1723 .iter()
1724 .enumerate()
1725 .max_by_key(|(_, action)| match action {
1726 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1727 CodeActionsItem::CodeAction { action, .. } => {
1728 action.lsp_action.title.chars().count()
1729 }
1730 })
1731 .map(|(ix, _)| ix),
1732 )
1733 .with_sizing_behavior(ListSizingBehavior::Infer)
1734 .into_any_element();
1735
1736 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1737 ContextMenuOrigin::GutterIndicator(row)
1738 } else {
1739 ContextMenuOrigin::EditorPoint(cursor_position)
1740 };
1741
1742 (cursor_position, element)
1743 }
1744}
1745
1746#[derive(Debug)]
1747struct ActiveDiagnosticGroup {
1748 primary_range: Range<Anchor>,
1749 primary_message: String,
1750 group_id: usize,
1751 blocks: HashMap<CustomBlockId, Diagnostic>,
1752 is_valid: bool,
1753}
1754
1755#[derive(Serialize, Deserialize, Clone, Debug)]
1756pub struct ClipboardSelection {
1757 pub len: usize,
1758 pub is_entire_line: bool,
1759 pub first_line_indent: u32,
1760}
1761
1762#[derive(Debug)]
1763pub(crate) struct NavigationData {
1764 cursor_anchor: Anchor,
1765 cursor_position: Point,
1766 scroll_anchor: ScrollAnchor,
1767 scroll_top_row: u32,
1768}
1769
1770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1771pub enum GotoDefinitionKind {
1772 Symbol,
1773 Declaration,
1774 Type,
1775 Implementation,
1776}
1777
1778#[derive(Debug, Clone)]
1779enum InlayHintRefreshReason {
1780 Toggle(bool),
1781 SettingsChange(InlayHintSettings),
1782 NewLinesShown,
1783 BufferEdited(HashSet<Arc<Language>>),
1784 RefreshRequested,
1785 ExcerptsRemoved(Vec<ExcerptId>),
1786}
1787
1788impl InlayHintRefreshReason {
1789 fn description(&self) -> &'static str {
1790 match self {
1791 Self::Toggle(_) => "toggle",
1792 Self::SettingsChange(_) => "settings change",
1793 Self::NewLinesShown => "new lines shown",
1794 Self::BufferEdited(_) => "buffer edited",
1795 Self::RefreshRequested => "refresh requested",
1796 Self::ExcerptsRemoved(_) => "excerpts removed",
1797 }
1798 }
1799}
1800
1801pub(crate) struct FocusedBlock {
1802 id: BlockId,
1803 focus_handle: WeakFocusHandle,
1804}
1805
1806#[derive(Clone)]
1807struct JumpData {
1808 excerpt_id: ExcerptId,
1809 position: Point,
1810 anchor: text::Anchor,
1811 path: Option<project::ProjectPath>,
1812 line_offset_from_top: u32,
1813}
1814
1815impl Editor {
1816 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1817 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1818 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1819 Self::new(
1820 EditorMode::SingleLine { auto_width: false },
1821 buffer,
1822 None,
1823 false,
1824 cx,
1825 )
1826 }
1827
1828 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1829 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1830 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1831 Self::new(EditorMode::Full, buffer, None, false, cx)
1832 }
1833
1834 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1835 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1836 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1837 Self::new(
1838 EditorMode::SingleLine { auto_width: true },
1839 buffer,
1840 None,
1841 false,
1842 cx,
1843 )
1844 }
1845
1846 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1847 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1848 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1849 Self::new(
1850 EditorMode::AutoHeight { max_lines },
1851 buffer,
1852 None,
1853 false,
1854 cx,
1855 )
1856 }
1857
1858 pub fn for_buffer(
1859 buffer: Model<Buffer>,
1860 project: Option<Model<Project>>,
1861 cx: &mut ViewContext<Self>,
1862 ) -> Self {
1863 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1864 Self::new(EditorMode::Full, buffer, project, false, cx)
1865 }
1866
1867 pub fn for_multibuffer(
1868 buffer: Model<MultiBuffer>,
1869 project: Option<Model<Project>>,
1870 show_excerpt_controls: bool,
1871 cx: &mut ViewContext<Self>,
1872 ) -> Self {
1873 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1874 }
1875
1876 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1877 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1878 let mut clone = Self::new(
1879 self.mode,
1880 self.buffer.clone(),
1881 self.project.clone(),
1882 show_excerpt_controls,
1883 cx,
1884 );
1885 self.display_map.update(cx, |display_map, cx| {
1886 let snapshot = display_map.snapshot(cx);
1887 clone.display_map.update(cx, |display_map, cx| {
1888 display_map.set_state(&snapshot, cx);
1889 });
1890 });
1891 clone.selections.clone_state(&self.selections);
1892 clone.scroll_manager.clone_state(&self.scroll_manager);
1893 clone.searchable = self.searchable;
1894 clone
1895 }
1896
1897 pub fn new(
1898 mode: EditorMode,
1899 buffer: Model<MultiBuffer>,
1900 project: Option<Model<Project>>,
1901 show_excerpt_controls: bool,
1902 cx: &mut ViewContext<Self>,
1903 ) -> Self {
1904 let style = cx.text_style();
1905 let font_size = style.font_size.to_pixels(cx.rem_size());
1906 let editor = cx.view().downgrade();
1907 let fold_placeholder = FoldPlaceholder {
1908 constrain_width: true,
1909 render: Arc::new(move |fold_id, fold_range, cx| {
1910 let editor = editor.clone();
1911 div()
1912 .id(fold_id)
1913 .bg(cx.theme().colors().ghost_element_background)
1914 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1915 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1916 .rounded_sm()
1917 .size_full()
1918 .cursor_pointer()
1919 .child("⋯")
1920 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1921 .on_click(move |_, cx| {
1922 editor
1923 .update(cx, |editor, cx| {
1924 editor.unfold_ranges(
1925 &[fold_range.start..fold_range.end],
1926 true,
1927 false,
1928 cx,
1929 );
1930 cx.stop_propagation();
1931 })
1932 .ok();
1933 })
1934 .into_any()
1935 }),
1936 merge_adjacent: true,
1937 ..Default::default()
1938 };
1939 let display_map = cx.new_model(|cx| {
1940 DisplayMap::new(
1941 buffer.clone(),
1942 style.font(),
1943 font_size,
1944 None,
1945 show_excerpt_controls,
1946 FILE_HEADER_HEIGHT,
1947 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1948 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1949 fold_placeholder,
1950 cx,
1951 )
1952 });
1953
1954 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1955
1956 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1957
1958 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1959 .then(|| language_settings::SoftWrap::None);
1960
1961 let mut project_subscriptions = Vec::new();
1962 if mode == EditorMode::Full {
1963 if let Some(project) = project.as_ref() {
1964 if buffer.read(cx).is_singleton() {
1965 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1966 cx.emit(EditorEvent::TitleChanged);
1967 }));
1968 }
1969 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1970 if let project::Event::RefreshInlayHints = event {
1971 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1972 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1973 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1974 let focus_handle = editor.focus_handle(cx);
1975 if focus_handle.is_focused(cx) {
1976 let snapshot = buffer.read(cx).snapshot();
1977 for (range, snippet) in snippet_edits {
1978 let editor_range =
1979 language::range_from_lsp(*range).to_offset(&snapshot);
1980 editor
1981 .insert_snippet(&[editor_range], snippet.clone(), cx)
1982 .ok();
1983 }
1984 }
1985 }
1986 }
1987 }));
1988 if let Some(task_inventory) = project
1989 .read(cx)
1990 .task_store()
1991 .read(cx)
1992 .task_inventory()
1993 .cloned()
1994 {
1995 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1996 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1997 }));
1998 }
1999 }
2000 }
2001
2002 let inlay_hint_settings = inlay_hint_settings(
2003 selections.newest_anchor().head(),
2004 &buffer.read(cx).snapshot(cx),
2005 cx,
2006 );
2007 let focus_handle = cx.focus_handle();
2008 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2009 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2010 .detach();
2011 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2012 .detach();
2013 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2014
2015 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2016 Some(false)
2017 } else {
2018 None
2019 };
2020
2021 let mut code_action_providers = Vec::new();
2022 if let Some(project) = project.clone() {
2023 code_action_providers.push(Arc::new(project) as Arc<_>);
2024 }
2025
2026 let mut this = Self {
2027 focus_handle,
2028 show_cursor_when_unfocused: false,
2029 last_focused_descendant: None,
2030 buffer: buffer.clone(),
2031 display_map: display_map.clone(),
2032 selections,
2033 scroll_manager: ScrollManager::new(cx),
2034 columnar_selection_tail: None,
2035 add_selections_state: None,
2036 select_next_state: None,
2037 select_prev_state: None,
2038 selection_history: Default::default(),
2039 autoclose_regions: Default::default(),
2040 snippet_stack: Default::default(),
2041 select_larger_syntax_node_stack: Vec::new(),
2042 ime_transaction: Default::default(),
2043 active_diagnostics: None,
2044 soft_wrap_mode_override,
2045 completion_provider: project.clone().map(|project| Box::new(project) as _),
2046 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2047 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2048 project,
2049 blink_manager: blink_manager.clone(),
2050 show_local_selections: true,
2051 mode,
2052 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2053 show_gutter: mode == EditorMode::Full,
2054 show_line_numbers: None,
2055 use_relative_line_numbers: None,
2056 show_git_diff_gutter: None,
2057 show_code_actions: None,
2058 show_runnables: None,
2059 show_wrap_guides: None,
2060 show_indent_guides,
2061 placeholder_text: None,
2062 highlight_order: 0,
2063 highlighted_rows: HashMap::default(),
2064 background_highlights: Default::default(),
2065 gutter_highlights: TreeMap::default(),
2066 scrollbar_marker_state: ScrollbarMarkerState::default(),
2067 active_indent_guides_state: ActiveIndentGuidesState::default(),
2068 nav_history: None,
2069 context_menu: RwLock::new(None),
2070 mouse_context_menu: None,
2071 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2072 completion_tasks: Default::default(),
2073 signature_help_state: SignatureHelpState::default(),
2074 auto_signature_help: None,
2075 find_all_references_task_sources: Vec::new(),
2076 next_completion_id: 0,
2077 next_inlay_id: 0,
2078 code_action_providers,
2079 available_code_actions: Default::default(),
2080 code_actions_task: Default::default(),
2081 document_highlights_task: Default::default(),
2082 linked_editing_range_task: Default::default(),
2083 pending_rename: Default::default(),
2084 searchable: true,
2085 cursor_shape: EditorSettings::get_global(cx)
2086 .cursor_shape
2087 .unwrap_or_default(),
2088 current_line_highlight: None,
2089 autoindent_mode: Some(AutoindentMode::EachLine),
2090 collapse_matches: false,
2091 workspace: None,
2092 input_enabled: true,
2093 use_modal_editing: mode == EditorMode::Full,
2094 read_only: false,
2095 use_autoclose: true,
2096 use_auto_surround: true,
2097 auto_replace_emoji_shortcode: false,
2098 leader_peer_id: None,
2099 remote_id: None,
2100 hover_state: Default::default(),
2101 hovered_link_state: Default::default(),
2102 inline_completion_provider: None,
2103 active_inline_completion: None,
2104 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2105 expanded_hunks: ExpandedHunks::default(),
2106 gutter_hovered: false,
2107 pixel_position_of_newest_cursor: None,
2108 last_bounds: None,
2109 expect_bounds_change: None,
2110 gutter_dimensions: GutterDimensions::default(),
2111 style: None,
2112 show_cursor_names: false,
2113 hovered_cursors: Default::default(),
2114 next_editor_action_id: EditorActionId::default(),
2115 editor_actions: Rc::default(),
2116 show_inline_completions_override: None,
2117 enable_inline_completions: true,
2118 custom_context_menu: None,
2119 show_git_blame_gutter: false,
2120 show_git_blame_inline: false,
2121 show_selection_menu: None,
2122 show_git_blame_inline_delay_task: None,
2123 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2124 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2125 .session
2126 .restore_unsaved_buffers,
2127 blame: None,
2128 blame_subscription: None,
2129 tasks: Default::default(),
2130 _subscriptions: vec![
2131 cx.observe(&buffer, Self::on_buffer_changed),
2132 cx.subscribe(&buffer, Self::on_buffer_event),
2133 cx.observe(&display_map, Self::on_display_map_changed),
2134 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2135 cx.observe_global::<SettingsStore>(Self::settings_changed),
2136 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2137 cx.observe_window_activation(|editor, cx| {
2138 let active = cx.is_window_active();
2139 editor.blink_manager.update(cx, |blink_manager, cx| {
2140 if active {
2141 blink_manager.enable(cx);
2142 } else {
2143 blink_manager.disable(cx);
2144 }
2145 });
2146 }),
2147 ],
2148 tasks_update_task: None,
2149 linked_edit_ranges: Default::default(),
2150 previous_search_ranges: None,
2151 breadcrumb_header: None,
2152 focused_block: None,
2153 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2154 addons: HashMap::default(),
2155 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2156 text_style_refinement: None,
2157 };
2158 this.tasks_update_task = Some(this.refresh_runnables(cx));
2159 this._subscriptions.extend(project_subscriptions);
2160
2161 this.end_selection(cx);
2162 this.scroll_manager.show_scrollbar(cx);
2163
2164 if mode == EditorMode::Full {
2165 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2166 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2167
2168 if this.git_blame_inline_enabled {
2169 this.git_blame_inline_enabled = true;
2170 this.start_git_blame_inline(false, cx);
2171 }
2172 }
2173
2174 this.report_editor_event("open", None, cx);
2175 this
2176 }
2177
2178 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2179 self.mouse_context_menu
2180 .as_ref()
2181 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2182 }
2183
2184 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2185 let mut key_context = KeyContext::new_with_defaults();
2186 key_context.add("Editor");
2187 let mode = match self.mode {
2188 EditorMode::SingleLine { .. } => "single_line",
2189 EditorMode::AutoHeight { .. } => "auto_height",
2190 EditorMode::Full => "full",
2191 };
2192
2193 if EditorSettings::jupyter_enabled(cx) {
2194 key_context.add("jupyter");
2195 }
2196
2197 key_context.set("mode", mode);
2198 if self.pending_rename.is_some() {
2199 key_context.add("renaming");
2200 }
2201 if self.context_menu_visible() {
2202 match self.context_menu.read().as_ref() {
2203 Some(ContextMenu::Completions(_)) => {
2204 key_context.add("menu");
2205 key_context.add("showing_completions")
2206 }
2207 Some(ContextMenu::CodeActions(_)) => {
2208 key_context.add("menu");
2209 key_context.add("showing_code_actions")
2210 }
2211 None => {}
2212 }
2213 }
2214
2215 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2216 if !self.focus_handle(cx).contains_focused(cx)
2217 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2218 {
2219 for addon in self.addons.values() {
2220 addon.extend_key_context(&mut key_context, cx)
2221 }
2222 }
2223
2224 if let Some(extension) = self
2225 .buffer
2226 .read(cx)
2227 .as_singleton()
2228 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2229 {
2230 key_context.set("extension", extension.to_string());
2231 }
2232
2233 if self.has_active_inline_completion(cx) {
2234 key_context.add("copilot_suggestion");
2235 key_context.add("inline_completion");
2236 }
2237
2238 key_context
2239 }
2240
2241 pub fn new_file(
2242 workspace: &mut Workspace,
2243 _: &workspace::NewFile,
2244 cx: &mut ViewContext<Workspace>,
2245 ) {
2246 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2247 "Failed to create buffer",
2248 cx,
2249 |e, _| match e.error_code() {
2250 ErrorCode::RemoteUpgradeRequired => Some(format!(
2251 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2252 e.error_tag("required").unwrap_or("the latest version")
2253 )),
2254 _ => None,
2255 },
2256 );
2257 }
2258
2259 pub fn new_in_workspace(
2260 workspace: &mut Workspace,
2261 cx: &mut ViewContext<Workspace>,
2262 ) -> Task<Result<View<Editor>>> {
2263 let project = workspace.project().clone();
2264 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2265
2266 cx.spawn(|workspace, mut cx| async move {
2267 let buffer = create.await?;
2268 workspace.update(&mut cx, |workspace, cx| {
2269 let editor =
2270 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2271 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2272 editor
2273 })
2274 })
2275 }
2276
2277 fn new_file_vertical(
2278 workspace: &mut Workspace,
2279 _: &workspace::NewFileSplitVertical,
2280 cx: &mut ViewContext<Workspace>,
2281 ) {
2282 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2283 }
2284
2285 fn new_file_horizontal(
2286 workspace: &mut Workspace,
2287 _: &workspace::NewFileSplitHorizontal,
2288 cx: &mut ViewContext<Workspace>,
2289 ) {
2290 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2291 }
2292
2293 fn new_file_in_direction(
2294 workspace: &mut Workspace,
2295 direction: SplitDirection,
2296 cx: &mut ViewContext<Workspace>,
2297 ) {
2298 let project = workspace.project().clone();
2299 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2300
2301 cx.spawn(|workspace, mut cx| async move {
2302 let buffer = create.await?;
2303 workspace.update(&mut cx, move |workspace, cx| {
2304 workspace.split_item(
2305 direction,
2306 Box::new(
2307 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2308 ),
2309 cx,
2310 )
2311 })?;
2312 anyhow::Ok(())
2313 })
2314 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2315 ErrorCode::RemoteUpgradeRequired => Some(format!(
2316 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2317 e.error_tag("required").unwrap_or("the latest version")
2318 )),
2319 _ => None,
2320 });
2321 }
2322
2323 pub fn leader_peer_id(&self) -> Option<PeerId> {
2324 self.leader_peer_id
2325 }
2326
2327 pub fn buffer(&self) -> &Model<MultiBuffer> {
2328 &self.buffer
2329 }
2330
2331 pub fn workspace(&self) -> Option<View<Workspace>> {
2332 self.workspace.as_ref()?.0.upgrade()
2333 }
2334
2335 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2336 self.buffer().read(cx).title(cx)
2337 }
2338
2339 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2340 let git_blame_gutter_max_author_length = self
2341 .render_git_blame_gutter(cx)
2342 .then(|| {
2343 if let Some(blame) = self.blame.as_ref() {
2344 let max_author_length =
2345 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2346 Some(max_author_length)
2347 } else {
2348 None
2349 }
2350 })
2351 .flatten();
2352
2353 EditorSnapshot {
2354 mode: self.mode,
2355 show_gutter: self.show_gutter,
2356 show_line_numbers: self.show_line_numbers,
2357 show_git_diff_gutter: self.show_git_diff_gutter,
2358 show_code_actions: self.show_code_actions,
2359 show_runnables: self.show_runnables,
2360 git_blame_gutter_max_author_length,
2361 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2362 scroll_anchor: self.scroll_manager.anchor(),
2363 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2364 placeholder_text: self.placeholder_text.clone(),
2365 is_focused: self.focus_handle.is_focused(cx),
2366 current_line_highlight: self
2367 .current_line_highlight
2368 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2369 gutter_hovered: self.gutter_hovered,
2370 }
2371 }
2372
2373 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2374 self.buffer.read(cx).language_at(point, cx)
2375 }
2376
2377 pub fn file_at<T: ToOffset>(
2378 &self,
2379 point: T,
2380 cx: &AppContext,
2381 ) -> Option<Arc<dyn language::File>> {
2382 self.buffer.read(cx).read(cx).file_at(point).cloned()
2383 }
2384
2385 pub fn active_excerpt(
2386 &self,
2387 cx: &AppContext,
2388 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2389 self.buffer
2390 .read(cx)
2391 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2392 }
2393
2394 pub fn mode(&self) -> EditorMode {
2395 self.mode
2396 }
2397
2398 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2399 self.collaboration_hub.as_deref()
2400 }
2401
2402 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2403 self.collaboration_hub = Some(hub);
2404 }
2405
2406 pub fn set_custom_context_menu(
2407 &mut self,
2408 f: impl 'static
2409 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2410 ) {
2411 self.custom_context_menu = Some(Box::new(f))
2412 }
2413
2414 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2415 self.completion_provider = provider;
2416 }
2417
2418 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2419 self.semantics_provider.clone()
2420 }
2421
2422 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2423 self.semantics_provider = provider;
2424 }
2425
2426 pub fn set_inline_completion_provider<T>(
2427 &mut self,
2428 provider: Option<Model<T>>,
2429 cx: &mut ViewContext<Self>,
2430 ) where
2431 T: InlineCompletionProvider,
2432 {
2433 self.inline_completion_provider =
2434 provider.map(|provider| RegisteredInlineCompletionProvider {
2435 _subscription: cx.observe(&provider, |this, _, cx| {
2436 if this.focus_handle.is_focused(cx) {
2437 this.update_visible_inline_completion(cx);
2438 }
2439 }),
2440 provider: Arc::new(provider),
2441 });
2442 self.refresh_inline_completion(false, false, cx);
2443 }
2444
2445 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2446 self.placeholder_text.as_deref()
2447 }
2448
2449 pub fn set_placeholder_text(
2450 &mut self,
2451 placeholder_text: impl Into<Arc<str>>,
2452 cx: &mut ViewContext<Self>,
2453 ) {
2454 let placeholder_text = Some(placeholder_text.into());
2455 if self.placeholder_text != placeholder_text {
2456 self.placeholder_text = placeholder_text;
2457 cx.notify();
2458 }
2459 }
2460
2461 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2462 self.cursor_shape = cursor_shape;
2463
2464 // Disrupt blink for immediate user feedback that the cursor shape has changed
2465 self.blink_manager.update(cx, BlinkManager::show_cursor);
2466
2467 cx.notify();
2468 }
2469
2470 pub fn set_current_line_highlight(
2471 &mut self,
2472 current_line_highlight: Option<CurrentLineHighlight>,
2473 ) {
2474 self.current_line_highlight = current_line_highlight;
2475 }
2476
2477 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2478 self.collapse_matches = collapse_matches;
2479 }
2480
2481 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2482 if self.collapse_matches {
2483 return range.start..range.start;
2484 }
2485 range.clone()
2486 }
2487
2488 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2489 if self.display_map.read(cx).clip_at_line_ends != clip {
2490 self.display_map
2491 .update(cx, |map, _| map.clip_at_line_ends = clip);
2492 }
2493 }
2494
2495 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2496 self.input_enabled = input_enabled;
2497 }
2498
2499 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2500 self.enable_inline_completions = enabled;
2501 }
2502
2503 pub fn set_autoindent(&mut self, autoindent: bool) {
2504 if autoindent {
2505 self.autoindent_mode = Some(AutoindentMode::EachLine);
2506 } else {
2507 self.autoindent_mode = None;
2508 }
2509 }
2510
2511 pub fn read_only(&self, cx: &AppContext) -> bool {
2512 self.read_only || self.buffer.read(cx).read_only()
2513 }
2514
2515 pub fn set_read_only(&mut self, read_only: bool) {
2516 self.read_only = read_only;
2517 }
2518
2519 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2520 self.use_autoclose = autoclose;
2521 }
2522
2523 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2524 self.use_auto_surround = auto_surround;
2525 }
2526
2527 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2528 self.auto_replace_emoji_shortcode = auto_replace;
2529 }
2530
2531 pub fn toggle_inline_completions(
2532 &mut self,
2533 _: &ToggleInlineCompletions,
2534 cx: &mut ViewContext<Self>,
2535 ) {
2536 if self.show_inline_completions_override.is_some() {
2537 self.set_show_inline_completions(None, cx);
2538 } else {
2539 let cursor = self.selections.newest_anchor().head();
2540 if let Some((buffer, cursor_buffer_position)) =
2541 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2542 {
2543 let show_inline_completions =
2544 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2545 self.set_show_inline_completions(Some(show_inline_completions), cx);
2546 }
2547 }
2548 }
2549
2550 pub fn set_show_inline_completions(
2551 &mut self,
2552 show_inline_completions: Option<bool>,
2553 cx: &mut ViewContext<Self>,
2554 ) {
2555 self.show_inline_completions_override = show_inline_completions;
2556 self.refresh_inline_completion(false, true, cx);
2557 }
2558
2559 fn should_show_inline_completions(
2560 &self,
2561 buffer: &Model<Buffer>,
2562 buffer_position: language::Anchor,
2563 cx: &AppContext,
2564 ) -> bool {
2565 if !self.snippet_stack.is_empty() {
2566 return false;
2567 }
2568
2569 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2570 return false;
2571 }
2572
2573 if let Some(provider) = self.inline_completion_provider() {
2574 if let Some(show_inline_completions) = self.show_inline_completions_override {
2575 show_inline_completions
2576 } else {
2577 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2578 }
2579 } else {
2580 false
2581 }
2582 }
2583
2584 fn inline_completions_disabled_in_scope(
2585 &self,
2586 buffer: &Model<Buffer>,
2587 buffer_position: language::Anchor,
2588 cx: &AppContext,
2589 ) -> bool {
2590 let snapshot = buffer.read(cx).snapshot();
2591 let settings = snapshot.settings_at(buffer_position, cx);
2592
2593 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2594 return false;
2595 };
2596
2597 scope.override_name().map_or(false, |scope_name| {
2598 settings
2599 .inline_completions_disabled_in
2600 .iter()
2601 .any(|s| s == scope_name)
2602 })
2603 }
2604
2605 pub fn set_use_modal_editing(&mut self, to: bool) {
2606 self.use_modal_editing = to;
2607 }
2608
2609 pub fn use_modal_editing(&self) -> bool {
2610 self.use_modal_editing
2611 }
2612
2613 fn selections_did_change(
2614 &mut self,
2615 local: bool,
2616 old_cursor_position: &Anchor,
2617 show_completions: bool,
2618 cx: &mut ViewContext<Self>,
2619 ) {
2620 cx.invalidate_character_coordinates();
2621
2622 // Copy selections to primary selection buffer
2623 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2624 if local {
2625 let selections = self.selections.all::<usize>(cx);
2626 let buffer_handle = self.buffer.read(cx).read(cx);
2627
2628 let mut text = String::new();
2629 for (index, selection) in selections.iter().enumerate() {
2630 let text_for_selection = buffer_handle
2631 .text_for_range(selection.start..selection.end)
2632 .collect::<String>();
2633
2634 text.push_str(&text_for_selection);
2635 if index != selections.len() - 1 {
2636 text.push('\n');
2637 }
2638 }
2639
2640 if !text.is_empty() {
2641 cx.write_to_primary(ClipboardItem::new_string(text));
2642 }
2643 }
2644
2645 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2646 self.buffer.update(cx, |buffer, cx| {
2647 buffer.set_active_selections(
2648 &self.selections.disjoint_anchors(),
2649 self.selections.line_mode,
2650 self.cursor_shape,
2651 cx,
2652 )
2653 });
2654 }
2655 let display_map = self
2656 .display_map
2657 .update(cx, |display_map, cx| display_map.snapshot(cx));
2658 let buffer = &display_map.buffer_snapshot;
2659 self.add_selections_state = None;
2660 self.select_next_state = None;
2661 self.select_prev_state = None;
2662 self.select_larger_syntax_node_stack.clear();
2663 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2664 self.snippet_stack
2665 .invalidate(&self.selections.disjoint_anchors(), buffer);
2666 self.take_rename(false, cx);
2667
2668 let new_cursor_position = self.selections.newest_anchor().head();
2669
2670 self.push_to_nav_history(
2671 *old_cursor_position,
2672 Some(new_cursor_position.to_point(buffer)),
2673 cx,
2674 );
2675
2676 if local {
2677 let new_cursor_position = self.selections.newest_anchor().head();
2678 let mut context_menu = self.context_menu.write();
2679 let completion_menu = match context_menu.as_ref() {
2680 Some(ContextMenu::Completions(menu)) => Some(menu),
2681
2682 _ => {
2683 *context_menu = None;
2684 None
2685 }
2686 };
2687
2688 if let Some(completion_menu) = completion_menu {
2689 let cursor_position = new_cursor_position.to_offset(buffer);
2690 let (word_range, kind) =
2691 buffer.surrounding_word(completion_menu.initial_position, true);
2692 if kind == Some(CharKind::Word)
2693 && word_range.to_inclusive().contains(&cursor_position)
2694 {
2695 let mut completion_menu = completion_menu.clone();
2696 drop(context_menu);
2697
2698 let query = Self::completion_query(buffer, cursor_position);
2699 cx.spawn(move |this, mut cx| async move {
2700 completion_menu
2701 .filter(query.as_deref(), cx.background_executor().clone())
2702 .await;
2703
2704 this.update(&mut cx, |this, cx| {
2705 let mut context_menu = this.context_menu.write();
2706 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2707 return;
2708 };
2709
2710 if menu.id > completion_menu.id {
2711 return;
2712 }
2713
2714 *context_menu = Some(ContextMenu::Completions(completion_menu));
2715 drop(context_menu);
2716 cx.notify();
2717 })
2718 })
2719 .detach();
2720
2721 if show_completions {
2722 self.show_completions(&ShowCompletions { trigger: None }, cx);
2723 }
2724 } else {
2725 drop(context_menu);
2726 self.hide_context_menu(cx);
2727 }
2728 } else {
2729 drop(context_menu);
2730 }
2731
2732 hide_hover(self, cx);
2733
2734 if old_cursor_position.to_display_point(&display_map).row()
2735 != new_cursor_position.to_display_point(&display_map).row()
2736 {
2737 self.available_code_actions.take();
2738 }
2739 self.refresh_code_actions(cx);
2740 self.refresh_document_highlights(cx);
2741 refresh_matching_bracket_highlights(self, cx);
2742 self.discard_inline_completion(false, cx);
2743 linked_editing_ranges::refresh_linked_ranges(self, cx);
2744 if self.git_blame_inline_enabled {
2745 self.start_inline_blame_timer(cx);
2746 }
2747 }
2748
2749 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2750 cx.emit(EditorEvent::SelectionsChanged { local });
2751
2752 if self.selections.disjoint_anchors().len() == 1 {
2753 cx.emit(SearchEvent::ActiveMatchChanged)
2754 }
2755 cx.notify();
2756 }
2757
2758 pub fn change_selections<R>(
2759 &mut self,
2760 autoscroll: Option<Autoscroll>,
2761 cx: &mut ViewContext<Self>,
2762 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2763 ) -> R {
2764 self.change_selections_inner(autoscroll, true, cx, change)
2765 }
2766
2767 pub fn change_selections_inner<R>(
2768 &mut self,
2769 autoscroll: Option<Autoscroll>,
2770 request_completions: bool,
2771 cx: &mut ViewContext<Self>,
2772 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2773 ) -> R {
2774 let old_cursor_position = self.selections.newest_anchor().head();
2775 self.push_to_selection_history();
2776
2777 let (changed, result) = self.selections.change_with(cx, change);
2778
2779 if changed {
2780 if let Some(autoscroll) = autoscroll {
2781 self.request_autoscroll(autoscroll, cx);
2782 }
2783 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2784
2785 if self.should_open_signature_help_automatically(
2786 &old_cursor_position,
2787 self.signature_help_state.backspace_pressed(),
2788 cx,
2789 ) {
2790 self.show_signature_help(&ShowSignatureHelp, cx);
2791 }
2792 self.signature_help_state.set_backspace_pressed(false);
2793 }
2794
2795 result
2796 }
2797
2798 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2799 where
2800 I: IntoIterator<Item = (Range<S>, T)>,
2801 S: ToOffset,
2802 T: Into<Arc<str>>,
2803 {
2804 if self.read_only(cx) {
2805 return;
2806 }
2807
2808 self.buffer
2809 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2810 }
2811
2812 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2813 where
2814 I: IntoIterator<Item = (Range<S>, T)>,
2815 S: ToOffset,
2816 T: Into<Arc<str>>,
2817 {
2818 if self.read_only(cx) {
2819 return;
2820 }
2821
2822 self.buffer.update(cx, |buffer, cx| {
2823 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2824 });
2825 }
2826
2827 pub fn edit_with_block_indent<I, S, T>(
2828 &mut self,
2829 edits: I,
2830 original_indent_columns: Vec<u32>,
2831 cx: &mut ViewContext<Self>,
2832 ) where
2833 I: IntoIterator<Item = (Range<S>, T)>,
2834 S: ToOffset,
2835 T: Into<Arc<str>>,
2836 {
2837 if self.read_only(cx) {
2838 return;
2839 }
2840
2841 self.buffer.update(cx, |buffer, cx| {
2842 buffer.edit(
2843 edits,
2844 Some(AutoindentMode::Block {
2845 original_indent_columns,
2846 }),
2847 cx,
2848 )
2849 });
2850 }
2851
2852 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2853 self.hide_context_menu(cx);
2854
2855 match phase {
2856 SelectPhase::Begin {
2857 position,
2858 add,
2859 click_count,
2860 } => self.begin_selection(position, add, click_count, cx),
2861 SelectPhase::BeginColumnar {
2862 position,
2863 goal_column,
2864 reset,
2865 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2866 SelectPhase::Extend {
2867 position,
2868 click_count,
2869 } => self.extend_selection(position, click_count, cx),
2870 SelectPhase::Update {
2871 position,
2872 goal_column,
2873 scroll_delta,
2874 } => self.update_selection(position, goal_column, scroll_delta, cx),
2875 SelectPhase::End => self.end_selection(cx),
2876 }
2877 }
2878
2879 fn extend_selection(
2880 &mut self,
2881 position: DisplayPoint,
2882 click_count: usize,
2883 cx: &mut ViewContext<Self>,
2884 ) {
2885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2886 let tail = self.selections.newest::<usize>(cx).tail();
2887 self.begin_selection(position, false, click_count, cx);
2888
2889 let position = position.to_offset(&display_map, Bias::Left);
2890 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2891
2892 let mut pending_selection = self
2893 .selections
2894 .pending_anchor()
2895 .expect("extend_selection not called with pending selection");
2896 if position >= tail {
2897 pending_selection.start = tail_anchor;
2898 } else {
2899 pending_selection.end = tail_anchor;
2900 pending_selection.reversed = true;
2901 }
2902
2903 let mut pending_mode = self.selections.pending_mode().unwrap();
2904 match &mut pending_mode {
2905 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2906 _ => {}
2907 }
2908
2909 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2910 s.set_pending(pending_selection, pending_mode)
2911 });
2912 }
2913
2914 fn begin_selection(
2915 &mut self,
2916 position: DisplayPoint,
2917 add: bool,
2918 click_count: usize,
2919 cx: &mut ViewContext<Self>,
2920 ) {
2921 if !self.focus_handle.is_focused(cx) {
2922 self.last_focused_descendant = None;
2923 cx.focus(&self.focus_handle);
2924 }
2925
2926 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2927 let buffer = &display_map.buffer_snapshot;
2928 let newest_selection = self.selections.newest_anchor().clone();
2929 let position = display_map.clip_point(position, Bias::Left);
2930
2931 let start;
2932 let end;
2933 let mode;
2934 let auto_scroll;
2935 match click_count {
2936 1 => {
2937 start = buffer.anchor_before(position.to_point(&display_map));
2938 end = start;
2939 mode = SelectMode::Character;
2940 auto_scroll = true;
2941 }
2942 2 => {
2943 let range = movement::surrounding_word(&display_map, position);
2944 start = buffer.anchor_before(range.start.to_point(&display_map));
2945 end = buffer.anchor_before(range.end.to_point(&display_map));
2946 mode = SelectMode::Word(start..end);
2947 auto_scroll = true;
2948 }
2949 3 => {
2950 let position = display_map
2951 .clip_point(position, Bias::Left)
2952 .to_point(&display_map);
2953 let line_start = display_map.prev_line_boundary(position).0;
2954 let next_line_start = buffer.clip_point(
2955 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2956 Bias::Left,
2957 );
2958 start = buffer.anchor_before(line_start);
2959 end = buffer.anchor_before(next_line_start);
2960 mode = SelectMode::Line(start..end);
2961 auto_scroll = true;
2962 }
2963 _ => {
2964 start = buffer.anchor_before(0);
2965 end = buffer.anchor_before(buffer.len());
2966 mode = SelectMode::All;
2967 auto_scroll = false;
2968 }
2969 }
2970
2971 let point_to_delete: Option<usize> = {
2972 let selected_points: Vec<Selection<Point>> =
2973 self.selections.disjoint_in_range(start..end, cx);
2974
2975 if !add || click_count > 1 {
2976 None
2977 } else if !selected_points.is_empty() {
2978 Some(selected_points[0].id)
2979 } else {
2980 let clicked_point_already_selected =
2981 self.selections.disjoint.iter().find(|selection| {
2982 selection.start.to_point(buffer) == start.to_point(buffer)
2983 || selection.end.to_point(buffer) == end.to_point(buffer)
2984 });
2985
2986 clicked_point_already_selected.map(|selection| selection.id)
2987 }
2988 };
2989
2990 let selections_count = self.selections.count();
2991
2992 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2993 if let Some(point_to_delete) = point_to_delete {
2994 s.delete(point_to_delete);
2995
2996 if selections_count == 1 {
2997 s.set_pending_anchor_range(start..end, mode);
2998 }
2999 } else {
3000 if !add {
3001 s.clear_disjoint();
3002 } else if click_count > 1 {
3003 s.delete(newest_selection.id)
3004 }
3005
3006 s.set_pending_anchor_range(start..end, mode);
3007 }
3008 });
3009 }
3010
3011 fn begin_columnar_selection(
3012 &mut self,
3013 position: DisplayPoint,
3014 goal_column: u32,
3015 reset: bool,
3016 cx: &mut ViewContext<Self>,
3017 ) {
3018 if !self.focus_handle.is_focused(cx) {
3019 self.last_focused_descendant = None;
3020 cx.focus(&self.focus_handle);
3021 }
3022
3023 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3024
3025 if reset {
3026 let pointer_position = display_map
3027 .buffer_snapshot
3028 .anchor_before(position.to_point(&display_map));
3029
3030 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3031 s.clear_disjoint();
3032 s.set_pending_anchor_range(
3033 pointer_position..pointer_position,
3034 SelectMode::Character,
3035 );
3036 });
3037 }
3038
3039 let tail = self.selections.newest::<Point>(cx).tail();
3040 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3041
3042 if !reset {
3043 self.select_columns(
3044 tail.to_display_point(&display_map),
3045 position,
3046 goal_column,
3047 &display_map,
3048 cx,
3049 );
3050 }
3051 }
3052
3053 fn update_selection(
3054 &mut self,
3055 position: DisplayPoint,
3056 goal_column: u32,
3057 scroll_delta: gpui::Point<f32>,
3058 cx: &mut ViewContext<Self>,
3059 ) {
3060 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3061
3062 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3063 let tail = tail.to_display_point(&display_map);
3064 self.select_columns(tail, position, goal_column, &display_map, cx);
3065 } else if let Some(mut pending) = self.selections.pending_anchor() {
3066 let buffer = self.buffer.read(cx).snapshot(cx);
3067 let head;
3068 let tail;
3069 let mode = self.selections.pending_mode().unwrap();
3070 match &mode {
3071 SelectMode::Character => {
3072 head = position.to_point(&display_map);
3073 tail = pending.tail().to_point(&buffer);
3074 }
3075 SelectMode::Word(original_range) => {
3076 let original_display_range = original_range.start.to_display_point(&display_map)
3077 ..original_range.end.to_display_point(&display_map);
3078 let original_buffer_range = original_display_range.start.to_point(&display_map)
3079 ..original_display_range.end.to_point(&display_map);
3080 if movement::is_inside_word(&display_map, position)
3081 || original_display_range.contains(&position)
3082 {
3083 let word_range = movement::surrounding_word(&display_map, position);
3084 if word_range.start < original_display_range.start {
3085 head = word_range.start.to_point(&display_map);
3086 } else {
3087 head = word_range.end.to_point(&display_map);
3088 }
3089 } else {
3090 head = position.to_point(&display_map);
3091 }
3092
3093 if head <= original_buffer_range.start {
3094 tail = original_buffer_range.end;
3095 } else {
3096 tail = original_buffer_range.start;
3097 }
3098 }
3099 SelectMode::Line(original_range) => {
3100 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3101
3102 let position = display_map
3103 .clip_point(position, Bias::Left)
3104 .to_point(&display_map);
3105 let line_start = display_map.prev_line_boundary(position).0;
3106 let next_line_start = buffer.clip_point(
3107 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3108 Bias::Left,
3109 );
3110
3111 if line_start < original_range.start {
3112 head = line_start
3113 } else {
3114 head = next_line_start
3115 }
3116
3117 if head <= original_range.start {
3118 tail = original_range.end;
3119 } else {
3120 tail = original_range.start;
3121 }
3122 }
3123 SelectMode::All => {
3124 return;
3125 }
3126 };
3127
3128 if head < tail {
3129 pending.start = buffer.anchor_before(head);
3130 pending.end = buffer.anchor_before(tail);
3131 pending.reversed = true;
3132 } else {
3133 pending.start = buffer.anchor_before(tail);
3134 pending.end = buffer.anchor_before(head);
3135 pending.reversed = false;
3136 }
3137
3138 self.change_selections(None, cx, |s| {
3139 s.set_pending(pending, mode);
3140 });
3141 } else {
3142 log::error!("update_selection dispatched with no pending selection");
3143 return;
3144 }
3145
3146 self.apply_scroll_delta(scroll_delta, cx);
3147 cx.notify();
3148 }
3149
3150 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3151 self.columnar_selection_tail.take();
3152 if self.selections.pending_anchor().is_some() {
3153 let selections = self.selections.all::<usize>(cx);
3154 self.change_selections(None, cx, |s| {
3155 s.select(selections);
3156 s.clear_pending();
3157 });
3158 }
3159 }
3160
3161 fn select_columns(
3162 &mut self,
3163 tail: DisplayPoint,
3164 head: DisplayPoint,
3165 goal_column: u32,
3166 display_map: &DisplaySnapshot,
3167 cx: &mut ViewContext<Self>,
3168 ) {
3169 let start_row = cmp::min(tail.row(), head.row());
3170 let end_row = cmp::max(tail.row(), head.row());
3171 let start_column = cmp::min(tail.column(), goal_column);
3172 let end_column = cmp::max(tail.column(), goal_column);
3173 let reversed = start_column < tail.column();
3174
3175 let selection_ranges = (start_row.0..=end_row.0)
3176 .map(DisplayRow)
3177 .filter_map(|row| {
3178 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3179 let start = display_map
3180 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3181 .to_point(display_map);
3182 let end = display_map
3183 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3184 .to_point(display_map);
3185 if reversed {
3186 Some(end..start)
3187 } else {
3188 Some(start..end)
3189 }
3190 } else {
3191 None
3192 }
3193 })
3194 .collect::<Vec<_>>();
3195
3196 self.change_selections(None, cx, |s| {
3197 s.select_ranges(selection_ranges);
3198 });
3199 cx.notify();
3200 }
3201
3202 pub fn has_pending_nonempty_selection(&self) -> bool {
3203 let pending_nonempty_selection = match self.selections.pending_anchor() {
3204 Some(Selection { start, end, .. }) => start != end,
3205 None => false,
3206 };
3207
3208 pending_nonempty_selection
3209 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3210 }
3211
3212 pub fn has_pending_selection(&self) -> bool {
3213 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3214 }
3215
3216 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3217 if self.clear_expanded_diff_hunks(cx) {
3218 cx.notify();
3219 return;
3220 }
3221 if self.dismiss_menus_and_popups(true, cx) {
3222 return;
3223 }
3224
3225 if self.mode == EditorMode::Full
3226 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3227 {
3228 return;
3229 }
3230
3231 cx.propagate();
3232 }
3233
3234 pub fn dismiss_menus_and_popups(
3235 &mut self,
3236 should_report_inline_completion_event: bool,
3237 cx: &mut ViewContext<Self>,
3238 ) -> bool {
3239 if self.take_rename(false, cx).is_some() {
3240 return true;
3241 }
3242
3243 if hide_hover(self, cx) {
3244 return true;
3245 }
3246
3247 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3248 return true;
3249 }
3250
3251 if self.hide_context_menu(cx).is_some() {
3252 return true;
3253 }
3254
3255 if self.mouse_context_menu.take().is_some() {
3256 return true;
3257 }
3258
3259 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3260 return true;
3261 }
3262
3263 if self.snippet_stack.pop().is_some() {
3264 return true;
3265 }
3266
3267 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3268 self.dismiss_diagnostics(cx);
3269 return true;
3270 }
3271
3272 false
3273 }
3274
3275 fn linked_editing_ranges_for(
3276 &self,
3277 selection: Range<text::Anchor>,
3278 cx: &AppContext,
3279 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3280 if self.linked_edit_ranges.is_empty() {
3281 return None;
3282 }
3283 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3284 selection.end.buffer_id.and_then(|end_buffer_id| {
3285 if selection.start.buffer_id != Some(end_buffer_id) {
3286 return None;
3287 }
3288 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3289 let snapshot = buffer.read(cx).snapshot();
3290 self.linked_edit_ranges
3291 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3292 .map(|ranges| (ranges, snapshot, buffer))
3293 })?;
3294 use text::ToOffset as TO;
3295 // find offset from the start of current range to current cursor position
3296 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3297
3298 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3299 let start_difference = start_offset - start_byte_offset;
3300 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3301 let end_difference = end_offset - start_byte_offset;
3302 // Current range has associated linked ranges.
3303 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3304 for range in linked_ranges.iter() {
3305 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3306 let end_offset = start_offset + end_difference;
3307 let start_offset = start_offset + start_difference;
3308 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3309 continue;
3310 }
3311 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3312 if s.start.buffer_id != selection.start.buffer_id
3313 || s.end.buffer_id != selection.end.buffer_id
3314 {
3315 return false;
3316 }
3317 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3318 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3319 }) {
3320 continue;
3321 }
3322 let start = buffer_snapshot.anchor_after(start_offset);
3323 let end = buffer_snapshot.anchor_after(end_offset);
3324 linked_edits
3325 .entry(buffer.clone())
3326 .or_default()
3327 .push(start..end);
3328 }
3329 Some(linked_edits)
3330 }
3331
3332 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3333 let text: Arc<str> = text.into();
3334
3335 if self.read_only(cx) {
3336 return;
3337 }
3338
3339 let selections = self.selections.all_adjusted(cx);
3340 let mut bracket_inserted = false;
3341 let mut edits = Vec::new();
3342 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3343 let mut new_selections = Vec::with_capacity(selections.len());
3344 let mut new_autoclose_regions = Vec::new();
3345 let snapshot = self.buffer.read(cx).read(cx);
3346
3347 for (selection, autoclose_region) in
3348 self.selections_with_autoclose_regions(selections, &snapshot)
3349 {
3350 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3351 // Determine if the inserted text matches the opening or closing
3352 // bracket of any of this language's bracket pairs.
3353 let mut bracket_pair = None;
3354 let mut is_bracket_pair_start = false;
3355 let mut is_bracket_pair_end = false;
3356 if !text.is_empty() {
3357 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3358 // and they are removing the character that triggered IME popup.
3359 for (pair, enabled) in scope.brackets() {
3360 if !pair.close && !pair.surround {
3361 continue;
3362 }
3363
3364 if enabled && pair.start.ends_with(text.as_ref()) {
3365 let prefix_len = pair.start.len() - text.len();
3366 let preceding_text_matches_prefix = prefix_len == 0
3367 || (selection.start.column >= (prefix_len as u32)
3368 && snapshot.contains_str_at(
3369 Point::new(
3370 selection.start.row,
3371 selection.start.column - (prefix_len as u32),
3372 ),
3373 &pair.start[..prefix_len],
3374 ));
3375 if preceding_text_matches_prefix {
3376 bracket_pair = Some(pair.clone());
3377 is_bracket_pair_start = true;
3378 break;
3379 }
3380 }
3381 if pair.end.as_str() == text.as_ref() {
3382 bracket_pair = Some(pair.clone());
3383 is_bracket_pair_end = true;
3384 break;
3385 }
3386 }
3387 }
3388
3389 if let Some(bracket_pair) = bracket_pair {
3390 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3391 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3392 let auto_surround =
3393 self.use_auto_surround && snapshot_settings.use_auto_surround;
3394 if selection.is_empty() {
3395 if is_bracket_pair_start {
3396 // If the inserted text is a suffix of an opening bracket and the
3397 // selection is preceded by the rest of the opening bracket, then
3398 // insert the closing bracket.
3399 let following_text_allows_autoclose = snapshot
3400 .chars_at(selection.start)
3401 .next()
3402 .map_or(true, |c| scope.should_autoclose_before(c));
3403
3404 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3405 && bracket_pair.start.len() == 1
3406 {
3407 let target = bracket_pair.start.chars().next().unwrap();
3408 let current_line_count = snapshot
3409 .reversed_chars_at(selection.start)
3410 .take_while(|&c| c != '\n')
3411 .filter(|&c| c == target)
3412 .count();
3413 current_line_count % 2 == 1
3414 } else {
3415 false
3416 };
3417
3418 if autoclose
3419 && bracket_pair.close
3420 && following_text_allows_autoclose
3421 && !is_closing_quote
3422 {
3423 let anchor = snapshot.anchor_before(selection.end);
3424 new_selections.push((selection.map(|_| anchor), text.len()));
3425 new_autoclose_regions.push((
3426 anchor,
3427 text.len(),
3428 selection.id,
3429 bracket_pair.clone(),
3430 ));
3431 edits.push((
3432 selection.range(),
3433 format!("{}{}", text, bracket_pair.end).into(),
3434 ));
3435 bracket_inserted = true;
3436 continue;
3437 }
3438 }
3439
3440 if let Some(region) = autoclose_region {
3441 // If the selection is followed by an auto-inserted closing bracket,
3442 // then don't insert that closing bracket again; just move the selection
3443 // past the closing bracket.
3444 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3445 && text.as_ref() == region.pair.end.as_str();
3446 if should_skip {
3447 let anchor = snapshot.anchor_after(selection.end);
3448 new_selections
3449 .push((selection.map(|_| anchor), region.pair.end.len()));
3450 continue;
3451 }
3452 }
3453
3454 let always_treat_brackets_as_autoclosed = snapshot
3455 .settings_at(selection.start, cx)
3456 .always_treat_brackets_as_autoclosed;
3457 if always_treat_brackets_as_autoclosed
3458 && is_bracket_pair_end
3459 && snapshot.contains_str_at(selection.end, text.as_ref())
3460 {
3461 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3462 // and the inserted text is a closing bracket and the selection is followed
3463 // by the closing bracket then move the selection past the closing bracket.
3464 let anchor = snapshot.anchor_after(selection.end);
3465 new_selections.push((selection.map(|_| anchor), text.len()));
3466 continue;
3467 }
3468 }
3469 // If an opening bracket is 1 character long and is typed while
3470 // text is selected, then surround that text with the bracket pair.
3471 else if auto_surround
3472 && bracket_pair.surround
3473 && is_bracket_pair_start
3474 && bracket_pair.start.chars().count() == 1
3475 {
3476 edits.push((selection.start..selection.start, text.clone()));
3477 edits.push((
3478 selection.end..selection.end,
3479 bracket_pair.end.as_str().into(),
3480 ));
3481 bracket_inserted = true;
3482 new_selections.push((
3483 Selection {
3484 id: selection.id,
3485 start: snapshot.anchor_after(selection.start),
3486 end: snapshot.anchor_before(selection.end),
3487 reversed: selection.reversed,
3488 goal: selection.goal,
3489 },
3490 0,
3491 ));
3492 continue;
3493 }
3494 }
3495 }
3496
3497 if self.auto_replace_emoji_shortcode
3498 && selection.is_empty()
3499 && text.as_ref().ends_with(':')
3500 {
3501 if let Some(possible_emoji_short_code) =
3502 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3503 {
3504 if !possible_emoji_short_code.is_empty() {
3505 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3506 let emoji_shortcode_start = Point::new(
3507 selection.start.row,
3508 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3509 );
3510
3511 // Remove shortcode from buffer
3512 edits.push((
3513 emoji_shortcode_start..selection.start,
3514 "".to_string().into(),
3515 ));
3516 new_selections.push((
3517 Selection {
3518 id: selection.id,
3519 start: snapshot.anchor_after(emoji_shortcode_start),
3520 end: snapshot.anchor_before(selection.start),
3521 reversed: selection.reversed,
3522 goal: selection.goal,
3523 },
3524 0,
3525 ));
3526
3527 // Insert emoji
3528 let selection_start_anchor = snapshot.anchor_after(selection.start);
3529 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3530 edits.push((selection.start..selection.end, emoji.to_string().into()));
3531
3532 continue;
3533 }
3534 }
3535 }
3536 }
3537
3538 // If not handling any auto-close operation, then just replace the selected
3539 // text with the given input and move the selection to the end of the
3540 // newly inserted text.
3541 let anchor = snapshot.anchor_after(selection.end);
3542 if !self.linked_edit_ranges.is_empty() {
3543 let start_anchor = snapshot.anchor_before(selection.start);
3544
3545 let is_word_char = text.chars().next().map_or(true, |char| {
3546 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3547 classifier.is_word(char)
3548 });
3549
3550 if is_word_char {
3551 if let Some(ranges) = self
3552 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3553 {
3554 for (buffer, edits) in ranges {
3555 linked_edits
3556 .entry(buffer.clone())
3557 .or_default()
3558 .extend(edits.into_iter().map(|range| (range, text.clone())));
3559 }
3560 }
3561 }
3562 }
3563
3564 new_selections.push((selection.map(|_| anchor), 0));
3565 edits.push((selection.start..selection.end, text.clone()));
3566 }
3567
3568 drop(snapshot);
3569
3570 self.transact(cx, |this, cx| {
3571 this.buffer.update(cx, |buffer, cx| {
3572 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3573 });
3574 for (buffer, edits) in linked_edits {
3575 buffer.update(cx, |buffer, cx| {
3576 let snapshot = buffer.snapshot();
3577 let edits = edits
3578 .into_iter()
3579 .map(|(range, text)| {
3580 use text::ToPoint as TP;
3581 let end_point = TP::to_point(&range.end, &snapshot);
3582 let start_point = TP::to_point(&range.start, &snapshot);
3583 (start_point..end_point, text)
3584 })
3585 .sorted_by_key(|(range, _)| range.start)
3586 .collect::<Vec<_>>();
3587 buffer.edit(edits, None, cx);
3588 })
3589 }
3590 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3591 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3592 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3593 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3594 .zip(new_selection_deltas)
3595 .map(|(selection, delta)| Selection {
3596 id: selection.id,
3597 start: selection.start + delta,
3598 end: selection.end + delta,
3599 reversed: selection.reversed,
3600 goal: SelectionGoal::None,
3601 })
3602 .collect::<Vec<_>>();
3603
3604 let mut i = 0;
3605 for (position, delta, selection_id, pair) in new_autoclose_regions {
3606 let position = position.to_offset(&map.buffer_snapshot) + delta;
3607 let start = map.buffer_snapshot.anchor_before(position);
3608 let end = map.buffer_snapshot.anchor_after(position);
3609 while let Some(existing_state) = this.autoclose_regions.get(i) {
3610 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3611 Ordering::Less => i += 1,
3612 Ordering::Greater => break,
3613 Ordering::Equal => {
3614 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3615 Ordering::Less => i += 1,
3616 Ordering::Equal => break,
3617 Ordering::Greater => break,
3618 }
3619 }
3620 }
3621 }
3622 this.autoclose_regions.insert(
3623 i,
3624 AutocloseRegion {
3625 selection_id,
3626 range: start..end,
3627 pair,
3628 },
3629 );
3630 }
3631
3632 let had_active_inline_completion = this.has_active_inline_completion(cx);
3633 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3634 s.select(new_selections)
3635 });
3636
3637 if !bracket_inserted {
3638 if let Some(on_type_format_task) =
3639 this.trigger_on_type_formatting(text.to_string(), cx)
3640 {
3641 on_type_format_task.detach_and_log_err(cx);
3642 }
3643 }
3644
3645 let editor_settings = EditorSettings::get_global(cx);
3646 if bracket_inserted
3647 && (editor_settings.auto_signature_help
3648 || editor_settings.show_signature_help_after_edits)
3649 {
3650 this.show_signature_help(&ShowSignatureHelp, cx);
3651 }
3652
3653 let trigger_in_words = !had_active_inline_completion;
3654 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3655 linked_editing_ranges::refresh_linked_ranges(this, cx);
3656 this.refresh_inline_completion(true, false, cx);
3657 });
3658 }
3659
3660 fn find_possible_emoji_shortcode_at_position(
3661 snapshot: &MultiBufferSnapshot,
3662 position: Point,
3663 ) -> Option<String> {
3664 let mut chars = Vec::new();
3665 let mut found_colon = false;
3666 for char in snapshot.reversed_chars_at(position).take(100) {
3667 // Found a possible emoji shortcode in the middle of the buffer
3668 if found_colon {
3669 if char.is_whitespace() {
3670 chars.reverse();
3671 return Some(chars.iter().collect());
3672 }
3673 // If the previous character is not a whitespace, we are in the middle of a word
3674 // and we only want to complete the shortcode if the word is made up of other emojis
3675 let mut containing_word = String::new();
3676 for ch in snapshot
3677 .reversed_chars_at(position)
3678 .skip(chars.len() + 1)
3679 .take(100)
3680 {
3681 if ch.is_whitespace() {
3682 break;
3683 }
3684 containing_word.push(ch);
3685 }
3686 let containing_word = containing_word.chars().rev().collect::<String>();
3687 if util::word_consists_of_emojis(containing_word.as_str()) {
3688 chars.reverse();
3689 return Some(chars.iter().collect());
3690 }
3691 }
3692
3693 if char.is_whitespace() || !char.is_ascii() {
3694 return None;
3695 }
3696 if char == ':' {
3697 found_colon = true;
3698 } else {
3699 chars.push(char);
3700 }
3701 }
3702 // Found a possible emoji shortcode at the beginning of the buffer
3703 chars.reverse();
3704 Some(chars.iter().collect())
3705 }
3706
3707 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3708 self.transact(cx, |this, cx| {
3709 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3710 let selections = this.selections.all::<usize>(cx);
3711 let multi_buffer = this.buffer.read(cx);
3712 let buffer = multi_buffer.snapshot(cx);
3713 selections
3714 .iter()
3715 .map(|selection| {
3716 let start_point = selection.start.to_point(&buffer);
3717 let mut indent =
3718 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3719 indent.len = cmp::min(indent.len, start_point.column);
3720 let start = selection.start;
3721 let end = selection.end;
3722 let selection_is_empty = start == end;
3723 let language_scope = buffer.language_scope_at(start);
3724 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3725 &language_scope
3726 {
3727 let leading_whitespace_len = buffer
3728 .reversed_chars_at(start)
3729 .take_while(|c| c.is_whitespace() && *c != '\n')
3730 .map(|c| c.len_utf8())
3731 .sum::<usize>();
3732
3733 let trailing_whitespace_len = buffer
3734 .chars_at(end)
3735 .take_while(|c| c.is_whitespace() && *c != '\n')
3736 .map(|c| c.len_utf8())
3737 .sum::<usize>();
3738
3739 let insert_extra_newline =
3740 language.brackets().any(|(pair, enabled)| {
3741 let pair_start = pair.start.trim_end();
3742 let pair_end = pair.end.trim_start();
3743
3744 enabled
3745 && pair.newline
3746 && buffer.contains_str_at(
3747 end + trailing_whitespace_len,
3748 pair_end,
3749 )
3750 && buffer.contains_str_at(
3751 (start - leading_whitespace_len)
3752 .saturating_sub(pair_start.len()),
3753 pair_start,
3754 )
3755 });
3756
3757 // Comment extension on newline is allowed only for cursor selections
3758 let comment_delimiter = maybe!({
3759 if !selection_is_empty {
3760 return None;
3761 }
3762
3763 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3764 return None;
3765 }
3766
3767 let delimiters = language.line_comment_prefixes();
3768 let max_len_of_delimiter =
3769 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3770 let (snapshot, range) =
3771 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3772
3773 let mut index_of_first_non_whitespace = 0;
3774 let comment_candidate = snapshot
3775 .chars_for_range(range)
3776 .skip_while(|c| {
3777 let should_skip = c.is_whitespace();
3778 if should_skip {
3779 index_of_first_non_whitespace += 1;
3780 }
3781 should_skip
3782 })
3783 .take(max_len_of_delimiter)
3784 .collect::<String>();
3785 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3786 comment_candidate.starts_with(comment_prefix.as_ref())
3787 })?;
3788 let cursor_is_placed_after_comment_marker =
3789 index_of_first_non_whitespace + comment_prefix.len()
3790 <= start_point.column as usize;
3791 if cursor_is_placed_after_comment_marker {
3792 Some(comment_prefix.clone())
3793 } else {
3794 None
3795 }
3796 });
3797 (comment_delimiter, insert_extra_newline)
3798 } else {
3799 (None, false)
3800 };
3801
3802 let capacity_for_delimiter = comment_delimiter
3803 .as_deref()
3804 .map(str::len)
3805 .unwrap_or_default();
3806 let mut new_text =
3807 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3808 new_text.push('\n');
3809 new_text.extend(indent.chars());
3810 if let Some(delimiter) = &comment_delimiter {
3811 new_text.push_str(delimiter);
3812 }
3813 if insert_extra_newline {
3814 new_text = new_text.repeat(2);
3815 }
3816
3817 let anchor = buffer.anchor_after(end);
3818 let new_selection = selection.map(|_| anchor);
3819 (
3820 (start..end, new_text),
3821 (insert_extra_newline, new_selection),
3822 )
3823 })
3824 .unzip()
3825 };
3826
3827 this.edit_with_autoindent(edits, cx);
3828 let buffer = this.buffer.read(cx).snapshot(cx);
3829 let new_selections = selection_fixup_info
3830 .into_iter()
3831 .map(|(extra_newline_inserted, new_selection)| {
3832 let mut cursor = new_selection.end.to_point(&buffer);
3833 if extra_newline_inserted {
3834 cursor.row -= 1;
3835 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3836 }
3837 new_selection.map(|_| cursor)
3838 })
3839 .collect();
3840
3841 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3842 this.refresh_inline_completion(true, false, cx);
3843 });
3844 }
3845
3846 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3847 let buffer = self.buffer.read(cx);
3848 let snapshot = buffer.snapshot(cx);
3849
3850 let mut edits = Vec::new();
3851 let mut rows = Vec::new();
3852
3853 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3854 let cursor = selection.head();
3855 let row = cursor.row;
3856
3857 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3858
3859 let newline = "\n".to_string();
3860 edits.push((start_of_line..start_of_line, newline));
3861
3862 rows.push(row + rows_inserted as u32);
3863 }
3864
3865 self.transact(cx, |editor, cx| {
3866 editor.edit(edits, cx);
3867
3868 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3869 let mut index = 0;
3870 s.move_cursors_with(|map, _, _| {
3871 let row = rows[index];
3872 index += 1;
3873
3874 let point = Point::new(row, 0);
3875 let boundary = map.next_line_boundary(point).1;
3876 let clipped = map.clip_point(boundary, Bias::Left);
3877
3878 (clipped, SelectionGoal::None)
3879 });
3880 });
3881
3882 let mut indent_edits = Vec::new();
3883 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3884 for row in rows {
3885 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3886 for (row, indent) in indents {
3887 if indent.len == 0 {
3888 continue;
3889 }
3890
3891 let text = match indent.kind {
3892 IndentKind::Space => " ".repeat(indent.len as usize),
3893 IndentKind::Tab => "\t".repeat(indent.len as usize),
3894 };
3895 let point = Point::new(row.0, 0);
3896 indent_edits.push((point..point, text));
3897 }
3898 }
3899 editor.edit(indent_edits, cx);
3900 });
3901 }
3902
3903 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3904 let buffer = self.buffer.read(cx);
3905 let snapshot = buffer.snapshot(cx);
3906
3907 let mut edits = Vec::new();
3908 let mut rows = Vec::new();
3909 let mut rows_inserted = 0;
3910
3911 for selection in self.selections.all_adjusted(cx) {
3912 let cursor = selection.head();
3913 let row = cursor.row;
3914
3915 let point = Point::new(row + 1, 0);
3916 let start_of_line = snapshot.clip_point(point, Bias::Left);
3917
3918 let newline = "\n".to_string();
3919 edits.push((start_of_line..start_of_line, newline));
3920
3921 rows_inserted += 1;
3922 rows.push(row + rows_inserted);
3923 }
3924
3925 self.transact(cx, |editor, cx| {
3926 editor.edit(edits, cx);
3927
3928 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3929 let mut index = 0;
3930 s.move_cursors_with(|map, _, _| {
3931 let row = rows[index];
3932 index += 1;
3933
3934 let point = Point::new(row, 0);
3935 let boundary = map.next_line_boundary(point).1;
3936 let clipped = map.clip_point(boundary, Bias::Left);
3937
3938 (clipped, SelectionGoal::None)
3939 });
3940 });
3941
3942 let mut indent_edits = Vec::new();
3943 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3944 for row in rows {
3945 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3946 for (row, indent) in indents {
3947 if indent.len == 0 {
3948 continue;
3949 }
3950
3951 let text = match indent.kind {
3952 IndentKind::Space => " ".repeat(indent.len as usize),
3953 IndentKind::Tab => "\t".repeat(indent.len as usize),
3954 };
3955 let point = Point::new(row.0, 0);
3956 indent_edits.push((point..point, text));
3957 }
3958 }
3959 editor.edit(indent_edits, cx);
3960 });
3961 }
3962
3963 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3964 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3965 original_indent_columns: Vec::new(),
3966 });
3967 self.insert_with_autoindent_mode(text, autoindent, cx);
3968 }
3969
3970 fn insert_with_autoindent_mode(
3971 &mut self,
3972 text: &str,
3973 autoindent_mode: Option<AutoindentMode>,
3974 cx: &mut ViewContext<Self>,
3975 ) {
3976 if self.read_only(cx) {
3977 return;
3978 }
3979
3980 let text: Arc<str> = text.into();
3981 self.transact(cx, |this, cx| {
3982 let old_selections = this.selections.all_adjusted(cx);
3983 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3984 let anchors = {
3985 let snapshot = buffer.read(cx);
3986 old_selections
3987 .iter()
3988 .map(|s| {
3989 let anchor = snapshot.anchor_after(s.head());
3990 s.map(|_| anchor)
3991 })
3992 .collect::<Vec<_>>()
3993 };
3994 buffer.edit(
3995 old_selections
3996 .iter()
3997 .map(|s| (s.start..s.end, text.clone())),
3998 autoindent_mode,
3999 cx,
4000 );
4001 anchors
4002 });
4003
4004 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4005 s.select_anchors(selection_anchors);
4006 })
4007 });
4008 }
4009
4010 fn trigger_completion_on_input(
4011 &mut self,
4012 text: &str,
4013 trigger_in_words: bool,
4014 cx: &mut ViewContext<Self>,
4015 ) {
4016 if self.is_completion_trigger(text, trigger_in_words, cx) {
4017 self.show_completions(
4018 &ShowCompletions {
4019 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4020 },
4021 cx,
4022 );
4023 } else {
4024 self.hide_context_menu(cx);
4025 }
4026 }
4027
4028 fn is_completion_trigger(
4029 &self,
4030 text: &str,
4031 trigger_in_words: bool,
4032 cx: &mut ViewContext<Self>,
4033 ) -> bool {
4034 let position = self.selections.newest_anchor().head();
4035 let multibuffer = self.buffer.read(cx);
4036 let Some(buffer) = position
4037 .buffer_id
4038 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4039 else {
4040 return false;
4041 };
4042
4043 if let Some(completion_provider) = &self.completion_provider {
4044 completion_provider.is_completion_trigger(
4045 &buffer,
4046 position.text_anchor,
4047 text,
4048 trigger_in_words,
4049 cx,
4050 )
4051 } else {
4052 false
4053 }
4054 }
4055
4056 /// If any empty selections is touching the start of its innermost containing autoclose
4057 /// region, expand it to select the brackets.
4058 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4059 let selections = self.selections.all::<usize>(cx);
4060 let buffer = self.buffer.read(cx).read(cx);
4061 let new_selections = self
4062 .selections_with_autoclose_regions(selections, &buffer)
4063 .map(|(mut selection, region)| {
4064 if !selection.is_empty() {
4065 return selection;
4066 }
4067
4068 if let Some(region) = region {
4069 let mut range = region.range.to_offset(&buffer);
4070 if selection.start == range.start && range.start >= region.pair.start.len() {
4071 range.start -= region.pair.start.len();
4072 if buffer.contains_str_at(range.start, ®ion.pair.start)
4073 && buffer.contains_str_at(range.end, ®ion.pair.end)
4074 {
4075 range.end += region.pair.end.len();
4076 selection.start = range.start;
4077 selection.end = range.end;
4078
4079 return selection;
4080 }
4081 }
4082 }
4083
4084 let always_treat_brackets_as_autoclosed = buffer
4085 .settings_at(selection.start, cx)
4086 .always_treat_brackets_as_autoclosed;
4087
4088 if !always_treat_brackets_as_autoclosed {
4089 return selection;
4090 }
4091
4092 if let Some(scope) = buffer.language_scope_at(selection.start) {
4093 for (pair, enabled) in scope.brackets() {
4094 if !enabled || !pair.close {
4095 continue;
4096 }
4097
4098 if buffer.contains_str_at(selection.start, &pair.end) {
4099 let pair_start_len = pair.start.len();
4100 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4101 {
4102 selection.start -= pair_start_len;
4103 selection.end += pair.end.len();
4104
4105 return selection;
4106 }
4107 }
4108 }
4109 }
4110
4111 selection
4112 })
4113 .collect();
4114
4115 drop(buffer);
4116 self.change_selections(None, cx, |selections| selections.select(new_selections));
4117 }
4118
4119 /// Iterate the given selections, and for each one, find the smallest surrounding
4120 /// autoclose region. This uses the ordering of the selections and the autoclose
4121 /// regions to avoid repeated comparisons.
4122 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4123 &'a self,
4124 selections: impl IntoIterator<Item = Selection<D>>,
4125 buffer: &'a MultiBufferSnapshot,
4126 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4127 let mut i = 0;
4128 let mut regions = self.autoclose_regions.as_slice();
4129 selections.into_iter().map(move |selection| {
4130 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4131
4132 let mut enclosing = None;
4133 while let Some(pair_state) = regions.get(i) {
4134 if pair_state.range.end.to_offset(buffer) < range.start {
4135 regions = ®ions[i + 1..];
4136 i = 0;
4137 } else if pair_state.range.start.to_offset(buffer) > range.end {
4138 break;
4139 } else {
4140 if pair_state.selection_id == selection.id {
4141 enclosing = Some(pair_state);
4142 }
4143 i += 1;
4144 }
4145 }
4146
4147 (selection, enclosing)
4148 })
4149 }
4150
4151 /// Remove any autoclose regions that no longer contain their selection.
4152 fn invalidate_autoclose_regions(
4153 &mut self,
4154 mut selections: &[Selection<Anchor>],
4155 buffer: &MultiBufferSnapshot,
4156 ) {
4157 self.autoclose_regions.retain(|state| {
4158 let mut i = 0;
4159 while let Some(selection) = selections.get(i) {
4160 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4161 selections = &selections[1..];
4162 continue;
4163 }
4164 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4165 break;
4166 }
4167 if selection.id == state.selection_id {
4168 return true;
4169 } else {
4170 i += 1;
4171 }
4172 }
4173 false
4174 });
4175 }
4176
4177 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4178 let offset = position.to_offset(buffer);
4179 let (word_range, kind) = buffer.surrounding_word(offset, true);
4180 if offset > word_range.start && kind == Some(CharKind::Word) {
4181 Some(
4182 buffer
4183 .text_for_range(word_range.start..offset)
4184 .collect::<String>(),
4185 )
4186 } else {
4187 None
4188 }
4189 }
4190
4191 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4192 self.refresh_inlay_hints(
4193 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4194 cx,
4195 );
4196 }
4197
4198 pub fn inlay_hints_enabled(&self) -> bool {
4199 self.inlay_hint_cache.enabled
4200 }
4201
4202 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4203 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4204 return;
4205 }
4206
4207 let reason_description = reason.description();
4208 let ignore_debounce = matches!(
4209 reason,
4210 InlayHintRefreshReason::SettingsChange(_)
4211 | InlayHintRefreshReason::Toggle(_)
4212 | InlayHintRefreshReason::ExcerptsRemoved(_)
4213 );
4214 let (invalidate_cache, required_languages) = match reason {
4215 InlayHintRefreshReason::Toggle(enabled) => {
4216 self.inlay_hint_cache.enabled = enabled;
4217 if enabled {
4218 (InvalidationStrategy::RefreshRequested, None)
4219 } else {
4220 self.inlay_hint_cache.clear();
4221 self.splice_inlays(
4222 self.visible_inlay_hints(cx)
4223 .iter()
4224 .map(|inlay| inlay.id)
4225 .collect(),
4226 Vec::new(),
4227 cx,
4228 );
4229 return;
4230 }
4231 }
4232 InlayHintRefreshReason::SettingsChange(new_settings) => {
4233 match self.inlay_hint_cache.update_settings(
4234 &self.buffer,
4235 new_settings,
4236 self.visible_inlay_hints(cx),
4237 cx,
4238 ) {
4239 ControlFlow::Break(Some(InlaySplice {
4240 to_remove,
4241 to_insert,
4242 })) => {
4243 self.splice_inlays(to_remove, to_insert, cx);
4244 return;
4245 }
4246 ControlFlow::Break(None) => return,
4247 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4248 }
4249 }
4250 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4251 if let Some(InlaySplice {
4252 to_remove,
4253 to_insert,
4254 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4255 {
4256 self.splice_inlays(to_remove, to_insert, cx);
4257 }
4258 return;
4259 }
4260 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4261 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4262 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4263 }
4264 InlayHintRefreshReason::RefreshRequested => {
4265 (InvalidationStrategy::RefreshRequested, None)
4266 }
4267 };
4268
4269 if let Some(InlaySplice {
4270 to_remove,
4271 to_insert,
4272 }) = self.inlay_hint_cache.spawn_hint_refresh(
4273 reason_description,
4274 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4275 invalidate_cache,
4276 ignore_debounce,
4277 cx,
4278 ) {
4279 self.splice_inlays(to_remove, to_insert, cx);
4280 }
4281 }
4282
4283 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4284 self.display_map
4285 .read(cx)
4286 .current_inlays()
4287 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4288 .cloned()
4289 .collect()
4290 }
4291
4292 pub fn excerpts_for_inlay_hints_query(
4293 &self,
4294 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4295 cx: &mut ViewContext<Editor>,
4296 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4297 let Some(project) = self.project.as_ref() else {
4298 return HashMap::default();
4299 };
4300 let project = project.read(cx);
4301 let multi_buffer = self.buffer().read(cx);
4302 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4303 let multi_buffer_visible_start = self
4304 .scroll_manager
4305 .anchor()
4306 .anchor
4307 .to_point(&multi_buffer_snapshot);
4308 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4309 multi_buffer_visible_start
4310 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4311 Bias::Left,
4312 );
4313 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4314 multi_buffer
4315 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4316 .into_iter()
4317 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4318 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4319 let buffer = buffer_handle.read(cx);
4320 let buffer_file = project::File::from_dyn(buffer.file())?;
4321 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4322 let worktree_entry = buffer_worktree
4323 .read(cx)
4324 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4325 if worktree_entry.is_ignored {
4326 return None;
4327 }
4328
4329 let language = buffer.language()?;
4330 if let Some(restrict_to_languages) = restrict_to_languages {
4331 if !restrict_to_languages.contains(language) {
4332 return None;
4333 }
4334 }
4335 Some((
4336 excerpt_id,
4337 (
4338 buffer_handle,
4339 buffer.version().clone(),
4340 excerpt_visible_range,
4341 ),
4342 ))
4343 })
4344 .collect()
4345 }
4346
4347 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4348 TextLayoutDetails {
4349 text_system: cx.text_system().clone(),
4350 editor_style: self.style.clone().unwrap(),
4351 rem_size: cx.rem_size(),
4352 scroll_anchor: self.scroll_manager.anchor(),
4353 visible_rows: self.visible_line_count(),
4354 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4355 }
4356 }
4357
4358 fn splice_inlays(
4359 &self,
4360 to_remove: Vec<InlayId>,
4361 to_insert: Vec<Inlay>,
4362 cx: &mut ViewContext<Self>,
4363 ) {
4364 self.display_map.update(cx, |display_map, cx| {
4365 display_map.splice_inlays(to_remove, to_insert, cx);
4366 });
4367 cx.notify();
4368 }
4369
4370 fn trigger_on_type_formatting(
4371 &self,
4372 input: String,
4373 cx: &mut ViewContext<Self>,
4374 ) -> Option<Task<Result<()>>> {
4375 if input.len() != 1 {
4376 return None;
4377 }
4378
4379 let project = self.project.as_ref()?;
4380 let position = self.selections.newest_anchor().head();
4381 let (buffer, buffer_position) = self
4382 .buffer
4383 .read(cx)
4384 .text_anchor_for_position(position, cx)?;
4385
4386 let settings = language_settings::language_settings(
4387 buffer
4388 .read(cx)
4389 .language_at(buffer_position)
4390 .map(|l| l.name()),
4391 buffer.read(cx).file(),
4392 cx,
4393 );
4394 if !settings.use_on_type_format {
4395 return None;
4396 }
4397
4398 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4399 // hence we do LSP request & edit on host side only — add formats to host's history.
4400 let push_to_lsp_host_history = true;
4401 // If this is not the host, append its history with new edits.
4402 let push_to_client_history = project.read(cx).is_via_collab();
4403
4404 let on_type_formatting = project.update(cx, |project, cx| {
4405 project.on_type_format(
4406 buffer.clone(),
4407 buffer_position,
4408 input,
4409 push_to_lsp_host_history,
4410 cx,
4411 )
4412 });
4413 Some(cx.spawn(|editor, mut cx| async move {
4414 if let Some(transaction) = on_type_formatting.await? {
4415 if push_to_client_history {
4416 buffer
4417 .update(&mut cx, |buffer, _| {
4418 buffer.push_transaction(transaction, Instant::now());
4419 })
4420 .ok();
4421 }
4422 editor.update(&mut cx, |editor, cx| {
4423 editor.refresh_document_highlights(cx);
4424 })?;
4425 }
4426 Ok(())
4427 }))
4428 }
4429
4430 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4431 if self.pending_rename.is_some() {
4432 return;
4433 }
4434
4435 let Some(provider) = self.completion_provider.as_ref() else {
4436 return;
4437 };
4438
4439 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4440 return;
4441 }
4442
4443 let position = self.selections.newest_anchor().head();
4444 let (buffer, buffer_position) =
4445 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4446 output
4447 } else {
4448 return;
4449 };
4450
4451 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4452 let is_followup_invoke = {
4453 let context_menu_state = self.context_menu.read();
4454 matches!(
4455 context_menu_state.deref(),
4456 Some(ContextMenu::Completions(_))
4457 )
4458 };
4459 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4460 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4461 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4462 CompletionTriggerKind::TRIGGER_CHARACTER
4463 }
4464
4465 _ => CompletionTriggerKind::INVOKED,
4466 };
4467 let completion_context = CompletionContext {
4468 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4469 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4470 Some(String::from(trigger))
4471 } else {
4472 None
4473 }
4474 }),
4475 trigger_kind,
4476 };
4477 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4478 let sort_completions = provider.sort_completions();
4479
4480 let id = post_inc(&mut self.next_completion_id);
4481 let task = cx.spawn(|editor, mut cx| {
4482 async move {
4483 editor.update(&mut cx, |this, _| {
4484 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4485 })?;
4486 let completions = completions.await.log_err();
4487 let menu = if let Some(completions) = completions {
4488 let mut menu = CompletionsMenu::new(
4489 id,
4490 sort_completions,
4491 position,
4492 buffer.clone(),
4493 completions.into(),
4494 );
4495 menu.filter(query.as_deref(), cx.background_executor().clone())
4496 .await;
4497
4498 if menu.matches.is_empty() {
4499 None
4500 } else {
4501 Some(menu)
4502 }
4503 } else {
4504 None
4505 };
4506
4507 editor.update(&mut cx, |editor, cx| {
4508 let mut context_menu = editor.context_menu.write();
4509 match context_menu.as_ref() {
4510 None => {}
4511
4512 Some(ContextMenu::Completions(prev_menu)) => {
4513 if prev_menu.id > id {
4514 return;
4515 }
4516 }
4517
4518 _ => return,
4519 }
4520
4521 if editor.focus_handle.is_focused(cx) && menu.is_some() {
4522 let mut menu = menu.unwrap();
4523 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
4524 *context_menu = Some(ContextMenu::Completions(menu));
4525 drop(context_menu);
4526 editor.discard_inline_completion(false, cx);
4527 cx.notify();
4528 } else if editor.completion_tasks.len() <= 1 {
4529 // If there are no more completion tasks and the last menu was
4530 // empty, we should hide it. If it was already hidden, we should
4531 // also show the copilot completion when available.
4532 drop(context_menu);
4533 if editor.hide_context_menu(cx).is_none() {
4534 editor.update_visible_inline_completion(cx);
4535 }
4536 }
4537 })?;
4538
4539 Ok::<_, anyhow::Error>(())
4540 }
4541 .log_err()
4542 });
4543
4544 self.completion_tasks.push((id, task));
4545 }
4546
4547 pub fn confirm_completion(
4548 &mut self,
4549 action: &ConfirmCompletion,
4550 cx: &mut ViewContext<Self>,
4551 ) -> Option<Task<Result<()>>> {
4552 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4553 }
4554
4555 pub fn compose_completion(
4556 &mut self,
4557 action: &ComposeCompletion,
4558 cx: &mut ViewContext<Self>,
4559 ) -> Option<Task<Result<()>>> {
4560 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4561 }
4562
4563 fn do_completion(
4564 &mut self,
4565 item_ix: Option<usize>,
4566 intent: CompletionIntent,
4567 cx: &mut ViewContext<Editor>,
4568 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4569 use language::ToOffset as _;
4570
4571 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4572 menu
4573 } else {
4574 return None;
4575 };
4576
4577 let mat = completions_menu
4578 .matches
4579 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4580 let buffer_handle = completions_menu.buffer;
4581 let completions = completions_menu.completions.read();
4582 let completion = completions.get(mat.candidate_id)?;
4583 cx.stop_propagation();
4584
4585 let snippet;
4586 let text;
4587
4588 if completion.is_snippet() {
4589 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4590 text = snippet.as_ref().unwrap().text.clone();
4591 } else {
4592 snippet = None;
4593 text = completion.new_text.clone();
4594 };
4595 let selections = self.selections.all::<usize>(cx);
4596 let buffer = buffer_handle.read(cx);
4597 let old_range = completion.old_range.to_offset(buffer);
4598 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4599
4600 let newest_selection = self.selections.newest_anchor();
4601 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4602 return None;
4603 }
4604
4605 let lookbehind = newest_selection
4606 .start
4607 .text_anchor
4608 .to_offset(buffer)
4609 .saturating_sub(old_range.start);
4610 let lookahead = old_range
4611 .end
4612 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4613 let mut common_prefix_len = old_text
4614 .bytes()
4615 .zip(text.bytes())
4616 .take_while(|(a, b)| a == b)
4617 .count();
4618
4619 let snapshot = self.buffer.read(cx).snapshot(cx);
4620 let mut range_to_replace: Option<Range<isize>> = None;
4621 let mut ranges = Vec::new();
4622 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4623 for selection in &selections {
4624 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4625 let start = selection.start.saturating_sub(lookbehind);
4626 let end = selection.end + lookahead;
4627 if selection.id == newest_selection.id {
4628 range_to_replace = Some(
4629 ((start + common_prefix_len) as isize - selection.start as isize)
4630 ..(end as isize - selection.start as isize),
4631 );
4632 }
4633 ranges.push(start + common_prefix_len..end);
4634 } else {
4635 common_prefix_len = 0;
4636 ranges.clear();
4637 ranges.extend(selections.iter().map(|s| {
4638 if s.id == newest_selection.id {
4639 range_to_replace = Some(
4640 old_range.start.to_offset_utf16(&snapshot).0 as isize
4641 - selection.start as isize
4642 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4643 - selection.start as isize,
4644 );
4645 old_range.clone()
4646 } else {
4647 s.start..s.end
4648 }
4649 }));
4650 break;
4651 }
4652 if !self.linked_edit_ranges.is_empty() {
4653 let start_anchor = snapshot.anchor_before(selection.head());
4654 let end_anchor = snapshot.anchor_after(selection.tail());
4655 if let Some(ranges) = self
4656 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4657 {
4658 for (buffer, edits) in ranges {
4659 linked_edits.entry(buffer.clone()).or_default().extend(
4660 edits
4661 .into_iter()
4662 .map(|range| (range, text[common_prefix_len..].to_owned())),
4663 );
4664 }
4665 }
4666 }
4667 }
4668 let text = &text[common_prefix_len..];
4669
4670 cx.emit(EditorEvent::InputHandled {
4671 utf16_range_to_replace: range_to_replace,
4672 text: text.into(),
4673 });
4674
4675 self.transact(cx, |this, cx| {
4676 if let Some(mut snippet) = snippet {
4677 snippet.text = text.to_string();
4678 for tabstop in snippet
4679 .tabstops
4680 .iter_mut()
4681 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4682 {
4683 tabstop.start -= common_prefix_len as isize;
4684 tabstop.end -= common_prefix_len as isize;
4685 }
4686
4687 this.insert_snippet(&ranges, snippet, cx).log_err();
4688 } else {
4689 this.buffer.update(cx, |buffer, cx| {
4690 buffer.edit(
4691 ranges.iter().map(|range| (range.clone(), text)),
4692 this.autoindent_mode.clone(),
4693 cx,
4694 );
4695 });
4696 }
4697 for (buffer, edits) in linked_edits {
4698 buffer.update(cx, |buffer, cx| {
4699 let snapshot = buffer.snapshot();
4700 let edits = edits
4701 .into_iter()
4702 .map(|(range, text)| {
4703 use text::ToPoint as TP;
4704 let end_point = TP::to_point(&range.end, &snapshot);
4705 let start_point = TP::to_point(&range.start, &snapshot);
4706 (start_point..end_point, text)
4707 })
4708 .sorted_by_key(|(range, _)| range.start)
4709 .collect::<Vec<_>>();
4710 buffer.edit(edits, None, cx);
4711 })
4712 }
4713
4714 this.refresh_inline_completion(true, false, cx);
4715 });
4716
4717 let show_new_completions_on_confirm = completion
4718 .confirm
4719 .as_ref()
4720 .map_or(false, |confirm| confirm(intent, cx));
4721 if show_new_completions_on_confirm {
4722 self.show_completions(&ShowCompletions { trigger: None }, cx);
4723 }
4724
4725 let provider = self.completion_provider.as_ref()?;
4726 let apply_edits = provider.apply_additional_edits_for_completion(
4727 buffer_handle,
4728 completion.clone(),
4729 true,
4730 cx,
4731 );
4732
4733 let editor_settings = EditorSettings::get_global(cx);
4734 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4735 // After the code completion is finished, users often want to know what signatures are needed.
4736 // so we should automatically call signature_help
4737 self.show_signature_help(&ShowSignatureHelp, cx);
4738 }
4739
4740 Some(cx.foreground_executor().spawn(async move {
4741 apply_edits.await?;
4742 Ok(())
4743 }))
4744 }
4745
4746 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4747 let mut context_menu = self.context_menu.write();
4748 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4749 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4750 // Toggle if we're selecting the same one
4751 *context_menu = None;
4752 cx.notify();
4753 return;
4754 } else {
4755 // Otherwise, clear it and start a new one
4756 *context_menu = None;
4757 cx.notify();
4758 }
4759 }
4760 drop(context_menu);
4761 let snapshot = self.snapshot(cx);
4762 let deployed_from_indicator = action.deployed_from_indicator;
4763 let mut task = self.code_actions_task.take();
4764 let action = action.clone();
4765 cx.spawn(|editor, mut cx| async move {
4766 while let Some(prev_task) = task {
4767 prev_task.await.log_err();
4768 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4769 }
4770
4771 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4772 if editor.focus_handle.is_focused(cx) {
4773 let multibuffer_point = action
4774 .deployed_from_indicator
4775 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4776 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4777 let (buffer, buffer_row) = snapshot
4778 .buffer_snapshot
4779 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4780 .and_then(|(buffer_snapshot, range)| {
4781 editor
4782 .buffer
4783 .read(cx)
4784 .buffer(buffer_snapshot.remote_id())
4785 .map(|buffer| (buffer, range.start.row))
4786 })?;
4787 let (_, code_actions) = editor
4788 .available_code_actions
4789 .clone()
4790 .and_then(|(location, code_actions)| {
4791 let snapshot = location.buffer.read(cx).snapshot();
4792 let point_range = location.range.to_point(&snapshot);
4793 let point_range = point_range.start.row..=point_range.end.row;
4794 if point_range.contains(&buffer_row) {
4795 Some((location, code_actions))
4796 } else {
4797 None
4798 }
4799 })
4800 .unzip();
4801 let buffer_id = buffer.read(cx).remote_id();
4802 let tasks = editor
4803 .tasks
4804 .get(&(buffer_id, buffer_row))
4805 .map(|t| Arc::new(t.to_owned()));
4806 if tasks.is_none() && code_actions.is_none() {
4807 return None;
4808 }
4809
4810 editor.completion_tasks.clear();
4811 editor.discard_inline_completion(false, cx);
4812 let task_context =
4813 tasks
4814 .as_ref()
4815 .zip(editor.project.clone())
4816 .map(|(tasks, project)| {
4817 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4818 });
4819
4820 Some(cx.spawn(|editor, mut cx| async move {
4821 let task_context = match task_context {
4822 Some(task_context) => task_context.await,
4823 None => None,
4824 };
4825 let resolved_tasks =
4826 tasks.zip(task_context).map(|(tasks, task_context)| {
4827 Arc::new(ResolvedTasks {
4828 templates: tasks.resolve(&task_context).collect(),
4829 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4830 multibuffer_point.row,
4831 tasks.column,
4832 )),
4833 })
4834 });
4835 let spawn_straight_away = resolved_tasks
4836 .as_ref()
4837 .map_or(false, |tasks| tasks.templates.len() == 1)
4838 && code_actions
4839 .as_ref()
4840 .map_or(true, |actions| actions.is_empty());
4841 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4842 *editor.context_menu.write() =
4843 Some(ContextMenu::CodeActions(CodeActionsMenu {
4844 buffer,
4845 actions: CodeActionContents {
4846 tasks: resolved_tasks,
4847 actions: code_actions,
4848 },
4849 selected_item: Default::default(),
4850 scroll_handle: UniformListScrollHandle::default(),
4851 deployed_from_indicator,
4852 }));
4853 if spawn_straight_away {
4854 if let Some(task) = editor.confirm_code_action(
4855 &ConfirmCodeAction { item_ix: Some(0) },
4856 cx,
4857 ) {
4858 cx.notify();
4859 return task;
4860 }
4861 }
4862 cx.notify();
4863 Task::ready(Ok(()))
4864 }) {
4865 task.await
4866 } else {
4867 Ok(())
4868 }
4869 }))
4870 } else {
4871 Some(Task::ready(Ok(())))
4872 }
4873 })?;
4874 if let Some(task) = spawned_test_task {
4875 task.await?;
4876 }
4877
4878 Ok::<_, anyhow::Error>(())
4879 })
4880 .detach_and_log_err(cx);
4881 }
4882
4883 pub fn confirm_code_action(
4884 &mut self,
4885 action: &ConfirmCodeAction,
4886 cx: &mut ViewContext<Self>,
4887 ) -> Option<Task<Result<()>>> {
4888 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4889 menu
4890 } else {
4891 return None;
4892 };
4893 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4894 let action = actions_menu.actions.get(action_ix)?;
4895 let title = action.label();
4896 let buffer = actions_menu.buffer;
4897 let workspace = self.workspace()?;
4898
4899 match action {
4900 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4901 workspace.update(cx, |workspace, cx| {
4902 workspace::tasks::schedule_resolved_task(
4903 workspace,
4904 task_source_kind,
4905 resolved_task,
4906 false,
4907 cx,
4908 );
4909
4910 Some(Task::ready(Ok(())))
4911 })
4912 }
4913 CodeActionsItem::CodeAction {
4914 excerpt_id,
4915 action,
4916 provider,
4917 } => {
4918 let apply_code_action =
4919 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4920 let workspace = workspace.downgrade();
4921 Some(cx.spawn(|editor, cx| async move {
4922 let project_transaction = apply_code_action.await?;
4923 Self::open_project_transaction(
4924 &editor,
4925 workspace,
4926 project_transaction,
4927 title,
4928 cx,
4929 )
4930 .await
4931 }))
4932 }
4933 }
4934 }
4935
4936 pub async fn open_project_transaction(
4937 this: &WeakView<Editor>,
4938 workspace: WeakView<Workspace>,
4939 transaction: ProjectTransaction,
4940 title: String,
4941 mut cx: AsyncWindowContext,
4942 ) -> Result<()> {
4943 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4944 cx.update(|cx| {
4945 entries.sort_unstable_by_key(|(buffer, _)| {
4946 buffer.read(cx).file().map(|f| f.path().clone())
4947 });
4948 })?;
4949
4950 // If the project transaction's edits are all contained within this editor, then
4951 // avoid opening a new editor to display them.
4952
4953 if let Some((buffer, transaction)) = entries.first() {
4954 if entries.len() == 1 {
4955 let excerpt = this.update(&mut cx, |editor, cx| {
4956 editor
4957 .buffer()
4958 .read(cx)
4959 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4960 })?;
4961 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4962 if excerpted_buffer == *buffer {
4963 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4964 let excerpt_range = excerpt_range.to_offset(buffer);
4965 buffer
4966 .edited_ranges_for_transaction::<usize>(transaction)
4967 .all(|range| {
4968 excerpt_range.start <= range.start
4969 && excerpt_range.end >= range.end
4970 })
4971 })?;
4972
4973 if all_edits_within_excerpt {
4974 return Ok(());
4975 }
4976 }
4977 }
4978 }
4979 } else {
4980 return Ok(());
4981 }
4982
4983 let mut ranges_to_highlight = Vec::new();
4984 let excerpt_buffer = cx.new_model(|cx| {
4985 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4986 for (buffer_handle, transaction) in &entries {
4987 let buffer = buffer_handle.read(cx);
4988 ranges_to_highlight.extend(
4989 multibuffer.push_excerpts_with_context_lines(
4990 buffer_handle.clone(),
4991 buffer
4992 .edited_ranges_for_transaction::<usize>(transaction)
4993 .collect(),
4994 DEFAULT_MULTIBUFFER_CONTEXT,
4995 cx,
4996 ),
4997 );
4998 }
4999 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5000 multibuffer
5001 })?;
5002
5003 workspace.update(&mut cx, |workspace, cx| {
5004 let project = workspace.project().clone();
5005 let editor =
5006 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5007 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5008 editor.update(cx, |editor, cx| {
5009 editor.highlight_background::<Self>(
5010 &ranges_to_highlight,
5011 |theme| theme.editor_highlighted_line_background,
5012 cx,
5013 );
5014 });
5015 })?;
5016
5017 Ok(())
5018 }
5019
5020 pub fn clear_code_action_providers(&mut self) {
5021 self.code_action_providers.clear();
5022 self.available_code_actions.take();
5023 }
5024
5025 pub fn push_code_action_provider(
5026 &mut self,
5027 provider: Arc<dyn CodeActionProvider>,
5028 cx: &mut ViewContext<Self>,
5029 ) {
5030 self.code_action_providers.push(provider);
5031 self.refresh_code_actions(cx);
5032 }
5033
5034 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5035 let buffer = self.buffer.read(cx);
5036 let newest_selection = self.selections.newest_anchor().clone();
5037 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5038 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5039 if start_buffer != end_buffer {
5040 return None;
5041 }
5042
5043 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5044 cx.background_executor()
5045 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5046 .await;
5047
5048 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5049 let providers = this.code_action_providers.clone();
5050 let tasks = this
5051 .code_action_providers
5052 .iter()
5053 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5054 .collect::<Vec<_>>();
5055 (providers, tasks)
5056 })?;
5057
5058 let mut actions = Vec::new();
5059 for (provider, provider_actions) in
5060 providers.into_iter().zip(future::join_all(tasks).await)
5061 {
5062 if let Some(provider_actions) = provider_actions.log_err() {
5063 actions.extend(provider_actions.into_iter().map(|action| {
5064 AvailableCodeAction {
5065 excerpt_id: newest_selection.start.excerpt_id,
5066 action,
5067 provider: provider.clone(),
5068 }
5069 }));
5070 }
5071 }
5072
5073 this.update(&mut cx, |this, cx| {
5074 this.available_code_actions = if actions.is_empty() {
5075 None
5076 } else {
5077 Some((
5078 Location {
5079 buffer: start_buffer,
5080 range: start..end,
5081 },
5082 actions.into(),
5083 ))
5084 };
5085 cx.notify();
5086 })
5087 }));
5088 None
5089 }
5090
5091 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5092 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5093 self.show_git_blame_inline = false;
5094
5095 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5096 cx.background_executor().timer(delay).await;
5097
5098 this.update(&mut cx, |this, cx| {
5099 this.show_git_blame_inline = true;
5100 cx.notify();
5101 })
5102 .log_err();
5103 }));
5104 }
5105 }
5106
5107 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5108 if self.pending_rename.is_some() {
5109 return None;
5110 }
5111
5112 let provider = self.semantics_provider.clone()?;
5113 let buffer = self.buffer.read(cx);
5114 let newest_selection = self.selections.newest_anchor().clone();
5115 let cursor_position = newest_selection.head();
5116 let (cursor_buffer, cursor_buffer_position) =
5117 buffer.text_anchor_for_position(cursor_position, cx)?;
5118 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5119 if cursor_buffer != tail_buffer {
5120 return None;
5121 }
5122
5123 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5124 cx.background_executor()
5125 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5126 .await;
5127
5128 let highlights = if let Some(highlights) = cx
5129 .update(|cx| {
5130 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5131 })
5132 .ok()
5133 .flatten()
5134 {
5135 highlights.await.log_err()
5136 } else {
5137 None
5138 };
5139
5140 if let Some(highlights) = highlights {
5141 this.update(&mut cx, |this, cx| {
5142 if this.pending_rename.is_some() {
5143 return;
5144 }
5145
5146 let buffer_id = cursor_position.buffer_id;
5147 let buffer = this.buffer.read(cx);
5148 if !buffer
5149 .text_anchor_for_position(cursor_position, cx)
5150 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5151 {
5152 return;
5153 }
5154
5155 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5156 let mut write_ranges = Vec::new();
5157 let mut read_ranges = Vec::new();
5158 for highlight in highlights {
5159 for (excerpt_id, excerpt_range) in
5160 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5161 {
5162 let start = highlight
5163 .range
5164 .start
5165 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5166 let end = highlight
5167 .range
5168 .end
5169 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5170 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5171 continue;
5172 }
5173
5174 let range = Anchor {
5175 buffer_id,
5176 excerpt_id,
5177 text_anchor: start,
5178 }..Anchor {
5179 buffer_id,
5180 excerpt_id,
5181 text_anchor: end,
5182 };
5183 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5184 write_ranges.push(range);
5185 } else {
5186 read_ranges.push(range);
5187 }
5188 }
5189 }
5190
5191 this.highlight_background::<DocumentHighlightRead>(
5192 &read_ranges,
5193 |theme| theme.editor_document_highlight_read_background,
5194 cx,
5195 );
5196 this.highlight_background::<DocumentHighlightWrite>(
5197 &write_ranges,
5198 |theme| theme.editor_document_highlight_write_background,
5199 cx,
5200 );
5201 cx.notify();
5202 })
5203 .log_err();
5204 }
5205 }));
5206 None
5207 }
5208
5209 pub fn refresh_inline_completion(
5210 &mut self,
5211 debounce: bool,
5212 user_requested: bool,
5213 cx: &mut ViewContext<Self>,
5214 ) -> Option<()> {
5215 let provider = self.inline_completion_provider()?;
5216 let cursor = self.selections.newest_anchor().head();
5217 let (buffer, cursor_buffer_position) =
5218 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5219
5220 if !user_requested
5221 && (!self.enable_inline_completions
5222 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5223 {
5224 self.discard_inline_completion(false, cx);
5225 return None;
5226 }
5227
5228 self.update_visible_inline_completion(cx);
5229 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5230 Some(())
5231 }
5232
5233 fn cycle_inline_completion(
5234 &mut self,
5235 direction: Direction,
5236 cx: &mut ViewContext<Self>,
5237 ) -> Option<()> {
5238 let provider = self.inline_completion_provider()?;
5239 let cursor = self.selections.newest_anchor().head();
5240 let (buffer, cursor_buffer_position) =
5241 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5242 if !self.enable_inline_completions
5243 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5244 {
5245 return None;
5246 }
5247
5248 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5249 self.update_visible_inline_completion(cx);
5250
5251 Some(())
5252 }
5253
5254 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5255 if !self.has_active_inline_completion(cx) {
5256 self.refresh_inline_completion(false, true, cx);
5257 return;
5258 }
5259
5260 self.update_visible_inline_completion(cx);
5261 }
5262
5263 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5264 self.show_cursor_names(cx);
5265 }
5266
5267 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5268 self.show_cursor_names = true;
5269 cx.notify();
5270 cx.spawn(|this, mut cx| async move {
5271 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5272 this.update(&mut cx, |this, cx| {
5273 this.show_cursor_names = false;
5274 cx.notify()
5275 })
5276 .ok()
5277 })
5278 .detach();
5279 }
5280
5281 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5282 if self.has_active_inline_completion(cx) {
5283 self.cycle_inline_completion(Direction::Next, cx);
5284 } else {
5285 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5286 if is_copilot_disabled {
5287 cx.propagate();
5288 }
5289 }
5290 }
5291
5292 pub fn previous_inline_completion(
5293 &mut self,
5294 _: &PreviousInlineCompletion,
5295 cx: &mut ViewContext<Self>,
5296 ) {
5297 if self.has_active_inline_completion(cx) {
5298 self.cycle_inline_completion(Direction::Prev, cx);
5299 } else {
5300 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5301 if is_copilot_disabled {
5302 cx.propagate();
5303 }
5304 }
5305 }
5306
5307 pub fn accept_inline_completion(
5308 &mut self,
5309 _: &AcceptInlineCompletion,
5310 cx: &mut ViewContext<Self>,
5311 ) {
5312 let Some(completion) = self.take_active_inline_completion(cx) else {
5313 return;
5314 };
5315 if let Some(provider) = self.inline_completion_provider() {
5316 provider.accept(cx);
5317 }
5318
5319 cx.emit(EditorEvent::InputHandled {
5320 utf16_range_to_replace: None,
5321 text: completion.text.to_string().into(),
5322 });
5323
5324 if let Some(range) = completion.delete_range {
5325 self.change_selections(None, cx, |s| s.select_ranges([range]))
5326 }
5327 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5328 self.refresh_inline_completion(true, true, cx);
5329 cx.notify();
5330 }
5331
5332 pub fn accept_partial_inline_completion(
5333 &mut self,
5334 _: &AcceptPartialInlineCompletion,
5335 cx: &mut ViewContext<Self>,
5336 ) {
5337 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5338 if let Some(completion) = self.take_active_inline_completion(cx) {
5339 let mut partial_completion = completion
5340 .text
5341 .chars()
5342 .by_ref()
5343 .take_while(|c| c.is_alphabetic())
5344 .collect::<String>();
5345 if partial_completion.is_empty() {
5346 partial_completion = completion
5347 .text
5348 .chars()
5349 .by_ref()
5350 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5351 .collect::<String>();
5352 }
5353
5354 cx.emit(EditorEvent::InputHandled {
5355 utf16_range_to_replace: None,
5356 text: partial_completion.clone().into(),
5357 });
5358
5359 if let Some(range) = completion.delete_range {
5360 self.change_selections(None, cx, |s| s.select_ranges([range]))
5361 }
5362 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5363
5364 self.refresh_inline_completion(true, true, cx);
5365 cx.notify();
5366 }
5367 }
5368 }
5369
5370 fn discard_inline_completion(
5371 &mut self,
5372 should_report_inline_completion_event: bool,
5373 cx: &mut ViewContext<Self>,
5374 ) -> bool {
5375 if let Some(provider) = self.inline_completion_provider() {
5376 provider.discard(should_report_inline_completion_event, cx);
5377 }
5378
5379 self.take_active_inline_completion(cx).is_some()
5380 }
5381
5382 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5383 if let Some(completion) = self.active_inline_completion.as_ref() {
5384 let buffer = self.buffer.read(cx).read(cx);
5385 completion.position.is_valid(&buffer)
5386 } else {
5387 false
5388 }
5389 }
5390
5391 fn take_active_inline_completion(
5392 &mut self,
5393 cx: &mut ViewContext<Self>,
5394 ) -> Option<CompletionState> {
5395 let completion = self.active_inline_completion.take()?;
5396 let render_inlay_ids = completion.render_inlay_ids.clone();
5397 self.display_map.update(cx, |map, cx| {
5398 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5399 });
5400 let buffer = self.buffer.read(cx).read(cx);
5401
5402 if completion.position.is_valid(&buffer) {
5403 Some(completion)
5404 } else {
5405 None
5406 }
5407 }
5408
5409 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5410 let selection = self.selections.newest_anchor();
5411 let cursor = selection.head();
5412
5413 let excerpt_id = cursor.excerpt_id;
5414
5415 if self.context_menu.read().is_none()
5416 && self.completion_tasks.is_empty()
5417 && selection.start == selection.end
5418 {
5419 if let Some(provider) = self.inline_completion_provider() {
5420 if let Some((buffer, cursor_buffer_position)) =
5421 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5422 {
5423 if let Some(proposal) =
5424 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5425 {
5426 let mut to_remove = Vec::new();
5427 if let Some(completion) = self.active_inline_completion.take() {
5428 to_remove.extend(completion.render_inlay_ids.iter());
5429 }
5430
5431 let to_add = proposal
5432 .inlays
5433 .iter()
5434 .filter_map(|inlay| {
5435 let snapshot = self.buffer.read(cx).snapshot(cx);
5436 let id = post_inc(&mut self.next_inlay_id);
5437 match inlay {
5438 InlayProposal::Hint(position, hint) => {
5439 let position =
5440 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5441 Some(Inlay::hint(id, position, hint))
5442 }
5443 InlayProposal::Suggestion(position, text) => {
5444 let position =
5445 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5446 Some(Inlay::suggestion(id, position, text.clone()))
5447 }
5448 }
5449 })
5450 .collect_vec();
5451
5452 self.active_inline_completion = Some(CompletionState {
5453 position: cursor,
5454 text: proposal.text,
5455 delete_range: proposal.delete_range.and_then(|range| {
5456 let snapshot = self.buffer.read(cx).snapshot(cx);
5457 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5458 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5459 Some(start?..end?)
5460 }),
5461 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5462 });
5463
5464 self.display_map
5465 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5466
5467 cx.notify();
5468 return;
5469 }
5470 }
5471 }
5472 }
5473
5474 self.discard_inline_completion(false, cx);
5475 }
5476
5477 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5478 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5479 }
5480
5481 fn render_code_actions_indicator(
5482 &self,
5483 _style: &EditorStyle,
5484 row: DisplayRow,
5485 is_active: bool,
5486 cx: &mut ViewContext<Self>,
5487 ) -> Option<IconButton> {
5488 if self.available_code_actions.is_some() {
5489 Some(
5490 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5491 .shape(ui::IconButtonShape::Square)
5492 .icon_size(IconSize::XSmall)
5493 .icon_color(Color::Muted)
5494 .selected(is_active)
5495 .tooltip({
5496 let focus_handle = self.focus_handle.clone();
5497 move |cx| {
5498 Tooltip::for_action_in(
5499 "Toggle Code Actions",
5500 &ToggleCodeActions {
5501 deployed_from_indicator: None,
5502 },
5503 &focus_handle,
5504 cx,
5505 )
5506 }
5507 })
5508 .on_click(cx.listener(move |editor, _e, cx| {
5509 editor.focus(cx);
5510 editor.toggle_code_actions(
5511 &ToggleCodeActions {
5512 deployed_from_indicator: Some(row),
5513 },
5514 cx,
5515 );
5516 })),
5517 )
5518 } else {
5519 None
5520 }
5521 }
5522
5523 fn clear_tasks(&mut self) {
5524 self.tasks.clear()
5525 }
5526
5527 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5528 if self.tasks.insert(key, value).is_some() {
5529 // This case should hopefully be rare, but just in case...
5530 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5531 }
5532 }
5533
5534 fn build_tasks_context(
5535 project: &Model<Project>,
5536 buffer: &Model<Buffer>,
5537 buffer_row: u32,
5538 tasks: &Arc<RunnableTasks>,
5539 cx: &mut ViewContext<Self>,
5540 ) -> Task<Option<task::TaskContext>> {
5541 let position = Point::new(buffer_row, tasks.column);
5542 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5543 let location = Location {
5544 buffer: buffer.clone(),
5545 range: range_start..range_start,
5546 };
5547 // Fill in the environmental variables from the tree-sitter captures
5548 let mut captured_task_variables = TaskVariables::default();
5549 for (capture_name, value) in tasks.extra_variables.clone() {
5550 captured_task_variables.insert(
5551 task::VariableName::Custom(capture_name.into()),
5552 value.clone(),
5553 );
5554 }
5555 project.update(cx, |project, cx| {
5556 project.task_store().update(cx, |task_store, cx| {
5557 task_store.task_context_for_location(captured_task_variables, location, cx)
5558 })
5559 })
5560 }
5561
5562 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5563 let Some((workspace, _)) = self.workspace.clone() else {
5564 return;
5565 };
5566 let Some(project) = self.project.clone() else {
5567 return;
5568 };
5569
5570 // Try to find a closest, enclosing node using tree-sitter that has a
5571 // task
5572 let Some((buffer, buffer_row, tasks)) = self
5573 .find_enclosing_node_task(cx)
5574 // Or find the task that's closest in row-distance.
5575 .or_else(|| self.find_closest_task(cx))
5576 else {
5577 return;
5578 };
5579
5580 let reveal_strategy = action.reveal;
5581 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5582 cx.spawn(|_, mut cx| async move {
5583 let context = task_context.await?;
5584 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5585
5586 let resolved = resolved_task.resolved.as_mut()?;
5587 resolved.reveal = reveal_strategy;
5588
5589 workspace
5590 .update(&mut cx, |workspace, cx| {
5591 workspace::tasks::schedule_resolved_task(
5592 workspace,
5593 task_source_kind,
5594 resolved_task,
5595 false,
5596 cx,
5597 );
5598 })
5599 .ok()
5600 })
5601 .detach();
5602 }
5603
5604 fn find_closest_task(
5605 &mut self,
5606 cx: &mut ViewContext<Self>,
5607 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5608 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5609
5610 let ((buffer_id, row), tasks) = self
5611 .tasks
5612 .iter()
5613 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5614
5615 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5616 let tasks = Arc::new(tasks.to_owned());
5617 Some((buffer, *row, tasks))
5618 }
5619
5620 fn find_enclosing_node_task(
5621 &mut self,
5622 cx: &mut ViewContext<Self>,
5623 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5624 let snapshot = self.buffer.read(cx).snapshot(cx);
5625 let offset = self.selections.newest::<usize>(cx).head();
5626 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5627 let buffer_id = excerpt.buffer().remote_id();
5628
5629 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5630 let mut cursor = layer.node().walk();
5631
5632 while cursor.goto_first_child_for_byte(offset).is_some() {
5633 if cursor.node().end_byte() == offset {
5634 cursor.goto_next_sibling();
5635 }
5636 }
5637
5638 // Ascend to the smallest ancestor that contains the range and has a task.
5639 loop {
5640 let node = cursor.node();
5641 let node_range = node.byte_range();
5642 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5643
5644 // Check if this node contains our offset
5645 if node_range.start <= offset && node_range.end >= offset {
5646 // If it contains offset, check for task
5647 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5648 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5649 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5650 }
5651 }
5652
5653 if !cursor.goto_parent() {
5654 break;
5655 }
5656 }
5657 None
5658 }
5659
5660 fn render_run_indicator(
5661 &self,
5662 _style: &EditorStyle,
5663 is_active: bool,
5664 row: DisplayRow,
5665 cx: &mut ViewContext<Self>,
5666 ) -> IconButton {
5667 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5668 .shape(ui::IconButtonShape::Square)
5669 .icon_size(IconSize::XSmall)
5670 .icon_color(Color::Muted)
5671 .selected(is_active)
5672 .on_click(cx.listener(move |editor, _e, cx| {
5673 editor.focus(cx);
5674 editor.toggle_code_actions(
5675 &ToggleCodeActions {
5676 deployed_from_indicator: Some(row),
5677 },
5678 cx,
5679 );
5680 }))
5681 }
5682
5683 pub fn context_menu_visible(&self) -> bool {
5684 self.context_menu
5685 .read()
5686 .as_ref()
5687 .map_or(false, |menu| menu.visible())
5688 }
5689
5690 fn render_context_menu(
5691 &self,
5692 cursor_position: DisplayPoint,
5693 style: &EditorStyle,
5694 max_height: Pixels,
5695 cx: &mut ViewContext<Editor>,
5696 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5697 self.context_menu.read().as_ref().map(|menu| {
5698 menu.render(
5699 cursor_position,
5700 style,
5701 max_height,
5702 self.workspace.as_ref().map(|(w, _)| w.clone()),
5703 cx,
5704 )
5705 })
5706 }
5707
5708 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5709 cx.notify();
5710 self.completion_tasks.clear();
5711 let context_menu = self.context_menu.write().take();
5712 if context_menu.is_some() {
5713 self.update_visible_inline_completion(cx);
5714 }
5715 context_menu
5716 }
5717
5718 fn show_snippet_choices(
5719 &mut self,
5720 choices: &Vec<String>,
5721 selection: Range<Anchor>,
5722 cx: &mut ViewContext<Self>,
5723 ) {
5724 if selection.start.buffer_id.is_none() {
5725 return;
5726 }
5727 let buffer_id = selection.start.buffer_id.unwrap();
5728 let buffer = self.buffer().read(cx).buffer(buffer_id);
5729 let id = post_inc(&mut self.next_completion_id);
5730
5731 if let Some(buffer) = buffer {
5732 *self.context_menu.write() = Some(ContextMenu::Completions(
5733 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5734 .suppress_documentation_resolution(),
5735 ));
5736 }
5737 }
5738
5739 pub fn insert_snippet(
5740 &mut self,
5741 insertion_ranges: &[Range<usize>],
5742 snippet: Snippet,
5743 cx: &mut ViewContext<Self>,
5744 ) -> Result<()> {
5745 struct Tabstop<T> {
5746 is_end_tabstop: bool,
5747 ranges: Vec<Range<T>>,
5748 choices: Option<Vec<String>>,
5749 }
5750
5751 let tabstops = self.buffer.update(cx, |buffer, cx| {
5752 let snippet_text: Arc<str> = snippet.text.clone().into();
5753 buffer.edit(
5754 insertion_ranges
5755 .iter()
5756 .cloned()
5757 .map(|range| (range, snippet_text.clone())),
5758 Some(AutoindentMode::EachLine),
5759 cx,
5760 );
5761
5762 let snapshot = &*buffer.read(cx);
5763 let snippet = &snippet;
5764 snippet
5765 .tabstops
5766 .iter()
5767 .map(|tabstop| {
5768 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5769 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5770 });
5771 let mut tabstop_ranges = tabstop
5772 .ranges
5773 .iter()
5774 .flat_map(|tabstop_range| {
5775 let mut delta = 0_isize;
5776 insertion_ranges.iter().map(move |insertion_range| {
5777 let insertion_start = insertion_range.start as isize + delta;
5778 delta +=
5779 snippet.text.len() as isize - insertion_range.len() as isize;
5780
5781 let start = ((insertion_start + tabstop_range.start) as usize)
5782 .min(snapshot.len());
5783 let end = ((insertion_start + tabstop_range.end) as usize)
5784 .min(snapshot.len());
5785 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5786 })
5787 })
5788 .collect::<Vec<_>>();
5789 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5790
5791 Tabstop {
5792 is_end_tabstop,
5793 ranges: tabstop_ranges,
5794 choices: tabstop.choices.clone(),
5795 }
5796 })
5797 .collect::<Vec<_>>()
5798 });
5799 if let Some(tabstop) = tabstops.first() {
5800 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5801 s.select_ranges(tabstop.ranges.iter().cloned());
5802 });
5803
5804 if let Some(choices) = &tabstop.choices {
5805 if let Some(selection) = tabstop.ranges.first() {
5806 self.show_snippet_choices(choices, selection.clone(), cx)
5807 }
5808 }
5809
5810 // If we're already at the last tabstop and it's at the end of the snippet,
5811 // we're done, we don't need to keep the state around.
5812 if !tabstop.is_end_tabstop {
5813 let choices = tabstops
5814 .iter()
5815 .map(|tabstop| tabstop.choices.clone())
5816 .collect();
5817
5818 let ranges = tabstops
5819 .into_iter()
5820 .map(|tabstop| tabstop.ranges)
5821 .collect::<Vec<_>>();
5822
5823 self.snippet_stack.push(SnippetState {
5824 active_index: 0,
5825 ranges,
5826 choices,
5827 });
5828 }
5829
5830 // Check whether the just-entered snippet ends with an auto-closable bracket.
5831 if self.autoclose_regions.is_empty() {
5832 let snapshot = self.buffer.read(cx).snapshot(cx);
5833 for selection in &mut self.selections.all::<Point>(cx) {
5834 let selection_head = selection.head();
5835 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5836 continue;
5837 };
5838
5839 let mut bracket_pair = None;
5840 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5841 let prev_chars = snapshot
5842 .reversed_chars_at(selection_head)
5843 .collect::<String>();
5844 for (pair, enabled) in scope.brackets() {
5845 if enabled
5846 && pair.close
5847 && prev_chars.starts_with(pair.start.as_str())
5848 && next_chars.starts_with(pair.end.as_str())
5849 {
5850 bracket_pair = Some(pair.clone());
5851 break;
5852 }
5853 }
5854 if let Some(pair) = bracket_pair {
5855 let start = snapshot.anchor_after(selection_head);
5856 let end = snapshot.anchor_after(selection_head);
5857 self.autoclose_regions.push(AutocloseRegion {
5858 selection_id: selection.id,
5859 range: start..end,
5860 pair,
5861 });
5862 }
5863 }
5864 }
5865 }
5866 Ok(())
5867 }
5868
5869 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5870 self.move_to_snippet_tabstop(Bias::Right, cx)
5871 }
5872
5873 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5874 self.move_to_snippet_tabstop(Bias::Left, cx)
5875 }
5876
5877 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5878 if let Some(mut snippet) = self.snippet_stack.pop() {
5879 match bias {
5880 Bias::Left => {
5881 if snippet.active_index > 0 {
5882 snippet.active_index -= 1;
5883 } else {
5884 self.snippet_stack.push(snippet);
5885 return false;
5886 }
5887 }
5888 Bias::Right => {
5889 if snippet.active_index + 1 < snippet.ranges.len() {
5890 snippet.active_index += 1;
5891 } else {
5892 self.snippet_stack.push(snippet);
5893 return false;
5894 }
5895 }
5896 }
5897 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5899 s.select_anchor_ranges(current_ranges.iter().cloned())
5900 });
5901
5902 if let Some(choices) = &snippet.choices[snippet.active_index] {
5903 if let Some(selection) = current_ranges.first() {
5904 self.show_snippet_choices(&choices, selection.clone(), cx);
5905 }
5906 }
5907
5908 // If snippet state is not at the last tabstop, push it back on the stack
5909 if snippet.active_index + 1 < snippet.ranges.len() {
5910 self.snippet_stack.push(snippet);
5911 }
5912 return true;
5913 }
5914 }
5915
5916 false
5917 }
5918
5919 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5920 self.transact(cx, |this, cx| {
5921 this.select_all(&SelectAll, cx);
5922 this.insert("", cx);
5923 });
5924 }
5925
5926 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5927 self.transact(cx, |this, cx| {
5928 this.select_autoclose_pair(cx);
5929 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5930 if !this.linked_edit_ranges.is_empty() {
5931 let selections = this.selections.all::<MultiBufferPoint>(cx);
5932 let snapshot = this.buffer.read(cx).snapshot(cx);
5933
5934 for selection in selections.iter() {
5935 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5936 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5937 if selection_start.buffer_id != selection_end.buffer_id {
5938 continue;
5939 }
5940 if let Some(ranges) =
5941 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5942 {
5943 for (buffer, entries) in ranges {
5944 linked_ranges.entry(buffer).or_default().extend(entries);
5945 }
5946 }
5947 }
5948 }
5949
5950 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5951 if !this.selections.line_mode {
5952 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5953 for selection in &mut selections {
5954 if selection.is_empty() {
5955 let old_head = selection.head();
5956 let mut new_head =
5957 movement::left(&display_map, old_head.to_display_point(&display_map))
5958 .to_point(&display_map);
5959 if let Some((buffer, line_buffer_range)) = display_map
5960 .buffer_snapshot
5961 .buffer_line_for_row(MultiBufferRow(old_head.row))
5962 {
5963 let indent_size =
5964 buffer.indent_size_for_line(line_buffer_range.start.row);
5965 let indent_len = match indent_size.kind {
5966 IndentKind::Space => {
5967 buffer.settings_at(line_buffer_range.start, cx).tab_size
5968 }
5969 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5970 };
5971 if old_head.column <= indent_size.len && old_head.column > 0 {
5972 let indent_len = indent_len.get();
5973 new_head = cmp::min(
5974 new_head,
5975 MultiBufferPoint::new(
5976 old_head.row,
5977 ((old_head.column - 1) / indent_len) * indent_len,
5978 ),
5979 );
5980 }
5981 }
5982
5983 selection.set_head(new_head, SelectionGoal::None);
5984 }
5985 }
5986 }
5987
5988 this.signature_help_state.set_backspace_pressed(true);
5989 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5990 this.insert("", cx);
5991 let empty_str: Arc<str> = Arc::from("");
5992 for (buffer, edits) in linked_ranges {
5993 let snapshot = buffer.read(cx).snapshot();
5994 use text::ToPoint as TP;
5995
5996 let edits = edits
5997 .into_iter()
5998 .map(|range| {
5999 let end_point = TP::to_point(&range.end, &snapshot);
6000 let mut start_point = TP::to_point(&range.start, &snapshot);
6001
6002 if end_point == start_point {
6003 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6004 .saturating_sub(1);
6005 start_point = TP::to_point(&offset, &snapshot);
6006 };
6007
6008 (start_point..end_point, empty_str.clone())
6009 })
6010 .sorted_by_key(|(range, _)| range.start)
6011 .collect::<Vec<_>>();
6012 buffer.update(cx, |this, cx| {
6013 this.edit(edits, None, cx);
6014 })
6015 }
6016 this.refresh_inline_completion(true, false, cx);
6017 linked_editing_ranges::refresh_linked_ranges(this, cx);
6018 });
6019 }
6020
6021 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6022 self.transact(cx, |this, cx| {
6023 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6024 let line_mode = s.line_mode;
6025 s.move_with(|map, selection| {
6026 if selection.is_empty() && !line_mode {
6027 let cursor = movement::right(map, selection.head());
6028 selection.end = cursor;
6029 selection.reversed = true;
6030 selection.goal = SelectionGoal::None;
6031 }
6032 })
6033 });
6034 this.insert("", cx);
6035 this.refresh_inline_completion(true, false, cx);
6036 });
6037 }
6038
6039 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6040 if self.move_to_prev_snippet_tabstop(cx) {
6041 return;
6042 }
6043
6044 self.outdent(&Outdent, cx);
6045 }
6046
6047 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6048 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6049 return;
6050 }
6051
6052 let mut selections = self.selections.all_adjusted(cx);
6053 let buffer = self.buffer.read(cx);
6054 let snapshot = buffer.snapshot(cx);
6055 let rows_iter = selections.iter().map(|s| s.head().row);
6056 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6057
6058 let mut edits = Vec::new();
6059 let mut prev_edited_row = 0;
6060 let mut row_delta = 0;
6061 for selection in &mut selections {
6062 if selection.start.row != prev_edited_row {
6063 row_delta = 0;
6064 }
6065 prev_edited_row = selection.end.row;
6066
6067 // If the selection is non-empty, then increase the indentation of the selected lines.
6068 if !selection.is_empty() {
6069 row_delta =
6070 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6071 continue;
6072 }
6073
6074 // If the selection is empty and the cursor is in the leading whitespace before the
6075 // suggested indentation, then auto-indent the line.
6076 let cursor = selection.head();
6077 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6078 if let Some(suggested_indent) =
6079 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6080 {
6081 if cursor.column < suggested_indent.len
6082 && cursor.column <= current_indent.len
6083 && current_indent.len <= suggested_indent.len
6084 {
6085 selection.start = Point::new(cursor.row, suggested_indent.len);
6086 selection.end = selection.start;
6087 if row_delta == 0 {
6088 edits.extend(Buffer::edit_for_indent_size_adjustment(
6089 cursor.row,
6090 current_indent,
6091 suggested_indent,
6092 ));
6093 row_delta = suggested_indent.len - current_indent.len;
6094 }
6095 continue;
6096 }
6097 }
6098
6099 // Otherwise, insert a hard or soft tab.
6100 let settings = buffer.settings_at(cursor, cx);
6101 let tab_size = if settings.hard_tabs {
6102 IndentSize::tab()
6103 } else {
6104 let tab_size = settings.tab_size.get();
6105 let char_column = snapshot
6106 .text_for_range(Point::new(cursor.row, 0)..cursor)
6107 .flat_map(str::chars)
6108 .count()
6109 + row_delta as usize;
6110 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6111 IndentSize::spaces(chars_to_next_tab_stop)
6112 };
6113 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6114 selection.end = selection.start;
6115 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6116 row_delta += tab_size.len;
6117 }
6118
6119 self.transact(cx, |this, cx| {
6120 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6121 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6122 this.refresh_inline_completion(true, false, cx);
6123 });
6124 }
6125
6126 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6127 if self.read_only(cx) {
6128 return;
6129 }
6130 let mut selections = self.selections.all::<Point>(cx);
6131 let mut prev_edited_row = 0;
6132 let mut row_delta = 0;
6133 let mut edits = Vec::new();
6134 let buffer = self.buffer.read(cx);
6135 let snapshot = buffer.snapshot(cx);
6136 for selection in &mut selections {
6137 if selection.start.row != prev_edited_row {
6138 row_delta = 0;
6139 }
6140 prev_edited_row = selection.end.row;
6141
6142 row_delta =
6143 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6144 }
6145
6146 self.transact(cx, |this, cx| {
6147 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6148 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6149 });
6150 }
6151
6152 fn indent_selection(
6153 buffer: &MultiBuffer,
6154 snapshot: &MultiBufferSnapshot,
6155 selection: &mut Selection<Point>,
6156 edits: &mut Vec<(Range<Point>, String)>,
6157 delta_for_start_row: u32,
6158 cx: &AppContext,
6159 ) -> u32 {
6160 let settings = buffer.settings_at(selection.start, cx);
6161 let tab_size = settings.tab_size.get();
6162 let indent_kind = if settings.hard_tabs {
6163 IndentKind::Tab
6164 } else {
6165 IndentKind::Space
6166 };
6167 let mut start_row = selection.start.row;
6168 let mut end_row = selection.end.row + 1;
6169
6170 // If a selection ends at the beginning of a line, don't indent
6171 // that last line.
6172 if selection.end.column == 0 && selection.end.row > selection.start.row {
6173 end_row -= 1;
6174 }
6175
6176 // Avoid re-indenting a row that has already been indented by a
6177 // previous selection, but still update this selection's column
6178 // to reflect that indentation.
6179 if delta_for_start_row > 0 {
6180 start_row += 1;
6181 selection.start.column += delta_for_start_row;
6182 if selection.end.row == selection.start.row {
6183 selection.end.column += delta_for_start_row;
6184 }
6185 }
6186
6187 let mut delta_for_end_row = 0;
6188 let has_multiple_rows = start_row + 1 != end_row;
6189 for row in start_row..end_row {
6190 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6191 let indent_delta = match (current_indent.kind, indent_kind) {
6192 (IndentKind::Space, IndentKind::Space) => {
6193 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6194 IndentSize::spaces(columns_to_next_tab_stop)
6195 }
6196 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6197 (_, IndentKind::Tab) => IndentSize::tab(),
6198 };
6199
6200 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6201 0
6202 } else {
6203 selection.start.column
6204 };
6205 let row_start = Point::new(row, start);
6206 edits.push((
6207 row_start..row_start,
6208 indent_delta.chars().collect::<String>(),
6209 ));
6210
6211 // Update this selection's endpoints to reflect the indentation.
6212 if row == selection.start.row {
6213 selection.start.column += indent_delta.len;
6214 }
6215 if row == selection.end.row {
6216 selection.end.column += indent_delta.len;
6217 delta_for_end_row = indent_delta.len;
6218 }
6219 }
6220
6221 if selection.start.row == selection.end.row {
6222 delta_for_start_row + delta_for_end_row
6223 } else {
6224 delta_for_end_row
6225 }
6226 }
6227
6228 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6229 if self.read_only(cx) {
6230 return;
6231 }
6232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6233 let selections = self.selections.all::<Point>(cx);
6234 let mut deletion_ranges = Vec::new();
6235 let mut last_outdent = None;
6236 {
6237 let buffer = self.buffer.read(cx);
6238 let snapshot = buffer.snapshot(cx);
6239 for selection in &selections {
6240 let settings = buffer.settings_at(selection.start, cx);
6241 let tab_size = settings.tab_size.get();
6242 let mut rows = selection.spanned_rows(false, &display_map);
6243
6244 // Avoid re-outdenting a row that has already been outdented by a
6245 // previous selection.
6246 if let Some(last_row) = last_outdent {
6247 if last_row == rows.start {
6248 rows.start = rows.start.next_row();
6249 }
6250 }
6251 let has_multiple_rows = rows.len() > 1;
6252 for row in rows.iter_rows() {
6253 let indent_size = snapshot.indent_size_for_line(row);
6254 if indent_size.len > 0 {
6255 let deletion_len = match indent_size.kind {
6256 IndentKind::Space => {
6257 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6258 if columns_to_prev_tab_stop == 0 {
6259 tab_size
6260 } else {
6261 columns_to_prev_tab_stop
6262 }
6263 }
6264 IndentKind::Tab => 1,
6265 };
6266 let start = if has_multiple_rows
6267 || deletion_len > selection.start.column
6268 || indent_size.len < selection.start.column
6269 {
6270 0
6271 } else {
6272 selection.start.column - deletion_len
6273 };
6274 deletion_ranges.push(
6275 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6276 );
6277 last_outdent = Some(row);
6278 }
6279 }
6280 }
6281 }
6282
6283 self.transact(cx, |this, cx| {
6284 this.buffer.update(cx, |buffer, cx| {
6285 let empty_str: Arc<str> = Arc::default();
6286 buffer.edit(
6287 deletion_ranges
6288 .into_iter()
6289 .map(|range| (range, empty_str.clone())),
6290 None,
6291 cx,
6292 );
6293 });
6294 let selections = this.selections.all::<usize>(cx);
6295 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6296 });
6297 }
6298
6299 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6300 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6301 let selections = self.selections.all::<Point>(cx);
6302
6303 let mut new_cursors = Vec::new();
6304 let mut edit_ranges = Vec::new();
6305 let mut selections = selections.iter().peekable();
6306 while let Some(selection) = selections.next() {
6307 let mut rows = selection.spanned_rows(false, &display_map);
6308 let goal_display_column = selection.head().to_display_point(&display_map).column();
6309
6310 // Accumulate contiguous regions of rows that we want to delete.
6311 while let Some(next_selection) = selections.peek() {
6312 let next_rows = next_selection.spanned_rows(false, &display_map);
6313 if next_rows.start <= rows.end {
6314 rows.end = next_rows.end;
6315 selections.next().unwrap();
6316 } else {
6317 break;
6318 }
6319 }
6320
6321 let buffer = &display_map.buffer_snapshot;
6322 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6323 let edit_end;
6324 let cursor_buffer_row;
6325 if buffer.max_point().row >= rows.end.0 {
6326 // If there's a line after the range, delete the \n from the end of the row range
6327 // and position the cursor on the next line.
6328 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6329 cursor_buffer_row = rows.end;
6330 } else {
6331 // If there isn't a line after the range, delete the \n from the line before the
6332 // start of the row range and position the cursor there.
6333 edit_start = edit_start.saturating_sub(1);
6334 edit_end = buffer.len();
6335 cursor_buffer_row = rows.start.previous_row();
6336 }
6337
6338 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6339 *cursor.column_mut() =
6340 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6341
6342 new_cursors.push((
6343 selection.id,
6344 buffer.anchor_after(cursor.to_point(&display_map)),
6345 ));
6346 edit_ranges.push(edit_start..edit_end);
6347 }
6348
6349 self.transact(cx, |this, cx| {
6350 let buffer = this.buffer.update(cx, |buffer, cx| {
6351 let empty_str: Arc<str> = Arc::default();
6352 buffer.edit(
6353 edit_ranges
6354 .into_iter()
6355 .map(|range| (range, empty_str.clone())),
6356 None,
6357 cx,
6358 );
6359 buffer.snapshot(cx)
6360 });
6361 let new_selections = new_cursors
6362 .into_iter()
6363 .map(|(id, cursor)| {
6364 let cursor = cursor.to_point(&buffer);
6365 Selection {
6366 id,
6367 start: cursor,
6368 end: cursor,
6369 reversed: false,
6370 goal: SelectionGoal::None,
6371 }
6372 })
6373 .collect();
6374
6375 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6376 s.select(new_selections);
6377 });
6378 });
6379 }
6380
6381 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6382 if self.read_only(cx) {
6383 return;
6384 }
6385 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6386 for selection in self.selections.all::<Point>(cx) {
6387 let start = MultiBufferRow(selection.start.row);
6388 // Treat single line selections as if they include the next line. Otherwise this action
6389 // would do nothing for single line selections individual cursors.
6390 let end = if selection.start.row == selection.end.row {
6391 MultiBufferRow(selection.start.row + 1)
6392 } else {
6393 MultiBufferRow(selection.end.row)
6394 };
6395
6396 if let Some(last_row_range) = row_ranges.last_mut() {
6397 if start <= last_row_range.end {
6398 last_row_range.end = end;
6399 continue;
6400 }
6401 }
6402 row_ranges.push(start..end);
6403 }
6404
6405 let snapshot = self.buffer.read(cx).snapshot(cx);
6406 let mut cursor_positions = Vec::new();
6407 for row_range in &row_ranges {
6408 let anchor = snapshot.anchor_before(Point::new(
6409 row_range.end.previous_row().0,
6410 snapshot.line_len(row_range.end.previous_row()),
6411 ));
6412 cursor_positions.push(anchor..anchor);
6413 }
6414
6415 self.transact(cx, |this, cx| {
6416 for row_range in row_ranges.into_iter().rev() {
6417 for row in row_range.iter_rows().rev() {
6418 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6419 let next_line_row = row.next_row();
6420 let indent = snapshot.indent_size_for_line(next_line_row);
6421 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6422
6423 let replace = if snapshot.line_len(next_line_row) > indent.len {
6424 " "
6425 } else {
6426 ""
6427 };
6428
6429 this.buffer.update(cx, |buffer, cx| {
6430 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6431 });
6432 }
6433 }
6434
6435 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6436 s.select_anchor_ranges(cursor_positions)
6437 });
6438 });
6439 }
6440
6441 pub fn sort_lines_case_sensitive(
6442 &mut self,
6443 _: &SortLinesCaseSensitive,
6444 cx: &mut ViewContext<Self>,
6445 ) {
6446 self.manipulate_lines(cx, |lines| lines.sort())
6447 }
6448
6449 pub fn sort_lines_case_insensitive(
6450 &mut self,
6451 _: &SortLinesCaseInsensitive,
6452 cx: &mut ViewContext<Self>,
6453 ) {
6454 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6455 }
6456
6457 pub fn unique_lines_case_insensitive(
6458 &mut self,
6459 _: &UniqueLinesCaseInsensitive,
6460 cx: &mut ViewContext<Self>,
6461 ) {
6462 self.manipulate_lines(cx, |lines| {
6463 let mut seen = HashSet::default();
6464 lines.retain(|line| seen.insert(line.to_lowercase()));
6465 })
6466 }
6467
6468 pub fn unique_lines_case_sensitive(
6469 &mut self,
6470 _: &UniqueLinesCaseSensitive,
6471 cx: &mut ViewContext<Self>,
6472 ) {
6473 self.manipulate_lines(cx, |lines| {
6474 let mut seen = HashSet::default();
6475 lines.retain(|line| seen.insert(*line));
6476 })
6477 }
6478
6479 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6480 let mut revert_changes = HashMap::default();
6481 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6482 for hunk in hunks_for_rows(
6483 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6484 &multi_buffer_snapshot,
6485 ) {
6486 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6487 }
6488 if !revert_changes.is_empty() {
6489 self.transact(cx, |editor, cx| {
6490 editor.revert(revert_changes, cx);
6491 });
6492 }
6493 }
6494
6495 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6496 let Some(project) = self.project.clone() else {
6497 return;
6498 };
6499 self.reload(project, cx).detach_and_notify_err(cx);
6500 }
6501
6502 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6503 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6504 if !revert_changes.is_empty() {
6505 self.transact(cx, |editor, cx| {
6506 editor.revert(revert_changes, cx);
6507 });
6508 }
6509 }
6510
6511 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6512 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6513 let project_path = buffer.read(cx).project_path(cx)?;
6514 let project = self.project.as_ref()?.read(cx);
6515 let entry = project.entry_for_path(&project_path, cx)?;
6516 let parent = match &entry.canonical_path {
6517 Some(canonical_path) => canonical_path.to_path_buf(),
6518 None => project.absolute_path(&project_path, cx)?,
6519 }
6520 .parent()?
6521 .to_path_buf();
6522 Some(parent)
6523 }) {
6524 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6525 }
6526 }
6527
6528 fn gather_revert_changes(
6529 &mut self,
6530 selections: &[Selection<Anchor>],
6531 cx: &mut ViewContext<'_, Editor>,
6532 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6533 let mut revert_changes = HashMap::default();
6534 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6535 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6536 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6537 }
6538 revert_changes
6539 }
6540
6541 pub fn prepare_revert_change(
6542 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6543 multi_buffer: &Model<MultiBuffer>,
6544 hunk: &MultiBufferDiffHunk,
6545 cx: &AppContext,
6546 ) -> Option<()> {
6547 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6548 let buffer = buffer.read(cx);
6549 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6550 let buffer_snapshot = buffer.snapshot();
6551 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6552 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6553 probe
6554 .0
6555 .start
6556 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6557 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6558 }) {
6559 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6560 Some(())
6561 } else {
6562 None
6563 }
6564 }
6565
6566 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6567 self.manipulate_lines(cx, |lines| lines.reverse())
6568 }
6569
6570 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6571 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6572 }
6573
6574 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6575 where
6576 Fn: FnMut(&mut Vec<&str>),
6577 {
6578 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6579 let buffer = self.buffer.read(cx).snapshot(cx);
6580
6581 let mut edits = Vec::new();
6582
6583 let selections = self.selections.all::<Point>(cx);
6584 let mut selections = selections.iter().peekable();
6585 let mut contiguous_row_selections = Vec::new();
6586 let mut new_selections = Vec::new();
6587 let mut added_lines = 0;
6588 let mut removed_lines = 0;
6589
6590 while let Some(selection) = selections.next() {
6591 let (start_row, end_row) = consume_contiguous_rows(
6592 &mut contiguous_row_selections,
6593 selection,
6594 &display_map,
6595 &mut selections,
6596 );
6597
6598 let start_point = Point::new(start_row.0, 0);
6599 let end_point = Point::new(
6600 end_row.previous_row().0,
6601 buffer.line_len(end_row.previous_row()),
6602 );
6603 let text = buffer
6604 .text_for_range(start_point..end_point)
6605 .collect::<String>();
6606
6607 let mut lines = text.split('\n').collect_vec();
6608
6609 let lines_before = lines.len();
6610 callback(&mut lines);
6611 let lines_after = lines.len();
6612
6613 edits.push((start_point..end_point, lines.join("\n")));
6614
6615 // Selections must change based on added and removed line count
6616 let start_row =
6617 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6618 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6619 new_selections.push(Selection {
6620 id: selection.id,
6621 start: start_row,
6622 end: end_row,
6623 goal: SelectionGoal::None,
6624 reversed: selection.reversed,
6625 });
6626
6627 if lines_after > lines_before {
6628 added_lines += lines_after - lines_before;
6629 } else if lines_before > lines_after {
6630 removed_lines += lines_before - lines_after;
6631 }
6632 }
6633
6634 self.transact(cx, |this, cx| {
6635 let buffer = this.buffer.update(cx, |buffer, cx| {
6636 buffer.edit(edits, None, cx);
6637 buffer.snapshot(cx)
6638 });
6639
6640 // Recalculate offsets on newly edited buffer
6641 let new_selections = new_selections
6642 .iter()
6643 .map(|s| {
6644 let start_point = Point::new(s.start.0, 0);
6645 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6646 Selection {
6647 id: s.id,
6648 start: buffer.point_to_offset(start_point),
6649 end: buffer.point_to_offset(end_point),
6650 goal: s.goal,
6651 reversed: s.reversed,
6652 }
6653 })
6654 .collect();
6655
6656 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6657 s.select(new_selections);
6658 });
6659
6660 this.request_autoscroll(Autoscroll::fit(), cx);
6661 });
6662 }
6663
6664 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6665 self.manipulate_text(cx, |text| text.to_uppercase())
6666 }
6667
6668 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6669 self.manipulate_text(cx, |text| text.to_lowercase())
6670 }
6671
6672 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6673 self.manipulate_text(cx, |text| {
6674 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6675 // https://github.com/rutrum/convert-case/issues/16
6676 text.split('\n')
6677 .map(|line| line.to_case(Case::Title))
6678 .join("\n")
6679 })
6680 }
6681
6682 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6683 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6684 }
6685
6686 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6687 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6688 }
6689
6690 pub fn convert_to_upper_camel_case(
6691 &mut self,
6692 _: &ConvertToUpperCamelCase,
6693 cx: &mut ViewContext<Self>,
6694 ) {
6695 self.manipulate_text(cx, |text| {
6696 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6697 // https://github.com/rutrum/convert-case/issues/16
6698 text.split('\n')
6699 .map(|line| line.to_case(Case::UpperCamel))
6700 .join("\n")
6701 })
6702 }
6703
6704 pub fn convert_to_lower_camel_case(
6705 &mut self,
6706 _: &ConvertToLowerCamelCase,
6707 cx: &mut ViewContext<Self>,
6708 ) {
6709 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6710 }
6711
6712 pub fn convert_to_opposite_case(
6713 &mut self,
6714 _: &ConvertToOppositeCase,
6715 cx: &mut ViewContext<Self>,
6716 ) {
6717 self.manipulate_text(cx, |text| {
6718 text.chars()
6719 .fold(String::with_capacity(text.len()), |mut t, c| {
6720 if c.is_uppercase() {
6721 t.extend(c.to_lowercase());
6722 } else {
6723 t.extend(c.to_uppercase());
6724 }
6725 t
6726 })
6727 })
6728 }
6729
6730 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6731 where
6732 Fn: FnMut(&str) -> String,
6733 {
6734 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6735 let buffer = self.buffer.read(cx).snapshot(cx);
6736
6737 let mut new_selections = Vec::new();
6738 let mut edits = Vec::new();
6739 let mut selection_adjustment = 0i32;
6740
6741 for selection in self.selections.all::<usize>(cx) {
6742 let selection_is_empty = selection.is_empty();
6743
6744 let (start, end) = if selection_is_empty {
6745 let word_range = movement::surrounding_word(
6746 &display_map,
6747 selection.start.to_display_point(&display_map),
6748 );
6749 let start = word_range.start.to_offset(&display_map, Bias::Left);
6750 let end = word_range.end.to_offset(&display_map, Bias::Left);
6751 (start, end)
6752 } else {
6753 (selection.start, selection.end)
6754 };
6755
6756 let text = buffer.text_for_range(start..end).collect::<String>();
6757 let old_length = text.len() as i32;
6758 let text = callback(&text);
6759
6760 new_selections.push(Selection {
6761 start: (start as i32 - selection_adjustment) as usize,
6762 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6763 goal: SelectionGoal::None,
6764 ..selection
6765 });
6766
6767 selection_adjustment += old_length - text.len() as i32;
6768
6769 edits.push((start..end, text));
6770 }
6771
6772 self.transact(cx, |this, cx| {
6773 this.buffer.update(cx, |buffer, cx| {
6774 buffer.edit(edits, None, cx);
6775 });
6776
6777 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6778 s.select(new_selections);
6779 });
6780
6781 this.request_autoscroll(Autoscroll::fit(), cx);
6782 });
6783 }
6784
6785 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6786 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6787 let buffer = &display_map.buffer_snapshot;
6788 let selections = self.selections.all::<Point>(cx);
6789
6790 let mut edits = Vec::new();
6791 let mut selections_iter = selections.iter().peekable();
6792 while let Some(selection) = selections_iter.next() {
6793 // Avoid duplicating the same lines twice.
6794 let mut rows = selection.spanned_rows(false, &display_map);
6795
6796 while let Some(next_selection) = selections_iter.peek() {
6797 let next_rows = next_selection.spanned_rows(false, &display_map);
6798 if next_rows.start < rows.end {
6799 rows.end = next_rows.end;
6800 selections_iter.next().unwrap();
6801 } else {
6802 break;
6803 }
6804 }
6805
6806 // Copy the text from the selected row region and splice it either at the start
6807 // or end of the region.
6808 let start = Point::new(rows.start.0, 0);
6809 let end = Point::new(
6810 rows.end.previous_row().0,
6811 buffer.line_len(rows.end.previous_row()),
6812 );
6813 let text = buffer
6814 .text_for_range(start..end)
6815 .chain(Some("\n"))
6816 .collect::<String>();
6817 let insert_location = if upwards {
6818 Point::new(rows.end.0, 0)
6819 } else {
6820 start
6821 };
6822 edits.push((insert_location..insert_location, text));
6823 }
6824
6825 self.transact(cx, |this, cx| {
6826 this.buffer.update(cx, |buffer, cx| {
6827 buffer.edit(edits, None, cx);
6828 });
6829
6830 this.request_autoscroll(Autoscroll::fit(), cx);
6831 });
6832 }
6833
6834 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6835 self.duplicate_line(true, cx);
6836 }
6837
6838 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6839 self.duplicate_line(false, cx);
6840 }
6841
6842 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6844 let buffer = self.buffer.read(cx).snapshot(cx);
6845
6846 let mut edits = Vec::new();
6847 let mut unfold_ranges = Vec::new();
6848 let mut refold_creases = Vec::new();
6849
6850 let selections = self.selections.all::<Point>(cx);
6851 let mut selections = selections.iter().peekable();
6852 let mut contiguous_row_selections = Vec::new();
6853 let mut new_selections = Vec::new();
6854
6855 while let Some(selection) = selections.next() {
6856 // Find all the selections that span a contiguous row range
6857 let (start_row, end_row) = consume_contiguous_rows(
6858 &mut contiguous_row_selections,
6859 selection,
6860 &display_map,
6861 &mut selections,
6862 );
6863
6864 // Move the text spanned by the row range to be before the line preceding the row range
6865 if start_row.0 > 0 {
6866 let range_to_move = Point::new(
6867 start_row.previous_row().0,
6868 buffer.line_len(start_row.previous_row()),
6869 )
6870 ..Point::new(
6871 end_row.previous_row().0,
6872 buffer.line_len(end_row.previous_row()),
6873 );
6874 let insertion_point = display_map
6875 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6876 .0;
6877
6878 // Don't move lines across excerpts
6879 if buffer
6880 .excerpt_boundaries_in_range((
6881 Bound::Excluded(insertion_point),
6882 Bound::Included(range_to_move.end),
6883 ))
6884 .next()
6885 .is_none()
6886 {
6887 let text = buffer
6888 .text_for_range(range_to_move.clone())
6889 .flat_map(|s| s.chars())
6890 .skip(1)
6891 .chain(['\n'])
6892 .collect::<String>();
6893
6894 edits.push((
6895 buffer.anchor_after(range_to_move.start)
6896 ..buffer.anchor_before(range_to_move.end),
6897 String::new(),
6898 ));
6899 let insertion_anchor = buffer.anchor_after(insertion_point);
6900 edits.push((insertion_anchor..insertion_anchor, text));
6901
6902 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6903
6904 // Move selections up
6905 new_selections.extend(contiguous_row_selections.drain(..).map(
6906 |mut selection| {
6907 selection.start.row -= row_delta;
6908 selection.end.row -= row_delta;
6909 selection
6910 },
6911 ));
6912
6913 // Move folds up
6914 unfold_ranges.push(range_to_move.clone());
6915 for fold in display_map.folds_in_range(
6916 buffer.anchor_before(range_to_move.start)
6917 ..buffer.anchor_after(range_to_move.end),
6918 ) {
6919 let mut start = fold.range.start.to_point(&buffer);
6920 let mut end = fold.range.end.to_point(&buffer);
6921 start.row -= row_delta;
6922 end.row -= row_delta;
6923 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6924 }
6925 }
6926 }
6927
6928 // If we didn't move line(s), preserve the existing selections
6929 new_selections.append(&mut contiguous_row_selections);
6930 }
6931
6932 self.transact(cx, |this, cx| {
6933 this.unfold_ranges(&unfold_ranges, true, true, cx);
6934 this.buffer.update(cx, |buffer, cx| {
6935 for (range, text) in edits {
6936 buffer.edit([(range, text)], None, cx);
6937 }
6938 });
6939 this.fold_creases(refold_creases, true, cx);
6940 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6941 s.select(new_selections);
6942 })
6943 });
6944 }
6945
6946 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6947 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6948 let buffer = self.buffer.read(cx).snapshot(cx);
6949
6950 let mut edits = Vec::new();
6951 let mut unfold_ranges = Vec::new();
6952 let mut refold_creases = Vec::new();
6953
6954 let selections = self.selections.all::<Point>(cx);
6955 let mut selections = selections.iter().peekable();
6956 let mut contiguous_row_selections = Vec::new();
6957 let mut new_selections = Vec::new();
6958
6959 while let Some(selection) = selections.next() {
6960 // Find all the selections that span a contiguous row range
6961 let (start_row, end_row) = consume_contiguous_rows(
6962 &mut contiguous_row_selections,
6963 selection,
6964 &display_map,
6965 &mut selections,
6966 );
6967
6968 // Move the text spanned by the row range to be after the last line of the row range
6969 if end_row.0 <= buffer.max_point().row {
6970 let range_to_move =
6971 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6972 let insertion_point = display_map
6973 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6974 .0;
6975
6976 // Don't move lines across excerpt boundaries
6977 if buffer
6978 .excerpt_boundaries_in_range((
6979 Bound::Excluded(range_to_move.start),
6980 Bound::Included(insertion_point),
6981 ))
6982 .next()
6983 .is_none()
6984 {
6985 let mut text = String::from("\n");
6986 text.extend(buffer.text_for_range(range_to_move.clone()));
6987 text.pop(); // Drop trailing newline
6988 edits.push((
6989 buffer.anchor_after(range_to_move.start)
6990 ..buffer.anchor_before(range_to_move.end),
6991 String::new(),
6992 ));
6993 let insertion_anchor = buffer.anchor_after(insertion_point);
6994 edits.push((insertion_anchor..insertion_anchor, text));
6995
6996 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6997
6998 // Move selections down
6999 new_selections.extend(contiguous_row_selections.drain(..).map(
7000 |mut selection| {
7001 selection.start.row += row_delta;
7002 selection.end.row += row_delta;
7003 selection
7004 },
7005 ));
7006
7007 // Move folds down
7008 unfold_ranges.push(range_to_move.clone());
7009 for fold in display_map.folds_in_range(
7010 buffer.anchor_before(range_to_move.start)
7011 ..buffer.anchor_after(range_to_move.end),
7012 ) {
7013 let mut start = fold.range.start.to_point(&buffer);
7014 let mut end = fold.range.end.to_point(&buffer);
7015 start.row += row_delta;
7016 end.row += row_delta;
7017 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7018 }
7019 }
7020 }
7021
7022 // If we didn't move line(s), preserve the existing selections
7023 new_selections.append(&mut contiguous_row_selections);
7024 }
7025
7026 self.transact(cx, |this, cx| {
7027 this.unfold_ranges(&unfold_ranges, true, true, cx);
7028 this.buffer.update(cx, |buffer, cx| {
7029 for (range, text) in edits {
7030 buffer.edit([(range, text)], None, cx);
7031 }
7032 });
7033 this.fold_creases(refold_creases, true, cx);
7034 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7035 });
7036 }
7037
7038 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7039 let text_layout_details = &self.text_layout_details(cx);
7040 self.transact(cx, |this, cx| {
7041 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7042 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7043 let line_mode = s.line_mode;
7044 s.move_with(|display_map, selection| {
7045 if !selection.is_empty() || line_mode {
7046 return;
7047 }
7048
7049 let mut head = selection.head();
7050 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7051 if head.column() == display_map.line_len(head.row()) {
7052 transpose_offset = display_map
7053 .buffer_snapshot
7054 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7055 }
7056
7057 if transpose_offset == 0 {
7058 return;
7059 }
7060
7061 *head.column_mut() += 1;
7062 head = display_map.clip_point(head, Bias::Right);
7063 let goal = SelectionGoal::HorizontalPosition(
7064 display_map
7065 .x_for_display_point(head, text_layout_details)
7066 .into(),
7067 );
7068 selection.collapse_to(head, goal);
7069
7070 let transpose_start = display_map
7071 .buffer_snapshot
7072 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7073 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7074 let transpose_end = display_map
7075 .buffer_snapshot
7076 .clip_offset(transpose_offset + 1, Bias::Right);
7077 if let Some(ch) =
7078 display_map.buffer_snapshot.chars_at(transpose_start).next()
7079 {
7080 edits.push((transpose_start..transpose_offset, String::new()));
7081 edits.push((transpose_end..transpose_end, ch.to_string()));
7082 }
7083 }
7084 });
7085 edits
7086 });
7087 this.buffer
7088 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7089 let selections = this.selections.all::<usize>(cx);
7090 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7091 s.select(selections);
7092 });
7093 });
7094 }
7095
7096 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7097 self.rewrap_impl(IsVimMode::No, cx)
7098 }
7099
7100 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7101 let buffer = self.buffer.read(cx).snapshot(cx);
7102 let selections = self.selections.all::<Point>(cx);
7103 let mut selections = selections.iter().peekable();
7104
7105 let mut edits = Vec::new();
7106 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7107
7108 while let Some(selection) = selections.next() {
7109 let mut start_row = selection.start.row;
7110 let mut end_row = selection.end.row;
7111
7112 // Skip selections that overlap with a range that has already been rewrapped.
7113 let selection_range = start_row..end_row;
7114 if rewrapped_row_ranges
7115 .iter()
7116 .any(|range| range.overlaps(&selection_range))
7117 {
7118 continue;
7119 }
7120
7121 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7122
7123 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7124 match language_scope.language_name().0.as_ref() {
7125 "Markdown" | "Plain Text" => {
7126 should_rewrap = true;
7127 }
7128 _ => {}
7129 }
7130 }
7131
7132 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7133
7134 // Since not all lines in the selection may be at the same indent
7135 // level, choose the indent size that is the most common between all
7136 // of the lines.
7137 //
7138 // If there is a tie, we use the deepest indent.
7139 let (indent_size, indent_end) = {
7140 let mut indent_size_occurrences = HashMap::default();
7141 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7142
7143 for row in start_row..=end_row {
7144 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7145 rows_by_indent_size.entry(indent).or_default().push(row);
7146 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7147 }
7148
7149 let indent_size = indent_size_occurrences
7150 .into_iter()
7151 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7152 .map(|(indent, _)| indent)
7153 .unwrap_or_default();
7154 let row = rows_by_indent_size[&indent_size][0];
7155 let indent_end = Point::new(row, indent_size.len);
7156
7157 (indent_size, indent_end)
7158 };
7159
7160 let mut line_prefix = indent_size.chars().collect::<String>();
7161
7162 if let Some(comment_prefix) =
7163 buffer
7164 .language_scope_at(selection.head())
7165 .and_then(|language| {
7166 language
7167 .line_comment_prefixes()
7168 .iter()
7169 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7170 .cloned()
7171 })
7172 {
7173 line_prefix.push_str(&comment_prefix);
7174 should_rewrap = true;
7175 }
7176
7177 if !should_rewrap {
7178 continue;
7179 }
7180
7181 if selection.is_empty() {
7182 'expand_upwards: while start_row > 0 {
7183 let prev_row = start_row - 1;
7184 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7185 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7186 {
7187 start_row = prev_row;
7188 } else {
7189 break 'expand_upwards;
7190 }
7191 }
7192
7193 'expand_downwards: while end_row < buffer.max_point().row {
7194 let next_row = end_row + 1;
7195 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7196 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7197 {
7198 end_row = next_row;
7199 } else {
7200 break 'expand_downwards;
7201 }
7202 }
7203 }
7204
7205 let start = Point::new(start_row, 0);
7206 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7207 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7208 let Some(lines_without_prefixes) = selection_text
7209 .lines()
7210 .map(|line| {
7211 line.strip_prefix(&line_prefix)
7212 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7213 .ok_or_else(|| {
7214 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7215 })
7216 })
7217 .collect::<Result<Vec<_>, _>>()
7218 .log_err()
7219 else {
7220 continue;
7221 };
7222
7223 let wrap_column = buffer
7224 .settings_at(Point::new(start_row, 0), cx)
7225 .preferred_line_length as usize;
7226 let wrapped_text = wrap_with_prefix(
7227 line_prefix,
7228 lines_without_prefixes.join(" "),
7229 wrap_column,
7230 tab_size,
7231 );
7232
7233 // TODO: should always use char-based diff while still supporting cursor behavior that
7234 // matches vim.
7235 let diff = match is_vim_mode {
7236 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7237 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7238 };
7239 let mut offset = start.to_offset(&buffer);
7240 let mut moved_since_edit = true;
7241
7242 for change in diff.iter_all_changes() {
7243 let value = change.value();
7244 match change.tag() {
7245 ChangeTag::Equal => {
7246 offset += value.len();
7247 moved_since_edit = true;
7248 }
7249 ChangeTag::Delete => {
7250 let start = buffer.anchor_after(offset);
7251 let end = buffer.anchor_before(offset + value.len());
7252
7253 if moved_since_edit {
7254 edits.push((start..end, String::new()));
7255 } else {
7256 edits.last_mut().unwrap().0.end = end;
7257 }
7258
7259 offset += value.len();
7260 moved_since_edit = false;
7261 }
7262 ChangeTag::Insert => {
7263 if moved_since_edit {
7264 let anchor = buffer.anchor_after(offset);
7265 edits.push((anchor..anchor, value.to_string()));
7266 } else {
7267 edits.last_mut().unwrap().1.push_str(value);
7268 }
7269
7270 moved_since_edit = false;
7271 }
7272 }
7273 }
7274
7275 rewrapped_row_ranges.push(start_row..=end_row);
7276 }
7277
7278 self.buffer
7279 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7280 }
7281
7282 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
7283 let mut text = String::new();
7284 let buffer = self.buffer.read(cx).snapshot(cx);
7285 let mut selections = self.selections.all::<Point>(cx);
7286 let mut clipboard_selections = Vec::with_capacity(selections.len());
7287 {
7288 let max_point = buffer.max_point();
7289 let mut is_first = true;
7290 for selection in &mut selections {
7291 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7292 if is_entire_line {
7293 selection.start = Point::new(selection.start.row, 0);
7294 if !selection.is_empty() && selection.end.column == 0 {
7295 selection.end = cmp::min(max_point, selection.end);
7296 } else {
7297 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7298 }
7299 selection.goal = SelectionGoal::None;
7300 }
7301 if is_first {
7302 is_first = false;
7303 } else {
7304 text += "\n";
7305 }
7306 let mut len = 0;
7307 for chunk in buffer.text_for_range(selection.start..selection.end) {
7308 text.push_str(chunk);
7309 len += chunk.len();
7310 }
7311 clipboard_selections.push(ClipboardSelection {
7312 len,
7313 is_entire_line,
7314 first_line_indent: buffer
7315 .indent_size_for_line(MultiBufferRow(selection.start.row))
7316 .len,
7317 });
7318 }
7319 }
7320
7321 self.transact(cx, |this, cx| {
7322 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7323 s.select(selections);
7324 });
7325 this.insert("", cx);
7326 });
7327 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7328 }
7329
7330 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7331 let item = self.cut_common(cx);
7332 cx.write_to_clipboard(item);
7333 }
7334
7335 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
7336 self.change_selections(None, cx, |s| {
7337 s.move_with(|snapshot, sel| {
7338 if sel.is_empty() {
7339 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7340 }
7341 });
7342 });
7343 let item = self.cut_common(cx);
7344 cx.set_global(KillRing(item))
7345 }
7346
7347 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7348 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7349 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7350 (kill_ring.text().to_string(), kill_ring.metadata_json())
7351 } else {
7352 return;
7353 }
7354 } else {
7355 return;
7356 };
7357 self.do_paste(&text, metadata, false, cx);
7358 }
7359
7360 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7361 let selections = self.selections.all::<Point>(cx);
7362 let buffer = self.buffer.read(cx).read(cx);
7363 let mut text = String::new();
7364
7365 let mut clipboard_selections = Vec::with_capacity(selections.len());
7366 {
7367 let max_point = buffer.max_point();
7368 let mut is_first = true;
7369 for selection in selections.iter() {
7370 let mut start = selection.start;
7371 let mut end = selection.end;
7372 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7373 if is_entire_line {
7374 start = Point::new(start.row, 0);
7375 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7376 }
7377 if is_first {
7378 is_first = false;
7379 } else {
7380 text += "\n";
7381 }
7382 let mut len = 0;
7383 for chunk in buffer.text_for_range(start..end) {
7384 text.push_str(chunk);
7385 len += chunk.len();
7386 }
7387 clipboard_selections.push(ClipboardSelection {
7388 len,
7389 is_entire_line,
7390 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7391 });
7392 }
7393 }
7394
7395 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7396 text,
7397 clipboard_selections,
7398 ));
7399 }
7400
7401 pub fn do_paste(
7402 &mut self,
7403 text: &String,
7404 clipboard_selections: Option<Vec<ClipboardSelection>>,
7405 handle_entire_lines: bool,
7406 cx: &mut ViewContext<Self>,
7407 ) {
7408 if self.read_only(cx) {
7409 return;
7410 }
7411
7412 let clipboard_text = Cow::Borrowed(text);
7413
7414 self.transact(cx, |this, cx| {
7415 if let Some(mut clipboard_selections) = clipboard_selections {
7416 let old_selections = this.selections.all::<usize>(cx);
7417 let all_selections_were_entire_line =
7418 clipboard_selections.iter().all(|s| s.is_entire_line);
7419 let first_selection_indent_column =
7420 clipboard_selections.first().map(|s| s.first_line_indent);
7421 if clipboard_selections.len() != old_selections.len() {
7422 clipboard_selections.drain(..);
7423 }
7424 let cursor_offset = this.selections.last::<usize>(cx).head();
7425 let mut auto_indent_on_paste = true;
7426
7427 this.buffer.update(cx, |buffer, cx| {
7428 let snapshot = buffer.read(cx);
7429 auto_indent_on_paste =
7430 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7431
7432 let mut start_offset = 0;
7433 let mut edits = Vec::new();
7434 let mut original_indent_columns = Vec::new();
7435 for (ix, selection) in old_selections.iter().enumerate() {
7436 let to_insert;
7437 let entire_line;
7438 let original_indent_column;
7439 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7440 let end_offset = start_offset + clipboard_selection.len;
7441 to_insert = &clipboard_text[start_offset..end_offset];
7442 entire_line = clipboard_selection.is_entire_line;
7443 start_offset = end_offset + 1;
7444 original_indent_column = Some(clipboard_selection.first_line_indent);
7445 } else {
7446 to_insert = clipboard_text.as_str();
7447 entire_line = all_selections_were_entire_line;
7448 original_indent_column = first_selection_indent_column
7449 }
7450
7451 // If the corresponding selection was empty when this slice of the
7452 // clipboard text was written, then the entire line containing the
7453 // selection was copied. If this selection is also currently empty,
7454 // then paste the line before the current line of the buffer.
7455 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7456 let column = selection.start.to_point(&snapshot).column as usize;
7457 let line_start = selection.start - column;
7458 line_start..line_start
7459 } else {
7460 selection.range()
7461 };
7462
7463 edits.push((range, to_insert));
7464 original_indent_columns.extend(original_indent_column);
7465 }
7466 drop(snapshot);
7467
7468 buffer.edit(
7469 edits,
7470 if auto_indent_on_paste {
7471 Some(AutoindentMode::Block {
7472 original_indent_columns,
7473 })
7474 } else {
7475 None
7476 },
7477 cx,
7478 );
7479 });
7480
7481 let selections = this.selections.all::<usize>(cx);
7482 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7483 } else {
7484 this.insert(&clipboard_text, cx);
7485 }
7486 });
7487 }
7488
7489 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7490 if let Some(item) = cx.read_from_clipboard() {
7491 let entries = item.entries();
7492
7493 match entries.first() {
7494 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7495 // of all the pasted entries.
7496 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7497 .do_paste(
7498 clipboard_string.text(),
7499 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7500 true,
7501 cx,
7502 ),
7503 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7504 }
7505 }
7506 }
7507
7508 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7509 if self.read_only(cx) {
7510 return;
7511 }
7512
7513 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7514 if let Some((selections, _)) =
7515 self.selection_history.transaction(transaction_id).cloned()
7516 {
7517 self.change_selections(None, cx, |s| {
7518 s.select_anchors(selections.to_vec());
7519 });
7520 }
7521 self.request_autoscroll(Autoscroll::fit(), cx);
7522 self.unmark_text(cx);
7523 self.refresh_inline_completion(true, false, cx);
7524 cx.emit(EditorEvent::Edited { transaction_id });
7525 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7526 }
7527 }
7528
7529 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7530 if self.read_only(cx) {
7531 return;
7532 }
7533
7534 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7535 if let Some((_, Some(selections))) =
7536 self.selection_history.transaction(transaction_id).cloned()
7537 {
7538 self.change_selections(None, cx, |s| {
7539 s.select_anchors(selections.to_vec());
7540 });
7541 }
7542 self.request_autoscroll(Autoscroll::fit(), cx);
7543 self.unmark_text(cx);
7544 self.refresh_inline_completion(true, false, cx);
7545 cx.emit(EditorEvent::Edited { transaction_id });
7546 }
7547 }
7548
7549 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7550 self.buffer
7551 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7552 }
7553
7554 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7555 self.buffer
7556 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7557 }
7558
7559 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7560 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7561 let line_mode = s.line_mode;
7562 s.move_with(|map, selection| {
7563 let cursor = if selection.is_empty() && !line_mode {
7564 movement::left(map, selection.start)
7565 } else {
7566 selection.start
7567 };
7568 selection.collapse_to(cursor, SelectionGoal::None);
7569 });
7570 })
7571 }
7572
7573 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7574 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7575 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7576 })
7577 }
7578
7579 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 let line_mode = s.line_mode;
7582 s.move_with(|map, selection| {
7583 let cursor = if selection.is_empty() && !line_mode {
7584 movement::right(map, selection.end)
7585 } else {
7586 selection.end
7587 };
7588 selection.collapse_to(cursor, SelectionGoal::None)
7589 });
7590 })
7591 }
7592
7593 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7594 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7595 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7596 })
7597 }
7598
7599 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7600 if self.take_rename(true, cx).is_some() {
7601 return;
7602 }
7603
7604 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7605 cx.propagate();
7606 return;
7607 }
7608
7609 let text_layout_details = &self.text_layout_details(cx);
7610 let selection_count = self.selections.count();
7611 let first_selection = self.selections.first_anchor();
7612
7613 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 let line_mode = s.line_mode;
7615 s.move_with(|map, selection| {
7616 if !selection.is_empty() && !line_mode {
7617 selection.goal = SelectionGoal::None;
7618 }
7619 let (cursor, goal) = movement::up(
7620 map,
7621 selection.start,
7622 selection.goal,
7623 false,
7624 text_layout_details,
7625 );
7626 selection.collapse_to(cursor, goal);
7627 });
7628 });
7629
7630 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7631 {
7632 cx.propagate();
7633 }
7634 }
7635
7636 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7637 if self.take_rename(true, cx).is_some() {
7638 return;
7639 }
7640
7641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7642 cx.propagate();
7643 return;
7644 }
7645
7646 let text_layout_details = &self.text_layout_details(cx);
7647
7648 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7649 let line_mode = s.line_mode;
7650 s.move_with(|map, selection| {
7651 if !selection.is_empty() && !line_mode {
7652 selection.goal = SelectionGoal::None;
7653 }
7654 let (cursor, goal) = movement::up_by_rows(
7655 map,
7656 selection.start,
7657 action.lines,
7658 selection.goal,
7659 false,
7660 text_layout_details,
7661 );
7662 selection.collapse_to(cursor, goal);
7663 });
7664 })
7665 }
7666
7667 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7668 if self.take_rename(true, cx).is_some() {
7669 return;
7670 }
7671
7672 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7673 cx.propagate();
7674 return;
7675 }
7676
7677 let text_layout_details = &self.text_layout_details(cx);
7678
7679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7680 let line_mode = s.line_mode;
7681 s.move_with(|map, selection| {
7682 if !selection.is_empty() && !line_mode {
7683 selection.goal = SelectionGoal::None;
7684 }
7685 let (cursor, goal) = movement::down_by_rows(
7686 map,
7687 selection.start,
7688 action.lines,
7689 selection.goal,
7690 false,
7691 text_layout_details,
7692 );
7693 selection.collapse_to(cursor, goal);
7694 });
7695 })
7696 }
7697
7698 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7699 let text_layout_details = &self.text_layout_details(cx);
7700 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7701 s.move_heads_with(|map, head, goal| {
7702 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7703 })
7704 })
7705 }
7706
7707 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7708 let text_layout_details = &self.text_layout_details(cx);
7709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7710 s.move_heads_with(|map, head, goal| {
7711 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7712 })
7713 })
7714 }
7715
7716 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7717 let Some(row_count) = self.visible_row_count() else {
7718 return;
7719 };
7720
7721 let text_layout_details = &self.text_layout_details(cx);
7722
7723 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7724 s.move_heads_with(|map, head, goal| {
7725 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7726 })
7727 })
7728 }
7729
7730 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7731 if self.take_rename(true, cx).is_some() {
7732 return;
7733 }
7734
7735 if self
7736 .context_menu
7737 .write()
7738 .as_mut()
7739 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7740 .unwrap_or(false)
7741 {
7742 return;
7743 }
7744
7745 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7746 cx.propagate();
7747 return;
7748 }
7749
7750 let Some(row_count) = self.visible_row_count() else {
7751 return;
7752 };
7753
7754 let autoscroll = if action.center_cursor {
7755 Autoscroll::center()
7756 } else {
7757 Autoscroll::fit()
7758 };
7759
7760 let text_layout_details = &self.text_layout_details(cx);
7761
7762 self.change_selections(Some(autoscroll), cx, |s| {
7763 let line_mode = s.line_mode;
7764 s.move_with(|map, selection| {
7765 if !selection.is_empty() && !line_mode {
7766 selection.goal = SelectionGoal::None;
7767 }
7768 let (cursor, goal) = movement::up_by_rows(
7769 map,
7770 selection.end,
7771 row_count,
7772 selection.goal,
7773 false,
7774 text_layout_details,
7775 );
7776 selection.collapse_to(cursor, goal);
7777 });
7778 });
7779 }
7780
7781 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7782 let text_layout_details = &self.text_layout_details(cx);
7783 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7784 s.move_heads_with(|map, head, goal| {
7785 movement::up(map, head, goal, false, text_layout_details)
7786 })
7787 })
7788 }
7789
7790 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7791 self.take_rename(true, cx);
7792
7793 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7794 cx.propagate();
7795 return;
7796 }
7797
7798 let text_layout_details = &self.text_layout_details(cx);
7799 let selection_count = self.selections.count();
7800 let first_selection = self.selections.first_anchor();
7801
7802 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7803 let line_mode = s.line_mode;
7804 s.move_with(|map, selection| {
7805 if !selection.is_empty() && !line_mode {
7806 selection.goal = SelectionGoal::None;
7807 }
7808 let (cursor, goal) = movement::down(
7809 map,
7810 selection.end,
7811 selection.goal,
7812 false,
7813 text_layout_details,
7814 );
7815 selection.collapse_to(cursor, goal);
7816 });
7817 });
7818
7819 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7820 {
7821 cx.propagate();
7822 }
7823 }
7824
7825 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7826 let Some(row_count) = self.visible_row_count() else {
7827 return;
7828 };
7829
7830 let text_layout_details = &self.text_layout_details(cx);
7831
7832 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7833 s.move_heads_with(|map, head, goal| {
7834 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7835 })
7836 })
7837 }
7838
7839 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7840 if self.take_rename(true, cx).is_some() {
7841 return;
7842 }
7843
7844 if self
7845 .context_menu
7846 .write()
7847 .as_mut()
7848 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7849 .unwrap_or(false)
7850 {
7851 return;
7852 }
7853
7854 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7855 cx.propagate();
7856 return;
7857 }
7858
7859 let Some(row_count) = self.visible_row_count() else {
7860 return;
7861 };
7862
7863 let autoscroll = if action.center_cursor {
7864 Autoscroll::center()
7865 } else {
7866 Autoscroll::fit()
7867 };
7868
7869 let text_layout_details = &self.text_layout_details(cx);
7870 self.change_selections(Some(autoscroll), cx, |s| {
7871 let line_mode = s.line_mode;
7872 s.move_with(|map, selection| {
7873 if !selection.is_empty() && !line_mode {
7874 selection.goal = SelectionGoal::None;
7875 }
7876 let (cursor, goal) = movement::down_by_rows(
7877 map,
7878 selection.end,
7879 row_count,
7880 selection.goal,
7881 false,
7882 text_layout_details,
7883 );
7884 selection.collapse_to(cursor, goal);
7885 });
7886 });
7887 }
7888
7889 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7890 let text_layout_details = &self.text_layout_details(cx);
7891 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7892 s.move_heads_with(|map, head, goal| {
7893 movement::down(map, head, goal, false, text_layout_details)
7894 })
7895 });
7896 }
7897
7898 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7899 if let Some(context_menu) = self.context_menu.write().as_mut() {
7900 context_menu.select_first(self.completion_provider.as_deref(), cx);
7901 }
7902 }
7903
7904 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7905 if let Some(context_menu) = self.context_menu.write().as_mut() {
7906 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7907 }
7908 }
7909
7910 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7911 if let Some(context_menu) = self.context_menu.write().as_mut() {
7912 context_menu.select_next(self.completion_provider.as_deref(), cx);
7913 }
7914 }
7915
7916 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7917 if let Some(context_menu) = self.context_menu.write().as_mut() {
7918 context_menu.select_last(self.completion_provider.as_deref(), cx);
7919 }
7920 }
7921
7922 pub fn move_to_previous_word_start(
7923 &mut self,
7924 _: &MoveToPreviousWordStart,
7925 cx: &mut ViewContext<Self>,
7926 ) {
7927 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7928 s.move_cursors_with(|map, head, _| {
7929 (
7930 movement::previous_word_start(map, head),
7931 SelectionGoal::None,
7932 )
7933 });
7934 })
7935 }
7936
7937 pub fn move_to_previous_subword_start(
7938 &mut self,
7939 _: &MoveToPreviousSubwordStart,
7940 cx: &mut ViewContext<Self>,
7941 ) {
7942 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7943 s.move_cursors_with(|map, head, _| {
7944 (
7945 movement::previous_subword_start(map, head),
7946 SelectionGoal::None,
7947 )
7948 });
7949 })
7950 }
7951
7952 pub fn select_to_previous_word_start(
7953 &mut self,
7954 _: &SelectToPreviousWordStart,
7955 cx: &mut ViewContext<Self>,
7956 ) {
7957 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7958 s.move_heads_with(|map, head, _| {
7959 (
7960 movement::previous_word_start(map, head),
7961 SelectionGoal::None,
7962 )
7963 });
7964 })
7965 }
7966
7967 pub fn select_to_previous_subword_start(
7968 &mut self,
7969 _: &SelectToPreviousSubwordStart,
7970 cx: &mut ViewContext<Self>,
7971 ) {
7972 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7973 s.move_heads_with(|map, head, _| {
7974 (
7975 movement::previous_subword_start(map, head),
7976 SelectionGoal::None,
7977 )
7978 });
7979 })
7980 }
7981
7982 pub fn delete_to_previous_word_start(
7983 &mut self,
7984 action: &DeleteToPreviousWordStart,
7985 cx: &mut ViewContext<Self>,
7986 ) {
7987 self.transact(cx, |this, cx| {
7988 this.select_autoclose_pair(cx);
7989 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7990 let line_mode = s.line_mode;
7991 s.move_with(|map, selection| {
7992 if selection.is_empty() && !line_mode {
7993 let cursor = if action.ignore_newlines {
7994 movement::previous_word_start(map, selection.head())
7995 } else {
7996 movement::previous_word_start_or_newline(map, selection.head())
7997 };
7998 selection.set_head(cursor, SelectionGoal::None);
7999 }
8000 });
8001 });
8002 this.insert("", cx);
8003 });
8004 }
8005
8006 pub fn delete_to_previous_subword_start(
8007 &mut self,
8008 _: &DeleteToPreviousSubwordStart,
8009 cx: &mut ViewContext<Self>,
8010 ) {
8011 self.transact(cx, |this, cx| {
8012 this.select_autoclose_pair(cx);
8013 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8014 let line_mode = s.line_mode;
8015 s.move_with(|map, selection| {
8016 if selection.is_empty() && !line_mode {
8017 let cursor = movement::previous_subword_start(map, selection.head());
8018 selection.set_head(cursor, SelectionGoal::None);
8019 }
8020 });
8021 });
8022 this.insert("", cx);
8023 });
8024 }
8025
8026 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8027 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8028 s.move_cursors_with(|map, head, _| {
8029 (movement::next_word_end(map, head), SelectionGoal::None)
8030 });
8031 })
8032 }
8033
8034 pub fn move_to_next_subword_end(
8035 &mut self,
8036 _: &MoveToNextSubwordEnd,
8037 cx: &mut ViewContext<Self>,
8038 ) {
8039 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8040 s.move_cursors_with(|map, head, _| {
8041 (movement::next_subword_end(map, head), SelectionGoal::None)
8042 });
8043 })
8044 }
8045
8046 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8047 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8048 s.move_heads_with(|map, head, _| {
8049 (movement::next_word_end(map, head), SelectionGoal::None)
8050 });
8051 })
8052 }
8053
8054 pub fn select_to_next_subword_end(
8055 &mut self,
8056 _: &SelectToNextSubwordEnd,
8057 cx: &mut ViewContext<Self>,
8058 ) {
8059 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8060 s.move_heads_with(|map, head, _| {
8061 (movement::next_subword_end(map, head), SelectionGoal::None)
8062 });
8063 })
8064 }
8065
8066 pub fn delete_to_next_word_end(
8067 &mut self,
8068 action: &DeleteToNextWordEnd,
8069 cx: &mut ViewContext<Self>,
8070 ) {
8071 self.transact(cx, |this, cx| {
8072 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8073 let line_mode = s.line_mode;
8074 s.move_with(|map, selection| {
8075 if selection.is_empty() && !line_mode {
8076 let cursor = if action.ignore_newlines {
8077 movement::next_word_end(map, selection.head())
8078 } else {
8079 movement::next_word_end_or_newline(map, selection.head())
8080 };
8081 selection.set_head(cursor, SelectionGoal::None);
8082 }
8083 });
8084 });
8085 this.insert("", cx);
8086 });
8087 }
8088
8089 pub fn delete_to_next_subword_end(
8090 &mut self,
8091 _: &DeleteToNextSubwordEnd,
8092 cx: &mut ViewContext<Self>,
8093 ) {
8094 self.transact(cx, |this, cx| {
8095 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8096 s.move_with(|map, selection| {
8097 if selection.is_empty() {
8098 let cursor = movement::next_subword_end(map, selection.head());
8099 selection.set_head(cursor, SelectionGoal::None);
8100 }
8101 });
8102 });
8103 this.insert("", cx);
8104 });
8105 }
8106
8107 pub fn move_to_beginning_of_line(
8108 &mut self,
8109 action: &MoveToBeginningOfLine,
8110 cx: &mut ViewContext<Self>,
8111 ) {
8112 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8113 s.move_cursors_with(|map, head, _| {
8114 (
8115 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8116 SelectionGoal::None,
8117 )
8118 });
8119 })
8120 }
8121
8122 pub fn select_to_beginning_of_line(
8123 &mut self,
8124 action: &SelectToBeginningOfLine,
8125 cx: &mut ViewContext<Self>,
8126 ) {
8127 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8128 s.move_heads_with(|map, head, _| {
8129 (
8130 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8131 SelectionGoal::None,
8132 )
8133 });
8134 });
8135 }
8136
8137 pub fn delete_to_beginning_of_line(
8138 &mut self,
8139 _: &DeleteToBeginningOfLine,
8140 cx: &mut ViewContext<Self>,
8141 ) {
8142 self.transact(cx, |this, cx| {
8143 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8144 s.move_with(|_, selection| {
8145 selection.reversed = true;
8146 });
8147 });
8148
8149 this.select_to_beginning_of_line(
8150 &SelectToBeginningOfLine {
8151 stop_at_soft_wraps: false,
8152 },
8153 cx,
8154 );
8155 this.backspace(&Backspace, cx);
8156 });
8157 }
8158
8159 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8160 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8161 s.move_cursors_with(|map, head, _| {
8162 (
8163 movement::line_end(map, head, action.stop_at_soft_wraps),
8164 SelectionGoal::None,
8165 )
8166 });
8167 })
8168 }
8169
8170 pub fn select_to_end_of_line(
8171 &mut self,
8172 action: &SelectToEndOfLine,
8173 cx: &mut ViewContext<Self>,
8174 ) {
8175 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8176 s.move_heads_with(|map, head, _| {
8177 (
8178 movement::line_end(map, head, action.stop_at_soft_wraps),
8179 SelectionGoal::None,
8180 )
8181 });
8182 })
8183 }
8184
8185 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8186 self.transact(cx, |this, cx| {
8187 this.select_to_end_of_line(
8188 &SelectToEndOfLine {
8189 stop_at_soft_wraps: false,
8190 },
8191 cx,
8192 );
8193 this.delete(&Delete, cx);
8194 });
8195 }
8196
8197 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8198 self.transact(cx, |this, cx| {
8199 this.select_to_end_of_line(
8200 &SelectToEndOfLine {
8201 stop_at_soft_wraps: false,
8202 },
8203 cx,
8204 );
8205 this.cut(&Cut, cx);
8206 });
8207 }
8208
8209 pub fn move_to_start_of_paragraph(
8210 &mut self,
8211 _: &MoveToStartOfParagraph,
8212 cx: &mut ViewContext<Self>,
8213 ) {
8214 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8215 cx.propagate();
8216 return;
8217 }
8218
8219 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8220 s.move_with(|map, selection| {
8221 selection.collapse_to(
8222 movement::start_of_paragraph(map, selection.head(), 1),
8223 SelectionGoal::None,
8224 )
8225 });
8226 })
8227 }
8228
8229 pub fn move_to_end_of_paragraph(
8230 &mut self,
8231 _: &MoveToEndOfParagraph,
8232 cx: &mut ViewContext<Self>,
8233 ) {
8234 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8235 cx.propagate();
8236 return;
8237 }
8238
8239 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8240 s.move_with(|map, selection| {
8241 selection.collapse_to(
8242 movement::end_of_paragraph(map, selection.head(), 1),
8243 SelectionGoal::None,
8244 )
8245 });
8246 })
8247 }
8248
8249 pub fn select_to_start_of_paragraph(
8250 &mut self,
8251 _: &SelectToStartOfParagraph,
8252 cx: &mut ViewContext<Self>,
8253 ) {
8254 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8255 cx.propagate();
8256 return;
8257 }
8258
8259 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8260 s.move_heads_with(|map, head, _| {
8261 (
8262 movement::start_of_paragraph(map, head, 1),
8263 SelectionGoal::None,
8264 )
8265 });
8266 })
8267 }
8268
8269 pub fn select_to_end_of_paragraph(
8270 &mut self,
8271 _: &SelectToEndOfParagraph,
8272 cx: &mut ViewContext<Self>,
8273 ) {
8274 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8275 cx.propagate();
8276 return;
8277 }
8278
8279 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8280 s.move_heads_with(|map, head, _| {
8281 (
8282 movement::end_of_paragraph(map, head, 1),
8283 SelectionGoal::None,
8284 )
8285 });
8286 })
8287 }
8288
8289 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8290 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8291 cx.propagate();
8292 return;
8293 }
8294
8295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8296 s.select_ranges(vec![0..0]);
8297 });
8298 }
8299
8300 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8301 let mut selection = self.selections.last::<Point>(cx);
8302 selection.set_head(Point::zero(), SelectionGoal::None);
8303
8304 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8305 s.select(vec![selection]);
8306 });
8307 }
8308
8309 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8310 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8311 cx.propagate();
8312 return;
8313 }
8314
8315 let cursor = self.buffer.read(cx).read(cx).len();
8316 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8317 s.select_ranges(vec![cursor..cursor])
8318 });
8319 }
8320
8321 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8322 self.nav_history = nav_history;
8323 }
8324
8325 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8326 self.nav_history.as_ref()
8327 }
8328
8329 fn push_to_nav_history(
8330 &mut self,
8331 cursor_anchor: Anchor,
8332 new_position: Option<Point>,
8333 cx: &mut ViewContext<Self>,
8334 ) {
8335 if let Some(nav_history) = self.nav_history.as_mut() {
8336 let buffer = self.buffer.read(cx).read(cx);
8337 let cursor_position = cursor_anchor.to_point(&buffer);
8338 let scroll_state = self.scroll_manager.anchor();
8339 let scroll_top_row = scroll_state.top_row(&buffer);
8340 drop(buffer);
8341
8342 if let Some(new_position) = new_position {
8343 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8344 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8345 return;
8346 }
8347 }
8348
8349 nav_history.push(
8350 Some(NavigationData {
8351 cursor_anchor,
8352 cursor_position,
8353 scroll_anchor: scroll_state,
8354 scroll_top_row,
8355 }),
8356 cx,
8357 );
8358 }
8359 }
8360
8361 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8362 let buffer = self.buffer.read(cx).snapshot(cx);
8363 let mut selection = self.selections.first::<usize>(cx);
8364 selection.set_head(buffer.len(), SelectionGoal::None);
8365 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8366 s.select(vec![selection]);
8367 });
8368 }
8369
8370 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8371 let end = self.buffer.read(cx).read(cx).len();
8372 self.change_selections(None, cx, |s| {
8373 s.select_ranges(vec![0..end]);
8374 });
8375 }
8376
8377 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8379 let mut selections = self.selections.all::<Point>(cx);
8380 let max_point = display_map.buffer_snapshot.max_point();
8381 for selection in &mut selections {
8382 let rows = selection.spanned_rows(true, &display_map);
8383 selection.start = Point::new(rows.start.0, 0);
8384 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8385 selection.reversed = false;
8386 }
8387 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8388 s.select(selections);
8389 });
8390 }
8391
8392 pub fn split_selection_into_lines(
8393 &mut self,
8394 _: &SplitSelectionIntoLines,
8395 cx: &mut ViewContext<Self>,
8396 ) {
8397 let mut to_unfold = Vec::new();
8398 let mut new_selection_ranges = Vec::new();
8399 {
8400 let selections = self.selections.all::<Point>(cx);
8401 let buffer = self.buffer.read(cx).read(cx);
8402 for selection in selections {
8403 for row in selection.start.row..selection.end.row {
8404 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8405 new_selection_ranges.push(cursor..cursor);
8406 }
8407 new_selection_ranges.push(selection.end..selection.end);
8408 to_unfold.push(selection.start..selection.end);
8409 }
8410 }
8411 self.unfold_ranges(&to_unfold, true, true, cx);
8412 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8413 s.select_ranges(new_selection_ranges);
8414 });
8415 }
8416
8417 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8418 self.add_selection(true, cx);
8419 }
8420
8421 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8422 self.add_selection(false, cx);
8423 }
8424
8425 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8426 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8427 let mut selections = self.selections.all::<Point>(cx);
8428 let text_layout_details = self.text_layout_details(cx);
8429 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8430 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8431 let range = oldest_selection.display_range(&display_map).sorted();
8432
8433 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8434 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8435 let positions = start_x.min(end_x)..start_x.max(end_x);
8436
8437 selections.clear();
8438 let mut stack = Vec::new();
8439 for row in range.start.row().0..=range.end.row().0 {
8440 if let Some(selection) = self.selections.build_columnar_selection(
8441 &display_map,
8442 DisplayRow(row),
8443 &positions,
8444 oldest_selection.reversed,
8445 &text_layout_details,
8446 ) {
8447 stack.push(selection.id);
8448 selections.push(selection);
8449 }
8450 }
8451
8452 if above {
8453 stack.reverse();
8454 }
8455
8456 AddSelectionsState { above, stack }
8457 });
8458
8459 let last_added_selection = *state.stack.last().unwrap();
8460 let mut new_selections = Vec::new();
8461 if above == state.above {
8462 let end_row = if above {
8463 DisplayRow(0)
8464 } else {
8465 display_map.max_point().row()
8466 };
8467
8468 'outer: for selection in selections {
8469 if selection.id == last_added_selection {
8470 let range = selection.display_range(&display_map).sorted();
8471 debug_assert_eq!(range.start.row(), range.end.row());
8472 let mut row = range.start.row();
8473 let positions =
8474 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8475 px(start)..px(end)
8476 } else {
8477 let start_x =
8478 display_map.x_for_display_point(range.start, &text_layout_details);
8479 let end_x =
8480 display_map.x_for_display_point(range.end, &text_layout_details);
8481 start_x.min(end_x)..start_x.max(end_x)
8482 };
8483
8484 while row != end_row {
8485 if above {
8486 row.0 -= 1;
8487 } else {
8488 row.0 += 1;
8489 }
8490
8491 if let Some(new_selection) = self.selections.build_columnar_selection(
8492 &display_map,
8493 row,
8494 &positions,
8495 selection.reversed,
8496 &text_layout_details,
8497 ) {
8498 state.stack.push(new_selection.id);
8499 if above {
8500 new_selections.push(new_selection);
8501 new_selections.push(selection);
8502 } else {
8503 new_selections.push(selection);
8504 new_selections.push(new_selection);
8505 }
8506
8507 continue 'outer;
8508 }
8509 }
8510 }
8511
8512 new_selections.push(selection);
8513 }
8514 } else {
8515 new_selections = selections;
8516 new_selections.retain(|s| s.id != last_added_selection);
8517 state.stack.pop();
8518 }
8519
8520 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8521 s.select(new_selections);
8522 });
8523 if state.stack.len() > 1 {
8524 self.add_selections_state = Some(state);
8525 }
8526 }
8527
8528 pub fn select_next_match_internal(
8529 &mut self,
8530 display_map: &DisplaySnapshot,
8531 replace_newest: bool,
8532 autoscroll: Option<Autoscroll>,
8533 cx: &mut ViewContext<Self>,
8534 ) -> Result<()> {
8535 fn select_next_match_ranges(
8536 this: &mut Editor,
8537 range: Range<usize>,
8538 replace_newest: bool,
8539 auto_scroll: Option<Autoscroll>,
8540 cx: &mut ViewContext<Editor>,
8541 ) {
8542 this.unfold_ranges(&[range.clone()], false, true, cx);
8543 this.change_selections(auto_scroll, cx, |s| {
8544 if replace_newest {
8545 s.delete(s.newest_anchor().id);
8546 }
8547 s.insert_range(range.clone());
8548 });
8549 }
8550
8551 let buffer = &display_map.buffer_snapshot;
8552 let mut selections = self.selections.all::<usize>(cx);
8553 if let Some(mut select_next_state) = self.select_next_state.take() {
8554 let query = &select_next_state.query;
8555 if !select_next_state.done {
8556 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8557 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8558 let mut next_selected_range = None;
8559
8560 let bytes_after_last_selection =
8561 buffer.bytes_in_range(last_selection.end..buffer.len());
8562 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8563 let query_matches = query
8564 .stream_find_iter(bytes_after_last_selection)
8565 .map(|result| (last_selection.end, result))
8566 .chain(
8567 query
8568 .stream_find_iter(bytes_before_first_selection)
8569 .map(|result| (0, result)),
8570 );
8571
8572 for (start_offset, query_match) in query_matches {
8573 let query_match = query_match.unwrap(); // can only fail due to I/O
8574 let offset_range =
8575 start_offset + query_match.start()..start_offset + query_match.end();
8576 let display_range = offset_range.start.to_display_point(display_map)
8577 ..offset_range.end.to_display_point(display_map);
8578
8579 if !select_next_state.wordwise
8580 || (!movement::is_inside_word(display_map, display_range.start)
8581 && !movement::is_inside_word(display_map, display_range.end))
8582 {
8583 // TODO: This is n^2, because we might check all the selections
8584 if !selections
8585 .iter()
8586 .any(|selection| selection.range().overlaps(&offset_range))
8587 {
8588 next_selected_range = Some(offset_range);
8589 break;
8590 }
8591 }
8592 }
8593
8594 if let Some(next_selected_range) = next_selected_range {
8595 select_next_match_ranges(
8596 self,
8597 next_selected_range,
8598 replace_newest,
8599 autoscroll,
8600 cx,
8601 );
8602 } else {
8603 select_next_state.done = true;
8604 }
8605 }
8606
8607 self.select_next_state = Some(select_next_state);
8608 } else {
8609 let mut only_carets = true;
8610 let mut same_text_selected = true;
8611 let mut selected_text = None;
8612
8613 let mut selections_iter = selections.iter().peekable();
8614 while let Some(selection) = selections_iter.next() {
8615 if selection.start != selection.end {
8616 only_carets = false;
8617 }
8618
8619 if same_text_selected {
8620 if selected_text.is_none() {
8621 selected_text =
8622 Some(buffer.text_for_range(selection.range()).collect::<String>());
8623 }
8624
8625 if let Some(next_selection) = selections_iter.peek() {
8626 if next_selection.range().len() == selection.range().len() {
8627 let next_selected_text = buffer
8628 .text_for_range(next_selection.range())
8629 .collect::<String>();
8630 if Some(next_selected_text) != selected_text {
8631 same_text_selected = false;
8632 selected_text = None;
8633 }
8634 } else {
8635 same_text_selected = false;
8636 selected_text = None;
8637 }
8638 }
8639 }
8640 }
8641
8642 if only_carets {
8643 for selection in &mut selections {
8644 let word_range = movement::surrounding_word(
8645 display_map,
8646 selection.start.to_display_point(display_map),
8647 );
8648 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8649 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8650 selection.goal = SelectionGoal::None;
8651 selection.reversed = false;
8652 select_next_match_ranges(
8653 self,
8654 selection.start..selection.end,
8655 replace_newest,
8656 autoscroll,
8657 cx,
8658 );
8659 }
8660
8661 if selections.len() == 1 {
8662 let selection = selections
8663 .last()
8664 .expect("ensured that there's only one selection");
8665 let query = buffer
8666 .text_for_range(selection.start..selection.end)
8667 .collect::<String>();
8668 let is_empty = query.is_empty();
8669 let select_state = SelectNextState {
8670 query: AhoCorasick::new(&[query])?,
8671 wordwise: true,
8672 done: is_empty,
8673 };
8674 self.select_next_state = Some(select_state);
8675 } else {
8676 self.select_next_state = None;
8677 }
8678 } else if let Some(selected_text) = selected_text {
8679 self.select_next_state = Some(SelectNextState {
8680 query: AhoCorasick::new(&[selected_text])?,
8681 wordwise: false,
8682 done: false,
8683 });
8684 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8685 }
8686 }
8687 Ok(())
8688 }
8689
8690 pub fn select_all_matches(
8691 &mut self,
8692 _action: &SelectAllMatches,
8693 cx: &mut ViewContext<Self>,
8694 ) -> Result<()> {
8695 self.push_to_selection_history();
8696 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8697
8698 self.select_next_match_internal(&display_map, false, None, cx)?;
8699 let Some(select_next_state) = self.select_next_state.as_mut() else {
8700 return Ok(());
8701 };
8702 if select_next_state.done {
8703 return Ok(());
8704 }
8705
8706 let mut new_selections = self.selections.all::<usize>(cx);
8707
8708 let buffer = &display_map.buffer_snapshot;
8709 let query_matches = select_next_state
8710 .query
8711 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8712
8713 for query_match in query_matches {
8714 let query_match = query_match.unwrap(); // can only fail due to I/O
8715 let offset_range = query_match.start()..query_match.end();
8716 let display_range = offset_range.start.to_display_point(&display_map)
8717 ..offset_range.end.to_display_point(&display_map);
8718
8719 if !select_next_state.wordwise
8720 || (!movement::is_inside_word(&display_map, display_range.start)
8721 && !movement::is_inside_word(&display_map, display_range.end))
8722 {
8723 self.selections.change_with(cx, |selections| {
8724 new_selections.push(Selection {
8725 id: selections.new_selection_id(),
8726 start: offset_range.start,
8727 end: offset_range.end,
8728 reversed: false,
8729 goal: SelectionGoal::None,
8730 });
8731 });
8732 }
8733 }
8734
8735 new_selections.sort_by_key(|selection| selection.start);
8736 let mut ix = 0;
8737 while ix + 1 < new_selections.len() {
8738 let current_selection = &new_selections[ix];
8739 let next_selection = &new_selections[ix + 1];
8740 if current_selection.range().overlaps(&next_selection.range()) {
8741 if current_selection.id < next_selection.id {
8742 new_selections.remove(ix + 1);
8743 } else {
8744 new_selections.remove(ix);
8745 }
8746 } else {
8747 ix += 1;
8748 }
8749 }
8750
8751 select_next_state.done = true;
8752 self.unfold_ranges(
8753 &new_selections
8754 .iter()
8755 .map(|selection| selection.range())
8756 .collect::<Vec<_>>(),
8757 false,
8758 false,
8759 cx,
8760 );
8761 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8762 selections.select(new_selections)
8763 });
8764
8765 Ok(())
8766 }
8767
8768 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8769 self.push_to_selection_history();
8770 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8771 self.select_next_match_internal(
8772 &display_map,
8773 action.replace_newest,
8774 Some(Autoscroll::newest()),
8775 cx,
8776 )?;
8777 Ok(())
8778 }
8779
8780 pub fn select_previous(
8781 &mut self,
8782 action: &SelectPrevious,
8783 cx: &mut ViewContext<Self>,
8784 ) -> Result<()> {
8785 self.push_to_selection_history();
8786 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8787 let buffer = &display_map.buffer_snapshot;
8788 let mut selections = self.selections.all::<usize>(cx);
8789 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8790 let query = &select_prev_state.query;
8791 if !select_prev_state.done {
8792 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8793 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8794 let mut next_selected_range = None;
8795 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8796 let bytes_before_last_selection =
8797 buffer.reversed_bytes_in_range(0..last_selection.start);
8798 let bytes_after_first_selection =
8799 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8800 let query_matches = query
8801 .stream_find_iter(bytes_before_last_selection)
8802 .map(|result| (last_selection.start, result))
8803 .chain(
8804 query
8805 .stream_find_iter(bytes_after_first_selection)
8806 .map(|result| (buffer.len(), result)),
8807 );
8808 for (end_offset, query_match) in query_matches {
8809 let query_match = query_match.unwrap(); // can only fail due to I/O
8810 let offset_range =
8811 end_offset - query_match.end()..end_offset - query_match.start();
8812 let display_range = offset_range.start.to_display_point(&display_map)
8813 ..offset_range.end.to_display_point(&display_map);
8814
8815 if !select_prev_state.wordwise
8816 || (!movement::is_inside_word(&display_map, display_range.start)
8817 && !movement::is_inside_word(&display_map, display_range.end))
8818 {
8819 next_selected_range = Some(offset_range);
8820 break;
8821 }
8822 }
8823
8824 if let Some(next_selected_range) = next_selected_range {
8825 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8826 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8827 if action.replace_newest {
8828 s.delete(s.newest_anchor().id);
8829 }
8830 s.insert_range(next_selected_range);
8831 });
8832 } else {
8833 select_prev_state.done = true;
8834 }
8835 }
8836
8837 self.select_prev_state = Some(select_prev_state);
8838 } else {
8839 let mut only_carets = true;
8840 let mut same_text_selected = true;
8841 let mut selected_text = None;
8842
8843 let mut selections_iter = selections.iter().peekable();
8844 while let Some(selection) = selections_iter.next() {
8845 if selection.start != selection.end {
8846 only_carets = false;
8847 }
8848
8849 if same_text_selected {
8850 if selected_text.is_none() {
8851 selected_text =
8852 Some(buffer.text_for_range(selection.range()).collect::<String>());
8853 }
8854
8855 if let Some(next_selection) = selections_iter.peek() {
8856 if next_selection.range().len() == selection.range().len() {
8857 let next_selected_text = buffer
8858 .text_for_range(next_selection.range())
8859 .collect::<String>();
8860 if Some(next_selected_text) != selected_text {
8861 same_text_selected = false;
8862 selected_text = None;
8863 }
8864 } else {
8865 same_text_selected = false;
8866 selected_text = None;
8867 }
8868 }
8869 }
8870 }
8871
8872 if only_carets {
8873 for selection in &mut selections {
8874 let word_range = movement::surrounding_word(
8875 &display_map,
8876 selection.start.to_display_point(&display_map),
8877 );
8878 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8879 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8880 selection.goal = SelectionGoal::None;
8881 selection.reversed = false;
8882 }
8883 if selections.len() == 1 {
8884 let selection = selections
8885 .last()
8886 .expect("ensured that there's only one selection");
8887 let query = buffer
8888 .text_for_range(selection.start..selection.end)
8889 .collect::<String>();
8890 let is_empty = query.is_empty();
8891 let select_state = SelectNextState {
8892 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8893 wordwise: true,
8894 done: is_empty,
8895 };
8896 self.select_prev_state = Some(select_state);
8897 } else {
8898 self.select_prev_state = None;
8899 }
8900
8901 self.unfold_ranges(
8902 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8903 false,
8904 true,
8905 cx,
8906 );
8907 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8908 s.select(selections);
8909 });
8910 } else if let Some(selected_text) = selected_text {
8911 self.select_prev_state = Some(SelectNextState {
8912 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8913 wordwise: false,
8914 done: false,
8915 });
8916 self.select_previous(action, cx)?;
8917 }
8918 }
8919 Ok(())
8920 }
8921
8922 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8923 if self.read_only(cx) {
8924 return;
8925 }
8926 let text_layout_details = &self.text_layout_details(cx);
8927 self.transact(cx, |this, cx| {
8928 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8929 let mut edits = Vec::new();
8930 let mut selection_edit_ranges = Vec::new();
8931 let mut last_toggled_row = None;
8932 let snapshot = this.buffer.read(cx).read(cx);
8933 let empty_str: Arc<str> = Arc::default();
8934 let mut suffixes_inserted = Vec::new();
8935 let ignore_indent = action.ignore_indent;
8936
8937 fn comment_prefix_range(
8938 snapshot: &MultiBufferSnapshot,
8939 row: MultiBufferRow,
8940 comment_prefix: &str,
8941 comment_prefix_whitespace: &str,
8942 ignore_indent: bool,
8943 ) -> Range<Point> {
8944 let indent_size = if ignore_indent {
8945 0
8946 } else {
8947 snapshot.indent_size_for_line(row).len
8948 };
8949
8950 let start = Point::new(row.0, indent_size);
8951
8952 let mut line_bytes = snapshot
8953 .bytes_in_range(start..snapshot.max_point())
8954 .flatten()
8955 .copied();
8956
8957 // If this line currently begins with the line comment prefix, then record
8958 // the range containing the prefix.
8959 if line_bytes
8960 .by_ref()
8961 .take(comment_prefix.len())
8962 .eq(comment_prefix.bytes())
8963 {
8964 // Include any whitespace that matches the comment prefix.
8965 let matching_whitespace_len = line_bytes
8966 .zip(comment_prefix_whitespace.bytes())
8967 .take_while(|(a, b)| a == b)
8968 .count() as u32;
8969 let end = Point::new(
8970 start.row,
8971 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8972 );
8973 start..end
8974 } else {
8975 start..start
8976 }
8977 }
8978
8979 fn comment_suffix_range(
8980 snapshot: &MultiBufferSnapshot,
8981 row: MultiBufferRow,
8982 comment_suffix: &str,
8983 comment_suffix_has_leading_space: bool,
8984 ) -> Range<Point> {
8985 let end = Point::new(row.0, snapshot.line_len(row));
8986 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8987
8988 let mut line_end_bytes = snapshot
8989 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8990 .flatten()
8991 .copied();
8992
8993 let leading_space_len = if suffix_start_column > 0
8994 && line_end_bytes.next() == Some(b' ')
8995 && comment_suffix_has_leading_space
8996 {
8997 1
8998 } else {
8999 0
9000 };
9001
9002 // If this line currently begins with the line comment prefix, then record
9003 // the range containing the prefix.
9004 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9005 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9006 start..end
9007 } else {
9008 end..end
9009 }
9010 }
9011
9012 // TODO: Handle selections that cross excerpts
9013 for selection in &mut selections {
9014 let start_column = snapshot
9015 .indent_size_for_line(MultiBufferRow(selection.start.row))
9016 .len;
9017 let language = if let Some(language) =
9018 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9019 {
9020 language
9021 } else {
9022 continue;
9023 };
9024
9025 selection_edit_ranges.clear();
9026
9027 // If multiple selections contain a given row, avoid processing that
9028 // row more than once.
9029 let mut start_row = MultiBufferRow(selection.start.row);
9030 if last_toggled_row == Some(start_row) {
9031 start_row = start_row.next_row();
9032 }
9033 let end_row =
9034 if selection.end.row > selection.start.row && selection.end.column == 0 {
9035 MultiBufferRow(selection.end.row - 1)
9036 } else {
9037 MultiBufferRow(selection.end.row)
9038 };
9039 last_toggled_row = Some(end_row);
9040
9041 if start_row > end_row {
9042 continue;
9043 }
9044
9045 // If the language has line comments, toggle those.
9046 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9047
9048 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9049 if ignore_indent {
9050 full_comment_prefixes = full_comment_prefixes
9051 .into_iter()
9052 .map(|s| Arc::from(s.trim_end()))
9053 .collect();
9054 }
9055
9056 if !full_comment_prefixes.is_empty() {
9057 let first_prefix = full_comment_prefixes
9058 .first()
9059 .expect("prefixes is non-empty");
9060 let prefix_trimmed_lengths = full_comment_prefixes
9061 .iter()
9062 .map(|p| p.trim_end_matches(' ').len())
9063 .collect::<SmallVec<[usize; 4]>>();
9064
9065 let mut all_selection_lines_are_comments = true;
9066
9067 for row in start_row.0..=end_row.0 {
9068 let row = MultiBufferRow(row);
9069 if start_row < end_row && snapshot.is_line_blank(row) {
9070 continue;
9071 }
9072
9073 let prefix_range = full_comment_prefixes
9074 .iter()
9075 .zip(prefix_trimmed_lengths.iter().copied())
9076 .map(|(prefix, trimmed_prefix_len)| {
9077 comment_prefix_range(
9078 snapshot.deref(),
9079 row,
9080 &prefix[..trimmed_prefix_len],
9081 &prefix[trimmed_prefix_len..],
9082 ignore_indent,
9083 )
9084 })
9085 .max_by_key(|range| range.end.column - range.start.column)
9086 .expect("prefixes is non-empty");
9087
9088 if prefix_range.is_empty() {
9089 all_selection_lines_are_comments = false;
9090 }
9091
9092 selection_edit_ranges.push(prefix_range);
9093 }
9094
9095 if all_selection_lines_are_comments {
9096 edits.extend(
9097 selection_edit_ranges
9098 .iter()
9099 .cloned()
9100 .map(|range| (range, empty_str.clone())),
9101 );
9102 } else {
9103 let min_column = selection_edit_ranges
9104 .iter()
9105 .map(|range| range.start.column)
9106 .min()
9107 .unwrap_or(0);
9108 edits.extend(selection_edit_ranges.iter().map(|range| {
9109 let position = Point::new(range.start.row, min_column);
9110 (position..position, first_prefix.clone())
9111 }));
9112 }
9113 } else if let Some((full_comment_prefix, comment_suffix)) =
9114 language.block_comment_delimiters()
9115 {
9116 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9117 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9118 let prefix_range = comment_prefix_range(
9119 snapshot.deref(),
9120 start_row,
9121 comment_prefix,
9122 comment_prefix_whitespace,
9123 ignore_indent,
9124 );
9125 let suffix_range = comment_suffix_range(
9126 snapshot.deref(),
9127 end_row,
9128 comment_suffix.trim_start_matches(' '),
9129 comment_suffix.starts_with(' '),
9130 );
9131
9132 if prefix_range.is_empty() || suffix_range.is_empty() {
9133 edits.push((
9134 prefix_range.start..prefix_range.start,
9135 full_comment_prefix.clone(),
9136 ));
9137 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9138 suffixes_inserted.push((end_row, comment_suffix.len()));
9139 } else {
9140 edits.push((prefix_range, empty_str.clone()));
9141 edits.push((suffix_range, empty_str.clone()));
9142 }
9143 } else {
9144 continue;
9145 }
9146 }
9147
9148 drop(snapshot);
9149 this.buffer.update(cx, |buffer, cx| {
9150 buffer.edit(edits, None, cx);
9151 });
9152
9153 // Adjust selections so that they end before any comment suffixes that
9154 // were inserted.
9155 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9156 let mut selections = this.selections.all::<Point>(cx);
9157 let snapshot = this.buffer.read(cx).read(cx);
9158 for selection in &mut selections {
9159 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9160 match row.cmp(&MultiBufferRow(selection.end.row)) {
9161 Ordering::Less => {
9162 suffixes_inserted.next();
9163 continue;
9164 }
9165 Ordering::Greater => break,
9166 Ordering::Equal => {
9167 if selection.end.column == snapshot.line_len(row) {
9168 if selection.is_empty() {
9169 selection.start.column -= suffix_len as u32;
9170 }
9171 selection.end.column -= suffix_len as u32;
9172 }
9173 break;
9174 }
9175 }
9176 }
9177 }
9178
9179 drop(snapshot);
9180 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9181
9182 let selections = this.selections.all::<Point>(cx);
9183 let selections_on_single_row = selections.windows(2).all(|selections| {
9184 selections[0].start.row == selections[1].start.row
9185 && selections[0].end.row == selections[1].end.row
9186 && selections[0].start.row == selections[0].end.row
9187 });
9188 let selections_selecting = selections
9189 .iter()
9190 .any(|selection| selection.start != selection.end);
9191 let advance_downwards = action.advance_downwards
9192 && selections_on_single_row
9193 && !selections_selecting
9194 && !matches!(this.mode, EditorMode::SingleLine { .. });
9195
9196 if advance_downwards {
9197 let snapshot = this.buffer.read(cx).snapshot(cx);
9198
9199 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9200 s.move_cursors_with(|display_snapshot, display_point, _| {
9201 let mut point = display_point.to_point(display_snapshot);
9202 point.row += 1;
9203 point = snapshot.clip_point(point, Bias::Left);
9204 let display_point = point.to_display_point(display_snapshot);
9205 let goal = SelectionGoal::HorizontalPosition(
9206 display_snapshot
9207 .x_for_display_point(display_point, text_layout_details)
9208 .into(),
9209 );
9210 (display_point, goal)
9211 })
9212 });
9213 }
9214 });
9215 }
9216
9217 pub fn select_enclosing_symbol(
9218 &mut self,
9219 _: &SelectEnclosingSymbol,
9220 cx: &mut ViewContext<Self>,
9221 ) {
9222 let buffer = self.buffer.read(cx).snapshot(cx);
9223 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9224
9225 fn update_selection(
9226 selection: &Selection<usize>,
9227 buffer_snap: &MultiBufferSnapshot,
9228 ) -> Option<Selection<usize>> {
9229 let cursor = selection.head();
9230 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9231 for symbol in symbols.iter().rev() {
9232 let start = symbol.range.start.to_offset(buffer_snap);
9233 let end = symbol.range.end.to_offset(buffer_snap);
9234 let new_range = start..end;
9235 if start < selection.start || end > selection.end {
9236 return Some(Selection {
9237 id: selection.id,
9238 start: new_range.start,
9239 end: new_range.end,
9240 goal: SelectionGoal::None,
9241 reversed: selection.reversed,
9242 });
9243 }
9244 }
9245 None
9246 }
9247
9248 let mut selected_larger_symbol = false;
9249 let new_selections = old_selections
9250 .iter()
9251 .map(|selection| match update_selection(selection, &buffer) {
9252 Some(new_selection) => {
9253 if new_selection.range() != selection.range() {
9254 selected_larger_symbol = true;
9255 }
9256 new_selection
9257 }
9258 None => selection.clone(),
9259 })
9260 .collect::<Vec<_>>();
9261
9262 if selected_larger_symbol {
9263 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9264 s.select(new_selections);
9265 });
9266 }
9267 }
9268
9269 pub fn select_larger_syntax_node(
9270 &mut self,
9271 _: &SelectLargerSyntaxNode,
9272 cx: &mut ViewContext<Self>,
9273 ) {
9274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9275 let buffer = self.buffer.read(cx).snapshot(cx);
9276 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9277
9278 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9279 let mut selected_larger_node = false;
9280 let new_selections = old_selections
9281 .iter()
9282 .map(|selection| {
9283 let old_range = selection.start..selection.end;
9284 let mut new_range = old_range.clone();
9285 while let Some(containing_range) =
9286 buffer.range_for_syntax_ancestor(new_range.clone())
9287 {
9288 new_range = containing_range;
9289 if !display_map.intersects_fold(new_range.start)
9290 && !display_map.intersects_fold(new_range.end)
9291 {
9292 break;
9293 }
9294 }
9295
9296 selected_larger_node |= new_range != old_range;
9297 Selection {
9298 id: selection.id,
9299 start: new_range.start,
9300 end: new_range.end,
9301 goal: SelectionGoal::None,
9302 reversed: selection.reversed,
9303 }
9304 })
9305 .collect::<Vec<_>>();
9306
9307 if selected_larger_node {
9308 stack.push(old_selections);
9309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9310 s.select(new_selections);
9311 });
9312 }
9313 self.select_larger_syntax_node_stack = stack;
9314 }
9315
9316 pub fn select_smaller_syntax_node(
9317 &mut self,
9318 _: &SelectSmallerSyntaxNode,
9319 cx: &mut ViewContext<Self>,
9320 ) {
9321 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9322 if let Some(selections) = stack.pop() {
9323 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9324 s.select(selections.to_vec());
9325 });
9326 }
9327 self.select_larger_syntax_node_stack = stack;
9328 }
9329
9330 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9331 if !EditorSettings::get_global(cx).gutter.runnables {
9332 self.clear_tasks();
9333 return Task::ready(());
9334 }
9335 let project = self.project.as_ref().map(Model::downgrade);
9336 cx.spawn(|this, mut cx| async move {
9337 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9338 let Some(project) = project.and_then(|p| p.upgrade()) else {
9339 return;
9340 };
9341 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9342 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9343 }) else {
9344 return;
9345 };
9346
9347 let hide_runnables = project
9348 .update(&mut cx, |project, cx| {
9349 // Do not display any test indicators in non-dev server remote projects.
9350 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9351 })
9352 .unwrap_or(true);
9353 if hide_runnables {
9354 return;
9355 }
9356 let new_rows =
9357 cx.background_executor()
9358 .spawn({
9359 let snapshot = display_snapshot.clone();
9360 async move {
9361 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9362 }
9363 })
9364 .await;
9365 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9366
9367 this.update(&mut cx, |this, _| {
9368 this.clear_tasks();
9369 for (key, value) in rows {
9370 this.insert_tasks(key, value);
9371 }
9372 })
9373 .ok();
9374 })
9375 }
9376 fn fetch_runnable_ranges(
9377 snapshot: &DisplaySnapshot,
9378 range: Range<Anchor>,
9379 ) -> Vec<language::RunnableRange> {
9380 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9381 }
9382
9383 fn runnable_rows(
9384 project: Model<Project>,
9385 snapshot: DisplaySnapshot,
9386 runnable_ranges: Vec<RunnableRange>,
9387 mut cx: AsyncWindowContext,
9388 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9389 runnable_ranges
9390 .into_iter()
9391 .filter_map(|mut runnable| {
9392 let tasks = cx
9393 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9394 .ok()?;
9395 if tasks.is_empty() {
9396 return None;
9397 }
9398
9399 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9400
9401 let row = snapshot
9402 .buffer_snapshot
9403 .buffer_line_for_row(MultiBufferRow(point.row))?
9404 .1
9405 .start
9406 .row;
9407
9408 let context_range =
9409 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9410 Some((
9411 (runnable.buffer_id, row),
9412 RunnableTasks {
9413 templates: tasks,
9414 offset: MultiBufferOffset(runnable.run_range.start),
9415 context_range,
9416 column: point.column,
9417 extra_variables: runnable.extra_captures,
9418 },
9419 ))
9420 })
9421 .collect()
9422 }
9423
9424 fn templates_with_tags(
9425 project: &Model<Project>,
9426 runnable: &mut Runnable,
9427 cx: &WindowContext<'_>,
9428 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9429 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9430 let (worktree_id, file) = project
9431 .buffer_for_id(runnable.buffer, cx)
9432 .and_then(|buffer| buffer.read(cx).file())
9433 .map(|file| (file.worktree_id(cx), file.clone()))
9434 .unzip();
9435
9436 (
9437 project.task_store().read(cx).task_inventory().cloned(),
9438 worktree_id,
9439 file,
9440 )
9441 });
9442
9443 let tags = mem::take(&mut runnable.tags);
9444 let mut tags: Vec<_> = tags
9445 .into_iter()
9446 .flat_map(|tag| {
9447 let tag = tag.0.clone();
9448 inventory
9449 .as_ref()
9450 .into_iter()
9451 .flat_map(|inventory| {
9452 inventory.read(cx).list_tasks(
9453 file.clone(),
9454 Some(runnable.language.clone()),
9455 worktree_id,
9456 cx,
9457 )
9458 })
9459 .filter(move |(_, template)| {
9460 template.tags.iter().any(|source_tag| source_tag == &tag)
9461 })
9462 })
9463 .sorted_by_key(|(kind, _)| kind.to_owned())
9464 .collect();
9465 if let Some((leading_tag_source, _)) = tags.first() {
9466 // Strongest source wins; if we have worktree tag binding, prefer that to
9467 // global and language bindings;
9468 // if we have a global binding, prefer that to language binding.
9469 let first_mismatch = tags
9470 .iter()
9471 .position(|(tag_source, _)| tag_source != leading_tag_source);
9472 if let Some(index) = first_mismatch {
9473 tags.truncate(index);
9474 }
9475 }
9476
9477 tags
9478 }
9479
9480 pub fn move_to_enclosing_bracket(
9481 &mut self,
9482 _: &MoveToEnclosingBracket,
9483 cx: &mut ViewContext<Self>,
9484 ) {
9485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9486 s.move_offsets_with(|snapshot, selection| {
9487 let Some(enclosing_bracket_ranges) =
9488 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9489 else {
9490 return;
9491 };
9492
9493 let mut best_length = usize::MAX;
9494 let mut best_inside = false;
9495 let mut best_in_bracket_range = false;
9496 let mut best_destination = None;
9497 for (open, close) in enclosing_bracket_ranges {
9498 let close = close.to_inclusive();
9499 let length = close.end() - open.start;
9500 let inside = selection.start >= open.end && selection.end <= *close.start();
9501 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9502 || close.contains(&selection.head());
9503
9504 // If best is next to a bracket and current isn't, skip
9505 if !in_bracket_range && best_in_bracket_range {
9506 continue;
9507 }
9508
9509 // Prefer smaller lengths unless best is inside and current isn't
9510 if length > best_length && (best_inside || !inside) {
9511 continue;
9512 }
9513
9514 best_length = length;
9515 best_inside = inside;
9516 best_in_bracket_range = in_bracket_range;
9517 best_destination = Some(
9518 if close.contains(&selection.start) && close.contains(&selection.end) {
9519 if inside {
9520 open.end
9521 } else {
9522 open.start
9523 }
9524 } else if inside {
9525 *close.start()
9526 } else {
9527 *close.end()
9528 },
9529 );
9530 }
9531
9532 if let Some(destination) = best_destination {
9533 selection.collapse_to(destination, SelectionGoal::None);
9534 }
9535 })
9536 });
9537 }
9538
9539 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9540 self.end_selection(cx);
9541 self.selection_history.mode = SelectionHistoryMode::Undoing;
9542 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9543 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9544 self.select_next_state = entry.select_next_state;
9545 self.select_prev_state = entry.select_prev_state;
9546 self.add_selections_state = entry.add_selections_state;
9547 self.request_autoscroll(Autoscroll::newest(), cx);
9548 }
9549 self.selection_history.mode = SelectionHistoryMode::Normal;
9550 }
9551
9552 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9553 self.end_selection(cx);
9554 self.selection_history.mode = SelectionHistoryMode::Redoing;
9555 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9556 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9557 self.select_next_state = entry.select_next_state;
9558 self.select_prev_state = entry.select_prev_state;
9559 self.add_selections_state = entry.add_selections_state;
9560 self.request_autoscroll(Autoscroll::newest(), cx);
9561 }
9562 self.selection_history.mode = SelectionHistoryMode::Normal;
9563 }
9564
9565 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9566 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9567 }
9568
9569 pub fn expand_excerpts_down(
9570 &mut self,
9571 action: &ExpandExcerptsDown,
9572 cx: &mut ViewContext<Self>,
9573 ) {
9574 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9575 }
9576
9577 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9578 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9579 }
9580
9581 pub fn expand_excerpts_for_direction(
9582 &mut self,
9583 lines: u32,
9584 direction: ExpandExcerptDirection,
9585 cx: &mut ViewContext<Self>,
9586 ) {
9587 let selections = self.selections.disjoint_anchors();
9588
9589 let lines = if lines == 0 {
9590 EditorSettings::get_global(cx).expand_excerpt_lines
9591 } else {
9592 lines
9593 };
9594
9595 self.buffer.update(cx, |buffer, cx| {
9596 buffer.expand_excerpts(
9597 selections
9598 .iter()
9599 .map(|selection| selection.head().excerpt_id)
9600 .dedup(),
9601 lines,
9602 direction,
9603 cx,
9604 )
9605 })
9606 }
9607
9608 pub fn expand_excerpt(
9609 &mut self,
9610 excerpt: ExcerptId,
9611 direction: ExpandExcerptDirection,
9612 cx: &mut ViewContext<Self>,
9613 ) {
9614 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9615 self.buffer.update(cx, |buffer, cx| {
9616 buffer.expand_excerpts([excerpt], lines, direction, cx)
9617 })
9618 }
9619
9620 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9621 self.go_to_diagnostic_impl(Direction::Next, cx)
9622 }
9623
9624 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9625 self.go_to_diagnostic_impl(Direction::Prev, cx)
9626 }
9627
9628 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9629 let buffer = self.buffer.read(cx).snapshot(cx);
9630 let selection = self.selections.newest::<usize>(cx);
9631
9632 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9633 if direction == Direction::Next {
9634 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9635 let (group_id, jump_to) = popover.activation_info();
9636 if self.activate_diagnostics(group_id, cx) {
9637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9638 let mut new_selection = s.newest_anchor().clone();
9639 new_selection.collapse_to(jump_to, SelectionGoal::None);
9640 s.select_anchors(vec![new_selection.clone()]);
9641 });
9642 }
9643 return;
9644 }
9645 }
9646
9647 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9648 active_diagnostics
9649 .primary_range
9650 .to_offset(&buffer)
9651 .to_inclusive()
9652 });
9653 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9654 if active_primary_range.contains(&selection.head()) {
9655 *active_primary_range.start()
9656 } else {
9657 selection.head()
9658 }
9659 } else {
9660 selection.head()
9661 };
9662 let snapshot = self.snapshot(cx);
9663 loop {
9664 let diagnostics = if direction == Direction::Prev {
9665 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9666 } else {
9667 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9668 }
9669 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9670 let group = diagnostics
9671 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9672 // be sorted in a stable way
9673 // skip until we are at current active diagnostic, if it exists
9674 .skip_while(|entry| {
9675 (match direction {
9676 Direction::Prev => entry.range.start >= search_start,
9677 Direction::Next => entry.range.start <= search_start,
9678 }) && self
9679 .active_diagnostics
9680 .as_ref()
9681 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9682 })
9683 .find_map(|entry| {
9684 if entry.diagnostic.is_primary
9685 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9686 && !entry.range.is_empty()
9687 // if we match with the active diagnostic, skip it
9688 && Some(entry.diagnostic.group_id)
9689 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9690 {
9691 Some((entry.range, entry.diagnostic.group_id))
9692 } else {
9693 None
9694 }
9695 });
9696
9697 if let Some((primary_range, group_id)) = group {
9698 if self.activate_diagnostics(group_id, cx) {
9699 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9700 s.select(vec![Selection {
9701 id: selection.id,
9702 start: primary_range.start,
9703 end: primary_range.start,
9704 reversed: false,
9705 goal: SelectionGoal::None,
9706 }]);
9707 });
9708 }
9709 break;
9710 } else {
9711 // Cycle around to the start of the buffer, potentially moving back to the start of
9712 // the currently active diagnostic.
9713 active_primary_range.take();
9714 if direction == Direction::Prev {
9715 if search_start == buffer.len() {
9716 break;
9717 } else {
9718 search_start = buffer.len();
9719 }
9720 } else if search_start == 0 {
9721 break;
9722 } else {
9723 search_start = 0;
9724 }
9725 }
9726 }
9727 }
9728
9729 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9730 let snapshot = self
9731 .display_map
9732 .update(cx, |display_map, cx| display_map.snapshot(cx));
9733 let selection = self.selections.newest::<Point>(cx);
9734 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9735 }
9736
9737 fn go_to_hunk_after_position(
9738 &mut self,
9739 snapshot: &DisplaySnapshot,
9740 position: Point,
9741 cx: &mut ViewContext<'_, Editor>,
9742 ) -> Option<MultiBufferDiffHunk> {
9743 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9744 snapshot,
9745 position,
9746 false,
9747 snapshot
9748 .buffer_snapshot
9749 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9750 cx,
9751 ) {
9752 return Some(hunk);
9753 }
9754
9755 let wrapped_point = Point::zero();
9756 self.go_to_next_hunk_in_direction(
9757 snapshot,
9758 wrapped_point,
9759 true,
9760 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9761 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9762 ),
9763 cx,
9764 )
9765 }
9766
9767 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9768 let snapshot = self
9769 .display_map
9770 .update(cx, |display_map, cx| display_map.snapshot(cx));
9771 let selection = self.selections.newest::<Point>(cx);
9772
9773 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9774 }
9775
9776 fn go_to_hunk_before_position(
9777 &mut self,
9778 snapshot: &DisplaySnapshot,
9779 position: Point,
9780 cx: &mut ViewContext<'_, Editor>,
9781 ) -> Option<MultiBufferDiffHunk> {
9782 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9783 snapshot,
9784 position,
9785 false,
9786 snapshot
9787 .buffer_snapshot
9788 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9789 cx,
9790 ) {
9791 return Some(hunk);
9792 }
9793
9794 let wrapped_point = snapshot.buffer_snapshot.max_point();
9795 self.go_to_next_hunk_in_direction(
9796 snapshot,
9797 wrapped_point,
9798 true,
9799 snapshot
9800 .buffer_snapshot
9801 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9802 cx,
9803 )
9804 }
9805
9806 fn go_to_next_hunk_in_direction(
9807 &mut self,
9808 snapshot: &DisplaySnapshot,
9809 initial_point: Point,
9810 is_wrapped: bool,
9811 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9812 cx: &mut ViewContext<Editor>,
9813 ) -> Option<MultiBufferDiffHunk> {
9814 let display_point = initial_point.to_display_point(snapshot);
9815 let mut hunks = hunks
9816 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9817 .filter(|(display_hunk, _)| {
9818 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9819 })
9820 .dedup();
9821
9822 if let Some((display_hunk, hunk)) = hunks.next() {
9823 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9824 let row = display_hunk.start_display_row();
9825 let point = DisplayPoint::new(row, 0);
9826 s.select_display_ranges([point..point]);
9827 });
9828
9829 Some(hunk)
9830 } else {
9831 None
9832 }
9833 }
9834
9835 pub fn go_to_definition(
9836 &mut self,
9837 _: &GoToDefinition,
9838 cx: &mut ViewContext<Self>,
9839 ) -> Task<Result<Navigated>> {
9840 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9841 cx.spawn(|editor, mut cx| async move {
9842 if definition.await? == Navigated::Yes {
9843 return Ok(Navigated::Yes);
9844 }
9845 match editor.update(&mut cx, |editor, cx| {
9846 editor.find_all_references(&FindAllReferences, cx)
9847 })? {
9848 Some(references) => references.await,
9849 None => Ok(Navigated::No),
9850 }
9851 })
9852 }
9853
9854 pub fn go_to_declaration(
9855 &mut self,
9856 _: &GoToDeclaration,
9857 cx: &mut ViewContext<Self>,
9858 ) -> Task<Result<Navigated>> {
9859 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9860 }
9861
9862 pub fn go_to_declaration_split(
9863 &mut self,
9864 _: &GoToDeclaration,
9865 cx: &mut ViewContext<Self>,
9866 ) -> Task<Result<Navigated>> {
9867 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9868 }
9869
9870 pub fn go_to_implementation(
9871 &mut self,
9872 _: &GoToImplementation,
9873 cx: &mut ViewContext<Self>,
9874 ) -> Task<Result<Navigated>> {
9875 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9876 }
9877
9878 pub fn go_to_implementation_split(
9879 &mut self,
9880 _: &GoToImplementationSplit,
9881 cx: &mut ViewContext<Self>,
9882 ) -> Task<Result<Navigated>> {
9883 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9884 }
9885
9886 pub fn go_to_type_definition(
9887 &mut self,
9888 _: &GoToTypeDefinition,
9889 cx: &mut ViewContext<Self>,
9890 ) -> Task<Result<Navigated>> {
9891 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9892 }
9893
9894 pub fn go_to_definition_split(
9895 &mut self,
9896 _: &GoToDefinitionSplit,
9897 cx: &mut ViewContext<Self>,
9898 ) -> Task<Result<Navigated>> {
9899 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9900 }
9901
9902 pub fn go_to_type_definition_split(
9903 &mut self,
9904 _: &GoToTypeDefinitionSplit,
9905 cx: &mut ViewContext<Self>,
9906 ) -> Task<Result<Navigated>> {
9907 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9908 }
9909
9910 fn go_to_definition_of_kind(
9911 &mut self,
9912 kind: GotoDefinitionKind,
9913 split: bool,
9914 cx: &mut ViewContext<Self>,
9915 ) -> Task<Result<Navigated>> {
9916 let Some(provider) = self.semantics_provider.clone() else {
9917 return Task::ready(Ok(Navigated::No));
9918 };
9919 let head = self.selections.newest::<usize>(cx).head();
9920 let buffer = self.buffer.read(cx);
9921 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9922 text_anchor
9923 } else {
9924 return Task::ready(Ok(Navigated::No));
9925 };
9926
9927 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9928 return Task::ready(Ok(Navigated::No));
9929 };
9930
9931 cx.spawn(|editor, mut cx| async move {
9932 let definitions = definitions.await?;
9933 let navigated = editor
9934 .update(&mut cx, |editor, cx| {
9935 editor.navigate_to_hover_links(
9936 Some(kind),
9937 definitions
9938 .into_iter()
9939 .filter(|location| {
9940 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9941 })
9942 .map(HoverLink::Text)
9943 .collect::<Vec<_>>(),
9944 split,
9945 cx,
9946 )
9947 })?
9948 .await?;
9949 anyhow::Ok(navigated)
9950 })
9951 }
9952
9953 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9954 let position = self.selections.newest_anchor().head();
9955 let Some((buffer, buffer_position)) =
9956 self.buffer.read(cx).text_anchor_for_position(position, cx)
9957 else {
9958 return;
9959 };
9960
9961 cx.spawn(|editor, mut cx| async move {
9962 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9963 editor.update(&mut cx, |_, cx| {
9964 cx.open_url(&url);
9965 })
9966 } else {
9967 Ok(())
9968 }
9969 })
9970 .detach();
9971 }
9972
9973 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9974 let Some(workspace) = self.workspace() else {
9975 return;
9976 };
9977
9978 let position = self.selections.newest_anchor().head();
9979
9980 let Some((buffer, buffer_position)) =
9981 self.buffer.read(cx).text_anchor_for_position(position, cx)
9982 else {
9983 return;
9984 };
9985
9986 let project = self.project.clone();
9987
9988 cx.spawn(|_, mut cx| async move {
9989 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9990
9991 if let Some((_, path)) = result {
9992 workspace
9993 .update(&mut cx, |workspace, cx| {
9994 workspace.open_resolved_path(path, cx)
9995 })?
9996 .await?;
9997 }
9998 anyhow::Ok(())
9999 })
10000 .detach();
10001 }
10002
10003 pub(crate) fn navigate_to_hover_links(
10004 &mut self,
10005 kind: Option<GotoDefinitionKind>,
10006 mut definitions: Vec<HoverLink>,
10007 split: bool,
10008 cx: &mut ViewContext<Editor>,
10009 ) -> Task<Result<Navigated>> {
10010 // If there is one definition, just open it directly
10011 if definitions.len() == 1 {
10012 let definition = definitions.pop().unwrap();
10013
10014 enum TargetTaskResult {
10015 Location(Option<Location>),
10016 AlreadyNavigated,
10017 }
10018
10019 let target_task = match definition {
10020 HoverLink::Text(link) => {
10021 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10022 }
10023 HoverLink::InlayHint(lsp_location, server_id) => {
10024 let computation = self.compute_target_location(lsp_location, server_id, cx);
10025 cx.background_executor().spawn(async move {
10026 let location = computation.await?;
10027 Ok(TargetTaskResult::Location(location))
10028 })
10029 }
10030 HoverLink::Url(url) => {
10031 cx.open_url(&url);
10032 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10033 }
10034 HoverLink::File(path) => {
10035 if let Some(workspace) = self.workspace() {
10036 cx.spawn(|_, mut cx| async move {
10037 workspace
10038 .update(&mut cx, |workspace, cx| {
10039 workspace.open_resolved_path(path, cx)
10040 })?
10041 .await
10042 .map(|_| TargetTaskResult::AlreadyNavigated)
10043 })
10044 } else {
10045 Task::ready(Ok(TargetTaskResult::Location(None)))
10046 }
10047 }
10048 };
10049 cx.spawn(|editor, mut cx| async move {
10050 let target = match target_task.await.context("target resolution task")? {
10051 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10052 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10053 TargetTaskResult::Location(Some(target)) => target,
10054 };
10055
10056 editor.update(&mut cx, |editor, cx| {
10057 let Some(workspace) = editor.workspace() else {
10058 return Navigated::No;
10059 };
10060 let pane = workspace.read(cx).active_pane().clone();
10061
10062 let range = target.range.to_offset(target.buffer.read(cx));
10063 let range = editor.range_for_match(&range);
10064
10065 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10066 let buffer = target.buffer.read(cx);
10067 let range = check_multiline_range(buffer, range);
10068 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10069 s.select_ranges([range]);
10070 });
10071 } else {
10072 cx.window_context().defer(move |cx| {
10073 let target_editor: View<Self> =
10074 workspace.update(cx, |workspace, cx| {
10075 let pane = if split {
10076 workspace.adjacent_pane(cx)
10077 } else {
10078 workspace.active_pane().clone()
10079 };
10080
10081 workspace.open_project_item(
10082 pane,
10083 target.buffer.clone(),
10084 true,
10085 true,
10086 cx,
10087 )
10088 });
10089 target_editor.update(cx, |target_editor, cx| {
10090 // When selecting a definition in a different buffer, disable the nav history
10091 // to avoid creating a history entry at the previous cursor location.
10092 pane.update(cx, |pane, _| pane.disable_history());
10093 let buffer = target.buffer.read(cx);
10094 let range = check_multiline_range(buffer, range);
10095 target_editor.change_selections(
10096 Some(Autoscroll::focused()),
10097 cx,
10098 |s| {
10099 s.select_ranges([range]);
10100 },
10101 );
10102 pane.update(cx, |pane, _| pane.enable_history());
10103 });
10104 });
10105 }
10106 Navigated::Yes
10107 })
10108 })
10109 } else if !definitions.is_empty() {
10110 cx.spawn(|editor, mut cx| async move {
10111 let (title, location_tasks, workspace) = editor
10112 .update(&mut cx, |editor, cx| {
10113 let tab_kind = match kind {
10114 Some(GotoDefinitionKind::Implementation) => "Implementations",
10115 _ => "Definitions",
10116 };
10117 let title = definitions
10118 .iter()
10119 .find_map(|definition| match definition {
10120 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10121 let buffer = origin.buffer.read(cx);
10122 format!(
10123 "{} for {}",
10124 tab_kind,
10125 buffer
10126 .text_for_range(origin.range.clone())
10127 .collect::<String>()
10128 )
10129 }),
10130 HoverLink::InlayHint(_, _) => None,
10131 HoverLink::Url(_) => None,
10132 HoverLink::File(_) => None,
10133 })
10134 .unwrap_or(tab_kind.to_string());
10135 let location_tasks = definitions
10136 .into_iter()
10137 .map(|definition| match definition {
10138 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10139 HoverLink::InlayHint(lsp_location, server_id) => {
10140 editor.compute_target_location(lsp_location, server_id, cx)
10141 }
10142 HoverLink::Url(_) => Task::ready(Ok(None)),
10143 HoverLink::File(_) => Task::ready(Ok(None)),
10144 })
10145 .collect::<Vec<_>>();
10146 (title, location_tasks, editor.workspace().clone())
10147 })
10148 .context("location tasks preparation")?;
10149
10150 let locations = future::join_all(location_tasks)
10151 .await
10152 .into_iter()
10153 .filter_map(|location| location.transpose())
10154 .collect::<Result<_>>()
10155 .context("location tasks")?;
10156
10157 let Some(workspace) = workspace else {
10158 return Ok(Navigated::No);
10159 };
10160 let opened = workspace
10161 .update(&mut cx, |workspace, cx| {
10162 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10163 })
10164 .ok();
10165
10166 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10167 })
10168 } else {
10169 Task::ready(Ok(Navigated::No))
10170 }
10171 }
10172
10173 fn compute_target_location(
10174 &self,
10175 lsp_location: lsp::Location,
10176 server_id: LanguageServerId,
10177 cx: &mut ViewContext<Self>,
10178 ) -> Task<anyhow::Result<Option<Location>>> {
10179 let Some(project) = self.project.clone() else {
10180 return Task::Ready(Some(Ok(None)));
10181 };
10182
10183 cx.spawn(move |editor, mut cx| async move {
10184 let location_task = editor.update(&mut cx, |_, cx| {
10185 project.update(cx, |project, cx| {
10186 let language_server_name = project
10187 .language_server_statuses(cx)
10188 .find(|(id, _)| server_id == *id)
10189 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10190 language_server_name.map(|language_server_name| {
10191 project.open_local_buffer_via_lsp(
10192 lsp_location.uri.clone(),
10193 server_id,
10194 language_server_name,
10195 cx,
10196 )
10197 })
10198 })
10199 })?;
10200 let location = match location_task {
10201 Some(task) => Some({
10202 let target_buffer_handle = task.await.context("open local buffer")?;
10203 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10204 let target_start = target_buffer
10205 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10206 let target_end = target_buffer
10207 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10208 target_buffer.anchor_after(target_start)
10209 ..target_buffer.anchor_before(target_end)
10210 })?;
10211 Location {
10212 buffer: target_buffer_handle,
10213 range,
10214 }
10215 }),
10216 None => None,
10217 };
10218 Ok(location)
10219 })
10220 }
10221
10222 pub fn find_all_references(
10223 &mut self,
10224 _: &FindAllReferences,
10225 cx: &mut ViewContext<Self>,
10226 ) -> Option<Task<Result<Navigated>>> {
10227 let selection = self.selections.newest::<usize>(cx);
10228 let multi_buffer = self.buffer.read(cx);
10229 let head = selection.head();
10230
10231 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10232 let head_anchor = multi_buffer_snapshot.anchor_at(
10233 head,
10234 if head < selection.tail() {
10235 Bias::Right
10236 } else {
10237 Bias::Left
10238 },
10239 );
10240
10241 match self
10242 .find_all_references_task_sources
10243 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10244 {
10245 Ok(_) => {
10246 log::info!(
10247 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10248 );
10249 return None;
10250 }
10251 Err(i) => {
10252 self.find_all_references_task_sources.insert(i, head_anchor);
10253 }
10254 }
10255
10256 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10257 let workspace = self.workspace()?;
10258 let project = workspace.read(cx).project().clone();
10259 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10260 Some(cx.spawn(|editor, mut cx| async move {
10261 let _cleanup = defer({
10262 let mut cx = cx.clone();
10263 move || {
10264 let _ = editor.update(&mut cx, |editor, _| {
10265 if let Ok(i) =
10266 editor
10267 .find_all_references_task_sources
10268 .binary_search_by(|anchor| {
10269 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10270 })
10271 {
10272 editor.find_all_references_task_sources.remove(i);
10273 }
10274 });
10275 }
10276 });
10277
10278 let locations = references.await?;
10279 if locations.is_empty() {
10280 return anyhow::Ok(Navigated::No);
10281 }
10282
10283 workspace.update(&mut cx, |workspace, cx| {
10284 let title = locations
10285 .first()
10286 .as_ref()
10287 .map(|location| {
10288 let buffer = location.buffer.read(cx);
10289 format!(
10290 "References to `{}`",
10291 buffer
10292 .text_for_range(location.range.clone())
10293 .collect::<String>()
10294 )
10295 })
10296 .unwrap();
10297 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10298 Navigated::Yes
10299 })
10300 }))
10301 }
10302
10303 /// Opens a multibuffer with the given project locations in it
10304 pub fn open_locations_in_multibuffer(
10305 workspace: &mut Workspace,
10306 mut locations: Vec<Location>,
10307 title: String,
10308 split: bool,
10309 cx: &mut ViewContext<Workspace>,
10310 ) {
10311 // If there are multiple definitions, open them in a multibuffer
10312 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10313 let mut locations = locations.into_iter().peekable();
10314 let mut ranges_to_highlight = Vec::new();
10315 let capability = workspace.project().read(cx).capability();
10316
10317 let excerpt_buffer = cx.new_model(|cx| {
10318 let mut multibuffer = MultiBuffer::new(capability);
10319 while let Some(location) = locations.next() {
10320 let buffer = location.buffer.read(cx);
10321 let mut ranges_for_buffer = Vec::new();
10322 let range = location.range.to_offset(buffer);
10323 ranges_for_buffer.push(range.clone());
10324
10325 while let Some(next_location) = locations.peek() {
10326 if next_location.buffer == location.buffer {
10327 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10328 locations.next();
10329 } else {
10330 break;
10331 }
10332 }
10333
10334 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10335 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10336 location.buffer.clone(),
10337 ranges_for_buffer,
10338 DEFAULT_MULTIBUFFER_CONTEXT,
10339 cx,
10340 ))
10341 }
10342
10343 multibuffer.with_title(title)
10344 });
10345
10346 let editor = cx.new_view(|cx| {
10347 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10348 });
10349 editor.update(cx, |editor, cx| {
10350 if let Some(first_range) = ranges_to_highlight.first() {
10351 editor.change_selections(None, cx, |selections| {
10352 selections.clear_disjoint();
10353 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10354 });
10355 }
10356 editor.highlight_background::<Self>(
10357 &ranges_to_highlight,
10358 |theme| theme.editor_highlighted_line_background,
10359 cx,
10360 );
10361 });
10362
10363 let item = Box::new(editor);
10364 let item_id = item.item_id();
10365
10366 if split {
10367 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10368 } else {
10369 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10370 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10371 pane.close_current_preview_item(cx)
10372 } else {
10373 None
10374 }
10375 });
10376 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10377 }
10378 workspace.active_pane().update(cx, |pane, cx| {
10379 pane.set_preview_item_id(Some(item_id), cx);
10380 });
10381 }
10382
10383 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10384 use language::ToOffset as _;
10385
10386 let provider = self.semantics_provider.clone()?;
10387 let selection = self.selections.newest_anchor().clone();
10388 let (cursor_buffer, cursor_buffer_position) = self
10389 .buffer
10390 .read(cx)
10391 .text_anchor_for_position(selection.head(), cx)?;
10392 let (tail_buffer, cursor_buffer_position_end) = self
10393 .buffer
10394 .read(cx)
10395 .text_anchor_for_position(selection.tail(), cx)?;
10396 if tail_buffer != cursor_buffer {
10397 return None;
10398 }
10399
10400 let snapshot = cursor_buffer.read(cx).snapshot();
10401 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10402 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10403 let prepare_rename = provider
10404 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10405 .unwrap_or_else(|| Task::ready(Ok(None)));
10406 drop(snapshot);
10407
10408 Some(cx.spawn(|this, mut cx| async move {
10409 let rename_range = if let Some(range) = prepare_rename.await? {
10410 Some(range)
10411 } else {
10412 this.update(&mut cx, |this, cx| {
10413 let buffer = this.buffer.read(cx).snapshot(cx);
10414 let mut buffer_highlights = this
10415 .document_highlights_for_position(selection.head(), &buffer)
10416 .filter(|highlight| {
10417 highlight.start.excerpt_id == selection.head().excerpt_id
10418 && highlight.end.excerpt_id == selection.head().excerpt_id
10419 });
10420 buffer_highlights
10421 .next()
10422 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10423 })?
10424 };
10425 if let Some(rename_range) = rename_range {
10426 this.update(&mut cx, |this, cx| {
10427 let snapshot = cursor_buffer.read(cx).snapshot();
10428 let rename_buffer_range = rename_range.to_offset(&snapshot);
10429 let cursor_offset_in_rename_range =
10430 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10431 let cursor_offset_in_rename_range_end =
10432 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10433
10434 this.take_rename(false, cx);
10435 let buffer = this.buffer.read(cx).read(cx);
10436 let cursor_offset = selection.head().to_offset(&buffer);
10437 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10438 let rename_end = rename_start + rename_buffer_range.len();
10439 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10440 let mut old_highlight_id = None;
10441 let old_name: Arc<str> = buffer
10442 .chunks(rename_start..rename_end, true)
10443 .map(|chunk| {
10444 if old_highlight_id.is_none() {
10445 old_highlight_id = chunk.syntax_highlight_id;
10446 }
10447 chunk.text
10448 })
10449 .collect::<String>()
10450 .into();
10451
10452 drop(buffer);
10453
10454 // Position the selection in the rename editor so that it matches the current selection.
10455 this.show_local_selections = false;
10456 let rename_editor = cx.new_view(|cx| {
10457 let mut editor = Editor::single_line(cx);
10458 editor.buffer.update(cx, |buffer, cx| {
10459 buffer.edit([(0..0, old_name.clone())], None, cx)
10460 });
10461 let rename_selection_range = match cursor_offset_in_rename_range
10462 .cmp(&cursor_offset_in_rename_range_end)
10463 {
10464 Ordering::Equal => {
10465 editor.select_all(&SelectAll, cx);
10466 return editor;
10467 }
10468 Ordering::Less => {
10469 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10470 }
10471 Ordering::Greater => {
10472 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10473 }
10474 };
10475 if rename_selection_range.end > old_name.len() {
10476 editor.select_all(&SelectAll, cx);
10477 } else {
10478 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10479 s.select_ranges([rename_selection_range]);
10480 });
10481 }
10482 editor
10483 });
10484 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10485 if e == &EditorEvent::Focused {
10486 cx.emit(EditorEvent::FocusedIn)
10487 }
10488 })
10489 .detach();
10490
10491 let write_highlights =
10492 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10493 let read_highlights =
10494 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10495 let ranges = write_highlights
10496 .iter()
10497 .flat_map(|(_, ranges)| ranges.iter())
10498 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10499 .cloned()
10500 .collect();
10501
10502 this.highlight_text::<Rename>(
10503 ranges,
10504 HighlightStyle {
10505 fade_out: Some(0.6),
10506 ..Default::default()
10507 },
10508 cx,
10509 );
10510 let rename_focus_handle = rename_editor.focus_handle(cx);
10511 cx.focus(&rename_focus_handle);
10512 let block_id = this.insert_blocks(
10513 [BlockProperties {
10514 style: BlockStyle::Flex,
10515 placement: BlockPlacement::Below(range.start),
10516 height: 1,
10517 render: Arc::new({
10518 let rename_editor = rename_editor.clone();
10519 move |cx: &mut BlockContext| {
10520 let mut text_style = cx.editor_style.text.clone();
10521 if let Some(highlight_style) = old_highlight_id
10522 .and_then(|h| h.style(&cx.editor_style.syntax))
10523 {
10524 text_style = text_style.highlight(highlight_style);
10525 }
10526 div()
10527 .block_mouse_down()
10528 .pl(cx.anchor_x)
10529 .child(EditorElement::new(
10530 &rename_editor,
10531 EditorStyle {
10532 background: cx.theme().system().transparent,
10533 local_player: cx.editor_style.local_player,
10534 text: text_style,
10535 scrollbar_width: cx.editor_style.scrollbar_width,
10536 syntax: cx.editor_style.syntax.clone(),
10537 status: cx.editor_style.status.clone(),
10538 inlay_hints_style: HighlightStyle {
10539 font_weight: Some(FontWeight::BOLD),
10540 ..make_inlay_hints_style(cx)
10541 },
10542 suggestions_style: HighlightStyle {
10543 color: Some(cx.theme().status().predictive),
10544 ..HighlightStyle::default()
10545 },
10546 ..EditorStyle::default()
10547 },
10548 ))
10549 .into_any_element()
10550 }
10551 }),
10552 priority: 0,
10553 }],
10554 Some(Autoscroll::fit()),
10555 cx,
10556 )[0];
10557 this.pending_rename = Some(RenameState {
10558 range,
10559 old_name,
10560 editor: rename_editor,
10561 block_id,
10562 });
10563 })?;
10564 }
10565
10566 Ok(())
10567 }))
10568 }
10569
10570 pub fn confirm_rename(
10571 &mut self,
10572 _: &ConfirmRename,
10573 cx: &mut ViewContext<Self>,
10574 ) -> Option<Task<Result<()>>> {
10575 let rename = self.take_rename(false, cx)?;
10576 let workspace = self.workspace()?.downgrade();
10577 let (buffer, start) = self
10578 .buffer
10579 .read(cx)
10580 .text_anchor_for_position(rename.range.start, cx)?;
10581 let (end_buffer, _) = self
10582 .buffer
10583 .read(cx)
10584 .text_anchor_for_position(rename.range.end, cx)?;
10585 if buffer != end_buffer {
10586 return None;
10587 }
10588
10589 let old_name = rename.old_name;
10590 let new_name = rename.editor.read(cx).text(cx);
10591
10592 let rename = self.semantics_provider.as_ref()?.perform_rename(
10593 &buffer,
10594 start,
10595 new_name.clone(),
10596 cx,
10597 )?;
10598
10599 Some(cx.spawn(|editor, mut cx| async move {
10600 let project_transaction = rename.await?;
10601 Self::open_project_transaction(
10602 &editor,
10603 workspace,
10604 project_transaction,
10605 format!("Rename: {} → {}", old_name, new_name),
10606 cx.clone(),
10607 )
10608 .await?;
10609
10610 editor.update(&mut cx, |editor, cx| {
10611 editor.refresh_document_highlights(cx);
10612 })?;
10613 Ok(())
10614 }))
10615 }
10616
10617 fn take_rename(
10618 &mut self,
10619 moving_cursor: bool,
10620 cx: &mut ViewContext<Self>,
10621 ) -> Option<RenameState> {
10622 let rename = self.pending_rename.take()?;
10623 if rename.editor.focus_handle(cx).is_focused(cx) {
10624 cx.focus(&self.focus_handle);
10625 }
10626
10627 self.remove_blocks(
10628 [rename.block_id].into_iter().collect(),
10629 Some(Autoscroll::fit()),
10630 cx,
10631 );
10632 self.clear_highlights::<Rename>(cx);
10633 self.show_local_selections = true;
10634
10635 if moving_cursor {
10636 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10637 editor.selections.newest::<usize>(cx).head()
10638 });
10639
10640 // Update the selection to match the position of the selection inside
10641 // the rename editor.
10642 let snapshot = self.buffer.read(cx).read(cx);
10643 let rename_range = rename.range.to_offset(&snapshot);
10644 let cursor_in_editor = snapshot
10645 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10646 .min(rename_range.end);
10647 drop(snapshot);
10648
10649 self.change_selections(None, cx, |s| {
10650 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10651 });
10652 } else {
10653 self.refresh_document_highlights(cx);
10654 }
10655
10656 Some(rename)
10657 }
10658
10659 pub fn pending_rename(&self) -> Option<&RenameState> {
10660 self.pending_rename.as_ref()
10661 }
10662
10663 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10664 let project = match &self.project {
10665 Some(project) => project.clone(),
10666 None => return None,
10667 };
10668
10669 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10670 }
10671
10672 fn format_selections(
10673 &mut self,
10674 _: &FormatSelections,
10675 cx: &mut ViewContext<Self>,
10676 ) -> Option<Task<Result<()>>> {
10677 let project = match &self.project {
10678 Some(project) => project.clone(),
10679 None => return None,
10680 };
10681
10682 let selections = self
10683 .selections
10684 .all_adjusted(cx)
10685 .into_iter()
10686 .filter(|s| !s.is_empty())
10687 .collect_vec();
10688
10689 Some(self.perform_format(
10690 project,
10691 FormatTrigger::Manual,
10692 FormatTarget::Ranges(selections),
10693 cx,
10694 ))
10695 }
10696
10697 fn perform_format(
10698 &mut self,
10699 project: Model<Project>,
10700 trigger: FormatTrigger,
10701 target: FormatTarget,
10702 cx: &mut ViewContext<Self>,
10703 ) -> Task<Result<()>> {
10704 let buffer = self.buffer().clone();
10705 let mut buffers = buffer.read(cx).all_buffers();
10706 if trigger == FormatTrigger::Save {
10707 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10708 }
10709
10710 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10711 let format = project.update(cx, |project, cx| {
10712 project.format(buffers, true, trigger, target, cx)
10713 });
10714
10715 cx.spawn(|_, mut cx| async move {
10716 let transaction = futures::select_biased! {
10717 () = timeout => {
10718 log::warn!("timed out waiting for formatting");
10719 None
10720 }
10721 transaction = format.log_err().fuse() => transaction,
10722 };
10723
10724 buffer
10725 .update(&mut cx, |buffer, cx| {
10726 if let Some(transaction) = transaction {
10727 if !buffer.is_singleton() {
10728 buffer.push_transaction(&transaction.0, cx);
10729 }
10730 }
10731
10732 cx.notify();
10733 })
10734 .ok();
10735
10736 Ok(())
10737 })
10738 }
10739
10740 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10741 if let Some(project) = self.project.clone() {
10742 self.buffer.update(cx, |multi_buffer, cx| {
10743 project.update(cx, |project, cx| {
10744 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10745 });
10746 })
10747 }
10748 }
10749
10750 fn cancel_language_server_work(
10751 &mut self,
10752 _: &actions::CancelLanguageServerWork,
10753 cx: &mut ViewContext<Self>,
10754 ) {
10755 if let Some(project) = self.project.clone() {
10756 self.buffer.update(cx, |multi_buffer, cx| {
10757 project.update(cx, |project, cx| {
10758 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10759 });
10760 })
10761 }
10762 }
10763
10764 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10765 cx.show_character_palette();
10766 }
10767
10768 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10769 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10770 let buffer = self.buffer.read(cx).snapshot(cx);
10771 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10772 let is_valid = buffer
10773 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10774 .any(|entry| {
10775 entry.diagnostic.is_primary
10776 && !entry.range.is_empty()
10777 && entry.range.start == primary_range_start
10778 && entry.diagnostic.message == active_diagnostics.primary_message
10779 });
10780
10781 if is_valid != active_diagnostics.is_valid {
10782 active_diagnostics.is_valid = is_valid;
10783 let mut new_styles = HashMap::default();
10784 for (block_id, diagnostic) in &active_diagnostics.blocks {
10785 new_styles.insert(
10786 *block_id,
10787 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10788 );
10789 }
10790 self.display_map.update(cx, |display_map, _cx| {
10791 display_map.replace_blocks(new_styles)
10792 });
10793 }
10794 }
10795 }
10796
10797 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10798 self.dismiss_diagnostics(cx);
10799 let snapshot = self.snapshot(cx);
10800 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10801 let buffer = self.buffer.read(cx).snapshot(cx);
10802
10803 let mut primary_range = None;
10804 let mut primary_message = None;
10805 let mut group_end = Point::zero();
10806 let diagnostic_group = buffer
10807 .diagnostic_group::<MultiBufferPoint>(group_id)
10808 .filter_map(|entry| {
10809 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10810 && (entry.range.start.row == entry.range.end.row
10811 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10812 {
10813 return None;
10814 }
10815 if entry.range.end > group_end {
10816 group_end = entry.range.end;
10817 }
10818 if entry.diagnostic.is_primary {
10819 primary_range = Some(entry.range.clone());
10820 primary_message = Some(entry.diagnostic.message.clone());
10821 }
10822 Some(entry)
10823 })
10824 .collect::<Vec<_>>();
10825 let primary_range = primary_range?;
10826 let primary_message = primary_message?;
10827 let primary_range =
10828 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10829
10830 let blocks = display_map
10831 .insert_blocks(
10832 diagnostic_group.iter().map(|entry| {
10833 let diagnostic = entry.diagnostic.clone();
10834 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10835 BlockProperties {
10836 style: BlockStyle::Fixed,
10837 placement: BlockPlacement::Below(
10838 buffer.anchor_after(entry.range.start),
10839 ),
10840 height: message_height,
10841 render: diagnostic_block_renderer(diagnostic, None, true, true),
10842 priority: 0,
10843 }
10844 }),
10845 cx,
10846 )
10847 .into_iter()
10848 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10849 .collect();
10850
10851 Some(ActiveDiagnosticGroup {
10852 primary_range,
10853 primary_message,
10854 group_id,
10855 blocks,
10856 is_valid: true,
10857 })
10858 });
10859 self.active_diagnostics.is_some()
10860 }
10861
10862 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10863 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10864 self.display_map.update(cx, |display_map, cx| {
10865 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10866 });
10867 cx.notify();
10868 }
10869 }
10870
10871 pub fn set_selections_from_remote(
10872 &mut self,
10873 selections: Vec<Selection<Anchor>>,
10874 pending_selection: Option<Selection<Anchor>>,
10875 cx: &mut ViewContext<Self>,
10876 ) {
10877 let old_cursor_position = self.selections.newest_anchor().head();
10878 self.selections.change_with(cx, |s| {
10879 s.select_anchors(selections);
10880 if let Some(pending_selection) = pending_selection {
10881 s.set_pending(pending_selection, SelectMode::Character);
10882 } else {
10883 s.clear_pending();
10884 }
10885 });
10886 self.selections_did_change(false, &old_cursor_position, true, cx);
10887 }
10888
10889 fn push_to_selection_history(&mut self) {
10890 self.selection_history.push(SelectionHistoryEntry {
10891 selections: self.selections.disjoint_anchors(),
10892 select_next_state: self.select_next_state.clone(),
10893 select_prev_state: self.select_prev_state.clone(),
10894 add_selections_state: self.add_selections_state.clone(),
10895 });
10896 }
10897
10898 pub fn transact(
10899 &mut self,
10900 cx: &mut ViewContext<Self>,
10901 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10902 ) -> Option<TransactionId> {
10903 self.start_transaction_at(Instant::now(), cx);
10904 update(self, cx);
10905 self.end_transaction_at(Instant::now(), cx)
10906 }
10907
10908 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10909 self.end_selection(cx);
10910 if let Some(tx_id) = self
10911 .buffer
10912 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10913 {
10914 self.selection_history
10915 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10916 cx.emit(EditorEvent::TransactionBegun {
10917 transaction_id: tx_id,
10918 })
10919 }
10920 }
10921
10922 fn end_transaction_at(
10923 &mut self,
10924 now: Instant,
10925 cx: &mut ViewContext<Self>,
10926 ) -> Option<TransactionId> {
10927 if let Some(transaction_id) = self
10928 .buffer
10929 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10930 {
10931 if let Some((_, end_selections)) =
10932 self.selection_history.transaction_mut(transaction_id)
10933 {
10934 *end_selections = Some(self.selections.disjoint_anchors());
10935 } else {
10936 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10937 }
10938
10939 cx.emit(EditorEvent::Edited { transaction_id });
10940 Some(transaction_id)
10941 } else {
10942 None
10943 }
10944 }
10945
10946 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10947 let selection = self.selections.newest::<Point>(cx);
10948
10949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10950 let range = if selection.is_empty() {
10951 let point = selection.head().to_display_point(&display_map);
10952 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10953 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10954 .to_point(&display_map);
10955 start..end
10956 } else {
10957 selection.range()
10958 };
10959 if display_map.folds_in_range(range).next().is_some() {
10960 self.unfold_lines(&Default::default(), cx)
10961 } else {
10962 self.fold(&Default::default(), cx)
10963 }
10964 }
10965
10966 pub fn toggle_fold_recursive(
10967 &mut self,
10968 _: &actions::ToggleFoldRecursive,
10969 cx: &mut ViewContext<Self>,
10970 ) {
10971 let selection = self.selections.newest::<Point>(cx);
10972
10973 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10974 let range = if selection.is_empty() {
10975 let point = selection.head().to_display_point(&display_map);
10976 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10977 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10978 .to_point(&display_map);
10979 start..end
10980 } else {
10981 selection.range()
10982 };
10983 if display_map.folds_in_range(range).next().is_some() {
10984 self.unfold_recursive(&Default::default(), cx)
10985 } else {
10986 self.fold_recursive(&Default::default(), cx)
10987 }
10988 }
10989
10990 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10991 let mut to_fold = Vec::new();
10992 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10993 let selections = self.selections.all_adjusted(cx);
10994
10995 for selection in selections {
10996 let range = selection.range().sorted();
10997 let buffer_start_row = range.start.row;
10998
10999 if range.start.row != range.end.row {
11000 let mut found = false;
11001 let mut row = range.start.row;
11002 while row <= range.end.row {
11003 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11004 found = true;
11005 row = crease.range().end.row + 1;
11006 to_fold.push(crease);
11007 } else {
11008 row += 1
11009 }
11010 }
11011 if found {
11012 continue;
11013 }
11014 }
11015
11016 for row in (0..=range.start.row).rev() {
11017 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11018 if crease.range().end.row >= buffer_start_row {
11019 to_fold.push(crease);
11020 if row <= range.start.row {
11021 break;
11022 }
11023 }
11024 }
11025 }
11026 }
11027
11028 self.fold_creases(to_fold, true, cx);
11029 }
11030
11031 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11032 let fold_at_level = fold_at.level;
11033 let snapshot = self.buffer.read(cx).snapshot(cx);
11034 let mut to_fold = Vec::new();
11035 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11036
11037 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11038 while start_row < end_row {
11039 match self
11040 .snapshot(cx)
11041 .crease_for_buffer_row(MultiBufferRow(start_row))
11042 {
11043 Some(crease) => {
11044 let nested_start_row = crease.range().start.row + 1;
11045 let nested_end_row = crease.range().end.row;
11046
11047 if current_level < fold_at_level {
11048 stack.push((nested_start_row, nested_end_row, current_level + 1));
11049 } else if current_level == fold_at_level {
11050 to_fold.push(crease);
11051 }
11052
11053 start_row = nested_end_row + 1;
11054 }
11055 None => start_row += 1,
11056 }
11057 }
11058 }
11059
11060 self.fold_creases(to_fold, true, cx);
11061 }
11062
11063 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11064 let mut fold_ranges = Vec::new();
11065 let snapshot = self.buffer.read(cx).snapshot(cx);
11066
11067 for row in 0..snapshot.max_buffer_row().0 {
11068 if let Some(foldable_range) =
11069 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11070 {
11071 fold_ranges.push(foldable_range);
11072 }
11073 }
11074
11075 self.fold_creases(fold_ranges, true, cx);
11076 }
11077
11078 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11079 let mut to_fold = Vec::new();
11080 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11081 let selections = self.selections.all_adjusted(cx);
11082
11083 for selection in selections {
11084 let range = selection.range().sorted();
11085 let buffer_start_row = range.start.row;
11086
11087 if range.start.row != range.end.row {
11088 let mut found = false;
11089 for row in range.start.row..=range.end.row {
11090 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11091 found = true;
11092 to_fold.push(crease);
11093 }
11094 }
11095 if found {
11096 continue;
11097 }
11098 }
11099
11100 for row in (0..=range.start.row).rev() {
11101 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11102 if crease.range().end.row >= buffer_start_row {
11103 to_fold.push(crease);
11104 } else {
11105 break;
11106 }
11107 }
11108 }
11109 }
11110
11111 self.fold_creases(to_fold, true, cx);
11112 }
11113
11114 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11115 let buffer_row = fold_at.buffer_row;
11116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11117
11118 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11119 let autoscroll = self
11120 .selections
11121 .all::<Point>(cx)
11122 .iter()
11123 .any(|selection| crease.range().overlaps(&selection.range()));
11124
11125 self.fold_creases(vec![crease], autoscroll, cx);
11126 }
11127 }
11128
11129 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11130 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11131 let buffer = &display_map.buffer_snapshot;
11132 let selections = self.selections.all::<Point>(cx);
11133 let ranges = selections
11134 .iter()
11135 .map(|s| {
11136 let range = s.display_range(&display_map).sorted();
11137 let mut start = range.start.to_point(&display_map);
11138 let mut end = range.end.to_point(&display_map);
11139 start.column = 0;
11140 end.column = buffer.line_len(MultiBufferRow(end.row));
11141 start..end
11142 })
11143 .collect::<Vec<_>>();
11144
11145 self.unfold_ranges(&ranges, true, true, cx);
11146 }
11147
11148 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11149 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11150 let selections = self.selections.all::<Point>(cx);
11151 let ranges = selections
11152 .iter()
11153 .map(|s| {
11154 let mut range = s.display_range(&display_map).sorted();
11155 *range.start.column_mut() = 0;
11156 *range.end.column_mut() = display_map.line_len(range.end.row());
11157 let start = range.start.to_point(&display_map);
11158 let end = range.end.to_point(&display_map);
11159 start..end
11160 })
11161 .collect::<Vec<_>>();
11162
11163 self.unfold_ranges(&ranges, true, true, cx);
11164 }
11165
11166 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11167 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11168
11169 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11170 ..Point::new(
11171 unfold_at.buffer_row.0,
11172 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11173 );
11174
11175 let autoscroll = self
11176 .selections
11177 .all::<Point>(cx)
11178 .iter()
11179 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11180
11181 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11182 }
11183
11184 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11185 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11186 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11187 }
11188
11189 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11190 let selections = self.selections.all::<Point>(cx);
11191 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11192 let line_mode = self.selections.line_mode;
11193 let ranges = selections
11194 .into_iter()
11195 .map(|s| {
11196 if line_mode {
11197 let start = Point::new(s.start.row, 0);
11198 let end = Point::new(
11199 s.end.row,
11200 display_map
11201 .buffer_snapshot
11202 .line_len(MultiBufferRow(s.end.row)),
11203 );
11204 Crease::simple(start..end, display_map.fold_placeholder.clone())
11205 } else {
11206 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11207 }
11208 })
11209 .collect::<Vec<_>>();
11210 self.fold_creases(ranges, true, cx);
11211 }
11212
11213 pub fn fold_creases<T: ToOffset + Clone>(
11214 &mut self,
11215 creases: Vec<Crease<T>>,
11216 auto_scroll: bool,
11217 cx: &mut ViewContext<Self>,
11218 ) {
11219 if creases.is_empty() {
11220 return;
11221 }
11222
11223 let mut buffers_affected = HashMap::default();
11224 let multi_buffer = self.buffer().read(cx);
11225 for crease in &creases {
11226 if let Some((_, buffer, _)) =
11227 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11228 {
11229 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11230 };
11231 }
11232
11233 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11234
11235 if auto_scroll {
11236 self.request_autoscroll(Autoscroll::fit(), cx);
11237 }
11238
11239 for buffer in buffers_affected.into_values() {
11240 self.sync_expanded_diff_hunks(buffer, cx);
11241 }
11242
11243 cx.notify();
11244
11245 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11246 // Clear diagnostics block when folding a range that contains it.
11247 let snapshot = self.snapshot(cx);
11248 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11249 drop(snapshot);
11250 self.active_diagnostics = Some(active_diagnostics);
11251 self.dismiss_diagnostics(cx);
11252 } else {
11253 self.active_diagnostics = Some(active_diagnostics);
11254 }
11255 }
11256
11257 self.scrollbar_marker_state.dirty = true;
11258 }
11259
11260 /// Removes any folds whose ranges intersect any of the given ranges.
11261 pub fn unfold_ranges<T: ToOffset + Clone>(
11262 &mut self,
11263 ranges: &[Range<T>],
11264 inclusive: bool,
11265 auto_scroll: bool,
11266 cx: &mut ViewContext<Self>,
11267 ) {
11268 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11269 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11270 });
11271 }
11272
11273 /// Removes any folds with the given ranges.
11274 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11275 &mut self,
11276 ranges: &[Range<T>],
11277 type_id: TypeId,
11278 auto_scroll: bool,
11279 cx: &mut ViewContext<Self>,
11280 ) {
11281 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11282 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11283 });
11284 }
11285
11286 fn remove_folds_with<T: ToOffset + Clone>(
11287 &mut self,
11288 ranges: &[Range<T>],
11289 auto_scroll: bool,
11290 cx: &mut ViewContext<Self>,
11291 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11292 ) {
11293 if ranges.is_empty() {
11294 return;
11295 }
11296
11297 let mut buffers_affected = HashMap::default();
11298 let multi_buffer = self.buffer().read(cx);
11299 for range in ranges {
11300 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11301 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11302 };
11303 }
11304
11305 self.display_map.update(cx, update);
11306
11307 if auto_scroll {
11308 self.request_autoscroll(Autoscroll::fit(), cx);
11309 }
11310
11311 for buffer in buffers_affected.into_values() {
11312 self.sync_expanded_diff_hunks(buffer, cx);
11313 }
11314
11315 cx.notify();
11316 self.scrollbar_marker_state.dirty = true;
11317 self.active_indent_guides_state.dirty = true;
11318 }
11319
11320 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11321 self.display_map.read(cx).fold_placeholder.clone()
11322 }
11323
11324 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11325 if hovered != self.gutter_hovered {
11326 self.gutter_hovered = hovered;
11327 cx.notify();
11328 }
11329 }
11330
11331 pub fn insert_blocks(
11332 &mut self,
11333 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11334 autoscroll: Option<Autoscroll>,
11335 cx: &mut ViewContext<Self>,
11336 ) -> Vec<CustomBlockId> {
11337 let blocks = self
11338 .display_map
11339 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11340 if let Some(autoscroll) = autoscroll {
11341 self.request_autoscroll(autoscroll, cx);
11342 }
11343 cx.notify();
11344 blocks
11345 }
11346
11347 pub fn resize_blocks(
11348 &mut self,
11349 heights: HashMap<CustomBlockId, u32>,
11350 autoscroll: Option<Autoscroll>,
11351 cx: &mut ViewContext<Self>,
11352 ) {
11353 self.display_map
11354 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11355 if let Some(autoscroll) = autoscroll {
11356 self.request_autoscroll(autoscroll, cx);
11357 }
11358 cx.notify();
11359 }
11360
11361 pub fn replace_blocks(
11362 &mut self,
11363 renderers: HashMap<CustomBlockId, RenderBlock>,
11364 autoscroll: Option<Autoscroll>,
11365 cx: &mut ViewContext<Self>,
11366 ) {
11367 self.display_map
11368 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11369 if let Some(autoscroll) = autoscroll {
11370 self.request_autoscroll(autoscroll, cx);
11371 }
11372 cx.notify();
11373 }
11374
11375 pub fn remove_blocks(
11376 &mut self,
11377 block_ids: HashSet<CustomBlockId>,
11378 autoscroll: Option<Autoscroll>,
11379 cx: &mut ViewContext<Self>,
11380 ) {
11381 self.display_map.update(cx, |display_map, cx| {
11382 display_map.remove_blocks(block_ids, cx)
11383 });
11384 if let Some(autoscroll) = autoscroll {
11385 self.request_autoscroll(autoscroll, cx);
11386 }
11387 cx.notify();
11388 }
11389
11390 pub fn row_for_block(
11391 &self,
11392 block_id: CustomBlockId,
11393 cx: &mut ViewContext<Self>,
11394 ) -> Option<DisplayRow> {
11395 self.display_map
11396 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11397 }
11398
11399 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11400 self.focused_block = Some(focused_block);
11401 }
11402
11403 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11404 self.focused_block.take()
11405 }
11406
11407 pub fn insert_creases(
11408 &mut self,
11409 creases: impl IntoIterator<Item = Crease<Anchor>>,
11410 cx: &mut ViewContext<Self>,
11411 ) -> Vec<CreaseId> {
11412 self.display_map
11413 .update(cx, |map, cx| map.insert_creases(creases, cx))
11414 }
11415
11416 pub fn remove_creases(
11417 &mut self,
11418 ids: impl IntoIterator<Item = CreaseId>,
11419 cx: &mut ViewContext<Self>,
11420 ) {
11421 self.display_map
11422 .update(cx, |map, cx| map.remove_creases(ids, cx));
11423 }
11424
11425 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11426 self.display_map
11427 .update(cx, |map, cx| map.snapshot(cx))
11428 .longest_row()
11429 }
11430
11431 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11432 self.display_map
11433 .update(cx, |map, cx| map.snapshot(cx))
11434 .max_point()
11435 }
11436
11437 pub fn text(&self, cx: &AppContext) -> String {
11438 self.buffer.read(cx).read(cx).text()
11439 }
11440
11441 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11442 let text = self.text(cx);
11443 let text = text.trim();
11444
11445 if text.is_empty() {
11446 return None;
11447 }
11448
11449 Some(text.to_string())
11450 }
11451
11452 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11453 self.transact(cx, |this, cx| {
11454 this.buffer
11455 .read(cx)
11456 .as_singleton()
11457 .expect("you can only call set_text on editors for singleton buffers")
11458 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11459 });
11460 }
11461
11462 pub fn display_text(&self, cx: &mut AppContext) -> String {
11463 self.display_map
11464 .update(cx, |map, cx| map.snapshot(cx))
11465 .text()
11466 }
11467
11468 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11469 let mut wrap_guides = smallvec::smallvec![];
11470
11471 if self.show_wrap_guides == Some(false) {
11472 return wrap_guides;
11473 }
11474
11475 let settings = self.buffer.read(cx).settings_at(0, cx);
11476 if settings.show_wrap_guides {
11477 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11478 wrap_guides.push((soft_wrap as usize, true));
11479 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11480 wrap_guides.push((soft_wrap as usize, true));
11481 }
11482 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11483 }
11484
11485 wrap_guides
11486 }
11487
11488 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11489 let settings = self.buffer.read(cx).settings_at(0, cx);
11490 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11491 match mode {
11492 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11493 SoftWrap::None
11494 }
11495 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11496 language_settings::SoftWrap::PreferredLineLength => {
11497 SoftWrap::Column(settings.preferred_line_length)
11498 }
11499 language_settings::SoftWrap::Bounded => {
11500 SoftWrap::Bounded(settings.preferred_line_length)
11501 }
11502 }
11503 }
11504
11505 pub fn set_soft_wrap_mode(
11506 &mut self,
11507 mode: language_settings::SoftWrap,
11508 cx: &mut ViewContext<Self>,
11509 ) {
11510 self.soft_wrap_mode_override = Some(mode);
11511 cx.notify();
11512 }
11513
11514 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11515 self.text_style_refinement = Some(style);
11516 }
11517
11518 /// called by the Element so we know what style we were most recently rendered with.
11519 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11520 let rem_size = cx.rem_size();
11521 self.display_map.update(cx, |map, cx| {
11522 map.set_font(
11523 style.text.font(),
11524 style.text.font_size.to_pixels(rem_size),
11525 cx,
11526 )
11527 });
11528 self.style = Some(style);
11529 }
11530
11531 pub fn style(&self) -> Option<&EditorStyle> {
11532 self.style.as_ref()
11533 }
11534
11535 // Called by the element. This method is not designed to be called outside of the editor
11536 // element's layout code because it does not notify when rewrapping is computed synchronously.
11537 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11538 self.display_map
11539 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11540 }
11541
11542 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11543 if self.soft_wrap_mode_override.is_some() {
11544 self.soft_wrap_mode_override.take();
11545 } else {
11546 let soft_wrap = match self.soft_wrap_mode(cx) {
11547 SoftWrap::GitDiff => return,
11548 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11549 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11550 language_settings::SoftWrap::None
11551 }
11552 };
11553 self.soft_wrap_mode_override = Some(soft_wrap);
11554 }
11555 cx.notify();
11556 }
11557
11558 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11559 let Some(workspace) = self.workspace() else {
11560 return;
11561 };
11562 let fs = workspace.read(cx).app_state().fs.clone();
11563 let current_show = TabBarSettings::get_global(cx).show;
11564 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11565 setting.show = Some(!current_show);
11566 });
11567 }
11568
11569 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11570 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11571 self.buffer
11572 .read(cx)
11573 .settings_at(0, cx)
11574 .indent_guides
11575 .enabled
11576 });
11577 self.show_indent_guides = Some(!currently_enabled);
11578 cx.notify();
11579 }
11580
11581 fn should_show_indent_guides(&self) -> Option<bool> {
11582 self.show_indent_guides
11583 }
11584
11585 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11586 let mut editor_settings = EditorSettings::get_global(cx).clone();
11587 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11588 EditorSettings::override_global(editor_settings, cx);
11589 }
11590
11591 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11592 self.use_relative_line_numbers
11593 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11594 }
11595
11596 pub fn toggle_relative_line_numbers(
11597 &mut self,
11598 _: &ToggleRelativeLineNumbers,
11599 cx: &mut ViewContext<Self>,
11600 ) {
11601 let is_relative = self.should_use_relative_line_numbers(cx);
11602 self.set_relative_line_number(Some(!is_relative), cx)
11603 }
11604
11605 pub fn set_relative_line_number(
11606 &mut self,
11607 is_relative: Option<bool>,
11608 cx: &mut ViewContext<Self>,
11609 ) {
11610 self.use_relative_line_numbers = is_relative;
11611 cx.notify();
11612 }
11613
11614 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11615 self.show_gutter = show_gutter;
11616 cx.notify();
11617 }
11618
11619 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11620 self.show_line_numbers = Some(show_line_numbers);
11621 cx.notify();
11622 }
11623
11624 pub fn set_show_git_diff_gutter(
11625 &mut self,
11626 show_git_diff_gutter: bool,
11627 cx: &mut ViewContext<Self>,
11628 ) {
11629 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11630 cx.notify();
11631 }
11632
11633 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11634 self.show_code_actions = Some(show_code_actions);
11635 cx.notify();
11636 }
11637
11638 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11639 self.show_runnables = Some(show_runnables);
11640 cx.notify();
11641 }
11642
11643 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11644 if self.display_map.read(cx).masked != masked {
11645 self.display_map.update(cx, |map, _| map.masked = masked);
11646 }
11647 cx.notify()
11648 }
11649
11650 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11651 self.show_wrap_guides = Some(show_wrap_guides);
11652 cx.notify();
11653 }
11654
11655 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11656 self.show_indent_guides = Some(show_indent_guides);
11657 cx.notify();
11658 }
11659
11660 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11661 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11662 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11663 if let Some(dir) = file.abs_path(cx).parent() {
11664 return Some(dir.to_owned());
11665 }
11666 }
11667
11668 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11669 return Some(project_path.path.to_path_buf());
11670 }
11671 }
11672
11673 None
11674 }
11675
11676 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11677 self.active_excerpt(cx)?
11678 .1
11679 .read(cx)
11680 .file()
11681 .and_then(|f| f.as_local())
11682 }
11683
11684 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11685 if let Some(target) = self.target_file(cx) {
11686 cx.reveal_path(&target.abs_path(cx));
11687 }
11688 }
11689
11690 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11691 if let Some(file) = self.target_file(cx) {
11692 if let Some(path) = file.abs_path(cx).to_str() {
11693 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11694 }
11695 }
11696 }
11697
11698 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11699 if let Some(file) = self.target_file(cx) {
11700 if let Some(path) = file.path().to_str() {
11701 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11702 }
11703 }
11704 }
11705
11706 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11707 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11708
11709 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11710 self.start_git_blame(true, cx);
11711 }
11712
11713 cx.notify();
11714 }
11715
11716 pub fn toggle_git_blame_inline(
11717 &mut self,
11718 _: &ToggleGitBlameInline,
11719 cx: &mut ViewContext<Self>,
11720 ) {
11721 self.toggle_git_blame_inline_internal(true, cx);
11722 cx.notify();
11723 }
11724
11725 pub fn git_blame_inline_enabled(&self) -> bool {
11726 self.git_blame_inline_enabled
11727 }
11728
11729 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11730 self.show_selection_menu = self
11731 .show_selection_menu
11732 .map(|show_selections_menu| !show_selections_menu)
11733 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11734
11735 cx.notify();
11736 }
11737
11738 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11739 self.show_selection_menu
11740 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11741 }
11742
11743 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11744 if let Some(project) = self.project.as_ref() {
11745 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11746 return;
11747 };
11748
11749 if buffer.read(cx).file().is_none() {
11750 return;
11751 }
11752
11753 let focused = self.focus_handle(cx).contains_focused(cx);
11754
11755 let project = project.clone();
11756 let blame =
11757 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11758 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11759 self.blame = Some(blame);
11760 }
11761 }
11762
11763 fn toggle_git_blame_inline_internal(
11764 &mut self,
11765 user_triggered: bool,
11766 cx: &mut ViewContext<Self>,
11767 ) {
11768 if self.git_blame_inline_enabled {
11769 self.git_blame_inline_enabled = false;
11770 self.show_git_blame_inline = false;
11771 self.show_git_blame_inline_delay_task.take();
11772 } else {
11773 self.git_blame_inline_enabled = true;
11774 self.start_git_blame_inline(user_triggered, cx);
11775 }
11776
11777 cx.notify();
11778 }
11779
11780 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11781 self.start_git_blame(user_triggered, cx);
11782
11783 if ProjectSettings::get_global(cx)
11784 .git
11785 .inline_blame_delay()
11786 .is_some()
11787 {
11788 self.start_inline_blame_timer(cx);
11789 } else {
11790 self.show_git_blame_inline = true
11791 }
11792 }
11793
11794 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11795 self.blame.as_ref()
11796 }
11797
11798 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11799 self.show_git_blame_gutter && self.has_blame_entries(cx)
11800 }
11801
11802 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11803 self.show_git_blame_inline
11804 && self.focus_handle.is_focused(cx)
11805 && !self.newest_selection_head_on_empty_line(cx)
11806 && self.has_blame_entries(cx)
11807 }
11808
11809 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11810 self.blame()
11811 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11812 }
11813
11814 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11815 let cursor_anchor = self.selections.newest_anchor().head();
11816
11817 let snapshot = self.buffer.read(cx).snapshot(cx);
11818 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11819
11820 snapshot.line_len(buffer_row) == 0
11821 }
11822
11823 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11824 let buffer_and_selection = maybe!({
11825 let selection = self.selections.newest::<Point>(cx);
11826 let selection_range = selection.range();
11827
11828 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11829 (buffer, selection_range.start.row..selection_range.end.row)
11830 } else {
11831 let buffer_ranges = self
11832 .buffer()
11833 .read(cx)
11834 .range_to_buffer_ranges(selection_range, cx);
11835
11836 let (buffer, range, _) = if selection.reversed {
11837 buffer_ranges.first()
11838 } else {
11839 buffer_ranges.last()
11840 }?;
11841
11842 let snapshot = buffer.read(cx).snapshot();
11843 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11844 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11845 (buffer.clone(), selection)
11846 };
11847
11848 Some((buffer, selection))
11849 });
11850
11851 let Some((buffer, selection)) = buffer_and_selection else {
11852 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11853 };
11854
11855 let Some(project) = self.project.as_ref() else {
11856 return Task::ready(Err(anyhow!("editor does not have project")));
11857 };
11858
11859 project.update(cx, |project, cx| {
11860 project.get_permalink_to_line(&buffer, selection, cx)
11861 })
11862 }
11863
11864 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11865 let permalink_task = self.get_permalink_to_line(cx);
11866 let workspace = self.workspace();
11867
11868 cx.spawn(|_, mut cx| async move {
11869 match permalink_task.await {
11870 Ok(permalink) => {
11871 cx.update(|cx| {
11872 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11873 })
11874 .ok();
11875 }
11876 Err(err) => {
11877 let message = format!("Failed to copy permalink: {err}");
11878
11879 Err::<(), anyhow::Error>(err).log_err();
11880
11881 if let Some(workspace) = workspace {
11882 workspace
11883 .update(&mut cx, |workspace, cx| {
11884 struct CopyPermalinkToLine;
11885
11886 workspace.show_toast(
11887 Toast::new(
11888 NotificationId::unique::<CopyPermalinkToLine>(),
11889 message,
11890 ),
11891 cx,
11892 )
11893 })
11894 .ok();
11895 }
11896 }
11897 }
11898 })
11899 .detach();
11900 }
11901
11902 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11903 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11904 if let Some(file) = self.target_file(cx) {
11905 if let Some(path) = file.path().to_str() {
11906 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11907 }
11908 }
11909 }
11910
11911 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11912 let permalink_task = self.get_permalink_to_line(cx);
11913 let workspace = self.workspace();
11914
11915 cx.spawn(|_, mut cx| async move {
11916 match permalink_task.await {
11917 Ok(permalink) => {
11918 cx.update(|cx| {
11919 cx.open_url(permalink.as_ref());
11920 })
11921 .ok();
11922 }
11923 Err(err) => {
11924 let message = format!("Failed to open permalink: {err}");
11925
11926 Err::<(), anyhow::Error>(err).log_err();
11927
11928 if let Some(workspace) = workspace {
11929 workspace
11930 .update(&mut cx, |workspace, cx| {
11931 struct OpenPermalinkToLine;
11932
11933 workspace.show_toast(
11934 Toast::new(
11935 NotificationId::unique::<OpenPermalinkToLine>(),
11936 message,
11937 ),
11938 cx,
11939 )
11940 })
11941 .ok();
11942 }
11943 }
11944 }
11945 })
11946 .detach();
11947 }
11948
11949 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11950 /// last highlight added will be used.
11951 ///
11952 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11953 pub fn highlight_rows<T: 'static>(
11954 &mut self,
11955 range: Range<Anchor>,
11956 color: Hsla,
11957 should_autoscroll: bool,
11958 cx: &mut ViewContext<Self>,
11959 ) {
11960 let snapshot = self.buffer().read(cx).snapshot(cx);
11961 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11962 let ix = row_highlights.binary_search_by(|highlight| {
11963 Ordering::Equal
11964 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11965 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11966 });
11967
11968 if let Err(mut ix) = ix {
11969 let index = post_inc(&mut self.highlight_order);
11970
11971 // If this range intersects with the preceding highlight, then merge it with
11972 // the preceding highlight. Otherwise insert a new highlight.
11973 let mut merged = false;
11974 if ix > 0 {
11975 let prev_highlight = &mut row_highlights[ix - 1];
11976 if prev_highlight
11977 .range
11978 .end
11979 .cmp(&range.start, &snapshot)
11980 .is_ge()
11981 {
11982 ix -= 1;
11983 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11984 prev_highlight.range.end = range.end;
11985 }
11986 merged = true;
11987 prev_highlight.index = index;
11988 prev_highlight.color = color;
11989 prev_highlight.should_autoscroll = should_autoscroll;
11990 }
11991 }
11992
11993 if !merged {
11994 row_highlights.insert(
11995 ix,
11996 RowHighlight {
11997 range: range.clone(),
11998 index,
11999 color,
12000 should_autoscroll,
12001 },
12002 );
12003 }
12004
12005 // If any of the following highlights intersect with this one, merge them.
12006 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12007 let highlight = &row_highlights[ix];
12008 if next_highlight
12009 .range
12010 .start
12011 .cmp(&highlight.range.end, &snapshot)
12012 .is_le()
12013 {
12014 if next_highlight
12015 .range
12016 .end
12017 .cmp(&highlight.range.end, &snapshot)
12018 .is_gt()
12019 {
12020 row_highlights[ix].range.end = next_highlight.range.end;
12021 }
12022 row_highlights.remove(ix + 1);
12023 } else {
12024 break;
12025 }
12026 }
12027 }
12028 }
12029
12030 /// Remove any highlighted row ranges of the given type that intersect the
12031 /// given ranges.
12032 pub fn remove_highlighted_rows<T: 'static>(
12033 &mut self,
12034 ranges_to_remove: Vec<Range<Anchor>>,
12035 cx: &mut ViewContext<Self>,
12036 ) {
12037 let snapshot = self.buffer().read(cx).snapshot(cx);
12038 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12039 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12040 row_highlights.retain(|highlight| {
12041 while let Some(range_to_remove) = ranges_to_remove.peek() {
12042 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12043 Ordering::Less | Ordering::Equal => {
12044 ranges_to_remove.next();
12045 }
12046 Ordering::Greater => {
12047 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12048 Ordering::Less | Ordering::Equal => {
12049 return false;
12050 }
12051 Ordering::Greater => break,
12052 }
12053 }
12054 }
12055 }
12056
12057 true
12058 })
12059 }
12060
12061 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12062 pub fn clear_row_highlights<T: 'static>(&mut self) {
12063 self.highlighted_rows.remove(&TypeId::of::<T>());
12064 }
12065
12066 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12067 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12068 self.highlighted_rows
12069 .get(&TypeId::of::<T>())
12070 .map_or(&[] as &[_], |vec| vec.as_slice())
12071 .iter()
12072 .map(|highlight| (highlight.range.clone(), highlight.color))
12073 }
12074
12075 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12076 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12077 /// Allows to ignore certain kinds of highlights.
12078 pub fn highlighted_display_rows(
12079 &mut self,
12080 cx: &mut WindowContext,
12081 ) -> BTreeMap<DisplayRow, Hsla> {
12082 let snapshot = self.snapshot(cx);
12083 let mut used_highlight_orders = HashMap::default();
12084 self.highlighted_rows
12085 .iter()
12086 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12087 .fold(
12088 BTreeMap::<DisplayRow, Hsla>::new(),
12089 |mut unique_rows, highlight| {
12090 let start = highlight.range.start.to_display_point(&snapshot);
12091 let end = highlight.range.end.to_display_point(&snapshot);
12092 let start_row = start.row().0;
12093 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12094 && end.column() == 0
12095 {
12096 end.row().0.saturating_sub(1)
12097 } else {
12098 end.row().0
12099 };
12100 for row in start_row..=end_row {
12101 let used_index =
12102 used_highlight_orders.entry(row).or_insert(highlight.index);
12103 if highlight.index >= *used_index {
12104 *used_index = highlight.index;
12105 unique_rows.insert(DisplayRow(row), highlight.color);
12106 }
12107 }
12108 unique_rows
12109 },
12110 )
12111 }
12112
12113 pub fn highlighted_display_row_for_autoscroll(
12114 &self,
12115 snapshot: &DisplaySnapshot,
12116 ) -> Option<DisplayRow> {
12117 self.highlighted_rows
12118 .values()
12119 .flat_map(|highlighted_rows| highlighted_rows.iter())
12120 .filter_map(|highlight| {
12121 if highlight.should_autoscroll {
12122 Some(highlight.range.start.to_display_point(snapshot).row())
12123 } else {
12124 None
12125 }
12126 })
12127 .min()
12128 }
12129
12130 pub fn set_search_within_ranges(
12131 &mut self,
12132 ranges: &[Range<Anchor>],
12133 cx: &mut ViewContext<Self>,
12134 ) {
12135 self.highlight_background::<SearchWithinRange>(
12136 ranges,
12137 |colors| colors.editor_document_highlight_read_background,
12138 cx,
12139 )
12140 }
12141
12142 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12143 self.breadcrumb_header = Some(new_header);
12144 }
12145
12146 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12147 self.clear_background_highlights::<SearchWithinRange>(cx);
12148 }
12149
12150 pub fn highlight_background<T: 'static>(
12151 &mut self,
12152 ranges: &[Range<Anchor>],
12153 color_fetcher: fn(&ThemeColors) -> Hsla,
12154 cx: &mut ViewContext<Self>,
12155 ) {
12156 self.background_highlights
12157 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12158 self.scrollbar_marker_state.dirty = true;
12159 cx.notify();
12160 }
12161
12162 pub fn clear_background_highlights<T: 'static>(
12163 &mut self,
12164 cx: &mut ViewContext<Self>,
12165 ) -> Option<BackgroundHighlight> {
12166 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12167 if !text_highlights.1.is_empty() {
12168 self.scrollbar_marker_state.dirty = true;
12169 cx.notify();
12170 }
12171 Some(text_highlights)
12172 }
12173
12174 pub fn highlight_gutter<T: 'static>(
12175 &mut self,
12176 ranges: &[Range<Anchor>],
12177 color_fetcher: fn(&AppContext) -> Hsla,
12178 cx: &mut ViewContext<Self>,
12179 ) {
12180 self.gutter_highlights
12181 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12182 cx.notify();
12183 }
12184
12185 pub fn clear_gutter_highlights<T: 'static>(
12186 &mut self,
12187 cx: &mut ViewContext<Self>,
12188 ) -> Option<GutterHighlight> {
12189 cx.notify();
12190 self.gutter_highlights.remove(&TypeId::of::<T>())
12191 }
12192
12193 #[cfg(feature = "test-support")]
12194 pub fn all_text_background_highlights(
12195 &mut self,
12196 cx: &mut ViewContext<Self>,
12197 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12198 let snapshot = self.snapshot(cx);
12199 let buffer = &snapshot.buffer_snapshot;
12200 let start = buffer.anchor_before(0);
12201 let end = buffer.anchor_after(buffer.len());
12202 let theme = cx.theme().colors();
12203 self.background_highlights_in_range(start..end, &snapshot, theme)
12204 }
12205
12206 #[cfg(feature = "test-support")]
12207 pub fn search_background_highlights(
12208 &mut self,
12209 cx: &mut ViewContext<Self>,
12210 ) -> Vec<Range<Point>> {
12211 let snapshot = self.buffer().read(cx).snapshot(cx);
12212
12213 let highlights = self
12214 .background_highlights
12215 .get(&TypeId::of::<items::BufferSearchHighlights>());
12216
12217 if let Some((_color, ranges)) = highlights {
12218 ranges
12219 .iter()
12220 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12221 .collect_vec()
12222 } else {
12223 vec![]
12224 }
12225 }
12226
12227 fn document_highlights_for_position<'a>(
12228 &'a self,
12229 position: Anchor,
12230 buffer: &'a MultiBufferSnapshot,
12231 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12232 let read_highlights = self
12233 .background_highlights
12234 .get(&TypeId::of::<DocumentHighlightRead>())
12235 .map(|h| &h.1);
12236 let write_highlights = self
12237 .background_highlights
12238 .get(&TypeId::of::<DocumentHighlightWrite>())
12239 .map(|h| &h.1);
12240 let left_position = position.bias_left(buffer);
12241 let right_position = position.bias_right(buffer);
12242 read_highlights
12243 .into_iter()
12244 .chain(write_highlights)
12245 .flat_map(move |ranges| {
12246 let start_ix = match ranges.binary_search_by(|probe| {
12247 let cmp = probe.end.cmp(&left_position, buffer);
12248 if cmp.is_ge() {
12249 Ordering::Greater
12250 } else {
12251 Ordering::Less
12252 }
12253 }) {
12254 Ok(i) | Err(i) => i,
12255 };
12256
12257 ranges[start_ix..]
12258 .iter()
12259 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12260 })
12261 }
12262
12263 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12264 self.background_highlights
12265 .get(&TypeId::of::<T>())
12266 .map_or(false, |(_, highlights)| !highlights.is_empty())
12267 }
12268
12269 pub fn background_highlights_in_range(
12270 &self,
12271 search_range: Range<Anchor>,
12272 display_snapshot: &DisplaySnapshot,
12273 theme: &ThemeColors,
12274 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12275 let mut results = Vec::new();
12276 for (color_fetcher, ranges) in self.background_highlights.values() {
12277 let color = color_fetcher(theme);
12278 let start_ix = match ranges.binary_search_by(|probe| {
12279 let cmp = probe
12280 .end
12281 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12282 if cmp.is_gt() {
12283 Ordering::Greater
12284 } else {
12285 Ordering::Less
12286 }
12287 }) {
12288 Ok(i) | Err(i) => i,
12289 };
12290 for range in &ranges[start_ix..] {
12291 if range
12292 .start
12293 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12294 .is_ge()
12295 {
12296 break;
12297 }
12298
12299 let start = range.start.to_display_point(display_snapshot);
12300 let end = range.end.to_display_point(display_snapshot);
12301 results.push((start..end, color))
12302 }
12303 }
12304 results
12305 }
12306
12307 pub fn background_highlight_row_ranges<T: 'static>(
12308 &self,
12309 search_range: Range<Anchor>,
12310 display_snapshot: &DisplaySnapshot,
12311 count: usize,
12312 ) -> Vec<RangeInclusive<DisplayPoint>> {
12313 let mut results = Vec::new();
12314 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12315 return vec![];
12316 };
12317
12318 let start_ix = match ranges.binary_search_by(|probe| {
12319 let cmp = probe
12320 .end
12321 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12322 if cmp.is_gt() {
12323 Ordering::Greater
12324 } else {
12325 Ordering::Less
12326 }
12327 }) {
12328 Ok(i) | Err(i) => i,
12329 };
12330 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12331 if let (Some(start_display), Some(end_display)) = (start, end) {
12332 results.push(
12333 start_display.to_display_point(display_snapshot)
12334 ..=end_display.to_display_point(display_snapshot),
12335 );
12336 }
12337 };
12338 let mut start_row: Option<Point> = None;
12339 let mut end_row: Option<Point> = None;
12340 if ranges.len() > count {
12341 return Vec::new();
12342 }
12343 for range in &ranges[start_ix..] {
12344 if range
12345 .start
12346 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12347 .is_ge()
12348 {
12349 break;
12350 }
12351 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12352 if let Some(current_row) = &end_row {
12353 if end.row == current_row.row {
12354 continue;
12355 }
12356 }
12357 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12358 if start_row.is_none() {
12359 assert_eq!(end_row, None);
12360 start_row = Some(start);
12361 end_row = Some(end);
12362 continue;
12363 }
12364 if let Some(current_end) = end_row.as_mut() {
12365 if start.row > current_end.row + 1 {
12366 push_region(start_row, end_row);
12367 start_row = Some(start);
12368 end_row = Some(end);
12369 } else {
12370 // Merge two hunks.
12371 *current_end = end;
12372 }
12373 } else {
12374 unreachable!();
12375 }
12376 }
12377 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12378 push_region(start_row, end_row);
12379 results
12380 }
12381
12382 pub fn gutter_highlights_in_range(
12383 &self,
12384 search_range: Range<Anchor>,
12385 display_snapshot: &DisplaySnapshot,
12386 cx: &AppContext,
12387 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12388 let mut results = Vec::new();
12389 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12390 let color = color_fetcher(cx);
12391 let start_ix = match ranges.binary_search_by(|probe| {
12392 let cmp = probe
12393 .end
12394 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12395 if cmp.is_gt() {
12396 Ordering::Greater
12397 } else {
12398 Ordering::Less
12399 }
12400 }) {
12401 Ok(i) | Err(i) => i,
12402 };
12403 for range in &ranges[start_ix..] {
12404 if range
12405 .start
12406 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12407 .is_ge()
12408 {
12409 break;
12410 }
12411
12412 let start = range.start.to_display_point(display_snapshot);
12413 let end = range.end.to_display_point(display_snapshot);
12414 results.push((start..end, color))
12415 }
12416 }
12417 results
12418 }
12419
12420 /// Get the text ranges corresponding to the redaction query
12421 pub fn redacted_ranges(
12422 &self,
12423 search_range: Range<Anchor>,
12424 display_snapshot: &DisplaySnapshot,
12425 cx: &WindowContext,
12426 ) -> Vec<Range<DisplayPoint>> {
12427 display_snapshot
12428 .buffer_snapshot
12429 .redacted_ranges(search_range, |file| {
12430 if let Some(file) = file {
12431 file.is_private()
12432 && EditorSettings::get(
12433 Some(SettingsLocation {
12434 worktree_id: file.worktree_id(cx),
12435 path: file.path().as_ref(),
12436 }),
12437 cx,
12438 )
12439 .redact_private_values
12440 } else {
12441 false
12442 }
12443 })
12444 .map(|range| {
12445 range.start.to_display_point(display_snapshot)
12446 ..range.end.to_display_point(display_snapshot)
12447 })
12448 .collect()
12449 }
12450
12451 pub fn highlight_text<T: 'static>(
12452 &mut self,
12453 ranges: Vec<Range<Anchor>>,
12454 style: HighlightStyle,
12455 cx: &mut ViewContext<Self>,
12456 ) {
12457 self.display_map.update(cx, |map, _| {
12458 map.highlight_text(TypeId::of::<T>(), ranges, style)
12459 });
12460 cx.notify();
12461 }
12462
12463 pub(crate) fn highlight_inlays<T: 'static>(
12464 &mut self,
12465 highlights: Vec<InlayHighlight>,
12466 style: HighlightStyle,
12467 cx: &mut ViewContext<Self>,
12468 ) {
12469 self.display_map.update(cx, |map, _| {
12470 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12471 });
12472 cx.notify();
12473 }
12474
12475 pub fn text_highlights<'a, T: 'static>(
12476 &'a self,
12477 cx: &'a AppContext,
12478 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12479 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12480 }
12481
12482 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12483 let cleared = self
12484 .display_map
12485 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12486 if cleared {
12487 cx.notify();
12488 }
12489 }
12490
12491 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12492 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12493 && self.focus_handle.is_focused(cx)
12494 }
12495
12496 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12497 self.show_cursor_when_unfocused = is_enabled;
12498 cx.notify();
12499 }
12500
12501 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12502 cx.notify();
12503 }
12504
12505 fn on_buffer_event(
12506 &mut self,
12507 multibuffer: Model<MultiBuffer>,
12508 event: &multi_buffer::Event,
12509 cx: &mut ViewContext<Self>,
12510 ) {
12511 match event {
12512 multi_buffer::Event::Edited {
12513 singleton_buffer_edited,
12514 } => {
12515 self.scrollbar_marker_state.dirty = true;
12516 self.active_indent_guides_state.dirty = true;
12517 self.refresh_active_diagnostics(cx);
12518 self.refresh_code_actions(cx);
12519 if self.has_active_inline_completion(cx) {
12520 self.update_visible_inline_completion(cx);
12521 }
12522 cx.emit(EditorEvent::BufferEdited);
12523 cx.emit(SearchEvent::MatchesInvalidated);
12524 if *singleton_buffer_edited {
12525 if let Some(project) = &self.project {
12526 let project = project.read(cx);
12527 #[allow(clippy::mutable_key_type)]
12528 let languages_affected = multibuffer
12529 .read(cx)
12530 .all_buffers()
12531 .into_iter()
12532 .filter_map(|buffer| {
12533 let buffer = buffer.read(cx);
12534 let language = buffer.language()?;
12535 if project.is_local()
12536 && project.language_servers_for_buffer(buffer, cx).count() == 0
12537 {
12538 None
12539 } else {
12540 Some(language)
12541 }
12542 })
12543 .cloned()
12544 .collect::<HashSet<_>>();
12545 if !languages_affected.is_empty() {
12546 self.refresh_inlay_hints(
12547 InlayHintRefreshReason::BufferEdited(languages_affected),
12548 cx,
12549 );
12550 }
12551 }
12552 }
12553
12554 let Some(project) = &self.project else { return };
12555 let (telemetry, is_via_ssh) = {
12556 let project = project.read(cx);
12557 let telemetry = project.client().telemetry().clone();
12558 let is_via_ssh = project.is_via_ssh();
12559 (telemetry, is_via_ssh)
12560 };
12561 refresh_linked_ranges(self, cx);
12562 telemetry.log_edit_event("editor", is_via_ssh);
12563 }
12564 multi_buffer::Event::ExcerptsAdded {
12565 buffer,
12566 predecessor,
12567 excerpts,
12568 } => {
12569 self.tasks_update_task = Some(self.refresh_runnables(cx));
12570 cx.emit(EditorEvent::ExcerptsAdded {
12571 buffer: buffer.clone(),
12572 predecessor: *predecessor,
12573 excerpts: excerpts.clone(),
12574 });
12575 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12576 }
12577 multi_buffer::Event::ExcerptsRemoved { ids } => {
12578 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12579 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12580 }
12581 multi_buffer::Event::ExcerptsEdited { ids } => {
12582 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12583 }
12584 multi_buffer::Event::ExcerptsExpanded { ids } => {
12585 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12586 }
12587 multi_buffer::Event::Reparsed(buffer_id) => {
12588 self.tasks_update_task = Some(self.refresh_runnables(cx));
12589
12590 cx.emit(EditorEvent::Reparsed(*buffer_id));
12591 }
12592 multi_buffer::Event::LanguageChanged(buffer_id) => {
12593 linked_editing_ranges::refresh_linked_ranges(self, cx);
12594 cx.emit(EditorEvent::Reparsed(*buffer_id));
12595 cx.notify();
12596 }
12597 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12598 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12599 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12600 cx.emit(EditorEvent::TitleChanged)
12601 }
12602 multi_buffer::Event::DiffBaseChanged => {
12603 self.scrollbar_marker_state.dirty = true;
12604 cx.emit(EditorEvent::DiffBaseChanged);
12605 cx.notify();
12606 }
12607 multi_buffer::Event::DiffUpdated { buffer } => {
12608 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12609 cx.notify();
12610 }
12611 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12612 multi_buffer::Event::DiagnosticsUpdated => {
12613 self.refresh_active_diagnostics(cx);
12614 self.scrollbar_marker_state.dirty = true;
12615 cx.notify();
12616 }
12617 _ => {}
12618 };
12619 }
12620
12621 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12622 cx.notify();
12623 }
12624
12625 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12626 self.tasks_update_task = Some(self.refresh_runnables(cx));
12627 self.refresh_inline_completion(true, false, cx);
12628 self.refresh_inlay_hints(
12629 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12630 self.selections.newest_anchor().head(),
12631 &self.buffer.read(cx).snapshot(cx),
12632 cx,
12633 )),
12634 cx,
12635 );
12636
12637 let old_cursor_shape = self.cursor_shape;
12638
12639 {
12640 let editor_settings = EditorSettings::get_global(cx);
12641 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12642 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12643 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12644 }
12645
12646 if old_cursor_shape != self.cursor_shape {
12647 cx.emit(EditorEvent::CursorShapeChanged);
12648 }
12649
12650 let project_settings = ProjectSettings::get_global(cx);
12651 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12652
12653 if self.mode == EditorMode::Full {
12654 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12655 if self.git_blame_inline_enabled != inline_blame_enabled {
12656 self.toggle_git_blame_inline_internal(false, cx);
12657 }
12658 }
12659
12660 cx.notify();
12661 }
12662
12663 pub fn set_searchable(&mut self, searchable: bool) {
12664 self.searchable = searchable;
12665 }
12666
12667 pub fn searchable(&self) -> bool {
12668 self.searchable
12669 }
12670
12671 fn open_proposed_changes_editor(
12672 &mut self,
12673 _: &OpenProposedChangesEditor,
12674 cx: &mut ViewContext<Self>,
12675 ) {
12676 let Some(workspace) = self.workspace() else {
12677 cx.propagate();
12678 return;
12679 };
12680
12681 let selections = self.selections.all::<usize>(cx);
12682 let buffer = self.buffer.read(cx);
12683 let mut new_selections_by_buffer = HashMap::default();
12684 for selection in selections {
12685 for (buffer, range, _) in
12686 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12687 {
12688 let mut range = range.to_point(buffer.read(cx));
12689 range.start.column = 0;
12690 range.end.column = buffer.read(cx).line_len(range.end.row);
12691 new_selections_by_buffer
12692 .entry(buffer)
12693 .or_insert(Vec::new())
12694 .push(range)
12695 }
12696 }
12697
12698 let proposed_changes_buffers = new_selections_by_buffer
12699 .into_iter()
12700 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12701 .collect::<Vec<_>>();
12702 let proposed_changes_editor = cx.new_view(|cx| {
12703 ProposedChangesEditor::new(
12704 "Proposed changes",
12705 proposed_changes_buffers,
12706 self.project.clone(),
12707 cx,
12708 )
12709 });
12710
12711 cx.window_context().defer(move |cx| {
12712 workspace.update(cx, |workspace, cx| {
12713 workspace.active_pane().update(cx, |pane, cx| {
12714 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12715 });
12716 });
12717 });
12718 }
12719
12720 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12721 self.open_excerpts_common(None, true, cx)
12722 }
12723
12724 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12725 self.open_excerpts_common(None, false, cx)
12726 }
12727
12728 fn open_excerpts_common(
12729 &mut self,
12730 jump_data: Option<JumpData>,
12731 split: bool,
12732 cx: &mut ViewContext<Self>,
12733 ) {
12734 let Some(workspace) = self.workspace() else {
12735 cx.propagate();
12736 return;
12737 };
12738
12739 if self.buffer.read(cx).is_singleton() {
12740 cx.propagate();
12741 return;
12742 }
12743
12744 let mut new_selections_by_buffer = HashMap::default();
12745 match &jump_data {
12746 Some(jump_data) => {
12747 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12748 if let Some(buffer) = multi_buffer_snapshot
12749 .buffer_id_for_excerpt(jump_data.excerpt_id)
12750 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12751 {
12752 let buffer_snapshot = buffer.read(cx).snapshot();
12753 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12754 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12755 } else {
12756 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12757 };
12758 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12759 new_selections_by_buffer.insert(
12760 buffer,
12761 (
12762 vec![jump_to_offset..jump_to_offset],
12763 Some(jump_data.line_offset_from_top),
12764 ),
12765 );
12766 }
12767 }
12768 None => {
12769 let selections = self.selections.all::<usize>(cx);
12770 let buffer = self.buffer.read(cx);
12771 for selection in selections {
12772 for (mut buffer_handle, mut range, _) in
12773 buffer.range_to_buffer_ranges(selection.range(), cx)
12774 {
12775 // When editing branch buffers, jump to the corresponding location
12776 // in their base buffer.
12777 let buffer = buffer_handle.read(cx);
12778 if let Some(base_buffer) = buffer.diff_base_buffer() {
12779 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12780 buffer_handle = base_buffer;
12781 }
12782
12783 if selection.reversed {
12784 mem::swap(&mut range.start, &mut range.end);
12785 }
12786 new_selections_by_buffer
12787 .entry(buffer_handle)
12788 .or_insert((Vec::new(), None))
12789 .0
12790 .push(range)
12791 }
12792 }
12793 }
12794 }
12795
12796 if new_selections_by_buffer.is_empty() {
12797 return;
12798 }
12799
12800 // We defer the pane interaction because we ourselves are a workspace item
12801 // and activating a new item causes the pane to call a method on us reentrantly,
12802 // which panics if we're on the stack.
12803 cx.window_context().defer(move |cx| {
12804 workspace.update(cx, |workspace, cx| {
12805 let pane = if split {
12806 workspace.adjacent_pane(cx)
12807 } else {
12808 workspace.active_pane().clone()
12809 };
12810
12811 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12812 let editor =
12813 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12814 editor.update(cx, |editor, cx| {
12815 let autoscroll = match scroll_offset {
12816 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12817 None => Autoscroll::newest(),
12818 };
12819 let nav_history = editor.nav_history.take();
12820 editor.change_selections(Some(autoscroll), cx, |s| {
12821 s.select_ranges(ranges);
12822 });
12823 editor.nav_history = nav_history;
12824 });
12825 }
12826 })
12827 });
12828 }
12829
12830 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12831 let snapshot = self.buffer.read(cx).read(cx);
12832 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12833 Some(
12834 ranges
12835 .iter()
12836 .map(move |range| {
12837 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12838 })
12839 .collect(),
12840 )
12841 }
12842
12843 fn selection_replacement_ranges(
12844 &self,
12845 range: Range<OffsetUtf16>,
12846 cx: &mut AppContext,
12847 ) -> Vec<Range<OffsetUtf16>> {
12848 let selections = self.selections.all::<OffsetUtf16>(cx);
12849 let newest_selection = selections
12850 .iter()
12851 .max_by_key(|selection| selection.id)
12852 .unwrap();
12853 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12854 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12855 let snapshot = self.buffer.read(cx).read(cx);
12856 selections
12857 .into_iter()
12858 .map(|mut selection| {
12859 selection.start.0 =
12860 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12861 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12862 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12863 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12864 })
12865 .collect()
12866 }
12867
12868 fn report_editor_event(
12869 &self,
12870 operation: &'static str,
12871 file_extension: Option<String>,
12872 cx: &AppContext,
12873 ) {
12874 if cfg!(any(test, feature = "test-support")) {
12875 return;
12876 }
12877
12878 let Some(project) = &self.project else { return };
12879
12880 // If None, we are in a file without an extension
12881 let file = self
12882 .buffer
12883 .read(cx)
12884 .as_singleton()
12885 .and_then(|b| b.read(cx).file());
12886 let file_extension = file_extension.or(file
12887 .as_ref()
12888 .and_then(|file| Path::new(file.file_name(cx)).extension())
12889 .and_then(|e| e.to_str())
12890 .map(|a| a.to_string()));
12891
12892 let vim_mode = cx
12893 .global::<SettingsStore>()
12894 .raw_user_settings()
12895 .get("vim_mode")
12896 == Some(&serde_json::Value::Bool(true));
12897
12898 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12899 == language::language_settings::InlineCompletionProvider::Copilot;
12900 let copilot_enabled_for_language = self
12901 .buffer
12902 .read(cx)
12903 .settings_at(0, cx)
12904 .show_inline_completions;
12905
12906 let project = project.read(cx);
12907 let telemetry = project.client().telemetry().clone();
12908 telemetry.report_editor_event(
12909 file_extension,
12910 vim_mode,
12911 operation,
12912 copilot_enabled,
12913 copilot_enabled_for_language,
12914 project.is_via_ssh(),
12915 )
12916 }
12917
12918 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12919 /// with each line being an array of {text, highlight} objects.
12920 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12921 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12922 return;
12923 };
12924
12925 #[derive(Serialize)]
12926 struct Chunk<'a> {
12927 text: String,
12928 highlight: Option<&'a str>,
12929 }
12930
12931 let snapshot = buffer.read(cx).snapshot();
12932 let range = self
12933 .selected_text_range(false, cx)
12934 .and_then(|selection| {
12935 if selection.range.is_empty() {
12936 None
12937 } else {
12938 Some(selection.range)
12939 }
12940 })
12941 .unwrap_or_else(|| 0..snapshot.len());
12942
12943 let chunks = snapshot.chunks(range, true);
12944 let mut lines = Vec::new();
12945 let mut line: VecDeque<Chunk> = VecDeque::new();
12946
12947 let Some(style) = self.style.as_ref() else {
12948 return;
12949 };
12950
12951 for chunk in chunks {
12952 let highlight = chunk
12953 .syntax_highlight_id
12954 .and_then(|id| id.name(&style.syntax));
12955 let mut chunk_lines = chunk.text.split('\n').peekable();
12956 while let Some(text) = chunk_lines.next() {
12957 let mut merged_with_last_token = false;
12958 if let Some(last_token) = line.back_mut() {
12959 if last_token.highlight == highlight {
12960 last_token.text.push_str(text);
12961 merged_with_last_token = true;
12962 }
12963 }
12964
12965 if !merged_with_last_token {
12966 line.push_back(Chunk {
12967 text: text.into(),
12968 highlight,
12969 });
12970 }
12971
12972 if chunk_lines.peek().is_some() {
12973 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12974 line.pop_front();
12975 }
12976 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12977 line.pop_back();
12978 }
12979
12980 lines.push(mem::take(&mut line));
12981 }
12982 }
12983 }
12984
12985 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12986 return;
12987 };
12988 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12989 }
12990
12991 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12992 &self.inlay_hint_cache
12993 }
12994
12995 pub fn replay_insert_event(
12996 &mut self,
12997 text: &str,
12998 relative_utf16_range: Option<Range<isize>>,
12999 cx: &mut ViewContext<Self>,
13000 ) {
13001 if !self.input_enabled {
13002 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13003 return;
13004 }
13005 if let Some(relative_utf16_range) = relative_utf16_range {
13006 let selections = self.selections.all::<OffsetUtf16>(cx);
13007 self.change_selections(None, cx, |s| {
13008 let new_ranges = selections.into_iter().map(|range| {
13009 let start = OffsetUtf16(
13010 range
13011 .head()
13012 .0
13013 .saturating_add_signed(relative_utf16_range.start),
13014 );
13015 let end = OffsetUtf16(
13016 range
13017 .head()
13018 .0
13019 .saturating_add_signed(relative_utf16_range.end),
13020 );
13021 start..end
13022 });
13023 s.select_ranges(new_ranges);
13024 });
13025 }
13026
13027 self.handle_input(text, cx);
13028 }
13029
13030 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13031 let Some(provider) = self.semantics_provider.as_ref() else {
13032 return false;
13033 };
13034
13035 let mut supports = false;
13036 self.buffer().read(cx).for_each_buffer(|buffer| {
13037 supports |= provider.supports_inlay_hints(buffer, cx);
13038 });
13039 supports
13040 }
13041
13042 pub fn focus(&self, cx: &mut WindowContext) {
13043 cx.focus(&self.focus_handle)
13044 }
13045
13046 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13047 self.focus_handle.is_focused(cx)
13048 }
13049
13050 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13051 cx.emit(EditorEvent::Focused);
13052
13053 if let Some(descendant) = self
13054 .last_focused_descendant
13055 .take()
13056 .and_then(|descendant| descendant.upgrade())
13057 {
13058 cx.focus(&descendant);
13059 } else {
13060 if let Some(blame) = self.blame.as_ref() {
13061 blame.update(cx, GitBlame::focus)
13062 }
13063
13064 self.blink_manager.update(cx, BlinkManager::enable);
13065 self.show_cursor_names(cx);
13066 self.buffer.update(cx, |buffer, cx| {
13067 buffer.finalize_last_transaction(cx);
13068 if self.leader_peer_id.is_none() {
13069 buffer.set_active_selections(
13070 &self.selections.disjoint_anchors(),
13071 self.selections.line_mode,
13072 self.cursor_shape,
13073 cx,
13074 );
13075 }
13076 });
13077 }
13078 }
13079
13080 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13081 cx.emit(EditorEvent::FocusedIn)
13082 }
13083
13084 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13085 if event.blurred != self.focus_handle {
13086 self.last_focused_descendant = Some(event.blurred);
13087 }
13088 }
13089
13090 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13091 self.blink_manager.update(cx, BlinkManager::disable);
13092 self.buffer
13093 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13094
13095 if let Some(blame) = self.blame.as_ref() {
13096 blame.update(cx, GitBlame::blur)
13097 }
13098 if !self.hover_state.focused(cx) {
13099 hide_hover(self, cx);
13100 }
13101
13102 self.hide_context_menu(cx);
13103 cx.emit(EditorEvent::Blurred);
13104 cx.notify();
13105 }
13106
13107 pub fn register_action<A: Action>(
13108 &mut self,
13109 listener: impl Fn(&A, &mut WindowContext) + 'static,
13110 ) -> Subscription {
13111 let id = self.next_editor_action_id.post_inc();
13112 let listener = Arc::new(listener);
13113 self.editor_actions.borrow_mut().insert(
13114 id,
13115 Box::new(move |cx| {
13116 let cx = cx.window_context();
13117 let listener = listener.clone();
13118 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13119 let action = action.downcast_ref().unwrap();
13120 if phase == DispatchPhase::Bubble {
13121 listener(action, cx)
13122 }
13123 })
13124 }),
13125 );
13126
13127 let editor_actions = self.editor_actions.clone();
13128 Subscription::new(move || {
13129 editor_actions.borrow_mut().remove(&id);
13130 })
13131 }
13132
13133 pub fn file_header_size(&self) -> u32 {
13134 FILE_HEADER_HEIGHT
13135 }
13136
13137 pub fn revert(
13138 &mut self,
13139 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13140 cx: &mut ViewContext<Self>,
13141 ) {
13142 self.buffer().update(cx, |multi_buffer, cx| {
13143 for (buffer_id, changes) in revert_changes {
13144 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13145 buffer.update(cx, |buffer, cx| {
13146 buffer.edit(
13147 changes.into_iter().map(|(range, text)| {
13148 (range, text.to_string().map(Arc::<str>::from))
13149 }),
13150 None,
13151 cx,
13152 );
13153 });
13154 }
13155 }
13156 });
13157 self.change_selections(None, cx, |selections| selections.refresh());
13158 }
13159
13160 pub fn to_pixel_point(
13161 &mut self,
13162 source: multi_buffer::Anchor,
13163 editor_snapshot: &EditorSnapshot,
13164 cx: &mut ViewContext<Self>,
13165 ) -> Option<gpui::Point<Pixels>> {
13166 let source_point = source.to_display_point(editor_snapshot);
13167 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13168 }
13169
13170 pub fn display_to_pixel_point(
13171 &mut self,
13172 source: DisplayPoint,
13173 editor_snapshot: &EditorSnapshot,
13174 cx: &mut ViewContext<Self>,
13175 ) -> Option<gpui::Point<Pixels>> {
13176 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13177 let text_layout_details = self.text_layout_details(cx);
13178 let scroll_top = text_layout_details
13179 .scroll_anchor
13180 .scroll_position(editor_snapshot)
13181 .y;
13182
13183 if source.row().as_f32() < scroll_top.floor() {
13184 return None;
13185 }
13186 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13187 let source_y = line_height * (source.row().as_f32() - scroll_top);
13188 Some(gpui::Point::new(source_x, source_y))
13189 }
13190
13191 pub fn has_active_completions_menu(&self) -> bool {
13192 self.context_menu.read().as_ref().map_or(false, |menu| {
13193 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13194 })
13195 }
13196
13197 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13198 self.addons
13199 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13200 }
13201
13202 pub fn unregister_addon<T: Addon>(&mut self) {
13203 self.addons.remove(&std::any::TypeId::of::<T>());
13204 }
13205
13206 pub fn addon<T: Addon>(&self) -> Option<&T> {
13207 let type_id = std::any::TypeId::of::<T>();
13208 self.addons
13209 .get(&type_id)
13210 .and_then(|item| item.to_any().downcast_ref::<T>())
13211 }
13212}
13213
13214fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13215 let tab_size = tab_size.get() as usize;
13216 let mut width = offset;
13217
13218 for ch in text.chars() {
13219 width += if ch == '\t' {
13220 tab_size - (width % tab_size)
13221 } else {
13222 1
13223 };
13224 }
13225
13226 width - offset
13227}
13228
13229#[cfg(test)]
13230mod tests {
13231 use super::*;
13232
13233 #[test]
13234 fn test_string_size_with_expanded_tabs() {
13235 let nz = |val| NonZeroU32::new(val).unwrap();
13236 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13237 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13238 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13239 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13240 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13241 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13242 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13243 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13244 }
13245}
13246
13247/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13248struct WordBreakingTokenizer<'a> {
13249 input: &'a str,
13250}
13251
13252impl<'a> WordBreakingTokenizer<'a> {
13253 fn new(input: &'a str) -> Self {
13254 Self { input }
13255 }
13256}
13257
13258fn is_char_ideographic(ch: char) -> bool {
13259 use unicode_script::Script::*;
13260 use unicode_script::UnicodeScript;
13261 matches!(ch.script(), Han | Tangut | Yi)
13262}
13263
13264fn is_grapheme_ideographic(text: &str) -> bool {
13265 text.chars().any(is_char_ideographic)
13266}
13267
13268fn is_grapheme_whitespace(text: &str) -> bool {
13269 text.chars().any(|x| x.is_whitespace())
13270}
13271
13272fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13273 text.chars().next().map_or(false, |ch| {
13274 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13275 })
13276}
13277
13278#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13279struct WordBreakToken<'a> {
13280 token: &'a str,
13281 grapheme_len: usize,
13282 is_whitespace: bool,
13283}
13284
13285impl<'a> Iterator for WordBreakingTokenizer<'a> {
13286 /// Yields a span, the count of graphemes in the token, and whether it was
13287 /// whitespace. Note that it also breaks at word boundaries.
13288 type Item = WordBreakToken<'a>;
13289
13290 fn next(&mut self) -> Option<Self::Item> {
13291 use unicode_segmentation::UnicodeSegmentation;
13292 if self.input.is_empty() {
13293 return None;
13294 }
13295
13296 let mut iter = self.input.graphemes(true).peekable();
13297 let mut offset = 0;
13298 let mut graphemes = 0;
13299 if let Some(first_grapheme) = iter.next() {
13300 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13301 offset += first_grapheme.len();
13302 graphemes += 1;
13303 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13304 if let Some(grapheme) = iter.peek().copied() {
13305 if should_stay_with_preceding_ideograph(grapheme) {
13306 offset += grapheme.len();
13307 graphemes += 1;
13308 }
13309 }
13310 } else {
13311 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13312 let mut next_word_bound = words.peek().copied();
13313 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13314 next_word_bound = words.next();
13315 }
13316 while let Some(grapheme) = iter.peek().copied() {
13317 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13318 break;
13319 };
13320 if is_grapheme_whitespace(grapheme) != is_whitespace {
13321 break;
13322 };
13323 offset += grapheme.len();
13324 graphemes += 1;
13325 iter.next();
13326 }
13327 }
13328 let token = &self.input[..offset];
13329 self.input = &self.input[offset..];
13330 if is_whitespace {
13331 Some(WordBreakToken {
13332 token: " ",
13333 grapheme_len: 1,
13334 is_whitespace: true,
13335 })
13336 } else {
13337 Some(WordBreakToken {
13338 token,
13339 grapheme_len: graphemes,
13340 is_whitespace: false,
13341 })
13342 }
13343 } else {
13344 None
13345 }
13346 }
13347}
13348
13349#[test]
13350fn test_word_breaking_tokenizer() {
13351 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13352 ("", &[]),
13353 (" ", &[(" ", 1, true)]),
13354 ("Ʒ", &[("Ʒ", 1, false)]),
13355 ("Ǽ", &[("Ǽ", 1, false)]),
13356 ("⋑", &[("⋑", 1, false)]),
13357 ("⋑⋑", &[("⋑⋑", 2, false)]),
13358 (
13359 "原理,进而",
13360 &[
13361 ("原", 1, false),
13362 ("理,", 2, false),
13363 ("进", 1, false),
13364 ("而", 1, false),
13365 ],
13366 ),
13367 (
13368 "hello world",
13369 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13370 ),
13371 (
13372 "hello, world",
13373 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13374 ),
13375 (
13376 " hello world",
13377 &[
13378 (" ", 1, true),
13379 ("hello", 5, false),
13380 (" ", 1, true),
13381 ("world", 5, false),
13382 ],
13383 ),
13384 (
13385 "这是什么 \n 钢笔",
13386 &[
13387 ("这", 1, false),
13388 ("是", 1, false),
13389 ("什", 1, false),
13390 ("么", 1, false),
13391 (" ", 1, true),
13392 ("钢", 1, false),
13393 ("笔", 1, false),
13394 ],
13395 ),
13396 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13397 ];
13398
13399 for (input, result) in tests {
13400 assert_eq!(
13401 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13402 result
13403 .iter()
13404 .copied()
13405 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13406 token,
13407 grapheme_len,
13408 is_whitespace,
13409 })
13410 .collect::<Vec<_>>()
13411 );
13412 }
13413}
13414
13415fn wrap_with_prefix(
13416 line_prefix: String,
13417 unwrapped_text: String,
13418 wrap_column: usize,
13419 tab_size: NonZeroU32,
13420) -> String {
13421 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13422 let mut wrapped_text = String::new();
13423 let mut current_line = line_prefix.clone();
13424
13425 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13426 let mut current_line_len = line_prefix_len;
13427 for WordBreakToken {
13428 token,
13429 grapheme_len,
13430 is_whitespace,
13431 } in tokenizer
13432 {
13433 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13434 wrapped_text.push_str(current_line.trim_end());
13435 wrapped_text.push('\n');
13436 current_line.truncate(line_prefix.len());
13437 current_line_len = line_prefix_len;
13438 if !is_whitespace {
13439 current_line.push_str(token);
13440 current_line_len += grapheme_len;
13441 }
13442 } else if !is_whitespace {
13443 current_line.push_str(token);
13444 current_line_len += grapheme_len;
13445 } else if current_line_len != line_prefix_len {
13446 current_line.push(' ');
13447 current_line_len += 1;
13448 }
13449 }
13450
13451 if !current_line.is_empty() {
13452 wrapped_text.push_str(¤t_line);
13453 }
13454 wrapped_text
13455}
13456
13457#[test]
13458fn test_wrap_with_prefix() {
13459 assert_eq!(
13460 wrap_with_prefix(
13461 "# ".to_string(),
13462 "abcdefg".to_string(),
13463 4,
13464 NonZeroU32::new(4).unwrap()
13465 ),
13466 "# abcdefg"
13467 );
13468 assert_eq!(
13469 wrap_with_prefix(
13470 "".to_string(),
13471 "\thello world".to_string(),
13472 8,
13473 NonZeroU32::new(4).unwrap()
13474 ),
13475 "hello\nworld"
13476 );
13477 assert_eq!(
13478 wrap_with_prefix(
13479 "// ".to_string(),
13480 "xx \nyy zz aa bb cc".to_string(),
13481 12,
13482 NonZeroU32::new(4).unwrap()
13483 ),
13484 "// xx yy zz\n// aa bb cc"
13485 );
13486 assert_eq!(
13487 wrap_with_prefix(
13488 String::new(),
13489 "这是什么 \n 钢笔".to_string(),
13490 3,
13491 NonZeroU32::new(4).unwrap()
13492 ),
13493 "这是什\n么 钢\n笔"
13494 );
13495}
13496
13497fn hunks_for_selections(
13498 multi_buffer_snapshot: &MultiBufferSnapshot,
13499 selections: &[Selection<Anchor>],
13500) -> Vec<MultiBufferDiffHunk> {
13501 let buffer_rows_for_selections = selections.iter().map(|selection| {
13502 let head = selection.head();
13503 let tail = selection.tail();
13504 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13505 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13506 if start > end {
13507 end..start
13508 } else {
13509 start..end
13510 }
13511 });
13512
13513 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13514}
13515
13516pub fn hunks_for_rows(
13517 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13518 multi_buffer_snapshot: &MultiBufferSnapshot,
13519) -> Vec<MultiBufferDiffHunk> {
13520 let mut hunks = Vec::new();
13521 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13522 HashMap::default();
13523 for selected_multi_buffer_rows in rows {
13524 let query_rows =
13525 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13526 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13527 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13528 // when the caret is just above or just below the deleted hunk.
13529 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13530 let related_to_selection = if allow_adjacent {
13531 hunk.row_range.overlaps(&query_rows)
13532 || hunk.row_range.start == query_rows.end
13533 || hunk.row_range.end == query_rows.start
13534 } else {
13535 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13536 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13537 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13538 || selected_multi_buffer_rows.end == hunk.row_range.start
13539 };
13540 if related_to_selection {
13541 if !processed_buffer_rows
13542 .entry(hunk.buffer_id)
13543 .or_default()
13544 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13545 {
13546 continue;
13547 }
13548 hunks.push(hunk);
13549 }
13550 }
13551 }
13552
13553 hunks
13554}
13555
13556pub trait CollaborationHub {
13557 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13558 fn user_participant_indices<'a>(
13559 &self,
13560 cx: &'a AppContext,
13561 ) -> &'a HashMap<u64, ParticipantIndex>;
13562 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13563}
13564
13565impl CollaborationHub for Model<Project> {
13566 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13567 self.read(cx).collaborators()
13568 }
13569
13570 fn user_participant_indices<'a>(
13571 &self,
13572 cx: &'a AppContext,
13573 ) -> &'a HashMap<u64, ParticipantIndex> {
13574 self.read(cx).user_store().read(cx).participant_indices()
13575 }
13576
13577 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13578 let this = self.read(cx);
13579 let user_ids = this.collaborators().values().map(|c| c.user_id);
13580 this.user_store().read_with(cx, |user_store, cx| {
13581 user_store.participant_names(user_ids, cx)
13582 })
13583 }
13584}
13585
13586pub trait SemanticsProvider {
13587 fn hover(
13588 &self,
13589 buffer: &Model<Buffer>,
13590 position: text::Anchor,
13591 cx: &mut AppContext,
13592 ) -> Option<Task<Vec<project::Hover>>>;
13593
13594 fn inlay_hints(
13595 &self,
13596 buffer_handle: Model<Buffer>,
13597 range: Range<text::Anchor>,
13598 cx: &mut AppContext,
13599 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13600
13601 fn resolve_inlay_hint(
13602 &self,
13603 hint: InlayHint,
13604 buffer_handle: Model<Buffer>,
13605 server_id: LanguageServerId,
13606 cx: &mut AppContext,
13607 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13608
13609 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13610
13611 fn document_highlights(
13612 &self,
13613 buffer: &Model<Buffer>,
13614 position: text::Anchor,
13615 cx: &mut AppContext,
13616 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13617
13618 fn definitions(
13619 &self,
13620 buffer: &Model<Buffer>,
13621 position: text::Anchor,
13622 kind: GotoDefinitionKind,
13623 cx: &mut AppContext,
13624 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13625
13626 fn range_for_rename(
13627 &self,
13628 buffer: &Model<Buffer>,
13629 position: text::Anchor,
13630 cx: &mut AppContext,
13631 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13632
13633 fn perform_rename(
13634 &self,
13635 buffer: &Model<Buffer>,
13636 position: text::Anchor,
13637 new_name: String,
13638 cx: &mut AppContext,
13639 ) -> Option<Task<Result<ProjectTransaction>>>;
13640}
13641
13642pub trait CompletionProvider {
13643 fn completions(
13644 &self,
13645 buffer: &Model<Buffer>,
13646 buffer_position: text::Anchor,
13647 trigger: CompletionContext,
13648 cx: &mut ViewContext<Editor>,
13649 ) -> Task<Result<Vec<Completion>>>;
13650
13651 fn resolve_completions(
13652 &self,
13653 buffer: Model<Buffer>,
13654 completion_indices: Vec<usize>,
13655 completions: Arc<RwLock<Box<[Completion]>>>,
13656 cx: &mut ViewContext<Editor>,
13657 ) -> Task<Result<bool>>;
13658
13659 fn apply_additional_edits_for_completion(
13660 &self,
13661 buffer: Model<Buffer>,
13662 completion: Completion,
13663 push_to_history: bool,
13664 cx: &mut ViewContext<Editor>,
13665 ) -> Task<Result<Option<language::Transaction>>>;
13666
13667 fn is_completion_trigger(
13668 &self,
13669 buffer: &Model<Buffer>,
13670 position: language::Anchor,
13671 text: &str,
13672 trigger_in_words: bool,
13673 cx: &mut ViewContext<Editor>,
13674 ) -> bool;
13675
13676 fn sort_completions(&self) -> bool {
13677 true
13678 }
13679}
13680
13681pub trait CodeActionProvider {
13682 fn code_actions(
13683 &self,
13684 buffer: &Model<Buffer>,
13685 range: Range<text::Anchor>,
13686 cx: &mut WindowContext,
13687 ) -> Task<Result<Vec<CodeAction>>>;
13688
13689 fn apply_code_action(
13690 &self,
13691 buffer_handle: Model<Buffer>,
13692 action: CodeAction,
13693 excerpt_id: ExcerptId,
13694 push_to_history: bool,
13695 cx: &mut WindowContext,
13696 ) -> Task<Result<ProjectTransaction>>;
13697}
13698
13699impl CodeActionProvider for Model<Project> {
13700 fn code_actions(
13701 &self,
13702 buffer: &Model<Buffer>,
13703 range: Range<text::Anchor>,
13704 cx: &mut WindowContext,
13705 ) -> Task<Result<Vec<CodeAction>>> {
13706 self.update(cx, |project, cx| {
13707 project.code_actions(buffer, range, None, cx)
13708 })
13709 }
13710
13711 fn apply_code_action(
13712 &self,
13713 buffer_handle: Model<Buffer>,
13714 action: CodeAction,
13715 _excerpt_id: ExcerptId,
13716 push_to_history: bool,
13717 cx: &mut WindowContext,
13718 ) -> Task<Result<ProjectTransaction>> {
13719 self.update(cx, |project, cx| {
13720 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13721 })
13722 }
13723}
13724
13725fn snippet_completions(
13726 project: &Project,
13727 buffer: &Model<Buffer>,
13728 buffer_position: text::Anchor,
13729 cx: &mut AppContext,
13730) -> Vec<Completion> {
13731 let language = buffer.read(cx).language_at(buffer_position);
13732 let language_name = language.as_ref().map(|language| language.lsp_id());
13733 let snippet_store = project.snippets().read(cx);
13734 let snippets = snippet_store.snippets_for(language_name, cx);
13735
13736 if snippets.is_empty() {
13737 return vec![];
13738 }
13739 let snapshot = buffer.read(cx).text_snapshot();
13740 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13741
13742 let scope = language.map(|language| language.default_scope());
13743 let classifier = CharClassifier::new(scope).for_completion(true);
13744 let mut last_word = chars
13745 .take_while(|c| classifier.is_word(*c))
13746 .collect::<String>();
13747 last_word = last_word.chars().rev().collect();
13748 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13749 let to_lsp = |point: &text::Anchor| {
13750 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13751 point_to_lsp(end)
13752 };
13753 let lsp_end = to_lsp(&buffer_position);
13754 snippets
13755 .into_iter()
13756 .filter_map(|snippet| {
13757 let matching_prefix = snippet
13758 .prefix
13759 .iter()
13760 .find(|prefix| prefix.starts_with(&last_word))?;
13761 let start = as_offset - last_word.len();
13762 let start = snapshot.anchor_before(start);
13763 let range = start..buffer_position;
13764 let lsp_start = to_lsp(&start);
13765 let lsp_range = lsp::Range {
13766 start: lsp_start,
13767 end: lsp_end,
13768 };
13769 Some(Completion {
13770 old_range: range,
13771 new_text: snippet.body.clone(),
13772 label: CodeLabel {
13773 text: matching_prefix.clone(),
13774 runs: vec![],
13775 filter_range: 0..matching_prefix.len(),
13776 },
13777 server_id: LanguageServerId(usize::MAX),
13778 documentation: snippet.description.clone().map(Documentation::SingleLine),
13779 lsp_completion: lsp::CompletionItem {
13780 label: snippet.prefix.first().unwrap().clone(),
13781 kind: Some(CompletionItemKind::SNIPPET),
13782 label_details: snippet.description.as_ref().map(|description| {
13783 lsp::CompletionItemLabelDetails {
13784 detail: Some(description.clone()),
13785 description: None,
13786 }
13787 }),
13788 insert_text_format: Some(InsertTextFormat::SNIPPET),
13789 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13790 lsp::InsertReplaceEdit {
13791 new_text: snippet.body.clone(),
13792 insert: lsp_range,
13793 replace: lsp_range,
13794 },
13795 )),
13796 filter_text: Some(snippet.body.clone()),
13797 sort_text: Some(char::MAX.to_string()),
13798 ..Default::default()
13799 },
13800 confirm: None,
13801 })
13802 })
13803 .collect()
13804}
13805
13806impl CompletionProvider for Model<Project> {
13807 fn completions(
13808 &self,
13809 buffer: &Model<Buffer>,
13810 buffer_position: text::Anchor,
13811 options: CompletionContext,
13812 cx: &mut ViewContext<Editor>,
13813 ) -> Task<Result<Vec<Completion>>> {
13814 self.update(cx, |project, cx| {
13815 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13816 let project_completions = project.completions(buffer, buffer_position, options, cx);
13817 cx.background_executor().spawn(async move {
13818 let mut completions = project_completions.await?;
13819 //let snippets = snippets.into_iter().;
13820 completions.extend(snippets);
13821 Ok(completions)
13822 })
13823 })
13824 }
13825
13826 fn resolve_completions(
13827 &self,
13828 buffer: Model<Buffer>,
13829 completion_indices: Vec<usize>,
13830 completions: Arc<RwLock<Box<[Completion]>>>,
13831 cx: &mut ViewContext<Editor>,
13832 ) -> Task<Result<bool>> {
13833 self.update(cx, |project, cx| {
13834 project.resolve_completions(buffer, completion_indices, completions, cx)
13835 })
13836 }
13837
13838 fn apply_additional_edits_for_completion(
13839 &self,
13840 buffer: Model<Buffer>,
13841 completion: Completion,
13842 push_to_history: bool,
13843 cx: &mut ViewContext<Editor>,
13844 ) -> Task<Result<Option<language::Transaction>>> {
13845 self.update(cx, |project, cx| {
13846 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13847 })
13848 }
13849
13850 fn is_completion_trigger(
13851 &self,
13852 buffer: &Model<Buffer>,
13853 position: language::Anchor,
13854 text: &str,
13855 trigger_in_words: bool,
13856 cx: &mut ViewContext<Editor>,
13857 ) -> bool {
13858 if !EditorSettings::get_global(cx).show_completions_on_input {
13859 return false;
13860 }
13861
13862 let mut chars = text.chars();
13863 let char = if let Some(char) = chars.next() {
13864 char
13865 } else {
13866 return false;
13867 };
13868 if chars.next().is_some() {
13869 return false;
13870 }
13871
13872 let buffer = buffer.read(cx);
13873 let classifier = buffer
13874 .snapshot()
13875 .char_classifier_at(position)
13876 .for_completion(true);
13877 if trigger_in_words && classifier.is_word(char) {
13878 return true;
13879 }
13880
13881 buffer.completion_triggers().contains(text)
13882 }
13883}
13884
13885impl SemanticsProvider for Model<Project> {
13886 fn hover(
13887 &self,
13888 buffer: &Model<Buffer>,
13889 position: text::Anchor,
13890 cx: &mut AppContext,
13891 ) -> Option<Task<Vec<project::Hover>>> {
13892 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13893 }
13894
13895 fn document_highlights(
13896 &self,
13897 buffer: &Model<Buffer>,
13898 position: text::Anchor,
13899 cx: &mut AppContext,
13900 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13901 Some(self.update(cx, |project, cx| {
13902 project.document_highlights(buffer, position, cx)
13903 }))
13904 }
13905
13906 fn definitions(
13907 &self,
13908 buffer: &Model<Buffer>,
13909 position: text::Anchor,
13910 kind: GotoDefinitionKind,
13911 cx: &mut AppContext,
13912 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13913 Some(self.update(cx, |project, cx| match kind {
13914 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13915 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13916 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13917 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13918 }))
13919 }
13920
13921 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13922 // TODO: make this work for remote projects
13923 self.read(cx)
13924 .language_servers_for_buffer(buffer.read(cx), cx)
13925 .any(
13926 |(_, server)| match server.capabilities().inlay_hint_provider {
13927 Some(lsp::OneOf::Left(enabled)) => enabled,
13928 Some(lsp::OneOf::Right(_)) => true,
13929 None => false,
13930 },
13931 )
13932 }
13933
13934 fn inlay_hints(
13935 &self,
13936 buffer_handle: Model<Buffer>,
13937 range: Range<text::Anchor>,
13938 cx: &mut AppContext,
13939 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13940 Some(self.update(cx, |project, cx| {
13941 project.inlay_hints(buffer_handle, range, cx)
13942 }))
13943 }
13944
13945 fn resolve_inlay_hint(
13946 &self,
13947 hint: InlayHint,
13948 buffer_handle: Model<Buffer>,
13949 server_id: LanguageServerId,
13950 cx: &mut AppContext,
13951 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13952 Some(self.update(cx, |project, cx| {
13953 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13954 }))
13955 }
13956
13957 fn range_for_rename(
13958 &self,
13959 buffer: &Model<Buffer>,
13960 position: text::Anchor,
13961 cx: &mut AppContext,
13962 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13963 Some(self.update(cx, |project, cx| {
13964 project.prepare_rename(buffer.clone(), position, cx)
13965 }))
13966 }
13967
13968 fn perform_rename(
13969 &self,
13970 buffer: &Model<Buffer>,
13971 position: text::Anchor,
13972 new_name: String,
13973 cx: &mut AppContext,
13974 ) -> Option<Task<Result<ProjectTransaction>>> {
13975 Some(self.update(cx, |project, cx| {
13976 project.perform_rename(buffer.clone(), position, new_name, cx)
13977 }))
13978 }
13979}
13980
13981fn inlay_hint_settings(
13982 location: Anchor,
13983 snapshot: &MultiBufferSnapshot,
13984 cx: &mut ViewContext<'_, Editor>,
13985) -> InlayHintSettings {
13986 let file = snapshot.file_at(location);
13987 let language = snapshot.language_at(location).map(|l| l.name());
13988 language_settings(language, file, cx).inlay_hints
13989}
13990
13991fn consume_contiguous_rows(
13992 contiguous_row_selections: &mut Vec<Selection<Point>>,
13993 selection: &Selection<Point>,
13994 display_map: &DisplaySnapshot,
13995 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13996) -> (MultiBufferRow, MultiBufferRow) {
13997 contiguous_row_selections.push(selection.clone());
13998 let start_row = MultiBufferRow(selection.start.row);
13999 let mut end_row = ending_row(selection, display_map);
14000
14001 while let Some(next_selection) = selections.peek() {
14002 if next_selection.start.row <= end_row.0 {
14003 end_row = ending_row(next_selection, display_map);
14004 contiguous_row_selections.push(selections.next().unwrap().clone());
14005 } else {
14006 break;
14007 }
14008 }
14009 (start_row, end_row)
14010}
14011
14012fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14013 if next_selection.end.column > 0 || next_selection.is_empty() {
14014 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14015 } else {
14016 MultiBufferRow(next_selection.end.row)
14017 }
14018}
14019
14020impl EditorSnapshot {
14021 pub fn remote_selections_in_range<'a>(
14022 &'a self,
14023 range: &'a Range<Anchor>,
14024 collaboration_hub: &dyn CollaborationHub,
14025 cx: &'a AppContext,
14026 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14027 let participant_names = collaboration_hub.user_names(cx);
14028 let participant_indices = collaboration_hub.user_participant_indices(cx);
14029 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14030 let collaborators_by_replica_id = collaborators_by_peer_id
14031 .iter()
14032 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14033 .collect::<HashMap<_, _>>();
14034 self.buffer_snapshot
14035 .selections_in_range(range, false)
14036 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14037 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14038 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14039 let user_name = participant_names.get(&collaborator.user_id).cloned();
14040 Some(RemoteSelection {
14041 replica_id,
14042 selection,
14043 cursor_shape,
14044 line_mode,
14045 participant_index,
14046 peer_id: collaborator.peer_id,
14047 user_name,
14048 })
14049 })
14050 }
14051
14052 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14053 self.display_snapshot.buffer_snapshot.language_at(position)
14054 }
14055
14056 pub fn is_focused(&self) -> bool {
14057 self.is_focused
14058 }
14059
14060 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14061 self.placeholder_text.as_ref()
14062 }
14063
14064 pub fn scroll_position(&self) -> gpui::Point<f32> {
14065 self.scroll_anchor.scroll_position(&self.display_snapshot)
14066 }
14067
14068 fn gutter_dimensions(
14069 &self,
14070 font_id: FontId,
14071 font_size: Pixels,
14072 em_width: Pixels,
14073 em_advance: Pixels,
14074 max_line_number_width: Pixels,
14075 cx: &AppContext,
14076 ) -> GutterDimensions {
14077 if !self.show_gutter {
14078 return GutterDimensions::default();
14079 }
14080 let descent = cx.text_system().descent(font_id, font_size);
14081
14082 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14083 matches!(
14084 ProjectSettings::get_global(cx).git.git_gutter,
14085 Some(GitGutterSetting::TrackedFiles)
14086 )
14087 });
14088 let gutter_settings = EditorSettings::get_global(cx).gutter;
14089 let show_line_numbers = self
14090 .show_line_numbers
14091 .unwrap_or(gutter_settings.line_numbers);
14092 let line_gutter_width = if show_line_numbers {
14093 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14094 let min_width_for_number_on_gutter = em_advance * 4.0;
14095 max_line_number_width.max(min_width_for_number_on_gutter)
14096 } else {
14097 0.0.into()
14098 };
14099
14100 let show_code_actions = self
14101 .show_code_actions
14102 .unwrap_or(gutter_settings.code_actions);
14103
14104 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14105
14106 let git_blame_entries_width =
14107 self.git_blame_gutter_max_author_length
14108 .map(|max_author_length| {
14109 // Length of the author name, but also space for the commit hash,
14110 // the spacing and the timestamp.
14111 let max_char_count = max_author_length
14112 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14113 + 7 // length of commit sha
14114 + 14 // length of max relative timestamp ("60 minutes ago")
14115 + 4; // gaps and margins
14116
14117 em_advance * max_char_count
14118 });
14119
14120 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14121 left_padding += if show_code_actions || show_runnables {
14122 em_width * 3.0
14123 } else if show_git_gutter && show_line_numbers {
14124 em_width * 2.0
14125 } else if show_git_gutter || show_line_numbers {
14126 em_width
14127 } else {
14128 px(0.)
14129 };
14130
14131 let right_padding = if gutter_settings.folds && show_line_numbers {
14132 em_width * 4.0
14133 } else if gutter_settings.folds {
14134 em_width * 3.0
14135 } else if show_line_numbers {
14136 em_width
14137 } else {
14138 px(0.)
14139 };
14140
14141 GutterDimensions {
14142 left_padding,
14143 right_padding,
14144 width: line_gutter_width + left_padding + right_padding,
14145 margin: -descent,
14146 git_blame_entries_width,
14147 }
14148 }
14149
14150 pub fn render_crease_toggle(
14151 &self,
14152 buffer_row: MultiBufferRow,
14153 row_contains_cursor: bool,
14154 editor: View<Editor>,
14155 cx: &mut WindowContext,
14156 ) -> Option<AnyElement> {
14157 let folded = self.is_line_folded(buffer_row);
14158 let mut is_foldable = false;
14159
14160 if let Some(crease) = self
14161 .crease_snapshot
14162 .query_row(buffer_row, &self.buffer_snapshot)
14163 {
14164 is_foldable = true;
14165 match crease {
14166 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14167 if let Some(render_toggle) = render_toggle {
14168 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14169 if folded {
14170 editor.update(cx, |editor, cx| {
14171 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14172 });
14173 } else {
14174 editor.update(cx, |editor, cx| {
14175 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14176 });
14177 }
14178 });
14179 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14180 }
14181 }
14182 }
14183 }
14184
14185 is_foldable |= self.starts_indent(buffer_row);
14186
14187 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14188 Some(
14189 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14190 .selected(folded)
14191 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14192 if folded {
14193 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14194 } else {
14195 this.fold_at(&FoldAt { buffer_row }, cx);
14196 }
14197 }))
14198 .into_any_element(),
14199 )
14200 } else {
14201 None
14202 }
14203 }
14204
14205 pub fn render_crease_trailer(
14206 &self,
14207 buffer_row: MultiBufferRow,
14208 cx: &mut WindowContext,
14209 ) -> Option<AnyElement> {
14210 let folded = self.is_line_folded(buffer_row);
14211 if let Crease::Inline { render_trailer, .. } = self
14212 .crease_snapshot
14213 .query_row(buffer_row, &self.buffer_snapshot)?
14214 {
14215 let render_trailer = render_trailer.as_ref()?;
14216 Some(render_trailer(buffer_row, folded, cx))
14217 } else {
14218 None
14219 }
14220 }
14221}
14222
14223impl Deref for EditorSnapshot {
14224 type Target = DisplaySnapshot;
14225
14226 fn deref(&self) -> &Self::Target {
14227 &self.display_snapshot
14228 }
14229}
14230
14231#[derive(Clone, Debug, PartialEq, Eq)]
14232pub enum EditorEvent {
14233 InputIgnored {
14234 text: Arc<str>,
14235 },
14236 InputHandled {
14237 utf16_range_to_replace: Option<Range<isize>>,
14238 text: Arc<str>,
14239 },
14240 ExcerptsAdded {
14241 buffer: Model<Buffer>,
14242 predecessor: ExcerptId,
14243 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14244 },
14245 ExcerptsRemoved {
14246 ids: Vec<ExcerptId>,
14247 },
14248 ExcerptsEdited {
14249 ids: Vec<ExcerptId>,
14250 },
14251 ExcerptsExpanded {
14252 ids: Vec<ExcerptId>,
14253 },
14254 BufferEdited,
14255 Edited {
14256 transaction_id: clock::Lamport,
14257 },
14258 Reparsed(BufferId),
14259 Focused,
14260 FocusedIn,
14261 Blurred,
14262 DirtyChanged,
14263 Saved,
14264 TitleChanged,
14265 DiffBaseChanged,
14266 SelectionsChanged {
14267 local: bool,
14268 },
14269 ScrollPositionChanged {
14270 local: bool,
14271 autoscroll: bool,
14272 },
14273 Closed,
14274 TransactionUndone {
14275 transaction_id: clock::Lamport,
14276 },
14277 TransactionBegun {
14278 transaction_id: clock::Lamport,
14279 },
14280 Reloaded,
14281 CursorShapeChanged,
14282}
14283
14284impl EventEmitter<EditorEvent> for Editor {}
14285
14286impl FocusableView for Editor {
14287 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14288 self.focus_handle.clone()
14289 }
14290}
14291
14292impl Render for Editor {
14293 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14294 let settings = ThemeSettings::get_global(cx);
14295
14296 let mut text_style = match self.mode {
14297 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14298 color: cx.theme().colors().editor_foreground,
14299 font_family: settings.ui_font.family.clone(),
14300 font_features: settings.ui_font.features.clone(),
14301 font_fallbacks: settings.ui_font.fallbacks.clone(),
14302 font_size: rems(0.875).into(),
14303 font_weight: settings.ui_font.weight,
14304 line_height: relative(settings.buffer_line_height.value()),
14305 ..Default::default()
14306 },
14307 EditorMode::Full => TextStyle {
14308 color: cx.theme().colors().editor_foreground,
14309 font_family: settings.buffer_font.family.clone(),
14310 font_features: settings.buffer_font.features.clone(),
14311 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14312 font_size: settings.buffer_font_size(cx).into(),
14313 font_weight: settings.buffer_font.weight,
14314 line_height: relative(settings.buffer_line_height.value()),
14315 ..Default::default()
14316 },
14317 };
14318 if let Some(text_style_refinement) = &self.text_style_refinement {
14319 text_style.refine(text_style_refinement)
14320 }
14321
14322 let background = match self.mode {
14323 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14324 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14325 EditorMode::Full => cx.theme().colors().editor_background,
14326 };
14327
14328 EditorElement::new(
14329 cx.view(),
14330 EditorStyle {
14331 background,
14332 local_player: cx.theme().players().local(),
14333 text: text_style,
14334 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14335 syntax: cx.theme().syntax().clone(),
14336 status: cx.theme().status().clone(),
14337 inlay_hints_style: make_inlay_hints_style(cx),
14338 suggestions_style: HighlightStyle {
14339 color: Some(cx.theme().status().predictive),
14340 ..HighlightStyle::default()
14341 },
14342 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14343 },
14344 )
14345 }
14346}
14347
14348impl ViewInputHandler for Editor {
14349 fn text_for_range(
14350 &mut self,
14351 range_utf16: Range<usize>,
14352 adjusted_range: &mut Option<Range<usize>>,
14353 cx: &mut ViewContext<Self>,
14354 ) -> Option<String> {
14355 let snapshot = self.buffer.read(cx).read(cx);
14356 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14357 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14358 if (start.0..end.0) != range_utf16 {
14359 adjusted_range.replace(start.0..end.0);
14360 }
14361 Some(snapshot.text_for_range(start..end).collect())
14362 }
14363
14364 fn selected_text_range(
14365 &mut self,
14366 ignore_disabled_input: bool,
14367 cx: &mut ViewContext<Self>,
14368 ) -> Option<UTF16Selection> {
14369 // Prevent the IME menu from appearing when holding down an alphabetic key
14370 // while input is disabled.
14371 if !ignore_disabled_input && !self.input_enabled {
14372 return None;
14373 }
14374
14375 let selection = self.selections.newest::<OffsetUtf16>(cx);
14376 let range = selection.range();
14377
14378 Some(UTF16Selection {
14379 range: range.start.0..range.end.0,
14380 reversed: selection.reversed,
14381 })
14382 }
14383
14384 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14385 let snapshot = self.buffer.read(cx).read(cx);
14386 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14387 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14388 }
14389
14390 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14391 self.clear_highlights::<InputComposition>(cx);
14392 self.ime_transaction.take();
14393 }
14394
14395 fn replace_text_in_range(
14396 &mut self,
14397 range_utf16: Option<Range<usize>>,
14398 text: &str,
14399 cx: &mut ViewContext<Self>,
14400 ) {
14401 if !self.input_enabled {
14402 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14403 return;
14404 }
14405
14406 self.transact(cx, |this, cx| {
14407 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14408 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14409 Some(this.selection_replacement_ranges(range_utf16, cx))
14410 } else {
14411 this.marked_text_ranges(cx)
14412 };
14413
14414 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14415 let newest_selection_id = this.selections.newest_anchor().id;
14416 this.selections
14417 .all::<OffsetUtf16>(cx)
14418 .iter()
14419 .zip(ranges_to_replace.iter())
14420 .find_map(|(selection, range)| {
14421 if selection.id == newest_selection_id {
14422 Some(
14423 (range.start.0 as isize - selection.head().0 as isize)
14424 ..(range.end.0 as isize - selection.head().0 as isize),
14425 )
14426 } else {
14427 None
14428 }
14429 })
14430 });
14431
14432 cx.emit(EditorEvent::InputHandled {
14433 utf16_range_to_replace: range_to_replace,
14434 text: text.into(),
14435 });
14436
14437 if let Some(new_selected_ranges) = new_selected_ranges {
14438 this.change_selections(None, cx, |selections| {
14439 selections.select_ranges(new_selected_ranges)
14440 });
14441 this.backspace(&Default::default(), cx);
14442 }
14443
14444 this.handle_input(text, cx);
14445 });
14446
14447 if let Some(transaction) = self.ime_transaction {
14448 self.buffer.update(cx, |buffer, cx| {
14449 buffer.group_until_transaction(transaction, cx);
14450 });
14451 }
14452
14453 self.unmark_text(cx);
14454 }
14455
14456 fn replace_and_mark_text_in_range(
14457 &mut self,
14458 range_utf16: Option<Range<usize>>,
14459 text: &str,
14460 new_selected_range_utf16: Option<Range<usize>>,
14461 cx: &mut ViewContext<Self>,
14462 ) {
14463 if !self.input_enabled {
14464 return;
14465 }
14466
14467 let transaction = self.transact(cx, |this, cx| {
14468 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14469 let snapshot = this.buffer.read(cx).read(cx);
14470 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14471 for marked_range in &mut marked_ranges {
14472 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14473 marked_range.start.0 += relative_range_utf16.start;
14474 marked_range.start =
14475 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14476 marked_range.end =
14477 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14478 }
14479 }
14480 Some(marked_ranges)
14481 } else if let Some(range_utf16) = range_utf16 {
14482 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14483 Some(this.selection_replacement_ranges(range_utf16, cx))
14484 } else {
14485 None
14486 };
14487
14488 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14489 let newest_selection_id = this.selections.newest_anchor().id;
14490 this.selections
14491 .all::<OffsetUtf16>(cx)
14492 .iter()
14493 .zip(ranges_to_replace.iter())
14494 .find_map(|(selection, range)| {
14495 if selection.id == newest_selection_id {
14496 Some(
14497 (range.start.0 as isize - selection.head().0 as isize)
14498 ..(range.end.0 as isize - selection.head().0 as isize),
14499 )
14500 } else {
14501 None
14502 }
14503 })
14504 });
14505
14506 cx.emit(EditorEvent::InputHandled {
14507 utf16_range_to_replace: range_to_replace,
14508 text: text.into(),
14509 });
14510
14511 if let Some(ranges) = ranges_to_replace {
14512 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14513 }
14514
14515 let marked_ranges = {
14516 let snapshot = this.buffer.read(cx).read(cx);
14517 this.selections
14518 .disjoint_anchors()
14519 .iter()
14520 .map(|selection| {
14521 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14522 })
14523 .collect::<Vec<_>>()
14524 };
14525
14526 if text.is_empty() {
14527 this.unmark_text(cx);
14528 } else {
14529 this.highlight_text::<InputComposition>(
14530 marked_ranges.clone(),
14531 HighlightStyle {
14532 underline: Some(UnderlineStyle {
14533 thickness: px(1.),
14534 color: None,
14535 wavy: false,
14536 }),
14537 ..Default::default()
14538 },
14539 cx,
14540 );
14541 }
14542
14543 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14544 let use_autoclose = this.use_autoclose;
14545 let use_auto_surround = this.use_auto_surround;
14546 this.set_use_autoclose(false);
14547 this.set_use_auto_surround(false);
14548 this.handle_input(text, cx);
14549 this.set_use_autoclose(use_autoclose);
14550 this.set_use_auto_surround(use_auto_surround);
14551
14552 if let Some(new_selected_range) = new_selected_range_utf16 {
14553 let snapshot = this.buffer.read(cx).read(cx);
14554 let new_selected_ranges = marked_ranges
14555 .into_iter()
14556 .map(|marked_range| {
14557 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14558 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14559 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14560 snapshot.clip_offset_utf16(new_start, Bias::Left)
14561 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14562 })
14563 .collect::<Vec<_>>();
14564
14565 drop(snapshot);
14566 this.change_selections(None, cx, |selections| {
14567 selections.select_ranges(new_selected_ranges)
14568 });
14569 }
14570 });
14571
14572 self.ime_transaction = self.ime_transaction.or(transaction);
14573 if let Some(transaction) = self.ime_transaction {
14574 self.buffer.update(cx, |buffer, cx| {
14575 buffer.group_until_transaction(transaction, cx);
14576 });
14577 }
14578
14579 if self.text_highlights::<InputComposition>(cx).is_none() {
14580 self.ime_transaction.take();
14581 }
14582 }
14583
14584 fn bounds_for_range(
14585 &mut self,
14586 range_utf16: Range<usize>,
14587 element_bounds: gpui::Bounds<Pixels>,
14588 cx: &mut ViewContext<Self>,
14589 ) -> Option<gpui::Bounds<Pixels>> {
14590 let text_layout_details = self.text_layout_details(cx);
14591 let style = &text_layout_details.editor_style;
14592 let font_id = cx.text_system().resolve_font(&style.text.font());
14593 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14594 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14595
14596 let em_width = cx
14597 .text_system()
14598 .typographic_bounds(font_id, font_size, 'm')
14599 .unwrap()
14600 .size
14601 .width;
14602
14603 let snapshot = self.snapshot(cx);
14604 let scroll_position = snapshot.scroll_position();
14605 let scroll_left = scroll_position.x * em_width;
14606
14607 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14608 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14609 + self.gutter_dimensions.width;
14610 let y = line_height * (start.row().as_f32() - scroll_position.y);
14611
14612 Some(Bounds {
14613 origin: element_bounds.origin + point(x, y),
14614 size: size(em_width, line_height),
14615 })
14616 }
14617}
14618
14619trait SelectionExt {
14620 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14621 fn spanned_rows(
14622 &self,
14623 include_end_if_at_line_start: bool,
14624 map: &DisplaySnapshot,
14625 ) -> Range<MultiBufferRow>;
14626}
14627
14628impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14629 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14630 let start = self
14631 .start
14632 .to_point(&map.buffer_snapshot)
14633 .to_display_point(map);
14634 let end = self
14635 .end
14636 .to_point(&map.buffer_snapshot)
14637 .to_display_point(map);
14638 if self.reversed {
14639 end..start
14640 } else {
14641 start..end
14642 }
14643 }
14644
14645 fn spanned_rows(
14646 &self,
14647 include_end_if_at_line_start: bool,
14648 map: &DisplaySnapshot,
14649 ) -> Range<MultiBufferRow> {
14650 let start = self.start.to_point(&map.buffer_snapshot);
14651 let mut end = self.end.to_point(&map.buffer_snapshot);
14652 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14653 end.row -= 1;
14654 }
14655
14656 let buffer_start = map.prev_line_boundary(start).0;
14657 let buffer_end = map.next_line_boundary(end).0;
14658 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14659 }
14660}
14661
14662impl<T: InvalidationRegion> InvalidationStack<T> {
14663 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14664 where
14665 S: Clone + ToOffset,
14666 {
14667 while let Some(region) = self.last() {
14668 let all_selections_inside_invalidation_ranges =
14669 if selections.len() == region.ranges().len() {
14670 selections
14671 .iter()
14672 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14673 .all(|(selection, invalidation_range)| {
14674 let head = selection.head().to_offset(buffer);
14675 invalidation_range.start <= head && invalidation_range.end >= head
14676 })
14677 } else {
14678 false
14679 };
14680
14681 if all_selections_inside_invalidation_ranges {
14682 break;
14683 } else {
14684 self.pop();
14685 }
14686 }
14687 }
14688}
14689
14690impl<T> Default for InvalidationStack<T> {
14691 fn default() -> Self {
14692 Self(Default::default())
14693 }
14694}
14695
14696impl<T> Deref for InvalidationStack<T> {
14697 type Target = Vec<T>;
14698
14699 fn deref(&self) -> &Self::Target {
14700 &self.0
14701 }
14702}
14703
14704impl<T> DerefMut for InvalidationStack<T> {
14705 fn deref_mut(&mut self) -> &mut Self::Target {
14706 &mut self.0
14707 }
14708}
14709
14710impl InvalidationRegion for SnippetState {
14711 fn ranges(&self) -> &[Range<Anchor>] {
14712 &self.ranges[self.active_index]
14713 }
14714}
14715
14716pub fn diagnostic_block_renderer(
14717 diagnostic: Diagnostic,
14718 max_message_rows: Option<u8>,
14719 allow_closing: bool,
14720 _is_valid: bool,
14721) -> RenderBlock {
14722 let (text_without_backticks, code_ranges) =
14723 highlight_diagnostic_message(&diagnostic, max_message_rows);
14724
14725 Arc::new(move |cx: &mut BlockContext| {
14726 let group_id: SharedString = cx.block_id.to_string().into();
14727
14728 let mut text_style = cx.text_style().clone();
14729 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14730 let theme_settings = ThemeSettings::get_global(cx);
14731 text_style.font_family = theme_settings.buffer_font.family.clone();
14732 text_style.font_style = theme_settings.buffer_font.style;
14733 text_style.font_features = theme_settings.buffer_font.features.clone();
14734 text_style.font_weight = theme_settings.buffer_font.weight;
14735
14736 let multi_line_diagnostic = diagnostic.message.contains('\n');
14737
14738 let buttons = |diagnostic: &Diagnostic| {
14739 if multi_line_diagnostic {
14740 v_flex()
14741 } else {
14742 h_flex()
14743 }
14744 .when(allow_closing, |div| {
14745 div.children(diagnostic.is_primary.then(|| {
14746 IconButton::new("close-block", IconName::XCircle)
14747 .icon_color(Color::Muted)
14748 .size(ButtonSize::Compact)
14749 .style(ButtonStyle::Transparent)
14750 .visible_on_hover(group_id.clone())
14751 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14752 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14753 }))
14754 })
14755 .child(
14756 IconButton::new("copy-block", IconName::Copy)
14757 .icon_color(Color::Muted)
14758 .size(ButtonSize::Compact)
14759 .style(ButtonStyle::Transparent)
14760 .visible_on_hover(group_id.clone())
14761 .on_click({
14762 let message = diagnostic.message.clone();
14763 move |_click, cx| {
14764 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14765 }
14766 })
14767 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14768 )
14769 };
14770
14771 let icon_size = buttons(&diagnostic)
14772 .into_any_element()
14773 .layout_as_root(AvailableSpace::min_size(), cx);
14774
14775 h_flex()
14776 .id(cx.block_id)
14777 .group(group_id.clone())
14778 .relative()
14779 .size_full()
14780 .block_mouse_down()
14781 .pl(cx.gutter_dimensions.width)
14782 .w(cx.max_width - cx.gutter_dimensions.full_width())
14783 .child(
14784 div()
14785 .flex()
14786 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14787 .flex_shrink(),
14788 )
14789 .child(buttons(&diagnostic))
14790 .child(div().flex().flex_shrink_0().child(
14791 StyledText::new(text_without_backticks.clone()).with_highlights(
14792 &text_style,
14793 code_ranges.iter().map(|range| {
14794 (
14795 range.clone(),
14796 HighlightStyle {
14797 font_weight: Some(FontWeight::BOLD),
14798 ..Default::default()
14799 },
14800 )
14801 }),
14802 ),
14803 ))
14804 .into_any_element()
14805 })
14806}
14807
14808pub fn highlight_diagnostic_message(
14809 diagnostic: &Diagnostic,
14810 mut max_message_rows: Option<u8>,
14811) -> (SharedString, Vec<Range<usize>>) {
14812 let mut text_without_backticks = String::new();
14813 let mut code_ranges = Vec::new();
14814
14815 if let Some(source) = &diagnostic.source {
14816 text_without_backticks.push_str(source);
14817 code_ranges.push(0..source.len());
14818 text_without_backticks.push_str(": ");
14819 }
14820
14821 let mut prev_offset = 0;
14822 let mut in_code_block = false;
14823 let has_row_limit = max_message_rows.is_some();
14824 let mut newline_indices = diagnostic
14825 .message
14826 .match_indices('\n')
14827 .filter(|_| has_row_limit)
14828 .map(|(ix, _)| ix)
14829 .fuse()
14830 .peekable();
14831
14832 for (quote_ix, _) in diagnostic
14833 .message
14834 .match_indices('`')
14835 .chain([(diagnostic.message.len(), "")])
14836 {
14837 let mut first_newline_ix = None;
14838 let mut last_newline_ix = None;
14839 while let Some(newline_ix) = newline_indices.peek() {
14840 if *newline_ix < quote_ix {
14841 if first_newline_ix.is_none() {
14842 first_newline_ix = Some(*newline_ix);
14843 }
14844 last_newline_ix = Some(*newline_ix);
14845
14846 if let Some(rows_left) = &mut max_message_rows {
14847 if *rows_left == 0 {
14848 break;
14849 } else {
14850 *rows_left -= 1;
14851 }
14852 }
14853 let _ = newline_indices.next();
14854 } else {
14855 break;
14856 }
14857 }
14858 let prev_len = text_without_backticks.len();
14859 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14860 text_without_backticks.push_str(new_text);
14861 if in_code_block {
14862 code_ranges.push(prev_len..text_without_backticks.len());
14863 }
14864 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14865 in_code_block = !in_code_block;
14866 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14867 text_without_backticks.push_str("...");
14868 break;
14869 }
14870 }
14871
14872 (text_without_backticks.into(), code_ranges)
14873}
14874
14875fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14876 match severity {
14877 DiagnosticSeverity::ERROR => colors.error,
14878 DiagnosticSeverity::WARNING => colors.warning,
14879 DiagnosticSeverity::INFORMATION => colors.info,
14880 DiagnosticSeverity::HINT => colors.info,
14881 _ => colors.ignored,
14882 }
14883}
14884
14885pub fn styled_runs_for_code_label<'a>(
14886 label: &'a CodeLabel,
14887 syntax_theme: &'a theme::SyntaxTheme,
14888) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14889 let fade_out = HighlightStyle {
14890 fade_out: Some(0.35),
14891 ..Default::default()
14892 };
14893
14894 let mut prev_end = label.filter_range.end;
14895 label
14896 .runs
14897 .iter()
14898 .enumerate()
14899 .flat_map(move |(ix, (range, highlight_id))| {
14900 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14901 style
14902 } else {
14903 return Default::default();
14904 };
14905 let mut muted_style = style;
14906 muted_style.highlight(fade_out);
14907
14908 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14909 if range.start >= label.filter_range.end {
14910 if range.start > prev_end {
14911 runs.push((prev_end..range.start, fade_out));
14912 }
14913 runs.push((range.clone(), muted_style));
14914 } else if range.end <= label.filter_range.end {
14915 runs.push((range.clone(), style));
14916 } else {
14917 runs.push((range.start..label.filter_range.end, style));
14918 runs.push((label.filter_range.end..range.end, muted_style));
14919 }
14920 prev_end = cmp::max(prev_end, range.end);
14921
14922 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14923 runs.push((prev_end..label.text.len(), fade_out));
14924 }
14925
14926 runs
14927 })
14928}
14929
14930pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14931 let mut prev_index = 0;
14932 let mut prev_codepoint: Option<char> = None;
14933 text.char_indices()
14934 .chain([(text.len(), '\0')])
14935 .filter_map(move |(index, codepoint)| {
14936 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14937 let is_boundary = index == text.len()
14938 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14939 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14940 if is_boundary {
14941 let chunk = &text[prev_index..index];
14942 prev_index = index;
14943 Some(chunk)
14944 } else {
14945 None
14946 }
14947 })
14948}
14949
14950pub trait RangeToAnchorExt: Sized {
14951 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14952
14953 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14954 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14955 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14956 }
14957}
14958
14959impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14960 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14961 let start_offset = self.start.to_offset(snapshot);
14962 let end_offset = self.end.to_offset(snapshot);
14963 if start_offset == end_offset {
14964 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14965 } else {
14966 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14967 }
14968 }
14969}
14970
14971pub trait RowExt {
14972 fn as_f32(&self) -> f32;
14973
14974 fn next_row(&self) -> Self;
14975
14976 fn previous_row(&self) -> Self;
14977
14978 fn minus(&self, other: Self) -> u32;
14979}
14980
14981impl RowExt for DisplayRow {
14982 fn as_f32(&self) -> f32 {
14983 self.0 as f32
14984 }
14985
14986 fn next_row(&self) -> Self {
14987 Self(self.0 + 1)
14988 }
14989
14990 fn previous_row(&self) -> Self {
14991 Self(self.0.saturating_sub(1))
14992 }
14993
14994 fn minus(&self, other: Self) -> u32 {
14995 self.0 - other.0
14996 }
14997}
14998
14999impl RowExt for MultiBufferRow {
15000 fn as_f32(&self) -> f32 {
15001 self.0 as f32
15002 }
15003
15004 fn next_row(&self) -> Self {
15005 Self(self.0 + 1)
15006 }
15007
15008 fn previous_row(&self) -> Self {
15009 Self(self.0.saturating_sub(1))
15010 }
15011
15012 fn minus(&self, other: Self) -> u32 {
15013 self.0 - other.0
15014 }
15015}
15016
15017trait RowRangeExt {
15018 type Row;
15019
15020 fn len(&self) -> usize;
15021
15022 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15023}
15024
15025impl RowRangeExt for Range<MultiBufferRow> {
15026 type Row = MultiBufferRow;
15027
15028 fn len(&self) -> usize {
15029 (self.end.0 - self.start.0) as usize
15030 }
15031
15032 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15033 (self.start.0..self.end.0).map(MultiBufferRow)
15034 }
15035}
15036
15037impl RowRangeExt for Range<DisplayRow> {
15038 type Row = DisplayRow;
15039
15040 fn len(&self) -> usize {
15041 (self.end.0 - self.start.0) as usize
15042 }
15043
15044 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15045 (self.start.0..self.end.0).map(DisplayRow)
15046 }
15047}
15048
15049fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15050 if hunk.diff_base_byte_range.is_empty() {
15051 DiffHunkStatus::Added
15052 } else if hunk.row_range.is_empty() {
15053 DiffHunkStatus::Removed
15054 } else {
15055 DiffHunkStatus::Modified
15056 }
15057}
15058
15059/// If select range has more than one line, we
15060/// just point the cursor to range.start.
15061fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15062 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15063 range
15064 } else {
15065 range.start..range.start
15066 }
15067}
15068
15069pub struct KillRing(ClipboardItem);
15070impl Global for KillRing {}
15071
15072const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);