1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
78 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
79 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
81 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
82 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
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(Copy, Clone, PartialEq, Eq)]
277pub enum Direction {
278 Prev,
279 Next,
280}
281
282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
283pub enum Navigated {
284 Yes,
285 No,
286}
287
288impl Navigated {
289 pub fn from_bool(yes: bool) -> Navigated {
290 if yes {
291 Navigated::Yes
292 } else {
293 Navigated::No
294 }
295 }
296}
297
298pub fn init_settings(cx: &mut AppContext) {
299 EditorSettings::register(cx);
300}
301
302pub fn init(cx: &mut AppContext) {
303 init_settings(cx);
304
305 workspace::register_project_item::<Editor>(cx);
306 workspace::FollowableViewRegistry::register::<Editor>(cx);
307 workspace::register_serializable_item::<Editor>(cx);
308
309 cx.observe_new_views(
310 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
311 workspace.register_action(Editor::new_file);
312 workspace.register_action(Editor::new_file_vertical);
313 workspace.register_action(Editor::new_file_horizontal);
314 },
315 )
316 .detach();
317
318 cx.on_action(move |_: &workspace::NewFile, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327 cx.on_action(move |_: &workspace::NewWindow, cx| {
328 let app_state = workspace::AppState::global(cx);
329 if let Some(app_state) = app_state.upgrade() {
330 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
331 Editor::new_file(workspace, &Default::default(), cx)
332 })
333 .detach();
334 }
335 });
336}
337
338pub struct SearchWithinRange;
339
340trait InvalidationRegion {
341 fn ranges(&self) -> &[Range<Anchor>];
342}
343
344#[derive(Clone, Debug, PartialEq)]
345pub enum SelectPhase {
346 Begin {
347 position: DisplayPoint,
348 add: bool,
349 click_count: usize,
350 },
351 BeginColumnar {
352 position: DisplayPoint,
353 reset: bool,
354 goal_column: u32,
355 },
356 Extend {
357 position: DisplayPoint,
358 click_count: usize,
359 },
360 Update {
361 position: DisplayPoint,
362 goal_column: u32,
363 scroll_delta: gpui::Point<f32>,
364 },
365 End,
366}
367
368#[derive(Clone, Debug)]
369pub enum SelectMode {
370 Character,
371 Word(Range<Anchor>),
372 Line(Range<Anchor>),
373 All,
374}
375
376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
377pub enum EditorMode {
378 SingleLine { auto_width: bool },
379 AutoHeight { max_lines: usize },
380 Full,
381}
382
383#[derive(Copy, Clone, Debug)]
384pub enum SoftWrap {
385 /// Prefer not to wrap at all.
386 ///
387 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
388 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
389 GitDiff,
390 /// Prefer a single line generally, unless an overly long line is encountered.
391 None,
392 /// Soft wrap lines that exceed the editor width.
393 EditorWidth,
394 /// Soft wrap lines at the preferred line length.
395 Column(u32),
396 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
397 Bounded(u32),
398}
399
400#[derive(Clone)]
401pub struct EditorStyle {
402 pub background: Hsla,
403 pub local_player: PlayerColor,
404 pub text: TextStyle,
405 pub scrollbar_width: Pixels,
406 pub syntax: Arc<SyntaxTheme>,
407 pub status: StatusColors,
408 pub inlay_hints_style: HighlightStyle,
409 pub suggestions_style: HighlightStyle,
410 pub unnecessary_code_fade: f32,
411}
412
413impl Default for EditorStyle {
414 fn default() -> Self {
415 Self {
416 background: Hsla::default(),
417 local_player: PlayerColor::default(),
418 text: TextStyle::default(),
419 scrollbar_width: Pixels::default(),
420 syntax: Default::default(),
421 // HACK: Status colors don't have a real default.
422 // We should look into removing the status colors from the editor
423 // style and retrieve them directly from the theme.
424 status: StatusColors::dark(),
425 inlay_hints_style: HighlightStyle::default(),
426 suggestions_style: HighlightStyle::default(),
427 unnecessary_code_fade: Default::default(),
428 }
429 }
430}
431
432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
433 let show_background = language_settings::language_settings(None, None, cx)
434 .inlay_hints
435 .show_background;
436
437 HighlightStyle {
438 color: Some(cx.theme().status().hint),
439 background_color: show_background.then(|| cx.theme().status().hint_background),
440 ..HighlightStyle::default()
441 }
442}
443
444type CompletionId = usize;
445
446#[derive(Clone, Debug)]
447struct CompletionState {
448 // render_inlay_ids represents the inlay hints that are inserted
449 // for rendering the inline completions. They may be discontinuous
450 // in the event that the completion provider returns some intersection
451 // with the existing content.
452 render_inlay_ids: Vec<InlayId>,
453 // text is the resulting rope that is inserted when the user accepts a completion.
454 text: Rope,
455 // position is the position of the cursor when the completion was triggered.
456 position: multi_buffer::Anchor,
457 // delete_range is the range of text that this completion state covers.
458 // if the completion is accepted, this range should be deleted.
459 delete_range: Option<Range<multi_buffer::Anchor>>,
460}
461
462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
463struct EditorActionId(usize);
464
465impl EditorActionId {
466 pub fn post_inc(&mut self) -> Self {
467 let answer = self.0;
468
469 *self = Self(answer + 1);
470
471 Self(answer)
472 }
473}
474
475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
477
478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
480
481#[derive(Default)]
482struct ScrollbarMarkerState {
483 scrollbar_size: Size<Pixels>,
484 dirty: bool,
485 markers: Arc<[PaintQuad]>,
486 pending_refresh: Option<Task<Result<()>>>,
487}
488
489impl ScrollbarMarkerState {
490 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
491 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
492 }
493}
494
495#[derive(Clone, Debug)]
496struct RunnableTasks {
497 templates: Vec<(TaskSourceKind, TaskTemplate)>,
498 offset: MultiBufferOffset,
499 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
500 column: u32,
501 // Values of all named captures, including those starting with '_'
502 extra_variables: HashMap<String, String>,
503 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
504 context_range: Range<BufferOffset>,
505}
506
507impl RunnableTasks {
508 fn resolve<'a>(
509 &'a self,
510 cx: &'a task::TaskContext,
511 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
512 self.templates.iter().filter_map(|(kind, template)| {
513 template
514 .resolve_task(&kind.to_id_base(), cx)
515 .map(|task| (kind.clone(), task))
516 })
517 }
518}
519
520#[derive(Clone)]
521struct ResolvedTasks {
522 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
523 position: Anchor,
524}
525#[derive(Copy, Clone, Debug)]
526struct MultiBufferOffset(usize);
527#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
528struct BufferOffset(usize);
529
530// Addons allow storing per-editor state in other crates (e.g. Vim)
531pub trait Addon: 'static {
532 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
533
534 fn to_any(&self) -> &dyn std::any::Any;
535}
536
537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
538///
539/// See the [module level documentation](self) for more information.
540pub struct Editor {
541 focus_handle: FocusHandle,
542 last_focused_descendant: Option<WeakFocusHandle>,
543 /// The text buffer being edited
544 buffer: Model<MultiBuffer>,
545 /// Map of how text in the buffer should be displayed.
546 /// Handles soft wraps, folds, fake inlay text insertions, etc.
547 pub display_map: Model<DisplayMap>,
548 pub selections: SelectionsCollection,
549 pub scroll_manager: ScrollManager,
550 /// When inline assist editors are linked, they all render cursors because
551 /// typing enters text into each of them, even the ones that aren't focused.
552 pub(crate) show_cursor_when_unfocused: bool,
553 columnar_selection_tail: Option<Anchor>,
554 add_selections_state: Option<AddSelectionsState>,
555 select_next_state: Option<SelectNextState>,
556 select_prev_state: Option<SelectNextState>,
557 selection_history: SelectionHistory,
558 autoclose_regions: Vec<AutocloseRegion>,
559 snippet_stack: InvalidationStack<SnippetState>,
560 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
561 ime_transaction: Option<TransactionId>,
562 active_diagnostics: Option<ActiveDiagnosticGroup>,
563 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
564
565 project: Option<Model<Project>>,
566 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
567 completion_provider: Option<Box<dyn CompletionProvider>>,
568 collaboration_hub: Option<Box<dyn CollaborationHub>>,
569 blink_manager: Model<BlinkManager>,
570 show_cursor_names: bool,
571 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
572 pub show_local_selections: bool,
573 mode: EditorMode,
574 show_breadcrumbs: bool,
575 show_gutter: bool,
576 show_line_numbers: Option<bool>,
577 use_relative_line_numbers: Option<bool>,
578 show_git_diff_gutter: Option<bool>,
579 show_code_actions: Option<bool>,
580 show_runnables: Option<bool>,
581 show_wrap_guides: Option<bool>,
582 show_indent_guides: Option<bool>,
583 placeholder_text: Option<Arc<str>>,
584 highlight_order: usize,
585 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
586 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
587 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
588 scrollbar_marker_state: ScrollbarMarkerState,
589 active_indent_guides_state: ActiveIndentGuidesState,
590 nav_history: Option<ItemNavHistory>,
591 context_menu: RwLock<Option<ContextMenu>>,
592 mouse_context_menu: Option<MouseContextMenu>,
593 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
594 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
595 signature_help_state: SignatureHelpState,
596 auto_signature_help: Option<bool>,
597 find_all_references_task_sources: Vec<Anchor>,
598 next_completion_id: CompletionId,
599 completion_documentation_pre_resolve_debounce: DebouncedDelay,
600 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
601 code_actions_task: Option<Task<Result<()>>>,
602 document_highlights_task: Option<Task<()>>,
603 linked_editing_range_task: Option<Task<Option<()>>>,
604 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
605 pending_rename: Option<RenameState>,
606 searchable: bool,
607 cursor_shape: CursorShape,
608 current_line_highlight: Option<CurrentLineHighlight>,
609 collapse_matches: bool,
610 autoindent_mode: Option<AutoindentMode>,
611 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
612 input_enabled: bool,
613 use_modal_editing: bool,
614 read_only: bool,
615 leader_peer_id: Option<PeerId>,
616 remote_id: Option<ViewId>,
617 hover_state: HoverState,
618 gutter_hovered: bool,
619 hovered_link_state: Option<HoveredLinkState>,
620 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
621 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
622 active_inline_completion: Option<CompletionState>,
623 // enable_inline_completions is a switch that Vim can use to disable
624 // inline completions based on its mode.
625 enable_inline_completions: bool,
626 show_inline_completions_override: Option<bool>,
627 inlay_hint_cache: InlayHintCache,
628 expanded_hunks: ExpandedHunks,
629 next_inlay_id: usize,
630 _subscriptions: Vec<Subscription>,
631 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
632 gutter_dimensions: GutterDimensions,
633 style: Option<EditorStyle>,
634 text_style_refinement: Option<TextStyleRefinement>,
635 next_editor_action_id: EditorActionId,
636 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
637 use_autoclose: bool,
638 use_auto_surround: bool,
639 auto_replace_emoji_shortcode: bool,
640 show_git_blame_gutter: bool,
641 show_git_blame_inline: bool,
642 show_git_blame_inline_delay_task: Option<Task<()>>,
643 git_blame_inline_enabled: bool,
644 serialize_dirty_buffers: bool,
645 show_selection_menu: Option<bool>,
646 blame: Option<Model<GitBlame>>,
647 blame_subscription: Option<Subscription>,
648 custom_context_menu: Option<
649 Box<
650 dyn 'static
651 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
652 >,
653 >,
654 last_bounds: Option<Bounds<Pixels>>,
655 expect_bounds_change: Option<Bounds<Pixels>>,
656 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
657 tasks_update_task: Option<Task<()>>,
658 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
659 breadcrumb_header: Option<String>,
660 focused_block: Option<FocusedBlock>,
661 next_scroll_position: NextScrollCursorCenterTopBottom,
662 addons: HashMap<TypeId, Box<dyn Addon>>,
663 _scroll_cursor_center_top_bottom_task: Task<()>,
664}
665
666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
667enum NextScrollCursorCenterTopBottom {
668 #[default]
669 Center,
670 Top,
671 Bottom,
672}
673
674impl NextScrollCursorCenterTopBottom {
675 fn next(&self) -> Self {
676 match self {
677 Self::Center => Self::Top,
678 Self::Top => Self::Bottom,
679 Self::Bottom => Self::Center,
680 }
681 }
682}
683
684#[derive(Clone)]
685pub struct EditorSnapshot {
686 pub mode: EditorMode,
687 show_gutter: bool,
688 show_line_numbers: Option<bool>,
689 show_git_diff_gutter: Option<bool>,
690 show_code_actions: Option<bool>,
691 show_runnables: Option<bool>,
692 git_blame_gutter_max_author_length: Option<usize>,
693 pub display_snapshot: DisplaySnapshot,
694 pub placeholder_text: Option<Arc<str>>,
695 is_focused: bool,
696 scroll_anchor: ScrollAnchor,
697 ongoing_scroll: OngoingScroll,
698 current_line_highlight: CurrentLineHighlight,
699 gutter_hovered: bool,
700}
701
702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
703
704#[derive(Default, Debug, Clone, Copy)]
705pub struct GutterDimensions {
706 pub left_padding: Pixels,
707 pub right_padding: Pixels,
708 pub width: Pixels,
709 pub margin: Pixels,
710 pub git_blame_entries_width: Option<Pixels>,
711}
712
713impl GutterDimensions {
714 /// The full width of the space taken up by the gutter.
715 pub fn full_width(&self) -> Pixels {
716 self.margin + self.width
717 }
718
719 /// The width of the space reserved for the fold indicators,
720 /// use alongside 'justify_end' and `gutter_width` to
721 /// right align content with the line numbers
722 pub fn fold_area_width(&self) -> Pixels {
723 self.margin + self.right_padding
724 }
725}
726
727#[derive(Debug)]
728pub struct RemoteSelection {
729 pub replica_id: ReplicaId,
730 pub selection: Selection<Anchor>,
731 pub cursor_shape: CursorShape,
732 pub peer_id: PeerId,
733 pub line_mode: bool,
734 pub participant_index: Option<ParticipantIndex>,
735 pub user_name: Option<SharedString>,
736}
737
738#[derive(Clone, Debug)]
739struct SelectionHistoryEntry {
740 selections: Arc<[Selection<Anchor>]>,
741 select_next_state: Option<SelectNextState>,
742 select_prev_state: Option<SelectNextState>,
743 add_selections_state: Option<AddSelectionsState>,
744}
745
746enum SelectionHistoryMode {
747 Normal,
748 Undoing,
749 Redoing,
750}
751
752#[derive(Clone, PartialEq, Eq, Hash)]
753struct HoveredCursor {
754 replica_id: u16,
755 selection_id: usize,
756}
757
758impl Default for SelectionHistoryMode {
759 fn default() -> Self {
760 Self::Normal
761 }
762}
763
764#[derive(Default)]
765struct SelectionHistory {
766 #[allow(clippy::type_complexity)]
767 selections_by_transaction:
768 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
769 mode: SelectionHistoryMode,
770 undo_stack: VecDeque<SelectionHistoryEntry>,
771 redo_stack: VecDeque<SelectionHistoryEntry>,
772}
773
774impl SelectionHistory {
775 fn insert_transaction(
776 &mut self,
777 transaction_id: TransactionId,
778 selections: Arc<[Selection<Anchor>]>,
779 ) {
780 self.selections_by_transaction
781 .insert(transaction_id, (selections, None));
782 }
783
784 #[allow(clippy::type_complexity)]
785 fn transaction(
786 &self,
787 transaction_id: TransactionId,
788 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
789 self.selections_by_transaction.get(&transaction_id)
790 }
791
792 #[allow(clippy::type_complexity)]
793 fn transaction_mut(
794 &mut self,
795 transaction_id: TransactionId,
796 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
797 self.selections_by_transaction.get_mut(&transaction_id)
798 }
799
800 fn push(&mut self, entry: SelectionHistoryEntry) {
801 if !entry.selections.is_empty() {
802 match self.mode {
803 SelectionHistoryMode::Normal => {
804 self.push_undo(entry);
805 self.redo_stack.clear();
806 }
807 SelectionHistoryMode::Undoing => self.push_redo(entry),
808 SelectionHistoryMode::Redoing => self.push_undo(entry),
809 }
810 }
811 }
812
813 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
814 if self
815 .undo_stack
816 .back()
817 .map_or(true, |e| e.selections != entry.selections)
818 {
819 self.undo_stack.push_back(entry);
820 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
821 self.undo_stack.pop_front();
822 }
823 }
824 }
825
826 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
827 if self
828 .redo_stack
829 .back()
830 .map_or(true, |e| e.selections != entry.selections)
831 {
832 self.redo_stack.push_back(entry);
833 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
834 self.redo_stack.pop_front();
835 }
836 }
837 }
838}
839
840struct RowHighlight {
841 index: usize,
842 range: Range<Anchor>,
843 color: Hsla,
844 should_autoscroll: bool,
845}
846
847#[derive(Clone, Debug)]
848struct AddSelectionsState {
849 above: bool,
850 stack: Vec<usize>,
851}
852
853#[derive(Clone)]
854struct SelectNextState {
855 query: AhoCorasick,
856 wordwise: bool,
857 done: bool,
858}
859
860impl std::fmt::Debug for SelectNextState {
861 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
862 f.debug_struct(std::any::type_name::<Self>())
863 .field("wordwise", &self.wordwise)
864 .field("done", &self.done)
865 .finish()
866 }
867}
868
869#[derive(Debug)]
870struct AutocloseRegion {
871 selection_id: usize,
872 range: Range<Anchor>,
873 pair: BracketPair,
874}
875
876#[derive(Debug)]
877struct SnippetState {
878 ranges: Vec<Vec<Range<Anchor>>>,
879 active_index: usize,
880}
881
882#[doc(hidden)]
883pub struct RenameState {
884 pub range: Range<Anchor>,
885 pub old_name: Arc<str>,
886 pub editor: View<Editor>,
887 block_id: CustomBlockId,
888}
889
890struct InvalidationStack<T>(Vec<T>);
891
892struct RegisteredInlineCompletionProvider {
893 provider: Arc<dyn InlineCompletionProviderHandle>,
894 _subscription: Subscription,
895}
896
897enum ContextMenu {
898 Completions(CompletionsMenu),
899 CodeActions(CodeActionsMenu),
900}
901
902impl ContextMenu {
903 fn select_first(
904 &mut self,
905 provider: Option<&dyn CompletionProvider>,
906 cx: &mut ViewContext<Editor>,
907 ) -> bool {
908 if self.visible() {
909 match self {
910 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
911 ContextMenu::CodeActions(menu) => menu.select_first(cx),
912 }
913 true
914 } else {
915 false
916 }
917 }
918
919 fn select_prev(
920 &mut self,
921 provider: Option<&dyn CompletionProvider>,
922 cx: &mut ViewContext<Editor>,
923 ) -> bool {
924 if self.visible() {
925 match self {
926 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
927 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
928 }
929 true
930 } else {
931 false
932 }
933 }
934
935 fn select_next(
936 &mut self,
937 provider: Option<&dyn CompletionProvider>,
938 cx: &mut ViewContext<Editor>,
939 ) -> bool {
940 if self.visible() {
941 match self {
942 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
943 ContextMenu::CodeActions(menu) => menu.select_next(cx),
944 }
945 true
946 } else {
947 false
948 }
949 }
950
951 fn select_last(
952 &mut self,
953 provider: Option<&dyn CompletionProvider>,
954 cx: &mut ViewContext<Editor>,
955 ) -> bool {
956 if self.visible() {
957 match self {
958 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
959 ContextMenu::CodeActions(menu) => menu.select_last(cx),
960 }
961 true
962 } else {
963 false
964 }
965 }
966
967 fn visible(&self) -> bool {
968 match self {
969 ContextMenu::Completions(menu) => menu.visible(),
970 ContextMenu::CodeActions(menu) => menu.visible(),
971 }
972 }
973
974 fn render(
975 &self,
976 cursor_position: DisplayPoint,
977 style: &EditorStyle,
978 max_height: Pixels,
979 workspace: Option<WeakView<Workspace>>,
980 cx: &mut ViewContext<Editor>,
981 ) -> (ContextMenuOrigin, AnyElement) {
982 match self {
983 ContextMenu::Completions(menu) => (
984 ContextMenuOrigin::EditorPoint(cursor_position),
985 menu.render(style, max_height, workspace, cx),
986 ),
987 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
988 }
989 }
990}
991
992enum ContextMenuOrigin {
993 EditorPoint(DisplayPoint),
994 GutterIndicator(DisplayRow),
995}
996
997#[derive(Clone)]
998struct CompletionsMenu {
999 id: CompletionId,
1000 sort_completions: bool,
1001 initial_position: Anchor,
1002 buffer: Model<Buffer>,
1003 completions: Arc<RwLock<Box<[Completion]>>>,
1004 match_candidates: Arc<[StringMatchCandidate]>,
1005 matches: Arc<[StringMatch]>,
1006 selected_item: usize,
1007 scroll_handle: UniformListScrollHandle,
1008 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
1009}
1010
1011impl CompletionsMenu {
1012 fn select_first(
1013 &mut self,
1014 provider: Option<&dyn CompletionProvider>,
1015 cx: &mut ViewContext<Editor>,
1016 ) {
1017 self.selected_item = 0;
1018 self.scroll_handle
1019 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1020 self.attempt_resolve_selected_completion_documentation(provider, cx);
1021 cx.notify();
1022 }
1023
1024 fn select_prev(
1025 &mut self,
1026 provider: Option<&dyn CompletionProvider>,
1027 cx: &mut ViewContext<Editor>,
1028 ) {
1029 if self.selected_item > 0 {
1030 self.selected_item -= 1;
1031 } else {
1032 self.selected_item = self.matches.len() - 1;
1033 }
1034 self.scroll_handle
1035 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1036 self.attempt_resolve_selected_completion_documentation(provider, cx);
1037 cx.notify();
1038 }
1039
1040 fn select_next(
1041 &mut self,
1042 provider: Option<&dyn CompletionProvider>,
1043 cx: &mut ViewContext<Editor>,
1044 ) {
1045 if self.selected_item + 1 < self.matches.len() {
1046 self.selected_item += 1;
1047 } else {
1048 self.selected_item = 0;
1049 }
1050 self.scroll_handle
1051 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1052 self.attempt_resolve_selected_completion_documentation(provider, cx);
1053 cx.notify();
1054 }
1055
1056 fn select_last(
1057 &mut self,
1058 provider: Option<&dyn CompletionProvider>,
1059 cx: &mut ViewContext<Editor>,
1060 ) {
1061 self.selected_item = self.matches.len() - 1;
1062 self.scroll_handle
1063 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1064 self.attempt_resolve_selected_completion_documentation(provider, cx);
1065 cx.notify();
1066 }
1067
1068 fn pre_resolve_completion_documentation(
1069 buffer: Model<Buffer>,
1070 completions: Arc<RwLock<Box<[Completion]>>>,
1071 matches: Arc<[StringMatch]>,
1072 editor: &Editor,
1073 cx: &mut ViewContext<Editor>,
1074 ) -> Task<()> {
1075 let settings = EditorSettings::get_global(cx);
1076 if !settings.show_completion_documentation {
1077 return Task::ready(());
1078 }
1079
1080 let Some(provider) = editor.completion_provider.as_ref() else {
1081 return Task::ready(());
1082 };
1083
1084 let resolve_task = provider.resolve_completions(
1085 buffer,
1086 matches.iter().map(|m| m.candidate_id).collect(),
1087 completions.clone(),
1088 cx,
1089 );
1090
1091 cx.spawn(move |this, mut cx| async move {
1092 if let Some(true) = resolve_task.await.log_err() {
1093 this.update(&mut cx, |_, cx| cx.notify()).ok();
1094 }
1095 })
1096 }
1097
1098 fn attempt_resolve_selected_completion_documentation(
1099 &mut self,
1100 provider: Option<&dyn CompletionProvider>,
1101 cx: &mut ViewContext<Editor>,
1102 ) {
1103 let settings = EditorSettings::get_global(cx);
1104 if !settings.show_completion_documentation {
1105 return;
1106 }
1107
1108 let completion_index = self.matches[self.selected_item].candidate_id;
1109 let Some(provider) = provider else {
1110 return;
1111 };
1112
1113 let resolve_task = provider.resolve_completions(
1114 self.buffer.clone(),
1115 vec![completion_index],
1116 self.completions.clone(),
1117 cx,
1118 );
1119
1120 let delay_ms =
1121 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1122 let delay = Duration::from_millis(delay_ms);
1123
1124 self.selected_completion_documentation_resolve_debounce
1125 .lock()
1126 .fire_new(delay, cx, |_, cx| {
1127 cx.spawn(move |this, mut cx| async move {
1128 if let Some(true) = resolve_task.await.log_err() {
1129 this.update(&mut cx, |_, cx| cx.notify()).ok();
1130 }
1131 })
1132 });
1133 }
1134
1135 fn visible(&self) -> bool {
1136 !self.matches.is_empty()
1137 }
1138
1139 fn render(
1140 &self,
1141 style: &EditorStyle,
1142 max_height: Pixels,
1143 workspace: Option<WeakView<Workspace>>,
1144 cx: &mut ViewContext<Editor>,
1145 ) -> AnyElement {
1146 let settings = EditorSettings::get_global(cx);
1147 let show_completion_documentation = settings.show_completion_documentation;
1148
1149 let widest_completion_ix = self
1150 .matches
1151 .iter()
1152 .enumerate()
1153 .max_by_key(|(_, mat)| {
1154 let completions = self.completions.read();
1155 let completion = &completions[mat.candidate_id];
1156 let documentation = &completion.documentation;
1157
1158 let mut len = completion.label.text.chars().count();
1159 if let Some(Documentation::SingleLine(text)) = documentation {
1160 if show_completion_documentation {
1161 len += text.chars().count();
1162 }
1163 }
1164
1165 len
1166 })
1167 .map(|(ix, _)| ix);
1168
1169 let completions = self.completions.clone();
1170 let matches = self.matches.clone();
1171 let selected_item = self.selected_item;
1172 let style = style.clone();
1173
1174 let multiline_docs = if show_completion_documentation {
1175 let mat = &self.matches[selected_item];
1176 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1177 Some(Documentation::MultiLinePlainText(text)) => {
1178 Some(div().child(SharedString::from(text.clone())))
1179 }
1180 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1181 Some(div().child(render_parsed_markdown(
1182 "completions_markdown",
1183 parsed,
1184 &style,
1185 workspace,
1186 cx,
1187 )))
1188 }
1189 _ => None,
1190 };
1191 multiline_docs.map(|div| {
1192 div.id("multiline_docs")
1193 .max_h(max_height)
1194 .flex_1()
1195 .px_1p5()
1196 .py_1()
1197 .min_w(px(260.))
1198 .max_w(px(640.))
1199 .w(px(500.))
1200 .overflow_y_scroll()
1201 .occlude()
1202 })
1203 } else {
1204 None
1205 };
1206
1207 let list = uniform_list(
1208 cx.view().clone(),
1209 "completions",
1210 matches.len(),
1211 move |_editor, range, cx| {
1212 let start_ix = range.start;
1213 let completions_guard = completions.read();
1214
1215 matches[range]
1216 .iter()
1217 .enumerate()
1218 .map(|(ix, mat)| {
1219 let item_ix = start_ix + ix;
1220 let candidate_id = mat.candidate_id;
1221 let completion = &completions_guard[candidate_id];
1222
1223 let documentation = if show_completion_documentation {
1224 &completion.documentation
1225 } else {
1226 &None
1227 };
1228
1229 let highlights = gpui::combine_highlights(
1230 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1231 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1232 |(range, mut highlight)| {
1233 // Ignore font weight for syntax highlighting, as we'll use it
1234 // for fuzzy matches.
1235 highlight.font_weight = None;
1236
1237 if completion.lsp_completion.deprecated.unwrap_or(false) {
1238 highlight.strikethrough = Some(StrikethroughStyle {
1239 thickness: 1.0.into(),
1240 ..Default::default()
1241 });
1242 highlight.color = Some(cx.theme().colors().text_muted);
1243 }
1244
1245 (range, highlight)
1246 },
1247 ),
1248 );
1249 let completion_label = StyledText::new(completion.label.text.clone())
1250 .with_highlights(&style.text, highlights);
1251 let documentation_label =
1252 if let Some(Documentation::SingleLine(text)) = documentation {
1253 if text.trim().is_empty() {
1254 None
1255 } else {
1256 Some(
1257 Label::new(text.clone())
1258 .ml_4()
1259 .size(LabelSize::Small)
1260 .color(Color::Muted),
1261 )
1262 }
1263 } else {
1264 None
1265 };
1266
1267 let color_swatch = completion
1268 .color()
1269 .map(|color| div().size_4().bg(color).rounded_sm());
1270
1271 div().min_w(px(220.)).max_w(px(540.)).child(
1272 ListItem::new(mat.candidate_id)
1273 .inset(true)
1274 .selected(item_ix == selected_item)
1275 .on_click(cx.listener(move |editor, _event, cx| {
1276 cx.stop_propagation();
1277 if let Some(task) = editor.confirm_completion(
1278 &ConfirmCompletion {
1279 item_ix: Some(item_ix),
1280 },
1281 cx,
1282 ) {
1283 task.detach_and_log_err(cx)
1284 }
1285 }))
1286 .start_slot::<Div>(color_swatch)
1287 .child(h_flex().overflow_hidden().child(completion_label))
1288 .end_slot::<Label>(documentation_label),
1289 )
1290 })
1291 .collect()
1292 },
1293 )
1294 .occlude()
1295 .max_h(max_height)
1296 .track_scroll(self.scroll_handle.clone())
1297 .with_width_from_item(widest_completion_ix)
1298 .with_sizing_behavior(ListSizingBehavior::Infer);
1299
1300 Popover::new()
1301 .child(list)
1302 .when_some(multiline_docs, |popover, multiline_docs| {
1303 popover.aside(multiline_docs)
1304 })
1305 .into_any_element()
1306 }
1307
1308 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1309 let mut matches = if let Some(query) = query {
1310 fuzzy::match_strings(
1311 &self.match_candidates,
1312 query,
1313 query.chars().any(|c| c.is_uppercase()),
1314 100,
1315 &Default::default(),
1316 executor,
1317 )
1318 .await
1319 } else {
1320 self.match_candidates
1321 .iter()
1322 .enumerate()
1323 .map(|(candidate_id, candidate)| StringMatch {
1324 candidate_id,
1325 score: Default::default(),
1326 positions: Default::default(),
1327 string: candidate.string.clone(),
1328 })
1329 .collect()
1330 };
1331
1332 // Remove all candidates where the query's start does not match the start of any word in the candidate
1333 if let Some(query) = query {
1334 if let Some(query_start) = query.chars().next() {
1335 matches.retain(|string_match| {
1336 split_words(&string_match.string).any(|word| {
1337 // Check that the first codepoint of the word as lowercase matches the first
1338 // codepoint of the query as lowercase
1339 word.chars()
1340 .flat_map(|codepoint| codepoint.to_lowercase())
1341 .zip(query_start.to_lowercase())
1342 .all(|(word_cp, query_cp)| word_cp == query_cp)
1343 })
1344 });
1345 }
1346 }
1347
1348 let completions = self.completions.read();
1349 if self.sort_completions {
1350 matches.sort_unstable_by_key(|mat| {
1351 // We do want to strike a balance here between what the language server tells us
1352 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1353 // `Creat` and there is a local variable called `CreateComponent`).
1354 // So what we do is: we bucket all matches into two buckets
1355 // - Strong matches
1356 // - Weak matches
1357 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1358 // and the Weak matches are the rest.
1359 //
1360 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1361 // matches, we prefer language-server sort_text first.
1362 //
1363 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1364 // Rest of the matches(weak) can be sorted as language-server expects.
1365
1366 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1367 enum MatchScore<'a> {
1368 Strong {
1369 score: Reverse<OrderedFloat<f64>>,
1370 sort_text: Option<&'a str>,
1371 sort_key: (usize, &'a str),
1372 },
1373 Weak {
1374 sort_text: Option<&'a str>,
1375 score: Reverse<OrderedFloat<f64>>,
1376 sort_key: (usize, &'a str),
1377 },
1378 }
1379
1380 let completion = &completions[mat.candidate_id];
1381 let sort_key = completion.sort_key();
1382 let sort_text = completion.lsp_completion.sort_text.as_deref();
1383 let score = Reverse(OrderedFloat(mat.score));
1384
1385 if mat.score >= 0.2 {
1386 MatchScore::Strong {
1387 score,
1388 sort_text,
1389 sort_key,
1390 }
1391 } else {
1392 MatchScore::Weak {
1393 sort_text,
1394 score,
1395 sort_key,
1396 }
1397 }
1398 });
1399 }
1400
1401 for mat in &mut matches {
1402 let completion = &completions[mat.candidate_id];
1403 mat.string.clone_from(&completion.label.text);
1404 for position in &mut mat.positions {
1405 *position += completion.label.filter_range.start;
1406 }
1407 }
1408 drop(completions);
1409
1410 self.matches = matches.into();
1411 self.selected_item = 0;
1412 }
1413}
1414
1415struct AvailableCodeAction {
1416 excerpt_id: ExcerptId,
1417 action: CodeAction,
1418 provider: Arc<dyn CodeActionProvider>,
1419}
1420
1421#[derive(Clone)]
1422struct CodeActionContents {
1423 tasks: Option<Arc<ResolvedTasks>>,
1424 actions: Option<Arc<[AvailableCodeAction]>>,
1425}
1426
1427impl CodeActionContents {
1428 fn len(&self) -> usize {
1429 match (&self.tasks, &self.actions) {
1430 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1431 (Some(tasks), None) => tasks.templates.len(),
1432 (None, Some(actions)) => actions.len(),
1433 (None, None) => 0,
1434 }
1435 }
1436
1437 fn is_empty(&self) -> bool {
1438 match (&self.tasks, &self.actions) {
1439 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1440 (Some(tasks), None) => tasks.templates.is_empty(),
1441 (None, Some(actions)) => actions.is_empty(),
1442 (None, None) => true,
1443 }
1444 }
1445
1446 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1447 self.tasks
1448 .iter()
1449 .flat_map(|tasks| {
1450 tasks
1451 .templates
1452 .iter()
1453 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1454 })
1455 .chain(self.actions.iter().flat_map(|actions| {
1456 actions.iter().map(|available| CodeActionsItem::CodeAction {
1457 excerpt_id: available.excerpt_id,
1458 action: available.action.clone(),
1459 provider: available.provider.clone(),
1460 })
1461 }))
1462 }
1463 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1464 match (&self.tasks, &self.actions) {
1465 (Some(tasks), Some(actions)) => {
1466 if index < tasks.templates.len() {
1467 tasks
1468 .templates
1469 .get(index)
1470 .cloned()
1471 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1472 } else {
1473 actions.get(index - tasks.templates.len()).map(|available| {
1474 CodeActionsItem::CodeAction {
1475 excerpt_id: available.excerpt_id,
1476 action: available.action.clone(),
1477 provider: available.provider.clone(),
1478 }
1479 })
1480 }
1481 }
1482 (Some(tasks), None) => tasks
1483 .templates
1484 .get(index)
1485 .cloned()
1486 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1487 (None, Some(actions)) => {
1488 actions
1489 .get(index)
1490 .map(|available| CodeActionsItem::CodeAction {
1491 excerpt_id: available.excerpt_id,
1492 action: available.action.clone(),
1493 provider: available.provider.clone(),
1494 })
1495 }
1496 (None, None) => None,
1497 }
1498 }
1499}
1500
1501#[allow(clippy::large_enum_variant)]
1502#[derive(Clone)]
1503enum CodeActionsItem {
1504 Task(TaskSourceKind, ResolvedTask),
1505 CodeAction {
1506 excerpt_id: ExcerptId,
1507 action: CodeAction,
1508 provider: Arc<dyn CodeActionProvider>,
1509 },
1510}
1511
1512impl CodeActionsItem {
1513 fn as_task(&self) -> Option<&ResolvedTask> {
1514 let Self::Task(_, task) = self else {
1515 return None;
1516 };
1517 Some(task)
1518 }
1519 fn as_code_action(&self) -> Option<&CodeAction> {
1520 let Self::CodeAction { action, .. } = self else {
1521 return None;
1522 };
1523 Some(action)
1524 }
1525 fn label(&self) -> String {
1526 match self {
1527 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1528 Self::Task(_, task) => task.resolved_label.clone(),
1529 }
1530 }
1531}
1532
1533struct CodeActionsMenu {
1534 actions: CodeActionContents,
1535 buffer: Model<Buffer>,
1536 selected_item: usize,
1537 scroll_handle: UniformListScrollHandle,
1538 deployed_from_indicator: Option<DisplayRow>,
1539}
1540
1541impl CodeActionsMenu {
1542 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1543 self.selected_item = 0;
1544 self.scroll_handle
1545 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1546 cx.notify()
1547 }
1548
1549 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1550 if self.selected_item > 0 {
1551 self.selected_item -= 1;
1552 } else {
1553 self.selected_item = self.actions.len() - 1;
1554 }
1555 self.scroll_handle
1556 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1557 cx.notify();
1558 }
1559
1560 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1561 if self.selected_item + 1 < self.actions.len() {
1562 self.selected_item += 1;
1563 } else {
1564 self.selected_item = 0;
1565 }
1566 self.scroll_handle
1567 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1568 cx.notify();
1569 }
1570
1571 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1572 self.selected_item = self.actions.len() - 1;
1573 self.scroll_handle
1574 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1575 cx.notify()
1576 }
1577
1578 fn visible(&self) -> bool {
1579 !self.actions.is_empty()
1580 }
1581
1582 fn render(
1583 &self,
1584 cursor_position: DisplayPoint,
1585 _style: &EditorStyle,
1586 max_height: Pixels,
1587 cx: &mut ViewContext<Editor>,
1588 ) -> (ContextMenuOrigin, AnyElement) {
1589 let actions = self.actions.clone();
1590 let selected_item = self.selected_item;
1591 let element = uniform_list(
1592 cx.view().clone(),
1593 "code_actions_menu",
1594 self.actions.len(),
1595 move |_this, range, cx| {
1596 actions
1597 .iter()
1598 .skip(range.start)
1599 .take(range.end - range.start)
1600 .enumerate()
1601 .map(|(ix, action)| {
1602 let item_ix = range.start + ix;
1603 let selected = selected_item == item_ix;
1604 let colors = cx.theme().colors();
1605 div()
1606 .px_1()
1607 .rounded_md()
1608 .text_color(colors.text)
1609 .when(selected, |style| {
1610 style
1611 .bg(colors.element_active)
1612 .text_color(colors.text_accent)
1613 })
1614 .hover(|style| {
1615 style
1616 .bg(colors.element_hover)
1617 .text_color(colors.text_accent)
1618 })
1619 .whitespace_nowrap()
1620 .when_some(action.as_code_action(), |this, action| {
1621 this.on_mouse_down(
1622 MouseButton::Left,
1623 cx.listener(move |editor, _, cx| {
1624 cx.stop_propagation();
1625 if let Some(task) = editor.confirm_code_action(
1626 &ConfirmCodeAction {
1627 item_ix: Some(item_ix),
1628 },
1629 cx,
1630 ) {
1631 task.detach_and_log_err(cx)
1632 }
1633 }),
1634 )
1635 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1636 .child(SharedString::from(action.lsp_action.title.clone()))
1637 })
1638 .when_some(action.as_task(), |this, task| {
1639 this.on_mouse_down(
1640 MouseButton::Left,
1641 cx.listener(move |editor, _, cx| {
1642 cx.stop_propagation();
1643 if let Some(task) = editor.confirm_code_action(
1644 &ConfirmCodeAction {
1645 item_ix: Some(item_ix),
1646 },
1647 cx,
1648 ) {
1649 task.detach_and_log_err(cx)
1650 }
1651 }),
1652 )
1653 .child(SharedString::from(task.resolved_label.clone()))
1654 })
1655 })
1656 .collect()
1657 },
1658 )
1659 .elevation_1(cx)
1660 .p_1()
1661 .max_h(max_height)
1662 .occlude()
1663 .track_scroll(self.scroll_handle.clone())
1664 .with_width_from_item(
1665 self.actions
1666 .iter()
1667 .enumerate()
1668 .max_by_key(|(_, action)| match action {
1669 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1670 CodeActionsItem::CodeAction { action, .. } => {
1671 action.lsp_action.title.chars().count()
1672 }
1673 })
1674 .map(|(ix, _)| ix),
1675 )
1676 .with_sizing_behavior(ListSizingBehavior::Infer)
1677 .into_any_element();
1678
1679 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1680 ContextMenuOrigin::GutterIndicator(row)
1681 } else {
1682 ContextMenuOrigin::EditorPoint(cursor_position)
1683 };
1684
1685 (cursor_position, element)
1686 }
1687}
1688
1689#[derive(Debug)]
1690struct ActiveDiagnosticGroup {
1691 primary_range: Range<Anchor>,
1692 primary_message: String,
1693 group_id: usize,
1694 blocks: HashMap<CustomBlockId, Diagnostic>,
1695 is_valid: bool,
1696}
1697
1698#[derive(Serialize, Deserialize, Clone, Debug)]
1699pub struct ClipboardSelection {
1700 pub len: usize,
1701 pub is_entire_line: bool,
1702 pub first_line_indent: u32,
1703}
1704
1705#[derive(Debug)]
1706pub(crate) struct NavigationData {
1707 cursor_anchor: Anchor,
1708 cursor_position: Point,
1709 scroll_anchor: ScrollAnchor,
1710 scroll_top_row: u32,
1711}
1712
1713#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1714pub enum GotoDefinitionKind {
1715 Symbol,
1716 Declaration,
1717 Type,
1718 Implementation,
1719}
1720
1721#[derive(Debug, Clone)]
1722enum InlayHintRefreshReason {
1723 Toggle(bool),
1724 SettingsChange(InlayHintSettings),
1725 NewLinesShown,
1726 BufferEdited(HashSet<Arc<Language>>),
1727 RefreshRequested,
1728 ExcerptsRemoved(Vec<ExcerptId>),
1729}
1730
1731impl InlayHintRefreshReason {
1732 fn description(&self) -> &'static str {
1733 match self {
1734 Self::Toggle(_) => "toggle",
1735 Self::SettingsChange(_) => "settings change",
1736 Self::NewLinesShown => "new lines shown",
1737 Self::BufferEdited(_) => "buffer edited",
1738 Self::RefreshRequested => "refresh requested",
1739 Self::ExcerptsRemoved(_) => "excerpts removed",
1740 }
1741 }
1742}
1743
1744pub(crate) struct FocusedBlock {
1745 id: BlockId,
1746 focus_handle: WeakFocusHandle,
1747}
1748
1749#[derive(Clone)]
1750struct JumpData {
1751 excerpt_id: ExcerptId,
1752 position: Point,
1753 anchor: text::Anchor,
1754 path: Option<project::ProjectPath>,
1755 line_offset_from_top: u32,
1756}
1757
1758impl Editor {
1759 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1760 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1761 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1762 Self::new(
1763 EditorMode::SingleLine { auto_width: false },
1764 buffer,
1765 None,
1766 false,
1767 cx,
1768 )
1769 }
1770
1771 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1772 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1773 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1774 Self::new(EditorMode::Full, buffer, None, false, cx)
1775 }
1776
1777 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1778 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1779 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1780 Self::new(
1781 EditorMode::SingleLine { auto_width: true },
1782 buffer,
1783 None,
1784 false,
1785 cx,
1786 )
1787 }
1788
1789 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1790 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1791 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1792 Self::new(
1793 EditorMode::AutoHeight { max_lines },
1794 buffer,
1795 None,
1796 false,
1797 cx,
1798 )
1799 }
1800
1801 pub fn for_buffer(
1802 buffer: Model<Buffer>,
1803 project: Option<Model<Project>>,
1804 cx: &mut ViewContext<Self>,
1805 ) -> Self {
1806 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1807 Self::new(EditorMode::Full, buffer, project, false, cx)
1808 }
1809
1810 pub fn for_multibuffer(
1811 buffer: Model<MultiBuffer>,
1812 project: Option<Model<Project>>,
1813 show_excerpt_controls: bool,
1814 cx: &mut ViewContext<Self>,
1815 ) -> Self {
1816 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1817 }
1818
1819 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1820 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1821 let mut clone = Self::new(
1822 self.mode,
1823 self.buffer.clone(),
1824 self.project.clone(),
1825 show_excerpt_controls,
1826 cx,
1827 );
1828 self.display_map.update(cx, |display_map, cx| {
1829 let snapshot = display_map.snapshot(cx);
1830 clone.display_map.update(cx, |display_map, cx| {
1831 display_map.set_state(&snapshot, cx);
1832 });
1833 });
1834 clone.selections.clone_state(&self.selections);
1835 clone.scroll_manager.clone_state(&self.scroll_manager);
1836 clone.searchable = self.searchable;
1837 clone
1838 }
1839
1840 pub fn new(
1841 mode: EditorMode,
1842 buffer: Model<MultiBuffer>,
1843 project: Option<Model<Project>>,
1844 show_excerpt_controls: bool,
1845 cx: &mut ViewContext<Self>,
1846 ) -> Self {
1847 let style = cx.text_style();
1848 let font_size = style.font_size.to_pixels(cx.rem_size());
1849 let editor = cx.view().downgrade();
1850 let fold_placeholder = FoldPlaceholder {
1851 constrain_width: true,
1852 render: Arc::new(move |fold_id, fold_range, cx| {
1853 let editor = editor.clone();
1854 div()
1855 .id(fold_id)
1856 .bg(cx.theme().colors().ghost_element_background)
1857 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1858 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1859 .rounded_sm()
1860 .size_full()
1861 .cursor_pointer()
1862 .child("⋯")
1863 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1864 .on_click(move |_, cx| {
1865 editor
1866 .update(cx, |editor, cx| {
1867 editor.unfold_ranges(
1868 &[fold_range.start..fold_range.end],
1869 true,
1870 false,
1871 cx,
1872 );
1873 cx.stop_propagation();
1874 })
1875 .ok();
1876 })
1877 .into_any()
1878 }),
1879 merge_adjacent: true,
1880 ..Default::default()
1881 };
1882 let display_map = cx.new_model(|cx| {
1883 DisplayMap::new(
1884 buffer.clone(),
1885 style.font(),
1886 font_size,
1887 None,
1888 show_excerpt_controls,
1889 FILE_HEADER_HEIGHT,
1890 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1891 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1892 fold_placeholder,
1893 cx,
1894 )
1895 });
1896
1897 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1898
1899 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1900
1901 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1902 .then(|| language_settings::SoftWrap::None);
1903
1904 let mut project_subscriptions = Vec::new();
1905 if mode == EditorMode::Full {
1906 if let Some(project) = project.as_ref() {
1907 if buffer.read(cx).is_singleton() {
1908 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1909 cx.emit(EditorEvent::TitleChanged);
1910 }));
1911 }
1912 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1913 if let project::Event::RefreshInlayHints = event {
1914 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1915 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1916 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1917 let focus_handle = editor.focus_handle(cx);
1918 if focus_handle.is_focused(cx) {
1919 let snapshot = buffer.read(cx).snapshot();
1920 for (range, snippet) in snippet_edits {
1921 let editor_range =
1922 language::range_from_lsp(*range).to_offset(&snapshot);
1923 editor
1924 .insert_snippet(&[editor_range], snippet.clone(), cx)
1925 .ok();
1926 }
1927 }
1928 }
1929 }
1930 }));
1931 if let Some(task_inventory) = project
1932 .read(cx)
1933 .task_store()
1934 .read(cx)
1935 .task_inventory()
1936 .cloned()
1937 {
1938 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1939 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1940 }));
1941 }
1942 }
1943 }
1944
1945 let inlay_hint_settings = inlay_hint_settings(
1946 selections.newest_anchor().head(),
1947 &buffer.read(cx).snapshot(cx),
1948 cx,
1949 );
1950 let focus_handle = cx.focus_handle();
1951 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1952 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1953 .detach();
1954 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1955 .detach();
1956 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1957
1958 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1959 Some(false)
1960 } else {
1961 None
1962 };
1963
1964 let mut code_action_providers = Vec::new();
1965 if let Some(project) = project.clone() {
1966 code_action_providers.push(Arc::new(project) as Arc<_>);
1967 }
1968
1969 let mut this = Self {
1970 focus_handle,
1971 show_cursor_when_unfocused: false,
1972 last_focused_descendant: None,
1973 buffer: buffer.clone(),
1974 display_map: display_map.clone(),
1975 selections,
1976 scroll_manager: ScrollManager::new(cx),
1977 columnar_selection_tail: None,
1978 add_selections_state: None,
1979 select_next_state: None,
1980 select_prev_state: None,
1981 selection_history: Default::default(),
1982 autoclose_regions: Default::default(),
1983 snippet_stack: Default::default(),
1984 select_larger_syntax_node_stack: Vec::new(),
1985 ime_transaction: Default::default(),
1986 active_diagnostics: None,
1987 soft_wrap_mode_override,
1988 completion_provider: project.clone().map(|project| Box::new(project) as _),
1989 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1990 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1991 project,
1992 blink_manager: blink_manager.clone(),
1993 show_local_selections: true,
1994 mode,
1995 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1996 show_gutter: mode == EditorMode::Full,
1997 show_line_numbers: None,
1998 use_relative_line_numbers: None,
1999 show_git_diff_gutter: None,
2000 show_code_actions: None,
2001 show_runnables: None,
2002 show_wrap_guides: None,
2003 show_indent_guides,
2004 placeholder_text: None,
2005 highlight_order: 0,
2006 highlighted_rows: HashMap::default(),
2007 background_highlights: Default::default(),
2008 gutter_highlights: TreeMap::default(),
2009 scrollbar_marker_state: ScrollbarMarkerState::default(),
2010 active_indent_guides_state: ActiveIndentGuidesState::default(),
2011 nav_history: None,
2012 context_menu: RwLock::new(None),
2013 mouse_context_menu: None,
2014 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2015 completion_tasks: Default::default(),
2016 signature_help_state: SignatureHelpState::default(),
2017 auto_signature_help: None,
2018 find_all_references_task_sources: Vec::new(),
2019 next_completion_id: 0,
2020 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2021 next_inlay_id: 0,
2022 code_action_providers,
2023 available_code_actions: Default::default(),
2024 code_actions_task: Default::default(),
2025 document_highlights_task: Default::default(),
2026 linked_editing_range_task: Default::default(),
2027 pending_rename: Default::default(),
2028 searchable: true,
2029 cursor_shape: EditorSettings::get_global(cx)
2030 .cursor_shape
2031 .unwrap_or_default(),
2032 current_line_highlight: None,
2033 autoindent_mode: Some(AutoindentMode::EachLine),
2034 collapse_matches: false,
2035 workspace: None,
2036 input_enabled: true,
2037 use_modal_editing: mode == EditorMode::Full,
2038 read_only: false,
2039 use_autoclose: true,
2040 use_auto_surround: true,
2041 auto_replace_emoji_shortcode: false,
2042 leader_peer_id: None,
2043 remote_id: None,
2044 hover_state: Default::default(),
2045 hovered_link_state: Default::default(),
2046 inline_completion_provider: None,
2047 active_inline_completion: None,
2048 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2049 expanded_hunks: ExpandedHunks::default(),
2050 gutter_hovered: false,
2051 pixel_position_of_newest_cursor: None,
2052 last_bounds: None,
2053 expect_bounds_change: None,
2054 gutter_dimensions: GutterDimensions::default(),
2055 style: None,
2056 show_cursor_names: false,
2057 hovered_cursors: Default::default(),
2058 next_editor_action_id: EditorActionId::default(),
2059 editor_actions: Rc::default(),
2060 show_inline_completions_override: None,
2061 enable_inline_completions: true,
2062 custom_context_menu: None,
2063 show_git_blame_gutter: false,
2064 show_git_blame_inline: false,
2065 show_selection_menu: None,
2066 show_git_blame_inline_delay_task: None,
2067 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2068 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2069 .session
2070 .restore_unsaved_buffers,
2071 blame: None,
2072 blame_subscription: None,
2073 tasks: Default::default(),
2074 _subscriptions: vec![
2075 cx.observe(&buffer, Self::on_buffer_changed),
2076 cx.subscribe(&buffer, Self::on_buffer_event),
2077 cx.observe(&display_map, Self::on_display_map_changed),
2078 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2079 cx.observe_global::<SettingsStore>(Self::settings_changed),
2080 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2081 cx.observe_window_activation(|editor, cx| {
2082 let active = cx.is_window_active();
2083 editor.blink_manager.update(cx, |blink_manager, cx| {
2084 if active {
2085 blink_manager.enable(cx);
2086 } else {
2087 blink_manager.disable(cx);
2088 }
2089 });
2090 }),
2091 ],
2092 tasks_update_task: None,
2093 linked_edit_ranges: Default::default(),
2094 previous_search_ranges: None,
2095 breadcrumb_header: None,
2096 focused_block: None,
2097 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2098 addons: HashMap::default(),
2099 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2100 text_style_refinement: None,
2101 };
2102 this.tasks_update_task = Some(this.refresh_runnables(cx));
2103 this._subscriptions.extend(project_subscriptions);
2104
2105 this.end_selection(cx);
2106 this.scroll_manager.show_scrollbar(cx);
2107
2108 if mode == EditorMode::Full {
2109 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2110 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2111
2112 if this.git_blame_inline_enabled {
2113 this.git_blame_inline_enabled = true;
2114 this.start_git_blame_inline(false, cx);
2115 }
2116 }
2117
2118 this.report_editor_event("open", None, cx);
2119 this
2120 }
2121
2122 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2123 self.mouse_context_menu
2124 .as_ref()
2125 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2126 }
2127
2128 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2129 let mut key_context = KeyContext::new_with_defaults();
2130 key_context.add("Editor");
2131 let mode = match self.mode {
2132 EditorMode::SingleLine { .. } => "single_line",
2133 EditorMode::AutoHeight { .. } => "auto_height",
2134 EditorMode::Full => "full",
2135 };
2136
2137 if EditorSettings::jupyter_enabled(cx) {
2138 key_context.add("jupyter");
2139 }
2140
2141 key_context.set("mode", mode);
2142 if self.pending_rename.is_some() {
2143 key_context.add("renaming");
2144 }
2145 if self.context_menu_visible() {
2146 match self.context_menu.read().as_ref() {
2147 Some(ContextMenu::Completions(_)) => {
2148 key_context.add("menu");
2149 key_context.add("showing_completions")
2150 }
2151 Some(ContextMenu::CodeActions(_)) => {
2152 key_context.add("menu");
2153 key_context.add("showing_code_actions")
2154 }
2155 None => {}
2156 }
2157 }
2158
2159 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2160 if !self.focus_handle(cx).contains_focused(cx)
2161 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2162 {
2163 for addon in self.addons.values() {
2164 addon.extend_key_context(&mut key_context, cx)
2165 }
2166 }
2167
2168 if let Some(extension) = self
2169 .buffer
2170 .read(cx)
2171 .as_singleton()
2172 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2173 {
2174 key_context.set("extension", extension.to_string());
2175 }
2176
2177 if self.has_active_inline_completion(cx) {
2178 key_context.add("copilot_suggestion");
2179 key_context.add("inline_completion");
2180 }
2181
2182 key_context
2183 }
2184
2185 pub fn new_file(
2186 workspace: &mut Workspace,
2187 _: &workspace::NewFile,
2188 cx: &mut ViewContext<Workspace>,
2189 ) {
2190 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2191 "Failed to create buffer",
2192 cx,
2193 |e, _| match e.error_code() {
2194 ErrorCode::RemoteUpgradeRequired => Some(format!(
2195 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2196 e.error_tag("required").unwrap_or("the latest version")
2197 )),
2198 _ => None,
2199 },
2200 );
2201 }
2202
2203 pub fn new_in_workspace(
2204 workspace: &mut Workspace,
2205 cx: &mut ViewContext<Workspace>,
2206 ) -> Task<Result<View<Editor>>> {
2207 let project = workspace.project().clone();
2208 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2209
2210 cx.spawn(|workspace, mut cx| async move {
2211 let buffer = create.await?;
2212 workspace.update(&mut cx, |workspace, cx| {
2213 let editor =
2214 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2215 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2216 editor
2217 })
2218 })
2219 }
2220
2221 fn new_file_vertical(
2222 workspace: &mut Workspace,
2223 _: &workspace::NewFileSplitVertical,
2224 cx: &mut ViewContext<Workspace>,
2225 ) {
2226 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2227 }
2228
2229 fn new_file_horizontal(
2230 workspace: &mut Workspace,
2231 _: &workspace::NewFileSplitHorizontal,
2232 cx: &mut ViewContext<Workspace>,
2233 ) {
2234 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2235 }
2236
2237 fn new_file_in_direction(
2238 workspace: &mut Workspace,
2239 direction: SplitDirection,
2240 cx: &mut ViewContext<Workspace>,
2241 ) {
2242 let project = workspace.project().clone();
2243 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2244
2245 cx.spawn(|workspace, mut cx| async move {
2246 let buffer = create.await?;
2247 workspace.update(&mut cx, move |workspace, cx| {
2248 workspace.split_item(
2249 direction,
2250 Box::new(
2251 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2252 ),
2253 cx,
2254 )
2255 })?;
2256 anyhow::Ok(())
2257 })
2258 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2259 ErrorCode::RemoteUpgradeRequired => Some(format!(
2260 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2261 e.error_tag("required").unwrap_or("the latest version")
2262 )),
2263 _ => None,
2264 });
2265 }
2266
2267 pub fn leader_peer_id(&self) -> Option<PeerId> {
2268 self.leader_peer_id
2269 }
2270
2271 pub fn buffer(&self) -> &Model<MultiBuffer> {
2272 &self.buffer
2273 }
2274
2275 pub fn workspace(&self) -> Option<View<Workspace>> {
2276 self.workspace.as_ref()?.0.upgrade()
2277 }
2278
2279 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2280 self.buffer().read(cx).title(cx)
2281 }
2282
2283 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2284 let git_blame_gutter_max_author_length = self
2285 .render_git_blame_gutter(cx)
2286 .then(|| {
2287 if let Some(blame) = self.blame.as_ref() {
2288 let max_author_length =
2289 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2290 Some(max_author_length)
2291 } else {
2292 None
2293 }
2294 })
2295 .flatten();
2296
2297 EditorSnapshot {
2298 mode: self.mode,
2299 show_gutter: self.show_gutter,
2300 show_line_numbers: self.show_line_numbers,
2301 show_git_diff_gutter: self.show_git_diff_gutter,
2302 show_code_actions: self.show_code_actions,
2303 show_runnables: self.show_runnables,
2304 git_blame_gutter_max_author_length,
2305 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2306 scroll_anchor: self.scroll_manager.anchor(),
2307 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2308 placeholder_text: self.placeholder_text.clone(),
2309 is_focused: self.focus_handle.is_focused(cx),
2310 current_line_highlight: self
2311 .current_line_highlight
2312 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2313 gutter_hovered: self.gutter_hovered,
2314 }
2315 }
2316
2317 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2318 self.buffer.read(cx).language_at(point, cx)
2319 }
2320
2321 pub fn file_at<T: ToOffset>(
2322 &self,
2323 point: T,
2324 cx: &AppContext,
2325 ) -> Option<Arc<dyn language::File>> {
2326 self.buffer.read(cx).read(cx).file_at(point).cloned()
2327 }
2328
2329 pub fn active_excerpt(
2330 &self,
2331 cx: &AppContext,
2332 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2333 self.buffer
2334 .read(cx)
2335 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2336 }
2337
2338 pub fn mode(&self) -> EditorMode {
2339 self.mode
2340 }
2341
2342 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2343 self.collaboration_hub.as_deref()
2344 }
2345
2346 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2347 self.collaboration_hub = Some(hub);
2348 }
2349
2350 pub fn set_custom_context_menu(
2351 &mut self,
2352 f: impl 'static
2353 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2354 ) {
2355 self.custom_context_menu = Some(Box::new(f))
2356 }
2357
2358 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2359 self.completion_provider = provider;
2360 }
2361
2362 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2363 self.semantics_provider.clone()
2364 }
2365
2366 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2367 self.semantics_provider = provider;
2368 }
2369
2370 pub fn set_inline_completion_provider<T>(
2371 &mut self,
2372 provider: Option<Model<T>>,
2373 cx: &mut ViewContext<Self>,
2374 ) where
2375 T: InlineCompletionProvider,
2376 {
2377 self.inline_completion_provider =
2378 provider.map(|provider| RegisteredInlineCompletionProvider {
2379 _subscription: cx.observe(&provider, |this, _, cx| {
2380 if this.focus_handle.is_focused(cx) {
2381 this.update_visible_inline_completion(cx);
2382 }
2383 }),
2384 provider: Arc::new(provider),
2385 });
2386 self.refresh_inline_completion(false, false, cx);
2387 }
2388
2389 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2390 self.placeholder_text.as_deref()
2391 }
2392
2393 pub fn set_placeholder_text(
2394 &mut self,
2395 placeholder_text: impl Into<Arc<str>>,
2396 cx: &mut ViewContext<Self>,
2397 ) {
2398 let placeholder_text = Some(placeholder_text.into());
2399 if self.placeholder_text != placeholder_text {
2400 self.placeholder_text = placeholder_text;
2401 cx.notify();
2402 }
2403 }
2404
2405 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2406 self.cursor_shape = cursor_shape;
2407
2408 // Disrupt blink for immediate user feedback that the cursor shape has changed
2409 self.blink_manager.update(cx, BlinkManager::show_cursor);
2410
2411 cx.notify();
2412 }
2413
2414 pub fn set_current_line_highlight(
2415 &mut self,
2416 current_line_highlight: Option<CurrentLineHighlight>,
2417 ) {
2418 self.current_line_highlight = current_line_highlight;
2419 }
2420
2421 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2422 self.collapse_matches = collapse_matches;
2423 }
2424
2425 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2426 if self.collapse_matches {
2427 return range.start..range.start;
2428 }
2429 range.clone()
2430 }
2431
2432 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2433 if self.display_map.read(cx).clip_at_line_ends != clip {
2434 self.display_map
2435 .update(cx, |map, _| map.clip_at_line_ends = clip);
2436 }
2437 }
2438
2439 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2440 self.input_enabled = input_enabled;
2441 }
2442
2443 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2444 self.enable_inline_completions = enabled;
2445 }
2446
2447 pub fn set_autoindent(&mut self, autoindent: bool) {
2448 if autoindent {
2449 self.autoindent_mode = Some(AutoindentMode::EachLine);
2450 } else {
2451 self.autoindent_mode = None;
2452 }
2453 }
2454
2455 pub fn read_only(&self, cx: &AppContext) -> bool {
2456 self.read_only || self.buffer.read(cx).read_only()
2457 }
2458
2459 pub fn set_read_only(&mut self, read_only: bool) {
2460 self.read_only = read_only;
2461 }
2462
2463 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2464 self.use_autoclose = autoclose;
2465 }
2466
2467 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2468 self.use_auto_surround = auto_surround;
2469 }
2470
2471 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2472 self.auto_replace_emoji_shortcode = auto_replace;
2473 }
2474
2475 pub fn toggle_inline_completions(
2476 &mut self,
2477 _: &ToggleInlineCompletions,
2478 cx: &mut ViewContext<Self>,
2479 ) {
2480 if self.show_inline_completions_override.is_some() {
2481 self.set_show_inline_completions(None, cx);
2482 } else {
2483 let cursor = self.selections.newest_anchor().head();
2484 if let Some((buffer, cursor_buffer_position)) =
2485 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2486 {
2487 let show_inline_completions =
2488 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2489 self.set_show_inline_completions(Some(show_inline_completions), cx);
2490 }
2491 }
2492 }
2493
2494 pub fn set_show_inline_completions(
2495 &mut self,
2496 show_inline_completions: Option<bool>,
2497 cx: &mut ViewContext<Self>,
2498 ) {
2499 self.show_inline_completions_override = show_inline_completions;
2500 self.refresh_inline_completion(false, true, cx);
2501 }
2502
2503 fn should_show_inline_completions(
2504 &self,
2505 buffer: &Model<Buffer>,
2506 buffer_position: language::Anchor,
2507 cx: &AppContext,
2508 ) -> bool {
2509 if !self.snippet_stack.is_empty() {
2510 return false;
2511 }
2512
2513 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2514 return false;
2515 }
2516
2517 if let Some(provider) = self.inline_completion_provider() {
2518 if let Some(show_inline_completions) = self.show_inline_completions_override {
2519 show_inline_completions
2520 } else {
2521 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2522 }
2523 } else {
2524 false
2525 }
2526 }
2527
2528 fn inline_completions_disabled_in_scope(
2529 &self,
2530 buffer: &Model<Buffer>,
2531 buffer_position: language::Anchor,
2532 cx: &AppContext,
2533 ) -> bool {
2534 let snapshot = buffer.read(cx).snapshot();
2535 let settings = snapshot.settings_at(buffer_position, cx);
2536
2537 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2538 return false;
2539 };
2540
2541 scope.override_name().map_or(false, |scope_name| {
2542 settings
2543 .inline_completions_disabled_in
2544 .iter()
2545 .any(|s| s == scope_name)
2546 })
2547 }
2548
2549 pub fn set_use_modal_editing(&mut self, to: bool) {
2550 self.use_modal_editing = to;
2551 }
2552
2553 pub fn use_modal_editing(&self) -> bool {
2554 self.use_modal_editing
2555 }
2556
2557 fn selections_did_change(
2558 &mut self,
2559 local: bool,
2560 old_cursor_position: &Anchor,
2561 show_completions: bool,
2562 cx: &mut ViewContext<Self>,
2563 ) {
2564 cx.invalidate_character_coordinates();
2565
2566 // Copy selections to primary selection buffer
2567 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2568 if local {
2569 let selections = self.selections.all::<usize>(cx);
2570 let buffer_handle = self.buffer.read(cx).read(cx);
2571
2572 let mut text = String::new();
2573 for (index, selection) in selections.iter().enumerate() {
2574 let text_for_selection = buffer_handle
2575 .text_for_range(selection.start..selection.end)
2576 .collect::<String>();
2577
2578 text.push_str(&text_for_selection);
2579 if index != selections.len() - 1 {
2580 text.push('\n');
2581 }
2582 }
2583
2584 if !text.is_empty() {
2585 cx.write_to_primary(ClipboardItem::new_string(text));
2586 }
2587 }
2588
2589 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2590 self.buffer.update(cx, |buffer, cx| {
2591 buffer.set_active_selections(
2592 &self.selections.disjoint_anchors(),
2593 self.selections.line_mode,
2594 self.cursor_shape,
2595 cx,
2596 )
2597 });
2598 }
2599 let display_map = self
2600 .display_map
2601 .update(cx, |display_map, cx| display_map.snapshot(cx));
2602 let buffer = &display_map.buffer_snapshot;
2603 self.add_selections_state = None;
2604 self.select_next_state = None;
2605 self.select_prev_state = None;
2606 self.select_larger_syntax_node_stack.clear();
2607 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2608 self.snippet_stack
2609 .invalidate(&self.selections.disjoint_anchors(), buffer);
2610 self.take_rename(false, cx);
2611
2612 let new_cursor_position = self.selections.newest_anchor().head();
2613
2614 self.push_to_nav_history(
2615 *old_cursor_position,
2616 Some(new_cursor_position.to_point(buffer)),
2617 cx,
2618 );
2619
2620 if local {
2621 let new_cursor_position = self.selections.newest_anchor().head();
2622 let mut context_menu = self.context_menu.write();
2623 let completion_menu = match context_menu.as_ref() {
2624 Some(ContextMenu::Completions(menu)) => Some(menu),
2625
2626 _ => {
2627 *context_menu = None;
2628 None
2629 }
2630 };
2631
2632 if let Some(completion_menu) = completion_menu {
2633 let cursor_position = new_cursor_position.to_offset(buffer);
2634 let (word_range, kind) =
2635 buffer.surrounding_word(completion_menu.initial_position, true);
2636 if kind == Some(CharKind::Word)
2637 && word_range.to_inclusive().contains(&cursor_position)
2638 {
2639 let mut completion_menu = completion_menu.clone();
2640 drop(context_menu);
2641
2642 let query = Self::completion_query(buffer, cursor_position);
2643 cx.spawn(move |this, mut cx| async move {
2644 completion_menu
2645 .filter(query.as_deref(), cx.background_executor().clone())
2646 .await;
2647
2648 this.update(&mut cx, |this, cx| {
2649 let mut context_menu = this.context_menu.write();
2650 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2651 return;
2652 };
2653
2654 if menu.id > completion_menu.id {
2655 return;
2656 }
2657
2658 *context_menu = Some(ContextMenu::Completions(completion_menu));
2659 drop(context_menu);
2660 cx.notify();
2661 })
2662 })
2663 .detach();
2664
2665 if show_completions {
2666 self.show_completions(&ShowCompletions { trigger: None }, cx);
2667 }
2668 } else {
2669 drop(context_menu);
2670 self.hide_context_menu(cx);
2671 }
2672 } else {
2673 drop(context_menu);
2674 }
2675
2676 hide_hover(self, cx);
2677
2678 if old_cursor_position.to_display_point(&display_map).row()
2679 != new_cursor_position.to_display_point(&display_map).row()
2680 {
2681 self.available_code_actions.take();
2682 }
2683 self.refresh_code_actions(cx);
2684 self.refresh_document_highlights(cx);
2685 refresh_matching_bracket_highlights(self, cx);
2686 self.discard_inline_completion(false, cx);
2687 linked_editing_ranges::refresh_linked_ranges(self, cx);
2688 if self.git_blame_inline_enabled {
2689 self.start_inline_blame_timer(cx);
2690 }
2691 }
2692
2693 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2694 cx.emit(EditorEvent::SelectionsChanged { local });
2695
2696 if self.selections.disjoint_anchors().len() == 1 {
2697 cx.emit(SearchEvent::ActiveMatchChanged)
2698 }
2699 cx.notify();
2700 }
2701
2702 pub fn change_selections<R>(
2703 &mut self,
2704 autoscroll: Option<Autoscroll>,
2705 cx: &mut ViewContext<Self>,
2706 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2707 ) -> R {
2708 self.change_selections_inner(autoscroll, true, cx, change)
2709 }
2710
2711 pub fn change_selections_inner<R>(
2712 &mut self,
2713 autoscroll: Option<Autoscroll>,
2714 request_completions: bool,
2715 cx: &mut ViewContext<Self>,
2716 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2717 ) -> R {
2718 let old_cursor_position = self.selections.newest_anchor().head();
2719 self.push_to_selection_history();
2720
2721 let (changed, result) = self.selections.change_with(cx, change);
2722
2723 if changed {
2724 if let Some(autoscroll) = autoscroll {
2725 self.request_autoscroll(autoscroll, cx);
2726 }
2727 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2728
2729 if self.should_open_signature_help_automatically(
2730 &old_cursor_position,
2731 self.signature_help_state.backspace_pressed(),
2732 cx,
2733 ) {
2734 self.show_signature_help(&ShowSignatureHelp, cx);
2735 }
2736 self.signature_help_state.set_backspace_pressed(false);
2737 }
2738
2739 result
2740 }
2741
2742 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2743 where
2744 I: IntoIterator<Item = (Range<S>, T)>,
2745 S: ToOffset,
2746 T: Into<Arc<str>>,
2747 {
2748 if self.read_only(cx) {
2749 return;
2750 }
2751
2752 self.buffer
2753 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2754 }
2755
2756 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2757 where
2758 I: IntoIterator<Item = (Range<S>, T)>,
2759 S: ToOffset,
2760 T: Into<Arc<str>>,
2761 {
2762 if self.read_only(cx) {
2763 return;
2764 }
2765
2766 self.buffer.update(cx, |buffer, cx| {
2767 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2768 });
2769 }
2770
2771 pub fn edit_with_block_indent<I, S, T>(
2772 &mut self,
2773 edits: I,
2774 original_indent_columns: Vec<u32>,
2775 cx: &mut ViewContext<Self>,
2776 ) where
2777 I: IntoIterator<Item = (Range<S>, T)>,
2778 S: ToOffset,
2779 T: Into<Arc<str>>,
2780 {
2781 if self.read_only(cx) {
2782 return;
2783 }
2784
2785 self.buffer.update(cx, |buffer, cx| {
2786 buffer.edit(
2787 edits,
2788 Some(AutoindentMode::Block {
2789 original_indent_columns,
2790 }),
2791 cx,
2792 )
2793 });
2794 }
2795
2796 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2797 self.hide_context_menu(cx);
2798
2799 match phase {
2800 SelectPhase::Begin {
2801 position,
2802 add,
2803 click_count,
2804 } => self.begin_selection(position, add, click_count, cx),
2805 SelectPhase::BeginColumnar {
2806 position,
2807 goal_column,
2808 reset,
2809 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2810 SelectPhase::Extend {
2811 position,
2812 click_count,
2813 } => self.extend_selection(position, click_count, cx),
2814 SelectPhase::Update {
2815 position,
2816 goal_column,
2817 scroll_delta,
2818 } => self.update_selection(position, goal_column, scroll_delta, cx),
2819 SelectPhase::End => self.end_selection(cx),
2820 }
2821 }
2822
2823 fn extend_selection(
2824 &mut self,
2825 position: DisplayPoint,
2826 click_count: usize,
2827 cx: &mut ViewContext<Self>,
2828 ) {
2829 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2830 let tail = self.selections.newest::<usize>(cx).tail();
2831 self.begin_selection(position, false, click_count, cx);
2832
2833 let position = position.to_offset(&display_map, Bias::Left);
2834 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2835
2836 let mut pending_selection = self
2837 .selections
2838 .pending_anchor()
2839 .expect("extend_selection not called with pending selection");
2840 if position >= tail {
2841 pending_selection.start = tail_anchor;
2842 } else {
2843 pending_selection.end = tail_anchor;
2844 pending_selection.reversed = true;
2845 }
2846
2847 let mut pending_mode = self.selections.pending_mode().unwrap();
2848 match &mut pending_mode {
2849 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2850 _ => {}
2851 }
2852
2853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2854 s.set_pending(pending_selection, pending_mode)
2855 });
2856 }
2857
2858 fn begin_selection(
2859 &mut self,
2860 position: DisplayPoint,
2861 add: bool,
2862 click_count: usize,
2863 cx: &mut ViewContext<Self>,
2864 ) {
2865 if !self.focus_handle.is_focused(cx) {
2866 self.last_focused_descendant = None;
2867 cx.focus(&self.focus_handle);
2868 }
2869
2870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2871 let buffer = &display_map.buffer_snapshot;
2872 let newest_selection = self.selections.newest_anchor().clone();
2873 let position = display_map.clip_point(position, Bias::Left);
2874
2875 let start;
2876 let end;
2877 let mode;
2878 let auto_scroll;
2879 match click_count {
2880 1 => {
2881 start = buffer.anchor_before(position.to_point(&display_map));
2882 end = start;
2883 mode = SelectMode::Character;
2884 auto_scroll = true;
2885 }
2886 2 => {
2887 let range = movement::surrounding_word(&display_map, position);
2888 start = buffer.anchor_before(range.start.to_point(&display_map));
2889 end = buffer.anchor_before(range.end.to_point(&display_map));
2890 mode = SelectMode::Word(start..end);
2891 auto_scroll = true;
2892 }
2893 3 => {
2894 let position = display_map
2895 .clip_point(position, Bias::Left)
2896 .to_point(&display_map);
2897 let line_start = display_map.prev_line_boundary(position).0;
2898 let next_line_start = buffer.clip_point(
2899 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2900 Bias::Left,
2901 );
2902 start = buffer.anchor_before(line_start);
2903 end = buffer.anchor_before(next_line_start);
2904 mode = SelectMode::Line(start..end);
2905 auto_scroll = true;
2906 }
2907 _ => {
2908 start = buffer.anchor_before(0);
2909 end = buffer.anchor_before(buffer.len());
2910 mode = SelectMode::All;
2911 auto_scroll = false;
2912 }
2913 }
2914
2915 let point_to_delete: Option<usize> = {
2916 let selected_points: Vec<Selection<Point>> =
2917 self.selections.disjoint_in_range(start..end, cx);
2918
2919 if !add || click_count > 1 {
2920 None
2921 } else if !selected_points.is_empty() {
2922 Some(selected_points[0].id)
2923 } else {
2924 let clicked_point_already_selected =
2925 self.selections.disjoint.iter().find(|selection| {
2926 selection.start.to_point(buffer) == start.to_point(buffer)
2927 || selection.end.to_point(buffer) == end.to_point(buffer)
2928 });
2929
2930 clicked_point_already_selected.map(|selection| selection.id)
2931 }
2932 };
2933
2934 let selections_count = self.selections.count();
2935
2936 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2937 if let Some(point_to_delete) = point_to_delete {
2938 s.delete(point_to_delete);
2939
2940 if selections_count == 1 {
2941 s.set_pending_anchor_range(start..end, mode);
2942 }
2943 } else {
2944 if !add {
2945 s.clear_disjoint();
2946 } else if click_count > 1 {
2947 s.delete(newest_selection.id)
2948 }
2949
2950 s.set_pending_anchor_range(start..end, mode);
2951 }
2952 });
2953 }
2954
2955 fn begin_columnar_selection(
2956 &mut self,
2957 position: DisplayPoint,
2958 goal_column: u32,
2959 reset: bool,
2960 cx: &mut ViewContext<Self>,
2961 ) {
2962 if !self.focus_handle.is_focused(cx) {
2963 self.last_focused_descendant = None;
2964 cx.focus(&self.focus_handle);
2965 }
2966
2967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2968
2969 if reset {
2970 let pointer_position = display_map
2971 .buffer_snapshot
2972 .anchor_before(position.to_point(&display_map));
2973
2974 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2975 s.clear_disjoint();
2976 s.set_pending_anchor_range(
2977 pointer_position..pointer_position,
2978 SelectMode::Character,
2979 );
2980 });
2981 }
2982
2983 let tail = self.selections.newest::<Point>(cx).tail();
2984 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2985
2986 if !reset {
2987 self.select_columns(
2988 tail.to_display_point(&display_map),
2989 position,
2990 goal_column,
2991 &display_map,
2992 cx,
2993 );
2994 }
2995 }
2996
2997 fn update_selection(
2998 &mut self,
2999 position: DisplayPoint,
3000 goal_column: u32,
3001 scroll_delta: gpui::Point<f32>,
3002 cx: &mut ViewContext<Self>,
3003 ) {
3004 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3005
3006 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3007 let tail = tail.to_display_point(&display_map);
3008 self.select_columns(tail, position, goal_column, &display_map, cx);
3009 } else if let Some(mut pending) = self.selections.pending_anchor() {
3010 let buffer = self.buffer.read(cx).snapshot(cx);
3011 let head;
3012 let tail;
3013 let mode = self.selections.pending_mode().unwrap();
3014 match &mode {
3015 SelectMode::Character => {
3016 head = position.to_point(&display_map);
3017 tail = pending.tail().to_point(&buffer);
3018 }
3019 SelectMode::Word(original_range) => {
3020 let original_display_range = original_range.start.to_display_point(&display_map)
3021 ..original_range.end.to_display_point(&display_map);
3022 let original_buffer_range = original_display_range.start.to_point(&display_map)
3023 ..original_display_range.end.to_point(&display_map);
3024 if movement::is_inside_word(&display_map, position)
3025 || original_display_range.contains(&position)
3026 {
3027 let word_range = movement::surrounding_word(&display_map, position);
3028 if word_range.start < original_display_range.start {
3029 head = word_range.start.to_point(&display_map);
3030 } else {
3031 head = word_range.end.to_point(&display_map);
3032 }
3033 } else {
3034 head = position.to_point(&display_map);
3035 }
3036
3037 if head <= original_buffer_range.start {
3038 tail = original_buffer_range.end;
3039 } else {
3040 tail = original_buffer_range.start;
3041 }
3042 }
3043 SelectMode::Line(original_range) => {
3044 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3045
3046 let position = display_map
3047 .clip_point(position, Bias::Left)
3048 .to_point(&display_map);
3049 let line_start = display_map.prev_line_boundary(position).0;
3050 let next_line_start = buffer.clip_point(
3051 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3052 Bias::Left,
3053 );
3054
3055 if line_start < original_range.start {
3056 head = line_start
3057 } else {
3058 head = next_line_start
3059 }
3060
3061 if head <= original_range.start {
3062 tail = original_range.end;
3063 } else {
3064 tail = original_range.start;
3065 }
3066 }
3067 SelectMode::All => {
3068 return;
3069 }
3070 };
3071
3072 if head < tail {
3073 pending.start = buffer.anchor_before(head);
3074 pending.end = buffer.anchor_before(tail);
3075 pending.reversed = true;
3076 } else {
3077 pending.start = buffer.anchor_before(tail);
3078 pending.end = buffer.anchor_before(head);
3079 pending.reversed = false;
3080 }
3081
3082 self.change_selections(None, cx, |s| {
3083 s.set_pending(pending, mode);
3084 });
3085 } else {
3086 log::error!("update_selection dispatched with no pending selection");
3087 return;
3088 }
3089
3090 self.apply_scroll_delta(scroll_delta, cx);
3091 cx.notify();
3092 }
3093
3094 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3095 self.columnar_selection_tail.take();
3096 if self.selections.pending_anchor().is_some() {
3097 let selections = self.selections.all::<usize>(cx);
3098 self.change_selections(None, cx, |s| {
3099 s.select(selections);
3100 s.clear_pending();
3101 });
3102 }
3103 }
3104
3105 fn select_columns(
3106 &mut self,
3107 tail: DisplayPoint,
3108 head: DisplayPoint,
3109 goal_column: u32,
3110 display_map: &DisplaySnapshot,
3111 cx: &mut ViewContext<Self>,
3112 ) {
3113 let start_row = cmp::min(tail.row(), head.row());
3114 let end_row = cmp::max(tail.row(), head.row());
3115 let start_column = cmp::min(tail.column(), goal_column);
3116 let end_column = cmp::max(tail.column(), goal_column);
3117 let reversed = start_column < tail.column();
3118
3119 let selection_ranges = (start_row.0..=end_row.0)
3120 .map(DisplayRow)
3121 .filter_map(|row| {
3122 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3123 let start = display_map
3124 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3125 .to_point(display_map);
3126 let end = display_map
3127 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3128 .to_point(display_map);
3129 if reversed {
3130 Some(end..start)
3131 } else {
3132 Some(start..end)
3133 }
3134 } else {
3135 None
3136 }
3137 })
3138 .collect::<Vec<_>>();
3139
3140 self.change_selections(None, cx, |s| {
3141 s.select_ranges(selection_ranges);
3142 });
3143 cx.notify();
3144 }
3145
3146 pub fn has_pending_nonempty_selection(&self) -> bool {
3147 let pending_nonempty_selection = match self.selections.pending_anchor() {
3148 Some(Selection { start, end, .. }) => start != end,
3149 None => false,
3150 };
3151
3152 pending_nonempty_selection
3153 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3154 }
3155
3156 pub fn has_pending_selection(&self) -> bool {
3157 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3158 }
3159
3160 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3161 if self.clear_expanded_diff_hunks(cx) {
3162 cx.notify();
3163 return;
3164 }
3165 if self.dismiss_menus_and_popups(true, cx) {
3166 return;
3167 }
3168
3169 if self.mode == EditorMode::Full
3170 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3171 {
3172 return;
3173 }
3174
3175 cx.propagate();
3176 }
3177
3178 pub fn dismiss_menus_and_popups(
3179 &mut self,
3180 should_report_inline_completion_event: bool,
3181 cx: &mut ViewContext<Self>,
3182 ) -> bool {
3183 if self.take_rename(false, cx).is_some() {
3184 return true;
3185 }
3186
3187 if hide_hover(self, cx) {
3188 return true;
3189 }
3190
3191 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3192 return true;
3193 }
3194
3195 if self.hide_context_menu(cx).is_some() {
3196 return true;
3197 }
3198
3199 if self.mouse_context_menu.take().is_some() {
3200 return true;
3201 }
3202
3203 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3204 return true;
3205 }
3206
3207 if self.snippet_stack.pop().is_some() {
3208 return true;
3209 }
3210
3211 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3212 self.dismiss_diagnostics(cx);
3213 return true;
3214 }
3215
3216 false
3217 }
3218
3219 fn linked_editing_ranges_for(
3220 &self,
3221 selection: Range<text::Anchor>,
3222 cx: &AppContext,
3223 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3224 if self.linked_edit_ranges.is_empty() {
3225 return None;
3226 }
3227 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3228 selection.end.buffer_id.and_then(|end_buffer_id| {
3229 if selection.start.buffer_id != Some(end_buffer_id) {
3230 return None;
3231 }
3232 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3233 let snapshot = buffer.read(cx).snapshot();
3234 self.linked_edit_ranges
3235 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3236 .map(|ranges| (ranges, snapshot, buffer))
3237 })?;
3238 use text::ToOffset as TO;
3239 // find offset from the start of current range to current cursor position
3240 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3241
3242 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3243 let start_difference = start_offset - start_byte_offset;
3244 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3245 let end_difference = end_offset - start_byte_offset;
3246 // Current range has associated linked ranges.
3247 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3248 for range in linked_ranges.iter() {
3249 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3250 let end_offset = start_offset + end_difference;
3251 let start_offset = start_offset + start_difference;
3252 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3253 continue;
3254 }
3255 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3256 if s.start.buffer_id != selection.start.buffer_id
3257 || s.end.buffer_id != selection.end.buffer_id
3258 {
3259 return false;
3260 }
3261 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3262 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3263 }) {
3264 continue;
3265 }
3266 let start = buffer_snapshot.anchor_after(start_offset);
3267 let end = buffer_snapshot.anchor_after(end_offset);
3268 linked_edits
3269 .entry(buffer.clone())
3270 .or_default()
3271 .push(start..end);
3272 }
3273 Some(linked_edits)
3274 }
3275
3276 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3277 let text: Arc<str> = text.into();
3278
3279 if self.read_only(cx) {
3280 return;
3281 }
3282
3283 let selections = self.selections.all_adjusted(cx);
3284 let mut bracket_inserted = false;
3285 let mut edits = Vec::new();
3286 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3287 let mut new_selections = Vec::with_capacity(selections.len());
3288 let mut new_autoclose_regions = Vec::new();
3289 let snapshot = self.buffer.read(cx).read(cx);
3290
3291 for (selection, autoclose_region) in
3292 self.selections_with_autoclose_regions(selections, &snapshot)
3293 {
3294 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3295 // Determine if the inserted text matches the opening or closing
3296 // bracket of any of this language's bracket pairs.
3297 let mut bracket_pair = None;
3298 let mut is_bracket_pair_start = false;
3299 let mut is_bracket_pair_end = false;
3300 if !text.is_empty() {
3301 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3302 // and they are removing the character that triggered IME popup.
3303 for (pair, enabled) in scope.brackets() {
3304 if !pair.close && !pair.surround {
3305 continue;
3306 }
3307
3308 if enabled && pair.start.ends_with(text.as_ref()) {
3309 let prefix_len = pair.start.len() - text.len();
3310 let preceding_text_matches_prefix = prefix_len == 0
3311 || (selection.start.column >= (prefix_len as u32)
3312 && snapshot.contains_str_at(
3313 Point::new(
3314 selection.start.row,
3315 selection.start.column - (prefix_len as u32),
3316 ),
3317 &pair.start[..prefix_len],
3318 ));
3319 if preceding_text_matches_prefix {
3320 bracket_pair = Some(pair.clone());
3321 is_bracket_pair_start = true;
3322 break;
3323 }
3324 }
3325 if pair.end.as_str() == text.as_ref() {
3326 bracket_pair = Some(pair.clone());
3327 is_bracket_pair_end = true;
3328 break;
3329 }
3330 }
3331 }
3332
3333 if let Some(bracket_pair) = bracket_pair {
3334 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3335 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3336 let auto_surround =
3337 self.use_auto_surround && snapshot_settings.use_auto_surround;
3338 if selection.is_empty() {
3339 if is_bracket_pair_start {
3340 // If the inserted text is a suffix of an opening bracket and the
3341 // selection is preceded by the rest of the opening bracket, then
3342 // insert the closing bracket.
3343 let following_text_allows_autoclose = snapshot
3344 .chars_at(selection.start)
3345 .next()
3346 .map_or(true, |c| scope.should_autoclose_before(c));
3347
3348 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3349 && bracket_pair.start.len() == 1
3350 {
3351 let target = bracket_pair.start.chars().next().unwrap();
3352 let current_line_count = snapshot
3353 .reversed_chars_at(selection.start)
3354 .take_while(|&c| c != '\n')
3355 .filter(|&c| c == target)
3356 .count();
3357 current_line_count % 2 == 1
3358 } else {
3359 false
3360 };
3361
3362 if autoclose
3363 && bracket_pair.close
3364 && following_text_allows_autoclose
3365 && !is_closing_quote
3366 {
3367 let anchor = snapshot.anchor_before(selection.end);
3368 new_selections.push((selection.map(|_| anchor), text.len()));
3369 new_autoclose_regions.push((
3370 anchor,
3371 text.len(),
3372 selection.id,
3373 bracket_pair.clone(),
3374 ));
3375 edits.push((
3376 selection.range(),
3377 format!("{}{}", text, bracket_pair.end).into(),
3378 ));
3379 bracket_inserted = true;
3380 continue;
3381 }
3382 }
3383
3384 if let Some(region) = autoclose_region {
3385 // If the selection is followed by an auto-inserted closing bracket,
3386 // then don't insert that closing bracket again; just move the selection
3387 // past the closing bracket.
3388 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3389 && text.as_ref() == region.pair.end.as_str();
3390 if should_skip {
3391 let anchor = snapshot.anchor_after(selection.end);
3392 new_selections
3393 .push((selection.map(|_| anchor), region.pair.end.len()));
3394 continue;
3395 }
3396 }
3397
3398 let always_treat_brackets_as_autoclosed = snapshot
3399 .settings_at(selection.start, cx)
3400 .always_treat_brackets_as_autoclosed;
3401 if always_treat_brackets_as_autoclosed
3402 && is_bracket_pair_end
3403 && snapshot.contains_str_at(selection.end, text.as_ref())
3404 {
3405 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3406 // and the inserted text is a closing bracket and the selection is followed
3407 // by the closing bracket then move the selection past the closing bracket.
3408 let anchor = snapshot.anchor_after(selection.end);
3409 new_selections.push((selection.map(|_| anchor), text.len()));
3410 continue;
3411 }
3412 }
3413 // If an opening bracket is 1 character long and is typed while
3414 // text is selected, then surround that text with the bracket pair.
3415 else if auto_surround
3416 && bracket_pair.surround
3417 && is_bracket_pair_start
3418 && bracket_pair.start.chars().count() == 1
3419 {
3420 edits.push((selection.start..selection.start, text.clone()));
3421 edits.push((
3422 selection.end..selection.end,
3423 bracket_pair.end.as_str().into(),
3424 ));
3425 bracket_inserted = true;
3426 new_selections.push((
3427 Selection {
3428 id: selection.id,
3429 start: snapshot.anchor_after(selection.start),
3430 end: snapshot.anchor_before(selection.end),
3431 reversed: selection.reversed,
3432 goal: selection.goal,
3433 },
3434 0,
3435 ));
3436 continue;
3437 }
3438 }
3439 }
3440
3441 if self.auto_replace_emoji_shortcode
3442 && selection.is_empty()
3443 && text.as_ref().ends_with(':')
3444 {
3445 if let Some(possible_emoji_short_code) =
3446 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3447 {
3448 if !possible_emoji_short_code.is_empty() {
3449 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3450 let emoji_shortcode_start = Point::new(
3451 selection.start.row,
3452 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3453 );
3454
3455 // Remove shortcode from buffer
3456 edits.push((
3457 emoji_shortcode_start..selection.start,
3458 "".to_string().into(),
3459 ));
3460 new_selections.push((
3461 Selection {
3462 id: selection.id,
3463 start: snapshot.anchor_after(emoji_shortcode_start),
3464 end: snapshot.anchor_before(selection.start),
3465 reversed: selection.reversed,
3466 goal: selection.goal,
3467 },
3468 0,
3469 ));
3470
3471 // Insert emoji
3472 let selection_start_anchor = snapshot.anchor_after(selection.start);
3473 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3474 edits.push((selection.start..selection.end, emoji.to_string().into()));
3475
3476 continue;
3477 }
3478 }
3479 }
3480 }
3481
3482 // If not handling any auto-close operation, then just replace the selected
3483 // text with the given input and move the selection to the end of the
3484 // newly inserted text.
3485 let anchor = snapshot.anchor_after(selection.end);
3486 if !self.linked_edit_ranges.is_empty() {
3487 let start_anchor = snapshot.anchor_before(selection.start);
3488
3489 let is_word_char = text.chars().next().map_or(true, |char| {
3490 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3491 classifier.is_word(char)
3492 });
3493
3494 if is_word_char {
3495 if let Some(ranges) = self
3496 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3497 {
3498 for (buffer, edits) in ranges {
3499 linked_edits
3500 .entry(buffer.clone())
3501 .or_default()
3502 .extend(edits.into_iter().map(|range| (range, text.clone())));
3503 }
3504 }
3505 }
3506 }
3507
3508 new_selections.push((selection.map(|_| anchor), 0));
3509 edits.push((selection.start..selection.end, text.clone()));
3510 }
3511
3512 drop(snapshot);
3513
3514 self.transact(cx, |this, cx| {
3515 this.buffer.update(cx, |buffer, cx| {
3516 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3517 });
3518 for (buffer, edits) in linked_edits {
3519 buffer.update(cx, |buffer, cx| {
3520 let snapshot = buffer.snapshot();
3521 let edits = edits
3522 .into_iter()
3523 .map(|(range, text)| {
3524 use text::ToPoint as TP;
3525 let end_point = TP::to_point(&range.end, &snapshot);
3526 let start_point = TP::to_point(&range.start, &snapshot);
3527 (start_point..end_point, text)
3528 })
3529 .sorted_by_key(|(range, _)| range.start)
3530 .collect::<Vec<_>>();
3531 buffer.edit(edits, None, cx);
3532 })
3533 }
3534 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3535 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3536 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3537 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3538 .zip(new_selection_deltas)
3539 .map(|(selection, delta)| Selection {
3540 id: selection.id,
3541 start: selection.start + delta,
3542 end: selection.end + delta,
3543 reversed: selection.reversed,
3544 goal: SelectionGoal::None,
3545 })
3546 .collect::<Vec<_>>();
3547
3548 let mut i = 0;
3549 for (position, delta, selection_id, pair) in new_autoclose_regions {
3550 let position = position.to_offset(&map.buffer_snapshot) + delta;
3551 let start = map.buffer_snapshot.anchor_before(position);
3552 let end = map.buffer_snapshot.anchor_after(position);
3553 while let Some(existing_state) = this.autoclose_regions.get(i) {
3554 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3555 Ordering::Less => i += 1,
3556 Ordering::Greater => break,
3557 Ordering::Equal => {
3558 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3559 Ordering::Less => i += 1,
3560 Ordering::Equal => break,
3561 Ordering::Greater => break,
3562 }
3563 }
3564 }
3565 }
3566 this.autoclose_regions.insert(
3567 i,
3568 AutocloseRegion {
3569 selection_id,
3570 range: start..end,
3571 pair,
3572 },
3573 );
3574 }
3575
3576 let had_active_inline_completion = this.has_active_inline_completion(cx);
3577 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3578 s.select(new_selections)
3579 });
3580
3581 if !bracket_inserted {
3582 if let Some(on_type_format_task) =
3583 this.trigger_on_type_formatting(text.to_string(), cx)
3584 {
3585 on_type_format_task.detach_and_log_err(cx);
3586 }
3587 }
3588
3589 let editor_settings = EditorSettings::get_global(cx);
3590 if bracket_inserted
3591 && (editor_settings.auto_signature_help
3592 || editor_settings.show_signature_help_after_edits)
3593 {
3594 this.show_signature_help(&ShowSignatureHelp, cx);
3595 }
3596
3597 let trigger_in_words = !had_active_inline_completion;
3598 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3599 linked_editing_ranges::refresh_linked_ranges(this, cx);
3600 this.refresh_inline_completion(true, false, cx);
3601 });
3602 }
3603
3604 fn find_possible_emoji_shortcode_at_position(
3605 snapshot: &MultiBufferSnapshot,
3606 position: Point,
3607 ) -> Option<String> {
3608 let mut chars = Vec::new();
3609 let mut found_colon = false;
3610 for char in snapshot.reversed_chars_at(position).take(100) {
3611 // Found a possible emoji shortcode in the middle of the buffer
3612 if found_colon {
3613 if char.is_whitespace() {
3614 chars.reverse();
3615 return Some(chars.iter().collect());
3616 }
3617 // If the previous character is not a whitespace, we are in the middle of a word
3618 // and we only want to complete the shortcode if the word is made up of other emojis
3619 let mut containing_word = String::new();
3620 for ch in snapshot
3621 .reversed_chars_at(position)
3622 .skip(chars.len() + 1)
3623 .take(100)
3624 {
3625 if ch.is_whitespace() {
3626 break;
3627 }
3628 containing_word.push(ch);
3629 }
3630 let containing_word = containing_word.chars().rev().collect::<String>();
3631 if util::word_consists_of_emojis(containing_word.as_str()) {
3632 chars.reverse();
3633 return Some(chars.iter().collect());
3634 }
3635 }
3636
3637 if char.is_whitespace() || !char.is_ascii() {
3638 return None;
3639 }
3640 if char == ':' {
3641 found_colon = true;
3642 } else {
3643 chars.push(char);
3644 }
3645 }
3646 // Found a possible emoji shortcode at the beginning of the buffer
3647 chars.reverse();
3648 Some(chars.iter().collect())
3649 }
3650
3651 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3652 self.transact(cx, |this, cx| {
3653 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3654 let selections = this.selections.all::<usize>(cx);
3655 let multi_buffer = this.buffer.read(cx);
3656 let buffer = multi_buffer.snapshot(cx);
3657 selections
3658 .iter()
3659 .map(|selection| {
3660 let start_point = selection.start.to_point(&buffer);
3661 let mut indent =
3662 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3663 indent.len = cmp::min(indent.len, start_point.column);
3664 let start = selection.start;
3665 let end = selection.end;
3666 let selection_is_empty = start == end;
3667 let language_scope = buffer.language_scope_at(start);
3668 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3669 &language_scope
3670 {
3671 let leading_whitespace_len = buffer
3672 .reversed_chars_at(start)
3673 .take_while(|c| c.is_whitespace() && *c != '\n')
3674 .map(|c| c.len_utf8())
3675 .sum::<usize>();
3676
3677 let trailing_whitespace_len = buffer
3678 .chars_at(end)
3679 .take_while(|c| c.is_whitespace() && *c != '\n')
3680 .map(|c| c.len_utf8())
3681 .sum::<usize>();
3682
3683 let insert_extra_newline =
3684 language.brackets().any(|(pair, enabled)| {
3685 let pair_start = pair.start.trim_end();
3686 let pair_end = pair.end.trim_start();
3687
3688 enabled
3689 && pair.newline
3690 && buffer.contains_str_at(
3691 end + trailing_whitespace_len,
3692 pair_end,
3693 )
3694 && buffer.contains_str_at(
3695 (start - leading_whitespace_len)
3696 .saturating_sub(pair_start.len()),
3697 pair_start,
3698 )
3699 });
3700
3701 // Comment extension on newline is allowed only for cursor selections
3702 let comment_delimiter = maybe!({
3703 if !selection_is_empty {
3704 return None;
3705 }
3706
3707 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3708 return None;
3709 }
3710
3711 let delimiters = language.line_comment_prefixes();
3712 let max_len_of_delimiter =
3713 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3714 let (snapshot, range) =
3715 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3716
3717 let mut index_of_first_non_whitespace = 0;
3718 let comment_candidate = snapshot
3719 .chars_for_range(range)
3720 .skip_while(|c| {
3721 let should_skip = c.is_whitespace();
3722 if should_skip {
3723 index_of_first_non_whitespace += 1;
3724 }
3725 should_skip
3726 })
3727 .take(max_len_of_delimiter)
3728 .collect::<String>();
3729 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3730 comment_candidate.starts_with(comment_prefix.as_ref())
3731 })?;
3732 let cursor_is_placed_after_comment_marker =
3733 index_of_first_non_whitespace + comment_prefix.len()
3734 <= start_point.column as usize;
3735 if cursor_is_placed_after_comment_marker {
3736 Some(comment_prefix.clone())
3737 } else {
3738 None
3739 }
3740 });
3741 (comment_delimiter, insert_extra_newline)
3742 } else {
3743 (None, false)
3744 };
3745
3746 let capacity_for_delimiter = comment_delimiter
3747 .as_deref()
3748 .map(str::len)
3749 .unwrap_or_default();
3750 let mut new_text =
3751 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3752 new_text.push('\n');
3753 new_text.extend(indent.chars());
3754 if let Some(delimiter) = &comment_delimiter {
3755 new_text.push_str(delimiter);
3756 }
3757 if insert_extra_newline {
3758 new_text = new_text.repeat(2);
3759 }
3760
3761 let anchor = buffer.anchor_after(end);
3762 let new_selection = selection.map(|_| anchor);
3763 (
3764 (start..end, new_text),
3765 (insert_extra_newline, new_selection),
3766 )
3767 })
3768 .unzip()
3769 };
3770
3771 this.edit_with_autoindent(edits, cx);
3772 let buffer = this.buffer.read(cx).snapshot(cx);
3773 let new_selections = selection_fixup_info
3774 .into_iter()
3775 .map(|(extra_newline_inserted, new_selection)| {
3776 let mut cursor = new_selection.end.to_point(&buffer);
3777 if extra_newline_inserted {
3778 cursor.row -= 1;
3779 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3780 }
3781 new_selection.map(|_| cursor)
3782 })
3783 .collect();
3784
3785 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3786 this.refresh_inline_completion(true, false, cx);
3787 });
3788 }
3789
3790 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3791 let buffer = self.buffer.read(cx);
3792 let snapshot = buffer.snapshot(cx);
3793
3794 let mut edits = Vec::new();
3795 let mut rows = Vec::new();
3796
3797 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3798 let cursor = selection.head();
3799 let row = cursor.row;
3800
3801 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3802
3803 let newline = "\n".to_string();
3804 edits.push((start_of_line..start_of_line, newline));
3805
3806 rows.push(row + rows_inserted as u32);
3807 }
3808
3809 self.transact(cx, |editor, cx| {
3810 editor.edit(edits, cx);
3811
3812 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3813 let mut index = 0;
3814 s.move_cursors_with(|map, _, _| {
3815 let row = rows[index];
3816 index += 1;
3817
3818 let point = Point::new(row, 0);
3819 let boundary = map.next_line_boundary(point).1;
3820 let clipped = map.clip_point(boundary, Bias::Left);
3821
3822 (clipped, SelectionGoal::None)
3823 });
3824 });
3825
3826 let mut indent_edits = Vec::new();
3827 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3828 for row in rows {
3829 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3830 for (row, indent) in indents {
3831 if indent.len == 0 {
3832 continue;
3833 }
3834
3835 let text = match indent.kind {
3836 IndentKind::Space => " ".repeat(indent.len as usize),
3837 IndentKind::Tab => "\t".repeat(indent.len as usize),
3838 };
3839 let point = Point::new(row.0, 0);
3840 indent_edits.push((point..point, text));
3841 }
3842 }
3843 editor.edit(indent_edits, cx);
3844 });
3845 }
3846
3847 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3848 let buffer = self.buffer.read(cx);
3849 let snapshot = buffer.snapshot(cx);
3850
3851 let mut edits = Vec::new();
3852 let mut rows = Vec::new();
3853 let mut rows_inserted = 0;
3854
3855 for selection in self.selections.all_adjusted(cx) {
3856 let cursor = selection.head();
3857 let row = cursor.row;
3858
3859 let point = Point::new(row + 1, 0);
3860 let start_of_line = snapshot.clip_point(point, Bias::Left);
3861
3862 let newline = "\n".to_string();
3863 edits.push((start_of_line..start_of_line, newline));
3864
3865 rows_inserted += 1;
3866 rows.push(row + rows_inserted);
3867 }
3868
3869 self.transact(cx, |editor, cx| {
3870 editor.edit(edits, cx);
3871
3872 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3873 let mut index = 0;
3874 s.move_cursors_with(|map, _, _| {
3875 let row = rows[index];
3876 index += 1;
3877
3878 let point = Point::new(row, 0);
3879 let boundary = map.next_line_boundary(point).1;
3880 let clipped = map.clip_point(boundary, Bias::Left);
3881
3882 (clipped, SelectionGoal::None)
3883 });
3884 });
3885
3886 let mut indent_edits = Vec::new();
3887 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3888 for row in rows {
3889 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3890 for (row, indent) in indents {
3891 if indent.len == 0 {
3892 continue;
3893 }
3894
3895 let text = match indent.kind {
3896 IndentKind::Space => " ".repeat(indent.len as usize),
3897 IndentKind::Tab => "\t".repeat(indent.len as usize),
3898 };
3899 let point = Point::new(row.0, 0);
3900 indent_edits.push((point..point, text));
3901 }
3902 }
3903 editor.edit(indent_edits, cx);
3904 });
3905 }
3906
3907 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3908 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3909 original_indent_columns: Vec::new(),
3910 });
3911 self.insert_with_autoindent_mode(text, autoindent, cx);
3912 }
3913
3914 fn insert_with_autoindent_mode(
3915 &mut self,
3916 text: &str,
3917 autoindent_mode: Option<AutoindentMode>,
3918 cx: &mut ViewContext<Self>,
3919 ) {
3920 if self.read_only(cx) {
3921 return;
3922 }
3923
3924 let text: Arc<str> = text.into();
3925 self.transact(cx, |this, cx| {
3926 let old_selections = this.selections.all_adjusted(cx);
3927 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3928 let anchors = {
3929 let snapshot = buffer.read(cx);
3930 old_selections
3931 .iter()
3932 .map(|s| {
3933 let anchor = snapshot.anchor_after(s.head());
3934 s.map(|_| anchor)
3935 })
3936 .collect::<Vec<_>>()
3937 };
3938 buffer.edit(
3939 old_selections
3940 .iter()
3941 .map(|s| (s.start..s.end, text.clone())),
3942 autoindent_mode,
3943 cx,
3944 );
3945 anchors
3946 });
3947
3948 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3949 s.select_anchors(selection_anchors);
3950 })
3951 });
3952 }
3953
3954 fn trigger_completion_on_input(
3955 &mut self,
3956 text: &str,
3957 trigger_in_words: bool,
3958 cx: &mut ViewContext<Self>,
3959 ) {
3960 if self.is_completion_trigger(text, trigger_in_words, cx) {
3961 self.show_completions(
3962 &ShowCompletions {
3963 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3964 },
3965 cx,
3966 );
3967 } else {
3968 self.hide_context_menu(cx);
3969 }
3970 }
3971
3972 fn is_completion_trigger(
3973 &self,
3974 text: &str,
3975 trigger_in_words: bool,
3976 cx: &mut ViewContext<Self>,
3977 ) -> bool {
3978 let position = self.selections.newest_anchor().head();
3979 let multibuffer = self.buffer.read(cx);
3980 let Some(buffer) = position
3981 .buffer_id
3982 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3983 else {
3984 return false;
3985 };
3986
3987 if let Some(completion_provider) = &self.completion_provider {
3988 completion_provider.is_completion_trigger(
3989 &buffer,
3990 position.text_anchor,
3991 text,
3992 trigger_in_words,
3993 cx,
3994 )
3995 } else {
3996 false
3997 }
3998 }
3999
4000 /// If any empty selections is touching the start of its innermost containing autoclose
4001 /// region, expand it to select the brackets.
4002 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4003 let selections = self.selections.all::<usize>(cx);
4004 let buffer = self.buffer.read(cx).read(cx);
4005 let new_selections = self
4006 .selections_with_autoclose_regions(selections, &buffer)
4007 .map(|(mut selection, region)| {
4008 if !selection.is_empty() {
4009 return selection;
4010 }
4011
4012 if let Some(region) = region {
4013 let mut range = region.range.to_offset(&buffer);
4014 if selection.start == range.start && range.start >= region.pair.start.len() {
4015 range.start -= region.pair.start.len();
4016 if buffer.contains_str_at(range.start, ®ion.pair.start)
4017 && buffer.contains_str_at(range.end, ®ion.pair.end)
4018 {
4019 range.end += region.pair.end.len();
4020 selection.start = range.start;
4021 selection.end = range.end;
4022
4023 return selection;
4024 }
4025 }
4026 }
4027
4028 let always_treat_brackets_as_autoclosed = buffer
4029 .settings_at(selection.start, cx)
4030 .always_treat_brackets_as_autoclosed;
4031
4032 if !always_treat_brackets_as_autoclosed {
4033 return selection;
4034 }
4035
4036 if let Some(scope) = buffer.language_scope_at(selection.start) {
4037 for (pair, enabled) in scope.brackets() {
4038 if !enabled || !pair.close {
4039 continue;
4040 }
4041
4042 if buffer.contains_str_at(selection.start, &pair.end) {
4043 let pair_start_len = pair.start.len();
4044 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4045 {
4046 selection.start -= pair_start_len;
4047 selection.end += pair.end.len();
4048
4049 return selection;
4050 }
4051 }
4052 }
4053 }
4054
4055 selection
4056 })
4057 .collect();
4058
4059 drop(buffer);
4060 self.change_selections(None, cx, |selections| selections.select(new_selections));
4061 }
4062
4063 /// Iterate the given selections, and for each one, find the smallest surrounding
4064 /// autoclose region. This uses the ordering of the selections and the autoclose
4065 /// regions to avoid repeated comparisons.
4066 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4067 &'a self,
4068 selections: impl IntoIterator<Item = Selection<D>>,
4069 buffer: &'a MultiBufferSnapshot,
4070 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4071 let mut i = 0;
4072 let mut regions = self.autoclose_regions.as_slice();
4073 selections.into_iter().map(move |selection| {
4074 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4075
4076 let mut enclosing = None;
4077 while let Some(pair_state) = regions.get(i) {
4078 if pair_state.range.end.to_offset(buffer) < range.start {
4079 regions = ®ions[i + 1..];
4080 i = 0;
4081 } else if pair_state.range.start.to_offset(buffer) > range.end {
4082 break;
4083 } else {
4084 if pair_state.selection_id == selection.id {
4085 enclosing = Some(pair_state);
4086 }
4087 i += 1;
4088 }
4089 }
4090
4091 (selection, enclosing)
4092 })
4093 }
4094
4095 /// Remove any autoclose regions that no longer contain their selection.
4096 fn invalidate_autoclose_regions(
4097 &mut self,
4098 mut selections: &[Selection<Anchor>],
4099 buffer: &MultiBufferSnapshot,
4100 ) {
4101 self.autoclose_regions.retain(|state| {
4102 let mut i = 0;
4103 while let Some(selection) = selections.get(i) {
4104 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4105 selections = &selections[1..];
4106 continue;
4107 }
4108 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4109 break;
4110 }
4111 if selection.id == state.selection_id {
4112 return true;
4113 } else {
4114 i += 1;
4115 }
4116 }
4117 false
4118 });
4119 }
4120
4121 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4122 let offset = position.to_offset(buffer);
4123 let (word_range, kind) = buffer.surrounding_word(offset, true);
4124 if offset > word_range.start && kind == Some(CharKind::Word) {
4125 Some(
4126 buffer
4127 .text_for_range(word_range.start..offset)
4128 .collect::<String>(),
4129 )
4130 } else {
4131 None
4132 }
4133 }
4134
4135 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4136 self.refresh_inlay_hints(
4137 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4138 cx,
4139 );
4140 }
4141
4142 pub fn inlay_hints_enabled(&self) -> bool {
4143 self.inlay_hint_cache.enabled
4144 }
4145
4146 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4147 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4148 return;
4149 }
4150
4151 let reason_description = reason.description();
4152 let ignore_debounce = matches!(
4153 reason,
4154 InlayHintRefreshReason::SettingsChange(_)
4155 | InlayHintRefreshReason::Toggle(_)
4156 | InlayHintRefreshReason::ExcerptsRemoved(_)
4157 );
4158 let (invalidate_cache, required_languages) = match reason {
4159 InlayHintRefreshReason::Toggle(enabled) => {
4160 self.inlay_hint_cache.enabled = enabled;
4161 if enabled {
4162 (InvalidationStrategy::RefreshRequested, None)
4163 } else {
4164 self.inlay_hint_cache.clear();
4165 self.splice_inlays(
4166 self.visible_inlay_hints(cx)
4167 .iter()
4168 .map(|inlay| inlay.id)
4169 .collect(),
4170 Vec::new(),
4171 cx,
4172 );
4173 return;
4174 }
4175 }
4176 InlayHintRefreshReason::SettingsChange(new_settings) => {
4177 match self.inlay_hint_cache.update_settings(
4178 &self.buffer,
4179 new_settings,
4180 self.visible_inlay_hints(cx),
4181 cx,
4182 ) {
4183 ControlFlow::Break(Some(InlaySplice {
4184 to_remove,
4185 to_insert,
4186 })) => {
4187 self.splice_inlays(to_remove, to_insert, cx);
4188 return;
4189 }
4190 ControlFlow::Break(None) => return,
4191 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4192 }
4193 }
4194 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4195 if let Some(InlaySplice {
4196 to_remove,
4197 to_insert,
4198 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4199 {
4200 self.splice_inlays(to_remove, to_insert, cx);
4201 }
4202 return;
4203 }
4204 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4205 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4206 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4207 }
4208 InlayHintRefreshReason::RefreshRequested => {
4209 (InvalidationStrategy::RefreshRequested, None)
4210 }
4211 };
4212
4213 if let Some(InlaySplice {
4214 to_remove,
4215 to_insert,
4216 }) = self.inlay_hint_cache.spawn_hint_refresh(
4217 reason_description,
4218 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4219 invalidate_cache,
4220 ignore_debounce,
4221 cx,
4222 ) {
4223 self.splice_inlays(to_remove, to_insert, cx);
4224 }
4225 }
4226
4227 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4228 self.display_map
4229 .read(cx)
4230 .current_inlays()
4231 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4232 .cloned()
4233 .collect()
4234 }
4235
4236 pub fn excerpts_for_inlay_hints_query(
4237 &self,
4238 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4239 cx: &mut ViewContext<Editor>,
4240 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4241 let Some(project) = self.project.as_ref() else {
4242 return HashMap::default();
4243 };
4244 let project = project.read(cx);
4245 let multi_buffer = self.buffer().read(cx);
4246 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4247 let multi_buffer_visible_start = self
4248 .scroll_manager
4249 .anchor()
4250 .anchor
4251 .to_point(&multi_buffer_snapshot);
4252 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4253 multi_buffer_visible_start
4254 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4255 Bias::Left,
4256 );
4257 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4258 multi_buffer
4259 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4260 .into_iter()
4261 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4262 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4263 let buffer = buffer_handle.read(cx);
4264 let buffer_file = project::File::from_dyn(buffer.file())?;
4265 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4266 let worktree_entry = buffer_worktree
4267 .read(cx)
4268 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4269 if worktree_entry.is_ignored {
4270 return None;
4271 }
4272
4273 let language = buffer.language()?;
4274 if let Some(restrict_to_languages) = restrict_to_languages {
4275 if !restrict_to_languages.contains(language) {
4276 return None;
4277 }
4278 }
4279 Some((
4280 excerpt_id,
4281 (
4282 buffer_handle,
4283 buffer.version().clone(),
4284 excerpt_visible_range,
4285 ),
4286 ))
4287 })
4288 .collect()
4289 }
4290
4291 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4292 TextLayoutDetails {
4293 text_system: cx.text_system().clone(),
4294 editor_style: self.style.clone().unwrap(),
4295 rem_size: cx.rem_size(),
4296 scroll_anchor: self.scroll_manager.anchor(),
4297 visible_rows: self.visible_line_count(),
4298 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4299 }
4300 }
4301
4302 fn splice_inlays(
4303 &self,
4304 to_remove: Vec<InlayId>,
4305 to_insert: Vec<Inlay>,
4306 cx: &mut ViewContext<Self>,
4307 ) {
4308 self.display_map.update(cx, |display_map, cx| {
4309 display_map.splice_inlays(to_remove, to_insert, cx);
4310 });
4311 cx.notify();
4312 }
4313
4314 fn trigger_on_type_formatting(
4315 &self,
4316 input: String,
4317 cx: &mut ViewContext<Self>,
4318 ) -> Option<Task<Result<()>>> {
4319 if input.len() != 1 {
4320 return None;
4321 }
4322
4323 let project = self.project.as_ref()?;
4324 let position = self.selections.newest_anchor().head();
4325 let (buffer, buffer_position) = self
4326 .buffer
4327 .read(cx)
4328 .text_anchor_for_position(position, cx)?;
4329
4330 let settings = language_settings::language_settings(
4331 buffer
4332 .read(cx)
4333 .language_at(buffer_position)
4334 .map(|l| l.name()),
4335 buffer.read(cx).file(),
4336 cx,
4337 );
4338 if !settings.use_on_type_format {
4339 return None;
4340 }
4341
4342 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4343 // hence we do LSP request & edit on host side only — add formats to host's history.
4344 let push_to_lsp_host_history = true;
4345 // If this is not the host, append its history with new edits.
4346 let push_to_client_history = project.read(cx).is_via_collab();
4347
4348 let on_type_formatting = project.update(cx, |project, cx| {
4349 project.on_type_format(
4350 buffer.clone(),
4351 buffer_position,
4352 input,
4353 push_to_lsp_host_history,
4354 cx,
4355 )
4356 });
4357 Some(cx.spawn(|editor, mut cx| async move {
4358 if let Some(transaction) = on_type_formatting.await? {
4359 if push_to_client_history {
4360 buffer
4361 .update(&mut cx, |buffer, _| {
4362 buffer.push_transaction(transaction, Instant::now());
4363 })
4364 .ok();
4365 }
4366 editor.update(&mut cx, |editor, cx| {
4367 editor.refresh_document_highlights(cx);
4368 })?;
4369 }
4370 Ok(())
4371 }))
4372 }
4373
4374 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4375 if self.pending_rename.is_some() {
4376 return;
4377 }
4378
4379 let Some(provider) = self.completion_provider.as_ref() else {
4380 return;
4381 };
4382
4383 let position = self.selections.newest_anchor().head();
4384 let (buffer, buffer_position) =
4385 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4386 output
4387 } else {
4388 return;
4389 };
4390
4391 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4392 let is_followup_invoke = {
4393 let context_menu_state = self.context_menu.read();
4394 matches!(
4395 context_menu_state.deref(),
4396 Some(ContextMenu::Completions(_))
4397 )
4398 };
4399 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4400 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4401 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4402 CompletionTriggerKind::TRIGGER_CHARACTER
4403 }
4404
4405 _ => CompletionTriggerKind::INVOKED,
4406 };
4407 let completion_context = CompletionContext {
4408 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4409 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4410 Some(String::from(trigger))
4411 } else {
4412 None
4413 }
4414 }),
4415 trigger_kind,
4416 };
4417 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4418 let sort_completions = provider.sort_completions();
4419
4420 let id = post_inc(&mut self.next_completion_id);
4421 let task = cx.spawn(|this, mut cx| {
4422 async move {
4423 this.update(&mut cx, |this, _| {
4424 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4425 })?;
4426 let completions = completions.await.log_err();
4427 let menu = if let Some(completions) = completions {
4428 let mut menu = CompletionsMenu {
4429 id,
4430 sort_completions,
4431 initial_position: position,
4432 match_candidates: completions
4433 .iter()
4434 .enumerate()
4435 .map(|(id, completion)| {
4436 StringMatchCandidate::new(
4437 id,
4438 completion.label.text[completion.label.filter_range.clone()]
4439 .into(),
4440 )
4441 })
4442 .collect(),
4443 buffer: buffer.clone(),
4444 completions: Arc::new(RwLock::new(completions.into())),
4445 matches: Vec::new().into(),
4446 selected_item: 0,
4447 scroll_handle: UniformListScrollHandle::new(),
4448 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4449 DebouncedDelay::new(),
4450 )),
4451 };
4452 menu.filter(query.as_deref(), cx.background_executor().clone())
4453 .await;
4454
4455 if menu.matches.is_empty() {
4456 None
4457 } else {
4458 this.update(&mut cx, |editor, cx| {
4459 let completions = menu.completions.clone();
4460 let matches = menu.matches.clone();
4461
4462 let delay_ms = EditorSettings::get_global(cx)
4463 .completion_documentation_secondary_query_debounce;
4464 let delay = Duration::from_millis(delay_ms);
4465 editor
4466 .completion_documentation_pre_resolve_debounce
4467 .fire_new(delay, cx, |editor, cx| {
4468 CompletionsMenu::pre_resolve_completion_documentation(
4469 buffer,
4470 completions,
4471 matches,
4472 editor,
4473 cx,
4474 )
4475 });
4476 })
4477 .ok();
4478 Some(menu)
4479 }
4480 } else {
4481 None
4482 };
4483
4484 this.update(&mut cx, |this, cx| {
4485 let mut context_menu = this.context_menu.write();
4486 match context_menu.as_ref() {
4487 None => {}
4488
4489 Some(ContextMenu::Completions(prev_menu)) => {
4490 if prev_menu.id > id {
4491 return;
4492 }
4493 }
4494
4495 _ => return,
4496 }
4497
4498 if this.focus_handle.is_focused(cx) && menu.is_some() {
4499 let menu = menu.unwrap();
4500 *context_menu = Some(ContextMenu::Completions(menu));
4501 drop(context_menu);
4502 this.discard_inline_completion(false, cx);
4503 cx.notify();
4504 } else if this.completion_tasks.len() <= 1 {
4505 // If there are no more completion tasks and the last menu was
4506 // empty, we should hide it. If it was already hidden, we should
4507 // also show the copilot completion when available.
4508 drop(context_menu);
4509 if this.hide_context_menu(cx).is_none() {
4510 this.update_visible_inline_completion(cx);
4511 }
4512 }
4513 })?;
4514
4515 Ok::<_, anyhow::Error>(())
4516 }
4517 .log_err()
4518 });
4519
4520 self.completion_tasks.push((id, task));
4521 }
4522
4523 pub fn confirm_completion(
4524 &mut self,
4525 action: &ConfirmCompletion,
4526 cx: &mut ViewContext<Self>,
4527 ) -> Option<Task<Result<()>>> {
4528 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4529 }
4530
4531 pub fn compose_completion(
4532 &mut self,
4533 action: &ComposeCompletion,
4534 cx: &mut ViewContext<Self>,
4535 ) -> Option<Task<Result<()>>> {
4536 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4537 }
4538
4539 fn do_completion(
4540 &mut self,
4541 item_ix: Option<usize>,
4542 intent: CompletionIntent,
4543 cx: &mut ViewContext<Editor>,
4544 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4545 use language::ToOffset as _;
4546
4547 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4548 menu
4549 } else {
4550 return None;
4551 };
4552
4553 let mat = completions_menu
4554 .matches
4555 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4556 let buffer_handle = completions_menu.buffer;
4557 let completions = completions_menu.completions.read();
4558 let completion = completions.get(mat.candidate_id)?;
4559 cx.stop_propagation();
4560
4561 let snippet;
4562 let text;
4563
4564 if completion.is_snippet() {
4565 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4566 text = snippet.as_ref().unwrap().text.clone();
4567 } else {
4568 snippet = None;
4569 text = completion.new_text.clone();
4570 };
4571 let selections = self.selections.all::<usize>(cx);
4572 let buffer = buffer_handle.read(cx);
4573 let old_range = completion.old_range.to_offset(buffer);
4574 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4575
4576 let newest_selection = self.selections.newest_anchor();
4577 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4578 return None;
4579 }
4580
4581 let lookbehind = newest_selection
4582 .start
4583 .text_anchor
4584 .to_offset(buffer)
4585 .saturating_sub(old_range.start);
4586 let lookahead = old_range
4587 .end
4588 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4589 let mut common_prefix_len = old_text
4590 .bytes()
4591 .zip(text.bytes())
4592 .take_while(|(a, b)| a == b)
4593 .count();
4594
4595 let snapshot = self.buffer.read(cx).snapshot(cx);
4596 let mut range_to_replace: Option<Range<isize>> = None;
4597 let mut ranges = Vec::new();
4598 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4599 for selection in &selections {
4600 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4601 let start = selection.start.saturating_sub(lookbehind);
4602 let end = selection.end + lookahead;
4603 if selection.id == newest_selection.id {
4604 range_to_replace = Some(
4605 ((start + common_prefix_len) as isize - selection.start as isize)
4606 ..(end as isize - selection.start as isize),
4607 );
4608 }
4609 ranges.push(start + common_prefix_len..end);
4610 } else {
4611 common_prefix_len = 0;
4612 ranges.clear();
4613 ranges.extend(selections.iter().map(|s| {
4614 if s.id == newest_selection.id {
4615 range_to_replace = Some(
4616 old_range.start.to_offset_utf16(&snapshot).0 as isize
4617 - selection.start as isize
4618 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4619 - selection.start as isize,
4620 );
4621 old_range.clone()
4622 } else {
4623 s.start..s.end
4624 }
4625 }));
4626 break;
4627 }
4628 if !self.linked_edit_ranges.is_empty() {
4629 let start_anchor = snapshot.anchor_before(selection.head());
4630 let end_anchor = snapshot.anchor_after(selection.tail());
4631 if let Some(ranges) = self
4632 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4633 {
4634 for (buffer, edits) in ranges {
4635 linked_edits.entry(buffer.clone()).or_default().extend(
4636 edits
4637 .into_iter()
4638 .map(|range| (range, text[common_prefix_len..].to_owned())),
4639 );
4640 }
4641 }
4642 }
4643 }
4644 let text = &text[common_prefix_len..];
4645
4646 cx.emit(EditorEvent::InputHandled {
4647 utf16_range_to_replace: range_to_replace,
4648 text: text.into(),
4649 });
4650
4651 self.transact(cx, |this, cx| {
4652 if let Some(mut snippet) = snippet {
4653 snippet.text = text.to_string();
4654 for tabstop in snippet.tabstops.iter_mut().flatten() {
4655 tabstop.start -= common_prefix_len as isize;
4656 tabstop.end -= common_prefix_len as isize;
4657 }
4658
4659 this.insert_snippet(&ranges, snippet, cx).log_err();
4660 } else {
4661 this.buffer.update(cx, |buffer, cx| {
4662 buffer.edit(
4663 ranges.iter().map(|range| (range.clone(), text)),
4664 this.autoindent_mode.clone(),
4665 cx,
4666 );
4667 });
4668 }
4669 for (buffer, edits) in linked_edits {
4670 buffer.update(cx, |buffer, cx| {
4671 let snapshot = buffer.snapshot();
4672 let edits = edits
4673 .into_iter()
4674 .map(|(range, text)| {
4675 use text::ToPoint as TP;
4676 let end_point = TP::to_point(&range.end, &snapshot);
4677 let start_point = TP::to_point(&range.start, &snapshot);
4678 (start_point..end_point, text)
4679 })
4680 .sorted_by_key(|(range, _)| range.start)
4681 .collect::<Vec<_>>();
4682 buffer.edit(edits, None, cx);
4683 })
4684 }
4685
4686 this.refresh_inline_completion(true, false, cx);
4687 });
4688
4689 let show_new_completions_on_confirm = completion
4690 .confirm
4691 .as_ref()
4692 .map_or(false, |confirm| confirm(intent, cx));
4693 if show_new_completions_on_confirm {
4694 self.show_completions(&ShowCompletions { trigger: None }, cx);
4695 }
4696
4697 let provider = self.completion_provider.as_ref()?;
4698 let apply_edits = provider.apply_additional_edits_for_completion(
4699 buffer_handle,
4700 completion.clone(),
4701 true,
4702 cx,
4703 );
4704
4705 let editor_settings = EditorSettings::get_global(cx);
4706 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4707 // After the code completion is finished, users often want to know what signatures are needed.
4708 // so we should automatically call signature_help
4709 self.show_signature_help(&ShowSignatureHelp, cx);
4710 }
4711
4712 Some(cx.foreground_executor().spawn(async move {
4713 apply_edits.await?;
4714 Ok(())
4715 }))
4716 }
4717
4718 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4719 let mut context_menu = self.context_menu.write();
4720 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4721 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4722 // Toggle if we're selecting the same one
4723 *context_menu = None;
4724 cx.notify();
4725 return;
4726 } else {
4727 // Otherwise, clear it and start a new one
4728 *context_menu = None;
4729 cx.notify();
4730 }
4731 }
4732 drop(context_menu);
4733 let snapshot = self.snapshot(cx);
4734 let deployed_from_indicator = action.deployed_from_indicator;
4735 let mut task = self.code_actions_task.take();
4736 let action = action.clone();
4737 cx.spawn(|editor, mut cx| async move {
4738 while let Some(prev_task) = task {
4739 prev_task.await.log_err();
4740 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4741 }
4742
4743 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4744 if editor.focus_handle.is_focused(cx) {
4745 let multibuffer_point = action
4746 .deployed_from_indicator
4747 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4748 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4749 let (buffer, buffer_row) = snapshot
4750 .buffer_snapshot
4751 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4752 .and_then(|(buffer_snapshot, range)| {
4753 editor
4754 .buffer
4755 .read(cx)
4756 .buffer(buffer_snapshot.remote_id())
4757 .map(|buffer| (buffer, range.start.row))
4758 })?;
4759 let (_, code_actions) = editor
4760 .available_code_actions
4761 .clone()
4762 .and_then(|(location, code_actions)| {
4763 let snapshot = location.buffer.read(cx).snapshot();
4764 let point_range = location.range.to_point(&snapshot);
4765 let point_range = point_range.start.row..=point_range.end.row;
4766 if point_range.contains(&buffer_row) {
4767 Some((location, code_actions))
4768 } else {
4769 None
4770 }
4771 })
4772 .unzip();
4773 let buffer_id = buffer.read(cx).remote_id();
4774 let tasks = editor
4775 .tasks
4776 .get(&(buffer_id, buffer_row))
4777 .map(|t| Arc::new(t.to_owned()));
4778 if tasks.is_none() && code_actions.is_none() {
4779 return None;
4780 }
4781
4782 editor.completion_tasks.clear();
4783 editor.discard_inline_completion(false, cx);
4784 let task_context =
4785 tasks
4786 .as_ref()
4787 .zip(editor.project.clone())
4788 .map(|(tasks, project)| {
4789 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4790 });
4791
4792 Some(cx.spawn(|editor, mut cx| async move {
4793 let task_context = match task_context {
4794 Some(task_context) => task_context.await,
4795 None => None,
4796 };
4797 let resolved_tasks =
4798 tasks.zip(task_context).map(|(tasks, task_context)| {
4799 Arc::new(ResolvedTasks {
4800 templates: tasks.resolve(&task_context).collect(),
4801 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4802 multibuffer_point.row,
4803 tasks.column,
4804 )),
4805 })
4806 });
4807 let spawn_straight_away = resolved_tasks
4808 .as_ref()
4809 .map_or(false, |tasks| tasks.templates.len() == 1)
4810 && code_actions
4811 .as_ref()
4812 .map_or(true, |actions| actions.is_empty());
4813 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4814 *editor.context_menu.write() =
4815 Some(ContextMenu::CodeActions(CodeActionsMenu {
4816 buffer,
4817 actions: CodeActionContents {
4818 tasks: resolved_tasks,
4819 actions: code_actions,
4820 },
4821 selected_item: Default::default(),
4822 scroll_handle: UniformListScrollHandle::default(),
4823 deployed_from_indicator,
4824 }));
4825 if spawn_straight_away {
4826 if let Some(task) = editor.confirm_code_action(
4827 &ConfirmCodeAction { item_ix: Some(0) },
4828 cx,
4829 ) {
4830 cx.notify();
4831 return task;
4832 }
4833 }
4834 cx.notify();
4835 Task::ready(Ok(()))
4836 }) {
4837 task.await
4838 } else {
4839 Ok(())
4840 }
4841 }))
4842 } else {
4843 Some(Task::ready(Ok(())))
4844 }
4845 })?;
4846 if let Some(task) = spawned_test_task {
4847 task.await?;
4848 }
4849
4850 Ok::<_, anyhow::Error>(())
4851 })
4852 .detach_and_log_err(cx);
4853 }
4854
4855 pub fn confirm_code_action(
4856 &mut self,
4857 action: &ConfirmCodeAction,
4858 cx: &mut ViewContext<Self>,
4859 ) -> Option<Task<Result<()>>> {
4860 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4861 menu
4862 } else {
4863 return None;
4864 };
4865 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4866 let action = actions_menu.actions.get(action_ix)?;
4867 let title = action.label();
4868 let buffer = actions_menu.buffer;
4869 let workspace = self.workspace()?;
4870
4871 match action {
4872 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4873 workspace.update(cx, |workspace, cx| {
4874 workspace::tasks::schedule_resolved_task(
4875 workspace,
4876 task_source_kind,
4877 resolved_task,
4878 false,
4879 cx,
4880 );
4881
4882 Some(Task::ready(Ok(())))
4883 })
4884 }
4885 CodeActionsItem::CodeAction {
4886 excerpt_id,
4887 action,
4888 provider,
4889 } => {
4890 let apply_code_action =
4891 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4892 let workspace = workspace.downgrade();
4893 Some(cx.spawn(|editor, cx| async move {
4894 let project_transaction = apply_code_action.await?;
4895 Self::open_project_transaction(
4896 &editor,
4897 workspace,
4898 project_transaction,
4899 title,
4900 cx,
4901 )
4902 .await
4903 }))
4904 }
4905 }
4906 }
4907
4908 pub async fn open_project_transaction(
4909 this: &WeakView<Editor>,
4910 workspace: WeakView<Workspace>,
4911 transaction: ProjectTransaction,
4912 title: String,
4913 mut cx: AsyncWindowContext,
4914 ) -> Result<()> {
4915 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4916 cx.update(|cx| {
4917 entries.sort_unstable_by_key(|(buffer, _)| {
4918 buffer.read(cx).file().map(|f| f.path().clone())
4919 });
4920 })?;
4921
4922 // If the project transaction's edits are all contained within this editor, then
4923 // avoid opening a new editor to display them.
4924
4925 if let Some((buffer, transaction)) = entries.first() {
4926 if entries.len() == 1 {
4927 let excerpt = this.update(&mut cx, |editor, cx| {
4928 editor
4929 .buffer()
4930 .read(cx)
4931 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4932 })?;
4933 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4934 if excerpted_buffer == *buffer {
4935 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4936 let excerpt_range = excerpt_range.to_offset(buffer);
4937 buffer
4938 .edited_ranges_for_transaction::<usize>(transaction)
4939 .all(|range| {
4940 excerpt_range.start <= range.start
4941 && excerpt_range.end >= range.end
4942 })
4943 })?;
4944
4945 if all_edits_within_excerpt {
4946 return Ok(());
4947 }
4948 }
4949 }
4950 }
4951 } else {
4952 return Ok(());
4953 }
4954
4955 let mut ranges_to_highlight = Vec::new();
4956 let excerpt_buffer = cx.new_model(|cx| {
4957 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4958 for (buffer_handle, transaction) in &entries {
4959 let buffer = buffer_handle.read(cx);
4960 ranges_to_highlight.extend(
4961 multibuffer.push_excerpts_with_context_lines(
4962 buffer_handle.clone(),
4963 buffer
4964 .edited_ranges_for_transaction::<usize>(transaction)
4965 .collect(),
4966 DEFAULT_MULTIBUFFER_CONTEXT,
4967 cx,
4968 ),
4969 );
4970 }
4971 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4972 multibuffer
4973 })?;
4974
4975 workspace.update(&mut cx, |workspace, cx| {
4976 let project = workspace.project().clone();
4977 let editor =
4978 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4979 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4980 editor.update(cx, |editor, cx| {
4981 editor.highlight_background::<Self>(
4982 &ranges_to_highlight,
4983 |theme| theme.editor_highlighted_line_background,
4984 cx,
4985 );
4986 });
4987 })?;
4988
4989 Ok(())
4990 }
4991
4992 pub fn clear_code_action_providers(&mut self) {
4993 self.code_action_providers.clear();
4994 self.available_code_actions.take();
4995 }
4996
4997 pub fn push_code_action_provider(
4998 &mut self,
4999 provider: Arc<dyn CodeActionProvider>,
5000 cx: &mut ViewContext<Self>,
5001 ) {
5002 self.code_action_providers.push(provider);
5003 self.refresh_code_actions(cx);
5004 }
5005
5006 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5007 let buffer = self.buffer.read(cx);
5008 let newest_selection = self.selections.newest_anchor().clone();
5009 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5010 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5011 if start_buffer != end_buffer {
5012 return None;
5013 }
5014
5015 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5016 cx.background_executor()
5017 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5018 .await;
5019
5020 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5021 let providers = this.code_action_providers.clone();
5022 let tasks = this
5023 .code_action_providers
5024 .iter()
5025 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5026 .collect::<Vec<_>>();
5027 (providers, tasks)
5028 })?;
5029
5030 let mut actions = Vec::new();
5031 for (provider, provider_actions) in
5032 providers.into_iter().zip(future::join_all(tasks).await)
5033 {
5034 if let Some(provider_actions) = provider_actions.log_err() {
5035 actions.extend(provider_actions.into_iter().map(|action| {
5036 AvailableCodeAction {
5037 excerpt_id: newest_selection.start.excerpt_id,
5038 action,
5039 provider: provider.clone(),
5040 }
5041 }));
5042 }
5043 }
5044
5045 this.update(&mut cx, |this, cx| {
5046 this.available_code_actions = if actions.is_empty() {
5047 None
5048 } else {
5049 Some((
5050 Location {
5051 buffer: start_buffer,
5052 range: start..end,
5053 },
5054 actions.into(),
5055 ))
5056 };
5057 cx.notify();
5058 })
5059 }));
5060 None
5061 }
5062
5063 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5064 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5065 self.show_git_blame_inline = false;
5066
5067 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5068 cx.background_executor().timer(delay).await;
5069
5070 this.update(&mut cx, |this, cx| {
5071 this.show_git_blame_inline = true;
5072 cx.notify();
5073 })
5074 .log_err();
5075 }));
5076 }
5077 }
5078
5079 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5080 if self.pending_rename.is_some() {
5081 return None;
5082 }
5083
5084 let provider = self.semantics_provider.clone()?;
5085 let buffer = self.buffer.read(cx);
5086 let newest_selection = self.selections.newest_anchor().clone();
5087 let cursor_position = newest_selection.head();
5088 let (cursor_buffer, cursor_buffer_position) =
5089 buffer.text_anchor_for_position(cursor_position, cx)?;
5090 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5091 if cursor_buffer != tail_buffer {
5092 return None;
5093 }
5094
5095 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5096 cx.background_executor()
5097 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5098 .await;
5099
5100 let highlights = if let Some(highlights) = cx
5101 .update(|cx| {
5102 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5103 })
5104 .ok()
5105 .flatten()
5106 {
5107 highlights.await.log_err()
5108 } else {
5109 None
5110 };
5111
5112 if let Some(highlights) = highlights {
5113 this.update(&mut cx, |this, cx| {
5114 if this.pending_rename.is_some() {
5115 return;
5116 }
5117
5118 let buffer_id = cursor_position.buffer_id;
5119 let buffer = this.buffer.read(cx);
5120 if !buffer
5121 .text_anchor_for_position(cursor_position, cx)
5122 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5123 {
5124 return;
5125 }
5126
5127 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5128 let mut write_ranges = Vec::new();
5129 let mut read_ranges = Vec::new();
5130 for highlight in highlights {
5131 for (excerpt_id, excerpt_range) in
5132 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5133 {
5134 let start = highlight
5135 .range
5136 .start
5137 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5138 let end = highlight
5139 .range
5140 .end
5141 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5142 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5143 continue;
5144 }
5145
5146 let range = Anchor {
5147 buffer_id,
5148 excerpt_id,
5149 text_anchor: start,
5150 }..Anchor {
5151 buffer_id,
5152 excerpt_id,
5153 text_anchor: end,
5154 };
5155 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5156 write_ranges.push(range);
5157 } else {
5158 read_ranges.push(range);
5159 }
5160 }
5161 }
5162
5163 this.highlight_background::<DocumentHighlightRead>(
5164 &read_ranges,
5165 |theme| theme.editor_document_highlight_read_background,
5166 cx,
5167 );
5168 this.highlight_background::<DocumentHighlightWrite>(
5169 &write_ranges,
5170 |theme| theme.editor_document_highlight_write_background,
5171 cx,
5172 );
5173 cx.notify();
5174 })
5175 .log_err();
5176 }
5177 }));
5178 None
5179 }
5180
5181 pub fn refresh_inline_completion(
5182 &mut self,
5183 debounce: bool,
5184 user_requested: bool,
5185 cx: &mut ViewContext<Self>,
5186 ) -> Option<()> {
5187 let provider = self.inline_completion_provider()?;
5188 let cursor = self.selections.newest_anchor().head();
5189 let (buffer, cursor_buffer_position) =
5190 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5191
5192 if !user_requested
5193 && (!self.enable_inline_completions
5194 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5195 {
5196 self.discard_inline_completion(false, cx);
5197 return None;
5198 }
5199
5200 self.update_visible_inline_completion(cx);
5201 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5202 Some(())
5203 }
5204
5205 fn cycle_inline_completion(
5206 &mut self,
5207 direction: Direction,
5208 cx: &mut ViewContext<Self>,
5209 ) -> Option<()> {
5210 let provider = self.inline_completion_provider()?;
5211 let cursor = self.selections.newest_anchor().head();
5212 let (buffer, cursor_buffer_position) =
5213 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5214 if !self.enable_inline_completions
5215 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5216 {
5217 return None;
5218 }
5219
5220 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5221 self.update_visible_inline_completion(cx);
5222
5223 Some(())
5224 }
5225
5226 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5227 if !self.has_active_inline_completion(cx) {
5228 self.refresh_inline_completion(false, true, cx);
5229 return;
5230 }
5231
5232 self.update_visible_inline_completion(cx);
5233 }
5234
5235 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5236 self.show_cursor_names(cx);
5237 }
5238
5239 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5240 self.show_cursor_names = true;
5241 cx.notify();
5242 cx.spawn(|this, mut cx| async move {
5243 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5244 this.update(&mut cx, |this, cx| {
5245 this.show_cursor_names = false;
5246 cx.notify()
5247 })
5248 .ok()
5249 })
5250 .detach();
5251 }
5252
5253 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5254 if self.has_active_inline_completion(cx) {
5255 self.cycle_inline_completion(Direction::Next, cx);
5256 } else {
5257 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5258 if is_copilot_disabled {
5259 cx.propagate();
5260 }
5261 }
5262 }
5263
5264 pub fn previous_inline_completion(
5265 &mut self,
5266 _: &PreviousInlineCompletion,
5267 cx: &mut ViewContext<Self>,
5268 ) {
5269 if self.has_active_inline_completion(cx) {
5270 self.cycle_inline_completion(Direction::Prev, cx);
5271 } else {
5272 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5273 if is_copilot_disabled {
5274 cx.propagate();
5275 }
5276 }
5277 }
5278
5279 pub fn accept_inline_completion(
5280 &mut self,
5281 _: &AcceptInlineCompletion,
5282 cx: &mut ViewContext<Self>,
5283 ) {
5284 let Some(completion) = self.take_active_inline_completion(cx) else {
5285 return;
5286 };
5287 if let Some(provider) = self.inline_completion_provider() {
5288 provider.accept(cx);
5289 }
5290
5291 cx.emit(EditorEvent::InputHandled {
5292 utf16_range_to_replace: None,
5293 text: completion.text.to_string().into(),
5294 });
5295
5296 if let Some(range) = completion.delete_range {
5297 self.change_selections(None, cx, |s| s.select_ranges([range]))
5298 }
5299 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5300 self.refresh_inline_completion(true, true, cx);
5301 cx.notify();
5302 }
5303
5304 pub fn accept_partial_inline_completion(
5305 &mut self,
5306 _: &AcceptPartialInlineCompletion,
5307 cx: &mut ViewContext<Self>,
5308 ) {
5309 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5310 if let Some(completion) = self.take_active_inline_completion(cx) {
5311 let mut partial_completion = completion
5312 .text
5313 .chars()
5314 .by_ref()
5315 .take_while(|c| c.is_alphabetic())
5316 .collect::<String>();
5317 if partial_completion.is_empty() {
5318 partial_completion = completion
5319 .text
5320 .chars()
5321 .by_ref()
5322 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5323 .collect::<String>();
5324 }
5325
5326 cx.emit(EditorEvent::InputHandled {
5327 utf16_range_to_replace: None,
5328 text: partial_completion.clone().into(),
5329 });
5330
5331 if let Some(range) = completion.delete_range {
5332 self.change_selections(None, cx, |s| s.select_ranges([range]))
5333 }
5334 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5335
5336 self.refresh_inline_completion(true, true, cx);
5337 cx.notify();
5338 }
5339 }
5340 }
5341
5342 fn discard_inline_completion(
5343 &mut self,
5344 should_report_inline_completion_event: bool,
5345 cx: &mut ViewContext<Self>,
5346 ) -> bool {
5347 if let Some(provider) = self.inline_completion_provider() {
5348 provider.discard(should_report_inline_completion_event, cx);
5349 }
5350
5351 self.take_active_inline_completion(cx).is_some()
5352 }
5353
5354 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5355 if let Some(completion) = self.active_inline_completion.as_ref() {
5356 let buffer = self.buffer.read(cx).read(cx);
5357 completion.position.is_valid(&buffer)
5358 } else {
5359 false
5360 }
5361 }
5362
5363 fn take_active_inline_completion(
5364 &mut self,
5365 cx: &mut ViewContext<Self>,
5366 ) -> Option<CompletionState> {
5367 let completion = self.active_inline_completion.take()?;
5368 let render_inlay_ids = completion.render_inlay_ids.clone();
5369 self.display_map.update(cx, |map, cx| {
5370 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5371 });
5372 let buffer = self.buffer.read(cx).read(cx);
5373
5374 if completion.position.is_valid(&buffer) {
5375 Some(completion)
5376 } else {
5377 None
5378 }
5379 }
5380
5381 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5382 let selection = self.selections.newest_anchor();
5383 let cursor = selection.head();
5384
5385 let excerpt_id = cursor.excerpt_id;
5386
5387 if self.context_menu.read().is_none()
5388 && self.completion_tasks.is_empty()
5389 && selection.start == selection.end
5390 {
5391 if let Some(provider) = self.inline_completion_provider() {
5392 if let Some((buffer, cursor_buffer_position)) =
5393 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5394 {
5395 if let Some(proposal) =
5396 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5397 {
5398 let mut to_remove = Vec::new();
5399 if let Some(completion) = self.active_inline_completion.take() {
5400 to_remove.extend(completion.render_inlay_ids.iter());
5401 }
5402
5403 let to_add = proposal
5404 .inlays
5405 .iter()
5406 .filter_map(|inlay| {
5407 let snapshot = self.buffer.read(cx).snapshot(cx);
5408 let id = post_inc(&mut self.next_inlay_id);
5409 match inlay {
5410 InlayProposal::Hint(position, hint) => {
5411 let position =
5412 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5413 Some(Inlay::hint(id, position, hint))
5414 }
5415 InlayProposal::Suggestion(position, text) => {
5416 let position =
5417 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5418 Some(Inlay::suggestion(id, position, text.clone()))
5419 }
5420 }
5421 })
5422 .collect_vec();
5423
5424 self.active_inline_completion = Some(CompletionState {
5425 position: cursor,
5426 text: proposal.text,
5427 delete_range: proposal.delete_range.and_then(|range| {
5428 let snapshot = self.buffer.read(cx).snapshot(cx);
5429 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5430 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5431 Some(start?..end?)
5432 }),
5433 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5434 });
5435
5436 self.display_map
5437 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5438
5439 cx.notify();
5440 return;
5441 }
5442 }
5443 }
5444 }
5445
5446 self.discard_inline_completion(false, cx);
5447 }
5448
5449 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5450 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5451 }
5452
5453 fn render_code_actions_indicator(
5454 &self,
5455 _style: &EditorStyle,
5456 row: DisplayRow,
5457 is_active: bool,
5458 cx: &mut ViewContext<Self>,
5459 ) -> Option<IconButton> {
5460 if self.available_code_actions.is_some() {
5461 Some(
5462 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5463 .shape(ui::IconButtonShape::Square)
5464 .icon_size(IconSize::XSmall)
5465 .icon_color(Color::Muted)
5466 .selected(is_active)
5467 .tooltip({
5468 let focus_handle = self.focus_handle.clone();
5469 move |cx| {
5470 Tooltip::for_action_in(
5471 "Toggle Code Actions",
5472 &ToggleCodeActions {
5473 deployed_from_indicator: None,
5474 },
5475 &focus_handle,
5476 cx,
5477 )
5478 }
5479 })
5480 .on_click(cx.listener(move |editor, _e, cx| {
5481 editor.focus(cx);
5482 editor.toggle_code_actions(
5483 &ToggleCodeActions {
5484 deployed_from_indicator: Some(row),
5485 },
5486 cx,
5487 );
5488 })),
5489 )
5490 } else {
5491 None
5492 }
5493 }
5494
5495 fn clear_tasks(&mut self) {
5496 self.tasks.clear()
5497 }
5498
5499 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5500 if self.tasks.insert(key, value).is_some() {
5501 // This case should hopefully be rare, but just in case...
5502 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5503 }
5504 }
5505
5506 fn build_tasks_context(
5507 project: &Model<Project>,
5508 buffer: &Model<Buffer>,
5509 buffer_row: u32,
5510 tasks: &Arc<RunnableTasks>,
5511 cx: &mut ViewContext<Self>,
5512 ) -> Task<Option<task::TaskContext>> {
5513 let position = Point::new(buffer_row, tasks.column);
5514 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5515 let location = Location {
5516 buffer: buffer.clone(),
5517 range: range_start..range_start,
5518 };
5519 // Fill in the environmental variables from the tree-sitter captures
5520 let mut captured_task_variables = TaskVariables::default();
5521 for (capture_name, value) in tasks.extra_variables.clone() {
5522 captured_task_variables.insert(
5523 task::VariableName::Custom(capture_name.into()),
5524 value.clone(),
5525 );
5526 }
5527 project.update(cx, |project, cx| {
5528 project.task_store().update(cx, |task_store, cx| {
5529 task_store.task_context_for_location(captured_task_variables, location, cx)
5530 })
5531 })
5532 }
5533
5534 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5535 let Some((workspace, _)) = self.workspace.clone() else {
5536 return;
5537 };
5538 let Some(project) = self.project.clone() else {
5539 return;
5540 };
5541
5542 // Try to find a closest, enclosing node using tree-sitter that has a
5543 // task
5544 let Some((buffer, buffer_row, tasks)) = self
5545 .find_enclosing_node_task(cx)
5546 // Or find the task that's closest in row-distance.
5547 .or_else(|| self.find_closest_task(cx))
5548 else {
5549 return;
5550 };
5551
5552 let reveal_strategy = action.reveal;
5553 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5554 cx.spawn(|_, mut cx| async move {
5555 let context = task_context.await?;
5556 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5557
5558 let resolved = resolved_task.resolved.as_mut()?;
5559 resolved.reveal = reveal_strategy;
5560
5561 workspace
5562 .update(&mut cx, |workspace, cx| {
5563 workspace::tasks::schedule_resolved_task(
5564 workspace,
5565 task_source_kind,
5566 resolved_task,
5567 false,
5568 cx,
5569 );
5570 })
5571 .ok()
5572 })
5573 .detach();
5574 }
5575
5576 fn find_closest_task(
5577 &mut self,
5578 cx: &mut ViewContext<Self>,
5579 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5580 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5581
5582 let ((buffer_id, row), tasks) = self
5583 .tasks
5584 .iter()
5585 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5586
5587 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5588 let tasks = Arc::new(tasks.to_owned());
5589 Some((buffer, *row, tasks))
5590 }
5591
5592 fn find_enclosing_node_task(
5593 &mut self,
5594 cx: &mut ViewContext<Self>,
5595 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5596 let snapshot = self.buffer.read(cx).snapshot(cx);
5597 let offset = self.selections.newest::<usize>(cx).head();
5598 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5599 let buffer_id = excerpt.buffer().remote_id();
5600
5601 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5602 let mut cursor = layer.node().walk();
5603
5604 while cursor.goto_first_child_for_byte(offset).is_some() {
5605 if cursor.node().end_byte() == offset {
5606 cursor.goto_next_sibling();
5607 }
5608 }
5609
5610 // Ascend to the smallest ancestor that contains the range and has a task.
5611 loop {
5612 let node = cursor.node();
5613 let node_range = node.byte_range();
5614 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5615
5616 // Check if this node contains our offset
5617 if node_range.start <= offset && node_range.end >= offset {
5618 // If it contains offset, check for task
5619 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5620 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5621 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5622 }
5623 }
5624
5625 if !cursor.goto_parent() {
5626 break;
5627 }
5628 }
5629 None
5630 }
5631
5632 fn render_run_indicator(
5633 &self,
5634 _style: &EditorStyle,
5635 is_active: bool,
5636 row: DisplayRow,
5637 cx: &mut ViewContext<Self>,
5638 ) -> IconButton {
5639 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5640 .shape(ui::IconButtonShape::Square)
5641 .icon_size(IconSize::XSmall)
5642 .icon_color(Color::Muted)
5643 .selected(is_active)
5644 .on_click(cx.listener(move |editor, _e, cx| {
5645 editor.focus(cx);
5646 editor.toggle_code_actions(
5647 &ToggleCodeActions {
5648 deployed_from_indicator: Some(row),
5649 },
5650 cx,
5651 );
5652 }))
5653 }
5654
5655 pub fn context_menu_visible(&self) -> bool {
5656 self.context_menu
5657 .read()
5658 .as_ref()
5659 .map_or(false, |menu| menu.visible())
5660 }
5661
5662 fn render_context_menu(
5663 &self,
5664 cursor_position: DisplayPoint,
5665 style: &EditorStyle,
5666 max_height: Pixels,
5667 cx: &mut ViewContext<Editor>,
5668 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5669 self.context_menu.read().as_ref().map(|menu| {
5670 menu.render(
5671 cursor_position,
5672 style,
5673 max_height,
5674 self.workspace.as_ref().map(|(w, _)| w.clone()),
5675 cx,
5676 )
5677 })
5678 }
5679
5680 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5681 cx.notify();
5682 self.completion_tasks.clear();
5683 let context_menu = self.context_menu.write().take();
5684 if context_menu.is_some() {
5685 self.update_visible_inline_completion(cx);
5686 }
5687 context_menu
5688 }
5689
5690 pub fn insert_snippet(
5691 &mut self,
5692 insertion_ranges: &[Range<usize>],
5693 snippet: Snippet,
5694 cx: &mut ViewContext<Self>,
5695 ) -> Result<()> {
5696 struct Tabstop<T> {
5697 is_end_tabstop: bool,
5698 ranges: Vec<Range<T>>,
5699 }
5700
5701 let tabstops = self.buffer.update(cx, |buffer, cx| {
5702 let snippet_text: Arc<str> = snippet.text.clone().into();
5703 buffer.edit(
5704 insertion_ranges
5705 .iter()
5706 .cloned()
5707 .map(|range| (range, snippet_text.clone())),
5708 Some(AutoindentMode::EachLine),
5709 cx,
5710 );
5711
5712 let snapshot = &*buffer.read(cx);
5713 let snippet = &snippet;
5714 snippet
5715 .tabstops
5716 .iter()
5717 .map(|tabstop| {
5718 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5719 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5720 });
5721 let mut tabstop_ranges = tabstop
5722 .iter()
5723 .flat_map(|tabstop_range| {
5724 let mut delta = 0_isize;
5725 insertion_ranges.iter().map(move |insertion_range| {
5726 let insertion_start = insertion_range.start as isize + delta;
5727 delta +=
5728 snippet.text.len() as isize - insertion_range.len() as isize;
5729
5730 let start = ((insertion_start + tabstop_range.start) as usize)
5731 .min(snapshot.len());
5732 let end = ((insertion_start + tabstop_range.end) as usize)
5733 .min(snapshot.len());
5734 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5735 })
5736 })
5737 .collect::<Vec<_>>();
5738 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5739
5740 Tabstop {
5741 is_end_tabstop,
5742 ranges: tabstop_ranges,
5743 }
5744 })
5745 .collect::<Vec<_>>()
5746 });
5747 if let Some(tabstop) = tabstops.first() {
5748 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5749 s.select_ranges(tabstop.ranges.iter().cloned());
5750 });
5751
5752 // If we're already at the last tabstop and it's at the end of the snippet,
5753 // we're done, we don't need to keep the state around.
5754 if !tabstop.is_end_tabstop {
5755 let ranges = tabstops
5756 .into_iter()
5757 .map(|tabstop| tabstop.ranges)
5758 .collect::<Vec<_>>();
5759 self.snippet_stack.push(SnippetState {
5760 active_index: 0,
5761 ranges,
5762 });
5763 }
5764
5765 // Check whether the just-entered snippet ends with an auto-closable bracket.
5766 if self.autoclose_regions.is_empty() {
5767 let snapshot = self.buffer.read(cx).snapshot(cx);
5768 for selection in &mut self.selections.all::<Point>(cx) {
5769 let selection_head = selection.head();
5770 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5771 continue;
5772 };
5773
5774 let mut bracket_pair = None;
5775 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5776 let prev_chars = snapshot
5777 .reversed_chars_at(selection_head)
5778 .collect::<String>();
5779 for (pair, enabled) in scope.brackets() {
5780 if enabled
5781 && pair.close
5782 && prev_chars.starts_with(pair.start.as_str())
5783 && next_chars.starts_with(pair.end.as_str())
5784 {
5785 bracket_pair = Some(pair.clone());
5786 break;
5787 }
5788 }
5789 if let Some(pair) = bracket_pair {
5790 let start = snapshot.anchor_after(selection_head);
5791 let end = snapshot.anchor_after(selection_head);
5792 self.autoclose_regions.push(AutocloseRegion {
5793 selection_id: selection.id,
5794 range: start..end,
5795 pair,
5796 });
5797 }
5798 }
5799 }
5800 }
5801 Ok(())
5802 }
5803
5804 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5805 self.move_to_snippet_tabstop(Bias::Right, cx)
5806 }
5807
5808 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5809 self.move_to_snippet_tabstop(Bias::Left, cx)
5810 }
5811
5812 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5813 if let Some(mut snippet) = self.snippet_stack.pop() {
5814 match bias {
5815 Bias::Left => {
5816 if snippet.active_index > 0 {
5817 snippet.active_index -= 1;
5818 } else {
5819 self.snippet_stack.push(snippet);
5820 return false;
5821 }
5822 }
5823 Bias::Right => {
5824 if snippet.active_index + 1 < snippet.ranges.len() {
5825 snippet.active_index += 1;
5826 } else {
5827 self.snippet_stack.push(snippet);
5828 return false;
5829 }
5830 }
5831 }
5832 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5833 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5834 s.select_anchor_ranges(current_ranges.iter().cloned())
5835 });
5836 // If snippet state is not at the last tabstop, push it back on the stack
5837 if snippet.active_index + 1 < snippet.ranges.len() {
5838 self.snippet_stack.push(snippet);
5839 }
5840 return true;
5841 }
5842 }
5843
5844 false
5845 }
5846
5847 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5848 self.transact(cx, |this, cx| {
5849 this.select_all(&SelectAll, cx);
5850 this.insert("", cx);
5851 });
5852 }
5853
5854 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5855 self.transact(cx, |this, cx| {
5856 this.select_autoclose_pair(cx);
5857 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5858 if !this.linked_edit_ranges.is_empty() {
5859 let selections = this.selections.all::<MultiBufferPoint>(cx);
5860 let snapshot = this.buffer.read(cx).snapshot(cx);
5861
5862 for selection in selections.iter() {
5863 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5864 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5865 if selection_start.buffer_id != selection_end.buffer_id {
5866 continue;
5867 }
5868 if let Some(ranges) =
5869 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5870 {
5871 for (buffer, entries) in ranges {
5872 linked_ranges.entry(buffer).or_default().extend(entries);
5873 }
5874 }
5875 }
5876 }
5877
5878 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5879 if !this.selections.line_mode {
5880 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5881 for selection in &mut selections {
5882 if selection.is_empty() {
5883 let old_head = selection.head();
5884 let mut new_head =
5885 movement::left(&display_map, old_head.to_display_point(&display_map))
5886 .to_point(&display_map);
5887 if let Some((buffer, line_buffer_range)) = display_map
5888 .buffer_snapshot
5889 .buffer_line_for_row(MultiBufferRow(old_head.row))
5890 {
5891 let indent_size =
5892 buffer.indent_size_for_line(line_buffer_range.start.row);
5893 let indent_len = match indent_size.kind {
5894 IndentKind::Space => {
5895 buffer.settings_at(line_buffer_range.start, cx).tab_size
5896 }
5897 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5898 };
5899 if old_head.column <= indent_size.len && old_head.column > 0 {
5900 let indent_len = indent_len.get();
5901 new_head = cmp::min(
5902 new_head,
5903 MultiBufferPoint::new(
5904 old_head.row,
5905 ((old_head.column - 1) / indent_len) * indent_len,
5906 ),
5907 );
5908 }
5909 }
5910
5911 selection.set_head(new_head, SelectionGoal::None);
5912 }
5913 }
5914 }
5915
5916 this.signature_help_state.set_backspace_pressed(true);
5917 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5918 this.insert("", cx);
5919 let empty_str: Arc<str> = Arc::from("");
5920 for (buffer, edits) in linked_ranges {
5921 let snapshot = buffer.read(cx).snapshot();
5922 use text::ToPoint as TP;
5923
5924 let edits = edits
5925 .into_iter()
5926 .map(|range| {
5927 let end_point = TP::to_point(&range.end, &snapshot);
5928 let mut start_point = TP::to_point(&range.start, &snapshot);
5929
5930 if end_point == start_point {
5931 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5932 .saturating_sub(1);
5933 start_point = TP::to_point(&offset, &snapshot);
5934 };
5935
5936 (start_point..end_point, empty_str.clone())
5937 })
5938 .sorted_by_key(|(range, _)| range.start)
5939 .collect::<Vec<_>>();
5940 buffer.update(cx, |this, cx| {
5941 this.edit(edits, None, cx);
5942 })
5943 }
5944 this.refresh_inline_completion(true, false, cx);
5945 linked_editing_ranges::refresh_linked_ranges(this, cx);
5946 });
5947 }
5948
5949 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5950 self.transact(cx, |this, cx| {
5951 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5952 let line_mode = s.line_mode;
5953 s.move_with(|map, selection| {
5954 if selection.is_empty() && !line_mode {
5955 let cursor = movement::right(map, selection.head());
5956 selection.end = cursor;
5957 selection.reversed = true;
5958 selection.goal = SelectionGoal::None;
5959 }
5960 })
5961 });
5962 this.insert("", cx);
5963 this.refresh_inline_completion(true, false, cx);
5964 });
5965 }
5966
5967 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5968 if self.move_to_prev_snippet_tabstop(cx) {
5969 return;
5970 }
5971
5972 self.outdent(&Outdent, cx);
5973 }
5974
5975 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5976 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5977 return;
5978 }
5979
5980 let mut selections = self.selections.all_adjusted(cx);
5981 let buffer = self.buffer.read(cx);
5982 let snapshot = buffer.snapshot(cx);
5983 let rows_iter = selections.iter().map(|s| s.head().row);
5984 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5985
5986 let mut edits = Vec::new();
5987 let mut prev_edited_row = 0;
5988 let mut row_delta = 0;
5989 for selection in &mut selections {
5990 if selection.start.row != prev_edited_row {
5991 row_delta = 0;
5992 }
5993 prev_edited_row = selection.end.row;
5994
5995 // If the selection is non-empty, then increase the indentation of the selected lines.
5996 if !selection.is_empty() {
5997 row_delta =
5998 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5999 continue;
6000 }
6001
6002 // If the selection is empty and the cursor is in the leading whitespace before the
6003 // suggested indentation, then auto-indent the line.
6004 let cursor = selection.head();
6005 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6006 if let Some(suggested_indent) =
6007 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6008 {
6009 if cursor.column < suggested_indent.len
6010 && cursor.column <= current_indent.len
6011 && current_indent.len <= suggested_indent.len
6012 {
6013 selection.start = Point::new(cursor.row, suggested_indent.len);
6014 selection.end = selection.start;
6015 if row_delta == 0 {
6016 edits.extend(Buffer::edit_for_indent_size_adjustment(
6017 cursor.row,
6018 current_indent,
6019 suggested_indent,
6020 ));
6021 row_delta = suggested_indent.len - current_indent.len;
6022 }
6023 continue;
6024 }
6025 }
6026
6027 // Otherwise, insert a hard or soft tab.
6028 let settings = buffer.settings_at(cursor, cx);
6029 let tab_size = if settings.hard_tabs {
6030 IndentSize::tab()
6031 } else {
6032 let tab_size = settings.tab_size.get();
6033 let char_column = snapshot
6034 .text_for_range(Point::new(cursor.row, 0)..cursor)
6035 .flat_map(str::chars)
6036 .count()
6037 + row_delta as usize;
6038 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6039 IndentSize::spaces(chars_to_next_tab_stop)
6040 };
6041 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6042 selection.end = selection.start;
6043 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6044 row_delta += tab_size.len;
6045 }
6046
6047 self.transact(cx, |this, cx| {
6048 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6049 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6050 this.refresh_inline_completion(true, false, cx);
6051 });
6052 }
6053
6054 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6055 if self.read_only(cx) {
6056 return;
6057 }
6058 let mut selections = self.selections.all::<Point>(cx);
6059 let mut prev_edited_row = 0;
6060 let mut row_delta = 0;
6061 let mut edits = Vec::new();
6062 let buffer = self.buffer.read(cx);
6063 let snapshot = buffer.snapshot(cx);
6064 for selection in &mut selections {
6065 if selection.start.row != prev_edited_row {
6066 row_delta = 0;
6067 }
6068 prev_edited_row = selection.end.row;
6069
6070 row_delta =
6071 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6072 }
6073
6074 self.transact(cx, |this, cx| {
6075 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6076 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6077 });
6078 }
6079
6080 fn indent_selection(
6081 buffer: &MultiBuffer,
6082 snapshot: &MultiBufferSnapshot,
6083 selection: &mut Selection<Point>,
6084 edits: &mut Vec<(Range<Point>, String)>,
6085 delta_for_start_row: u32,
6086 cx: &AppContext,
6087 ) -> u32 {
6088 let settings = buffer.settings_at(selection.start, cx);
6089 let tab_size = settings.tab_size.get();
6090 let indent_kind = if settings.hard_tabs {
6091 IndentKind::Tab
6092 } else {
6093 IndentKind::Space
6094 };
6095 let mut start_row = selection.start.row;
6096 let mut end_row = selection.end.row + 1;
6097
6098 // If a selection ends at the beginning of a line, don't indent
6099 // that last line.
6100 if selection.end.column == 0 && selection.end.row > selection.start.row {
6101 end_row -= 1;
6102 }
6103
6104 // Avoid re-indenting a row that has already been indented by a
6105 // previous selection, but still update this selection's column
6106 // to reflect that indentation.
6107 if delta_for_start_row > 0 {
6108 start_row += 1;
6109 selection.start.column += delta_for_start_row;
6110 if selection.end.row == selection.start.row {
6111 selection.end.column += delta_for_start_row;
6112 }
6113 }
6114
6115 let mut delta_for_end_row = 0;
6116 let has_multiple_rows = start_row + 1 != end_row;
6117 for row in start_row..end_row {
6118 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6119 let indent_delta = match (current_indent.kind, indent_kind) {
6120 (IndentKind::Space, IndentKind::Space) => {
6121 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6122 IndentSize::spaces(columns_to_next_tab_stop)
6123 }
6124 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6125 (_, IndentKind::Tab) => IndentSize::tab(),
6126 };
6127
6128 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6129 0
6130 } else {
6131 selection.start.column
6132 };
6133 let row_start = Point::new(row, start);
6134 edits.push((
6135 row_start..row_start,
6136 indent_delta.chars().collect::<String>(),
6137 ));
6138
6139 // Update this selection's endpoints to reflect the indentation.
6140 if row == selection.start.row {
6141 selection.start.column += indent_delta.len;
6142 }
6143 if row == selection.end.row {
6144 selection.end.column += indent_delta.len;
6145 delta_for_end_row = indent_delta.len;
6146 }
6147 }
6148
6149 if selection.start.row == selection.end.row {
6150 delta_for_start_row + delta_for_end_row
6151 } else {
6152 delta_for_end_row
6153 }
6154 }
6155
6156 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6157 if self.read_only(cx) {
6158 return;
6159 }
6160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6161 let selections = self.selections.all::<Point>(cx);
6162 let mut deletion_ranges = Vec::new();
6163 let mut last_outdent = None;
6164 {
6165 let buffer = self.buffer.read(cx);
6166 let snapshot = buffer.snapshot(cx);
6167 for selection in &selections {
6168 let settings = buffer.settings_at(selection.start, cx);
6169 let tab_size = settings.tab_size.get();
6170 let mut rows = selection.spanned_rows(false, &display_map);
6171
6172 // Avoid re-outdenting a row that has already been outdented by a
6173 // previous selection.
6174 if let Some(last_row) = last_outdent {
6175 if last_row == rows.start {
6176 rows.start = rows.start.next_row();
6177 }
6178 }
6179 let has_multiple_rows = rows.len() > 1;
6180 for row in rows.iter_rows() {
6181 let indent_size = snapshot.indent_size_for_line(row);
6182 if indent_size.len > 0 {
6183 let deletion_len = match indent_size.kind {
6184 IndentKind::Space => {
6185 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6186 if columns_to_prev_tab_stop == 0 {
6187 tab_size
6188 } else {
6189 columns_to_prev_tab_stop
6190 }
6191 }
6192 IndentKind::Tab => 1,
6193 };
6194 let start = if has_multiple_rows
6195 || deletion_len > selection.start.column
6196 || indent_size.len < selection.start.column
6197 {
6198 0
6199 } else {
6200 selection.start.column - deletion_len
6201 };
6202 deletion_ranges.push(
6203 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6204 );
6205 last_outdent = Some(row);
6206 }
6207 }
6208 }
6209 }
6210
6211 self.transact(cx, |this, cx| {
6212 this.buffer.update(cx, |buffer, cx| {
6213 let empty_str: Arc<str> = Arc::default();
6214 buffer.edit(
6215 deletion_ranges
6216 .into_iter()
6217 .map(|range| (range, empty_str.clone())),
6218 None,
6219 cx,
6220 );
6221 });
6222 let selections = this.selections.all::<usize>(cx);
6223 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6224 });
6225 }
6226
6227 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6229 let selections = self.selections.all::<Point>(cx);
6230
6231 let mut new_cursors = Vec::new();
6232 let mut edit_ranges = Vec::new();
6233 let mut selections = selections.iter().peekable();
6234 while let Some(selection) = selections.next() {
6235 let mut rows = selection.spanned_rows(false, &display_map);
6236 let goal_display_column = selection.head().to_display_point(&display_map).column();
6237
6238 // Accumulate contiguous regions of rows that we want to delete.
6239 while let Some(next_selection) = selections.peek() {
6240 let next_rows = next_selection.spanned_rows(false, &display_map);
6241 if next_rows.start <= rows.end {
6242 rows.end = next_rows.end;
6243 selections.next().unwrap();
6244 } else {
6245 break;
6246 }
6247 }
6248
6249 let buffer = &display_map.buffer_snapshot;
6250 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6251 let edit_end;
6252 let cursor_buffer_row;
6253 if buffer.max_point().row >= rows.end.0 {
6254 // If there's a line after the range, delete the \n from the end of the row range
6255 // and position the cursor on the next line.
6256 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6257 cursor_buffer_row = rows.end;
6258 } else {
6259 // If there isn't a line after the range, delete the \n from the line before the
6260 // start of the row range and position the cursor there.
6261 edit_start = edit_start.saturating_sub(1);
6262 edit_end = buffer.len();
6263 cursor_buffer_row = rows.start.previous_row();
6264 }
6265
6266 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6267 *cursor.column_mut() =
6268 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6269
6270 new_cursors.push((
6271 selection.id,
6272 buffer.anchor_after(cursor.to_point(&display_map)),
6273 ));
6274 edit_ranges.push(edit_start..edit_end);
6275 }
6276
6277 self.transact(cx, |this, cx| {
6278 let buffer = this.buffer.update(cx, |buffer, cx| {
6279 let empty_str: Arc<str> = Arc::default();
6280 buffer.edit(
6281 edit_ranges
6282 .into_iter()
6283 .map(|range| (range, empty_str.clone())),
6284 None,
6285 cx,
6286 );
6287 buffer.snapshot(cx)
6288 });
6289 let new_selections = new_cursors
6290 .into_iter()
6291 .map(|(id, cursor)| {
6292 let cursor = cursor.to_point(&buffer);
6293 Selection {
6294 id,
6295 start: cursor,
6296 end: cursor,
6297 reversed: false,
6298 goal: SelectionGoal::None,
6299 }
6300 })
6301 .collect();
6302
6303 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6304 s.select(new_selections);
6305 });
6306 });
6307 }
6308
6309 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6310 if self.read_only(cx) {
6311 return;
6312 }
6313 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6314 for selection in self.selections.all::<Point>(cx) {
6315 let start = MultiBufferRow(selection.start.row);
6316 // Treat single line selections as if they include the next line. Otherwise this action
6317 // would do nothing for single line selections individual cursors.
6318 let end = if selection.start.row == selection.end.row {
6319 MultiBufferRow(selection.start.row + 1)
6320 } else {
6321 MultiBufferRow(selection.end.row)
6322 };
6323
6324 if let Some(last_row_range) = row_ranges.last_mut() {
6325 if start <= last_row_range.end {
6326 last_row_range.end = end;
6327 continue;
6328 }
6329 }
6330 row_ranges.push(start..end);
6331 }
6332
6333 let snapshot = self.buffer.read(cx).snapshot(cx);
6334 let mut cursor_positions = Vec::new();
6335 for row_range in &row_ranges {
6336 let anchor = snapshot.anchor_before(Point::new(
6337 row_range.end.previous_row().0,
6338 snapshot.line_len(row_range.end.previous_row()),
6339 ));
6340 cursor_positions.push(anchor..anchor);
6341 }
6342
6343 self.transact(cx, |this, cx| {
6344 for row_range in row_ranges.into_iter().rev() {
6345 for row in row_range.iter_rows().rev() {
6346 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6347 let next_line_row = row.next_row();
6348 let indent = snapshot.indent_size_for_line(next_line_row);
6349 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6350
6351 let replace = if snapshot.line_len(next_line_row) > indent.len {
6352 " "
6353 } else {
6354 ""
6355 };
6356
6357 this.buffer.update(cx, |buffer, cx| {
6358 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6359 });
6360 }
6361 }
6362
6363 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6364 s.select_anchor_ranges(cursor_positions)
6365 });
6366 });
6367 }
6368
6369 pub fn sort_lines_case_sensitive(
6370 &mut self,
6371 _: &SortLinesCaseSensitive,
6372 cx: &mut ViewContext<Self>,
6373 ) {
6374 self.manipulate_lines(cx, |lines| lines.sort())
6375 }
6376
6377 pub fn sort_lines_case_insensitive(
6378 &mut self,
6379 _: &SortLinesCaseInsensitive,
6380 cx: &mut ViewContext<Self>,
6381 ) {
6382 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6383 }
6384
6385 pub fn unique_lines_case_insensitive(
6386 &mut self,
6387 _: &UniqueLinesCaseInsensitive,
6388 cx: &mut ViewContext<Self>,
6389 ) {
6390 self.manipulate_lines(cx, |lines| {
6391 let mut seen = HashSet::default();
6392 lines.retain(|line| seen.insert(line.to_lowercase()));
6393 })
6394 }
6395
6396 pub fn unique_lines_case_sensitive(
6397 &mut self,
6398 _: &UniqueLinesCaseSensitive,
6399 cx: &mut ViewContext<Self>,
6400 ) {
6401 self.manipulate_lines(cx, |lines| {
6402 let mut seen = HashSet::default();
6403 lines.retain(|line| seen.insert(*line));
6404 })
6405 }
6406
6407 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6408 let mut revert_changes = HashMap::default();
6409 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6410 for hunk in hunks_for_rows(
6411 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6412 &multi_buffer_snapshot,
6413 ) {
6414 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6415 }
6416 if !revert_changes.is_empty() {
6417 self.transact(cx, |editor, cx| {
6418 editor.revert(revert_changes, cx);
6419 });
6420 }
6421 }
6422
6423 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6424 let Some(project) = self.project.clone() else {
6425 return;
6426 };
6427 self.reload(project, cx).detach_and_notify_err(cx);
6428 }
6429
6430 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6431 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6432 if !revert_changes.is_empty() {
6433 self.transact(cx, |editor, cx| {
6434 editor.revert(revert_changes, cx);
6435 });
6436 }
6437 }
6438
6439 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6440 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6441 let project_path = buffer.read(cx).project_path(cx)?;
6442 let project = self.project.as_ref()?.read(cx);
6443 let entry = project.entry_for_path(&project_path, cx)?;
6444 let parent = match &entry.canonical_path {
6445 Some(canonical_path) => canonical_path.to_path_buf(),
6446 None => project.absolute_path(&project_path, cx)?,
6447 }
6448 .parent()?
6449 .to_path_buf();
6450 Some(parent)
6451 }) {
6452 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6453 }
6454 }
6455
6456 fn gather_revert_changes(
6457 &mut self,
6458 selections: &[Selection<Anchor>],
6459 cx: &mut ViewContext<'_, Editor>,
6460 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6461 let mut revert_changes = HashMap::default();
6462 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6463 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6464 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6465 }
6466 revert_changes
6467 }
6468
6469 pub fn prepare_revert_change(
6470 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6471 multi_buffer: &Model<MultiBuffer>,
6472 hunk: &MultiBufferDiffHunk,
6473 cx: &AppContext,
6474 ) -> Option<()> {
6475 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6476 let buffer = buffer.read(cx);
6477 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6478 let buffer_snapshot = buffer.snapshot();
6479 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6480 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6481 probe
6482 .0
6483 .start
6484 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6485 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6486 }) {
6487 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6488 Some(())
6489 } else {
6490 None
6491 }
6492 }
6493
6494 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6495 self.manipulate_lines(cx, |lines| lines.reverse())
6496 }
6497
6498 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6499 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6500 }
6501
6502 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6503 where
6504 Fn: FnMut(&mut Vec<&str>),
6505 {
6506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6507 let buffer = self.buffer.read(cx).snapshot(cx);
6508
6509 let mut edits = Vec::new();
6510
6511 let selections = self.selections.all::<Point>(cx);
6512 let mut selections = selections.iter().peekable();
6513 let mut contiguous_row_selections = Vec::new();
6514 let mut new_selections = Vec::new();
6515 let mut added_lines = 0;
6516 let mut removed_lines = 0;
6517
6518 while let Some(selection) = selections.next() {
6519 let (start_row, end_row) = consume_contiguous_rows(
6520 &mut contiguous_row_selections,
6521 selection,
6522 &display_map,
6523 &mut selections,
6524 );
6525
6526 let start_point = Point::new(start_row.0, 0);
6527 let end_point = Point::new(
6528 end_row.previous_row().0,
6529 buffer.line_len(end_row.previous_row()),
6530 );
6531 let text = buffer
6532 .text_for_range(start_point..end_point)
6533 .collect::<String>();
6534
6535 let mut lines = text.split('\n').collect_vec();
6536
6537 let lines_before = lines.len();
6538 callback(&mut lines);
6539 let lines_after = lines.len();
6540
6541 edits.push((start_point..end_point, lines.join("\n")));
6542
6543 // Selections must change based on added and removed line count
6544 let start_row =
6545 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6546 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6547 new_selections.push(Selection {
6548 id: selection.id,
6549 start: start_row,
6550 end: end_row,
6551 goal: SelectionGoal::None,
6552 reversed: selection.reversed,
6553 });
6554
6555 if lines_after > lines_before {
6556 added_lines += lines_after - lines_before;
6557 } else if lines_before > lines_after {
6558 removed_lines += lines_before - lines_after;
6559 }
6560 }
6561
6562 self.transact(cx, |this, cx| {
6563 let buffer = this.buffer.update(cx, |buffer, cx| {
6564 buffer.edit(edits, None, cx);
6565 buffer.snapshot(cx)
6566 });
6567
6568 // Recalculate offsets on newly edited buffer
6569 let new_selections = new_selections
6570 .iter()
6571 .map(|s| {
6572 let start_point = Point::new(s.start.0, 0);
6573 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6574 Selection {
6575 id: s.id,
6576 start: buffer.point_to_offset(start_point),
6577 end: buffer.point_to_offset(end_point),
6578 goal: s.goal,
6579 reversed: s.reversed,
6580 }
6581 })
6582 .collect();
6583
6584 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6585 s.select(new_selections);
6586 });
6587
6588 this.request_autoscroll(Autoscroll::fit(), cx);
6589 });
6590 }
6591
6592 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6593 self.manipulate_text(cx, |text| text.to_uppercase())
6594 }
6595
6596 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6597 self.manipulate_text(cx, |text| text.to_lowercase())
6598 }
6599
6600 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6601 self.manipulate_text(cx, |text| {
6602 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6603 // https://github.com/rutrum/convert-case/issues/16
6604 text.split('\n')
6605 .map(|line| line.to_case(Case::Title))
6606 .join("\n")
6607 })
6608 }
6609
6610 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6611 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6612 }
6613
6614 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6615 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6616 }
6617
6618 pub fn convert_to_upper_camel_case(
6619 &mut self,
6620 _: &ConvertToUpperCamelCase,
6621 cx: &mut ViewContext<Self>,
6622 ) {
6623 self.manipulate_text(cx, |text| {
6624 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6625 // https://github.com/rutrum/convert-case/issues/16
6626 text.split('\n')
6627 .map(|line| line.to_case(Case::UpperCamel))
6628 .join("\n")
6629 })
6630 }
6631
6632 pub fn convert_to_lower_camel_case(
6633 &mut self,
6634 _: &ConvertToLowerCamelCase,
6635 cx: &mut ViewContext<Self>,
6636 ) {
6637 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6638 }
6639
6640 pub fn convert_to_opposite_case(
6641 &mut self,
6642 _: &ConvertToOppositeCase,
6643 cx: &mut ViewContext<Self>,
6644 ) {
6645 self.manipulate_text(cx, |text| {
6646 text.chars()
6647 .fold(String::with_capacity(text.len()), |mut t, c| {
6648 if c.is_uppercase() {
6649 t.extend(c.to_lowercase());
6650 } else {
6651 t.extend(c.to_uppercase());
6652 }
6653 t
6654 })
6655 })
6656 }
6657
6658 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6659 where
6660 Fn: FnMut(&str) -> String,
6661 {
6662 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6663 let buffer = self.buffer.read(cx).snapshot(cx);
6664
6665 let mut new_selections = Vec::new();
6666 let mut edits = Vec::new();
6667 let mut selection_adjustment = 0i32;
6668
6669 for selection in self.selections.all::<usize>(cx) {
6670 let selection_is_empty = selection.is_empty();
6671
6672 let (start, end) = if selection_is_empty {
6673 let word_range = movement::surrounding_word(
6674 &display_map,
6675 selection.start.to_display_point(&display_map),
6676 );
6677 let start = word_range.start.to_offset(&display_map, Bias::Left);
6678 let end = word_range.end.to_offset(&display_map, Bias::Left);
6679 (start, end)
6680 } else {
6681 (selection.start, selection.end)
6682 };
6683
6684 let text = buffer.text_for_range(start..end).collect::<String>();
6685 let old_length = text.len() as i32;
6686 let text = callback(&text);
6687
6688 new_selections.push(Selection {
6689 start: (start as i32 - selection_adjustment) as usize,
6690 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6691 goal: SelectionGoal::None,
6692 ..selection
6693 });
6694
6695 selection_adjustment += old_length - text.len() as i32;
6696
6697 edits.push((start..end, text));
6698 }
6699
6700 self.transact(cx, |this, cx| {
6701 this.buffer.update(cx, |buffer, cx| {
6702 buffer.edit(edits, None, cx);
6703 });
6704
6705 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6706 s.select(new_selections);
6707 });
6708
6709 this.request_autoscroll(Autoscroll::fit(), cx);
6710 });
6711 }
6712
6713 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6714 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6715 let buffer = &display_map.buffer_snapshot;
6716 let selections = self.selections.all::<Point>(cx);
6717
6718 let mut edits = Vec::new();
6719 let mut selections_iter = selections.iter().peekable();
6720 while let Some(selection) = selections_iter.next() {
6721 // Avoid duplicating the same lines twice.
6722 let mut rows = selection.spanned_rows(false, &display_map);
6723
6724 while let Some(next_selection) = selections_iter.peek() {
6725 let next_rows = next_selection.spanned_rows(false, &display_map);
6726 if next_rows.start < rows.end {
6727 rows.end = next_rows.end;
6728 selections_iter.next().unwrap();
6729 } else {
6730 break;
6731 }
6732 }
6733
6734 // Copy the text from the selected row region and splice it either at the start
6735 // or end of the region.
6736 let start = Point::new(rows.start.0, 0);
6737 let end = Point::new(
6738 rows.end.previous_row().0,
6739 buffer.line_len(rows.end.previous_row()),
6740 );
6741 let text = buffer
6742 .text_for_range(start..end)
6743 .chain(Some("\n"))
6744 .collect::<String>();
6745 let insert_location = if upwards {
6746 Point::new(rows.end.0, 0)
6747 } else {
6748 start
6749 };
6750 edits.push((insert_location..insert_location, text));
6751 }
6752
6753 self.transact(cx, |this, cx| {
6754 this.buffer.update(cx, |buffer, cx| {
6755 buffer.edit(edits, None, cx);
6756 });
6757
6758 this.request_autoscroll(Autoscroll::fit(), cx);
6759 });
6760 }
6761
6762 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6763 self.duplicate_line(true, cx);
6764 }
6765
6766 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6767 self.duplicate_line(false, cx);
6768 }
6769
6770 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6771 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6772 let buffer = self.buffer.read(cx).snapshot(cx);
6773
6774 let mut edits = Vec::new();
6775 let mut unfold_ranges = Vec::new();
6776 let mut refold_ranges = Vec::new();
6777
6778 let selections = self.selections.all::<Point>(cx);
6779 let mut selections = selections.iter().peekable();
6780 let mut contiguous_row_selections = Vec::new();
6781 let mut new_selections = Vec::new();
6782
6783 while let Some(selection) = selections.next() {
6784 // Find all the selections that span a contiguous row range
6785 let (start_row, end_row) = consume_contiguous_rows(
6786 &mut contiguous_row_selections,
6787 selection,
6788 &display_map,
6789 &mut selections,
6790 );
6791
6792 // Move the text spanned by the row range to be before the line preceding the row range
6793 if start_row.0 > 0 {
6794 let range_to_move = Point::new(
6795 start_row.previous_row().0,
6796 buffer.line_len(start_row.previous_row()),
6797 )
6798 ..Point::new(
6799 end_row.previous_row().0,
6800 buffer.line_len(end_row.previous_row()),
6801 );
6802 let insertion_point = display_map
6803 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6804 .0;
6805
6806 // Don't move lines across excerpts
6807 if buffer
6808 .excerpt_boundaries_in_range((
6809 Bound::Excluded(insertion_point),
6810 Bound::Included(range_to_move.end),
6811 ))
6812 .next()
6813 .is_none()
6814 {
6815 let text = buffer
6816 .text_for_range(range_to_move.clone())
6817 .flat_map(|s| s.chars())
6818 .skip(1)
6819 .chain(['\n'])
6820 .collect::<String>();
6821
6822 edits.push((
6823 buffer.anchor_after(range_to_move.start)
6824 ..buffer.anchor_before(range_to_move.end),
6825 String::new(),
6826 ));
6827 let insertion_anchor = buffer.anchor_after(insertion_point);
6828 edits.push((insertion_anchor..insertion_anchor, text));
6829
6830 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6831
6832 // Move selections up
6833 new_selections.extend(contiguous_row_selections.drain(..).map(
6834 |mut selection| {
6835 selection.start.row -= row_delta;
6836 selection.end.row -= row_delta;
6837 selection
6838 },
6839 ));
6840
6841 // Move folds up
6842 unfold_ranges.push(range_to_move.clone());
6843 for fold in display_map.folds_in_range(
6844 buffer.anchor_before(range_to_move.start)
6845 ..buffer.anchor_after(range_to_move.end),
6846 ) {
6847 let mut start = fold.range.start.to_point(&buffer);
6848 let mut end = fold.range.end.to_point(&buffer);
6849 start.row -= row_delta;
6850 end.row -= row_delta;
6851 refold_ranges.push((start..end, fold.placeholder.clone()));
6852 }
6853 }
6854 }
6855
6856 // If we didn't move line(s), preserve the existing selections
6857 new_selections.append(&mut contiguous_row_selections);
6858 }
6859
6860 self.transact(cx, |this, cx| {
6861 this.unfold_ranges(&unfold_ranges, true, true, cx);
6862 this.buffer.update(cx, |buffer, cx| {
6863 for (range, text) in edits {
6864 buffer.edit([(range, text)], None, cx);
6865 }
6866 });
6867 this.fold_ranges(refold_ranges, true, cx);
6868 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6869 s.select(new_selections);
6870 })
6871 });
6872 }
6873
6874 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6875 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6876 let buffer = self.buffer.read(cx).snapshot(cx);
6877
6878 let mut edits = Vec::new();
6879 let mut unfold_ranges = Vec::new();
6880 let mut refold_ranges = Vec::new();
6881
6882 let selections = self.selections.all::<Point>(cx);
6883 let mut selections = selections.iter().peekable();
6884 let mut contiguous_row_selections = Vec::new();
6885 let mut new_selections = Vec::new();
6886
6887 while let Some(selection) = selections.next() {
6888 // Find all the selections that span a contiguous row range
6889 let (start_row, end_row) = consume_contiguous_rows(
6890 &mut contiguous_row_selections,
6891 selection,
6892 &display_map,
6893 &mut selections,
6894 );
6895
6896 // Move the text spanned by the row range to be after the last line of the row range
6897 if end_row.0 <= buffer.max_point().row {
6898 let range_to_move =
6899 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6900 let insertion_point = display_map
6901 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6902 .0;
6903
6904 // Don't move lines across excerpt boundaries
6905 if buffer
6906 .excerpt_boundaries_in_range((
6907 Bound::Excluded(range_to_move.start),
6908 Bound::Included(insertion_point),
6909 ))
6910 .next()
6911 .is_none()
6912 {
6913 let mut text = String::from("\n");
6914 text.extend(buffer.text_for_range(range_to_move.clone()));
6915 text.pop(); // Drop trailing newline
6916 edits.push((
6917 buffer.anchor_after(range_to_move.start)
6918 ..buffer.anchor_before(range_to_move.end),
6919 String::new(),
6920 ));
6921 let insertion_anchor = buffer.anchor_after(insertion_point);
6922 edits.push((insertion_anchor..insertion_anchor, text));
6923
6924 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6925
6926 // Move selections down
6927 new_selections.extend(contiguous_row_selections.drain(..).map(
6928 |mut selection| {
6929 selection.start.row += row_delta;
6930 selection.end.row += row_delta;
6931 selection
6932 },
6933 ));
6934
6935 // Move folds down
6936 unfold_ranges.push(range_to_move.clone());
6937 for fold in display_map.folds_in_range(
6938 buffer.anchor_before(range_to_move.start)
6939 ..buffer.anchor_after(range_to_move.end),
6940 ) {
6941 let mut start = fold.range.start.to_point(&buffer);
6942 let mut end = fold.range.end.to_point(&buffer);
6943 start.row += row_delta;
6944 end.row += row_delta;
6945 refold_ranges.push((start..end, fold.placeholder.clone()));
6946 }
6947 }
6948 }
6949
6950 // If we didn't move line(s), preserve the existing selections
6951 new_selections.append(&mut contiguous_row_selections);
6952 }
6953
6954 self.transact(cx, |this, cx| {
6955 this.unfold_ranges(&unfold_ranges, true, true, cx);
6956 this.buffer.update(cx, |buffer, cx| {
6957 for (range, text) in edits {
6958 buffer.edit([(range, text)], None, cx);
6959 }
6960 });
6961 this.fold_ranges(refold_ranges, true, cx);
6962 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6963 });
6964 }
6965
6966 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6967 let text_layout_details = &self.text_layout_details(cx);
6968 self.transact(cx, |this, cx| {
6969 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6970 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6971 let line_mode = s.line_mode;
6972 s.move_with(|display_map, selection| {
6973 if !selection.is_empty() || line_mode {
6974 return;
6975 }
6976
6977 let mut head = selection.head();
6978 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6979 if head.column() == display_map.line_len(head.row()) {
6980 transpose_offset = display_map
6981 .buffer_snapshot
6982 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6983 }
6984
6985 if transpose_offset == 0 {
6986 return;
6987 }
6988
6989 *head.column_mut() += 1;
6990 head = display_map.clip_point(head, Bias::Right);
6991 let goal = SelectionGoal::HorizontalPosition(
6992 display_map
6993 .x_for_display_point(head, text_layout_details)
6994 .into(),
6995 );
6996 selection.collapse_to(head, goal);
6997
6998 let transpose_start = display_map
6999 .buffer_snapshot
7000 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7001 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7002 let transpose_end = display_map
7003 .buffer_snapshot
7004 .clip_offset(transpose_offset + 1, Bias::Right);
7005 if let Some(ch) =
7006 display_map.buffer_snapshot.chars_at(transpose_start).next()
7007 {
7008 edits.push((transpose_start..transpose_offset, String::new()));
7009 edits.push((transpose_end..transpose_end, ch.to_string()));
7010 }
7011 }
7012 });
7013 edits
7014 });
7015 this.buffer
7016 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7017 let selections = this.selections.all::<usize>(cx);
7018 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7019 s.select(selections);
7020 });
7021 });
7022 }
7023
7024 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7025 self.rewrap_impl(true, cx)
7026 }
7027
7028 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
7029 let buffer = self.buffer.read(cx).snapshot(cx);
7030 let selections = self.selections.all::<Point>(cx);
7031 let mut selections = selections.iter().peekable();
7032
7033 let mut edits = Vec::new();
7034 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7035
7036 while let Some(selection) = selections.next() {
7037 let mut start_row = selection.start.row;
7038 let mut end_row = selection.end.row;
7039
7040 // Skip selections that overlap with a range that has already been rewrapped.
7041 let selection_range = start_row..end_row;
7042 if rewrapped_row_ranges
7043 .iter()
7044 .any(|range| range.overlaps(&selection_range))
7045 {
7046 continue;
7047 }
7048
7049 let mut should_rewrap = !only_text;
7050
7051 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7052 match language_scope.language_name().0.as_ref() {
7053 "Markdown" | "Plain Text" => {
7054 should_rewrap = true;
7055 }
7056 _ => {}
7057 }
7058 }
7059
7060 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7061
7062 // Since not all lines in the selection may be at the same indent
7063 // level, choose the indent size that is the most common between all
7064 // of the lines.
7065 //
7066 // If there is a tie, we use the deepest indent.
7067 let (indent_size, indent_end) = {
7068 let mut indent_size_occurrences = HashMap::default();
7069 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7070
7071 for row in start_row..=end_row {
7072 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7073 rows_by_indent_size.entry(indent).or_default().push(row);
7074 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7075 }
7076
7077 let indent_size = indent_size_occurrences
7078 .into_iter()
7079 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7080 .map(|(indent, _)| indent)
7081 .unwrap_or_default();
7082 let row = rows_by_indent_size[&indent_size][0];
7083 let indent_end = Point::new(row, indent_size.len);
7084
7085 (indent_size, indent_end)
7086 };
7087
7088 let mut line_prefix = indent_size.chars().collect::<String>();
7089
7090 if let Some(comment_prefix) =
7091 buffer
7092 .language_scope_at(selection.head())
7093 .and_then(|language| {
7094 language
7095 .line_comment_prefixes()
7096 .iter()
7097 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7098 .cloned()
7099 })
7100 {
7101 line_prefix.push_str(&comment_prefix);
7102 should_rewrap = true;
7103 }
7104
7105 if !should_rewrap {
7106 continue;
7107 }
7108
7109 if selection.is_empty() {
7110 'expand_upwards: while start_row > 0 {
7111 let prev_row = start_row - 1;
7112 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7113 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7114 {
7115 start_row = prev_row;
7116 } else {
7117 break 'expand_upwards;
7118 }
7119 }
7120
7121 'expand_downwards: while end_row < buffer.max_point().row {
7122 let next_row = end_row + 1;
7123 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7124 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7125 {
7126 end_row = next_row;
7127 } else {
7128 break 'expand_downwards;
7129 }
7130 }
7131 }
7132
7133 let start = Point::new(start_row, 0);
7134 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7135 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7136 let Some(lines_without_prefixes) = selection_text
7137 .lines()
7138 .map(|line| {
7139 line.strip_prefix(&line_prefix)
7140 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7141 .ok_or_else(|| {
7142 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7143 })
7144 })
7145 .collect::<Result<Vec<_>, _>>()
7146 .log_err()
7147 else {
7148 continue;
7149 };
7150
7151 let wrap_column = buffer
7152 .settings_at(Point::new(start_row, 0), cx)
7153 .preferred_line_length as usize;
7154 let wrapped_text = wrap_with_prefix(
7155 line_prefix,
7156 lines_without_prefixes.join(" "),
7157 wrap_column,
7158 tab_size,
7159 );
7160
7161 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7162 let mut offset = start.to_offset(&buffer);
7163 let mut moved_since_edit = true;
7164
7165 for change in diff.iter_all_changes() {
7166 let value = change.value();
7167 match change.tag() {
7168 ChangeTag::Equal => {
7169 offset += value.len();
7170 moved_since_edit = true;
7171 }
7172 ChangeTag::Delete => {
7173 let start = buffer.anchor_after(offset);
7174 let end = buffer.anchor_before(offset + value.len());
7175
7176 if moved_since_edit {
7177 edits.push((start..end, String::new()));
7178 } else {
7179 edits.last_mut().unwrap().0.end = end;
7180 }
7181
7182 offset += value.len();
7183 moved_since_edit = false;
7184 }
7185 ChangeTag::Insert => {
7186 if moved_since_edit {
7187 let anchor = buffer.anchor_after(offset);
7188 edits.push((anchor..anchor, value.to_string()));
7189 } else {
7190 edits.last_mut().unwrap().1.push_str(value);
7191 }
7192
7193 moved_since_edit = false;
7194 }
7195 }
7196 }
7197
7198 rewrapped_row_ranges.push(start_row..=end_row);
7199 }
7200
7201 self.buffer
7202 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7203 }
7204
7205 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7206 let mut text = String::new();
7207 let buffer = self.buffer.read(cx).snapshot(cx);
7208 let mut selections = self.selections.all::<Point>(cx);
7209 let mut clipboard_selections = Vec::with_capacity(selections.len());
7210 {
7211 let max_point = buffer.max_point();
7212 let mut is_first = true;
7213 for selection in &mut selections {
7214 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7215 if is_entire_line {
7216 selection.start = Point::new(selection.start.row, 0);
7217 if !selection.is_empty() && selection.end.column == 0 {
7218 selection.end = cmp::min(max_point, selection.end);
7219 } else {
7220 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7221 }
7222 selection.goal = SelectionGoal::None;
7223 }
7224 if is_first {
7225 is_first = false;
7226 } else {
7227 text += "\n";
7228 }
7229 let mut len = 0;
7230 for chunk in buffer.text_for_range(selection.start..selection.end) {
7231 text.push_str(chunk);
7232 len += chunk.len();
7233 }
7234 clipboard_selections.push(ClipboardSelection {
7235 len,
7236 is_entire_line,
7237 first_line_indent: buffer
7238 .indent_size_for_line(MultiBufferRow(selection.start.row))
7239 .len,
7240 });
7241 }
7242 }
7243
7244 self.transact(cx, |this, cx| {
7245 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7246 s.select(selections);
7247 });
7248 this.insert("", cx);
7249 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7250 text,
7251 clipboard_selections,
7252 ));
7253 });
7254 }
7255
7256 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7257 let selections = self.selections.all::<Point>(cx);
7258 let buffer = self.buffer.read(cx).read(cx);
7259 let mut text = String::new();
7260
7261 let mut clipboard_selections = Vec::with_capacity(selections.len());
7262 {
7263 let max_point = buffer.max_point();
7264 let mut is_first = true;
7265 for selection in selections.iter() {
7266 let mut start = selection.start;
7267 let mut end = selection.end;
7268 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7269 if is_entire_line {
7270 start = Point::new(start.row, 0);
7271 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7272 }
7273 if is_first {
7274 is_first = false;
7275 } else {
7276 text += "\n";
7277 }
7278 let mut len = 0;
7279 for chunk in buffer.text_for_range(start..end) {
7280 text.push_str(chunk);
7281 len += chunk.len();
7282 }
7283 clipboard_selections.push(ClipboardSelection {
7284 len,
7285 is_entire_line,
7286 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7287 });
7288 }
7289 }
7290
7291 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7292 text,
7293 clipboard_selections,
7294 ));
7295 }
7296
7297 pub fn do_paste(
7298 &mut self,
7299 text: &String,
7300 clipboard_selections: Option<Vec<ClipboardSelection>>,
7301 handle_entire_lines: bool,
7302 cx: &mut ViewContext<Self>,
7303 ) {
7304 if self.read_only(cx) {
7305 return;
7306 }
7307
7308 let clipboard_text = Cow::Borrowed(text);
7309
7310 self.transact(cx, |this, cx| {
7311 if let Some(mut clipboard_selections) = clipboard_selections {
7312 let old_selections = this.selections.all::<usize>(cx);
7313 let all_selections_were_entire_line =
7314 clipboard_selections.iter().all(|s| s.is_entire_line);
7315 let first_selection_indent_column =
7316 clipboard_selections.first().map(|s| s.first_line_indent);
7317 if clipboard_selections.len() != old_selections.len() {
7318 clipboard_selections.drain(..);
7319 }
7320 let cursor_offset = this.selections.last::<usize>(cx).head();
7321 let mut auto_indent_on_paste = true;
7322
7323 this.buffer.update(cx, |buffer, cx| {
7324 let snapshot = buffer.read(cx);
7325 auto_indent_on_paste =
7326 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7327
7328 let mut start_offset = 0;
7329 let mut edits = Vec::new();
7330 let mut original_indent_columns = Vec::new();
7331 for (ix, selection) in old_selections.iter().enumerate() {
7332 let to_insert;
7333 let entire_line;
7334 let original_indent_column;
7335 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7336 let end_offset = start_offset + clipboard_selection.len;
7337 to_insert = &clipboard_text[start_offset..end_offset];
7338 entire_line = clipboard_selection.is_entire_line;
7339 start_offset = end_offset + 1;
7340 original_indent_column = Some(clipboard_selection.first_line_indent);
7341 } else {
7342 to_insert = clipboard_text.as_str();
7343 entire_line = all_selections_were_entire_line;
7344 original_indent_column = first_selection_indent_column
7345 }
7346
7347 // If the corresponding selection was empty when this slice of the
7348 // clipboard text was written, then the entire line containing the
7349 // selection was copied. If this selection is also currently empty,
7350 // then paste the line before the current line of the buffer.
7351 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7352 let column = selection.start.to_point(&snapshot).column as usize;
7353 let line_start = selection.start - column;
7354 line_start..line_start
7355 } else {
7356 selection.range()
7357 };
7358
7359 edits.push((range, to_insert));
7360 original_indent_columns.extend(original_indent_column);
7361 }
7362 drop(snapshot);
7363
7364 buffer.edit(
7365 edits,
7366 if auto_indent_on_paste {
7367 Some(AutoindentMode::Block {
7368 original_indent_columns,
7369 })
7370 } else {
7371 None
7372 },
7373 cx,
7374 );
7375 });
7376
7377 let selections = this.selections.all::<usize>(cx);
7378 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7379 } else {
7380 this.insert(&clipboard_text, cx);
7381 }
7382 });
7383 }
7384
7385 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7386 if let Some(item) = cx.read_from_clipboard() {
7387 let entries = item.entries();
7388
7389 match entries.first() {
7390 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7391 // of all the pasted entries.
7392 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7393 .do_paste(
7394 clipboard_string.text(),
7395 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7396 true,
7397 cx,
7398 ),
7399 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7400 }
7401 }
7402 }
7403
7404 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7405 if self.read_only(cx) {
7406 return;
7407 }
7408
7409 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7410 if let Some((selections, _)) =
7411 self.selection_history.transaction(transaction_id).cloned()
7412 {
7413 self.change_selections(None, cx, |s| {
7414 s.select_anchors(selections.to_vec());
7415 });
7416 }
7417 self.request_autoscroll(Autoscroll::fit(), cx);
7418 self.unmark_text(cx);
7419 self.refresh_inline_completion(true, false, cx);
7420 cx.emit(EditorEvent::Edited { transaction_id });
7421 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7422 }
7423 }
7424
7425 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7426 if self.read_only(cx) {
7427 return;
7428 }
7429
7430 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7431 if let Some((_, Some(selections))) =
7432 self.selection_history.transaction(transaction_id).cloned()
7433 {
7434 self.change_selections(None, cx, |s| {
7435 s.select_anchors(selections.to_vec());
7436 });
7437 }
7438 self.request_autoscroll(Autoscroll::fit(), cx);
7439 self.unmark_text(cx);
7440 self.refresh_inline_completion(true, false, cx);
7441 cx.emit(EditorEvent::Edited { transaction_id });
7442 }
7443 }
7444
7445 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7446 self.buffer
7447 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7448 }
7449
7450 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7451 self.buffer
7452 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7453 }
7454
7455 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7456 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7457 let line_mode = s.line_mode;
7458 s.move_with(|map, selection| {
7459 let cursor = if selection.is_empty() && !line_mode {
7460 movement::left(map, selection.start)
7461 } else {
7462 selection.start
7463 };
7464 selection.collapse_to(cursor, SelectionGoal::None);
7465 });
7466 })
7467 }
7468
7469 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7471 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7472 })
7473 }
7474
7475 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7476 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7477 let line_mode = s.line_mode;
7478 s.move_with(|map, selection| {
7479 let cursor = if selection.is_empty() && !line_mode {
7480 movement::right(map, selection.end)
7481 } else {
7482 selection.end
7483 };
7484 selection.collapse_to(cursor, SelectionGoal::None)
7485 });
7486 })
7487 }
7488
7489 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7490 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7491 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7492 })
7493 }
7494
7495 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7496 if self.take_rename(true, cx).is_some() {
7497 return;
7498 }
7499
7500 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7501 cx.propagate();
7502 return;
7503 }
7504
7505 let text_layout_details = &self.text_layout_details(cx);
7506 let selection_count = self.selections.count();
7507 let first_selection = self.selections.first_anchor();
7508
7509 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7510 let line_mode = s.line_mode;
7511 s.move_with(|map, selection| {
7512 if !selection.is_empty() && !line_mode {
7513 selection.goal = SelectionGoal::None;
7514 }
7515 let (cursor, goal) = movement::up(
7516 map,
7517 selection.start,
7518 selection.goal,
7519 false,
7520 text_layout_details,
7521 );
7522 selection.collapse_to(cursor, goal);
7523 });
7524 });
7525
7526 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7527 {
7528 cx.propagate();
7529 }
7530 }
7531
7532 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7533 if self.take_rename(true, cx).is_some() {
7534 return;
7535 }
7536
7537 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7538 cx.propagate();
7539 return;
7540 }
7541
7542 let text_layout_details = &self.text_layout_details(cx);
7543
7544 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7545 let line_mode = s.line_mode;
7546 s.move_with(|map, selection| {
7547 if !selection.is_empty() && !line_mode {
7548 selection.goal = SelectionGoal::None;
7549 }
7550 let (cursor, goal) = movement::up_by_rows(
7551 map,
7552 selection.start,
7553 action.lines,
7554 selection.goal,
7555 false,
7556 text_layout_details,
7557 );
7558 selection.collapse_to(cursor, goal);
7559 });
7560 })
7561 }
7562
7563 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7564 if self.take_rename(true, cx).is_some() {
7565 return;
7566 }
7567
7568 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7569 cx.propagate();
7570 return;
7571 }
7572
7573 let text_layout_details = &self.text_layout_details(cx);
7574
7575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7576 let line_mode = s.line_mode;
7577 s.move_with(|map, selection| {
7578 if !selection.is_empty() && !line_mode {
7579 selection.goal = SelectionGoal::None;
7580 }
7581 let (cursor, goal) = movement::down_by_rows(
7582 map,
7583 selection.start,
7584 action.lines,
7585 selection.goal,
7586 false,
7587 text_layout_details,
7588 );
7589 selection.collapse_to(cursor, goal);
7590 });
7591 })
7592 }
7593
7594 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7595 let text_layout_details = &self.text_layout_details(cx);
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.move_heads_with(|map, head, goal| {
7598 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7599 })
7600 })
7601 }
7602
7603 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7604 let text_layout_details = &self.text_layout_details(cx);
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 s.move_heads_with(|map, head, goal| {
7607 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7608 })
7609 })
7610 }
7611
7612 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7613 let Some(row_count) = self.visible_row_count() else {
7614 return;
7615 };
7616
7617 let text_layout_details = &self.text_layout_details(cx);
7618
7619 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7620 s.move_heads_with(|map, head, goal| {
7621 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7622 })
7623 })
7624 }
7625
7626 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7627 if self.take_rename(true, cx).is_some() {
7628 return;
7629 }
7630
7631 if self
7632 .context_menu
7633 .write()
7634 .as_mut()
7635 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7636 .unwrap_or(false)
7637 {
7638 return;
7639 }
7640
7641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7642 cx.propagate();
7643 return;
7644 }
7645
7646 let Some(row_count) = self.visible_row_count() else {
7647 return;
7648 };
7649
7650 let autoscroll = if action.center_cursor {
7651 Autoscroll::center()
7652 } else {
7653 Autoscroll::fit()
7654 };
7655
7656 let text_layout_details = &self.text_layout_details(cx);
7657
7658 self.change_selections(Some(autoscroll), cx, |s| {
7659 let line_mode = s.line_mode;
7660 s.move_with(|map, selection| {
7661 if !selection.is_empty() && !line_mode {
7662 selection.goal = SelectionGoal::None;
7663 }
7664 let (cursor, goal) = movement::up_by_rows(
7665 map,
7666 selection.end,
7667 row_count,
7668 selection.goal,
7669 false,
7670 text_layout_details,
7671 );
7672 selection.collapse_to(cursor, goal);
7673 });
7674 });
7675 }
7676
7677 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7678 let text_layout_details = &self.text_layout_details(cx);
7679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7680 s.move_heads_with(|map, head, goal| {
7681 movement::up(map, head, goal, false, text_layout_details)
7682 })
7683 })
7684 }
7685
7686 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7687 self.take_rename(true, cx);
7688
7689 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7690 cx.propagate();
7691 return;
7692 }
7693
7694 let text_layout_details = &self.text_layout_details(cx);
7695 let selection_count = self.selections.count();
7696 let first_selection = self.selections.first_anchor();
7697
7698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7699 let line_mode = s.line_mode;
7700 s.move_with(|map, selection| {
7701 if !selection.is_empty() && !line_mode {
7702 selection.goal = SelectionGoal::None;
7703 }
7704 let (cursor, goal) = movement::down(
7705 map,
7706 selection.end,
7707 selection.goal,
7708 false,
7709 text_layout_details,
7710 );
7711 selection.collapse_to(cursor, goal);
7712 });
7713 });
7714
7715 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7716 {
7717 cx.propagate();
7718 }
7719 }
7720
7721 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7722 let Some(row_count) = self.visible_row_count() else {
7723 return;
7724 };
7725
7726 let text_layout_details = &self.text_layout_details(cx);
7727
7728 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7729 s.move_heads_with(|map, head, goal| {
7730 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7731 })
7732 })
7733 }
7734
7735 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7736 if self.take_rename(true, cx).is_some() {
7737 return;
7738 }
7739
7740 if self
7741 .context_menu
7742 .write()
7743 .as_mut()
7744 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7745 .unwrap_or(false)
7746 {
7747 return;
7748 }
7749
7750 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7751 cx.propagate();
7752 return;
7753 }
7754
7755 let Some(row_count) = self.visible_row_count() else {
7756 return;
7757 };
7758
7759 let autoscroll = if action.center_cursor {
7760 Autoscroll::center()
7761 } else {
7762 Autoscroll::fit()
7763 };
7764
7765 let text_layout_details = &self.text_layout_details(cx);
7766 self.change_selections(Some(autoscroll), cx, |s| {
7767 let line_mode = s.line_mode;
7768 s.move_with(|map, selection| {
7769 if !selection.is_empty() && !line_mode {
7770 selection.goal = SelectionGoal::None;
7771 }
7772 let (cursor, goal) = movement::down_by_rows(
7773 map,
7774 selection.end,
7775 row_count,
7776 selection.goal,
7777 false,
7778 text_layout_details,
7779 );
7780 selection.collapse_to(cursor, goal);
7781 });
7782 });
7783 }
7784
7785 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7786 let text_layout_details = &self.text_layout_details(cx);
7787 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7788 s.move_heads_with(|map, head, goal| {
7789 movement::down(map, head, goal, false, text_layout_details)
7790 })
7791 });
7792 }
7793
7794 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7795 if let Some(context_menu) = self.context_menu.write().as_mut() {
7796 context_menu.select_first(self.completion_provider.as_deref(), cx);
7797 }
7798 }
7799
7800 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7801 if let Some(context_menu) = self.context_menu.write().as_mut() {
7802 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7803 }
7804 }
7805
7806 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7807 if let Some(context_menu) = self.context_menu.write().as_mut() {
7808 context_menu.select_next(self.completion_provider.as_deref(), cx);
7809 }
7810 }
7811
7812 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7813 if let Some(context_menu) = self.context_menu.write().as_mut() {
7814 context_menu.select_last(self.completion_provider.as_deref(), cx);
7815 }
7816 }
7817
7818 pub fn move_to_previous_word_start(
7819 &mut self,
7820 _: &MoveToPreviousWordStart,
7821 cx: &mut ViewContext<Self>,
7822 ) {
7823 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7824 s.move_cursors_with(|map, head, _| {
7825 (
7826 movement::previous_word_start(map, head),
7827 SelectionGoal::None,
7828 )
7829 });
7830 })
7831 }
7832
7833 pub fn move_to_previous_subword_start(
7834 &mut self,
7835 _: &MoveToPreviousSubwordStart,
7836 cx: &mut ViewContext<Self>,
7837 ) {
7838 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7839 s.move_cursors_with(|map, head, _| {
7840 (
7841 movement::previous_subword_start(map, head),
7842 SelectionGoal::None,
7843 )
7844 });
7845 })
7846 }
7847
7848 pub fn select_to_previous_word_start(
7849 &mut self,
7850 _: &SelectToPreviousWordStart,
7851 cx: &mut ViewContext<Self>,
7852 ) {
7853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7854 s.move_heads_with(|map, head, _| {
7855 (
7856 movement::previous_word_start(map, head),
7857 SelectionGoal::None,
7858 )
7859 });
7860 })
7861 }
7862
7863 pub fn select_to_previous_subword_start(
7864 &mut self,
7865 _: &SelectToPreviousSubwordStart,
7866 cx: &mut ViewContext<Self>,
7867 ) {
7868 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7869 s.move_heads_with(|map, head, _| {
7870 (
7871 movement::previous_subword_start(map, head),
7872 SelectionGoal::None,
7873 )
7874 });
7875 })
7876 }
7877
7878 pub fn delete_to_previous_word_start(
7879 &mut self,
7880 action: &DeleteToPreviousWordStart,
7881 cx: &mut ViewContext<Self>,
7882 ) {
7883 self.transact(cx, |this, cx| {
7884 this.select_autoclose_pair(cx);
7885 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7886 let line_mode = s.line_mode;
7887 s.move_with(|map, selection| {
7888 if selection.is_empty() && !line_mode {
7889 let cursor = if action.ignore_newlines {
7890 movement::previous_word_start(map, selection.head())
7891 } else {
7892 movement::previous_word_start_or_newline(map, selection.head())
7893 };
7894 selection.set_head(cursor, SelectionGoal::None);
7895 }
7896 });
7897 });
7898 this.insert("", cx);
7899 });
7900 }
7901
7902 pub fn delete_to_previous_subword_start(
7903 &mut self,
7904 _: &DeleteToPreviousSubwordStart,
7905 cx: &mut ViewContext<Self>,
7906 ) {
7907 self.transact(cx, |this, cx| {
7908 this.select_autoclose_pair(cx);
7909 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7910 let line_mode = s.line_mode;
7911 s.move_with(|map, selection| {
7912 if selection.is_empty() && !line_mode {
7913 let cursor = movement::previous_subword_start(map, selection.head());
7914 selection.set_head(cursor, SelectionGoal::None);
7915 }
7916 });
7917 });
7918 this.insert("", cx);
7919 });
7920 }
7921
7922 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7924 s.move_cursors_with(|map, head, _| {
7925 (movement::next_word_end(map, head), SelectionGoal::None)
7926 });
7927 })
7928 }
7929
7930 pub fn move_to_next_subword_end(
7931 &mut self,
7932 _: &MoveToNextSubwordEnd,
7933 cx: &mut ViewContext<Self>,
7934 ) {
7935 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7936 s.move_cursors_with(|map, head, _| {
7937 (movement::next_subword_end(map, head), SelectionGoal::None)
7938 });
7939 })
7940 }
7941
7942 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 s.move_heads_with(|map, head, _| {
7945 (movement::next_word_end(map, head), SelectionGoal::None)
7946 });
7947 })
7948 }
7949
7950 pub fn select_to_next_subword_end(
7951 &mut self,
7952 _: &SelectToNextSubwordEnd,
7953 cx: &mut ViewContext<Self>,
7954 ) {
7955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7956 s.move_heads_with(|map, head, _| {
7957 (movement::next_subword_end(map, head), SelectionGoal::None)
7958 });
7959 })
7960 }
7961
7962 pub fn delete_to_next_word_end(
7963 &mut self,
7964 action: &DeleteToNextWordEnd,
7965 cx: &mut ViewContext<Self>,
7966 ) {
7967 self.transact(cx, |this, cx| {
7968 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7969 let line_mode = s.line_mode;
7970 s.move_with(|map, selection| {
7971 if selection.is_empty() && !line_mode {
7972 let cursor = if action.ignore_newlines {
7973 movement::next_word_end(map, selection.head())
7974 } else {
7975 movement::next_word_end_or_newline(map, selection.head())
7976 };
7977 selection.set_head(cursor, SelectionGoal::None);
7978 }
7979 });
7980 });
7981 this.insert("", cx);
7982 });
7983 }
7984
7985 pub fn delete_to_next_subword_end(
7986 &mut self,
7987 _: &DeleteToNextSubwordEnd,
7988 cx: &mut ViewContext<Self>,
7989 ) {
7990 self.transact(cx, |this, cx| {
7991 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7992 s.move_with(|map, selection| {
7993 if selection.is_empty() {
7994 let cursor = movement::next_subword_end(map, selection.head());
7995 selection.set_head(cursor, SelectionGoal::None);
7996 }
7997 });
7998 });
7999 this.insert("", cx);
8000 });
8001 }
8002
8003 pub fn move_to_beginning_of_line(
8004 &mut self,
8005 action: &MoveToBeginningOfLine,
8006 cx: &mut ViewContext<Self>,
8007 ) {
8008 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8009 s.move_cursors_with(|map, head, _| {
8010 (
8011 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8012 SelectionGoal::None,
8013 )
8014 });
8015 })
8016 }
8017
8018 pub fn select_to_beginning_of_line(
8019 &mut self,
8020 action: &SelectToBeginningOfLine,
8021 cx: &mut ViewContext<Self>,
8022 ) {
8023 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8024 s.move_heads_with(|map, head, _| {
8025 (
8026 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8027 SelectionGoal::None,
8028 )
8029 });
8030 });
8031 }
8032
8033 pub fn delete_to_beginning_of_line(
8034 &mut self,
8035 _: &DeleteToBeginningOfLine,
8036 cx: &mut ViewContext<Self>,
8037 ) {
8038 self.transact(cx, |this, cx| {
8039 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8040 s.move_with(|_, selection| {
8041 selection.reversed = true;
8042 });
8043 });
8044
8045 this.select_to_beginning_of_line(
8046 &SelectToBeginningOfLine {
8047 stop_at_soft_wraps: false,
8048 },
8049 cx,
8050 );
8051 this.backspace(&Backspace, cx);
8052 });
8053 }
8054
8055 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8056 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8057 s.move_cursors_with(|map, head, _| {
8058 (
8059 movement::line_end(map, head, action.stop_at_soft_wraps),
8060 SelectionGoal::None,
8061 )
8062 });
8063 })
8064 }
8065
8066 pub fn select_to_end_of_line(
8067 &mut self,
8068 action: &SelectToEndOfLine,
8069 cx: &mut ViewContext<Self>,
8070 ) {
8071 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8072 s.move_heads_with(|map, head, _| {
8073 (
8074 movement::line_end(map, head, action.stop_at_soft_wraps),
8075 SelectionGoal::None,
8076 )
8077 });
8078 })
8079 }
8080
8081 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8082 self.transact(cx, |this, cx| {
8083 this.select_to_end_of_line(
8084 &SelectToEndOfLine {
8085 stop_at_soft_wraps: false,
8086 },
8087 cx,
8088 );
8089 this.delete(&Delete, cx);
8090 });
8091 }
8092
8093 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8094 self.transact(cx, |this, cx| {
8095 this.select_to_end_of_line(
8096 &SelectToEndOfLine {
8097 stop_at_soft_wraps: false,
8098 },
8099 cx,
8100 );
8101 this.cut(&Cut, cx);
8102 });
8103 }
8104
8105 pub fn move_to_start_of_paragraph(
8106 &mut self,
8107 _: &MoveToStartOfParagraph,
8108 cx: &mut ViewContext<Self>,
8109 ) {
8110 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8111 cx.propagate();
8112 return;
8113 }
8114
8115 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8116 s.move_with(|map, selection| {
8117 selection.collapse_to(
8118 movement::start_of_paragraph(map, selection.head(), 1),
8119 SelectionGoal::None,
8120 )
8121 });
8122 })
8123 }
8124
8125 pub fn move_to_end_of_paragraph(
8126 &mut self,
8127 _: &MoveToEndOfParagraph,
8128 cx: &mut ViewContext<Self>,
8129 ) {
8130 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8131 cx.propagate();
8132 return;
8133 }
8134
8135 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8136 s.move_with(|map, selection| {
8137 selection.collapse_to(
8138 movement::end_of_paragraph(map, selection.head(), 1),
8139 SelectionGoal::None,
8140 )
8141 });
8142 })
8143 }
8144
8145 pub fn select_to_start_of_paragraph(
8146 &mut self,
8147 _: &SelectToStartOfParagraph,
8148 cx: &mut ViewContext<Self>,
8149 ) {
8150 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8151 cx.propagate();
8152 return;
8153 }
8154
8155 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8156 s.move_heads_with(|map, head, _| {
8157 (
8158 movement::start_of_paragraph(map, head, 1),
8159 SelectionGoal::None,
8160 )
8161 });
8162 })
8163 }
8164
8165 pub fn select_to_end_of_paragraph(
8166 &mut self,
8167 _: &SelectToEndOfParagraph,
8168 cx: &mut ViewContext<Self>,
8169 ) {
8170 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8171 cx.propagate();
8172 return;
8173 }
8174
8175 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8176 s.move_heads_with(|map, head, _| {
8177 (
8178 movement::end_of_paragraph(map, head, 1),
8179 SelectionGoal::None,
8180 )
8181 });
8182 })
8183 }
8184
8185 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8186 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8187 cx.propagate();
8188 return;
8189 }
8190
8191 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8192 s.select_ranges(vec![0..0]);
8193 });
8194 }
8195
8196 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8197 let mut selection = self.selections.last::<Point>(cx);
8198 selection.set_head(Point::zero(), SelectionGoal::None);
8199
8200 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8201 s.select(vec![selection]);
8202 });
8203 }
8204
8205 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8206 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8207 cx.propagate();
8208 return;
8209 }
8210
8211 let cursor = self.buffer.read(cx).read(cx).len();
8212 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8213 s.select_ranges(vec![cursor..cursor])
8214 });
8215 }
8216
8217 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8218 self.nav_history = nav_history;
8219 }
8220
8221 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8222 self.nav_history.as_ref()
8223 }
8224
8225 fn push_to_nav_history(
8226 &mut self,
8227 cursor_anchor: Anchor,
8228 new_position: Option<Point>,
8229 cx: &mut ViewContext<Self>,
8230 ) {
8231 if let Some(nav_history) = self.nav_history.as_mut() {
8232 let buffer = self.buffer.read(cx).read(cx);
8233 let cursor_position = cursor_anchor.to_point(&buffer);
8234 let scroll_state = self.scroll_manager.anchor();
8235 let scroll_top_row = scroll_state.top_row(&buffer);
8236 drop(buffer);
8237
8238 if let Some(new_position) = new_position {
8239 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8240 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8241 return;
8242 }
8243 }
8244
8245 nav_history.push(
8246 Some(NavigationData {
8247 cursor_anchor,
8248 cursor_position,
8249 scroll_anchor: scroll_state,
8250 scroll_top_row,
8251 }),
8252 cx,
8253 );
8254 }
8255 }
8256
8257 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8258 let buffer = self.buffer.read(cx).snapshot(cx);
8259 let mut selection = self.selections.first::<usize>(cx);
8260 selection.set_head(buffer.len(), SelectionGoal::None);
8261 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8262 s.select(vec![selection]);
8263 });
8264 }
8265
8266 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8267 let end = self.buffer.read(cx).read(cx).len();
8268 self.change_selections(None, cx, |s| {
8269 s.select_ranges(vec![0..end]);
8270 });
8271 }
8272
8273 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8275 let mut selections = self.selections.all::<Point>(cx);
8276 let max_point = display_map.buffer_snapshot.max_point();
8277 for selection in &mut selections {
8278 let rows = selection.spanned_rows(true, &display_map);
8279 selection.start = Point::new(rows.start.0, 0);
8280 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8281 selection.reversed = false;
8282 }
8283 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8284 s.select(selections);
8285 });
8286 }
8287
8288 pub fn split_selection_into_lines(
8289 &mut self,
8290 _: &SplitSelectionIntoLines,
8291 cx: &mut ViewContext<Self>,
8292 ) {
8293 let mut to_unfold = Vec::new();
8294 let mut new_selection_ranges = Vec::new();
8295 {
8296 let selections = self.selections.all::<Point>(cx);
8297 let buffer = self.buffer.read(cx).read(cx);
8298 for selection in selections {
8299 for row in selection.start.row..selection.end.row {
8300 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8301 new_selection_ranges.push(cursor..cursor);
8302 }
8303 new_selection_ranges.push(selection.end..selection.end);
8304 to_unfold.push(selection.start..selection.end);
8305 }
8306 }
8307 self.unfold_ranges(&to_unfold, true, true, cx);
8308 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8309 s.select_ranges(new_selection_ranges);
8310 });
8311 }
8312
8313 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8314 self.add_selection(true, cx);
8315 }
8316
8317 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8318 self.add_selection(false, cx);
8319 }
8320
8321 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8322 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8323 let mut selections = self.selections.all::<Point>(cx);
8324 let text_layout_details = self.text_layout_details(cx);
8325 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8326 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8327 let range = oldest_selection.display_range(&display_map).sorted();
8328
8329 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8330 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8331 let positions = start_x.min(end_x)..start_x.max(end_x);
8332
8333 selections.clear();
8334 let mut stack = Vec::new();
8335 for row in range.start.row().0..=range.end.row().0 {
8336 if let Some(selection) = self.selections.build_columnar_selection(
8337 &display_map,
8338 DisplayRow(row),
8339 &positions,
8340 oldest_selection.reversed,
8341 &text_layout_details,
8342 ) {
8343 stack.push(selection.id);
8344 selections.push(selection);
8345 }
8346 }
8347
8348 if above {
8349 stack.reverse();
8350 }
8351
8352 AddSelectionsState { above, stack }
8353 });
8354
8355 let last_added_selection = *state.stack.last().unwrap();
8356 let mut new_selections = Vec::new();
8357 if above == state.above {
8358 let end_row = if above {
8359 DisplayRow(0)
8360 } else {
8361 display_map.max_point().row()
8362 };
8363
8364 'outer: for selection in selections {
8365 if selection.id == last_added_selection {
8366 let range = selection.display_range(&display_map).sorted();
8367 debug_assert_eq!(range.start.row(), range.end.row());
8368 let mut row = range.start.row();
8369 let positions =
8370 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8371 px(start)..px(end)
8372 } else {
8373 let start_x =
8374 display_map.x_for_display_point(range.start, &text_layout_details);
8375 let end_x =
8376 display_map.x_for_display_point(range.end, &text_layout_details);
8377 start_x.min(end_x)..start_x.max(end_x)
8378 };
8379
8380 while row != end_row {
8381 if above {
8382 row.0 -= 1;
8383 } else {
8384 row.0 += 1;
8385 }
8386
8387 if let Some(new_selection) = self.selections.build_columnar_selection(
8388 &display_map,
8389 row,
8390 &positions,
8391 selection.reversed,
8392 &text_layout_details,
8393 ) {
8394 state.stack.push(new_selection.id);
8395 if above {
8396 new_selections.push(new_selection);
8397 new_selections.push(selection);
8398 } else {
8399 new_selections.push(selection);
8400 new_selections.push(new_selection);
8401 }
8402
8403 continue 'outer;
8404 }
8405 }
8406 }
8407
8408 new_selections.push(selection);
8409 }
8410 } else {
8411 new_selections = selections;
8412 new_selections.retain(|s| s.id != last_added_selection);
8413 state.stack.pop();
8414 }
8415
8416 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8417 s.select(new_selections);
8418 });
8419 if state.stack.len() > 1 {
8420 self.add_selections_state = Some(state);
8421 }
8422 }
8423
8424 pub fn select_next_match_internal(
8425 &mut self,
8426 display_map: &DisplaySnapshot,
8427 replace_newest: bool,
8428 autoscroll: Option<Autoscroll>,
8429 cx: &mut ViewContext<Self>,
8430 ) -> Result<()> {
8431 fn select_next_match_ranges(
8432 this: &mut Editor,
8433 range: Range<usize>,
8434 replace_newest: bool,
8435 auto_scroll: Option<Autoscroll>,
8436 cx: &mut ViewContext<Editor>,
8437 ) {
8438 this.unfold_ranges(&[range.clone()], false, true, cx);
8439 this.change_selections(auto_scroll, cx, |s| {
8440 if replace_newest {
8441 s.delete(s.newest_anchor().id);
8442 }
8443 s.insert_range(range.clone());
8444 });
8445 }
8446
8447 let buffer = &display_map.buffer_snapshot;
8448 let mut selections = self.selections.all::<usize>(cx);
8449 if let Some(mut select_next_state) = self.select_next_state.take() {
8450 let query = &select_next_state.query;
8451 if !select_next_state.done {
8452 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8453 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8454 let mut next_selected_range = None;
8455
8456 let bytes_after_last_selection =
8457 buffer.bytes_in_range(last_selection.end..buffer.len());
8458 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8459 let query_matches = query
8460 .stream_find_iter(bytes_after_last_selection)
8461 .map(|result| (last_selection.end, result))
8462 .chain(
8463 query
8464 .stream_find_iter(bytes_before_first_selection)
8465 .map(|result| (0, result)),
8466 );
8467
8468 for (start_offset, query_match) in query_matches {
8469 let query_match = query_match.unwrap(); // can only fail due to I/O
8470 let offset_range =
8471 start_offset + query_match.start()..start_offset + query_match.end();
8472 let display_range = offset_range.start.to_display_point(display_map)
8473 ..offset_range.end.to_display_point(display_map);
8474
8475 if !select_next_state.wordwise
8476 || (!movement::is_inside_word(display_map, display_range.start)
8477 && !movement::is_inside_word(display_map, display_range.end))
8478 {
8479 // TODO: This is n^2, because we might check all the selections
8480 if !selections
8481 .iter()
8482 .any(|selection| selection.range().overlaps(&offset_range))
8483 {
8484 next_selected_range = Some(offset_range);
8485 break;
8486 }
8487 }
8488 }
8489
8490 if let Some(next_selected_range) = next_selected_range {
8491 select_next_match_ranges(
8492 self,
8493 next_selected_range,
8494 replace_newest,
8495 autoscroll,
8496 cx,
8497 );
8498 } else {
8499 select_next_state.done = true;
8500 }
8501 }
8502
8503 self.select_next_state = Some(select_next_state);
8504 } else {
8505 let mut only_carets = true;
8506 let mut same_text_selected = true;
8507 let mut selected_text = None;
8508
8509 let mut selections_iter = selections.iter().peekable();
8510 while let Some(selection) = selections_iter.next() {
8511 if selection.start != selection.end {
8512 only_carets = false;
8513 }
8514
8515 if same_text_selected {
8516 if selected_text.is_none() {
8517 selected_text =
8518 Some(buffer.text_for_range(selection.range()).collect::<String>());
8519 }
8520
8521 if let Some(next_selection) = selections_iter.peek() {
8522 if next_selection.range().len() == selection.range().len() {
8523 let next_selected_text = buffer
8524 .text_for_range(next_selection.range())
8525 .collect::<String>();
8526 if Some(next_selected_text) != selected_text {
8527 same_text_selected = false;
8528 selected_text = None;
8529 }
8530 } else {
8531 same_text_selected = false;
8532 selected_text = None;
8533 }
8534 }
8535 }
8536 }
8537
8538 if only_carets {
8539 for selection in &mut selections {
8540 let word_range = movement::surrounding_word(
8541 display_map,
8542 selection.start.to_display_point(display_map),
8543 );
8544 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8545 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8546 selection.goal = SelectionGoal::None;
8547 selection.reversed = false;
8548 select_next_match_ranges(
8549 self,
8550 selection.start..selection.end,
8551 replace_newest,
8552 autoscroll,
8553 cx,
8554 );
8555 }
8556
8557 if selections.len() == 1 {
8558 let selection = selections
8559 .last()
8560 .expect("ensured that there's only one selection");
8561 let query = buffer
8562 .text_for_range(selection.start..selection.end)
8563 .collect::<String>();
8564 let is_empty = query.is_empty();
8565 let select_state = SelectNextState {
8566 query: AhoCorasick::new(&[query])?,
8567 wordwise: true,
8568 done: is_empty,
8569 };
8570 self.select_next_state = Some(select_state);
8571 } else {
8572 self.select_next_state = None;
8573 }
8574 } else if let Some(selected_text) = selected_text {
8575 self.select_next_state = Some(SelectNextState {
8576 query: AhoCorasick::new(&[selected_text])?,
8577 wordwise: false,
8578 done: false,
8579 });
8580 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8581 }
8582 }
8583 Ok(())
8584 }
8585
8586 pub fn select_all_matches(
8587 &mut self,
8588 _action: &SelectAllMatches,
8589 cx: &mut ViewContext<Self>,
8590 ) -> Result<()> {
8591 self.push_to_selection_history();
8592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8593
8594 self.select_next_match_internal(&display_map, false, None, cx)?;
8595 let Some(select_next_state) = self.select_next_state.as_mut() else {
8596 return Ok(());
8597 };
8598 if select_next_state.done {
8599 return Ok(());
8600 }
8601
8602 let mut new_selections = self.selections.all::<usize>(cx);
8603
8604 let buffer = &display_map.buffer_snapshot;
8605 let query_matches = select_next_state
8606 .query
8607 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8608
8609 for query_match in query_matches {
8610 let query_match = query_match.unwrap(); // can only fail due to I/O
8611 let offset_range = query_match.start()..query_match.end();
8612 let display_range = offset_range.start.to_display_point(&display_map)
8613 ..offset_range.end.to_display_point(&display_map);
8614
8615 if !select_next_state.wordwise
8616 || (!movement::is_inside_word(&display_map, display_range.start)
8617 && !movement::is_inside_word(&display_map, display_range.end))
8618 {
8619 self.selections.change_with(cx, |selections| {
8620 new_selections.push(Selection {
8621 id: selections.new_selection_id(),
8622 start: offset_range.start,
8623 end: offset_range.end,
8624 reversed: false,
8625 goal: SelectionGoal::None,
8626 });
8627 });
8628 }
8629 }
8630
8631 new_selections.sort_by_key(|selection| selection.start);
8632 let mut ix = 0;
8633 while ix + 1 < new_selections.len() {
8634 let current_selection = &new_selections[ix];
8635 let next_selection = &new_selections[ix + 1];
8636 if current_selection.range().overlaps(&next_selection.range()) {
8637 if current_selection.id < next_selection.id {
8638 new_selections.remove(ix + 1);
8639 } else {
8640 new_selections.remove(ix);
8641 }
8642 } else {
8643 ix += 1;
8644 }
8645 }
8646
8647 select_next_state.done = true;
8648 self.unfold_ranges(
8649 &new_selections
8650 .iter()
8651 .map(|selection| selection.range())
8652 .collect::<Vec<_>>(),
8653 false,
8654 false,
8655 cx,
8656 );
8657 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8658 selections.select(new_selections)
8659 });
8660
8661 Ok(())
8662 }
8663
8664 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8665 self.push_to_selection_history();
8666 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8667 self.select_next_match_internal(
8668 &display_map,
8669 action.replace_newest,
8670 Some(Autoscroll::newest()),
8671 cx,
8672 )?;
8673 Ok(())
8674 }
8675
8676 pub fn select_previous(
8677 &mut self,
8678 action: &SelectPrevious,
8679 cx: &mut ViewContext<Self>,
8680 ) -> Result<()> {
8681 self.push_to_selection_history();
8682 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8683 let buffer = &display_map.buffer_snapshot;
8684 let mut selections = self.selections.all::<usize>(cx);
8685 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8686 let query = &select_prev_state.query;
8687 if !select_prev_state.done {
8688 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8689 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8690 let mut next_selected_range = None;
8691 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8692 let bytes_before_last_selection =
8693 buffer.reversed_bytes_in_range(0..last_selection.start);
8694 let bytes_after_first_selection =
8695 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8696 let query_matches = query
8697 .stream_find_iter(bytes_before_last_selection)
8698 .map(|result| (last_selection.start, result))
8699 .chain(
8700 query
8701 .stream_find_iter(bytes_after_first_selection)
8702 .map(|result| (buffer.len(), result)),
8703 );
8704 for (end_offset, query_match) in query_matches {
8705 let query_match = query_match.unwrap(); // can only fail due to I/O
8706 let offset_range =
8707 end_offset - query_match.end()..end_offset - query_match.start();
8708 let display_range = offset_range.start.to_display_point(&display_map)
8709 ..offset_range.end.to_display_point(&display_map);
8710
8711 if !select_prev_state.wordwise
8712 || (!movement::is_inside_word(&display_map, display_range.start)
8713 && !movement::is_inside_word(&display_map, display_range.end))
8714 {
8715 next_selected_range = Some(offset_range);
8716 break;
8717 }
8718 }
8719
8720 if let Some(next_selected_range) = next_selected_range {
8721 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8722 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8723 if action.replace_newest {
8724 s.delete(s.newest_anchor().id);
8725 }
8726 s.insert_range(next_selected_range);
8727 });
8728 } else {
8729 select_prev_state.done = true;
8730 }
8731 }
8732
8733 self.select_prev_state = Some(select_prev_state);
8734 } else {
8735 let mut only_carets = true;
8736 let mut same_text_selected = true;
8737 let mut selected_text = None;
8738
8739 let mut selections_iter = selections.iter().peekable();
8740 while let Some(selection) = selections_iter.next() {
8741 if selection.start != selection.end {
8742 only_carets = false;
8743 }
8744
8745 if same_text_selected {
8746 if selected_text.is_none() {
8747 selected_text =
8748 Some(buffer.text_for_range(selection.range()).collect::<String>());
8749 }
8750
8751 if let Some(next_selection) = selections_iter.peek() {
8752 if next_selection.range().len() == selection.range().len() {
8753 let next_selected_text = buffer
8754 .text_for_range(next_selection.range())
8755 .collect::<String>();
8756 if Some(next_selected_text) != selected_text {
8757 same_text_selected = false;
8758 selected_text = None;
8759 }
8760 } else {
8761 same_text_selected = false;
8762 selected_text = None;
8763 }
8764 }
8765 }
8766 }
8767
8768 if only_carets {
8769 for selection in &mut selections {
8770 let word_range = movement::surrounding_word(
8771 &display_map,
8772 selection.start.to_display_point(&display_map),
8773 );
8774 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8775 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8776 selection.goal = SelectionGoal::None;
8777 selection.reversed = false;
8778 }
8779 if selections.len() == 1 {
8780 let selection = selections
8781 .last()
8782 .expect("ensured that there's only one selection");
8783 let query = buffer
8784 .text_for_range(selection.start..selection.end)
8785 .collect::<String>();
8786 let is_empty = query.is_empty();
8787 let select_state = SelectNextState {
8788 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8789 wordwise: true,
8790 done: is_empty,
8791 };
8792 self.select_prev_state = Some(select_state);
8793 } else {
8794 self.select_prev_state = None;
8795 }
8796
8797 self.unfold_ranges(
8798 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8799 false,
8800 true,
8801 cx,
8802 );
8803 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8804 s.select(selections);
8805 });
8806 } else if let Some(selected_text) = selected_text {
8807 self.select_prev_state = Some(SelectNextState {
8808 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8809 wordwise: false,
8810 done: false,
8811 });
8812 self.select_previous(action, cx)?;
8813 }
8814 }
8815 Ok(())
8816 }
8817
8818 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8819 if self.read_only(cx) {
8820 return;
8821 }
8822 let text_layout_details = &self.text_layout_details(cx);
8823 self.transact(cx, |this, cx| {
8824 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8825 let mut edits = Vec::new();
8826 let mut selection_edit_ranges = Vec::new();
8827 let mut last_toggled_row = None;
8828 let snapshot = this.buffer.read(cx).read(cx);
8829 let empty_str: Arc<str> = Arc::default();
8830 let mut suffixes_inserted = Vec::new();
8831 let ignore_indent = action.ignore_indent;
8832
8833 fn comment_prefix_range(
8834 snapshot: &MultiBufferSnapshot,
8835 row: MultiBufferRow,
8836 comment_prefix: &str,
8837 comment_prefix_whitespace: &str,
8838 ignore_indent: bool,
8839 ) -> Range<Point> {
8840 let indent_size = if ignore_indent {
8841 0
8842 } else {
8843 snapshot.indent_size_for_line(row).len
8844 };
8845
8846 let start = Point::new(row.0, indent_size);
8847
8848 let mut line_bytes = snapshot
8849 .bytes_in_range(start..snapshot.max_point())
8850 .flatten()
8851 .copied();
8852
8853 // If this line currently begins with the line comment prefix, then record
8854 // the range containing the prefix.
8855 if line_bytes
8856 .by_ref()
8857 .take(comment_prefix.len())
8858 .eq(comment_prefix.bytes())
8859 {
8860 // Include any whitespace that matches the comment prefix.
8861 let matching_whitespace_len = line_bytes
8862 .zip(comment_prefix_whitespace.bytes())
8863 .take_while(|(a, b)| a == b)
8864 .count() as u32;
8865 let end = Point::new(
8866 start.row,
8867 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8868 );
8869 start..end
8870 } else {
8871 start..start
8872 }
8873 }
8874
8875 fn comment_suffix_range(
8876 snapshot: &MultiBufferSnapshot,
8877 row: MultiBufferRow,
8878 comment_suffix: &str,
8879 comment_suffix_has_leading_space: bool,
8880 ) -> Range<Point> {
8881 let end = Point::new(row.0, snapshot.line_len(row));
8882 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8883
8884 let mut line_end_bytes = snapshot
8885 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8886 .flatten()
8887 .copied();
8888
8889 let leading_space_len = if suffix_start_column > 0
8890 && line_end_bytes.next() == Some(b' ')
8891 && comment_suffix_has_leading_space
8892 {
8893 1
8894 } else {
8895 0
8896 };
8897
8898 // If this line currently begins with the line comment prefix, then record
8899 // the range containing the prefix.
8900 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8901 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8902 start..end
8903 } else {
8904 end..end
8905 }
8906 }
8907
8908 // TODO: Handle selections that cross excerpts
8909 for selection in &mut selections {
8910 let start_column = snapshot
8911 .indent_size_for_line(MultiBufferRow(selection.start.row))
8912 .len;
8913 let language = if let Some(language) =
8914 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8915 {
8916 language
8917 } else {
8918 continue;
8919 };
8920
8921 selection_edit_ranges.clear();
8922
8923 // If multiple selections contain a given row, avoid processing that
8924 // row more than once.
8925 let mut start_row = MultiBufferRow(selection.start.row);
8926 if last_toggled_row == Some(start_row) {
8927 start_row = start_row.next_row();
8928 }
8929 let end_row =
8930 if selection.end.row > selection.start.row && selection.end.column == 0 {
8931 MultiBufferRow(selection.end.row - 1)
8932 } else {
8933 MultiBufferRow(selection.end.row)
8934 };
8935 last_toggled_row = Some(end_row);
8936
8937 if start_row > end_row {
8938 continue;
8939 }
8940
8941 // If the language has line comments, toggle those.
8942 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8943
8944 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8945 if ignore_indent {
8946 full_comment_prefixes = full_comment_prefixes
8947 .into_iter()
8948 .map(|s| Arc::from(s.trim_end()))
8949 .collect();
8950 }
8951
8952 if !full_comment_prefixes.is_empty() {
8953 let first_prefix = full_comment_prefixes
8954 .first()
8955 .expect("prefixes is non-empty");
8956 let prefix_trimmed_lengths = full_comment_prefixes
8957 .iter()
8958 .map(|p| p.trim_end_matches(' ').len())
8959 .collect::<SmallVec<[usize; 4]>>();
8960
8961 let mut all_selection_lines_are_comments = true;
8962
8963 for row in start_row.0..=end_row.0 {
8964 let row = MultiBufferRow(row);
8965 if start_row < end_row && snapshot.is_line_blank(row) {
8966 continue;
8967 }
8968
8969 let prefix_range = full_comment_prefixes
8970 .iter()
8971 .zip(prefix_trimmed_lengths.iter().copied())
8972 .map(|(prefix, trimmed_prefix_len)| {
8973 comment_prefix_range(
8974 snapshot.deref(),
8975 row,
8976 &prefix[..trimmed_prefix_len],
8977 &prefix[trimmed_prefix_len..],
8978 ignore_indent,
8979 )
8980 })
8981 .max_by_key(|range| range.end.column - range.start.column)
8982 .expect("prefixes is non-empty");
8983
8984 if prefix_range.is_empty() {
8985 all_selection_lines_are_comments = false;
8986 }
8987
8988 selection_edit_ranges.push(prefix_range);
8989 }
8990
8991 if all_selection_lines_are_comments {
8992 edits.extend(
8993 selection_edit_ranges
8994 .iter()
8995 .cloned()
8996 .map(|range| (range, empty_str.clone())),
8997 );
8998 } else {
8999 let min_column = selection_edit_ranges
9000 .iter()
9001 .map(|range| range.start.column)
9002 .min()
9003 .unwrap_or(0);
9004 edits.extend(selection_edit_ranges.iter().map(|range| {
9005 let position = Point::new(range.start.row, min_column);
9006 (position..position, first_prefix.clone())
9007 }));
9008 }
9009 } else if let Some((full_comment_prefix, comment_suffix)) =
9010 language.block_comment_delimiters()
9011 {
9012 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9013 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9014 let prefix_range = comment_prefix_range(
9015 snapshot.deref(),
9016 start_row,
9017 comment_prefix,
9018 comment_prefix_whitespace,
9019 ignore_indent,
9020 );
9021 let suffix_range = comment_suffix_range(
9022 snapshot.deref(),
9023 end_row,
9024 comment_suffix.trim_start_matches(' '),
9025 comment_suffix.starts_with(' '),
9026 );
9027
9028 if prefix_range.is_empty() || suffix_range.is_empty() {
9029 edits.push((
9030 prefix_range.start..prefix_range.start,
9031 full_comment_prefix.clone(),
9032 ));
9033 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9034 suffixes_inserted.push((end_row, comment_suffix.len()));
9035 } else {
9036 edits.push((prefix_range, empty_str.clone()));
9037 edits.push((suffix_range, empty_str.clone()));
9038 }
9039 } else {
9040 continue;
9041 }
9042 }
9043
9044 drop(snapshot);
9045 this.buffer.update(cx, |buffer, cx| {
9046 buffer.edit(edits, None, cx);
9047 });
9048
9049 // Adjust selections so that they end before any comment suffixes that
9050 // were inserted.
9051 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9052 let mut selections = this.selections.all::<Point>(cx);
9053 let snapshot = this.buffer.read(cx).read(cx);
9054 for selection in &mut selections {
9055 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9056 match row.cmp(&MultiBufferRow(selection.end.row)) {
9057 Ordering::Less => {
9058 suffixes_inserted.next();
9059 continue;
9060 }
9061 Ordering::Greater => break,
9062 Ordering::Equal => {
9063 if selection.end.column == snapshot.line_len(row) {
9064 if selection.is_empty() {
9065 selection.start.column -= suffix_len as u32;
9066 }
9067 selection.end.column -= suffix_len as u32;
9068 }
9069 break;
9070 }
9071 }
9072 }
9073 }
9074
9075 drop(snapshot);
9076 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9077
9078 let selections = this.selections.all::<Point>(cx);
9079 let selections_on_single_row = selections.windows(2).all(|selections| {
9080 selections[0].start.row == selections[1].start.row
9081 && selections[0].end.row == selections[1].end.row
9082 && selections[0].start.row == selections[0].end.row
9083 });
9084 let selections_selecting = selections
9085 .iter()
9086 .any(|selection| selection.start != selection.end);
9087 let advance_downwards = action.advance_downwards
9088 && selections_on_single_row
9089 && !selections_selecting
9090 && !matches!(this.mode, EditorMode::SingleLine { .. });
9091
9092 if advance_downwards {
9093 let snapshot = this.buffer.read(cx).snapshot(cx);
9094
9095 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9096 s.move_cursors_with(|display_snapshot, display_point, _| {
9097 let mut point = display_point.to_point(display_snapshot);
9098 point.row += 1;
9099 point = snapshot.clip_point(point, Bias::Left);
9100 let display_point = point.to_display_point(display_snapshot);
9101 let goal = SelectionGoal::HorizontalPosition(
9102 display_snapshot
9103 .x_for_display_point(display_point, text_layout_details)
9104 .into(),
9105 );
9106 (display_point, goal)
9107 })
9108 });
9109 }
9110 });
9111 }
9112
9113 pub fn select_enclosing_symbol(
9114 &mut self,
9115 _: &SelectEnclosingSymbol,
9116 cx: &mut ViewContext<Self>,
9117 ) {
9118 let buffer = self.buffer.read(cx).snapshot(cx);
9119 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9120
9121 fn update_selection(
9122 selection: &Selection<usize>,
9123 buffer_snap: &MultiBufferSnapshot,
9124 ) -> Option<Selection<usize>> {
9125 let cursor = selection.head();
9126 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9127 for symbol in symbols.iter().rev() {
9128 let start = symbol.range.start.to_offset(buffer_snap);
9129 let end = symbol.range.end.to_offset(buffer_snap);
9130 let new_range = start..end;
9131 if start < selection.start || end > selection.end {
9132 return Some(Selection {
9133 id: selection.id,
9134 start: new_range.start,
9135 end: new_range.end,
9136 goal: SelectionGoal::None,
9137 reversed: selection.reversed,
9138 });
9139 }
9140 }
9141 None
9142 }
9143
9144 let mut selected_larger_symbol = false;
9145 let new_selections = old_selections
9146 .iter()
9147 .map(|selection| match update_selection(selection, &buffer) {
9148 Some(new_selection) => {
9149 if new_selection.range() != selection.range() {
9150 selected_larger_symbol = true;
9151 }
9152 new_selection
9153 }
9154 None => selection.clone(),
9155 })
9156 .collect::<Vec<_>>();
9157
9158 if selected_larger_symbol {
9159 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9160 s.select(new_selections);
9161 });
9162 }
9163 }
9164
9165 pub fn select_larger_syntax_node(
9166 &mut self,
9167 _: &SelectLargerSyntaxNode,
9168 cx: &mut ViewContext<Self>,
9169 ) {
9170 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9171 let buffer = self.buffer.read(cx).snapshot(cx);
9172 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9173
9174 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9175 let mut selected_larger_node = false;
9176 let new_selections = old_selections
9177 .iter()
9178 .map(|selection| {
9179 let old_range = selection.start..selection.end;
9180 let mut new_range = old_range.clone();
9181 while let Some(containing_range) =
9182 buffer.range_for_syntax_ancestor(new_range.clone())
9183 {
9184 new_range = containing_range;
9185 if !display_map.intersects_fold(new_range.start)
9186 && !display_map.intersects_fold(new_range.end)
9187 {
9188 break;
9189 }
9190 }
9191
9192 selected_larger_node |= new_range != old_range;
9193 Selection {
9194 id: selection.id,
9195 start: new_range.start,
9196 end: new_range.end,
9197 goal: SelectionGoal::None,
9198 reversed: selection.reversed,
9199 }
9200 })
9201 .collect::<Vec<_>>();
9202
9203 if selected_larger_node {
9204 stack.push(old_selections);
9205 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9206 s.select(new_selections);
9207 });
9208 }
9209 self.select_larger_syntax_node_stack = stack;
9210 }
9211
9212 pub fn select_smaller_syntax_node(
9213 &mut self,
9214 _: &SelectSmallerSyntaxNode,
9215 cx: &mut ViewContext<Self>,
9216 ) {
9217 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9218 if let Some(selections) = stack.pop() {
9219 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9220 s.select(selections.to_vec());
9221 });
9222 }
9223 self.select_larger_syntax_node_stack = stack;
9224 }
9225
9226 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9227 if !EditorSettings::get_global(cx).gutter.runnables {
9228 self.clear_tasks();
9229 return Task::ready(());
9230 }
9231 let project = self.project.as_ref().map(Model::downgrade);
9232 cx.spawn(|this, mut cx| async move {
9233 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9234 let Some(project) = project.and_then(|p| p.upgrade()) else {
9235 return;
9236 };
9237 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9238 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9239 }) else {
9240 return;
9241 };
9242
9243 let hide_runnables = project
9244 .update(&mut cx, |project, cx| {
9245 // Do not display any test indicators in non-dev server remote projects.
9246 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9247 })
9248 .unwrap_or(true);
9249 if hide_runnables {
9250 return;
9251 }
9252 let new_rows =
9253 cx.background_executor()
9254 .spawn({
9255 let snapshot = display_snapshot.clone();
9256 async move {
9257 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9258 }
9259 })
9260 .await;
9261 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9262
9263 this.update(&mut cx, |this, _| {
9264 this.clear_tasks();
9265 for (key, value) in rows {
9266 this.insert_tasks(key, value);
9267 }
9268 })
9269 .ok();
9270 })
9271 }
9272 fn fetch_runnable_ranges(
9273 snapshot: &DisplaySnapshot,
9274 range: Range<Anchor>,
9275 ) -> Vec<language::RunnableRange> {
9276 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9277 }
9278
9279 fn runnable_rows(
9280 project: Model<Project>,
9281 snapshot: DisplaySnapshot,
9282 runnable_ranges: Vec<RunnableRange>,
9283 mut cx: AsyncWindowContext,
9284 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9285 runnable_ranges
9286 .into_iter()
9287 .filter_map(|mut runnable| {
9288 let tasks = cx
9289 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9290 .ok()?;
9291 if tasks.is_empty() {
9292 return None;
9293 }
9294
9295 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9296
9297 let row = snapshot
9298 .buffer_snapshot
9299 .buffer_line_for_row(MultiBufferRow(point.row))?
9300 .1
9301 .start
9302 .row;
9303
9304 let context_range =
9305 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9306 Some((
9307 (runnable.buffer_id, row),
9308 RunnableTasks {
9309 templates: tasks,
9310 offset: MultiBufferOffset(runnable.run_range.start),
9311 context_range,
9312 column: point.column,
9313 extra_variables: runnable.extra_captures,
9314 },
9315 ))
9316 })
9317 .collect()
9318 }
9319
9320 fn templates_with_tags(
9321 project: &Model<Project>,
9322 runnable: &mut Runnable,
9323 cx: &WindowContext<'_>,
9324 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9325 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9326 let (worktree_id, file) = project
9327 .buffer_for_id(runnable.buffer, cx)
9328 .and_then(|buffer| buffer.read(cx).file())
9329 .map(|file| (file.worktree_id(cx), file.clone()))
9330 .unzip();
9331
9332 (
9333 project.task_store().read(cx).task_inventory().cloned(),
9334 worktree_id,
9335 file,
9336 )
9337 });
9338
9339 let tags = mem::take(&mut runnable.tags);
9340 let mut tags: Vec<_> = tags
9341 .into_iter()
9342 .flat_map(|tag| {
9343 let tag = tag.0.clone();
9344 inventory
9345 .as_ref()
9346 .into_iter()
9347 .flat_map(|inventory| {
9348 inventory.read(cx).list_tasks(
9349 file.clone(),
9350 Some(runnable.language.clone()),
9351 worktree_id,
9352 cx,
9353 )
9354 })
9355 .filter(move |(_, template)| {
9356 template.tags.iter().any(|source_tag| source_tag == &tag)
9357 })
9358 })
9359 .sorted_by_key(|(kind, _)| kind.to_owned())
9360 .collect();
9361 if let Some((leading_tag_source, _)) = tags.first() {
9362 // Strongest source wins; if we have worktree tag binding, prefer that to
9363 // global and language bindings;
9364 // if we have a global binding, prefer that to language binding.
9365 let first_mismatch = tags
9366 .iter()
9367 .position(|(tag_source, _)| tag_source != leading_tag_source);
9368 if let Some(index) = first_mismatch {
9369 tags.truncate(index);
9370 }
9371 }
9372
9373 tags
9374 }
9375
9376 pub fn move_to_enclosing_bracket(
9377 &mut self,
9378 _: &MoveToEnclosingBracket,
9379 cx: &mut ViewContext<Self>,
9380 ) {
9381 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9382 s.move_offsets_with(|snapshot, selection| {
9383 let Some(enclosing_bracket_ranges) =
9384 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9385 else {
9386 return;
9387 };
9388
9389 let mut best_length = usize::MAX;
9390 let mut best_inside = false;
9391 let mut best_in_bracket_range = false;
9392 let mut best_destination = None;
9393 for (open, close) in enclosing_bracket_ranges {
9394 let close = close.to_inclusive();
9395 let length = close.end() - open.start;
9396 let inside = selection.start >= open.end && selection.end <= *close.start();
9397 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9398 || close.contains(&selection.head());
9399
9400 // If best is next to a bracket and current isn't, skip
9401 if !in_bracket_range && best_in_bracket_range {
9402 continue;
9403 }
9404
9405 // Prefer smaller lengths unless best is inside and current isn't
9406 if length > best_length && (best_inside || !inside) {
9407 continue;
9408 }
9409
9410 best_length = length;
9411 best_inside = inside;
9412 best_in_bracket_range = in_bracket_range;
9413 best_destination = Some(
9414 if close.contains(&selection.start) && close.contains(&selection.end) {
9415 if inside {
9416 open.end
9417 } else {
9418 open.start
9419 }
9420 } else if inside {
9421 *close.start()
9422 } else {
9423 *close.end()
9424 },
9425 );
9426 }
9427
9428 if let Some(destination) = best_destination {
9429 selection.collapse_to(destination, SelectionGoal::None);
9430 }
9431 })
9432 });
9433 }
9434
9435 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9436 self.end_selection(cx);
9437 self.selection_history.mode = SelectionHistoryMode::Undoing;
9438 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9439 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9440 self.select_next_state = entry.select_next_state;
9441 self.select_prev_state = entry.select_prev_state;
9442 self.add_selections_state = entry.add_selections_state;
9443 self.request_autoscroll(Autoscroll::newest(), cx);
9444 }
9445 self.selection_history.mode = SelectionHistoryMode::Normal;
9446 }
9447
9448 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9449 self.end_selection(cx);
9450 self.selection_history.mode = SelectionHistoryMode::Redoing;
9451 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9452 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9453 self.select_next_state = entry.select_next_state;
9454 self.select_prev_state = entry.select_prev_state;
9455 self.add_selections_state = entry.add_selections_state;
9456 self.request_autoscroll(Autoscroll::newest(), cx);
9457 }
9458 self.selection_history.mode = SelectionHistoryMode::Normal;
9459 }
9460
9461 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9462 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9463 }
9464
9465 pub fn expand_excerpts_down(
9466 &mut self,
9467 action: &ExpandExcerptsDown,
9468 cx: &mut ViewContext<Self>,
9469 ) {
9470 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9471 }
9472
9473 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9474 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9475 }
9476
9477 pub fn expand_excerpts_for_direction(
9478 &mut self,
9479 lines: u32,
9480 direction: ExpandExcerptDirection,
9481 cx: &mut ViewContext<Self>,
9482 ) {
9483 let selections = self.selections.disjoint_anchors();
9484
9485 let lines = if lines == 0 {
9486 EditorSettings::get_global(cx).expand_excerpt_lines
9487 } else {
9488 lines
9489 };
9490
9491 self.buffer.update(cx, |buffer, cx| {
9492 buffer.expand_excerpts(
9493 selections
9494 .iter()
9495 .map(|selection| selection.head().excerpt_id)
9496 .dedup(),
9497 lines,
9498 direction,
9499 cx,
9500 )
9501 })
9502 }
9503
9504 pub fn expand_excerpt(
9505 &mut self,
9506 excerpt: ExcerptId,
9507 direction: ExpandExcerptDirection,
9508 cx: &mut ViewContext<Self>,
9509 ) {
9510 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9511 self.buffer.update(cx, |buffer, cx| {
9512 buffer.expand_excerpts([excerpt], lines, direction, cx)
9513 })
9514 }
9515
9516 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9517 self.go_to_diagnostic_impl(Direction::Next, cx)
9518 }
9519
9520 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9521 self.go_to_diagnostic_impl(Direction::Prev, cx)
9522 }
9523
9524 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9525 let buffer = self.buffer.read(cx).snapshot(cx);
9526 let selection = self.selections.newest::<usize>(cx);
9527
9528 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9529 if direction == Direction::Next {
9530 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9531 let (group_id, jump_to) = popover.activation_info();
9532 if self.activate_diagnostics(group_id, cx) {
9533 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9534 let mut new_selection = s.newest_anchor().clone();
9535 new_selection.collapse_to(jump_to, SelectionGoal::None);
9536 s.select_anchors(vec![new_selection.clone()]);
9537 });
9538 }
9539 return;
9540 }
9541 }
9542
9543 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9544 active_diagnostics
9545 .primary_range
9546 .to_offset(&buffer)
9547 .to_inclusive()
9548 });
9549 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9550 if active_primary_range.contains(&selection.head()) {
9551 *active_primary_range.start()
9552 } else {
9553 selection.head()
9554 }
9555 } else {
9556 selection.head()
9557 };
9558 let snapshot = self.snapshot(cx);
9559 loop {
9560 let diagnostics = if direction == Direction::Prev {
9561 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9562 } else {
9563 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9564 }
9565 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9566 let group = diagnostics
9567 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9568 // be sorted in a stable way
9569 // skip until we are at current active diagnostic, if it exists
9570 .skip_while(|entry| {
9571 (match direction {
9572 Direction::Prev => entry.range.start >= search_start,
9573 Direction::Next => entry.range.start <= search_start,
9574 }) && self
9575 .active_diagnostics
9576 .as_ref()
9577 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9578 })
9579 .find_map(|entry| {
9580 if entry.diagnostic.is_primary
9581 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9582 && !entry.range.is_empty()
9583 // if we match with the active diagnostic, skip it
9584 && Some(entry.diagnostic.group_id)
9585 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9586 {
9587 Some((entry.range, entry.diagnostic.group_id))
9588 } else {
9589 None
9590 }
9591 });
9592
9593 if let Some((primary_range, group_id)) = group {
9594 if self.activate_diagnostics(group_id, cx) {
9595 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9596 s.select(vec![Selection {
9597 id: selection.id,
9598 start: primary_range.start,
9599 end: primary_range.start,
9600 reversed: false,
9601 goal: SelectionGoal::None,
9602 }]);
9603 });
9604 }
9605 break;
9606 } else {
9607 // Cycle around to the start of the buffer, potentially moving back to the start of
9608 // the currently active diagnostic.
9609 active_primary_range.take();
9610 if direction == Direction::Prev {
9611 if search_start == buffer.len() {
9612 break;
9613 } else {
9614 search_start = buffer.len();
9615 }
9616 } else if search_start == 0 {
9617 break;
9618 } else {
9619 search_start = 0;
9620 }
9621 }
9622 }
9623 }
9624
9625 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9626 let snapshot = self
9627 .display_map
9628 .update(cx, |display_map, cx| display_map.snapshot(cx));
9629 let selection = self.selections.newest::<Point>(cx);
9630 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9631 }
9632
9633 fn go_to_hunk_after_position(
9634 &mut self,
9635 snapshot: &DisplaySnapshot,
9636 position: Point,
9637 cx: &mut ViewContext<'_, Editor>,
9638 ) -> Option<MultiBufferDiffHunk> {
9639 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9640 snapshot,
9641 position,
9642 false,
9643 snapshot
9644 .buffer_snapshot
9645 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9646 cx,
9647 ) {
9648 return Some(hunk);
9649 }
9650
9651 let wrapped_point = Point::zero();
9652 self.go_to_next_hunk_in_direction(
9653 snapshot,
9654 wrapped_point,
9655 true,
9656 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9657 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9658 ),
9659 cx,
9660 )
9661 }
9662
9663 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9664 let snapshot = self
9665 .display_map
9666 .update(cx, |display_map, cx| display_map.snapshot(cx));
9667 let selection = self.selections.newest::<Point>(cx);
9668
9669 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9670 }
9671
9672 fn go_to_hunk_before_position(
9673 &mut self,
9674 snapshot: &DisplaySnapshot,
9675 position: Point,
9676 cx: &mut ViewContext<'_, Editor>,
9677 ) -> Option<MultiBufferDiffHunk> {
9678 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9679 snapshot,
9680 position,
9681 false,
9682 snapshot
9683 .buffer_snapshot
9684 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9685 cx,
9686 ) {
9687 return Some(hunk);
9688 }
9689
9690 let wrapped_point = snapshot.buffer_snapshot.max_point();
9691 self.go_to_next_hunk_in_direction(
9692 snapshot,
9693 wrapped_point,
9694 true,
9695 snapshot
9696 .buffer_snapshot
9697 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9698 cx,
9699 )
9700 }
9701
9702 fn go_to_next_hunk_in_direction(
9703 &mut self,
9704 snapshot: &DisplaySnapshot,
9705 initial_point: Point,
9706 is_wrapped: bool,
9707 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9708 cx: &mut ViewContext<Editor>,
9709 ) -> Option<MultiBufferDiffHunk> {
9710 let display_point = initial_point.to_display_point(snapshot);
9711 let mut hunks = hunks
9712 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9713 .filter(|(display_hunk, _)| {
9714 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9715 })
9716 .dedup();
9717
9718 if let Some((display_hunk, hunk)) = hunks.next() {
9719 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9720 let row = display_hunk.start_display_row();
9721 let point = DisplayPoint::new(row, 0);
9722 s.select_display_ranges([point..point]);
9723 });
9724
9725 Some(hunk)
9726 } else {
9727 None
9728 }
9729 }
9730
9731 pub fn go_to_definition(
9732 &mut self,
9733 _: &GoToDefinition,
9734 cx: &mut ViewContext<Self>,
9735 ) -> Task<Result<Navigated>> {
9736 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9737 cx.spawn(|editor, mut cx| async move {
9738 if definition.await? == Navigated::Yes {
9739 return Ok(Navigated::Yes);
9740 }
9741 match editor.update(&mut cx, |editor, cx| {
9742 editor.find_all_references(&FindAllReferences, cx)
9743 })? {
9744 Some(references) => references.await,
9745 None => Ok(Navigated::No),
9746 }
9747 })
9748 }
9749
9750 pub fn go_to_declaration(
9751 &mut self,
9752 _: &GoToDeclaration,
9753 cx: &mut ViewContext<Self>,
9754 ) -> Task<Result<Navigated>> {
9755 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9756 }
9757
9758 pub fn go_to_declaration_split(
9759 &mut self,
9760 _: &GoToDeclaration,
9761 cx: &mut ViewContext<Self>,
9762 ) -> Task<Result<Navigated>> {
9763 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9764 }
9765
9766 pub fn go_to_implementation(
9767 &mut self,
9768 _: &GoToImplementation,
9769 cx: &mut ViewContext<Self>,
9770 ) -> Task<Result<Navigated>> {
9771 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9772 }
9773
9774 pub fn go_to_implementation_split(
9775 &mut self,
9776 _: &GoToImplementationSplit,
9777 cx: &mut ViewContext<Self>,
9778 ) -> Task<Result<Navigated>> {
9779 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9780 }
9781
9782 pub fn go_to_type_definition(
9783 &mut self,
9784 _: &GoToTypeDefinition,
9785 cx: &mut ViewContext<Self>,
9786 ) -> Task<Result<Navigated>> {
9787 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9788 }
9789
9790 pub fn go_to_definition_split(
9791 &mut self,
9792 _: &GoToDefinitionSplit,
9793 cx: &mut ViewContext<Self>,
9794 ) -> Task<Result<Navigated>> {
9795 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9796 }
9797
9798 pub fn go_to_type_definition_split(
9799 &mut self,
9800 _: &GoToTypeDefinitionSplit,
9801 cx: &mut ViewContext<Self>,
9802 ) -> Task<Result<Navigated>> {
9803 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9804 }
9805
9806 fn go_to_definition_of_kind(
9807 &mut self,
9808 kind: GotoDefinitionKind,
9809 split: bool,
9810 cx: &mut ViewContext<Self>,
9811 ) -> Task<Result<Navigated>> {
9812 let Some(provider) = self.semantics_provider.clone() else {
9813 return Task::ready(Ok(Navigated::No));
9814 };
9815 let head = self.selections.newest::<usize>(cx).head();
9816 let buffer = self.buffer.read(cx);
9817 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9818 text_anchor
9819 } else {
9820 return Task::ready(Ok(Navigated::No));
9821 };
9822
9823 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9824 return Task::ready(Ok(Navigated::No));
9825 };
9826
9827 cx.spawn(|editor, mut cx| async move {
9828 let definitions = definitions.await?;
9829 let navigated = editor
9830 .update(&mut cx, |editor, cx| {
9831 editor.navigate_to_hover_links(
9832 Some(kind),
9833 definitions
9834 .into_iter()
9835 .filter(|location| {
9836 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9837 })
9838 .map(HoverLink::Text)
9839 .collect::<Vec<_>>(),
9840 split,
9841 cx,
9842 )
9843 })?
9844 .await?;
9845 anyhow::Ok(navigated)
9846 })
9847 }
9848
9849 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9850 let position = self.selections.newest_anchor().head();
9851 let Some((buffer, buffer_position)) =
9852 self.buffer.read(cx).text_anchor_for_position(position, cx)
9853 else {
9854 return;
9855 };
9856
9857 cx.spawn(|editor, mut cx| async move {
9858 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9859 editor.update(&mut cx, |_, cx| {
9860 cx.open_url(&url);
9861 })
9862 } else {
9863 Ok(())
9864 }
9865 })
9866 .detach();
9867 }
9868
9869 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9870 let Some(workspace) = self.workspace() else {
9871 return;
9872 };
9873
9874 let position = self.selections.newest_anchor().head();
9875
9876 let Some((buffer, buffer_position)) =
9877 self.buffer.read(cx).text_anchor_for_position(position, cx)
9878 else {
9879 return;
9880 };
9881
9882 let project = self.project.clone();
9883
9884 cx.spawn(|_, mut cx| async move {
9885 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9886
9887 if let Some((_, path)) = result {
9888 workspace
9889 .update(&mut cx, |workspace, cx| {
9890 workspace.open_resolved_path(path, cx)
9891 })?
9892 .await?;
9893 }
9894 anyhow::Ok(())
9895 })
9896 .detach();
9897 }
9898
9899 pub(crate) fn navigate_to_hover_links(
9900 &mut self,
9901 kind: Option<GotoDefinitionKind>,
9902 mut definitions: Vec<HoverLink>,
9903 split: bool,
9904 cx: &mut ViewContext<Editor>,
9905 ) -> Task<Result<Navigated>> {
9906 // If there is one definition, just open it directly
9907 if definitions.len() == 1 {
9908 let definition = definitions.pop().unwrap();
9909
9910 enum TargetTaskResult {
9911 Location(Option<Location>),
9912 AlreadyNavigated,
9913 }
9914
9915 let target_task = match definition {
9916 HoverLink::Text(link) => {
9917 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9918 }
9919 HoverLink::InlayHint(lsp_location, server_id) => {
9920 let computation = self.compute_target_location(lsp_location, server_id, cx);
9921 cx.background_executor().spawn(async move {
9922 let location = computation.await?;
9923 Ok(TargetTaskResult::Location(location))
9924 })
9925 }
9926 HoverLink::Url(url) => {
9927 cx.open_url(&url);
9928 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9929 }
9930 HoverLink::File(path) => {
9931 if let Some(workspace) = self.workspace() {
9932 cx.spawn(|_, mut cx| async move {
9933 workspace
9934 .update(&mut cx, |workspace, cx| {
9935 workspace.open_resolved_path(path, cx)
9936 })?
9937 .await
9938 .map(|_| TargetTaskResult::AlreadyNavigated)
9939 })
9940 } else {
9941 Task::ready(Ok(TargetTaskResult::Location(None)))
9942 }
9943 }
9944 };
9945 cx.spawn(|editor, mut cx| async move {
9946 let target = match target_task.await.context("target resolution task")? {
9947 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9948 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9949 TargetTaskResult::Location(Some(target)) => target,
9950 };
9951
9952 editor.update(&mut cx, |editor, cx| {
9953 let Some(workspace) = editor.workspace() else {
9954 return Navigated::No;
9955 };
9956 let pane = workspace.read(cx).active_pane().clone();
9957
9958 let range = target.range.to_offset(target.buffer.read(cx));
9959 let range = editor.range_for_match(&range);
9960
9961 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9962 let buffer = target.buffer.read(cx);
9963 let range = check_multiline_range(buffer, range);
9964 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9965 s.select_ranges([range]);
9966 });
9967 } else {
9968 cx.window_context().defer(move |cx| {
9969 let target_editor: View<Self> =
9970 workspace.update(cx, |workspace, cx| {
9971 let pane = if split {
9972 workspace.adjacent_pane(cx)
9973 } else {
9974 workspace.active_pane().clone()
9975 };
9976
9977 workspace.open_project_item(
9978 pane,
9979 target.buffer.clone(),
9980 true,
9981 true,
9982 cx,
9983 )
9984 });
9985 target_editor.update(cx, |target_editor, cx| {
9986 // When selecting a definition in a different buffer, disable the nav history
9987 // to avoid creating a history entry at the previous cursor location.
9988 pane.update(cx, |pane, _| pane.disable_history());
9989 let buffer = target.buffer.read(cx);
9990 let range = check_multiline_range(buffer, range);
9991 target_editor.change_selections(
9992 Some(Autoscroll::focused()),
9993 cx,
9994 |s| {
9995 s.select_ranges([range]);
9996 },
9997 );
9998 pane.update(cx, |pane, _| pane.enable_history());
9999 });
10000 });
10001 }
10002 Navigated::Yes
10003 })
10004 })
10005 } else if !definitions.is_empty() {
10006 cx.spawn(|editor, mut cx| async move {
10007 let (title, location_tasks, workspace) = editor
10008 .update(&mut cx, |editor, cx| {
10009 let tab_kind = match kind {
10010 Some(GotoDefinitionKind::Implementation) => "Implementations",
10011 _ => "Definitions",
10012 };
10013 let title = definitions
10014 .iter()
10015 .find_map(|definition| match definition {
10016 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10017 let buffer = origin.buffer.read(cx);
10018 format!(
10019 "{} for {}",
10020 tab_kind,
10021 buffer
10022 .text_for_range(origin.range.clone())
10023 .collect::<String>()
10024 )
10025 }),
10026 HoverLink::InlayHint(_, _) => None,
10027 HoverLink::Url(_) => None,
10028 HoverLink::File(_) => None,
10029 })
10030 .unwrap_or(tab_kind.to_string());
10031 let location_tasks = definitions
10032 .into_iter()
10033 .map(|definition| match definition {
10034 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10035 HoverLink::InlayHint(lsp_location, server_id) => {
10036 editor.compute_target_location(lsp_location, server_id, cx)
10037 }
10038 HoverLink::Url(_) => Task::ready(Ok(None)),
10039 HoverLink::File(_) => Task::ready(Ok(None)),
10040 })
10041 .collect::<Vec<_>>();
10042 (title, location_tasks, editor.workspace().clone())
10043 })
10044 .context("location tasks preparation")?;
10045
10046 let locations = future::join_all(location_tasks)
10047 .await
10048 .into_iter()
10049 .filter_map(|location| location.transpose())
10050 .collect::<Result<_>>()
10051 .context("location tasks")?;
10052
10053 let Some(workspace) = workspace else {
10054 return Ok(Navigated::No);
10055 };
10056 let opened = workspace
10057 .update(&mut cx, |workspace, cx| {
10058 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10059 })
10060 .ok();
10061
10062 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10063 })
10064 } else {
10065 Task::ready(Ok(Navigated::No))
10066 }
10067 }
10068
10069 fn compute_target_location(
10070 &self,
10071 lsp_location: lsp::Location,
10072 server_id: LanguageServerId,
10073 cx: &mut ViewContext<Self>,
10074 ) -> Task<anyhow::Result<Option<Location>>> {
10075 let Some(project) = self.project.clone() else {
10076 return Task::Ready(Some(Ok(None)));
10077 };
10078
10079 cx.spawn(move |editor, mut cx| async move {
10080 let location_task = editor.update(&mut cx, |_, cx| {
10081 project.update(cx, |project, cx| {
10082 let language_server_name = project
10083 .language_server_statuses(cx)
10084 .find(|(id, _)| server_id == *id)
10085 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10086 language_server_name.map(|language_server_name| {
10087 project.open_local_buffer_via_lsp(
10088 lsp_location.uri.clone(),
10089 server_id,
10090 language_server_name,
10091 cx,
10092 )
10093 })
10094 })
10095 })?;
10096 let location = match location_task {
10097 Some(task) => Some({
10098 let target_buffer_handle = task.await.context("open local buffer")?;
10099 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10100 let target_start = target_buffer
10101 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10102 let target_end = target_buffer
10103 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10104 target_buffer.anchor_after(target_start)
10105 ..target_buffer.anchor_before(target_end)
10106 })?;
10107 Location {
10108 buffer: target_buffer_handle,
10109 range,
10110 }
10111 }),
10112 None => None,
10113 };
10114 Ok(location)
10115 })
10116 }
10117
10118 pub fn find_all_references(
10119 &mut self,
10120 _: &FindAllReferences,
10121 cx: &mut ViewContext<Self>,
10122 ) -> Option<Task<Result<Navigated>>> {
10123 let selection = self.selections.newest::<usize>(cx);
10124 let multi_buffer = self.buffer.read(cx);
10125 let head = selection.head();
10126
10127 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10128 let head_anchor = multi_buffer_snapshot.anchor_at(
10129 head,
10130 if head < selection.tail() {
10131 Bias::Right
10132 } else {
10133 Bias::Left
10134 },
10135 );
10136
10137 match self
10138 .find_all_references_task_sources
10139 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10140 {
10141 Ok(_) => {
10142 log::info!(
10143 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10144 );
10145 return None;
10146 }
10147 Err(i) => {
10148 self.find_all_references_task_sources.insert(i, head_anchor);
10149 }
10150 }
10151
10152 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10153 let workspace = self.workspace()?;
10154 let project = workspace.read(cx).project().clone();
10155 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10156 Some(cx.spawn(|editor, mut cx| async move {
10157 let _cleanup = defer({
10158 let mut cx = cx.clone();
10159 move || {
10160 let _ = editor.update(&mut cx, |editor, _| {
10161 if let Ok(i) =
10162 editor
10163 .find_all_references_task_sources
10164 .binary_search_by(|anchor| {
10165 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10166 })
10167 {
10168 editor.find_all_references_task_sources.remove(i);
10169 }
10170 });
10171 }
10172 });
10173
10174 let locations = references.await?;
10175 if locations.is_empty() {
10176 return anyhow::Ok(Navigated::No);
10177 }
10178
10179 workspace.update(&mut cx, |workspace, cx| {
10180 let title = locations
10181 .first()
10182 .as_ref()
10183 .map(|location| {
10184 let buffer = location.buffer.read(cx);
10185 format!(
10186 "References to `{}`",
10187 buffer
10188 .text_for_range(location.range.clone())
10189 .collect::<String>()
10190 )
10191 })
10192 .unwrap();
10193 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10194 Navigated::Yes
10195 })
10196 }))
10197 }
10198
10199 /// Opens a multibuffer with the given project locations in it
10200 pub fn open_locations_in_multibuffer(
10201 workspace: &mut Workspace,
10202 mut locations: Vec<Location>,
10203 title: String,
10204 split: bool,
10205 cx: &mut ViewContext<Workspace>,
10206 ) {
10207 // If there are multiple definitions, open them in a multibuffer
10208 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10209 let mut locations = locations.into_iter().peekable();
10210 let mut ranges_to_highlight = Vec::new();
10211 let capability = workspace.project().read(cx).capability();
10212
10213 let excerpt_buffer = cx.new_model(|cx| {
10214 let mut multibuffer = MultiBuffer::new(capability);
10215 while let Some(location) = locations.next() {
10216 let buffer = location.buffer.read(cx);
10217 let mut ranges_for_buffer = Vec::new();
10218 let range = location.range.to_offset(buffer);
10219 ranges_for_buffer.push(range.clone());
10220
10221 while let Some(next_location) = locations.peek() {
10222 if next_location.buffer == location.buffer {
10223 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10224 locations.next();
10225 } else {
10226 break;
10227 }
10228 }
10229
10230 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10231 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10232 location.buffer.clone(),
10233 ranges_for_buffer,
10234 DEFAULT_MULTIBUFFER_CONTEXT,
10235 cx,
10236 ))
10237 }
10238
10239 multibuffer.with_title(title)
10240 });
10241
10242 let editor = cx.new_view(|cx| {
10243 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10244 });
10245 editor.update(cx, |editor, cx| {
10246 if let Some(first_range) = ranges_to_highlight.first() {
10247 editor.change_selections(None, cx, |selections| {
10248 selections.clear_disjoint();
10249 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10250 });
10251 }
10252 editor.highlight_background::<Self>(
10253 &ranges_to_highlight,
10254 |theme| theme.editor_highlighted_line_background,
10255 cx,
10256 );
10257 });
10258
10259 let item = Box::new(editor);
10260 let item_id = item.item_id();
10261
10262 if split {
10263 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10264 } else {
10265 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10266 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10267 pane.close_current_preview_item(cx)
10268 } else {
10269 None
10270 }
10271 });
10272 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10273 }
10274 workspace.active_pane().update(cx, |pane, cx| {
10275 pane.set_preview_item_id(Some(item_id), cx);
10276 });
10277 }
10278
10279 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10280 use language::ToOffset as _;
10281
10282 let provider = self.semantics_provider.clone()?;
10283 let selection = self.selections.newest_anchor().clone();
10284 let (cursor_buffer, cursor_buffer_position) = self
10285 .buffer
10286 .read(cx)
10287 .text_anchor_for_position(selection.head(), cx)?;
10288 let (tail_buffer, cursor_buffer_position_end) = self
10289 .buffer
10290 .read(cx)
10291 .text_anchor_for_position(selection.tail(), cx)?;
10292 if tail_buffer != cursor_buffer {
10293 return None;
10294 }
10295
10296 let snapshot = cursor_buffer.read(cx).snapshot();
10297 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10298 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10299 let prepare_rename = provider
10300 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10301 .unwrap_or_else(|| Task::ready(Ok(None)));
10302 drop(snapshot);
10303
10304 Some(cx.spawn(|this, mut cx| async move {
10305 let rename_range = if let Some(range) = prepare_rename.await? {
10306 Some(range)
10307 } else {
10308 this.update(&mut cx, |this, cx| {
10309 let buffer = this.buffer.read(cx).snapshot(cx);
10310 let mut buffer_highlights = this
10311 .document_highlights_for_position(selection.head(), &buffer)
10312 .filter(|highlight| {
10313 highlight.start.excerpt_id == selection.head().excerpt_id
10314 && highlight.end.excerpt_id == selection.head().excerpt_id
10315 });
10316 buffer_highlights
10317 .next()
10318 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10319 })?
10320 };
10321 if let Some(rename_range) = rename_range {
10322 this.update(&mut cx, |this, cx| {
10323 let snapshot = cursor_buffer.read(cx).snapshot();
10324 let rename_buffer_range = rename_range.to_offset(&snapshot);
10325 let cursor_offset_in_rename_range =
10326 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10327 let cursor_offset_in_rename_range_end =
10328 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10329
10330 this.take_rename(false, cx);
10331 let buffer = this.buffer.read(cx).read(cx);
10332 let cursor_offset = selection.head().to_offset(&buffer);
10333 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10334 let rename_end = rename_start + rename_buffer_range.len();
10335 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10336 let mut old_highlight_id = None;
10337 let old_name: Arc<str> = buffer
10338 .chunks(rename_start..rename_end, true)
10339 .map(|chunk| {
10340 if old_highlight_id.is_none() {
10341 old_highlight_id = chunk.syntax_highlight_id;
10342 }
10343 chunk.text
10344 })
10345 .collect::<String>()
10346 .into();
10347
10348 drop(buffer);
10349
10350 // Position the selection in the rename editor so that it matches the current selection.
10351 this.show_local_selections = false;
10352 let rename_editor = cx.new_view(|cx| {
10353 let mut editor = Editor::single_line(cx);
10354 editor.buffer.update(cx, |buffer, cx| {
10355 buffer.edit([(0..0, old_name.clone())], None, cx)
10356 });
10357 let rename_selection_range = match cursor_offset_in_rename_range
10358 .cmp(&cursor_offset_in_rename_range_end)
10359 {
10360 Ordering::Equal => {
10361 editor.select_all(&SelectAll, cx);
10362 return editor;
10363 }
10364 Ordering::Less => {
10365 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10366 }
10367 Ordering::Greater => {
10368 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10369 }
10370 };
10371 if rename_selection_range.end > old_name.len() {
10372 editor.select_all(&SelectAll, cx);
10373 } else {
10374 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10375 s.select_ranges([rename_selection_range]);
10376 });
10377 }
10378 editor
10379 });
10380 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10381 if e == &EditorEvent::Focused {
10382 cx.emit(EditorEvent::FocusedIn)
10383 }
10384 })
10385 .detach();
10386
10387 let write_highlights =
10388 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10389 let read_highlights =
10390 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10391 let ranges = write_highlights
10392 .iter()
10393 .flat_map(|(_, ranges)| ranges.iter())
10394 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10395 .cloned()
10396 .collect();
10397
10398 this.highlight_text::<Rename>(
10399 ranges,
10400 HighlightStyle {
10401 fade_out: Some(0.6),
10402 ..Default::default()
10403 },
10404 cx,
10405 );
10406 let rename_focus_handle = rename_editor.focus_handle(cx);
10407 cx.focus(&rename_focus_handle);
10408 let block_id = this.insert_blocks(
10409 [BlockProperties {
10410 style: BlockStyle::Flex,
10411 placement: BlockPlacement::Below(range.start),
10412 height: 1,
10413 render: Box::new({
10414 let rename_editor = rename_editor.clone();
10415 move |cx: &mut BlockContext| {
10416 let mut text_style = cx.editor_style.text.clone();
10417 if let Some(highlight_style) = old_highlight_id
10418 .and_then(|h| h.style(&cx.editor_style.syntax))
10419 {
10420 text_style = text_style.highlight(highlight_style);
10421 }
10422 div()
10423 .pl(cx.anchor_x)
10424 .child(EditorElement::new(
10425 &rename_editor,
10426 EditorStyle {
10427 background: cx.theme().system().transparent,
10428 local_player: cx.editor_style.local_player,
10429 text: text_style,
10430 scrollbar_width: cx.editor_style.scrollbar_width,
10431 syntax: cx.editor_style.syntax.clone(),
10432 status: cx.editor_style.status.clone(),
10433 inlay_hints_style: HighlightStyle {
10434 font_weight: Some(FontWeight::BOLD),
10435 ..make_inlay_hints_style(cx)
10436 },
10437 suggestions_style: HighlightStyle {
10438 color: Some(cx.theme().status().predictive),
10439 ..HighlightStyle::default()
10440 },
10441 ..EditorStyle::default()
10442 },
10443 ))
10444 .into_any_element()
10445 }
10446 }),
10447 priority: 0,
10448 }],
10449 Some(Autoscroll::fit()),
10450 cx,
10451 )[0];
10452 this.pending_rename = Some(RenameState {
10453 range,
10454 old_name,
10455 editor: rename_editor,
10456 block_id,
10457 });
10458 })?;
10459 }
10460
10461 Ok(())
10462 }))
10463 }
10464
10465 pub fn confirm_rename(
10466 &mut self,
10467 _: &ConfirmRename,
10468 cx: &mut ViewContext<Self>,
10469 ) -> Option<Task<Result<()>>> {
10470 let rename = self.take_rename(false, cx)?;
10471 let workspace = self.workspace()?.downgrade();
10472 let (buffer, start) = self
10473 .buffer
10474 .read(cx)
10475 .text_anchor_for_position(rename.range.start, cx)?;
10476 let (end_buffer, _) = self
10477 .buffer
10478 .read(cx)
10479 .text_anchor_for_position(rename.range.end, cx)?;
10480 if buffer != end_buffer {
10481 return None;
10482 }
10483
10484 let old_name = rename.old_name;
10485 let new_name = rename.editor.read(cx).text(cx);
10486
10487 let rename = self.semantics_provider.as_ref()?.perform_rename(
10488 &buffer,
10489 start,
10490 new_name.clone(),
10491 cx,
10492 )?;
10493
10494 Some(cx.spawn(|editor, mut cx| async move {
10495 let project_transaction = rename.await?;
10496 Self::open_project_transaction(
10497 &editor,
10498 workspace,
10499 project_transaction,
10500 format!("Rename: {} → {}", old_name, new_name),
10501 cx.clone(),
10502 )
10503 .await?;
10504
10505 editor.update(&mut cx, |editor, cx| {
10506 editor.refresh_document_highlights(cx);
10507 })?;
10508 Ok(())
10509 }))
10510 }
10511
10512 fn take_rename(
10513 &mut self,
10514 moving_cursor: bool,
10515 cx: &mut ViewContext<Self>,
10516 ) -> Option<RenameState> {
10517 let rename = self.pending_rename.take()?;
10518 if rename.editor.focus_handle(cx).is_focused(cx) {
10519 cx.focus(&self.focus_handle);
10520 }
10521
10522 self.remove_blocks(
10523 [rename.block_id].into_iter().collect(),
10524 Some(Autoscroll::fit()),
10525 cx,
10526 );
10527 self.clear_highlights::<Rename>(cx);
10528 self.show_local_selections = true;
10529
10530 if moving_cursor {
10531 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10532 editor.selections.newest::<usize>(cx).head()
10533 });
10534
10535 // Update the selection to match the position of the selection inside
10536 // the rename editor.
10537 let snapshot = self.buffer.read(cx).read(cx);
10538 let rename_range = rename.range.to_offset(&snapshot);
10539 let cursor_in_editor = snapshot
10540 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10541 .min(rename_range.end);
10542 drop(snapshot);
10543
10544 self.change_selections(None, cx, |s| {
10545 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10546 });
10547 } else {
10548 self.refresh_document_highlights(cx);
10549 }
10550
10551 Some(rename)
10552 }
10553
10554 pub fn pending_rename(&self) -> Option<&RenameState> {
10555 self.pending_rename.as_ref()
10556 }
10557
10558 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10559 let project = match &self.project {
10560 Some(project) => project.clone(),
10561 None => return None,
10562 };
10563
10564 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10565 }
10566
10567 fn format_selections(
10568 &mut self,
10569 _: &FormatSelections,
10570 cx: &mut ViewContext<Self>,
10571 ) -> Option<Task<Result<()>>> {
10572 let project = match &self.project {
10573 Some(project) => project.clone(),
10574 None => return None,
10575 };
10576
10577 let selections = self
10578 .selections
10579 .all_adjusted(cx)
10580 .into_iter()
10581 .filter(|s| !s.is_empty())
10582 .collect_vec();
10583
10584 Some(self.perform_format(
10585 project,
10586 FormatTrigger::Manual,
10587 FormatTarget::Ranges(selections),
10588 cx,
10589 ))
10590 }
10591
10592 fn perform_format(
10593 &mut self,
10594 project: Model<Project>,
10595 trigger: FormatTrigger,
10596 target: FormatTarget,
10597 cx: &mut ViewContext<Self>,
10598 ) -> Task<Result<()>> {
10599 let buffer = self.buffer().clone();
10600 let mut buffers = buffer.read(cx).all_buffers();
10601 if trigger == FormatTrigger::Save {
10602 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10603 }
10604
10605 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10606 let format = project.update(cx, |project, cx| {
10607 project.format(buffers, true, trigger, target, cx)
10608 });
10609
10610 cx.spawn(|_, mut cx| async move {
10611 let transaction = futures::select_biased! {
10612 () = timeout => {
10613 log::warn!("timed out waiting for formatting");
10614 None
10615 }
10616 transaction = format.log_err().fuse() => transaction,
10617 };
10618
10619 buffer
10620 .update(&mut cx, |buffer, cx| {
10621 if let Some(transaction) = transaction {
10622 if !buffer.is_singleton() {
10623 buffer.push_transaction(&transaction.0, cx);
10624 }
10625 }
10626
10627 cx.notify();
10628 })
10629 .ok();
10630
10631 Ok(())
10632 })
10633 }
10634
10635 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10636 if let Some(project) = self.project.clone() {
10637 self.buffer.update(cx, |multi_buffer, cx| {
10638 project.update(cx, |project, cx| {
10639 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10640 });
10641 })
10642 }
10643 }
10644
10645 fn cancel_language_server_work(
10646 &mut self,
10647 _: &actions::CancelLanguageServerWork,
10648 cx: &mut ViewContext<Self>,
10649 ) {
10650 if let Some(project) = self.project.clone() {
10651 self.buffer.update(cx, |multi_buffer, cx| {
10652 project.update(cx, |project, cx| {
10653 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10654 });
10655 })
10656 }
10657 }
10658
10659 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10660 cx.show_character_palette();
10661 }
10662
10663 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10664 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10665 let buffer = self.buffer.read(cx).snapshot(cx);
10666 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10667 let is_valid = buffer
10668 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10669 .any(|entry| {
10670 entry.diagnostic.is_primary
10671 && !entry.range.is_empty()
10672 && entry.range.start == primary_range_start
10673 && entry.diagnostic.message == active_diagnostics.primary_message
10674 });
10675
10676 if is_valid != active_diagnostics.is_valid {
10677 active_diagnostics.is_valid = is_valid;
10678 let mut new_styles = HashMap::default();
10679 for (block_id, diagnostic) in &active_diagnostics.blocks {
10680 new_styles.insert(
10681 *block_id,
10682 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10683 );
10684 }
10685 self.display_map.update(cx, |display_map, _cx| {
10686 display_map.replace_blocks(new_styles)
10687 });
10688 }
10689 }
10690 }
10691
10692 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10693 self.dismiss_diagnostics(cx);
10694 let snapshot = self.snapshot(cx);
10695 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10696 let buffer = self.buffer.read(cx).snapshot(cx);
10697
10698 let mut primary_range = None;
10699 let mut primary_message = None;
10700 let mut group_end = Point::zero();
10701 let diagnostic_group = buffer
10702 .diagnostic_group::<MultiBufferPoint>(group_id)
10703 .filter_map(|entry| {
10704 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10705 && (entry.range.start.row == entry.range.end.row
10706 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10707 {
10708 return None;
10709 }
10710 if entry.range.end > group_end {
10711 group_end = entry.range.end;
10712 }
10713 if entry.diagnostic.is_primary {
10714 primary_range = Some(entry.range.clone());
10715 primary_message = Some(entry.diagnostic.message.clone());
10716 }
10717 Some(entry)
10718 })
10719 .collect::<Vec<_>>();
10720 let primary_range = primary_range?;
10721 let primary_message = primary_message?;
10722 let primary_range =
10723 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10724
10725 let blocks = display_map
10726 .insert_blocks(
10727 diagnostic_group.iter().map(|entry| {
10728 let diagnostic = entry.diagnostic.clone();
10729 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10730 BlockProperties {
10731 style: BlockStyle::Fixed,
10732 placement: BlockPlacement::Below(
10733 buffer.anchor_after(entry.range.start),
10734 ),
10735 height: message_height,
10736 render: diagnostic_block_renderer(diagnostic, None, true, true),
10737 priority: 0,
10738 }
10739 }),
10740 cx,
10741 )
10742 .into_iter()
10743 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10744 .collect();
10745
10746 Some(ActiveDiagnosticGroup {
10747 primary_range,
10748 primary_message,
10749 group_id,
10750 blocks,
10751 is_valid: true,
10752 })
10753 });
10754 self.active_diagnostics.is_some()
10755 }
10756
10757 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10758 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10759 self.display_map.update(cx, |display_map, cx| {
10760 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10761 });
10762 cx.notify();
10763 }
10764 }
10765
10766 pub fn set_selections_from_remote(
10767 &mut self,
10768 selections: Vec<Selection<Anchor>>,
10769 pending_selection: Option<Selection<Anchor>>,
10770 cx: &mut ViewContext<Self>,
10771 ) {
10772 let old_cursor_position = self.selections.newest_anchor().head();
10773 self.selections.change_with(cx, |s| {
10774 s.select_anchors(selections);
10775 if let Some(pending_selection) = pending_selection {
10776 s.set_pending(pending_selection, SelectMode::Character);
10777 } else {
10778 s.clear_pending();
10779 }
10780 });
10781 self.selections_did_change(false, &old_cursor_position, true, cx);
10782 }
10783
10784 fn push_to_selection_history(&mut self) {
10785 self.selection_history.push(SelectionHistoryEntry {
10786 selections: self.selections.disjoint_anchors(),
10787 select_next_state: self.select_next_state.clone(),
10788 select_prev_state: self.select_prev_state.clone(),
10789 add_selections_state: self.add_selections_state.clone(),
10790 });
10791 }
10792
10793 pub fn transact(
10794 &mut self,
10795 cx: &mut ViewContext<Self>,
10796 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10797 ) -> Option<TransactionId> {
10798 self.start_transaction_at(Instant::now(), cx);
10799 update(self, cx);
10800 self.end_transaction_at(Instant::now(), cx)
10801 }
10802
10803 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10804 self.end_selection(cx);
10805 if let Some(tx_id) = self
10806 .buffer
10807 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10808 {
10809 self.selection_history
10810 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10811 cx.emit(EditorEvent::TransactionBegun {
10812 transaction_id: tx_id,
10813 })
10814 }
10815 }
10816
10817 fn end_transaction_at(
10818 &mut self,
10819 now: Instant,
10820 cx: &mut ViewContext<Self>,
10821 ) -> Option<TransactionId> {
10822 if let Some(transaction_id) = self
10823 .buffer
10824 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10825 {
10826 if let Some((_, end_selections)) =
10827 self.selection_history.transaction_mut(transaction_id)
10828 {
10829 *end_selections = Some(self.selections.disjoint_anchors());
10830 } else {
10831 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10832 }
10833
10834 cx.emit(EditorEvent::Edited { transaction_id });
10835 Some(transaction_id)
10836 } else {
10837 None
10838 }
10839 }
10840
10841 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10842 let selection = self.selections.newest::<Point>(cx);
10843
10844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10845 let range = if selection.is_empty() {
10846 let point = selection.head().to_display_point(&display_map);
10847 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10848 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10849 .to_point(&display_map);
10850 start..end
10851 } else {
10852 selection.range()
10853 };
10854 if display_map.folds_in_range(range).next().is_some() {
10855 self.unfold_lines(&Default::default(), cx)
10856 } else {
10857 self.fold(&Default::default(), cx)
10858 }
10859 }
10860
10861 pub fn toggle_fold_recursive(
10862 &mut self,
10863 _: &actions::ToggleFoldRecursive,
10864 cx: &mut ViewContext<Self>,
10865 ) {
10866 let selection = self.selections.newest::<Point>(cx);
10867
10868 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10869 let range = if selection.is_empty() {
10870 let point = selection.head().to_display_point(&display_map);
10871 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10872 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10873 .to_point(&display_map);
10874 start..end
10875 } else {
10876 selection.range()
10877 };
10878 if display_map.folds_in_range(range).next().is_some() {
10879 self.unfold_recursive(&Default::default(), cx)
10880 } else {
10881 self.fold_recursive(&Default::default(), cx)
10882 }
10883 }
10884
10885 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10886 let mut fold_ranges = Vec::new();
10887 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10888 let selections = self.selections.all_adjusted(cx);
10889
10890 for selection in selections {
10891 let range = selection.range().sorted();
10892 let buffer_start_row = range.start.row;
10893
10894 if range.start.row != range.end.row {
10895 let mut found = false;
10896 let mut row = range.start.row;
10897 while row <= range.end.row {
10898 if let Some((foldable_range, fold_text)) =
10899 { display_map.foldable_range(MultiBufferRow(row)) }
10900 {
10901 found = true;
10902 row = foldable_range.end.row + 1;
10903 fold_ranges.push((foldable_range, fold_text));
10904 } else {
10905 row += 1
10906 }
10907 }
10908 if found {
10909 continue;
10910 }
10911 }
10912
10913 for row in (0..=range.start.row).rev() {
10914 if let Some((foldable_range, fold_text)) =
10915 display_map.foldable_range(MultiBufferRow(row))
10916 {
10917 if foldable_range.end.row >= buffer_start_row {
10918 fold_ranges.push((foldable_range, fold_text));
10919 if row <= range.start.row {
10920 break;
10921 }
10922 }
10923 }
10924 }
10925 }
10926
10927 self.fold_ranges(fold_ranges, true, cx);
10928 }
10929
10930 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10931 let fold_at_level = fold_at.level;
10932 let snapshot = self.buffer.read(cx).snapshot(cx);
10933 let mut fold_ranges = Vec::new();
10934 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10935
10936 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10937 while start_row < end_row {
10938 match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10939 Some(foldable_range) => {
10940 let nested_start_row = foldable_range.0.start.row + 1;
10941 let nested_end_row = foldable_range.0.end.row;
10942
10943 if current_level < fold_at_level {
10944 stack.push((nested_start_row, nested_end_row, current_level + 1));
10945 } else if current_level == fold_at_level {
10946 fold_ranges.push(foldable_range);
10947 }
10948
10949 start_row = nested_end_row + 1;
10950 }
10951 None => start_row += 1,
10952 }
10953 }
10954 }
10955
10956 self.fold_ranges(fold_ranges, true, cx);
10957 }
10958
10959 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10960 let mut fold_ranges = Vec::new();
10961 let snapshot = self.buffer.read(cx).snapshot(cx);
10962
10963 for row in 0..snapshot.max_buffer_row().0 {
10964 if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10965 fold_ranges.push(foldable_range);
10966 }
10967 }
10968
10969 self.fold_ranges(fold_ranges, true, cx);
10970 }
10971
10972 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10973 let mut fold_ranges = Vec::new();
10974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10975 let selections = self.selections.all_adjusted(cx);
10976
10977 for selection in selections {
10978 let range = selection.range().sorted();
10979 let buffer_start_row = range.start.row;
10980
10981 if range.start.row != range.end.row {
10982 let mut found = false;
10983 for row in range.start.row..=range.end.row {
10984 if let Some((foldable_range, fold_text)) =
10985 { display_map.foldable_range(MultiBufferRow(row)) }
10986 {
10987 found = true;
10988 fold_ranges.push((foldable_range, fold_text));
10989 }
10990 }
10991 if found {
10992 continue;
10993 }
10994 }
10995
10996 for row in (0..=range.start.row).rev() {
10997 if let Some((foldable_range, fold_text)) =
10998 display_map.foldable_range(MultiBufferRow(row))
10999 {
11000 if foldable_range.end.row >= buffer_start_row {
11001 fold_ranges.push((foldable_range, fold_text));
11002 } else {
11003 break;
11004 }
11005 }
11006 }
11007 }
11008
11009 self.fold_ranges(fold_ranges, true, cx);
11010 }
11011
11012 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11013 let buffer_row = fold_at.buffer_row;
11014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11015
11016 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
11017 let autoscroll = self
11018 .selections
11019 .all::<Point>(cx)
11020 .iter()
11021 .any(|selection| fold_range.overlaps(&selection.range()));
11022
11023 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
11024 }
11025 }
11026
11027 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11028 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11029 let buffer = &display_map.buffer_snapshot;
11030 let selections = self.selections.all::<Point>(cx);
11031 let ranges = selections
11032 .iter()
11033 .map(|s| {
11034 let range = s.display_range(&display_map).sorted();
11035 let mut start = range.start.to_point(&display_map);
11036 let mut end = range.end.to_point(&display_map);
11037 start.column = 0;
11038 end.column = buffer.line_len(MultiBufferRow(end.row));
11039 start..end
11040 })
11041 .collect::<Vec<_>>();
11042
11043 self.unfold_ranges(&ranges, true, true, cx);
11044 }
11045
11046 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11047 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11048 let selections = self.selections.all::<Point>(cx);
11049 let ranges = selections
11050 .iter()
11051 .map(|s| {
11052 let mut range = s.display_range(&display_map).sorted();
11053 *range.start.column_mut() = 0;
11054 *range.end.column_mut() = display_map.line_len(range.end.row());
11055 let start = range.start.to_point(&display_map);
11056 let end = range.end.to_point(&display_map);
11057 start..end
11058 })
11059 .collect::<Vec<_>>();
11060
11061 self.unfold_ranges(&ranges, true, true, cx);
11062 }
11063
11064 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11065 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11066
11067 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11068 ..Point::new(
11069 unfold_at.buffer_row.0,
11070 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11071 );
11072
11073 let autoscroll = self
11074 .selections
11075 .all::<Point>(cx)
11076 .iter()
11077 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11078
11079 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11080 }
11081
11082 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11083 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11084 self.unfold_ranges(
11085 &[Point::zero()..display_map.max_point().to_point(&display_map)],
11086 true,
11087 true,
11088 cx,
11089 );
11090 }
11091
11092 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11093 let selections = self.selections.all::<Point>(cx);
11094 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11095 let line_mode = self.selections.line_mode;
11096 let ranges = selections.into_iter().map(|s| {
11097 if line_mode {
11098 let start = Point::new(s.start.row, 0);
11099 let end = Point::new(
11100 s.end.row,
11101 display_map
11102 .buffer_snapshot
11103 .line_len(MultiBufferRow(s.end.row)),
11104 );
11105 (start..end, display_map.fold_placeholder.clone())
11106 } else {
11107 (s.start..s.end, display_map.fold_placeholder.clone())
11108 }
11109 });
11110 self.fold_ranges(ranges, true, cx);
11111 }
11112
11113 pub fn fold_ranges<T: ToOffset + Clone>(
11114 &mut self,
11115 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11116 auto_scroll: bool,
11117 cx: &mut ViewContext<Self>,
11118 ) {
11119 let mut fold_ranges = Vec::new();
11120 let mut buffers_affected = HashMap::default();
11121 let multi_buffer = self.buffer().read(cx);
11122 for (fold_range, fold_text) in ranges {
11123 if let Some((_, buffer, _)) =
11124 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11125 {
11126 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11127 };
11128 fold_ranges.push((fold_range, fold_text));
11129 }
11130
11131 let mut ranges = fold_ranges.into_iter().peekable();
11132 if ranges.peek().is_some() {
11133 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11134
11135 if auto_scroll {
11136 self.request_autoscroll(Autoscroll::fit(), cx);
11137 }
11138
11139 for buffer in buffers_affected.into_values() {
11140 self.sync_expanded_diff_hunks(buffer, cx);
11141 }
11142
11143 cx.notify();
11144
11145 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11146 // Clear diagnostics block when folding a range that contains it.
11147 let snapshot = self.snapshot(cx);
11148 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11149 drop(snapshot);
11150 self.active_diagnostics = Some(active_diagnostics);
11151 self.dismiss_diagnostics(cx);
11152 } else {
11153 self.active_diagnostics = Some(active_diagnostics);
11154 }
11155 }
11156
11157 self.scrollbar_marker_state.dirty = true;
11158 }
11159 }
11160
11161 /// Removes any folds whose ranges intersect any of the given ranges.
11162 pub fn unfold_ranges<T: ToOffset + Clone>(
11163 &mut self,
11164 ranges: &[Range<T>],
11165 inclusive: bool,
11166 auto_scroll: bool,
11167 cx: &mut ViewContext<Self>,
11168 ) {
11169 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11170 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11171 });
11172 }
11173
11174 /// Removes any folds with the given ranges.
11175 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11176 &mut self,
11177 ranges: &[Range<T>],
11178 type_id: TypeId,
11179 auto_scroll: bool,
11180 cx: &mut ViewContext<Self>,
11181 ) {
11182 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11183 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11184 });
11185 }
11186
11187 fn remove_folds_with<T: ToOffset + Clone>(
11188 &mut self,
11189 ranges: &[Range<T>],
11190 auto_scroll: bool,
11191 cx: &mut ViewContext<Self>,
11192 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11193 ) {
11194 if ranges.is_empty() {
11195 return;
11196 }
11197
11198 let mut buffers_affected = HashMap::default();
11199 let multi_buffer = self.buffer().read(cx);
11200 for range in ranges {
11201 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11202 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11203 };
11204 }
11205
11206 self.display_map.update(cx, update);
11207 if auto_scroll {
11208 self.request_autoscroll(Autoscroll::fit(), cx);
11209 }
11210
11211 for buffer in buffers_affected.into_values() {
11212 self.sync_expanded_diff_hunks(buffer, cx);
11213 }
11214
11215 cx.notify();
11216 self.scrollbar_marker_state.dirty = true;
11217 self.active_indent_guides_state.dirty = true;
11218 }
11219
11220 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11221 self.display_map.read(cx).fold_placeholder.clone()
11222 }
11223
11224 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11225 if hovered != self.gutter_hovered {
11226 self.gutter_hovered = hovered;
11227 cx.notify();
11228 }
11229 }
11230
11231 pub fn insert_blocks(
11232 &mut self,
11233 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11234 autoscroll: Option<Autoscroll>,
11235 cx: &mut ViewContext<Self>,
11236 ) -> Vec<CustomBlockId> {
11237 let blocks = self
11238 .display_map
11239 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11240 if let Some(autoscroll) = autoscroll {
11241 self.request_autoscroll(autoscroll, cx);
11242 }
11243 cx.notify();
11244 blocks
11245 }
11246
11247 pub fn resize_blocks(
11248 &mut self,
11249 heights: HashMap<CustomBlockId, u32>,
11250 autoscroll: Option<Autoscroll>,
11251 cx: &mut ViewContext<Self>,
11252 ) {
11253 self.display_map
11254 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11255 if let Some(autoscroll) = autoscroll {
11256 self.request_autoscroll(autoscroll, cx);
11257 }
11258 cx.notify();
11259 }
11260
11261 pub fn replace_blocks(
11262 &mut self,
11263 renderers: HashMap<CustomBlockId, RenderBlock>,
11264 autoscroll: Option<Autoscroll>,
11265 cx: &mut ViewContext<Self>,
11266 ) {
11267 self.display_map
11268 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11269 if let Some(autoscroll) = autoscroll {
11270 self.request_autoscroll(autoscroll, cx);
11271 }
11272 cx.notify();
11273 }
11274
11275 pub fn remove_blocks(
11276 &mut self,
11277 block_ids: HashSet<CustomBlockId>,
11278 autoscroll: Option<Autoscroll>,
11279 cx: &mut ViewContext<Self>,
11280 ) {
11281 self.display_map.update(cx, |display_map, cx| {
11282 display_map.remove_blocks(block_ids, cx)
11283 });
11284 if let Some(autoscroll) = autoscroll {
11285 self.request_autoscroll(autoscroll, cx);
11286 }
11287 cx.notify();
11288 }
11289
11290 pub fn row_for_block(
11291 &self,
11292 block_id: CustomBlockId,
11293 cx: &mut ViewContext<Self>,
11294 ) -> Option<DisplayRow> {
11295 self.display_map
11296 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11297 }
11298
11299 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11300 self.focused_block = Some(focused_block);
11301 }
11302
11303 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11304 self.focused_block.take()
11305 }
11306
11307 pub fn insert_creases(
11308 &mut self,
11309 creases: impl IntoIterator<Item = Crease>,
11310 cx: &mut ViewContext<Self>,
11311 ) -> Vec<CreaseId> {
11312 self.display_map
11313 .update(cx, |map, cx| map.insert_creases(creases, cx))
11314 }
11315
11316 pub fn remove_creases(
11317 &mut self,
11318 ids: impl IntoIterator<Item = CreaseId>,
11319 cx: &mut ViewContext<Self>,
11320 ) {
11321 self.display_map
11322 .update(cx, |map, cx| map.remove_creases(ids, cx));
11323 }
11324
11325 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11326 self.display_map
11327 .update(cx, |map, cx| map.snapshot(cx))
11328 .longest_row()
11329 }
11330
11331 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11332 self.display_map
11333 .update(cx, |map, cx| map.snapshot(cx))
11334 .max_point()
11335 }
11336
11337 pub fn text(&self, cx: &AppContext) -> String {
11338 self.buffer.read(cx).read(cx).text()
11339 }
11340
11341 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11342 let text = self.text(cx);
11343 let text = text.trim();
11344
11345 if text.is_empty() {
11346 return None;
11347 }
11348
11349 Some(text.to_string())
11350 }
11351
11352 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11353 self.transact(cx, |this, cx| {
11354 this.buffer
11355 .read(cx)
11356 .as_singleton()
11357 .expect("you can only call set_text on editors for singleton buffers")
11358 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11359 });
11360 }
11361
11362 pub fn display_text(&self, cx: &mut AppContext) -> String {
11363 self.display_map
11364 .update(cx, |map, cx| map.snapshot(cx))
11365 .text()
11366 }
11367
11368 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11369 let mut wrap_guides = smallvec::smallvec![];
11370
11371 if self.show_wrap_guides == Some(false) {
11372 return wrap_guides;
11373 }
11374
11375 let settings = self.buffer.read(cx).settings_at(0, cx);
11376 if settings.show_wrap_guides {
11377 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11378 wrap_guides.push((soft_wrap as usize, true));
11379 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11380 wrap_guides.push((soft_wrap as usize, true));
11381 }
11382 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11383 }
11384
11385 wrap_guides
11386 }
11387
11388 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11389 let settings = self.buffer.read(cx).settings_at(0, cx);
11390 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11391 match mode {
11392 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11393 SoftWrap::None
11394 }
11395 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11396 language_settings::SoftWrap::PreferredLineLength => {
11397 SoftWrap::Column(settings.preferred_line_length)
11398 }
11399 language_settings::SoftWrap::Bounded => {
11400 SoftWrap::Bounded(settings.preferred_line_length)
11401 }
11402 }
11403 }
11404
11405 pub fn set_soft_wrap_mode(
11406 &mut self,
11407 mode: language_settings::SoftWrap,
11408 cx: &mut ViewContext<Self>,
11409 ) {
11410 self.soft_wrap_mode_override = Some(mode);
11411 cx.notify();
11412 }
11413
11414 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11415 self.text_style_refinement = Some(style);
11416 }
11417
11418 /// called by the Element so we know what style we were most recently rendered with.
11419 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11420 let rem_size = cx.rem_size();
11421 self.display_map.update(cx, |map, cx| {
11422 map.set_font(
11423 style.text.font(),
11424 style.text.font_size.to_pixels(rem_size),
11425 cx,
11426 )
11427 });
11428 self.style = Some(style);
11429 }
11430
11431 pub fn style(&self) -> Option<&EditorStyle> {
11432 self.style.as_ref()
11433 }
11434
11435 // Called by the element. This method is not designed to be called outside of the editor
11436 // element's layout code because it does not notify when rewrapping is computed synchronously.
11437 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11438 self.display_map
11439 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11440 }
11441
11442 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11443 if self.soft_wrap_mode_override.is_some() {
11444 self.soft_wrap_mode_override.take();
11445 } else {
11446 let soft_wrap = match self.soft_wrap_mode(cx) {
11447 SoftWrap::GitDiff => return,
11448 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11449 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11450 language_settings::SoftWrap::None
11451 }
11452 };
11453 self.soft_wrap_mode_override = Some(soft_wrap);
11454 }
11455 cx.notify();
11456 }
11457
11458 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11459 let Some(workspace) = self.workspace() else {
11460 return;
11461 };
11462 let fs = workspace.read(cx).app_state().fs.clone();
11463 let current_show = TabBarSettings::get_global(cx).show;
11464 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11465 setting.show = Some(!current_show);
11466 });
11467 }
11468
11469 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11470 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11471 self.buffer
11472 .read(cx)
11473 .settings_at(0, cx)
11474 .indent_guides
11475 .enabled
11476 });
11477 self.show_indent_guides = Some(!currently_enabled);
11478 cx.notify();
11479 }
11480
11481 fn should_show_indent_guides(&self) -> Option<bool> {
11482 self.show_indent_guides
11483 }
11484
11485 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11486 let mut editor_settings = EditorSettings::get_global(cx).clone();
11487 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11488 EditorSettings::override_global(editor_settings, cx);
11489 }
11490
11491 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11492 self.use_relative_line_numbers
11493 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11494 }
11495
11496 pub fn toggle_relative_line_numbers(
11497 &mut self,
11498 _: &ToggleRelativeLineNumbers,
11499 cx: &mut ViewContext<Self>,
11500 ) {
11501 let is_relative = self.should_use_relative_line_numbers(cx);
11502 self.set_relative_line_number(Some(!is_relative), cx)
11503 }
11504
11505 pub fn set_relative_line_number(
11506 &mut self,
11507 is_relative: Option<bool>,
11508 cx: &mut ViewContext<Self>,
11509 ) {
11510 self.use_relative_line_numbers = is_relative;
11511 cx.notify();
11512 }
11513
11514 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11515 self.show_gutter = show_gutter;
11516 cx.notify();
11517 }
11518
11519 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11520 self.show_line_numbers = Some(show_line_numbers);
11521 cx.notify();
11522 }
11523
11524 pub fn set_show_git_diff_gutter(
11525 &mut self,
11526 show_git_diff_gutter: bool,
11527 cx: &mut ViewContext<Self>,
11528 ) {
11529 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11530 cx.notify();
11531 }
11532
11533 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11534 self.show_code_actions = Some(show_code_actions);
11535 cx.notify();
11536 }
11537
11538 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11539 self.show_runnables = Some(show_runnables);
11540 cx.notify();
11541 }
11542
11543 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11544 if self.display_map.read(cx).masked != masked {
11545 self.display_map.update(cx, |map, _| map.masked = masked);
11546 }
11547 cx.notify()
11548 }
11549
11550 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11551 self.show_wrap_guides = Some(show_wrap_guides);
11552 cx.notify();
11553 }
11554
11555 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11556 self.show_indent_guides = Some(show_indent_guides);
11557 cx.notify();
11558 }
11559
11560 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11561 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11562 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11563 if let Some(dir) = file.abs_path(cx).parent() {
11564 return Some(dir.to_owned());
11565 }
11566 }
11567
11568 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11569 return Some(project_path.path.to_path_buf());
11570 }
11571 }
11572
11573 None
11574 }
11575
11576 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11577 self.active_excerpt(cx)?
11578 .1
11579 .read(cx)
11580 .file()
11581 .and_then(|f| f.as_local())
11582 }
11583
11584 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11585 if let Some(target) = self.target_file(cx) {
11586 cx.reveal_path(&target.abs_path(cx));
11587 }
11588 }
11589
11590 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11591 if let Some(file) = self.target_file(cx) {
11592 if let Some(path) = file.abs_path(cx).to_str() {
11593 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11594 }
11595 }
11596 }
11597
11598 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11599 if let Some(file) = self.target_file(cx) {
11600 if let Some(path) = file.path().to_str() {
11601 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11602 }
11603 }
11604 }
11605
11606 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11607 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11608
11609 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11610 self.start_git_blame(true, cx);
11611 }
11612
11613 cx.notify();
11614 }
11615
11616 pub fn toggle_git_blame_inline(
11617 &mut self,
11618 _: &ToggleGitBlameInline,
11619 cx: &mut ViewContext<Self>,
11620 ) {
11621 self.toggle_git_blame_inline_internal(true, cx);
11622 cx.notify();
11623 }
11624
11625 pub fn git_blame_inline_enabled(&self) -> bool {
11626 self.git_blame_inline_enabled
11627 }
11628
11629 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11630 self.show_selection_menu = self
11631 .show_selection_menu
11632 .map(|show_selections_menu| !show_selections_menu)
11633 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11634
11635 cx.notify();
11636 }
11637
11638 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11639 self.show_selection_menu
11640 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11641 }
11642
11643 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11644 if let Some(project) = self.project.as_ref() {
11645 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11646 return;
11647 };
11648
11649 if buffer.read(cx).file().is_none() {
11650 return;
11651 }
11652
11653 let focused = self.focus_handle(cx).contains_focused(cx);
11654
11655 let project = project.clone();
11656 let blame =
11657 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11658 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11659 self.blame = Some(blame);
11660 }
11661 }
11662
11663 fn toggle_git_blame_inline_internal(
11664 &mut self,
11665 user_triggered: bool,
11666 cx: &mut ViewContext<Self>,
11667 ) {
11668 if self.git_blame_inline_enabled {
11669 self.git_blame_inline_enabled = false;
11670 self.show_git_blame_inline = false;
11671 self.show_git_blame_inline_delay_task.take();
11672 } else {
11673 self.git_blame_inline_enabled = true;
11674 self.start_git_blame_inline(user_triggered, cx);
11675 }
11676
11677 cx.notify();
11678 }
11679
11680 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11681 self.start_git_blame(user_triggered, cx);
11682
11683 if ProjectSettings::get_global(cx)
11684 .git
11685 .inline_blame_delay()
11686 .is_some()
11687 {
11688 self.start_inline_blame_timer(cx);
11689 } else {
11690 self.show_git_blame_inline = true
11691 }
11692 }
11693
11694 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11695 self.blame.as_ref()
11696 }
11697
11698 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11699 self.show_git_blame_gutter && self.has_blame_entries(cx)
11700 }
11701
11702 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11703 self.show_git_blame_inline
11704 && self.focus_handle.is_focused(cx)
11705 && !self.newest_selection_head_on_empty_line(cx)
11706 && self.has_blame_entries(cx)
11707 }
11708
11709 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11710 self.blame()
11711 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11712 }
11713
11714 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11715 let cursor_anchor = self.selections.newest_anchor().head();
11716
11717 let snapshot = self.buffer.read(cx).snapshot(cx);
11718 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11719
11720 snapshot.line_len(buffer_row) == 0
11721 }
11722
11723 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11724 let buffer_and_selection = maybe!({
11725 let selection = self.selections.newest::<Point>(cx);
11726 let selection_range = selection.range();
11727
11728 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11729 (buffer, selection_range.start.row..selection_range.end.row)
11730 } else {
11731 let buffer_ranges = self
11732 .buffer()
11733 .read(cx)
11734 .range_to_buffer_ranges(selection_range, cx);
11735
11736 let (buffer, range, _) = if selection.reversed {
11737 buffer_ranges.first()
11738 } else {
11739 buffer_ranges.last()
11740 }?;
11741
11742 let snapshot = buffer.read(cx).snapshot();
11743 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11744 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11745 (buffer.clone(), selection)
11746 };
11747
11748 Some((buffer, selection))
11749 });
11750
11751 let Some((buffer, selection)) = buffer_and_selection else {
11752 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11753 };
11754
11755 let Some(project) = self.project.as_ref() else {
11756 return Task::ready(Err(anyhow!("editor does not have project")));
11757 };
11758
11759 project.update(cx, |project, cx| {
11760 project.get_permalink_to_line(&buffer, selection, cx)
11761 })
11762 }
11763
11764 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11765 let permalink_task = self.get_permalink_to_line(cx);
11766 let workspace = self.workspace();
11767
11768 cx.spawn(|_, mut cx| async move {
11769 match permalink_task.await {
11770 Ok(permalink) => {
11771 cx.update(|cx| {
11772 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11773 })
11774 .ok();
11775 }
11776 Err(err) => {
11777 let message = format!("Failed to copy permalink: {err}");
11778
11779 Err::<(), anyhow::Error>(err).log_err();
11780
11781 if let Some(workspace) = workspace {
11782 workspace
11783 .update(&mut cx, |workspace, cx| {
11784 struct CopyPermalinkToLine;
11785
11786 workspace.show_toast(
11787 Toast::new(
11788 NotificationId::unique::<CopyPermalinkToLine>(),
11789 message,
11790 ),
11791 cx,
11792 )
11793 })
11794 .ok();
11795 }
11796 }
11797 }
11798 })
11799 .detach();
11800 }
11801
11802 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11803 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11804 if let Some(file) = self.target_file(cx) {
11805 if let Some(path) = file.path().to_str() {
11806 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11807 }
11808 }
11809 }
11810
11811 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11812 let permalink_task = self.get_permalink_to_line(cx);
11813 let workspace = self.workspace();
11814
11815 cx.spawn(|_, mut cx| async move {
11816 match permalink_task.await {
11817 Ok(permalink) => {
11818 cx.update(|cx| {
11819 cx.open_url(permalink.as_ref());
11820 })
11821 .ok();
11822 }
11823 Err(err) => {
11824 let message = format!("Failed to open permalink: {err}");
11825
11826 Err::<(), anyhow::Error>(err).log_err();
11827
11828 if let Some(workspace) = workspace {
11829 workspace
11830 .update(&mut cx, |workspace, cx| {
11831 struct OpenPermalinkToLine;
11832
11833 workspace.show_toast(
11834 Toast::new(
11835 NotificationId::unique::<OpenPermalinkToLine>(),
11836 message,
11837 ),
11838 cx,
11839 )
11840 })
11841 .ok();
11842 }
11843 }
11844 }
11845 })
11846 .detach();
11847 }
11848
11849 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11850 /// last highlight added will be used.
11851 ///
11852 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11853 pub fn highlight_rows<T: 'static>(
11854 &mut self,
11855 range: Range<Anchor>,
11856 color: Hsla,
11857 should_autoscroll: bool,
11858 cx: &mut ViewContext<Self>,
11859 ) {
11860 let snapshot = self.buffer().read(cx).snapshot(cx);
11861 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11862 let ix = row_highlights.binary_search_by(|highlight| {
11863 Ordering::Equal
11864 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11865 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11866 });
11867
11868 if let Err(mut ix) = ix {
11869 let index = post_inc(&mut self.highlight_order);
11870
11871 // If this range intersects with the preceding highlight, then merge it with
11872 // the preceding highlight. Otherwise insert a new highlight.
11873 let mut merged = false;
11874 if ix > 0 {
11875 let prev_highlight = &mut row_highlights[ix - 1];
11876 if prev_highlight
11877 .range
11878 .end
11879 .cmp(&range.start, &snapshot)
11880 .is_ge()
11881 {
11882 ix -= 1;
11883 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11884 prev_highlight.range.end = range.end;
11885 }
11886 merged = true;
11887 prev_highlight.index = index;
11888 prev_highlight.color = color;
11889 prev_highlight.should_autoscroll = should_autoscroll;
11890 }
11891 }
11892
11893 if !merged {
11894 row_highlights.insert(
11895 ix,
11896 RowHighlight {
11897 range: range.clone(),
11898 index,
11899 color,
11900 should_autoscroll,
11901 },
11902 );
11903 }
11904
11905 // If any of the following highlights intersect with this one, merge them.
11906 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11907 let highlight = &row_highlights[ix];
11908 if next_highlight
11909 .range
11910 .start
11911 .cmp(&highlight.range.end, &snapshot)
11912 .is_le()
11913 {
11914 if next_highlight
11915 .range
11916 .end
11917 .cmp(&highlight.range.end, &snapshot)
11918 .is_gt()
11919 {
11920 row_highlights[ix].range.end = next_highlight.range.end;
11921 }
11922 row_highlights.remove(ix + 1);
11923 } else {
11924 break;
11925 }
11926 }
11927 }
11928 }
11929
11930 /// Remove any highlighted row ranges of the given type that intersect the
11931 /// given ranges.
11932 pub fn remove_highlighted_rows<T: 'static>(
11933 &mut self,
11934 ranges_to_remove: Vec<Range<Anchor>>,
11935 cx: &mut ViewContext<Self>,
11936 ) {
11937 let snapshot = self.buffer().read(cx).snapshot(cx);
11938 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11939 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11940 row_highlights.retain(|highlight| {
11941 while let Some(range_to_remove) = ranges_to_remove.peek() {
11942 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11943 Ordering::Less | Ordering::Equal => {
11944 ranges_to_remove.next();
11945 }
11946 Ordering::Greater => {
11947 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11948 Ordering::Less | Ordering::Equal => {
11949 return false;
11950 }
11951 Ordering::Greater => break,
11952 }
11953 }
11954 }
11955 }
11956
11957 true
11958 })
11959 }
11960
11961 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11962 pub fn clear_row_highlights<T: 'static>(&mut self) {
11963 self.highlighted_rows.remove(&TypeId::of::<T>());
11964 }
11965
11966 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11967 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11968 self.highlighted_rows
11969 .get(&TypeId::of::<T>())
11970 .map_or(&[] as &[_], |vec| vec.as_slice())
11971 .iter()
11972 .map(|highlight| (highlight.range.clone(), highlight.color))
11973 }
11974
11975 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11976 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11977 /// Allows to ignore certain kinds of highlights.
11978 pub fn highlighted_display_rows(
11979 &mut self,
11980 cx: &mut WindowContext,
11981 ) -> BTreeMap<DisplayRow, Hsla> {
11982 let snapshot = self.snapshot(cx);
11983 let mut used_highlight_orders = HashMap::default();
11984 self.highlighted_rows
11985 .iter()
11986 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11987 .fold(
11988 BTreeMap::<DisplayRow, Hsla>::new(),
11989 |mut unique_rows, highlight| {
11990 let start = highlight.range.start.to_display_point(&snapshot);
11991 let end = highlight.range.end.to_display_point(&snapshot);
11992 let start_row = start.row().0;
11993 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11994 && end.column() == 0
11995 {
11996 end.row().0.saturating_sub(1)
11997 } else {
11998 end.row().0
11999 };
12000 for row in start_row..=end_row {
12001 let used_index =
12002 used_highlight_orders.entry(row).or_insert(highlight.index);
12003 if highlight.index >= *used_index {
12004 *used_index = highlight.index;
12005 unique_rows.insert(DisplayRow(row), highlight.color);
12006 }
12007 }
12008 unique_rows
12009 },
12010 )
12011 }
12012
12013 pub fn highlighted_display_row_for_autoscroll(
12014 &self,
12015 snapshot: &DisplaySnapshot,
12016 ) -> Option<DisplayRow> {
12017 self.highlighted_rows
12018 .values()
12019 .flat_map(|highlighted_rows| highlighted_rows.iter())
12020 .filter_map(|highlight| {
12021 if highlight.should_autoscroll {
12022 Some(highlight.range.start.to_display_point(snapshot).row())
12023 } else {
12024 None
12025 }
12026 })
12027 .min()
12028 }
12029
12030 pub fn set_search_within_ranges(
12031 &mut self,
12032 ranges: &[Range<Anchor>],
12033 cx: &mut ViewContext<Self>,
12034 ) {
12035 self.highlight_background::<SearchWithinRange>(
12036 ranges,
12037 |colors| colors.editor_document_highlight_read_background,
12038 cx,
12039 )
12040 }
12041
12042 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12043 self.breadcrumb_header = Some(new_header);
12044 }
12045
12046 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12047 self.clear_background_highlights::<SearchWithinRange>(cx);
12048 }
12049
12050 pub fn highlight_background<T: 'static>(
12051 &mut self,
12052 ranges: &[Range<Anchor>],
12053 color_fetcher: fn(&ThemeColors) -> Hsla,
12054 cx: &mut ViewContext<Self>,
12055 ) {
12056 self.background_highlights
12057 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12058 self.scrollbar_marker_state.dirty = true;
12059 cx.notify();
12060 }
12061
12062 pub fn clear_background_highlights<T: 'static>(
12063 &mut self,
12064 cx: &mut ViewContext<Self>,
12065 ) -> Option<BackgroundHighlight> {
12066 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12067 if !text_highlights.1.is_empty() {
12068 self.scrollbar_marker_state.dirty = true;
12069 cx.notify();
12070 }
12071 Some(text_highlights)
12072 }
12073
12074 pub fn highlight_gutter<T: 'static>(
12075 &mut self,
12076 ranges: &[Range<Anchor>],
12077 color_fetcher: fn(&AppContext) -> Hsla,
12078 cx: &mut ViewContext<Self>,
12079 ) {
12080 self.gutter_highlights
12081 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12082 cx.notify();
12083 }
12084
12085 pub fn clear_gutter_highlights<T: 'static>(
12086 &mut self,
12087 cx: &mut ViewContext<Self>,
12088 ) -> Option<GutterHighlight> {
12089 cx.notify();
12090 self.gutter_highlights.remove(&TypeId::of::<T>())
12091 }
12092
12093 #[cfg(feature = "test-support")]
12094 pub fn all_text_background_highlights(
12095 &mut self,
12096 cx: &mut ViewContext<Self>,
12097 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12098 let snapshot = self.snapshot(cx);
12099 let buffer = &snapshot.buffer_snapshot;
12100 let start = buffer.anchor_before(0);
12101 let end = buffer.anchor_after(buffer.len());
12102 let theme = cx.theme().colors();
12103 self.background_highlights_in_range(start..end, &snapshot, theme)
12104 }
12105
12106 #[cfg(feature = "test-support")]
12107 pub fn search_background_highlights(
12108 &mut self,
12109 cx: &mut ViewContext<Self>,
12110 ) -> Vec<Range<Point>> {
12111 let snapshot = self.buffer().read(cx).snapshot(cx);
12112
12113 let highlights = self
12114 .background_highlights
12115 .get(&TypeId::of::<items::BufferSearchHighlights>());
12116
12117 if let Some((_color, ranges)) = highlights {
12118 ranges
12119 .iter()
12120 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12121 .collect_vec()
12122 } else {
12123 vec![]
12124 }
12125 }
12126
12127 fn document_highlights_for_position<'a>(
12128 &'a self,
12129 position: Anchor,
12130 buffer: &'a MultiBufferSnapshot,
12131 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12132 let read_highlights = self
12133 .background_highlights
12134 .get(&TypeId::of::<DocumentHighlightRead>())
12135 .map(|h| &h.1);
12136 let write_highlights = self
12137 .background_highlights
12138 .get(&TypeId::of::<DocumentHighlightWrite>())
12139 .map(|h| &h.1);
12140 let left_position = position.bias_left(buffer);
12141 let right_position = position.bias_right(buffer);
12142 read_highlights
12143 .into_iter()
12144 .chain(write_highlights)
12145 .flat_map(move |ranges| {
12146 let start_ix = match ranges.binary_search_by(|probe| {
12147 let cmp = probe.end.cmp(&left_position, buffer);
12148 if cmp.is_ge() {
12149 Ordering::Greater
12150 } else {
12151 Ordering::Less
12152 }
12153 }) {
12154 Ok(i) | Err(i) => i,
12155 };
12156
12157 ranges[start_ix..]
12158 .iter()
12159 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12160 })
12161 }
12162
12163 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12164 self.background_highlights
12165 .get(&TypeId::of::<T>())
12166 .map_or(false, |(_, highlights)| !highlights.is_empty())
12167 }
12168
12169 pub fn background_highlights_in_range(
12170 &self,
12171 search_range: Range<Anchor>,
12172 display_snapshot: &DisplaySnapshot,
12173 theme: &ThemeColors,
12174 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12175 let mut results = Vec::new();
12176 for (color_fetcher, ranges) in self.background_highlights.values() {
12177 let color = color_fetcher(theme);
12178 let start_ix = match ranges.binary_search_by(|probe| {
12179 let cmp = probe
12180 .end
12181 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12182 if cmp.is_gt() {
12183 Ordering::Greater
12184 } else {
12185 Ordering::Less
12186 }
12187 }) {
12188 Ok(i) | Err(i) => i,
12189 };
12190 for range in &ranges[start_ix..] {
12191 if range
12192 .start
12193 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12194 .is_ge()
12195 {
12196 break;
12197 }
12198
12199 let start = range.start.to_display_point(display_snapshot);
12200 let end = range.end.to_display_point(display_snapshot);
12201 results.push((start..end, color))
12202 }
12203 }
12204 results
12205 }
12206
12207 pub fn background_highlight_row_ranges<T: 'static>(
12208 &self,
12209 search_range: Range<Anchor>,
12210 display_snapshot: &DisplaySnapshot,
12211 count: usize,
12212 ) -> Vec<RangeInclusive<DisplayPoint>> {
12213 let mut results = Vec::new();
12214 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12215 return vec![];
12216 };
12217
12218 let start_ix = match ranges.binary_search_by(|probe| {
12219 let cmp = probe
12220 .end
12221 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12222 if cmp.is_gt() {
12223 Ordering::Greater
12224 } else {
12225 Ordering::Less
12226 }
12227 }) {
12228 Ok(i) | Err(i) => i,
12229 };
12230 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12231 if let (Some(start_display), Some(end_display)) = (start, end) {
12232 results.push(
12233 start_display.to_display_point(display_snapshot)
12234 ..=end_display.to_display_point(display_snapshot),
12235 );
12236 }
12237 };
12238 let mut start_row: Option<Point> = None;
12239 let mut end_row: Option<Point> = None;
12240 if ranges.len() > count {
12241 return Vec::new();
12242 }
12243 for range in &ranges[start_ix..] {
12244 if range
12245 .start
12246 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12247 .is_ge()
12248 {
12249 break;
12250 }
12251 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12252 if let Some(current_row) = &end_row {
12253 if end.row == current_row.row {
12254 continue;
12255 }
12256 }
12257 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12258 if start_row.is_none() {
12259 assert_eq!(end_row, None);
12260 start_row = Some(start);
12261 end_row = Some(end);
12262 continue;
12263 }
12264 if let Some(current_end) = end_row.as_mut() {
12265 if start.row > current_end.row + 1 {
12266 push_region(start_row, end_row);
12267 start_row = Some(start);
12268 end_row = Some(end);
12269 } else {
12270 // Merge two hunks.
12271 *current_end = end;
12272 }
12273 } else {
12274 unreachable!();
12275 }
12276 }
12277 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12278 push_region(start_row, end_row);
12279 results
12280 }
12281
12282 pub fn gutter_highlights_in_range(
12283 &self,
12284 search_range: Range<Anchor>,
12285 display_snapshot: &DisplaySnapshot,
12286 cx: &AppContext,
12287 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12288 let mut results = Vec::new();
12289 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12290 let color = color_fetcher(cx);
12291 let start_ix = match ranges.binary_search_by(|probe| {
12292 let cmp = probe
12293 .end
12294 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12295 if cmp.is_gt() {
12296 Ordering::Greater
12297 } else {
12298 Ordering::Less
12299 }
12300 }) {
12301 Ok(i) | Err(i) => i,
12302 };
12303 for range in &ranges[start_ix..] {
12304 if range
12305 .start
12306 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12307 .is_ge()
12308 {
12309 break;
12310 }
12311
12312 let start = range.start.to_display_point(display_snapshot);
12313 let end = range.end.to_display_point(display_snapshot);
12314 results.push((start..end, color))
12315 }
12316 }
12317 results
12318 }
12319
12320 /// Get the text ranges corresponding to the redaction query
12321 pub fn redacted_ranges(
12322 &self,
12323 search_range: Range<Anchor>,
12324 display_snapshot: &DisplaySnapshot,
12325 cx: &WindowContext,
12326 ) -> Vec<Range<DisplayPoint>> {
12327 display_snapshot
12328 .buffer_snapshot
12329 .redacted_ranges(search_range, |file| {
12330 if let Some(file) = file {
12331 file.is_private()
12332 && EditorSettings::get(
12333 Some(SettingsLocation {
12334 worktree_id: file.worktree_id(cx),
12335 path: file.path().as_ref(),
12336 }),
12337 cx,
12338 )
12339 .redact_private_values
12340 } else {
12341 false
12342 }
12343 })
12344 .map(|range| {
12345 range.start.to_display_point(display_snapshot)
12346 ..range.end.to_display_point(display_snapshot)
12347 })
12348 .collect()
12349 }
12350
12351 pub fn highlight_text<T: 'static>(
12352 &mut self,
12353 ranges: Vec<Range<Anchor>>,
12354 style: HighlightStyle,
12355 cx: &mut ViewContext<Self>,
12356 ) {
12357 self.display_map.update(cx, |map, _| {
12358 map.highlight_text(TypeId::of::<T>(), ranges, style)
12359 });
12360 cx.notify();
12361 }
12362
12363 pub(crate) fn highlight_inlays<T: 'static>(
12364 &mut self,
12365 highlights: Vec<InlayHighlight>,
12366 style: HighlightStyle,
12367 cx: &mut ViewContext<Self>,
12368 ) {
12369 self.display_map.update(cx, |map, _| {
12370 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12371 });
12372 cx.notify();
12373 }
12374
12375 pub fn text_highlights<'a, T: 'static>(
12376 &'a self,
12377 cx: &'a AppContext,
12378 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12379 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12380 }
12381
12382 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12383 let cleared = self
12384 .display_map
12385 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12386 if cleared {
12387 cx.notify();
12388 }
12389 }
12390
12391 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12392 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12393 && self.focus_handle.is_focused(cx)
12394 }
12395
12396 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12397 self.show_cursor_when_unfocused = is_enabled;
12398 cx.notify();
12399 }
12400
12401 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12402 cx.notify();
12403 }
12404
12405 fn on_buffer_event(
12406 &mut self,
12407 multibuffer: Model<MultiBuffer>,
12408 event: &multi_buffer::Event,
12409 cx: &mut ViewContext<Self>,
12410 ) {
12411 match event {
12412 multi_buffer::Event::Edited {
12413 singleton_buffer_edited,
12414 } => {
12415 self.scrollbar_marker_state.dirty = true;
12416 self.active_indent_guides_state.dirty = true;
12417 self.refresh_active_diagnostics(cx);
12418 self.refresh_code_actions(cx);
12419 if self.has_active_inline_completion(cx) {
12420 self.update_visible_inline_completion(cx);
12421 }
12422 cx.emit(EditorEvent::BufferEdited);
12423 cx.emit(SearchEvent::MatchesInvalidated);
12424 if *singleton_buffer_edited {
12425 if let Some(project) = &self.project {
12426 let project = project.read(cx);
12427 #[allow(clippy::mutable_key_type)]
12428 let languages_affected = multibuffer
12429 .read(cx)
12430 .all_buffers()
12431 .into_iter()
12432 .filter_map(|buffer| {
12433 let buffer = buffer.read(cx);
12434 let language = buffer.language()?;
12435 if project.is_local()
12436 && project.language_servers_for_buffer(buffer, cx).count() == 0
12437 {
12438 None
12439 } else {
12440 Some(language)
12441 }
12442 })
12443 .cloned()
12444 .collect::<HashSet<_>>();
12445 if !languages_affected.is_empty() {
12446 self.refresh_inlay_hints(
12447 InlayHintRefreshReason::BufferEdited(languages_affected),
12448 cx,
12449 );
12450 }
12451 }
12452 }
12453
12454 let Some(project) = &self.project else { return };
12455 let (telemetry, is_via_ssh) = {
12456 let project = project.read(cx);
12457 let telemetry = project.client().telemetry().clone();
12458 let is_via_ssh = project.is_via_ssh();
12459 (telemetry, is_via_ssh)
12460 };
12461 refresh_linked_ranges(self, cx);
12462 telemetry.log_edit_event("editor", is_via_ssh);
12463 }
12464 multi_buffer::Event::ExcerptsAdded {
12465 buffer,
12466 predecessor,
12467 excerpts,
12468 } => {
12469 self.tasks_update_task = Some(self.refresh_runnables(cx));
12470 cx.emit(EditorEvent::ExcerptsAdded {
12471 buffer: buffer.clone(),
12472 predecessor: *predecessor,
12473 excerpts: excerpts.clone(),
12474 });
12475 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12476 }
12477 multi_buffer::Event::ExcerptsRemoved { ids } => {
12478 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12479 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12480 }
12481 multi_buffer::Event::ExcerptsEdited { ids } => {
12482 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12483 }
12484 multi_buffer::Event::ExcerptsExpanded { ids } => {
12485 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12486 }
12487 multi_buffer::Event::Reparsed(buffer_id) => {
12488 self.tasks_update_task = Some(self.refresh_runnables(cx));
12489
12490 cx.emit(EditorEvent::Reparsed(*buffer_id));
12491 }
12492 multi_buffer::Event::LanguageChanged(buffer_id) => {
12493 linked_editing_ranges::refresh_linked_ranges(self, cx);
12494 cx.emit(EditorEvent::Reparsed(*buffer_id));
12495 cx.notify();
12496 }
12497 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12498 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12499 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12500 cx.emit(EditorEvent::TitleChanged)
12501 }
12502 multi_buffer::Event::DiffBaseChanged => {
12503 self.scrollbar_marker_state.dirty = true;
12504 cx.emit(EditorEvent::DiffBaseChanged);
12505 cx.notify();
12506 }
12507 multi_buffer::Event::DiffUpdated { buffer } => {
12508 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12509 cx.notify();
12510 }
12511 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12512 multi_buffer::Event::DiagnosticsUpdated => {
12513 self.refresh_active_diagnostics(cx);
12514 self.scrollbar_marker_state.dirty = true;
12515 cx.notify();
12516 }
12517 _ => {}
12518 };
12519 }
12520
12521 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12522 cx.notify();
12523 }
12524
12525 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12526 self.tasks_update_task = Some(self.refresh_runnables(cx));
12527 self.refresh_inline_completion(true, false, cx);
12528 self.refresh_inlay_hints(
12529 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12530 self.selections.newest_anchor().head(),
12531 &self.buffer.read(cx).snapshot(cx),
12532 cx,
12533 )),
12534 cx,
12535 );
12536
12537 let old_cursor_shape = self.cursor_shape;
12538
12539 {
12540 let editor_settings = EditorSettings::get_global(cx);
12541 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12542 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12543 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12544 }
12545
12546 if old_cursor_shape != self.cursor_shape {
12547 cx.emit(EditorEvent::CursorShapeChanged);
12548 }
12549
12550 let project_settings = ProjectSettings::get_global(cx);
12551 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12552
12553 if self.mode == EditorMode::Full {
12554 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12555 if self.git_blame_inline_enabled != inline_blame_enabled {
12556 self.toggle_git_blame_inline_internal(false, cx);
12557 }
12558 }
12559
12560 cx.notify();
12561 }
12562
12563 pub fn set_searchable(&mut self, searchable: bool) {
12564 self.searchable = searchable;
12565 }
12566
12567 pub fn searchable(&self) -> bool {
12568 self.searchable
12569 }
12570
12571 fn open_proposed_changes_editor(
12572 &mut self,
12573 _: &OpenProposedChangesEditor,
12574 cx: &mut ViewContext<Self>,
12575 ) {
12576 let Some(workspace) = self.workspace() else {
12577 cx.propagate();
12578 return;
12579 };
12580
12581 let selections = self.selections.all::<usize>(cx);
12582 let buffer = self.buffer.read(cx);
12583 let mut new_selections_by_buffer = HashMap::default();
12584 for selection in selections {
12585 for (buffer, range, _) in
12586 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12587 {
12588 let mut range = range.to_point(buffer.read(cx));
12589 range.start.column = 0;
12590 range.end.column = buffer.read(cx).line_len(range.end.row);
12591 new_selections_by_buffer
12592 .entry(buffer)
12593 .or_insert(Vec::new())
12594 .push(range)
12595 }
12596 }
12597
12598 let proposed_changes_buffers = new_selections_by_buffer
12599 .into_iter()
12600 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12601 .collect::<Vec<_>>();
12602 let proposed_changes_editor = cx.new_view(|cx| {
12603 ProposedChangesEditor::new(
12604 "Proposed changes",
12605 proposed_changes_buffers,
12606 self.project.clone(),
12607 cx,
12608 )
12609 });
12610
12611 cx.window_context().defer(move |cx| {
12612 workspace.update(cx, |workspace, cx| {
12613 workspace.active_pane().update(cx, |pane, cx| {
12614 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12615 });
12616 });
12617 });
12618 }
12619
12620 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12621 self.open_excerpts_common(None, true, cx)
12622 }
12623
12624 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12625 self.open_excerpts_common(None, false, cx)
12626 }
12627
12628 fn open_excerpts_common(
12629 &mut self,
12630 jump_data: Option<JumpData>,
12631 split: bool,
12632 cx: &mut ViewContext<Self>,
12633 ) {
12634 let Some(workspace) = self.workspace() else {
12635 cx.propagate();
12636 return;
12637 };
12638
12639 if self.buffer.read(cx).is_singleton() {
12640 cx.propagate();
12641 return;
12642 }
12643
12644 let mut new_selections_by_buffer = HashMap::default();
12645 match &jump_data {
12646 Some(jump_data) => {
12647 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12648 if let Some(buffer) = multi_buffer_snapshot
12649 .buffer_id_for_excerpt(jump_data.excerpt_id)
12650 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12651 {
12652 let buffer_snapshot = buffer.read(cx).snapshot();
12653 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12654 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12655 } else {
12656 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12657 };
12658 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12659 new_selections_by_buffer.insert(
12660 buffer,
12661 (
12662 vec![jump_to_offset..jump_to_offset],
12663 Some(jump_data.line_offset_from_top),
12664 ),
12665 );
12666 }
12667 }
12668 None => {
12669 let selections = self.selections.all::<usize>(cx);
12670 let buffer = self.buffer.read(cx);
12671 for selection in selections {
12672 for (mut buffer_handle, mut range, _) in
12673 buffer.range_to_buffer_ranges(selection.range(), cx)
12674 {
12675 // When editing branch buffers, jump to the corresponding location
12676 // in their base buffer.
12677 let buffer = buffer_handle.read(cx);
12678 if let Some(base_buffer) = buffer.diff_base_buffer() {
12679 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12680 buffer_handle = base_buffer;
12681 }
12682
12683 if selection.reversed {
12684 mem::swap(&mut range.start, &mut range.end);
12685 }
12686 new_selections_by_buffer
12687 .entry(buffer_handle)
12688 .or_insert((Vec::new(), None))
12689 .0
12690 .push(range)
12691 }
12692 }
12693 }
12694 }
12695
12696 if new_selections_by_buffer.is_empty() {
12697 return;
12698 }
12699
12700 // We defer the pane interaction because we ourselves are a workspace item
12701 // and activating a new item causes the pane to call a method on us reentrantly,
12702 // which panics if we're on the stack.
12703 cx.window_context().defer(move |cx| {
12704 workspace.update(cx, |workspace, cx| {
12705 let pane = if split {
12706 workspace.adjacent_pane(cx)
12707 } else {
12708 workspace.active_pane().clone()
12709 };
12710
12711 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12712 let editor =
12713 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12714 editor.update(cx, |editor, cx| {
12715 let autoscroll = match scroll_offset {
12716 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12717 None => Autoscroll::newest(),
12718 };
12719 let nav_history = editor.nav_history.take();
12720 editor.change_selections(Some(autoscroll), cx, |s| {
12721 s.select_ranges(ranges);
12722 });
12723 editor.nav_history = nav_history;
12724 });
12725 }
12726 })
12727 });
12728 }
12729
12730 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12731 let snapshot = self.buffer.read(cx).read(cx);
12732 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12733 Some(
12734 ranges
12735 .iter()
12736 .map(move |range| {
12737 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12738 })
12739 .collect(),
12740 )
12741 }
12742
12743 fn selection_replacement_ranges(
12744 &self,
12745 range: Range<OffsetUtf16>,
12746 cx: &mut AppContext,
12747 ) -> Vec<Range<OffsetUtf16>> {
12748 let selections = self.selections.all::<OffsetUtf16>(cx);
12749 let newest_selection = selections
12750 .iter()
12751 .max_by_key(|selection| selection.id)
12752 .unwrap();
12753 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12754 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12755 let snapshot = self.buffer.read(cx).read(cx);
12756 selections
12757 .into_iter()
12758 .map(|mut selection| {
12759 selection.start.0 =
12760 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12761 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12762 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12763 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12764 })
12765 .collect()
12766 }
12767
12768 fn report_editor_event(
12769 &self,
12770 operation: &'static str,
12771 file_extension: Option<String>,
12772 cx: &AppContext,
12773 ) {
12774 if cfg!(any(test, feature = "test-support")) {
12775 return;
12776 }
12777
12778 let Some(project) = &self.project else { return };
12779
12780 // If None, we are in a file without an extension
12781 let file = self
12782 .buffer
12783 .read(cx)
12784 .as_singleton()
12785 .and_then(|b| b.read(cx).file());
12786 let file_extension = file_extension.or(file
12787 .as_ref()
12788 .and_then(|file| Path::new(file.file_name(cx)).extension())
12789 .and_then(|e| e.to_str())
12790 .map(|a| a.to_string()));
12791
12792 let vim_mode = cx
12793 .global::<SettingsStore>()
12794 .raw_user_settings()
12795 .get("vim_mode")
12796 == Some(&serde_json::Value::Bool(true));
12797
12798 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12799 == language::language_settings::InlineCompletionProvider::Copilot;
12800 let copilot_enabled_for_language = self
12801 .buffer
12802 .read(cx)
12803 .settings_at(0, cx)
12804 .show_inline_completions;
12805
12806 let project = project.read(cx);
12807 let telemetry = project.client().telemetry().clone();
12808 telemetry.report_editor_event(
12809 file_extension,
12810 vim_mode,
12811 operation,
12812 copilot_enabled,
12813 copilot_enabled_for_language,
12814 project.is_via_ssh(),
12815 )
12816 }
12817
12818 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12819 /// with each line being an array of {text, highlight} objects.
12820 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12821 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12822 return;
12823 };
12824
12825 #[derive(Serialize)]
12826 struct Chunk<'a> {
12827 text: String,
12828 highlight: Option<&'a str>,
12829 }
12830
12831 let snapshot = buffer.read(cx).snapshot();
12832 let range = self
12833 .selected_text_range(false, cx)
12834 .and_then(|selection| {
12835 if selection.range.is_empty() {
12836 None
12837 } else {
12838 Some(selection.range)
12839 }
12840 })
12841 .unwrap_or_else(|| 0..snapshot.len());
12842
12843 let chunks = snapshot.chunks(range, true);
12844 let mut lines = Vec::new();
12845 let mut line: VecDeque<Chunk> = VecDeque::new();
12846
12847 let Some(style) = self.style.as_ref() else {
12848 return;
12849 };
12850
12851 for chunk in chunks {
12852 let highlight = chunk
12853 .syntax_highlight_id
12854 .and_then(|id| id.name(&style.syntax));
12855 let mut chunk_lines = chunk.text.split('\n').peekable();
12856 while let Some(text) = chunk_lines.next() {
12857 let mut merged_with_last_token = false;
12858 if let Some(last_token) = line.back_mut() {
12859 if last_token.highlight == highlight {
12860 last_token.text.push_str(text);
12861 merged_with_last_token = true;
12862 }
12863 }
12864
12865 if !merged_with_last_token {
12866 line.push_back(Chunk {
12867 text: text.into(),
12868 highlight,
12869 });
12870 }
12871
12872 if chunk_lines.peek().is_some() {
12873 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12874 line.pop_front();
12875 }
12876 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12877 line.pop_back();
12878 }
12879
12880 lines.push(mem::take(&mut line));
12881 }
12882 }
12883 }
12884
12885 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12886 return;
12887 };
12888 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12889 }
12890
12891 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12892 &self.inlay_hint_cache
12893 }
12894
12895 pub fn replay_insert_event(
12896 &mut self,
12897 text: &str,
12898 relative_utf16_range: Option<Range<isize>>,
12899 cx: &mut ViewContext<Self>,
12900 ) {
12901 if !self.input_enabled {
12902 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12903 return;
12904 }
12905 if let Some(relative_utf16_range) = relative_utf16_range {
12906 let selections = self.selections.all::<OffsetUtf16>(cx);
12907 self.change_selections(None, cx, |s| {
12908 let new_ranges = selections.into_iter().map(|range| {
12909 let start = OffsetUtf16(
12910 range
12911 .head()
12912 .0
12913 .saturating_add_signed(relative_utf16_range.start),
12914 );
12915 let end = OffsetUtf16(
12916 range
12917 .head()
12918 .0
12919 .saturating_add_signed(relative_utf16_range.end),
12920 );
12921 start..end
12922 });
12923 s.select_ranges(new_ranges);
12924 });
12925 }
12926
12927 self.handle_input(text, cx);
12928 }
12929
12930 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12931 let Some(provider) = self.semantics_provider.as_ref() else {
12932 return false;
12933 };
12934
12935 let mut supports = false;
12936 self.buffer().read(cx).for_each_buffer(|buffer| {
12937 supports |= provider.supports_inlay_hints(buffer, cx);
12938 });
12939 supports
12940 }
12941
12942 pub fn focus(&self, cx: &mut WindowContext) {
12943 cx.focus(&self.focus_handle)
12944 }
12945
12946 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12947 self.focus_handle.is_focused(cx)
12948 }
12949
12950 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12951 cx.emit(EditorEvent::Focused);
12952
12953 if let Some(descendant) = self
12954 .last_focused_descendant
12955 .take()
12956 .and_then(|descendant| descendant.upgrade())
12957 {
12958 cx.focus(&descendant);
12959 } else {
12960 if let Some(blame) = self.blame.as_ref() {
12961 blame.update(cx, GitBlame::focus)
12962 }
12963
12964 self.blink_manager.update(cx, BlinkManager::enable);
12965 self.show_cursor_names(cx);
12966 self.buffer.update(cx, |buffer, cx| {
12967 buffer.finalize_last_transaction(cx);
12968 if self.leader_peer_id.is_none() {
12969 buffer.set_active_selections(
12970 &self.selections.disjoint_anchors(),
12971 self.selections.line_mode,
12972 self.cursor_shape,
12973 cx,
12974 );
12975 }
12976 });
12977 }
12978 }
12979
12980 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12981 cx.emit(EditorEvent::FocusedIn)
12982 }
12983
12984 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12985 if event.blurred != self.focus_handle {
12986 self.last_focused_descendant = Some(event.blurred);
12987 }
12988 }
12989
12990 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12991 self.blink_manager.update(cx, BlinkManager::disable);
12992 self.buffer
12993 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12994
12995 if let Some(blame) = self.blame.as_ref() {
12996 blame.update(cx, GitBlame::blur)
12997 }
12998 if !self.hover_state.focused(cx) {
12999 hide_hover(self, cx);
13000 }
13001
13002 self.hide_context_menu(cx);
13003 cx.emit(EditorEvent::Blurred);
13004 cx.notify();
13005 }
13006
13007 pub fn register_action<A: Action>(
13008 &mut self,
13009 listener: impl Fn(&A, &mut WindowContext) + 'static,
13010 ) -> Subscription {
13011 let id = self.next_editor_action_id.post_inc();
13012 let listener = Arc::new(listener);
13013 self.editor_actions.borrow_mut().insert(
13014 id,
13015 Box::new(move |cx| {
13016 let cx = cx.window_context();
13017 let listener = listener.clone();
13018 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13019 let action = action.downcast_ref().unwrap();
13020 if phase == DispatchPhase::Bubble {
13021 listener(action, cx)
13022 }
13023 })
13024 }),
13025 );
13026
13027 let editor_actions = self.editor_actions.clone();
13028 Subscription::new(move || {
13029 editor_actions.borrow_mut().remove(&id);
13030 })
13031 }
13032
13033 pub fn file_header_size(&self) -> u32 {
13034 FILE_HEADER_HEIGHT
13035 }
13036
13037 pub fn revert(
13038 &mut self,
13039 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13040 cx: &mut ViewContext<Self>,
13041 ) {
13042 self.buffer().update(cx, |multi_buffer, cx| {
13043 for (buffer_id, changes) in revert_changes {
13044 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13045 buffer.update(cx, |buffer, cx| {
13046 buffer.edit(
13047 changes.into_iter().map(|(range, text)| {
13048 (range, text.to_string().map(Arc::<str>::from))
13049 }),
13050 None,
13051 cx,
13052 );
13053 });
13054 }
13055 }
13056 });
13057 self.change_selections(None, cx, |selections| selections.refresh());
13058 }
13059
13060 pub fn to_pixel_point(
13061 &mut self,
13062 source: multi_buffer::Anchor,
13063 editor_snapshot: &EditorSnapshot,
13064 cx: &mut ViewContext<Self>,
13065 ) -> Option<gpui::Point<Pixels>> {
13066 let source_point = source.to_display_point(editor_snapshot);
13067 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13068 }
13069
13070 pub fn display_to_pixel_point(
13071 &mut self,
13072 source: DisplayPoint,
13073 editor_snapshot: &EditorSnapshot,
13074 cx: &mut ViewContext<Self>,
13075 ) -> Option<gpui::Point<Pixels>> {
13076 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13077 let text_layout_details = self.text_layout_details(cx);
13078 let scroll_top = text_layout_details
13079 .scroll_anchor
13080 .scroll_position(editor_snapshot)
13081 .y;
13082
13083 if source.row().as_f32() < scroll_top.floor() {
13084 return None;
13085 }
13086 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13087 let source_y = line_height * (source.row().as_f32() - scroll_top);
13088 Some(gpui::Point::new(source_x, source_y))
13089 }
13090
13091 pub fn has_active_completions_menu(&self) -> bool {
13092 self.context_menu.read().as_ref().map_or(false, |menu| {
13093 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13094 })
13095 }
13096
13097 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13098 self.addons
13099 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13100 }
13101
13102 pub fn unregister_addon<T: Addon>(&mut self) {
13103 self.addons.remove(&std::any::TypeId::of::<T>());
13104 }
13105
13106 pub fn addon<T: Addon>(&self) -> Option<&T> {
13107 let type_id = std::any::TypeId::of::<T>();
13108 self.addons
13109 .get(&type_id)
13110 .and_then(|item| item.to_any().downcast_ref::<T>())
13111 }
13112}
13113
13114fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13115 let tab_size = tab_size.get() as usize;
13116 let mut width = offset;
13117
13118 for ch in text.chars() {
13119 width += if ch == '\t' {
13120 tab_size - (width % tab_size)
13121 } else {
13122 1
13123 };
13124 }
13125
13126 width - offset
13127}
13128
13129#[cfg(test)]
13130mod tests {
13131 use super::*;
13132
13133 #[test]
13134 fn test_string_size_with_expanded_tabs() {
13135 let nz = |val| NonZeroU32::new(val).unwrap();
13136 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13137 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13138 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13139 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13140 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13141 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13142 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13143 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13144 }
13145}
13146
13147/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13148struct WordBreakingTokenizer<'a> {
13149 input: &'a str,
13150}
13151
13152impl<'a> WordBreakingTokenizer<'a> {
13153 fn new(input: &'a str) -> Self {
13154 Self { input }
13155 }
13156}
13157
13158fn is_char_ideographic(ch: char) -> bool {
13159 use unicode_script::Script::*;
13160 use unicode_script::UnicodeScript;
13161 matches!(ch.script(), Han | Tangut | Yi)
13162}
13163
13164fn is_grapheme_ideographic(text: &str) -> bool {
13165 text.chars().any(is_char_ideographic)
13166}
13167
13168fn is_grapheme_whitespace(text: &str) -> bool {
13169 text.chars().any(|x| x.is_whitespace())
13170}
13171
13172fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13173 text.chars().next().map_or(false, |ch| {
13174 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13175 })
13176}
13177
13178#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13179struct WordBreakToken<'a> {
13180 token: &'a str,
13181 grapheme_len: usize,
13182 is_whitespace: bool,
13183}
13184
13185impl<'a> Iterator for WordBreakingTokenizer<'a> {
13186 /// Yields a span, the count of graphemes in the token, and whether it was
13187 /// whitespace. Note that it also breaks at word boundaries.
13188 type Item = WordBreakToken<'a>;
13189
13190 fn next(&mut self) -> Option<Self::Item> {
13191 use unicode_segmentation::UnicodeSegmentation;
13192 if self.input.is_empty() {
13193 return None;
13194 }
13195
13196 let mut iter = self.input.graphemes(true).peekable();
13197 let mut offset = 0;
13198 let mut graphemes = 0;
13199 if let Some(first_grapheme) = iter.next() {
13200 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13201 offset += first_grapheme.len();
13202 graphemes += 1;
13203 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13204 if let Some(grapheme) = iter.peek().copied() {
13205 if should_stay_with_preceding_ideograph(grapheme) {
13206 offset += grapheme.len();
13207 graphemes += 1;
13208 }
13209 }
13210 } else {
13211 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13212 let mut next_word_bound = words.peek().copied();
13213 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13214 next_word_bound = words.next();
13215 }
13216 while let Some(grapheme) = iter.peek().copied() {
13217 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13218 break;
13219 };
13220 if is_grapheme_whitespace(grapheme) != is_whitespace {
13221 break;
13222 };
13223 offset += grapheme.len();
13224 graphemes += 1;
13225 iter.next();
13226 }
13227 }
13228 let token = &self.input[..offset];
13229 self.input = &self.input[offset..];
13230 if is_whitespace {
13231 Some(WordBreakToken {
13232 token: " ",
13233 grapheme_len: 1,
13234 is_whitespace: true,
13235 })
13236 } else {
13237 Some(WordBreakToken {
13238 token,
13239 grapheme_len: graphemes,
13240 is_whitespace: false,
13241 })
13242 }
13243 } else {
13244 None
13245 }
13246 }
13247}
13248
13249#[test]
13250fn test_word_breaking_tokenizer() {
13251 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13252 ("", &[]),
13253 (" ", &[(" ", 1, true)]),
13254 ("Ʒ", &[("Ʒ", 1, false)]),
13255 ("Ǽ", &[("Ǽ", 1, false)]),
13256 ("⋑", &[("⋑", 1, false)]),
13257 ("⋑⋑", &[("⋑⋑", 2, false)]),
13258 (
13259 "原理,进而",
13260 &[
13261 ("原", 1, false),
13262 ("理,", 2, false),
13263 ("进", 1, false),
13264 ("而", 1, false),
13265 ],
13266 ),
13267 (
13268 "hello world",
13269 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13270 ),
13271 (
13272 "hello, world",
13273 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13274 ),
13275 (
13276 " hello world",
13277 &[
13278 (" ", 1, true),
13279 ("hello", 5, false),
13280 (" ", 1, true),
13281 ("world", 5, false),
13282 ],
13283 ),
13284 (
13285 "这是什么 \n 钢笔",
13286 &[
13287 ("这", 1, false),
13288 ("是", 1, false),
13289 ("什", 1, false),
13290 ("么", 1, false),
13291 (" ", 1, true),
13292 ("钢", 1, false),
13293 ("笔", 1, false),
13294 ],
13295 ),
13296 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13297 ];
13298
13299 for (input, result) in tests {
13300 assert_eq!(
13301 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13302 result
13303 .iter()
13304 .copied()
13305 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13306 token,
13307 grapheme_len,
13308 is_whitespace,
13309 })
13310 .collect::<Vec<_>>()
13311 );
13312 }
13313}
13314
13315fn wrap_with_prefix(
13316 line_prefix: String,
13317 unwrapped_text: String,
13318 wrap_column: usize,
13319 tab_size: NonZeroU32,
13320) -> String {
13321 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13322 let mut wrapped_text = String::new();
13323 let mut current_line = line_prefix.clone();
13324
13325 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13326 let mut current_line_len = line_prefix_len;
13327 for WordBreakToken {
13328 token,
13329 grapheme_len,
13330 is_whitespace,
13331 } in tokenizer
13332 {
13333 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13334 wrapped_text.push_str(current_line.trim_end());
13335 wrapped_text.push('\n');
13336 current_line.truncate(line_prefix.len());
13337 current_line_len = line_prefix_len;
13338 if !is_whitespace {
13339 current_line.push_str(token);
13340 current_line_len += grapheme_len;
13341 }
13342 } else if !is_whitespace {
13343 current_line.push_str(token);
13344 current_line_len += grapheme_len;
13345 } else if current_line_len != line_prefix_len {
13346 current_line.push(' ');
13347 current_line_len += 1;
13348 }
13349 }
13350
13351 if !current_line.is_empty() {
13352 wrapped_text.push_str(¤t_line);
13353 }
13354 wrapped_text
13355}
13356
13357#[test]
13358fn test_wrap_with_prefix() {
13359 assert_eq!(
13360 wrap_with_prefix(
13361 "# ".to_string(),
13362 "abcdefg".to_string(),
13363 4,
13364 NonZeroU32::new(4).unwrap()
13365 ),
13366 "# abcdefg"
13367 );
13368 assert_eq!(
13369 wrap_with_prefix(
13370 "".to_string(),
13371 "\thello world".to_string(),
13372 8,
13373 NonZeroU32::new(4).unwrap()
13374 ),
13375 "hello\nworld"
13376 );
13377 assert_eq!(
13378 wrap_with_prefix(
13379 "// ".to_string(),
13380 "xx \nyy zz aa bb cc".to_string(),
13381 12,
13382 NonZeroU32::new(4).unwrap()
13383 ),
13384 "// xx yy zz\n// aa bb cc"
13385 );
13386 assert_eq!(
13387 wrap_with_prefix(
13388 String::new(),
13389 "这是什么 \n 钢笔".to_string(),
13390 3,
13391 NonZeroU32::new(4).unwrap()
13392 ),
13393 "这是什\n么 钢\n笔"
13394 );
13395}
13396
13397fn hunks_for_selections(
13398 multi_buffer_snapshot: &MultiBufferSnapshot,
13399 selections: &[Selection<Anchor>],
13400) -> Vec<MultiBufferDiffHunk> {
13401 let buffer_rows_for_selections = selections.iter().map(|selection| {
13402 let head = selection.head();
13403 let tail = selection.tail();
13404 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13405 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13406 if start > end {
13407 end..start
13408 } else {
13409 start..end
13410 }
13411 });
13412
13413 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13414}
13415
13416pub fn hunks_for_rows(
13417 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13418 multi_buffer_snapshot: &MultiBufferSnapshot,
13419) -> Vec<MultiBufferDiffHunk> {
13420 let mut hunks = Vec::new();
13421 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13422 HashMap::default();
13423 for selected_multi_buffer_rows in rows {
13424 let query_rows =
13425 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13426 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13427 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13428 // when the caret is just above or just below the deleted hunk.
13429 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13430 let related_to_selection = if allow_adjacent {
13431 hunk.row_range.overlaps(&query_rows)
13432 || hunk.row_range.start == query_rows.end
13433 || hunk.row_range.end == query_rows.start
13434 } else {
13435 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13436 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13437 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13438 || selected_multi_buffer_rows.end == hunk.row_range.start
13439 };
13440 if related_to_selection {
13441 if !processed_buffer_rows
13442 .entry(hunk.buffer_id)
13443 .or_default()
13444 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13445 {
13446 continue;
13447 }
13448 hunks.push(hunk);
13449 }
13450 }
13451 }
13452
13453 hunks
13454}
13455
13456pub trait CollaborationHub {
13457 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13458 fn user_participant_indices<'a>(
13459 &self,
13460 cx: &'a AppContext,
13461 ) -> &'a HashMap<u64, ParticipantIndex>;
13462 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13463}
13464
13465impl CollaborationHub for Model<Project> {
13466 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13467 self.read(cx).collaborators()
13468 }
13469
13470 fn user_participant_indices<'a>(
13471 &self,
13472 cx: &'a AppContext,
13473 ) -> &'a HashMap<u64, ParticipantIndex> {
13474 self.read(cx).user_store().read(cx).participant_indices()
13475 }
13476
13477 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13478 let this = self.read(cx);
13479 let user_ids = this.collaborators().values().map(|c| c.user_id);
13480 this.user_store().read_with(cx, |user_store, cx| {
13481 user_store.participant_names(user_ids, cx)
13482 })
13483 }
13484}
13485
13486pub trait SemanticsProvider {
13487 fn hover(
13488 &self,
13489 buffer: &Model<Buffer>,
13490 position: text::Anchor,
13491 cx: &mut AppContext,
13492 ) -> Option<Task<Vec<project::Hover>>>;
13493
13494 fn inlay_hints(
13495 &self,
13496 buffer_handle: Model<Buffer>,
13497 range: Range<text::Anchor>,
13498 cx: &mut AppContext,
13499 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13500
13501 fn resolve_inlay_hint(
13502 &self,
13503 hint: InlayHint,
13504 buffer_handle: Model<Buffer>,
13505 server_id: LanguageServerId,
13506 cx: &mut AppContext,
13507 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13508
13509 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13510
13511 fn document_highlights(
13512 &self,
13513 buffer: &Model<Buffer>,
13514 position: text::Anchor,
13515 cx: &mut AppContext,
13516 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13517
13518 fn definitions(
13519 &self,
13520 buffer: &Model<Buffer>,
13521 position: text::Anchor,
13522 kind: GotoDefinitionKind,
13523 cx: &mut AppContext,
13524 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13525
13526 fn range_for_rename(
13527 &self,
13528 buffer: &Model<Buffer>,
13529 position: text::Anchor,
13530 cx: &mut AppContext,
13531 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13532
13533 fn perform_rename(
13534 &self,
13535 buffer: &Model<Buffer>,
13536 position: text::Anchor,
13537 new_name: String,
13538 cx: &mut AppContext,
13539 ) -> Option<Task<Result<ProjectTransaction>>>;
13540}
13541
13542pub trait CompletionProvider {
13543 fn completions(
13544 &self,
13545 buffer: &Model<Buffer>,
13546 buffer_position: text::Anchor,
13547 trigger: CompletionContext,
13548 cx: &mut ViewContext<Editor>,
13549 ) -> Task<Result<Vec<Completion>>>;
13550
13551 fn resolve_completions(
13552 &self,
13553 buffer: Model<Buffer>,
13554 completion_indices: Vec<usize>,
13555 completions: Arc<RwLock<Box<[Completion]>>>,
13556 cx: &mut ViewContext<Editor>,
13557 ) -> Task<Result<bool>>;
13558
13559 fn apply_additional_edits_for_completion(
13560 &self,
13561 buffer: Model<Buffer>,
13562 completion: Completion,
13563 push_to_history: bool,
13564 cx: &mut ViewContext<Editor>,
13565 ) -> Task<Result<Option<language::Transaction>>>;
13566
13567 fn is_completion_trigger(
13568 &self,
13569 buffer: &Model<Buffer>,
13570 position: language::Anchor,
13571 text: &str,
13572 trigger_in_words: bool,
13573 cx: &mut ViewContext<Editor>,
13574 ) -> bool;
13575
13576 fn sort_completions(&self) -> bool {
13577 true
13578 }
13579}
13580
13581pub trait CodeActionProvider {
13582 fn code_actions(
13583 &self,
13584 buffer: &Model<Buffer>,
13585 range: Range<text::Anchor>,
13586 cx: &mut WindowContext,
13587 ) -> Task<Result<Vec<CodeAction>>>;
13588
13589 fn apply_code_action(
13590 &self,
13591 buffer_handle: Model<Buffer>,
13592 action: CodeAction,
13593 excerpt_id: ExcerptId,
13594 push_to_history: bool,
13595 cx: &mut WindowContext,
13596 ) -> Task<Result<ProjectTransaction>>;
13597}
13598
13599impl CodeActionProvider for Model<Project> {
13600 fn code_actions(
13601 &self,
13602 buffer: &Model<Buffer>,
13603 range: Range<text::Anchor>,
13604 cx: &mut WindowContext,
13605 ) -> Task<Result<Vec<CodeAction>>> {
13606 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13607 }
13608
13609 fn apply_code_action(
13610 &self,
13611 buffer_handle: Model<Buffer>,
13612 action: CodeAction,
13613 _excerpt_id: ExcerptId,
13614 push_to_history: bool,
13615 cx: &mut WindowContext,
13616 ) -> Task<Result<ProjectTransaction>> {
13617 self.update(cx, |project, cx| {
13618 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13619 })
13620 }
13621}
13622
13623fn snippet_completions(
13624 project: &Project,
13625 buffer: &Model<Buffer>,
13626 buffer_position: text::Anchor,
13627 cx: &mut AppContext,
13628) -> Vec<Completion> {
13629 let language = buffer.read(cx).language_at(buffer_position);
13630 let language_name = language.as_ref().map(|language| language.lsp_id());
13631 let snippet_store = project.snippets().read(cx);
13632 let snippets = snippet_store.snippets_for(language_name, cx);
13633
13634 if snippets.is_empty() {
13635 return vec![];
13636 }
13637 let snapshot = buffer.read(cx).text_snapshot();
13638 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13639
13640 let scope = language.map(|language| language.default_scope());
13641 let classifier = CharClassifier::new(scope).for_completion(true);
13642 let mut last_word = chars
13643 .take_while(|c| classifier.is_word(*c))
13644 .collect::<String>();
13645 last_word = last_word.chars().rev().collect();
13646 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13647 let to_lsp = |point: &text::Anchor| {
13648 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13649 point_to_lsp(end)
13650 };
13651 let lsp_end = to_lsp(&buffer_position);
13652 snippets
13653 .into_iter()
13654 .filter_map(|snippet| {
13655 let matching_prefix = snippet
13656 .prefix
13657 .iter()
13658 .find(|prefix| prefix.starts_with(&last_word))?;
13659 let start = as_offset - last_word.len();
13660 let start = snapshot.anchor_before(start);
13661 let range = start..buffer_position;
13662 let lsp_start = to_lsp(&start);
13663 let lsp_range = lsp::Range {
13664 start: lsp_start,
13665 end: lsp_end,
13666 };
13667 Some(Completion {
13668 old_range: range,
13669 new_text: snippet.body.clone(),
13670 label: CodeLabel {
13671 text: matching_prefix.clone(),
13672 runs: vec![],
13673 filter_range: 0..matching_prefix.len(),
13674 },
13675 server_id: LanguageServerId(usize::MAX),
13676 documentation: snippet.description.clone().map(Documentation::SingleLine),
13677 lsp_completion: lsp::CompletionItem {
13678 label: snippet.prefix.first().unwrap().clone(),
13679 kind: Some(CompletionItemKind::SNIPPET),
13680 label_details: snippet.description.as_ref().map(|description| {
13681 lsp::CompletionItemLabelDetails {
13682 detail: Some(description.clone()),
13683 description: None,
13684 }
13685 }),
13686 insert_text_format: Some(InsertTextFormat::SNIPPET),
13687 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13688 lsp::InsertReplaceEdit {
13689 new_text: snippet.body.clone(),
13690 insert: lsp_range,
13691 replace: lsp_range,
13692 },
13693 )),
13694 filter_text: Some(snippet.body.clone()),
13695 sort_text: Some(char::MAX.to_string()),
13696 ..Default::default()
13697 },
13698 confirm: None,
13699 })
13700 })
13701 .collect()
13702}
13703
13704impl CompletionProvider for Model<Project> {
13705 fn completions(
13706 &self,
13707 buffer: &Model<Buffer>,
13708 buffer_position: text::Anchor,
13709 options: CompletionContext,
13710 cx: &mut ViewContext<Editor>,
13711 ) -> Task<Result<Vec<Completion>>> {
13712 self.update(cx, |project, cx| {
13713 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13714 let project_completions = project.completions(buffer, buffer_position, options, cx);
13715 cx.background_executor().spawn(async move {
13716 let mut completions = project_completions.await?;
13717 //let snippets = snippets.into_iter().;
13718 completions.extend(snippets);
13719 Ok(completions)
13720 })
13721 })
13722 }
13723
13724 fn resolve_completions(
13725 &self,
13726 buffer: Model<Buffer>,
13727 completion_indices: Vec<usize>,
13728 completions: Arc<RwLock<Box<[Completion]>>>,
13729 cx: &mut ViewContext<Editor>,
13730 ) -> Task<Result<bool>> {
13731 self.update(cx, |project, cx| {
13732 project.resolve_completions(buffer, completion_indices, completions, cx)
13733 })
13734 }
13735
13736 fn apply_additional_edits_for_completion(
13737 &self,
13738 buffer: Model<Buffer>,
13739 completion: Completion,
13740 push_to_history: bool,
13741 cx: &mut ViewContext<Editor>,
13742 ) -> Task<Result<Option<language::Transaction>>> {
13743 self.update(cx, |project, cx| {
13744 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13745 })
13746 }
13747
13748 fn is_completion_trigger(
13749 &self,
13750 buffer: &Model<Buffer>,
13751 position: language::Anchor,
13752 text: &str,
13753 trigger_in_words: bool,
13754 cx: &mut ViewContext<Editor>,
13755 ) -> bool {
13756 if !EditorSettings::get_global(cx).show_completions_on_input {
13757 return false;
13758 }
13759
13760 let mut chars = text.chars();
13761 let char = if let Some(char) = chars.next() {
13762 char
13763 } else {
13764 return false;
13765 };
13766 if chars.next().is_some() {
13767 return false;
13768 }
13769
13770 let buffer = buffer.read(cx);
13771 let classifier = buffer
13772 .snapshot()
13773 .char_classifier_at(position)
13774 .for_completion(true);
13775 if trigger_in_words && classifier.is_word(char) {
13776 return true;
13777 }
13778
13779 buffer.completion_triggers().contains(text)
13780 }
13781}
13782
13783impl SemanticsProvider for Model<Project> {
13784 fn hover(
13785 &self,
13786 buffer: &Model<Buffer>,
13787 position: text::Anchor,
13788 cx: &mut AppContext,
13789 ) -> Option<Task<Vec<project::Hover>>> {
13790 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13791 }
13792
13793 fn document_highlights(
13794 &self,
13795 buffer: &Model<Buffer>,
13796 position: text::Anchor,
13797 cx: &mut AppContext,
13798 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13799 Some(self.update(cx, |project, cx| {
13800 project.document_highlights(buffer, position, cx)
13801 }))
13802 }
13803
13804 fn definitions(
13805 &self,
13806 buffer: &Model<Buffer>,
13807 position: text::Anchor,
13808 kind: GotoDefinitionKind,
13809 cx: &mut AppContext,
13810 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13811 Some(self.update(cx, |project, cx| match kind {
13812 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13813 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13814 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13815 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13816 }))
13817 }
13818
13819 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13820 // TODO: make this work for remote projects
13821 self.read(cx)
13822 .language_servers_for_buffer(buffer.read(cx), cx)
13823 .any(
13824 |(_, server)| match server.capabilities().inlay_hint_provider {
13825 Some(lsp::OneOf::Left(enabled)) => enabled,
13826 Some(lsp::OneOf::Right(_)) => true,
13827 None => false,
13828 },
13829 )
13830 }
13831
13832 fn inlay_hints(
13833 &self,
13834 buffer_handle: Model<Buffer>,
13835 range: Range<text::Anchor>,
13836 cx: &mut AppContext,
13837 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13838 Some(self.update(cx, |project, cx| {
13839 project.inlay_hints(buffer_handle, range, cx)
13840 }))
13841 }
13842
13843 fn resolve_inlay_hint(
13844 &self,
13845 hint: InlayHint,
13846 buffer_handle: Model<Buffer>,
13847 server_id: LanguageServerId,
13848 cx: &mut AppContext,
13849 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13850 Some(self.update(cx, |project, cx| {
13851 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13852 }))
13853 }
13854
13855 fn range_for_rename(
13856 &self,
13857 buffer: &Model<Buffer>,
13858 position: text::Anchor,
13859 cx: &mut AppContext,
13860 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13861 Some(self.update(cx, |project, cx| {
13862 project.prepare_rename(buffer.clone(), position, cx)
13863 }))
13864 }
13865
13866 fn perform_rename(
13867 &self,
13868 buffer: &Model<Buffer>,
13869 position: text::Anchor,
13870 new_name: String,
13871 cx: &mut AppContext,
13872 ) -> Option<Task<Result<ProjectTransaction>>> {
13873 Some(self.update(cx, |project, cx| {
13874 project.perform_rename(buffer.clone(), position, new_name, cx)
13875 }))
13876 }
13877}
13878
13879fn inlay_hint_settings(
13880 location: Anchor,
13881 snapshot: &MultiBufferSnapshot,
13882 cx: &mut ViewContext<'_, Editor>,
13883) -> InlayHintSettings {
13884 let file = snapshot.file_at(location);
13885 let language = snapshot.language_at(location).map(|l| l.name());
13886 language_settings(language, file, cx).inlay_hints
13887}
13888
13889fn consume_contiguous_rows(
13890 contiguous_row_selections: &mut Vec<Selection<Point>>,
13891 selection: &Selection<Point>,
13892 display_map: &DisplaySnapshot,
13893 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13894) -> (MultiBufferRow, MultiBufferRow) {
13895 contiguous_row_selections.push(selection.clone());
13896 let start_row = MultiBufferRow(selection.start.row);
13897 let mut end_row = ending_row(selection, display_map);
13898
13899 while let Some(next_selection) = selections.peek() {
13900 if next_selection.start.row <= end_row.0 {
13901 end_row = ending_row(next_selection, display_map);
13902 contiguous_row_selections.push(selections.next().unwrap().clone());
13903 } else {
13904 break;
13905 }
13906 }
13907 (start_row, end_row)
13908}
13909
13910fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13911 if next_selection.end.column > 0 || next_selection.is_empty() {
13912 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13913 } else {
13914 MultiBufferRow(next_selection.end.row)
13915 }
13916}
13917
13918impl EditorSnapshot {
13919 pub fn remote_selections_in_range<'a>(
13920 &'a self,
13921 range: &'a Range<Anchor>,
13922 collaboration_hub: &dyn CollaborationHub,
13923 cx: &'a AppContext,
13924 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13925 let participant_names = collaboration_hub.user_names(cx);
13926 let participant_indices = collaboration_hub.user_participant_indices(cx);
13927 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13928 let collaborators_by_replica_id = collaborators_by_peer_id
13929 .iter()
13930 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13931 .collect::<HashMap<_, _>>();
13932 self.buffer_snapshot
13933 .selections_in_range(range, false)
13934 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13935 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13936 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13937 let user_name = participant_names.get(&collaborator.user_id).cloned();
13938 Some(RemoteSelection {
13939 replica_id,
13940 selection,
13941 cursor_shape,
13942 line_mode,
13943 participant_index,
13944 peer_id: collaborator.peer_id,
13945 user_name,
13946 })
13947 })
13948 }
13949
13950 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13951 self.display_snapshot.buffer_snapshot.language_at(position)
13952 }
13953
13954 pub fn is_focused(&self) -> bool {
13955 self.is_focused
13956 }
13957
13958 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13959 self.placeholder_text.as_ref()
13960 }
13961
13962 pub fn scroll_position(&self) -> gpui::Point<f32> {
13963 self.scroll_anchor.scroll_position(&self.display_snapshot)
13964 }
13965
13966 fn gutter_dimensions(
13967 &self,
13968 font_id: FontId,
13969 font_size: Pixels,
13970 em_width: Pixels,
13971 em_advance: Pixels,
13972 max_line_number_width: Pixels,
13973 cx: &AppContext,
13974 ) -> GutterDimensions {
13975 if !self.show_gutter {
13976 return GutterDimensions::default();
13977 }
13978 let descent = cx.text_system().descent(font_id, font_size);
13979
13980 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13981 matches!(
13982 ProjectSettings::get_global(cx).git.git_gutter,
13983 Some(GitGutterSetting::TrackedFiles)
13984 )
13985 });
13986 let gutter_settings = EditorSettings::get_global(cx).gutter;
13987 let show_line_numbers = self
13988 .show_line_numbers
13989 .unwrap_or(gutter_settings.line_numbers);
13990 let line_gutter_width = if show_line_numbers {
13991 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13992 let min_width_for_number_on_gutter = em_advance * 4.0;
13993 max_line_number_width.max(min_width_for_number_on_gutter)
13994 } else {
13995 0.0.into()
13996 };
13997
13998 let show_code_actions = self
13999 .show_code_actions
14000 .unwrap_or(gutter_settings.code_actions);
14001
14002 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14003
14004 let git_blame_entries_width =
14005 self.git_blame_gutter_max_author_length
14006 .map(|max_author_length| {
14007 // Length of the author name, but also space for the commit hash,
14008 // the spacing and the timestamp.
14009 let max_char_count = max_author_length
14010 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14011 + 7 // length of commit sha
14012 + 14 // length of max relative timestamp ("60 minutes ago")
14013 + 4; // gaps and margins
14014
14015 em_advance * max_char_count
14016 });
14017
14018 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14019 left_padding += if show_code_actions || show_runnables {
14020 em_width * 3.0
14021 } else if show_git_gutter && show_line_numbers {
14022 em_width * 2.0
14023 } else if show_git_gutter || show_line_numbers {
14024 em_width
14025 } else {
14026 px(0.)
14027 };
14028
14029 let right_padding = if gutter_settings.folds && show_line_numbers {
14030 em_width * 4.0
14031 } else if gutter_settings.folds {
14032 em_width * 3.0
14033 } else if show_line_numbers {
14034 em_width
14035 } else {
14036 px(0.)
14037 };
14038
14039 GutterDimensions {
14040 left_padding,
14041 right_padding,
14042 width: line_gutter_width + left_padding + right_padding,
14043 margin: -descent,
14044 git_blame_entries_width,
14045 }
14046 }
14047
14048 pub fn render_fold_toggle(
14049 &self,
14050 buffer_row: MultiBufferRow,
14051 row_contains_cursor: bool,
14052 editor: View<Editor>,
14053 cx: &mut WindowContext,
14054 ) -> Option<AnyElement> {
14055 let folded = self.is_line_folded(buffer_row);
14056
14057 if let Some(crease) = self
14058 .crease_snapshot
14059 .query_row(buffer_row, &self.buffer_snapshot)
14060 {
14061 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14062 if folded {
14063 editor.update(cx, |editor, cx| {
14064 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14065 });
14066 } else {
14067 editor.update(cx, |editor, cx| {
14068 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14069 });
14070 }
14071 });
14072
14073 Some((crease.render_toggle)(
14074 buffer_row,
14075 folded,
14076 toggle_callback,
14077 cx,
14078 ))
14079 } else if folded
14080 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14081 {
14082 Some(
14083 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14084 .selected(folded)
14085 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14086 if folded {
14087 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14088 } else {
14089 this.fold_at(&FoldAt { buffer_row }, cx);
14090 }
14091 }))
14092 .into_any_element(),
14093 )
14094 } else {
14095 None
14096 }
14097 }
14098
14099 pub fn render_crease_trailer(
14100 &self,
14101 buffer_row: MultiBufferRow,
14102 cx: &mut WindowContext,
14103 ) -> Option<AnyElement> {
14104 let folded = self.is_line_folded(buffer_row);
14105 let crease = self
14106 .crease_snapshot
14107 .query_row(buffer_row, &self.buffer_snapshot)?;
14108 Some((crease.render_trailer)(buffer_row, folded, cx))
14109 }
14110}
14111
14112impl Deref for EditorSnapshot {
14113 type Target = DisplaySnapshot;
14114
14115 fn deref(&self) -> &Self::Target {
14116 &self.display_snapshot
14117 }
14118}
14119
14120#[derive(Clone, Debug, PartialEq, Eq)]
14121pub enum EditorEvent {
14122 InputIgnored {
14123 text: Arc<str>,
14124 },
14125 InputHandled {
14126 utf16_range_to_replace: Option<Range<isize>>,
14127 text: Arc<str>,
14128 },
14129 ExcerptsAdded {
14130 buffer: Model<Buffer>,
14131 predecessor: ExcerptId,
14132 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14133 },
14134 ExcerptsRemoved {
14135 ids: Vec<ExcerptId>,
14136 },
14137 ExcerptsEdited {
14138 ids: Vec<ExcerptId>,
14139 },
14140 ExcerptsExpanded {
14141 ids: Vec<ExcerptId>,
14142 },
14143 BufferEdited,
14144 Edited {
14145 transaction_id: clock::Lamport,
14146 },
14147 Reparsed(BufferId),
14148 Focused,
14149 FocusedIn,
14150 Blurred,
14151 DirtyChanged,
14152 Saved,
14153 TitleChanged,
14154 DiffBaseChanged,
14155 SelectionsChanged {
14156 local: bool,
14157 },
14158 ScrollPositionChanged {
14159 local: bool,
14160 autoscroll: bool,
14161 },
14162 Closed,
14163 TransactionUndone {
14164 transaction_id: clock::Lamport,
14165 },
14166 TransactionBegun {
14167 transaction_id: clock::Lamport,
14168 },
14169 Reloaded,
14170 CursorShapeChanged,
14171}
14172
14173impl EventEmitter<EditorEvent> for Editor {}
14174
14175impl FocusableView for Editor {
14176 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14177 self.focus_handle.clone()
14178 }
14179}
14180
14181impl Render for Editor {
14182 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14183 let settings = ThemeSettings::get_global(cx);
14184
14185 let mut text_style = match self.mode {
14186 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14187 color: cx.theme().colors().editor_foreground,
14188 font_family: settings.ui_font.family.clone(),
14189 font_features: settings.ui_font.features.clone(),
14190 font_fallbacks: settings.ui_font.fallbacks.clone(),
14191 font_size: rems(0.875).into(),
14192 font_weight: settings.ui_font.weight,
14193 line_height: relative(settings.buffer_line_height.value()),
14194 ..Default::default()
14195 },
14196 EditorMode::Full => TextStyle {
14197 color: cx.theme().colors().editor_foreground,
14198 font_family: settings.buffer_font.family.clone(),
14199 font_features: settings.buffer_font.features.clone(),
14200 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14201 font_size: settings.buffer_font_size(cx).into(),
14202 font_weight: settings.buffer_font.weight,
14203 line_height: relative(settings.buffer_line_height.value()),
14204 ..Default::default()
14205 },
14206 };
14207 if let Some(text_style_refinement) = &self.text_style_refinement {
14208 text_style.refine(text_style_refinement)
14209 }
14210
14211 let background = match self.mode {
14212 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14213 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14214 EditorMode::Full => cx.theme().colors().editor_background,
14215 };
14216
14217 EditorElement::new(
14218 cx.view(),
14219 EditorStyle {
14220 background,
14221 local_player: cx.theme().players().local(),
14222 text: text_style,
14223 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14224 syntax: cx.theme().syntax().clone(),
14225 status: cx.theme().status().clone(),
14226 inlay_hints_style: make_inlay_hints_style(cx),
14227 suggestions_style: HighlightStyle {
14228 color: Some(cx.theme().status().predictive),
14229 ..HighlightStyle::default()
14230 },
14231 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14232 },
14233 )
14234 }
14235}
14236
14237impl ViewInputHandler for Editor {
14238 fn text_for_range(
14239 &mut self,
14240 range_utf16: Range<usize>,
14241 cx: &mut ViewContext<Self>,
14242 ) -> Option<String> {
14243 Some(
14244 self.buffer
14245 .read(cx)
14246 .read(cx)
14247 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14248 .collect(),
14249 )
14250 }
14251
14252 fn selected_text_range(
14253 &mut self,
14254 ignore_disabled_input: bool,
14255 cx: &mut ViewContext<Self>,
14256 ) -> Option<UTF16Selection> {
14257 // Prevent the IME menu from appearing when holding down an alphabetic key
14258 // while input is disabled.
14259 if !ignore_disabled_input && !self.input_enabled {
14260 return None;
14261 }
14262
14263 let selection = self.selections.newest::<OffsetUtf16>(cx);
14264 let range = selection.range();
14265
14266 Some(UTF16Selection {
14267 range: range.start.0..range.end.0,
14268 reversed: selection.reversed,
14269 })
14270 }
14271
14272 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14273 let snapshot = self.buffer.read(cx).read(cx);
14274 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14275 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14276 }
14277
14278 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14279 self.clear_highlights::<InputComposition>(cx);
14280 self.ime_transaction.take();
14281 }
14282
14283 fn replace_text_in_range(
14284 &mut self,
14285 range_utf16: Option<Range<usize>>,
14286 text: &str,
14287 cx: &mut ViewContext<Self>,
14288 ) {
14289 if !self.input_enabled {
14290 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14291 return;
14292 }
14293
14294 self.transact(cx, |this, cx| {
14295 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14296 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14297 Some(this.selection_replacement_ranges(range_utf16, cx))
14298 } else {
14299 this.marked_text_ranges(cx)
14300 };
14301
14302 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14303 let newest_selection_id = this.selections.newest_anchor().id;
14304 this.selections
14305 .all::<OffsetUtf16>(cx)
14306 .iter()
14307 .zip(ranges_to_replace.iter())
14308 .find_map(|(selection, range)| {
14309 if selection.id == newest_selection_id {
14310 Some(
14311 (range.start.0 as isize - selection.head().0 as isize)
14312 ..(range.end.0 as isize - selection.head().0 as isize),
14313 )
14314 } else {
14315 None
14316 }
14317 })
14318 });
14319
14320 cx.emit(EditorEvent::InputHandled {
14321 utf16_range_to_replace: range_to_replace,
14322 text: text.into(),
14323 });
14324
14325 if let Some(new_selected_ranges) = new_selected_ranges {
14326 this.change_selections(None, cx, |selections| {
14327 selections.select_ranges(new_selected_ranges)
14328 });
14329 this.backspace(&Default::default(), cx);
14330 }
14331
14332 this.handle_input(text, cx);
14333 });
14334
14335 if let Some(transaction) = self.ime_transaction {
14336 self.buffer.update(cx, |buffer, cx| {
14337 buffer.group_until_transaction(transaction, cx);
14338 });
14339 }
14340
14341 self.unmark_text(cx);
14342 }
14343
14344 fn replace_and_mark_text_in_range(
14345 &mut self,
14346 range_utf16: Option<Range<usize>>,
14347 text: &str,
14348 new_selected_range_utf16: Option<Range<usize>>,
14349 cx: &mut ViewContext<Self>,
14350 ) {
14351 if !self.input_enabled {
14352 return;
14353 }
14354
14355 let transaction = self.transact(cx, |this, cx| {
14356 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14357 let snapshot = this.buffer.read(cx).read(cx);
14358 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14359 for marked_range in &mut marked_ranges {
14360 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14361 marked_range.start.0 += relative_range_utf16.start;
14362 marked_range.start =
14363 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14364 marked_range.end =
14365 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14366 }
14367 }
14368 Some(marked_ranges)
14369 } else if let Some(range_utf16) = range_utf16 {
14370 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14371 Some(this.selection_replacement_ranges(range_utf16, cx))
14372 } else {
14373 None
14374 };
14375
14376 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14377 let newest_selection_id = this.selections.newest_anchor().id;
14378 this.selections
14379 .all::<OffsetUtf16>(cx)
14380 .iter()
14381 .zip(ranges_to_replace.iter())
14382 .find_map(|(selection, range)| {
14383 if selection.id == newest_selection_id {
14384 Some(
14385 (range.start.0 as isize - selection.head().0 as isize)
14386 ..(range.end.0 as isize - selection.head().0 as isize),
14387 )
14388 } else {
14389 None
14390 }
14391 })
14392 });
14393
14394 cx.emit(EditorEvent::InputHandled {
14395 utf16_range_to_replace: range_to_replace,
14396 text: text.into(),
14397 });
14398
14399 if let Some(ranges) = ranges_to_replace {
14400 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14401 }
14402
14403 let marked_ranges = {
14404 let snapshot = this.buffer.read(cx).read(cx);
14405 this.selections
14406 .disjoint_anchors()
14407 .iter()
14408 .map(|selection| {
14409 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14410 })
14411 .collect::<Vec<_>>()
14412 };
14413
14414 if text.is_empty() {
14415 this.unmark_text(cx);
14416 } else {
14417 this.highlight_text::<InputComposition>(
14418 marked_ranges.clone(),
14419 HighlightStyle {
14420 underline: Some(UnderlineStyle {
14421 thickness: px(1.),
14422 color: None,
14423 wavy: false,
14424 }),
14425 ..Default::default()
14426 },
14427 cx,
14428 );
14429 }
14430
14431 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14432 let use_autoclose = this.use_autoclose;
14433 let use_auto_surround = this.use_auto_surround;
14434 this.set_use_autoclose(false);
14435 this.set_use_auto_surround(false);
14436 this.handle_input(text, cx);
14437 this.set_use_autoclose(use_autoclose);
14438 this.set_use_auto_surround(use_auto_surround);
14439
14440 if let Some(new_selected_range) = new_selected_range_utf16 {
14441 let snapshot = this.buffer.read(cx).read(cx);
14442 let new_selected_ranges = marked_ranges
14443 .into_iter()
14444 .map(|marked_range| {
14445 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14446 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14447 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14448 snapshot.clip_offset_utf16(new_start, Bias::Left)
14449 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14450 })
14451 .collect::<Vec<_>>();
14452
14453 drop(snapshot);
14454 this.change_selections(None, cx, |selections| {
14455 selections.select_ranges(new_selected_ranges)
14456 });
14457 }
14458 });
14459
14460 self.ime_transaction = self.ime_transaction.or(transaction);
14461 if let Some(transaction) = self.ime_transaction {
14462 self.buffer.update(cx, |buffer, cx| {
14463 buffer.group_until_transaction(transaction, cx);
14464 });
14465 }
14466
14467 if self.text_highlights::<InputComposition>(cx).is_none() {
14468 self.ime_transaction.take();
14469 }
14470 }
14471
14472 fn bounds_for_range(
14473 &mut self,
14474 range_utf16: Range<usize>,
14475 element_bounds: gpui::Bounds<Pixels>,
14476 cx: &mut ViewContext<Self>,
14477 ) -> Option<gpui::Bounds<Pixels>> {
14478 let text_layout_details = self.text_layout_details(cx);
14479 let style = &text_layout_details.editor_style;
14480 let font_id = cx.text_system().resolve_font(&style.text.font());
14481 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14482 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14483
14484 let em_width = cx
14485 .text_system()
14486 .typographic_bounds(font_id, font_size, 'm')
14487 .unwrap()
14488 .size
14489 .width;
14490
14491 let snapshot = self.snapshot(cx);
14492 let scroll_position = snapshot.scroll_position();
14493 let scroll_left = scroll_position.x * em_width;
14494
14495 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14496 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14497 + self.gutter_dimensions.width;
14498 let y = line_height * (start.row().as_f32() - scroll_position.y);
14499
14500 Some(Bounds {
14501 origin: element_bounds.origin + point(x, y),
14502 size: size(em_width, line_height),
14503 })
14504 }
14505}
14506
14507trait SelectionExt {
14508 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14509 fn spanned_rows(
14510 &self,
14511 include_end_if_at_line_start: bool,
14512 map: &DisplaySnapshot,
14513 ) -> Range<MultiBufferRow>;
14514}
14515
14516impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14517 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14518 let start = self
14519 .start
14520 .to_point(&map.buffer_snapshot)
14521 .to_display_point(map);
14522 let end = self
14523 .end
14524 .to_point(&map.buffer_snapshot)
14525 .to_display_point(map);
14526 if self.reversed {
14527 end..start
14528 } else {
14529 start..end
14530 }
14531 }
14532
14533 fn spanned_rows(
14534 &self,
14535 include_end_if_at_line_start: bool,
14536 map: &DisplaySnapshot,
14537 ) -> Range<MultiBufferRow> {
14538 let start = self.start.to_point(&map.buffer_snapshot);
14539 let mut end = self.end.to_point(&map.buffer_snapshot);
14540 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14541 end.row -= 1;
14542 }
14543
14544 let buffer_start = map.prev_line_boundary(start).0;
14545 let buffer_end = map.next_line_boundary(end).0;
14546 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14547 }
14548}
14549
14550impl<T: InvalidationRegion> InvalidationStack<T> {
14551 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14552 where
14553 S: Clone + ToOffset,
14554 {
14555 while let Some(region) = self.last() {
14556 let all_selections_inside_invalidation_ranges =
14557 if selections.len() == region.ranges().len() {
14558 selections
14559 .iter()
14560 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14561 .all(|(selection, invalidation_range)| {
14562 let head = selection.head().to_offset(buffer);
14563 invalidation_range.start <= head && invalidation_range.end >= head
14564 })
14565 } else {
14566 false
14567 };
14568
14569 if all_selections_inside_invalidation_ranges {
14570 break;
14571 } else {
14572 self.pop();
14573 }
14574 }
14575 }
14576}
14577
14578impl<T> Default for InvalidationStack<T> {
14579 fn default() -> Self {
14580 Self(Default::default())
14581 }
14582}
14583
14584impl<T> Deref for InvalidationStack<T> {
14585 type Target = Vec<T>;
14586
14587 fn deref(&self) -> &Self::Target {
14588 &self.0
14589 }
14590}
14591
14592impl<T> DerefMut for InvalidationStack<T> {
14593 fn deref_mut(&mut self) -> &mut Self::Target {
14594 &mut self.0
14595 }
14596}
14597
14598impl InvalidationRegion for SnippetState {
14599 fn ranges(&self) -> &[Range<Anchor>] {
14600 &self.ranges[self.active_index]
14601 }
14602}
14603
14604pub fn diagnostic_block_renderer(
14605 diagnostic: Diagnostic,
14606 max_message_rows: Option<u8>,
14607 allow_closing: bool,
14608 _is_valid: bool,
14609) -> RenderBlock {
14610 let (text_without_backticks, code_ranges) =
14611 highlight_diagnostic_message(&diagnostic, max_message_rows);
14612
14613 Box::new(move |cx: &mut BlockContext| {
14614 let group_id: SharedString = cx.block_id.to_string().into();
14615
14616 let mut text_style = cx.text_style().clone();
14617 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14618 let theme_settings = ThemeSettings::get_global(cx);
14619 text_style.font_family = theme_settings.buffer_font.family.clone();
14620 text_style.font_style = theme_settings.buffer_font.style;
14621 text_style.font_features = theme_settings.buffer_font.features.clone();
14622 text_style.font_weight = theme_settings.buffer_font.weight;
14623
14624 let multi_line_diagnostic = diagnostic.message.contains('\n');
14625
14626 let buttons = |diagnostic: &Diagnostic| {
14627 if multi_line_diagnostic {
14628 v_flex()
14629 } else {
14630 h_flex()
14631 }
14632 .when(allow_closing, |div| {
14633 div.children(diagnostic.is_primary.then(|| {
14634 IconButton::new("close-block", IconName::XCircle)
14635 .icon_color(Color::Muted)
14636 .size(ButtonSize::Compact)
14637 .style(ButtonStyle::Transparent)
14638 .visible_on_hover(group_id.clone())
14639 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14640 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14641 }))
14642 })
14643 .child(
14644 IconButton::new("copy-block", IconName::Copy)
14645 .icon_color(Color::Muted)
14646 .size(ButtonSize::Compact)
14647 .style(ButtonStyle::Transparent)
14648 .visible_on_hover(group_id.clone())
14649 .on_click({
14650 let message = diagnostic.message.clone();
14651 move |_click, cx| {
14652 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14653 }
14654 })
14655 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14656 )
14657 };
14658
14659 let icon_size = buttons(&diagnostic)
14660 .into_any_element()
14661 .layout_as_root(AvailableSpace::min_size(), cx);
14662
14663 h_flex()
14664 .id(cx.block_id)
14665 .group(group_id.clone())
14666 .relative()
14667 .size_full()
14668 .pl(cx.gutter_dimensions.width)
14669 .w(cx.max_width - cx.gutter_dimensions.full_width())
14670 .child(
14671 div()
14672 .flex()
14673 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14674 .flex_shrink(),
14675 )
14676 .child(buttons(&diagnostic))
14677 .child(div().flex().flex_shrink_0().child(
14678 StyledText::new(text_without_backticks.clone()).with_highlights(
14679 &text_style,
14680 code_ranges.iter().map(|range| {
14681 (
14682 range.clone(),
14683 HighlightStyle {
14684 font_weight: Some(FontWeight::BOLD),
14685 ..Default::default()
14686 },
14687 )
14688 }),
14689 ),
14690 ))
14691 .into_any_element()
14692 })
14693}
14694
14695pub fn highlight_diagnostic_message(
14696 diagnostic: &Diagnostic,
14697 mut max_message_rows: Option<u8>,
14698) -> (SharedString, Vec<Range<usize>>) {
14699 let mut text_without_backticks = String::new();
14700 let mut code_ranges = Vec::new();
14701
14702 if let Some(source) = &diagnostic.source {
14703 text_without_backticks.push_str(source);
14704 code_ranges.push(0..source.len());
14705 text_without_backticks.push_str(": ");
14706 }
14707
14708 let mut prev_offset = 0;
14709 let mut in_code_block = false;
14710 let has_row_limit = max_message_rows.is_some();
14711 let mut newline_indices = diagnostic
14712 .message
14713 .match_indices('\n')
14714 .filter(|_| has_row_limit)
14715 .map(|(ix, _)| ix)
14716 .fuse()
14717 .peekable();
14718
14719 for (quote_ix, _) in diagnostic
14720 .message
14721 .match_indices('`')
14722 .chain([(diagnostic.message.len(), "")])
14723 {
14724 let mut first_newline_ix = None;
14725 let mut last_newline_ix = None;
14726 while let Some(newline_ix) = newline_indices.peek() {
14727 if *newline_ix < quote_ix {
14728 if first_newline_ix.is_none() {
14729 first_newline_ix = Some(*newline_ix);
14730 }
14731 last_newline_ix = Some(*newline_ix);
14732
14733 if let Some(rows_left) = &mut max_message_rows {
14734 if *rows_left == 0 {
14735 break;
14736 } else {
14737 *rows_left -= 1;
14738 }
14739 }
14740 let _ = newline_indices.next();
14741 } else {
14742 break;
14743 }
14744 }
14745 let prev_len = text_without_backticks.len();
14746 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14747 text_without_backticks.push_str(new_text);
14748 if in_code_block {
14749 code_ranges.push(prev_len..text_without_backticks.len());
14750 }
14751 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14752 in_code_block = !in_code_block;
14753 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14754 text_without_backticks.push_str("...");
14755 break;
14756 }
14757 }
14758
14759 (text_without_backticks.into(), code_ranges)
14760}
14761
14762fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14763 match severity {
14764 DiagnosticSeverity::ERROR => colors.error,
14765 DiagnosticSeverity::WARNING => colors.warning,
14766 DiagnosticSeverity::INFORMATION => colors.info,
14767 DiagnosticSeverity::HINT => colors.info,
14768 _ => colors.ignored,
14769 }
14770}
14771
14772pub fn styled_runs_for_code_label<'a>(
14773 label: &'a CodeLabel,
14774 syntax_theme: &'a theme::SyntaxTheme,
14775) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14776 let fade_out = HighlightStyle {
14777 fade_out: Some(0.35),
14778 ..Default::default()
14779 };
14780
14781 let mut prev_end = label.filter_range.end;
14782 label
14783 .runs
14784 .iter()
14785 .enumerate()
14786 .flat_map(move |(ix, (range, highlight_id))| {
14787 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14788 style
14789 } else {
14790 return Default::default();
14791 };
14792 let mut muted_style = style;
14793 muted_style.highlight(fade_out);
14794
14795 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14796 if range.start >= label.filter_range.end {
14797 if range.start > prev_end {
14798 runs.push((prev_end..range.start, fade_out));
14799 }
14800 runs.push((range.clone(), muted_style));
14801 } else if range.end <= label.filter_range.end {
14802 runs.push((range.clone(), style));
14803 } else {
14804 runs.push((range.start..label.filter_range.end, style));
14805 runs.push((label.filter_range.end..range.end, muted_style));
14806 }
14807 prev_end = cmp::max(prev_end, range.end);
14808
14809 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14810 runs.push((prev_end..label.text.len(), fade_out));
14811 }
14812
14813 runs
14814 })
14815}
14816
14817pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14818 let mut prev_index = 0;
14819 let mut prev_codepoint: Option<char> = None;
14820 text.char_indices()
14821 .chain([(text.len(), '\0')])
14822 .filter_map(move |(index, codepoint)| {
14823 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14824 let is_boundary = index == text.len()
14825 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14826 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14827 if is_boundary {
14828 let chunk = &text[prev_index..index];
14829 prev_index = index;
14830 Some(chunk)
14831 } else {
14832 None
14833 }
14834 })
14835}
14836
14837pub trait RangeToAnchorExt: Sized {
14838 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14839
14840 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14841 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14842 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14843 }
14844}
14845
14846impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14847 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14848 let start_offset = self.start.to_offset(snapshot);
14849 let end_offset = self.end.to_offset(snapshot);
14850 if start_offset == end_offset {
14851 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14852 } else {
14853 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14854 }
14855 }
14856}
14857
14858pub trait RowExt {
14859 fn as_f32(&self) -> f32;
14860
14861 fn next_row(&self) -> Self;
14862
14863 fn previous_row(&self) -> Self;
14864
14865 fn minus(&self, other: Self) -> u32;
14866}
14867
14868impl RowExt for DisplayRow {
14869 fn as_f32(&self) -> f32 {
14870 self.0 as f32
14871 }
14872
14873 fn next_row(&self) -> Self {
14874 Self(self.0 + 1)
14875 }
14876
14877 fn previous_row(&self) -> Self {
14878 Self(self.0.saturating_sub(1))
14879 }
14880
14881 fn minus(&self, other: Self) -> u32 {
14882 self.0 - other.0
14883 }
14884}
14885
14886impl RowExt for MultiBufferRow {
14887 fn as_f32(&self) -> f32 {
14888 self.0 as f32
14889 }
14890
14891 fn next_row(&self) -> Self {
14892 Self(self.0 + 1)
14893 }
14894
14895 fn previous_row(&self) -> Self {
14896 Self(self.0.saturating_sub(1))
14897 }
14898
14899 fn minus(&self, other: Self) -> u32 {
14900 self.0 - other.0
14901 }
14902}
14903
14904trait RowRangeExt {
14905 type Row;
14906
14907 fn len(&self) -> usize;
14908
14909 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14910}
14911
14912impl RowRangeExt for Range<MultiBufferRow> {
14913 type Row = MultiBufferRow;
14914
14915 fn len(&self) -> usize {
14916 (self.end.0 - self.start.0) as usize
14917 }
14918
14919 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14920 (self.start.0..self.end.0).map(MultiBufferRow)
14921 }
14922}
14923
14924impl RowRangeExt for Range<DisplayRow> {
14925 type Row = DisplayRow;
14926
14927 fn len(&self) -> usize {
14928 (self.end.0 - self.start.0) as usize
14929 }
14930
14931 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14932 (self.start.0..self.end.0).map(DisplayRow)
14933 }
14934}
14935
14936fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14937 if hunk.diff_base_byte_range.is_empty() {
14938 DiffHunkStatus::Added
14939 } else if hunk.row_range.is_empty() {
14940 DiffHunkStatus::Removed
14941 } else {
14942 DiffHunkStatus::Modified
14943 }
14944}
14945
14946/// If select range has more than one line, we
14947/// just point the cursor to range.start.
14948fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14949 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14950 range
14951 } else {
14952 range.start..range.start
14953 }
14954}
14955
14956const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);