1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::DiffHunkStatus;
50pub(crate) use actions::*;
51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use gpui::{
74 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
75 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
76 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
77 FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
78 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
79 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
80 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
81 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
82};
83use highlight_matching_bracket::refresh_matching_bracket_highlights;
84use hover_popover::{hide_hover, HoverState};
85pub(crate) use hunk_diff::HoveredHunk;
86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
87use indent_guides::ActiveIndentGuidesState;
88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
89pub use inline_completion::Direction;
90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use std::iter::Peekable;
106use task::{ResolvedTask, TaskTemplate, TaskVariables};
107
108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
109pub use lsp::CompletionContext;
110use lsp::{
111 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
112 LanguageServerId, LanguageServerName,
113};
114use mouse_context_menu::MouseContextMenu;
115use movement::TextLayoutDetails;
116pub use multi_buffer::{
117 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
118 ToPoint,
119};
120use multi_buffer::{
121 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
122};
123use ordered_float::OrderedFloat;
124use parking_lot::{Mutex, RwLock};
125use project::{
126 lsp_store::{FormatTarget, FormatTrigger},
127 project_settings::{GitGutterSetting, ProjectSettings},
128 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
129 Project, ProjectItem, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{
135 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
136};
137use serde::{Deserialize, Serialize};
138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
139use smallvec::SmallVec;
140use snippet::Snippet;
141use std::{
142 any::TypeId,
143 borrow::Cow,
144 cell::RefCell,
145 cmp::{self, Ordering, Reverse},
146 mem,
147 num::NonZeroU32,
148 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
149 path::{Path, PathBuf},
150 rc::Rc,
151 sync::Arc,
152 time::{Duration, Instant},
153};
154pub use sum_tree::Bias;
155use sum_tree::TreeMap;
156use text::{BufferId, OffsetUtf16, Rope};
157use theme::{
158 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
159 ThemeColors, ThemeSettings,
160};
161use ui::{
162 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
163 ListItem, Popover, PopoverMenuHandle, Tooltip,
164};
165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
166use workspace::item::{ItemHandle, PreviewTabsSettings};
167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
168use workspace::{
169 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
170};
171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
172
173use crate::hover_links::find_url;
174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
175
176pub const FILE_HEADER_HEIGHT: u32 = 2;
177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
181const MAX_LINE_LEN: usize = 1024;
182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
185#[doc(hidden)]
186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
187#[doc(hidden)]
188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakView<Workspace>>,
198 cx: &mut WindowContext,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(link_ranges, move |clicked_range_ix, cx| {
243 match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace.open_abs_path(path.clone(), false, cx).detach();
249 });
250 }
251 }
252 }
253 })
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
257pub(crate) enum InlayId {
258 Suggestion(usize),
259 Hint(usize),
260}
261
262impl InlayId {
263 fn id(&self) -> usize {
264 match self {
265 Self::Suggestion(id) => *id,
266 Self::Hint(id) => *id,
267 }
268 }
269}
270
271enum DiffRowHighlight {}
272enum DocumentHighlightRead {}
273enum DocumentHighlightWrite {}
274enum InputComposition {}
275
276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
277pub enum Navigated {
278 Yes,
279 No,
280}
281
282impl Navigated {
283 pub fn from_bool(yes: bool) -> Navigated {
284 if yes {
285 Navigated::Yes
286 } else {
287 Navigated::No
288 }
289 }
290}
291
292pub fn init_settings(cx: &mut AppContext) {
293 EditorSettings::register(cx);
294}
295
296pub fn init(cx: &mut AppContext) {
297 init_settings(cx);
298
299 workspace::register_project_item::<Editor>(cx);
300 workspace::FollowableViewRegistry::register::<Editor>(cx);
301 workspace::register_serializable_item::<Editor>(cx);
302
303 cx.observe_new_views(
304 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
305 workspace.register_action(Editor::new_file);
306 workspace.register_action(Editor::new_file_vertical);
307 workspace.register_action(Editor::new_file_horizontal);
308 },
309 )
310 .detach();
311
312 cx.on_action(move |_: &workspace::NewFile, cx| {
313 let app_state = workspace::AppState::global(cx);
314 if let Some(app_state) = app_state.upgrade() {
315 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
316 Editor::new_file(workspace, &Default::default(), cx)
317 })
318 .detach();
319 }
320 });
321 cx.on_action(move |_: &workspace::NewWindow, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
325 Editor::new_file(workspace, &Default::default(), cx)
326 })
327 .detach();
328 }
329 });
330}
331
332pub struct SearchWithinRange;
333
334trait InvalidationRegion {
335 fn ranges(&self) -> &[Range<Anchor>];
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub enum SelectPhase {
340 Begin {
341 position: DisplayPoint,
342 add: bool,
343 click_count: usize,
344 },
345 BeginColumnar {
346 position: DisplayPoint,
347 reset: bool,
348 goal_column: u32,
349 },
350 Extend {
351 position: DisplayPoint,
352 click_count: usize,
353 },
354 Update {
355 position: DisplayPoint,
356 goal_column: u32,
357 scroll_delta: gpui::Point<f32>,
358 },
359 End,
360}
361
362#[derive(Clone, Debug)]
363pub enum SelectMode {
364 Character,
365 Word(Range<Anchor>),
366 Line(Range<Anchor>),
367 All,
368}
369
370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
371pub enum EditorMode {
372 SingleLine { auto_width: bool },
373 AutoHeight { max_lines: usize },
374 Full,
375}
376
377#[derive(Copy, Clone, Debug)]
378pub enum SoftWrap {
379 /// Prefer not to wrap at all.
380 ///
381 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
382 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
383 GitDiff,
384 /// Prefer a single line generally, unless an overly long line is encountered.
385 None,
386 /// Soft wrap lines that exceed the editor width.
387 EditorWidth,
388 /// Soft wrap lines at the preferred line length.
389 Column(u32),
390 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
391 Bounded(u32),
392}
393
394#[derive(Clone)]
395pub struct EditorStyle {
396 pub background: Hsla,
397 pub local_player: PlayerColor,
398 pub text: TextStyle,
399 pub scrollbar_width: Pixels,
400 pub syntax: Arc<SyntaxTheme>,
401 pub status: StatusColors,
402 pub inlay_hints_style: HighlightStyle,
403 pub suggestions_style: HighlightStyle,
404 pub unnecessary_code_fade: f32,
405}
406
407impl Default for EditorStyle {
408 fn default() -> Self {
409 Self {
410 background: Hsla::default(),
411 local_player: PlayerColor::default(),
412 text: TextStyle::default(),
413 scrollbar_width: Pixels::default(),
414 syntax: Default::default(),
415 // HACK: Status colors don't have a real default.
416 // We should look into removing the status colors from the editor
417 // style and retrieve them directly from the theme.
418 status: StatusColors::dark(),
419 inlay_hints_style: HighlightStyle::default(),
420 suggestions_style: HighlightStyle::default(),
421 unnecessary_code_fade: Default::default(),
422 }
423 }
424}
425
426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
427 let show_background = language_settings::language_settings(None, None, cx)
428 .inlay_hints
429 .show_background;
430
431 HighlightStyle {
432 color: Some(cx.theme().status().hint),
433 background_color: show_background.then(|| cx.theme().status().hint_background),
434 ..HighlightStyle::default()
435 }
436}
437
438type CompletionId = usize;
439
440#[derive(Clone, Debug)]
441struct CompletionState {
442 // render_inlay_ids represents the inlay hints that are inserted
443 // for rendering the inline completions. They may be discontinuous
444 // in the event that the completion provider returns some intersection
445 // with the existing content.
446 render_inlay_ids: Vec<InlayId>,
447 // text is the resulting rope that is inserted when the user accepts a completion.
448 text: Rope,
449 // position is the position of the cursor when the completion was triggered.
450 position: multi_buffer::Anchor,
451 // delete_range is the range of text that this completion state covers.
452 // if the completion is accepted, this range should be deleted.
453 delete_range: Option<Range<multi_buffer::Anchor>>,
454}
455
456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
457struct EditorActionId(usize);
458
459impl EditorActionId {
460 pub fn post_inc(&mut self) -> Self {
461 let answer = self.0;
462
463 *self = Self(answer + 1);
464
465 Self(answer)
466 }
467}
468
469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
471
472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
474
475#[derive(Default)]
476struct ScrollbarMarkerState {
477 scrollbar_size: Size<Pixels>,
478 dirty: bool,
479 markers: Arc<[PaintQuad]>,
480 pending_refresh: Option<Task<Result<()>>>,
481}
482
483impl ScrollbarMarkerState {
484 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
485 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
486 }
487}
488
489#[derive(Clone, Debug)]
490struct RunnableTasks {
491 templates: Vec<(TaskSourceKind, TaskTemplate)>,
492 offset: MultiBufferOffset,
493 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
494 column: u32,
495 // Values of all named captures, including those starting with '_'
496 extra_variables: HashMap<String, String>,
497 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
498 context_range: Range<BufferOffset>,
499}
500
501impl RunnableTasks {
502 fn resolve<'a>(
503 &'a self,
504 cx: &'a task::TaskContext,
505 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
506 self.templates.iter().filter_map(|(kind, template)| {
507 template
508 .resolve_task(&kind.to_id_base(), cx)
509 .map(|task| (kind.clone(), task))
510 })
511 }
512}
513
514#[derive(Clone)]
515struct ResolvedTasks {
516 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
517 position: Anchor,
518}
519#[derive(Copy, Clone, Debug)]
520struct MultiBufferOffset(usize);
521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
522struct BufferOffset(usize);
523
524// Addons allow storing per-editor state in other crates (e.g. Vim)
525pub trait Addon: 'static {
526 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
527
528 fn to_any(&self) -> &dyn std::any::Any;
529}
530
531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
532pub enum IsVimMode {
533 Yes,
534 No,
535}
536
537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
538///
539/// See the [module level documentation](self) for more information.
540pub struct Editor {
541 focus_handle: FocusHandle,
542 last_focused_descendant: Option<WeakFocusHandle>,
543 /// The text buffer being edited
544 buffer: Model<MultiBuffer>,
545 /// Map of how text in the buffer should be displayed.
546 /// Handles soft wraps, folds, fake inlay text insertions, etc.
547 pub display_map: Model<DisplayMap>,
548 pub selections: SelectionsCollection,
549 pub scroll_manager: ScrollManager,
550 /// When inline assist editors are linked, they all render cursors because
551 /// typing enters text into each of them, even the ones that aren't focused.
552 pub(crate) show_cursor_when_unfocused: bool,
553 columnar_selection_tail: Option<Anchor>,
554 add_selections_state: Option<AddSelectionsState>,
555 select_next_state: Option<SelectNextState>,
556 select_prev_state: Option<SelectNextState>,
557 selection_history: SelectionHistory,
558 autoclose_regions: Vec<AutocloseRegion>,
559 snippet_stack: InvalidationStack<SnippetState>,
560 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
561 ime_transaction: Option<TransactionId>,
562 active_diagnostics: Option<ActiveDiagnosticGroup>,
563 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
564
565 project: Option<Model<Project>>,
566 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
567 completion_provider: Option<Box<dyn CompletionProvider>>,
568 collaboration_hub: Option<Box<dyn CollaborationHub>>,
569 blink_manager: Model<BlinkManager>,
570 show_cursor_names: bool,
571 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
572 pub show_local_selections: bool,
573 mode: EditorMode,
574 show_breadcrumbs: bool,
575 show_gutter: bool,
576 show_line_numbers: Option<bool>,
577 use_relative_line_numbers: Option<bool>,
578 show_git_diff_gutter: Option<bool>,
579 show_code_actions: Option<bool>,
580 show_runnables: Option<bool>,
581 show_wrap_guides: Option<bool>,
582 show_indent_guides: Option<bool>,
583 placeholder_text: Option<Arc<str>>,
584 highlight_order: usize,
585 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
586 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
587 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
588 scrollbar_marker_state: ScrollbarMarkerState,
589 active_indent_guides_state: ActiveIndentGuidesState,
590 nav_history: Option<ItemNavHistory>,
591 context_menu: RwLock<Option<ContextMenu>>,
592 mouse_context_menu: Option<MouseContextMenu>,
593 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
594 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
595 signature_help_state: SignatureHelpState,
596 auto_signature_help: Option<bool>,
597 find_all_references_task_sources: Vec<Anchor>,
598 next_completion_id: CompletionId,
599 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
600 code_actions_task: Option<Task<Result<()>>>,
601 document_highlights_task: Option<Task<()>>,
602 linked_editing_range_task: Option<Task<Option<()>>>,
603 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
604 pending_rename: Option<RenameState>,
605 searchable: bool,
606 cursor_shape: CursorShape,
607 current_line_highlight: Option<CurrentLineHighlight>,
608 collapse_matches: bool,
609 autoindent_mode: Option<AutoindentMode>,
610 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
611 input_enabled: bool,
612 use_modal_editing: bool,
613 read_only: bool,
614 leader_peer_id: Option<PeerId>,
615 remote_id: Option<ViewId>,
616 hover_state: HoverState,
617 gutter_hovered: bool,
618 hovered_link_state: Option<HoveredLinkState>,
619 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
620 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
621 active_inline_completion: Option<CompletionState>,
622 // enable_inline_completions is a switch that Vim can use to disable
623 // inline completions based on its mode.
624 enable_inline_completions: bool,
625 show_inline_completions_override: Option<bool>,
626 inlay_hint_cache: InlayHintCache,
627 expanded_hunks: ExpandedHunks,
628 next_inlay_id: usize,
629 _subscriptions: Vec<Subscription>,
630 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
631 gutter_dimensions: GutterDimensions,
632 style: Option<EditorStyle>,
633 text_style_refinement: Option<TextStyleRefinement>,
634 next_editor_action_id: EditorActionId,
635 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
636 use_autoclose: bool,
637 use_auto_surround: bool,
638 auto_replace_emoji_shortcode: bool,
639 show_git_blame_gutter: bool,
640 show_git_blame_inline: bool,
641 show_git_blame_inline_delay_task: Option<Task<()>>,
642 git_blame_inline_enabled: bool,
643 serialize_dirty_buffers: bool,
644 show_selection_menu: Option<bool>,
645 blame: Option<Model<GitBlame>>,
646 blame_subscription: Option<Subscription>,
647 custom_context_menu: Option<
648 Box<
649 dyn 'static
650 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
651 >,
652 >,
653 last_bounds: Option<Bounds<Pixels>>,
654 expect_bounds_change: Option<Bounds<Pixels>>,
655 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
656 tasks_update_task: Option<Task<()>>,
657 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
658 breadcrumb_header: Option<String>,
659 focused_block: Option<FocusedBlock>,
660 next_scroll_position: NextScrollCursorCenterTopBottom,
661 addons: HashMap<TypeId, Box<dyn Addon>>,
662 _scroll_cursor_center_top_bottom_task: Task<()>,
663}
664
665#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
666enum NextScrollCursorCenterTopBottom {
667 #[default]
668 Center,
669 Top,
670 Bottom,
671}
672
673impl NextScrollCursorCenterTopBottom {
674 fn next(&self) -> Self {
675 match self {
676 Self::Center => Self::Top,
677 Self::Top => Self::Bottom,
678 Self::Bottom => Self::Center,
679 }
680 }
681}
682
683#[derive(Clone)]
684pub struct EditorSnapshot {
685 pub mode: EditorMode,
686 show_gutter: bool,
687 show_line_numbers: Option<bool>,
688 show_git_diff_gutter: Option<bool>,
689 show_code_actions: Option<bool>,
690 show_runnables: Option<bool>,
691 git_blame_gutter_max_author_length: Option<usize>,
692 pub display_snapshot: DisplaySnapshot,
693 pub placeholder_text: Option<Arc<str>>,
694 is_focused: bool,
695 scroll_anchor: ScrollAnchor,
696 ongoing_scroll: OngoingScroll,
697 current_line_highlight: CurrentLineHighlight,
698 gutter_hovered: bool,
699}
700
701const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
702
703#[derive(Default, Debug, Clone, Copy)]
704pub struct GutterDimensions {
705 pub left_padding: Pixels,
706 pub right_padding: Pixels,
707 pub width: Pixels,
708 pub margin: Pixels,
709 pub git_blame_entries_width: Option<Pixels>,
710}
711
712impl GutterDimensions {
713 /// The full width of the space taken up by the gutter.
714 pub fn full_width(&self) -> Pixels {
715 self.margin + self.width
716 }
717
718 /// The width of the space reserved for the fold indicators,
719 /// use alongside 'justify_end' and `gutter_width` to
720 /// right align content with the line numbers
721 pub fn fold_area_width(&self) -> Pixels {
722 self.margin + self.right_padding
723 }
724}
725
726#[derive(Debug)]
727pub struct RemoteSelection {
728 pub replica_id: ReplicaId,
729 pub selection: Selection<Anchor>,
730 pub cursor_shape: CursorShape,
731 pub peer_id: PeerId,
732 pub line_mode: bool,
733 pub participant_index: Option<ParticipantIndex>,
734 pub user_name: Option<SharedString>,
735}
736
737#[derive(Clone, Debug)]
738struct SelectionHistoryEntry {
739 selections: Arc<[Selection<Anchor>]>,
740 select_next_state: Option<SelectNextState>,
741 select_prev_state: Option<SelectNextState>,
742 add_selections_state: Option<AddSelectionsState>,
743}
744
745enum SelectionHistoryMode {
746 Normal,
747 Undoing,
748 Redoing,
749}
750
751#[derive(Clone, PartialEq, Eq, Hash)]
752struct HoveredCursor {
753 replica_id: u16,
754 selection_id: usize,
755}
756
757impl Default for SelectionHistoryMode {
758 fn default() -> Self {
759 Self::Normal
760 }
761}
762
763#[derive(Default)]
764struct SelectionHistory {
765 #[allow(clippy::type_complexity)]
766 selections_by_transaction:
767 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
768 mode: SelectionHistoryMode,
769 undo_stack: VecDeque<SelectionHistoryEntry>,
770 redo_stack: VecDeque<SelectionHistoryEntry>,
771}
772
773impl SelectionHistory {
774 fn insert_transaction(
775 &mut self,
776 transaction_id: TransactionId,
777 selections: Arc<[Selection<Anchor>]>,
778 ) {
779 self.selections_by_transaction
780 .insert(transaction_id, (selections, None));
781 }
782
783 #[allow(clippy::type_complexity)]
784 fn transaction(
785 &self,
786 transaction_id: TransactionId,
787 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
788 self.selections_by_transaction.get(&transaction_id)
789 }
790
791 #[allow(clippy::type_complexity)]
792 fn transaction_mut(
793 &mut self,
794 transaction_id: TransactionId,
795 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
796 self.selections_by_transaction.get_mut(&transaction_id)
797 }
798
799 fn push(&mut self, entry: SelectionHistoryEntry) {
800 if !entry.selections.is_empty() {
801 match self.mode {
802 SelectionHistoryMode::Normal => {
803 self.push_undo(entry);
804 self.redo_stack.clear();
805 }
806 SelectionHistoryMode::Undoing => self.push_redo(entry),
807 SelectionHistoryMode::Redoing => self.push_undo(entry),
808 }
809 }
810 }
811
812 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
813 if self
814 .undo_stack
815 .back()
816 .map_or(true, |e| e.selections != entry.selections)
817 {
818 self.undo_stack.push_back(entry);
819 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
820 self.undo_stack.pop_front();
821 }
822 }
823 }
824
825 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
826 if self
827 .redo_stack
828 .back()
829 .map_or(true, |e| e.selections != entry.selections)
830 {
831 self.redo_stack.push_back(entry);
832 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
833 self.redo_stack.pop_front();
834 }
835 }
836 }
837}
838
839struct RowHighlight {
840 index: usize,
841 range: Range<Anchor>,
842 color: Hsla,
843 should_autoscroll: bool,
844}
845
846#[derive(Clone, Debug)]
847struct AddSelectionsState {
848 above: bool,
849 stack: Vec<usize>,
850}
851
852#[derive(Clone)]
853struct SelectNextState {
854 query: AhoCorasick,
855 wordwise: bool,
856 done: bool,
857}
858
859impl std::fmt::Debug for SelectNextState {
860 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
861 f.debug_struct(std::any::type_name::<Self>())
862 .field("wordwise", &self.wordwise)
863 .field("done", &self.done)
864 .finish()
865 }
866}
867
868#[derive(Debug)]
869struct AutocloseRegion {
870 selection_id: usize,
871 range: Range<Anchor>,
872 pair: BracketPair,
873}
874
875#[derive(Debug)]
876struct SnippetState {
877 ranges: Vec<Vec<Range<Anchor>>>,
878 active_index: usize,
879 choices: Vec<Option<Vec<String>>>,
880}
881
882#[doc(hidden)]
883pub struct RenameState {
884 pub range: Range<Anchor>,
885 pub old_name: Arc<str>,
886 pub editor: View<Editor>,
887 block_id: CustomBlockId,
888}
889
890struct InvalidationStack<T>(Vec<T>);
891
892struct RegisteredInlineCompletionProvider {
893 provider: Arc<dyn InlineCompletionProviderHandle>,
894 _subscription: Subscription,
895}
896
897enum ContextMenu {
898 Completions(CompletionsMenu),
899 CodeActions(CodeActionsMenu),
900}
901
902impl ContextMenu {
903 fn select_first(
904 &mut self,
905 provider: Option<&dyn CompletionProvider>,
906 cx: &mut ViewContext<Editor>,
907 ) -> bool {
908 if self.visible() {
909 match self {
910 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
911 ContextMenu::CodeActions(menu) => menu.select_first(cx),
912 }
913 true
914 } else {
915 false
916 }
917 }
918
919 fn select_prev(
920 &mut self,
921 provider: Option<&dyn CompletionProvider>,
922 cx: &mut ViewContext<Editor>,
923 ) -> bool {
924 if self.visible() {
925 match self {
926 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
927 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
928 }
929 true
930 } else {
931 false
932 }
933 }
934
935 fn select_next(
936 &mut self,
937 provider: Option<&dyn CompletionProvider>,
938 cx: &mut ViewContext<Editor>,
939 ) -> bool {
940 if self.visible() {
941 match self {
942 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
943 ContextMenu::CodeActions(menu) => menu.select_next(cx),
944 }
945 true
946 } else {
947 false
948 }
949 }
950
951 fn select_last(
952 &mut self,
953 provider: Option<&dyn CompletionProvider>,
954 cx: &mut ViewContext<Editor>,
955 ) -> bool {
956 if self.visible() {
957 match self {
958 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
959 ContextMenu::CodeActions(menu) => menu.select_last(cx),
960 }
961 true
962 } else {
963 false
964 }
965 }
966
967 fn visible(&self) -> bool {
968 match self {
969 ContextMenu::Completions(menu) => menu.visible(),
970 ContextMenu::CodeActions(menu) => menu.visible(),
971 }
972 }
973
974 fn render(
975 &self,
976 cursor_position: DisplayPoint,
977 style: &EditorStyle,
978 max_height: Pixels,
979 workspace: Option<WeakView<Workspace>>,
980 cx: &mut ViewContext<Editor>,
981 ) -> (ContextMenuOrigin, AnyElement) {
982 match self {
983 ContextMenu::Completions(menu) => (
984 ContextMenuOrigin::EditorPoint(cursor_position),
985 menu.render(style, max_height, workspace, cx),
986 ),
987 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
988 }
989 }
990}
991
992enum ContextMenuOrigin {
993 EditorPoint(DisplayPoint),
994 GutterIndicator(DisplayRow),
995}
996
997#[derive(Clone, Debug)]
998struct CompletionsMenu {
999 id: CompletionId,
1000 sort_completions: bool,
1001 initial_position: Anchor,
1002 buffer: Model<Buffer>,
1003 completions: Arc<RwLock<Box<[Completion]>>>,
1004 match_candidates: Arc<[StringMatchCandidate]>,
1005 matches: Arc<[StringMatch]>,
1006 selected_item: usize,
1007 scroll_handle: UniformListScrollHandle,
1008 selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
1009}
1010
1011impl CompletionsMenu {
1012 fn new(
1013 id: CompletionId,
1014 sort_completions: bool,
1015 initial_position: Anchor,
1016 buffer: Model<Buffer>,
1017 completions: Box<[Completion]>,
1018 ) -> Self {
1019 let match_candidates = completions
1020 .iter()
1021 .enumerate()
1022 .map(|(id, completion)| {
1023 StringMatchCandidate::new(
1024 id,
1025 completion.label.text[completion.label.filter_range.clone()].into(),
1026 )
1027 })
1028 .collect();
1029
1030 Self {
1031 id,
1032 sort_completions,
1033 initial_position,
1034 buffer,
1035 completions: Arc::new(RwLock::new(completions)),
1036 match_candidates,
1037 matches: Vec::new().into(),
1038 selected_item: 0,
1039 scroll_handle: UniformListScrollHandle::new(),
1040 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1041 }
1042 }
1043
1044 fn new_snippet_choices(
1045 id: CompletionId,
1046 sort_completions: bool,
1047 choices: &Vec<String>,
1048 selection: Range<Anchor>,
1049 buffer: Model<Buffer>,
1050 ) -> Self {
1051 let completions = choices
1052 .iter()
1053 .map(|choice| Completion {
1054 old_range: selection.start.text_anchor..selection.end.text_anchor,
1055 new_text: choice.to_string(),
1056 label: CodeLabel {
1057 text: choice.to_string(),
1058 runs: Default::default(),
1059 filter_range: Default::default(),
1060 },
1061 server_id: LanguageServerId(usize::MAX),
1062 documentation: None,
1063 lsp_completion: Default::default(),
1064 confirm: None,
1065 })
1066 .collect();
1067
1068 let match_candidates = choices
1069 .iter()
1070 .enumerate()
1071 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1072 .collect();
1073 let matches = choices
1074 .iter()
1075 .enumerate()
1076 .map(|(id, completion)| StringMatch {
1077 candidate_id: id,
1078 score: 1.,
1079 positions: vec![],
1080 string: completion.clone(),
1081 })
1082 .collect();
1083 Self {
1084 id,
1085 sort_completions,
1086 initial_position: selection.start,
1087 buffer,
1088 completions: Arc::new(RwLock::new(completions)),
1089 match_candidates,
1090 matches,
1091 selected_item: 0,
1092 scroll_handle: UniformListScrollHandle::new(),
1093 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1094 }
1095 }
1096
1097 fn suppress_documentation_resolution(mut self) -> Self {
1098 self.selected_completion_resolve_debounce.take();
1099 self
1100 }
1101
1102 fn select_first(
1103 &mut self,
1104 provider: Option<&dyn CompletionProvider>,
1105 cx: &mut ViewContext<Editor>,
1106 ) {
1107 self.selected_item = 0;
1108 self.scroll_handle
1109 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1110 self.resolve_selected_completion(provider, cx);
1111 cx.notify();
1112 }
1113
1114 fn select_prev(
1115 &mut self,
1116 provider: Option<&dyn CompletionProvider>,
1117 cx: &mut ViewContext<Editor>,
1118 ) {
1119 if self.selected_item > 0 {
1120 self.selected_item -= 1;
1121 } else {
1122 self.selected_item = self.matches.len() - 1;
1123 }
1124 self.scroll_handle
1125 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1126 self.resolve_selected_completion(provider, cx);
1127 cx.notify();
1128 }
1129
1130 fn select_next(
1131 &mut self,
1132 provider: Option<&dyn CompletionProvider>,
1133 cx: &mut ViewContext<Editor>,
1134 ) {
1135 if self.selected_item + 1 < self.matches.len() {
1136 self.selected_item += 1;
1137 } else {
1138 self.selected_item = 0;
1139 }
1140 self.scroll_handle
1141 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1142 self.resolve_selected_completion(provider, cx);
1143 cx.notify();
1144 }
1145
1146 fn select_last(
1147 &mut self,
1148 provider: Option<&dyn CompletionProvider>,
1149 cx: &mut ViewContext<Editor>,
1150 ) {
1151 self.selected_item = self.matches.len() - 1;
1152 self.scroll_handle
1153 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1154 self.resolve_selected_completion(provider, cx);
1155 cx.notify();
1156 }
1157
1158 fn resolve_selected_completion(
1159 &mut self,
1160 provider: Option<&dyn CompletionProvider>,
1161 cx: &mut ViewContext<Editor>,
1162 ) {
1163 let completion_index = self.matches[self.selected_item].candidate_id;
1164 let Some(provider) = provider else {
1165 return;
1166 };
1167 let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
1168 return;
1169 };
1170
1171 let resolve_task = provider.resolve_completions(
1172 self.buffer.clone(),
1173 vec![completion_index],
1174 self.completions.clone(),
1175 cx,
1176 );
1177
1178 let delay_ms =
1179 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1180 let delay = Duration::from_millis(delay_ms);
1181
1182 completion_resolve.lock().fire_new(delay, cx, |_, cx| {
1183 cx.spawn(move |this, mut cx| async move {
1184 if let Some(true) = resolve_task.await.log_err() {
1185 this.update(&mut cx, |_, cx| cx.notify()).ok();
1186 }
1187 })
1188 });
1189 }
1190
1191 fn visible(&self) -> bool {
1192 !self.matches.is_empty()
1193 }
1194
1195 fn render(
1196 &self,
1197 style: &EditorStyle,
1198 max_height: Pixels,
1199 workspace: Option<WeakView<Workspace>>,
1200 cx: &mut ViewContext<Editor>,
1201 ) -> AnyElement {
1202 let settings = EditorSettings::get_global(cx);
1203 let show_completion_documentation = settings.show_completion_documentation;
1204
1205 let widest_completion_ix = self
1206 .matches
1207 .iter()
1208 .enumerate()
1209 .max_by_key(|(_, mat)| {
1210 let completions = self.completions.read();
1211 let completion = &completions[mat.candidate_id];
1212 let documentation = &completion.documentation;
1213
1214 let mut len = completion.label.text.chars().count();
1215 if let Some(Documentation::SingleLine(text)) = documentation {
1216 if show_completion_documentation {
1217 len += text.chars().count();
1218 }
1219 }
1220
1221 len
1222 })
1223 .map(|(ix, _)| ix);
1224
1225 let completions = self.completions.clone();
1226 let matches = self.matches.clone();
1227 let selected_item = self.selected_item;
1228 let style = style.clone();
1229
1230 let multiline_docs = if show_completion_documentation {
1231 let mat = &self.matches[selected_item];
1232 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1233 Some(Documentation::MultiLinePlainText(text)) => {
1234 Some(div().child(SharedString::from(text.clone())))
1235 }
1236 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1237 Some(div().child(render_parsed_markdown(
1238 "completions_markdown",
1239 parsed,
1240 &style,
1241 workspace,
1242 cx,
1243 )))
1244 }
1245 _ => None,
1246 };
1247 multiline_docs.map(|div| {
1248 div.id("multiline_docs")
1249 .max_h(max_height)
1250 .flex_1()
1251 .px_1p5()
1252 .py_1()
1253 .min_w(px(260.))
1254 .max_w(px(640.))
1255 .w(px(500.))
1256 .overflow_y_scroll()
1257 .occlude()
1258 })
1259 } else {
1260 None
1261 };
1262
1263 let list = uniform_list(
1264 cx.view().clone(),
1265 "completions",
1266 matches.len(),
1267 move |_editor, range, cx| {
1268 let start_ix = range.start;
1269 let completions_guard = completions.read();
1270
1271 matches[range]
1272 .iter()
1273 .enumerate()
1274 .map(|(ix, mat)| {
1275 let item_ix = start_ix + ix;
1276 let candidate_id = mat.candidate_id;
1277 let completion = &completions_guard[candidate_id];
1278
1279 let documentation = if show_completion_documentation {
1280 &completion.documentation
1281 } else {
1282 &None
1283 };
1284
1285 let highlights = gpui::combine_highlights(
1286 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1287 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1288 |(range, mut highlight)| {
1289 // Ignore font weight for syntax highlighting, as we'll use it
1290 // for fuzzy matches.
1291 highlight.font_weight = None;
1292
1293 if completion.lsp_completion.deprecated.unwrap_or(false) {
1294 highlight.strikethrough = Some(StrikethroughStyle {
1295 thickness: 1.0.into(),
1296 ..Default::default()
1297 });
1298 highlight.color = Some(cx.theme().colors().text_muted);
1299 }
1300
1301 (range, highlight)
1302 },
1303 ),
1304 );
1305 let completion_label = StyledText::new(completion.label.text.clone())
1306 .with_highlights(&style.text, highlights);
1307 let documentation_label =
1308 if let Some(Documentation::SingleLine(text)) = documentation {
1309 if text.trim().is_empty() {
1310 None
1311 } else {
1312 Some(
1313 Label::new(text.clone())
1314 .ml_4()
1315 .size(LabelSize::Small)
1316 .color(Color::Muted),
1317 )
1318 }
1319 } else {
1320 None
1321 };
1322
1323 let color_swatch = completion
1324 .color()
1325 .map(|color| div().size_4().bg(color).rounded_sm());
1326
1327 div().min_w(px(220.)).max_w(px(540.)).child(
1328 ListItem::new(mat.candidate_id)
1329 .inset(true)
1330 .selected(item_ix == selected_item)
1331 .on_click(cx.listener(move |editor, _event, cx| {
1332 cx.stop_propagation();
1333 if let Some(task) = editor.confirm_completion(
1334 &ConfirmCompletion {
1335 item_ix: Some(item_ix),
1336 },
1337 cx,
1338 ) {
1339 task.detach_and_log_err(cx)
1340 }
1341 }))
1342 .start_slot::<Div>(color_swatch)
1343 .child(h_flex().overflow_hidden().child(completion_label))
1344 .end_slot::<Label>(documentation_label),
1345 )
1346 })
1347 .collect()
1348 },
1349 )
1350 .occlude()
1351 .max_h(max_height)
1352 .track_scroll(self.scroll_handle.clone())
1353 .with_width_from_item(widest_completion_ix)
1354 .with_sizing_behavior(ListSizingBehavior::Infer);
1355
1356 Popover::new()
1357 .child(list)
1358 .when_some(multiline_docs, |popover, multiline_docs| {
1359 popover.aside(multiline_docs)
1360 })
1361 .into_any_element()
1362 }
1363
1364 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1365 let mut matches = if let Some(query) = query {
1366 fuzzy::match_strings(
1367 &self.match_candidates,
1368 query,
1369 query.chars().any(|c| c.is_uppercase()),
1370 100,
1371 &Default::default(),
1372 executor,
1373 )
1374 .await
1375 } else {
1376 self.match_candidates
1377 .iter()
1378 .enumerate()
1379 .map(|(candidate_id, candidate)| StringMatch {
1380 candidate_id,
1381 score: Default::default(),
1382 positions: Default::default(),
1383 string: candidate.string.clone(),
1384 })
1385 .collect()
1386 };
1387
1388 // Remove all candidates where the query's start does not match the start of any word in the candidate
1389 if let Some(query) = query {
1390 if let Some(query_start) = query.chars().next() {
1391 matches.retain(|string_match| {
1392 split_words(&string_match.string).any(|word| {
1393 // Check that the first codepoint of the word as lowercase matches the first
1394 // codepoint of the query as lowercase
1395 word.chars()
1396 .flat_map(|codepoint| codepoint.to_lowercase())
1397 .zip(query_start.to_lowercase())
1398 .all(|(word_cp, query_cp)| word_cp == query_cp)
1399 })
1400 });
1401 }
1402 }
1403
1404 let completions = self.completions.read();
1405 if self.sort_completions {
1406 matches.sort_unstable_by_key(|mat| {
1407 // We do want to strike a balance here between what the language server tells us
1408 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1409 // `Creat` and there is a local variable called `CreateComponent`).
1410 // So what we do is: we bucket all matches into two buckets
1411 // - Strong matches
1412 // - Weak matches
1413 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1414 // and the Weak matches are the rest.
1415 //
1416 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1417 // matches, we prefer language-server sort_text first.
1418 //
1419 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1420 // Rest of the matches(weak) can be sorted as language-server expects.
1421
1422 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1423 enum MatchScore<'a> {
1424 Strong {
1425 score: Reverse<OrderedFloat<f64>>,
1426 sort_text: Option<&'a str>,
1427 sort_key: (usize, &'a str),
1428 },
1429 Weak {
1430 sort_text: Option<&'a str>,
1431 score: Reverse<OrderedFloat<f64>>,
1432 sort_key: (usize, &'a str),
1433 },
1434 }
1435
1436 let completion = &completions[mat.candidate_id];
1437 let sort_key = completion.sort_key();
1438 let sort_text = completion.lsp_completion.sort_text.as_deref();
1439 let score = Reverse(OrderedFloat(mat.score));
1440
1441 if mat.score >= 0.2 {
1442 MatchScore::Strong {
1443 score,
1444 sort_text,
1445 sort_key,
1446 }
1447 } else {
1448 MatchScore::Weak {
1449 sort_text,
1450 score,
1451 sort_key,
1452 }
1453 }
1454 });
1455 }
1456
1457 for mat in &mut matches {
1458 let completion = &completions[mat.candidate_id];
1459 mat.string.clone_from(&completion.label.text);
1460 for position in &mut mat.positions {
1461 *position += completion.label.filter_range.start;
1462 }
1463 }
1464 drop(completions);
1465
1466 self.matches = matches.into();
1467 self.selected_item = 0;
1468 }
1469}
1470
1471#[derive(Clone)]
1472struct AvailableCodeAction {
1473 excerpt_id: ExcerptId,
1474 action: CodeAction,
1475 provider: Arc<dyn CodeActionProvider>,
1476}
1477
1478#[derive(Clone)]
1479struct CodeActionContents {
1480 tasks: Option<Arc<ResolvedTasks>>,
1481 actions: Option<Arc<[AvailableCodeAction]>>,
1482}
1483
1484impl CodeActionContents {
1485 fn len(&self) -> usize {
1486 match (&self.tasks, &self.actions) {
1487 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1488 (Some(tasks), None) => tasks.templates.len(),
1489 (None, Some(actions)) => actions.len(),
1490 (None, None) => 0,
1491 }
1492 }
1493
1494 fn is_empty(&self) -> bool {
1495 match (&self.tasks, &self.actions) {
1496 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1497 (Some(tasks), None) => tasks.templates.is_empty(),
1498 (None, Some(actions)) => actions.is_empty(),
1499 (None, None) => true,
1500 }
1501 }
1502
1503 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1504 self.tasks
1505 .iter()
1506 .flat_map(|tasks| {
1507 tasks
1508 .templates
1509 .iter()
1510 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1511 })
1512 .chain(self.actions.iter().flat_map(|actions| {
1513 actions.iter().map(|available| CodeActionsItem::CodeAction {
1514 excerpt_id: available.excerpt_id,
1515 action: available.action.clone(),
1516 provider: available.provider.clone(),
1517 })
1518 }))
1519 }
1520 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1521 match (&self.tasks, &self.actions) {
1522 (Some(tasks), Some(actions)) => {
1523 if index < tasks.templates.len() {
1524 tasks
1525 .templates
1526 .get(index)
1527 .cloned()
1528 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1529 } else {
1530 actions.get(index - tasks.templates.len()).map(|available| {
1531 CodeActionsItem::CodeAction {
1532 excerpt_id: available.excerpt_id,
1533 action: available.action.clone(),
1534 provider: available.provider.clone(),
1535 }
1536 })
1537 }
1538 }
1539 (Some(tasks), None) => tasks
1540 .templates
1541 .get(index)
1542 .cloned()
1543 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1544 (None, Some(actions)) => {
1545 actions
1546 .get(index)
1547 .map(|available| CodeActionsItem::CodeAction {
1548 excerpt_id: available.excerpt_id,
1549 action: available.action.clone(),
1550 provider: available.provider.clone(),
1551 })
1552 }
1553 (None, None) => None,
1554 }
1555 }
1556}
1557
1558#[allow(clippy::large_enum_variant)]
1559#[derive(Clone)]
1560enum CodeActionsItem {
1561 Task(TaskSourceKind, ResolvedTask),
1562 CodeAction {
1563 excerpt_id: ExcerptId,
1564 action: CodeAction,
1565 provider: Arc<dyn CodeActionProvider>,
1566 },
1567}
1568
1569impl CodeActionsItem {
1570 fn as_task(&self) -> Option<&ResolvedTask> {
1571 let Self::Task(_, task) = self else {
1572 return None;
1573 };
1574 Some(task)
1575 }
1576 fn as_code_action(&self) -> Option<&CodeAction> {
1577 let Self::CodeAction { action, .. } = self else {
1578 return None;
1579 };
1580 Some(action)
1581 }
1582 fn label(&self) -> String {
1583 match self {
1584 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1585 Self::Task(_, task) => task.resolved_label.clone(),
1586 }
1587 }
1588}
1589
1590struct CodeActionsMenu {
1591 actions: CodeActionContents,
1592 buffer: Model<Buffer>,
1593 selected_item: usize,
1594 scroll_handle: UniformListScrollHandle,
1595 deployed_from_indicator: Option<DisplayRow>,
1596}
1597
1598impl CodeActionsMenu {
1599 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1600 self.selected_item = 0;
1601 self.scroll_handle
1602 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1603 cx.notify()
1604 }
1605
1606 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1607 if self.selected_item > 0 {
1608 self.selected_item -= 1;
1609 } else {
1610 self.selected_item = self.actions.len() - 1;
1611 }
1612 self.scroll_handle
1613 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1614 cx.notify();
1615 }
1616
1617 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1618 if self.selected_item + 1 < self.actions.len() {
1619 self.selected_item += 1;
1620 } else {
1621 self.selected_item = 0;
1622 }
1623 self.scroll_handle
1624 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1625 cx.notify();
1626 }
1627
1628 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1629 self.selected_item = self.actions.len() - 1;
1630 self.scroll_handle
1631 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1632 cx.notify()
1633 }
1634
1635 fn visible(&self) -> bool {
1636 !self.actions.is_empty()
1637 }
1638
1639 fn render(
1640 &self,
1641 cursor_position: DisplayPoint,
1642 _style: &EditorStyle,
1643 max_height: Pixels,
1644 cx: &mut ViewContext<Editor>,
1645 ) -> (ContextMenuOrigin, AnyElement) {
1646 let actions = self.actions.clone();
1647 let selected_item = self.selected_item;
1648 let element = uniform_list(
1649 cx.view().clone(),
1650 "code_actions_menu",
1651 self.actions.len(),
1652 move |_this, range, cx| {
1653 actions
1654 .iter()
1655 .skip(range.start)
1656 .take(range.end - range.start)
1657 .enumerate()
1658 .map(|(ix, action)| {
1659 let item_ix = range.start + ix;
1660 let selected = selected_item == item_ix;
1661 let colors = cx.theme().colors();
1662 div()
1663 .px_1()
1664 .rounded_md()
1665 .text_color(colors.text)
1666 .when(selected, |style| {
1667 style
1668 .bg(colors.element_active)
1669 .text_color(colors.text_accent)
1670 })
1671 .hover(|style| {
1672 style
1673 .bg(colors.element_hover)
1674 .text_color(colors.text_accent)
1675 })
1676 .whitespace_nowrap()
1677 .when_some(action.as_code_action(), |this, action| {
1678 this.on_mouse_down(
1679 MouseButton::Left,
1680 cx.listener(move |editor, _, cx| {
1681 cx.stop_propagation();
1682 if let Some(task) = editor.confirm_code_action(
1683 &ConfirmCodeAction {
1684 item_ix: Some(item_ix),
1685 },
1686 cx,
1687 ) {
1688 task.detach_and_log_err(cx)
1689 }
1690 }),
1691 )
1692 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1693 .child(SharedString::from(action.lsp_action.title.clone()))
1694 })
1695 .when_some(action.as_task(), |this, task| {
1696 this.on_mouse_down(
1697 MouseButton::Left,
1698 cx.listener(move |editor, _, cx| {
1699 cx.stop_propagation();
1700 if let Some(task) = editor.confirm_code_action(
1701 &ConfirmCodeAction {
1702 item_ix: Some(item_ix),
1703 },
1704 cx,
1705 ) {
1706 task.detach_and_log_err(cx)
1707 }
1708 }),
1709 )
1710 .child(SharedString::from(task.resolved_label.clone()))
1711 })
1712 })
1713 .collect()
1714 },
1715 )
1716 .elevation_1(cx)
1717 .p_1()
1718 .max_h(max_height)
1719 .occlude()
1720 .track_scroll(self.scroll_handle.clone())
1721 .with_width_from_item(
1722 self.actions
1723 .iter()
1724 .enumerate()
1725 .max_by_key(|(_, action)| match action {
1726 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1727 CodeActionsItem::CodeAction { action, .. } => {
1728 action.lsp_action.title.chars().count()
1729 }
1730 })
1731 .map(|(ix, _)| ix),
1732 )
1733 .with_sizing_behavior(ListSizingBehavior::Infer)
1734 .into_any_element();
1735
1736 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1737 ContextMenuOrigin::GutterIndicator(row)
1738 } else {
1739 ContextMenuOrigin::EditorPoint(cursor_position)
1740 };
1741
1742 (cursor_position, element)
1743 }
1744}
1745
1746#[derive(Debug)]
1747struct ActiveDiagnosticGroup {
1748 primary_range: Range<Anchor>,
1749 primary_message: String,
1750 group_id: usize,
1751 blocks: HashMap<CustomBlockId, Diagnostic>,
1752 is_valid: bool,
1753}
1754
1755#[derive(Serialize, Deserialize, Clone, Debug)]
1756pub struct ClipboardSelection {
1757 pub len: usize,
1758 pub is_entire_line: bool,
1759 pub first_line_indent: u32,
1760}
1761
1762#[derive(Debug)]
1763pub(crate) struct NavigationData {
1764 cursor_anchor: Anchor,
1765 cursor_position: Point,
1766 scroll_anchor: ScrollAnchor,
1767 scroll_top_row: u32,
1768}
1769
1770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1771pub enum GotoDefinitionKind {
1772 Symbol,
1773 Declaration,
1774 Type,
1775 Implementation,
1776}
1777
1778#[derive(Debug, Clone)]
1779enum InlayHintRefreshReason {
1780 Toggle(bool),
1781 SettingsChange(InlayHintSettings),
1782 NewLinesShown,
1783 BufferEdited(HashSet<Arc<Language>>),
1784 RefreshRequested,
1785 ExcerptsRemoved(Vec<ExcerptId>),
1786}
1787
1788impl InlayHintRefreshReason {
1789 fn description(&self) -> &'static str {
1790 match self {
1791 Self::Toggle(_) => "toggle",
1792 Self::SettingsChange(_) => "settings change",
1793 Self::NewLinesShown => "new lines shown",
1794 Self::BufferEdited(_) => "buffer edited",
1795 Self::RefreshRequested => "refresh requested",
1796 Self::ExcerptsRemoved(_) => "excerpts removed",
1797 }
1798 }
1799}
1800
1801pub(crate) struct FocusedBlock {
1802 id: BlockId,
1803 focus_handle: WeakFocusHandle,
1804}
1805
1806#[derive(Clone)]
1807struct JumpData {
1808 excerpt_id: ExcerptId,
1809 position: Point,
1810 anchor: text::Anchor,
1811 path: Option<project::ProjectPath>,
1812 line_offset_from_top: u32,
1813}
1814
1815impl Editor {
1816 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1817 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1818 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1819 Self::new(
1820 EditorMode::SingleLine { auto_width: false },
1821 buffer,
1822 None,
1823 false,
1824 cx,
1825 )
1826 }
1827
1828 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1829 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1830 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1831 Self::new(EditorMode::Full, buffer, None, false, cx)
1832 }
1833
1834 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1835 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1836 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1837 Self::new(
1838 EditorMode::SingleLine { auto_width: true },
1839 buffer,
1840 None,
1841 false,
1842 cx,
1843 )
1844 }
1845
1846 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1847 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1848 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1849 Self::new(
1850 EditorMode::AutoHeight { max_lines },
1851 buffer,
1852 None,
1853 false,
1854 cx,
1855 )
1856 }
1857
1858 pub fn for_buffer(
1859 buffer: Model<Buffer>,
1860 project: Option<Model<Project>>,
1861 cx: &mut ViewContext<Self>,
1862 ) -> Self {
1863 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1864 Self::new(EditorMode::Full, buffer, project, false, cx)
1865 }
1866
1867 pub fn for_multibuffer(
1868 buffer: Model<MultiBuffer>,
1869 project: Option<Model<Project>>,
1870 show_excerpt_controls: bool,
1871 cx: &mut ViewContext<Self>,
1872 ) -> Self {
1873 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1874 }
1875
1876 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1877 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1878 let mut clone = Self::new(
1879 self.mode,
1880 self.buffer.clone(),
1881 self.project.clone(),
1882 show_excerpt_controls,
1883 cx,
1884 );
1885 self.display_map.update(cx, |display_map, cx| {
1886 let snapshot = display_map.snapshot(cx);
1887 clone.display_map.update(cx, |display_map, cx| {
1888 display_map.set_state(&snapshot, cx);
1889 });
1890 });
1891 clone.selections.clone_state(&self.selections);
1892 clone.scroll_manager.clone_state(&self.scroll_manager);
1893 clone.searchable = self.searchable;
1894 clone
1895 }
1896
1897 pub fn new(
1898 mode: EditorMode,
1899 buffer: Model<MultiBuffer>,
1900 project: Option<Model<Project>>,
1901 show_excerpt_controls: bool,
1902 cx: &mut ViewContext<Self>,
1903 ) -> Self {
1904 let style = cx.text_style();
1905 let font_size = style.font_size.to_pixels(cx.rem_size());
1906 let editor = cx.view().downgrade();
1907 let fold_placeholder = FoldPlaceholder {
1908 constrain_width: true,
1909 render: Arc::new(move |fold_id, fold_range, cx| {
1910 let editor = editor.clone();
1911 div()
1912 .id(fold_id)
1913 .bg(cx.theme().colors().ghost_element_background)
1914 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1915 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1916 .rounded_sm()
1917 .size_full()
1918 .cursor_pointer()
1919 .child("⋯")
1920 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1921 .on_click(move |_, cx| {
1922 editor
1923 .update(cx, |editor, cx| {
1924 editor.unfold_ranges(
1925 &[fold_range.start..fold_range.end],
1926 true,
1927 false,
1928 cx,
1929 );
1930 cx.stop_propagation();
1931 })
1932 .ok();
1933 })
1934 .into_any()
1935 }),
1936 merge_adjacent: true,
1937 ..Default::default()
1938 };
1939 let display_map = cx.new_model(|cx| {
1940 DisplayMap::new(
1941 buffer.clone(),
1942 style.font(),
1943 font_size,
1944 None,
1945 show_excerpt_controls,
1946 FILE_HEADER_HEIGHT,
1947 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1948 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1949 fold_placeholder,
1950 cx,
1951 )
1952 });
1953
1954 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1955
1956 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1957
1958 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1959 .then(|| language_settings::SoftWrap::None);
1960
1961 let mut project_subscriptions = Vec::new();
1962 if mode == EditorMode::Full {
1963 if let Some(project) = project.as_ref() {
1964 if buffer.read(cx).is_singleton() {
1965 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1966 cx.emit(EditorEvent::TitleChanged);
1967 }));
1968 }
1969 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1970 if let project::Event::RefreshInlayHints = event {
1971 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1972 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1973 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1974 let focus_handle = editor.focus_handle(cx);
1975 if focus_handle.is_focused(cx) {
1976 let snapshot = buffer.read(cx).snapshot();
1977 for (range, snippet) in snippet_edits {
1978 let editor_range =
1979 language::range_from_lsp(*range).to_offset(&snapshot);
1980 editor
1981 .insert_snippet(&[editor_range], snippet.clone(), cx)
1982 .ok();
1983 }
1984 }
1985 }
1986 }
1987 }));
1988 if let Some(task_inventory) = project
1989 .read(cx)
1990 .task_store()
1991 .read(cx)
1992 .task_inventory()
1993 .cloned()
1994 {
1995 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1996 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1997 }));
1998 }
1999 }
2000 }
2001
2002 let inlay_hint_settings = inlay_hint_settings(
2003 selections.newest_anchor().head(),
2004 &buffer.read(cx).snapshot(cx),
2005 cx,
2006 );
2007 let focus_handle = cx.focus_handle();
2008 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2009 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2010 .detach();
2011 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2012 .detach();
2013 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2014
2015 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2016 Some(false)
2017 } else {
2018 None
2019 };
2020
2021 let mut code_action_providers = Vec::new();
2022 if let Some(project) = project.clone() {
2023 code_action_providers.push(Arc::new(project) as Arc<_>);
2024 }
2025
2026 let mut this = Self {
2027 focus_handle,
2028 show_cursor_when_unfocused: false,
2029 last_focused_descendant: None,
2030 buffer: buffer.clone(),
2031 display_map: display_map.clone(),
2032 selections,
2033 scroll_manager: ScrollManager::new(cx),
2034 columnar_selection_tail: None,
2035 add_selections_state: None,
2036 select_next_state: None,
2037 select_prev_state: None,
2038 selection_history: Default::default(),
2039 autoclose_regions: Default::default(),
2040 snippet_stack: Default::default(),
2041 select_larger_syntax_node_stack: Vec::new(),
2042 ime_transaction: Default::default(),
2043 active_diagnostics: None,
2044 soft_wrap_mode_override,
2045 completion_provider: project.clone().map(|project| Box::new(project) as _),
2046 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2047 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2048 project,
2049 blink_manager: blink_manager.clone(),
2050 show_local_selections: true,
2051 mode,
2052 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2053 show_gutter: mode == EditorMode::Full,
2054 show_line_numbers: None,
2055 use_relative_line_numbers: None,
2056 show_git_diff_gutter: None,
2057 show_code_actions: None,
2058 show_runnables: None,
2059 show_wrap_guides: None,
2060 show_indent_guides,
2061 placeholder_text: None,
2062 highlight_order: 0,
2063 highlighted_rows: HashMap::default(),
2064 background_highlights: Default::default(),
2065 gutter_highlights: TreeMap::default(),
2066 scrollbar_marker_state: ScrollbarMarkerState::default(),
2067 active_indent_guides_state: ActiveIndentGuidesState::default(),
2068 nav_history: None,
2069 context_menu: RwLock::new(None),
2070 mouse_context_menu: None,
2071 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2072 completion_tasks: Default::default(),
2073 signature_help_state: SignatureHelpState::default(),
2074 auto_signature_help: None,
2075 find_all_references_task_sources: Vec::new(),
2076 next_completion_id: 0,
2077 next_inlay_id: 0,
2078 code_action_providers,
2079 available_code_actions: Default::default(),
2080 code_actions_task: Default::default(),
2081 document_highlights_task: Default::default(),
2082 linked_editing_range_task: Default::default(),
2083 pending_rename: Default::default(),
2084 searchable: true,
2085 cursor_shape: EditorSettings::get_global(cx)
2086 .cursor_shape
2087 .unwrap_or_default(),
2088 current_line_highlight: None,
2089 autoindent_mode: Some(AutoindentMode::EachLine),
2090 collapse_matches: false,
2091 workspace: None,
2092 input_enabled: true,
2093 use_modal_editing: mode == EditorMode::Full,
2094 read_only: false,
2095 use_autoclose: true,
2096 use_auto_surround: true,
2097 auto_replace_emoji_shortcode: false,
2098 leader_peer_id: None,
2099 remote_id: None,
2100 hover_state: Default::default(),
2101 hovered_link_state: Default::default(),
2102 inline_completion_provider: None,
2103 active_inline_completion: None,
2104 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2105 expanded_hunks: ExpandedHunks::default(),
2106 gutter_hovered: false,
2107 pixel_position_of_newest_cursor: None,
2108 last_bounds: None,
2109 expect_bounds_change: None,
2110 gutter_dimensions: GutterDimensions::default(),
2111 style: None,
2112 show_cursor_names: false,
2113 hovered_cursors: Default::default(),
2114 next_editor_action_id: EditorActionId::default(),
2115 editor_actions: Rc::default(),
2116 show_inline_completions_override: None,
2117 enable_inline_completions: true,
2118 custom_context_menu: None,
2119 show_git_blame_gutter: false,
2120 show_git_blame_inline: false,
2121 show_selection_menu: None,
2122 show_git_blame_inline_delay_task: None,
2123 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2124 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2125 .session
2126 .restore_unsaved_buffers,
2127 blame: None,
2128 blame_subscription: None,
2129 tasks: Default::default(),
2130 _subscriptions: vec![
2131 cx.observe(&buffer, Self::on_buffer_changed),
2132 cx.subscribe(&buffer, Self::on_buffer_event),
2133 cx.observe(&display_map, Self::on_display_map_changed),
2134 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2135 cx.observe_global::<SettingsStore>(Self::settings_changed),
2136 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2137 cx.observe_window_activation(|editor, cx| {
2138 let active = cx.is_window_active();
2139 editor.blink_manager.update(cx, |blink_manager, cx| {
2140 if active {
2141 blink_manager.enable(cx);
2142 } else {
2143 blink_manager.disable(cx);
2144 }
2145 });
2146 }),
2147 ],
2148 tasks_update_task: None,
2149 linked_edit_ranges: Default::default(),
2150 previous_search_ranges: None,
2151 breadcrumb_header: None,
2152 focused_block: None,
2153 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2154 addons: HashMap::default(),
2155 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2156 text_style_refinement: None,
2157 };
2158 this.tasks_update_task = Some(this.refresh_runnables(cx));
2159 this._subscriptions.extend(project_subscriptions);
2160
2161 this.end_selection(cx);
2162 this.scroll_manager.show_scrollbar(cx);
2163
2164 if mode == EditorMode::Full {
2165 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2166 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2167
2168 if this.git_blame_inline_enabled {
2169 this.git_blame_inline_enabled = true;
2170 this.start_git_blame_inline(false, cx);
2171 }
2172 }
2173
2174 this.report_editor_event("open", None, cx);
2175 this
2176 }
2177
2178 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2179 self.mouse_context_menu
2180 .as_ref()
2181 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2182 }
2183
2184 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2185 let mut key_context = KeyContext::new_with_defaults();
2186 key_context.add("Editor");
2187 let mode = match self.mode {
2188 EditorMode::SingleLine { .. } => "single_line",
2189 EditorMode::AutoHeight { .. } => "auto_height",
2190 EditorMode::Full => "full",
2191 };
2192
2193 if EditorSettings::jupyter_enabled(cx) {
2194 key_context.add("jupyter");
2195 }
2196
2197 key_context.set("mode", mode);
2198 if self.pending_rename.is_some() {
2199 key_context.add("renaming");
2200 }
2201 if self.context_menu_visible() {
2202 match self.context_menu.read().as_ref() {
2203 Some(ContextMenu::Completions(_)) => {
2204 key_context.add("menu");
2205 key_context.add("showing_completions")
2206 }
2207 Some(ContextMenu::CodeActions(_)) => {
2208 key_context.add("menu");
2209 key_context.add("showing_code_actions")
2210 }
2211 None => {}
2212 }
2213 }
2214
2215 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2216 if !self.focus_handle(cx).contains_focused(cx)
2217 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2218 {
2219 for addon in self.addons.values() {
2220 addon.extend_key_context(&mut key_context, cx)
2221 }
2222 }
2223
2224 if let Some(extension) = self
2225 .buffer
2226 .read(cx)
2227 .as_singleton()
2228 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2229 {
2230 key_context.set("extension", extension.to_string());
2231 }
2232
2233 if self.has_active_inline_completion(cx) {
2234 key_context.add("copilot_suggestion");
2235 key_context.add("inline_completion");
2236 }
2237
2238 key_context
2239 }
2240
2241 pub fn new_file(
2242 workspace: &mut Workspace,
2243 _: &workspace::NewFile,
2244 cx: &mut ViewContext<Workspace>,
2245 ) {
2246 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2247 "Failed to create buffer",
2248 cx,
2249 |e, _| match e.error_code() {
2250 ErrorCode::RemoteUpgradeRequired => Some(format!(
2251 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2252 e.error_tag("required").unwrap_or("the latest version")
2253 )),
2254 _ => None,
2255 },
2256 );
2257 }
2258
2259 pub fn new_in_workspace(
2260 workspace: &mut Workspace,
2261 cx: &mut ViewContext<Workspace>,
2262 ) -> Task<Result<View<Editor>>> {
2263 let project = workspace.project().clone();
2264 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2265
2266 cx.spawn(|workspace, mut cx| async move {
2267 let buffer = create.await?;
2268 workspace.update(&mut cx, |workspace, cx| {
2269 let editor =
2270 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2271 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2272 editor
2273 })
2274 })
2275 }
2276
2277 fn new_file_vertical(
2278 workspace: &mut Workspace,
2279 _: &workspace::NewFileSplitVertical,
2280 cx: &mut ViewContext<Workspace>,
2281 ) {
2282 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2283 }
2284
2285 fn new_file_horizontal(
2286 workspace: &mut Workspace,
2287 _: &workspace::NewFileSplitHorizontal,
2288 cx: &mut ViewContext<Workspace>,
2289 ) {
2290 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2291 }
2292
2293 fn new_file_in_direction(
2294 workspace: &mut Workspace,
2295 direction: SplitDirection,
2296 cx: &mut ViewContext<Workspace>,
2297 ) {
2298 let project = workspace.project().clone();
2299 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2300
2301 cx.spawn(|workspace, mut cx| async move {
2302 let buffer = create.await?;
2303 workspace.update(&mut cx, move |workspace, cx| {
2304 workspace.split_item(
2305 direction,
2306 Box::new(
2307 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2308 ),
2309 cx,
2310 )
2311 })?;
2312 anyhow::Ok(())
2313 })
2314 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2315 ErrorCode::RemoteUpgradeRequired => Some(format!(
2316 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2317 e.error_tag("required").unwrap_or("the latest version")
2318 )),
2319 _ => None,
2320 });
2321 }
2322
2323 pub fn leader_peer_id(&self) -> Option<PeerId> {
2324 self.leader_peer_id
2325 }
2326
2327 pub fn buffer(&self) -> &Model<MultiBuffer> {
2328 &self.buffer
2329 }
2330
2331 pub fn workspace(&self) -> Option<View<Workspace>> {
2332 self.workspace.as_ref()?.0.upgrade()
2333 }
2334
2335 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2336 self.buffer().read(cx).title(cx)
2337 }
2338
2339 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2340 let git_blame_gutter_max_author_length = self
2341 .render_git_blame_gutter(cx)
2342 .then(|| {
2343 if let Some(blame) = self.blame.as_ref() {
2344 let max_author_length =
2345 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2346 Some(max_author_length)
2347 } else {
2348 None
2349 }
2350 })
2351 .flatten();
2352
2353 EditorSnapshot {
2354 mode: self.mode,
2355 show_gutter: self.show_gutter,
2356 show_line_numbers: self.show_line_numbers,
2357 show_git_diff_gutter: self.show_git_diff_gutter,
2358 show_code_actions: self.show_code_actions,
2359 show_runnables: self.show_runnables,
2360 git_blame_gutter_max_author_length,
2361 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2362 scroll_anchor: self.scroll_manager.anchor(),
2363 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2364 placeholder_text: self.placeholder_text.clone(),
2365 is_focused: self.focus_handle.is_focused(cx),
2366 current_line_highlight: self
2367 .current_line_highlight
2368 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2369 gutter_hovered: self.gutter_hovered,
2370 }
2371 }
2372
2373 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2374 self.buffer.read(cx).language_at(point, cx)
2375 }
2376
2377 pub fn file_at<T: ToOffset>(
2378 &self,
2379 point: T,
2380 cx: &AppContext,
2381 ) -> Option<Arc<dyn language::File>> {
2382 self.buffer.read(cx).read(cx).file_at(point).cloned()
2383 }
2384
2385 pub fn active_excerpt(
2386 &self,
2387 cx: &AppContext,
2388 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2389 self.buffer
2390 .read(cx)
2391 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2392 }
2393
2394 pub fn mode(&self) -> EditorMode {
2395 self.mode
2396 }
2397
2398 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2399 self.collaboration_hub.as_deref()
2400 }
2401
2402 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2403 self.collaboration_hub = Some(hub);
2404 }
2405
2406 pub fn set_custom_context_menu(
2407 &mut self,
2408 f: impl 'static
2409 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2410 ) {
2411 self.custom_context_menu = Some(Box::new(f))
2412 }
2413
2414 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2415 self.completion_provider = provider;
2416 }
2417
2418 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2419 self.semantics_provider.clone()
2420 }
2421
2422 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2423 self.semantics_provider = provider;
2424 }
2425
2426 pub fn set_inline_completion_provider<T>(
2427 &mut self,
2428 provider: Option<Model<T>>,
2429 cx: &mut ViewContext<Self>,
2430 ) where
2431 T: InlineCompletionProvider,
2432 {
2433 self.inline_completion_provider =
2434 provider.map(|provider| RegisteredInlineCompletionProvider {
2435 _subscription: cx.observe(&provider, |this, _, cx| {
2436 if this.focus_handle.is_focused(cx) {
2437 this.update_visible_inline_completion(cx);
2438 }
2439 }),
2440 provider: Arc::new(provider),
2441 });
2442 self.refresh_inline_completion(false, false, cx);
2443 }
2444
2445 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2446 self.placeholder_text.as_deref()
2447 }
2448
2449 pub fn set_placeholder_text(
2450 &mut self,
2451 placeholder_text: impl Into<Arc<str>>,
2452 cx: &mut ViewContext<Self>,
2453 ) {
2454 let placeholder_text = Some(placeholder_text.into());
2455 if self.placeholder_text != placeholder_text {
2456 self.placeholder_text = placeholder_text;
2457 cx.notify();
2458 }
2459 }
2460
2461 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2462 self.cursor_shape = cursor_shape;
2463
2464 // Disrupt blink for immediate user feedback that the cursor shape has changed
2465 self.blink_manager.update(cx, BlinkManager::show_cursor);
2466
2467 cx.notify();
2468 }
2469
2470 pub fn set_current_line_highlight(
2471 &mut self,
2472 current_line_highlight: Option<CurrentLineHighlight>,
2473 ) {
2474 self.current_line_highlight = current_line_highlight;
2475 }
2476
2477 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2478 self.collapse_matches = collapse_matches;
2479 }
2480
2481 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2482 if self.collapse_matches {
2483 return range.start..range.start;
2484 }
2485 range.clone()
2486 }
2487
2488 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2489 if self.display_map.read(cx).clip_at_line_ends != clip {
2490 self.display_map
2491 .update(cx, |map, _| map.clip_at_line_ends = clip);
2492 }
2493 }
2494
2495 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2496 self.input_enabled = input_enabled;
2497 }
2498
2499 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2500 self.enable_inline_completions = enabled;
2501 }
2502
2503 pub fn set_autoindent(&mut self, autoindent: bool) {
2504 if autoindent {
2505 self.autoindent_mode = Some(AutoindentMode::EachLine);
2506 } else {
2507 self.autoindent_mode = None;
2508 }
2509 }
2510
2511 pub fn read_only(&self, cx: &AppContext) -> bool {
2512 self.read_only || self.buffer.read(cx).read_only()
2513 }
2514
2515 pub fn set_read_only(&mut self, read_only: bool) {
2516 self.read_only = read_only;
2517 }
2518
2519 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2520 self.use_autoclose = autoclose;
2521 }
2522
2523 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2524 self.use_auto_surround = auto_surround;
2525 }
2526
2527 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2528 self.auto_replace_emoji_shortcode = auto_replace;
2529 }
2530
2531 pub fn toggle_inline_completions(
2532 &mut self,
2533 _: &ToggleInlineCompletions,
2534 cx: &mut ViewContext<Self>,
2535 ) {
2536 if self.show_inline_completions_override.is_some() {
2537 self.set_show_inline_completions(None, cx);
2538 } else {
2539 let cursor = self.selections.newest_anchor().head();
2540 if let Some((buffer, cursor_buffer_position)) =
2541 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2542 {
2543 let show_inline_completions =
2544 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2545 self.set_show_inline_completions(Some(show_inline_completions), cx);
2546 }
2547 }
2548 }
2549
2550 pub fn set_show_inline_completions(
2551 &mut self,
2552 show_inline_completions: Option<bool>,
2553 cx: &mut ViewContext<Self>,
2554 ) {
2555 self.show_inline_completions_override = show_inline_completions;
2556 self.refresh_inline_completion(false, true, cx);
2557 }
2558
2559 fn should_show_inline_completions(
2560 &self,
2561 buffer: &Model<Buffer>,
2562 buffer_position: language::Anchor,
2563 cx: &AppContext,
2564 ) -> bool {
2565 if !self.snippet_stack.is_empty() {
2566 return false;
2567 }
2568
2569 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2570 return false;
2571 }
2572
2573 if let Some(provider) = self.inline_completion_provider() {
2574 if let Some(show_inline_completions) = self.show_inline_completions_override {
2575 show_inline_completions
2576 } else {
2577 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2578 }
2579 } else {
2580 false
2581 }
2582 }
2583
2584 fn inline_completions_disabled_in_scope(
2585 &self,
2586 buffer: &Model<Buffer>,
2587 buffer_position: language::Anchor,
2588 cx: &AppContext,
2589 ) -> bool {
2590 let snapshot = buffer.read(cx).snapshot();
2591 let settings = snapshot.settings_at(buffer_position, cx);
2592
2593 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2594 return false;
2595 };
2596
2597 scope.override_name().map_or(false, |scope_name| {
2598 settings
2599 .inline_completions_disabled_in
2600 .iter()
2601 .any(|s| s == scope_name)
2602 })
2603 }
2604
2605 pub fn set_use_modal_editing(&mut self, to: bool) {
2606 self.use_modal_editing = to;
2607 }
2608
2609 pub fn use_modal_editing(&self) -> bool {
2610 self.use_modal_editing
2611 }
2612
2613 fn selections_did_change(
2614 &mut self,
2615 local: bool,
2616 old_cursor_position: &Anchor,
2617 show_completions: bool,
2618 cx: &mut ViewContext<Self>,
2619 ) {
2620 cx.invalidate_character_coordinates();
2621
2622 // Copy selections to primary selection buffer
2623 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2624 if local {
2625 let selections = self.selections.all::<usize>(cx);
2626 let buffer_handle = self.buffer.read(cx).read(cx);
2627
2628 let mut text = String::new();
2629 for (index, selection) in selections.iter().enumerate() {
2630 let text_for_selection = buffer_handle
2631 .text_for_range(selection.start..selection.end)
2632 .collect::<String>();
2633
2634 text.push_str(&text_for_selection);
2635 if index != selections.len() - 1 {
2636 text.push('\n');
2637 }
2638 }
2639
2640 if !text.is_empty() {
2641 cx.write_to_primary(ClipboardItem::new_string(text));
2642 }
2643 }
2644
2645 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2646 self.buffer.update(cx, |buffer, cx| {
2647 buffer.set_active_selections(
2648 &self.selections.disjoint_anchors(),
2649 self.selections.line_mode,
2650 self.cursor_shape,
2651 cx,
2652 )
2653 });
2654 }
2655 let display_map = self
2656 .display_map
2657 .update(cx, |display_map, cx| display_map.snapshot(cx));
2658 let buffer = &display_map.buffer_snapshot;
2659 self.add_selections_state = None;
2660 self.select_next_state = None;
2661 self.select_prev_state = None;
2662 self.select_larger_syntax_node_stack.clear();
2663 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2664 self.snippet_stack
2665 .invalidate(&self.selections.disjoint_anchors(), buffer);
2666 self.take_rename(false, cx);
2667
2668 let new_cursor_position = self.selections.newest_anchor().head();
2669
2670 self.push_to_nav_history(
2671 *old_cursor_position,
2672 Some(new_cursor_position.to_point(buffer)),
2673 cx,
2674 );
2675
2676 if local {
2677 let new_cursor_position = self.selections.newest_anchor().head();
2678 let mut context_menu = self.context_menu.write();
2679 let completion_menu = match context_menu.as_ref() {
2680 Some(ContextMenu::Completions(menu)) => Some(menu),
2681
2682 _ => {
2683 *context_menu = None;
2684 None
2685 }
2686 };
2687
2688 if let Some(completion_menu) = completion_menu {
2689 let cursor_position = new_cursor_position.to_offset(buffer);
2690 let (word_range, kind) =
2691 buffer.surrounding_word(completion_menu.initial_position, true);
2692 if kind == Some(CharKind::Word)
2693 && word_range.to_inclusive().contains(&cursor_position)
2694 {
2695 let mut completion_menu = completion_menu.clone();
2696 drop(context_menu);
2697
2698 let query = Self::completion_query(buffer, cursor_position);
2699 cx.spawn(move |this, mut cx| async move {
2700 completion_menu
2701 .filter(query.as_deref(), cx.background_executor().clone())
2702 .await;
2703
2704 this.update(&mut cx, |this, cx| {
2705 let mut context_menu = this.context_menu.write();
2706 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2707 return;
2708 };
2709
2710 if menu.id > completion_menu.id {
2711 return;
2712 }
2713
2714 *context_menu = Some(ContextMenu::Completions(completion_menu));
2715 drop(context_menu);
2716 cx.notify();
2717 })
2718 })
2719 .detach();
2720
2721 if show_completions {
2722 self.show_completions(&ShowCompletions { trigger: None }, cx);
2723 }
2724 } else {
2725 drop(context_menu);
2726 self.hide_context_menu(cx);
2727 }
2728 } else {
2729 drop(context_menu);
2730 }
2731
2732 hide_hover(self, cx);
2733
2734 if old_cursor_position.to_display_point(&display_map).row()
2735 != new_cursor_position.to_display_point(&display_map).row()
2736 {
2737 self.available_code_actions.take();
2738 }
2739 self.refresh_code_actions(cx);
2740 self.refresh_document_highlights(cx);
2741 refresh_matching_bracket_highlights(self, cx);
2742 self.discard_inline_completion(false, cx);
2743 linked_editing_ranges::refresh_linked_ranges(self, cx);
2744 if self.git_blame_inline_enabled {
2745 self.start_inline_blame_timer(cx);
2746 }
2747 }
2748
2749 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2750 cx.emit(EditorEvent::SelectionsChanged { local });
2751
2752 if self.selections.disjoint_anchors().len() == 1 {
2753 cx.emit(SearchEvent::ActiveMatchChanged)
2754 }
2755 cx.notify();
2756 }
2757
2758 pub fn change_selections<R>(
2759 &mut self,
2760 autoscroll: Option<Autoscroll>,
2761 cx: &mut ViewContext<Self>,
2762 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2763 ) -> R {
2764 self.change_selections_inner(autoscroll, true, cx, change)
2765 }
2766
2767 pub fn change_selections_inner<R>(
2768 &mut self,
2769 autoscroll: Option<Autoscroll>,
2770 request_completions: bool,
2771 cx: &mut ViewContext<Self>,
2772 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2773 ) -> R {
2774 let old_cursor_position = self.selections.newest_anchor().head();
2775 self.push_to_selection_history();
2776
2777 let (changed, result) = self.selections.change_with(cx, change);
2778
2779 if changed {
2780 if let Some(autoscroll) = autoscroll {
2781 self.request_autoscroll(autoscroll, cx);
2782 }
2783 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2784
2785 if self.should_open_signature_help_automatically(
2786 &old_cursor_position,
2787 self.signature_help_state.backspace_pressed(),
2788 cx,
2789 ) {
2790 self.show_signature_help(&ShowSignatureHelp, cx);
2791 }
2792 self.signature_help_state.set_backspace_pressed(false);
2793 }
2794
2795 result
2796 }
2797
2798 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2799 where
2800 I: IntoIterator<Item = (Range<S>, T)>,
2801 S: ToOffset,
2802 T: Into<Arc<str>>,
2803 {
2804 if self.read_only(cx) {
2805 return;
2806 }
2807
2808 self.buffer
2809 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2810 }
2811
2812 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2813 where
2814 I: IntoIterator<Item = (Range<S>, T)>,
2815 S: ToOffset,
2816 T: Into<Arc<str>>,
2817 {
2818 if self.read_only(cx) {
2819 return;
2820 }
2821
2822 self.buffer.update(cx, |buffer, cx| {
2823 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2824 });
2825 }
2826
2827 pub fn edit_with_block_indent<I, S, T>(
2828 &mut self,
2829 edits: I,
2830 original_indent_columns: Vec<u32>,
2831 cx: &mut ViewContext<Self>,
2832 ) where
2833 I: IntoIterator<Item = (Range<S>, T)>,
2834 S: ToOffset,
2835 T: Into<Arc<str>>,
2836 {
2837 if self.read_only(cx) {
2838 return;
2839 }
2840
2841 self.buffer.update(cx, |buffer, cx| {
2842 buffer.edit(
2843 edits,
2844 Some(AutoindentMode::Block {
2845 original_indent_columns,
2846 }),
2847 cx,
2848 )
2849 });
2850 }
2851
2852 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2853 self.hide_context_menu(cx);
2854
2855 match phase {
2856 SelectPhase::Begin {
2857 position,
2858 add,
2859 click_count,
2860 } => self.begin_selection(position, add, click_count, cx),
2861 SelectPhase::BeginColumnar {
2862 position,
2863 goal_column,
2864 reset,
2865 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2866 SelectPhase::Extend {
2867 position,
2868 click_count,
2869 } => self.extend_selection(position, click_count, cx),
2870 SelectPhase::Update {
2871 position,
2872 goal_column,
2873 scroll_delta,
2874 } => self.update_selection(position, goal_column, scroll_delta, cx),
2875 SelectPhase::End => self.end_selection(cx),
2876 }
2877 }
2878
2879 fn extend_selection(
2880 &mut self,
2881 position: DisplayPoint,
2882 click_count: usize,
2883 cx: &mut ViewContext<Self>,
2884 ) {
2885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2886 let tail = self.selections.newest::<usize>(cx).tail();
2887 self.begin_selection(position, false, click_count, cx);
2888
2889 let position = position.to_offset(&display_map, Bias::Left);
2890 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2891
2892 let mut pending_selection = self
2893 .selections
2894 .pending_anchor()
2895 .expect("extend_selection not called with pending selection");
2896 if position >= tail {
2897 pending_selection.start = tail_anchor;
2898 } else {
2899 pending_selection.end = tail_anchor;
2900 pending_selection.reversed = true;
2901 }
2902
2903 let mut pending_mode = self.selections.pending_mode().unwrap();
2904 match &mut pending_mode {
2905 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2906 _ => {}
2907 }
2908
2909 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2910 s.set_pending(pending_selection, pending_mode)
2911 });
2912 }
2913
2914 fn begin_selection(
2915 &mut self,
2916 position: DisplayPoint,
2917 add: bool,
2918 click_count: usize,
2919 cx: &mut ViewContext<Self>,
2920 ) {
2921 if !self.focus_handle.is_focused(cx) {
2922 self.last_focused_descendant = None;
2923 cx.focus(&self.focus_handle);
2924 }
2925
2926 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2927 let buffer = &display_map.buffer_snapshot;
2928 let newest_selection = self.selections.newest_anchor().clone();
2929 let position = display_map.clip_point(position, Bias::Left);
2930
2931 let start;
2932 let end;
2933 let mode;
2934 let mut auto_scroll;
2935 match click_count {
2936 1 => {
2937 start = buffer.anchor_before(position.to_point(&display_map));
2938 end = start;
2939 mode = SelectMode::Character;
2940 auto_scroll = true;
2941 }
2942 2 => {
2943 let range = movement::surrounding_word(&display_map, position);
2944 start = buffer.anchor_before(range.start.to_point(&display_map));
2945 end = buffer.anchor_before(range.end.to_point(&display_map));
2946 mode = SelectMode::Word(start..end);
2947 auto_scroll = true;
2948 }
2949 3 => {
2950 let position = display_map
2951 .clip_point(position, Bias::Left)
2952 .to_point(&display_map);
2953 let line_start = display_map.prev_line_boundary(position).0;
2954 let next_line_start = buffer.clip_point(
2955 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2956 Bias::Left,
2957 );
2958 start = buffer.anchor_before(line_start);
2959 end = buffer.anchor_before(next_line_start);
2960 mode = SelectMode::Line(start..end);
2961 auto_scroll = true;
2962 }
2963 _ => {
2964 start = buffer.anchor_before(0);
2965 end = buffer.anchor_before(buffer.len());
2966 mode = SelectMode::All;
2967 auto_scroll = false;
2968 }
2969 }
2970 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2971
2972 let point_to_delete: Option<usize> = {
2973 let selected_points: Vec<Selection<Point>> =
2974 self.selections.disjoint_in_range(start..end, cx);
2975
2976 if !add || click_count > 1 {
2977 None
2978 } else if !selected_points.is_empty() {
2979 Some(selected_points[0].id)
2980 } else {
2981 let clicked_point_already_selected =
2982 self.selections.disjoint.iter().find(|selection| {
2983 selection.start.to_point(buffer) == start.to_point(buffer)
2984 || selection.end.to_point(buffer) == end.to_point(buffer)
2985 });
2986
2987 clicked_point_already_selected.map(|selection| selection.id)
2988 }
2989 };
2990
2991 let selections_count = self.selections.count();
2992
2993 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2994 if let Some(point_to_delete) = point_to_delete {
2995 s.delete(point_to_delete);
2996
2997 if selections_count == 1 {
2998 s.set_pending_anchor_range(start..end, mode);
2999 }
3000 } else {
3001 if !add {
3002 s.clear_disjoint();
3003 } else if click_count > 1 {
3004 s.delete(newest_selection.id)
3005 }
3006
3007 s.set_pending_anchor_range(start..end, mode);
3008 }
3009 });
3010 }
3011
3012 fn begin_columnar_selection(
3013 &mut self,
3014 position: DisplayPoint,
3015 goal_column: u32,
3016 reset: bool,
3017 cx: &mut ViewContext<Self>,
3018 ) {
3019 if !self.focus_handle.is_focused(cx) {
3020 self.last_focused_descendant = None;
3021 cx.focus(&self.focus_handle);
3022 }
3023
3024 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3025
3026 if reset {
3027 let pointer_position = display_map
3028 .buffer_snapshot
3029 .anchor_before(position.to_point(&display_map));
3030
3031 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3032 s.clear_disjoint();
3033 s.set_pending_anchor_range(
3034 pointer_position..pointer_position,
3035 SelectMode::Character,
3036 );
3037 });
3038 }
3039
3040 let tail = self.selections.newest::<Point>(cx).tail();
3041 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3042
3043 if !reset {
3044 self.select_columns(
3045 tail.to_display_point(&display_map),
3046 position,
3047 goal_column,
3048 &display_map,
3049 cx,
3050 );
3051 }
3052 }
3053
3054 fn update_selection(
3055 &mut self,
3056 position: DisplayPoint,
3057 goal_column: u32,
3058 scroll_delta: gpui::Point<f32>,
3059 cx: &mut ViewContext<Self>,
3060 ) {
3061 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3062
3063 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3064 let tail = tail.to_display_point(&display_map);
3065 self.select_columns(tail, position, goal_column, &display_map, cx);
3066 } else if let Some(mut pending) = self.selections.pending_anchor() {
3067 let buffer = self.buffer.read(cx).snapshot(cx);
3068 let head;
3069 let tail;
3070 let mode = self.selections.pending_mode().unwrap();
3071 match &mode {
3072 SelectMode::Character => {
3073 head = position.to_point(&display_map);
3074 tail = pending.tail().to_point(&buffer);
3075 }
3076 SelectMode::Word(original_range) => {
3077 let original_display_range = original_range.start.to_display_point(&display_map)
3078 ..original_range.end.to_display_point(&display_map);
3079 let original_buffer_range = original_display_range.start.to_point(&display_map)
3080 ..original_display_range.end.to_point(&display_map);
3081 if movement::is_inside_word(&display_map, position)
3082 || original_display_range.contains(&position)
3083 {
3084 let word_range = movement::surrounding_word(&display_map, position);
3085 if word_range.start < original_display_range.start {
3086 head = word_range.start.to_point(&display_map);
3087 } else {
3088 head = word_range.end.to_point(&display_map);
3089 }
3090 } else {
3091 head = position.to_point(&display_map);
3092 }
3093
3094 if head <= original_buffer_range.start {
3095 tail = original_buffer_range.end;
3096 } else {
3097 tail = original_buffer_range.start;
3098 }
3099 }
3100 SelectMode::Line(original_range) => {
3101 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3102
3103 let position = display_map
3104 .clip_point(position, Bias::Left)
3105 .to_point(&display_map);
3106 let line_start = display_map.prev_line_boundary(position).0;
3107 let next_line_start = buffer.clip_point(
3108 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3109 Bias::Left,
3110 );
3111
3112 if line_start < original_range.start {
3113 head = line_start
3114 } else {
3115 head = next_line_start
3116 }
3117
3118 if head <= original_range.start {
3119 tail = original_range.end;
3120 } else {
3121 tail = original_range.start;
3122 }
3123 }
3124 SelectMode::All => {
3125 return;
3126 }
3127 };
3128
3129 if head < tail {
3130 pending.start = buffer.anchor_before(head);
3131 pending.end = buffer.anchor_before(tail);
3132 pending.reversed = true;
3133 } else {
3134 pending.start = buffer.anchor_before(tail);
3135 pending.end = buffer.anchor_before(head);
3136 pending.reversed = false;
3137 }
3138
3139 self.change_selections(None, cx, |s| {
3140 s.set_pending(pending, mode);
3141 });
3142 } else {
3143 log::error!("update_selection dispatched with no pending selection");
3144 return;
3145 }
3146
3147 self.apply_scroll_delta(scroll_delta, cx);
3148 cx.notify();
3149 }
3150
3151 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3152 self.columnar_selection_tail.take();
3153 if self.selections.pending_anchor().is_some() {
3154 let selections = self.selections.all::<usize>(cx);
3155 self.change_selections(None, cx, |s| {
3156 s.select(selections);
3157 s.clear_pending();
3158 });
3159 }
3160 }
3161
3162 fn select_columns(
3163 &mut self,
3164 tail: DisplayPoint,
3165 head: DisplayPoint,
3166 goal_column: u32,
3167 display_map: &DisplaySnapshot,
3168 cx: &mut ViewContext<Self>,
3169 ) {
3170 let start_row = cmp::min(tail.row(), head.row());
3171 let end_row = cmp::max(tail.row(), head.row());
3172 let start_column = cmp::min(tail.column(), goal_column);
3173 let end_column = cmp::max(tail.column(), goal_column);
3174 let reversed = start_column < tail.column();
3175
3176 let selection_ranges = (start_row.0..=end_row.0)
3177 .map(DisplayRow)
3178 .filter_map(|row| {
3179 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3180 let start = display_map
3181 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3182 .to_point(display_map);
3183 let end = display_map
3184 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3185 .to_point(display_map);
3186 if reversed {
3187 Some(end..start)
3188 } else {
3189 Some(start..end)
3190 }
3191 } else {
3192 None
3193 }
3194 })
3195 .collect::<Vec<_>>();
3196
3197 self.change_selections(None, cx, |s| {
3198 s.select_ranges(selection_ranges);
3199 });
3200 cx.notify();
3201 }
3202
3203 pub fn has_pending_nonempty_selection(&self) -> bool {
3204 let pending_nonempty_selection = match self.selections.pending_anchor() {
3205 Some(Selection { start, end, .. }) => start != end,
3206 None => false,
3207 };
3208
3209 pending_nonempty_selection
3210 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3211 }
3212
3213 pub fn has_pending_selection(&self) -> bool {
3214 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3215 }
3216
3217 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3218 if self.clear_expanded_diff_hunks(cx) {
3219 cx.notify();
3220 return;
3221 }
3222 if self.dismiss_menus_and_popups(true, cx) {
3223 return;
3224 }
3225
3226 if self.mode == EditorMode::Full
3227 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3228 {
3229 return;
3230 }
3231
3232 cx.propagate();
3233 }
3234
3235 pub fn dismiss_menus_and_popups(
3236 &mut self,
3237 should_report_inline_completion_event: bool,
3238 cx: &mut ViewContext<Self>,
3239 ) -> bool {
3240 if self.take_rename(false, cx).is_some() {
3241 return true;
3242 }
3243
3244 if hide_hover(self, cx) {
3245 return true;
3246 }
3247
3248 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3249 return true;
3250 }
3251
3252 if self.hide_context_menu(cx).is_some() {
3253 return true;
3254 }
3255
3256 if self.mouse_context_menu.take().is_some() {
3257 return true;
3258 }
3259
3260 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3261 return true;
3262 }
3263
3264 if self.snippet_stack.pop().is_some() {
3265 return true;
3266 }
3267
3268 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3269 self.dismiss_diagnostics(cx);
3270 return true;
3271 }
3272
3273 false
3274 }
3275
3276 fn linked_editing_ranges_for(
3277 &self,
3278 selection: Range<text::Anchor>,
3279 cx: &AppContext,
3280 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3281 if self.linked_edit_ranges.is_empty() {
3282 return None;
3283 }
3284 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3285 selection.end.buffer_id.and_then(|end_buffer_id| {
3286 if selection.start.buffer_id != Some(end_buffer_id) {
3287 return None;
3288 }
3289 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3290 let snapshot = buffer.read(cx).snapshot();
3291 self.linked_edit_ranges
3292 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3293 .map(|ranges| (ranges, snapshot, buffer))
3294 })?;
3295 use text::ToOffset as TO;
3296 // find offset from the start of current range to current cursor position
3297 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3298
3299 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3300 let start_difference = start_offset - start_byte_offset;
3301 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3302 let end_difference = end_offset - start_byte_offset;
3303 // Current range has associated linked ranges.
3304 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3305 for range in linked_ranges.iter() {
3306 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3307 let end_offset = start_offset + end_difference;
3308 let start_offset = start_offset + start_difference;
3309 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3310 continue;
3311 }
3312 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3313 if s.start.buffer_id != selection.start.buffer_id
3314 || s.end.buffer_id != selection.end.buffer_id
3315 {
3316 return false;
3317 }
3318 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3319 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3320 }) {
3321 continue;
3322 }
3323 let start = buffer_snapshot.anchor_after(start_offset);
3324 let end = buffer_snapshot.anchor_after(end_offset);
3325 linked_edits
3326 .entry(buffer.clone())
3327 .or_default()
3328 .push(start..end);
3329 }
3330 Some(linked_edits)
3331 }
3332
3333 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3334 let text: Arc<str> = text.into();
3335
3336 if self.read_only(cx) {
3337 return;
3338 }
3339
3340 let selections = self.selections.all_adjusted(cx);
3341 let mut bracket_inserted = false;
3342 let mut edits = Vec::new();
3343 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3344 let mut new_selections = Vec::with_capacity(selections.len());
3345 let mut new_autoclose_regions = Vec::new();
3346 let snapshot = self.buffer.read(cx).read(cx);
3347
3348 for (selection, autoclose_region) in
3349 self.selections_with_autoclose_regions(selections, &snapshot)
3350 {
3351 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3352 // Determine if the inserted text matches the opening or closing
3353 // bracket of any of this language's bracket pairs.
3354 let mut bracket_pair = None;
3355 let mut is_bracket_pair_start = false;
3356 let mut is_bracket_pair_end = false;
3357 if !text.is_empty() {
3358 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3359 // and they are removing the character that triggered IME popup.
3360 for (pair, enabled) in scope.brackets() {
3361 if !pair.close && !pair.surround {
3362 continue;
3363 }
3364
3365 if enabled && pair.start.ends_with(text.as_ref()) {
3366 let prefix_len = pair.start.len() - text.len();
3367 let preceding_text_matches_prefix = prefix_len == 0
3368 || (selection.start.column >= (prefix_len as u32)
3369 && snapshot.contains_str_at(
3370 Point::new(
3371 selection.start.row,
3372 selection.start.column - (prefix_len as u32),
3373 ),
3374 &pair.start[..prefix_len],
3375 ));
3376 if preceding_text_matches_prefix {
3377 bracket_pair = Some(pair.clone());
3378 is_bracket_pair_start = true;
3379 break;
3380 }
3381 }
3382 if pair.end.as_str() == text.as_ref() {
3383 bracket_pair = Some(pair.clone());
3384 is_bracket_pair_end = true;
3385 break;
3386 }
3387 }
3388 }
3389
3390 if let Some(bracket_pair) = bracket_pair {
3391 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3392 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3393 let auto_surround =
3394 self.use_auto_surround && snapshot_settings.use_auto_surround;
3395 if selection.is_empty() {
3396 if is_bracket_pair_start {
3397 // If the inserted text is a suffix of an opening bracket and the
3398 // selection is preceded by the rest of the opening bracket, then
3399 // insert the closing bracket.
3400 let following_text_allows_autoclose = snapshot
3401 .chars_at(selection.start)
3402 .next()
3403 .map_or(true, |c| scope.should_autoclose_before(c));
3404
3405 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3406 && bracket_pair.start.len() == 1
3407 {
3408 let target = bracket_pair.start.chars().next().unwrap();
3409 let current_line_count = snapshot
3410 .reversed_chars_at(selection.start)
3411 .take_while(|&c| c != '\n')
3412 .filter(|&c| c == target)
3413 .count();
3414 current_line_count % 2 == 1
3415 } else {
3416 false
3417 };
3418
3419 if autoclose
3420 && bracket_pair.close
3421 && following_text_allows_autoclose
3422 && !is_closing_quote
3423 {
3424 let anchor = snapshot.anchor_before(selection.end);
3425 new_selections.push((selection.map(|_| anchor), text.len()));
3426 new_autoclose_regions.push((
3427 anchor,
3428 text.len(),
3429 selection.id,
3430 bracket_pair.clone(),
3431 ));
3432 edits.push((
3433 selection.range(),
3434 format!("{}{}", text, bracket_pair.end).into(),
3435 ));
3436 bracket_inserted = true;
3437 continue;
3438 }
3439 }
3440
3441 if let Some(region) = autoclose_region {
3442 // If the selection is followed by an auto-inserted closing bracket,
3443 // then don't insert that closing bracket again; just move the selection
3444 // past the closing bracket.
3445 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3446 && text.as_ref() == region.pair.end.as_str();
3447 if should_skip {
3448 let anchor = snapshot.anchor_after(selection.end);
3449 new_selections
3450 .push((selection.map(|_| anchor), region.pair.end.len()));
3451 continue;
3452 }
3453 }
3454
3455 let always_treat_brackets_as_autoclosed = snapshot
3456 .settings_at(selection.start, cx)
3457 .always_treat_brackets_as_autoclosed;
3458 if always_treat_brackets_as_autoclosed
3459 && is_bracket_pair_end
3460 && snapshot.contains_str_at(selection.end, text.as_ref())
3461 {
3462 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3463 // and the inserted text is a closing bracket and the selection is followed
3464 // by the closing bracket then move the selection past the closing bracket.
3465 let anchor = snapshot.anchor_after(selection.end);
3466 new_selections.push((selection.map(|_| anchor), text.len()));
3467 continue;
3468 }
3469 }
3470 // If an opening bracket is 1 character long and is typed while
3471 // text is selected, then surround that text with the bracket pair.
3472 else if auto_surround
3473 && bracket_pair.surround
3474 && is_bracket_pair_start
3475 && bracket_pair.start.chars().count() == 1
3476 {
3477 edits.push((selection.start..selection.start, text.clone()));
3478 edits.push((
3479 selection.end..selection.end,
3480 bracket_pair.end.as_str().into(),
3481 ));
3482 bracket_inserted = true;
3483 new_selections.push((
3484 Selection {
3485 id: selection.id,
3486 start: snapshot.anchor_after(selection.start),
3487 end: snapshot.anchor_before(selection.end),
3488 reversed: selection.reversed,
3489 goal: selection.goal,
3490 },
3491 0,
3492 ));
3493 continue;
3494 }
3495 }
3496 }
3497
3498 if self.auto_replace_emoji_shortcode
3499 && selection.is_empty()
3500 && text.as_ref().ends_with(':')
3501 {
3502 if let Some(possible_emoji_short_code) =
3503 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3504 {
3505 if !possible_emoji_short_code.is_empty() {
3506 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3507 let emoji_shortcode_start = Point::new(
3508 selection.start.row,
3509 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3510 );
3511
3512 // Remove shortcode from buffer
3513 edits.push((
3514 emoji_shortcode_start..selection.start,
3515 "".to_string().into(),
3516 ));
3517 new_selections.push((
3518 Selection {
3519 id: selection.id,
3520 start: snapshot.anchor_after(emoji_shortcode_start),
3521 end: snapshot.anchor_before(selection.start),
3522 reversed: selection.reversed,
3523 goal: selection.goal,
3524 },
3525 0,
3526 ));
3527
3528 // Insert emoji
3529 let selection_start_anchor = snapshot.anchor_after(selection.start);
3530 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3531 edits.push((selection.start..selection.end, emoji.to_string().into()));
3532
3533 continue;
3534 }
3535 }
3536 }
3537 }
3538
3539 // If not handling any auto-close operation, then just replace the selected
3540 // text with the given input and move the selection to the end of the
3541 // newly inserted text.
3542 let anchor = snapshot.anchor_after(selection.end);
3543 if !self.linked_edit_ranges.is_empty() {
3544 let start_anchor = snapshot.anchor_before(selection.start);
3545
3546 let is_word_char = text.chars().next().map_or(true, |char| {
3547 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3548 classifier.is_word(char)
3549 });
3550
3551 if is_word_char {
3552 if let Some(ranges) = self
3553 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3554 {
3555 for (buffer, edits) in ranges {
3556 linked_edits
3557 .entry(buffer.clone())
3558 .or_default()
3559 .extend(edits.into_iter().map(|range| (range, text.clone())));
3560 }
3561 }
3562 }
3563 }
3564
3565 new_selections.push((selection.map(|_| anchor), 0));
3566 edits.push((selection.start..selection.end, text.clone()));
3567 }
3568
3569 drop(snapshot);
3570
3571 self.transact(cx, |this, cx| {
3572 this.buffer.update(cx, |buffer, cx| {
3573 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3574 });
3575 for (buffer, edits) in linked_edits {
3576 buffer.update(cx, |buffer, cx| {
3577 let snapshot = buffer.snapshot();
3578 let edits = edits
3579 .into_iter()
3580 .map(|(range, text)| {
3581 use text::ToPoint as TP;
3582 let end_point = TP::to_point(&range.end, &snapshot);
3583 let start_point = TP::to_point(&range.start, &snapshot);
3584 (start_point..end_point, text)
3585 })
3586 .sorted_by_key(|(range, _)| range.start)
3587 .collect::<Vec<_>>();
3588 buffer.edit(edits, None, cx);
3589 })
3590 }
3591 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3592 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3593 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3594 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3595 .zip(new_selection_deltas)
3596 .map(|(selection, delta)| Selection {
3597 id: selection.id,
3598 start: selection.start + delta,
3599 end: selection.end + delta,
3600 reversed: selection.reversed,
3601 goal: SelectionGoal::None,
3602 })
3603 .collect::<Vec<_>>();
3604
3605 let mut i = 0;
3606 for (position, delta, selection_id, pair) in new_autoclose_regions {
3607 let position = position.to_offset(&map.buffer_snapshot) + delta;
3608 let start = map.buffer_snapshot.anchor_before(position);
3609 let end = map.buffer_snapshot.anchor_after(position);
3610 while let Some(existing_state) = this.autoclose_regions.get(i) {
3611 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3612 Ordering::Less => i += 1,
3613 Ordering::Greater => break,
3614 Ordering::Equal => {
3615 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3616 Ordering::Less => i += 1,
3617 Ordering::Equal => break,
3618 Ordering::Greater => break,
3619 }
3620 }
3621 }
3622 }
3623 this.autoclose_regions.insert(
3624 i,
3625 AutocloseRegion {
3626 selection_id,
3627 range: start..end,
3628 pair,
3629 },
3630 );
3631 }
3632
3633 let had_active_inline_completion = this.has_active_inline_completion(cx);
3634 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3635 s.select(new_selections)
3636 });
3637
3638 if !bracket_inserted {
3639 if let Some(on_type_format_task) =
3640 this.trigger_on_type_formatting(text.to_string(), cx)
3641 {
3642 on_type_format_task.detach_and_log_err(cx);
3643 }
3644 }
3645
3646 let editor_settings = EditorSettings::get_global(cx);
3647 if bracket_inserted
3648 && (editor_settings.auto_signature_help
3649 || editor_settings.show_signature_help_after_edits)
3650 {
3651 this.show_signature_help(&ShowSignatureHelp, cx);
3652 }
3653
3654 let trigger_in_words = !had_active_inline_completion;
3655 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3656 linked_editing_ranges::refresh_linked_ranges(this, cx);
3657 this.refresh_inline_completion(true, false, cx);
3658 });
3659 }
3660
3661 fn find_possible_emoji_shortcode_at_position(
3662 snapshot: &MultiBufferSnapshot,
3663 position: Point,
3664 ) -> Option<String> {
3665 let mut chars = Vec::new();
3666 let mut found_colon = false;
3667 for char in snapshot.reversed_chars_at(position).take(100) {
3668 // Found a possible emoji shortcode in the middle of the buffer
3669 if found_colon {
3670 if char.is_whitespace() {
3671 chars.reverse();
3672 return Some(chars.iter().collect());
3673 }
3674 // If the previous character is not a whitespace, we are in the middle of a word
3675 // and we only want to complete the shortcode if the word is made up of other emojis
3676 let mut containing_word = String::new();
3677 for ch in snapshot
3678 .reversed_chars_at(position)
3679 .skip(chars.len() + 1)
3680 .take(100)
3681 {
3682 if ch.is_whitespace() {
3683 break;
3684 }
3685 containing_word.push(ch);
3686 }
3687 let containing_word = containing_word.chars().rev().collect::<String>();
3688 if util::word_consists_of_emojis(containing_word.as_str()) {
3689 chars.reverse();
3690 return Some(chars.iter().collect());
3691 }
3692 }
3693
3694 if char.is_whitespace() || !char.is_ascii() {
3695 return None;
3696 }
3697 if char == ':' {
3698 found_colon = true;
3699 } else {
3700 chars.push(char);
3701 }
3702 }
3703 // Found a possible emoji shortcode at the beginning of the buffer
3704 chars.reverse();
3705 Some(chars.iter().collect())
3706 }
3707
3708 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3709 self.transact(cx, |this, cx| {
3710 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3711 let selections = this.selections.all::<usize>(cx);
3712 let multi_buffer = this.buffer.read(cx);
3713 let buffer = multi_buffer.snapshot(cx);
3714 selections
3715 .iter()
3716 .map(|selection| {
3717 let start_point = selection.start.to_point(&buffer);
3718 let mut indent =
3719 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3720 indent.len = cmp::min(indent.len, start_point.column);
3721 let start = selection.start;
3722 let end = selection.end;
3723 let selection_is_empty = start == end;
3724 let language_scope = buffer.language_scope_at(start);
3725 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3726 &language_scope
3727 {
3728 let leading_whitespace_len = buffer
3729 .reversed_chars_at(start)
3730 .take_while(|c| c.is_whitespace() && *c != '\n')
3731 .map(|c| c.len_utf8())
3732 .sum::<usize>();
3733
3734 let trailing_whitespace_len = buffer
3735 .chars_at(end)
3736 .take_while(|c| c.is_whitespace() && *c != '\n')
3737 .map(|c| c.len_utf8())
3738 .sum::<usize>();
3739
3740 let insert_extra_newline =
3741 language.brackets().any(|(pair, enabled)| {
3742 let pair_start = pair.start.trim_end();
3743 let pair_end = pair.end.trim_start();
3744
3745 enabled
3746 && pair.newline
3747 && buffer.contains_str_at(
3748 end + trailing_whitespace_len,
3749 pair_end,
3750 )
3751 && buffer.contains_str_at(
3752 (start - leading_whitespace_len)
3753 .saturating_sub(pair_start.len()),
3754 pair_start,
3755 )
3756 });
3757
3758 // Comment extension on newline is allowed only for cursor selections
3759 let comment_delimiter = maybe!({
3760 if !selection_is_empty {
3761 return None;
3762 }
3763
3764 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3765 return None;
3766 }
3767
3768 let delimiters = language.line_comment_prefixes();
3769 let max_len_of_delimiter =
3770 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3771 let (snapshot, range) =
3772 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3773
3774 let mut index_of_first_non_whitespace = 0;
3775 let comment_candidate = snapshot
3776 .chars_for_range(range)
3777 .skip_while(|c| {
3778 let should_skip = c.is_whitespace();
3779 if should_skip {
3780 index_of_first_non_whitespace += 1;
3781 }
3782 should_skip
3783 })
3784 .take(max_len_of_delimiter)
3785 .collect::<String>();
3786 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3787 comment_candidate.starts_with(comment_prefix.as_ref())
3788 })?;
3789 let cursor_is_placed_after_comment_marker =
3790 index_of_first_non_whitespace + comment_prefix.len()
3791 <= start_point.column as usize;
3792 if cursor_is_placed_after_comment_marker {
3793 Some(comment_prefix.clone())
3794 } else {
3795 None
3796 }
3797 });
3798 (comment_delimiter, insert_extra_newline)
3799 } else {
3800 (None, false)
3801 };
3802
3803 let capacity_for_delimiter = comment_delimiter
3804 .as_deref()
3805 .map(str::len)
3806 .unwrap_or_default();
3807 let mut new_text =
3808 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3809 new_text.push('\n');
3810 new_text.extend(indent.chars());
3811 if let Some(delimiter) = &comment_delimiter {
3812 new_text.push_str(delimiter);
3813 }
3814 if insert_extra_newline {
3815 new_text = new_text.repeat(2);
3816 }
3817
3818 let anchor = buffer.anchor_after(end);
3819 let new_selection = selection.map(|_| anchor);
3820 (
3821 (start..end, new_text),
3822 (insert_extra_newline, new_selection),
3823 )
3824 })
3825 .unzip()
3826 };
3827
3828 this.edit_with_autoindent(edits, cx);
3829 let buffer = this.buffer.read(cx).snapshot(cx);
3830 let new_selections = selection_fixup_info
3831 .into_iter()
3832 .map(|(extra_newline_inserted, new_selection)| {
3833 let mut cursor = new_selection.end.to_point(&buffer);
3834 if extra_newline_inserted {
3835 cursor.row -= 1;
3836 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3837 }
3838 new_selection.map(|_| cursor)
3839 })
3840 .collect();
3841
3842 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3843 this.refresh_inline_completion(true, false, cx);
3844 });
3845 }
3846
3847 pub fn newline_above(&mut self, _: &NewlineAbove, 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
3854 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3855 let cursor = selection.head();
3856 let row = cursor.row;
3857
3858 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3859
3860 let newline = "\n".to_string();
3861 edits.push((start_of_line..start_of_line, newline));
3862
3863 rows.push(row + rows_inserted as u32);
3864 }
3865
3866 self.transact(cx, |editor, cx| {
3867 editor.edit(edits, cx);
3868
3869 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3870 let mut index = 0;
3871 s.move_cursors_with(|map, _, _| {
3872 let row = rows[index];
3873 index += 1;
3874
3875 let point = Point::new(row, 0);
3876 let boundary = map.next_line_boundary(point).1;
3877 let clipped = map.clip_point(boundary, Bias::Left);
3878
3879 (clipped, SelectionGoal::None)
3880 });
3881 });
3882
3883 let mut indent_edits = Vec::new();
3884 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3885 for row in rows {
3886 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3887 for (row, indent) in indents {
3888 if indent.len == 0 {
3889 continue;
3890 }
3891
3892 let text = match indent.kind {
3893 IndentKind::Space => " ".repeat(indent.len as usize),
3894 IndentKind::Tab => "\t".repeat(indent.len as usize),
3895 };
3896 let point = Point::new(row.0, 0);
3897 indent_edits.push((point..point, text));
3898 }
3899 }
3900 editor.edit(indent_edits, cx);
3901 });
3902 }
3903
3904 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3905 let buffer = self.buffer.read(cx);
3906 let snapshot = buffer.snapshot(cx);
3907
3908 let mut edits = Vec::new();
3909 let mut rows = Vec::new();
3910 let mut rows_inserted = 0;
3911
3912 for selection in self.selections.all_adjusted(cx) {
3913 let cursor = selection.head();
3914 let row = cursor.row;
3915
3916 let point = Point::new(row + 1, 0);
3917 let start_of_line = snapshot.clip_point(point, Bias::Left);
3918
3919 let newline = "\n".to_string();
3920 edits.push((start_of_line..start_of_line, newline));
3921
3922 rows_inserted += 1;
3923 rows.push(row + rows_inserted);
3924 }
3925
3926 self.transact(cx, |editor, cx| {
3927 editor.edit(edits, cx);
3928
3929 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3930 let mut index = 0;
3931 s.move_cursors_with(|map, _, _| {
3932 let row = rows[index];
3933 index += 1;
3934
3935 let point = Point::new(row, 0);
3936 let boundary = map.next_line_boundary(point).1;
3937 let clipped = map.clip_point(boundary, Bias::Left);
3938
3939 (clipped, SelectionGoal::None)
3940 });
3941 });
3942
3943 let mut indent_edits = Vec::new();
3944 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3945 for row in rows {
3946 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3947 for (row, indent) in indents {
3948 if indent.len == 0 {
3949 continue;
3950 }
3951
3952 let text = match indent.kind {
3953 IndentKind::Space => " ".repeat(indent.len as usize),
3954 IndentKind::Tab => "\t".repeat(indent.len as usize),
3955 };
3956 let point = Point::new(row.0, 0);
3957 indent_edits.push((point..point, text));
3958 }
3959 }
3960 editor.edit(indent_edits, cx);
3961 });
3962 }
3963
3964 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3965 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3966 original_indent_columns: Vec::new(),
3967 });
3968 self.insert_with_autoindent_mode(text, autoindent, cx);
3969 }
3970
3971 fn insert_with_autoindent_mode(
3972 &mut self,
3973 text: &str,
3974 autoindent_mode: Option<AutoindentMode>,
3975 cx: &mut ViewContext<Self>,
3976 ) {
3977 if self.read_only(cx) {
3978 return;
3979 }
3980
3981 let text: Arc<str> = text.into();
3982 self.transact(cx, |this, cx| {
3983 let old_selections = this.selections.all_adjusted(cx);
3984 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3985 let anchors = {
3986 let snapshot = buffer.read(cx);
3987 old_selections
3988 .iter()
3989 .map(|s| {
3990 let anchor = snapshot.anchor_after(s.head());
3991 s.map(|_| anchor)
3992 })
3993 .collect::<Vec<_>>()
3994 };
3995 buffer.edit(
3996 old_selections
3997 .iter()
3998 .map(|s| (s.start..s.end, text.clone())),
3999 autoindent_mode,
4000 cx,
4001 );
4002 anchors
4003 });
4004
4005 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4006 s.select_anchors(selection_anchors);
4007 })
4008 });
4009 }
4010
4011 fn trigger_completion_on_input(
4012 &mut self,
4013 text: &str,
4014 trigger_in_words: bool,
4015 cx: &mut ViewContext<Self>,
4016 ) {
4017 if self.is_completion_trigger(text, trigger_in_words, cx) {
4018 self.show_completions(
4019 &ShowCompletions {
4020 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4021 },
4022 cx,
4023 );
4024 } else {
4025 self.hide_context_menu(cx);
4026 }
4027 }
4028
4029 fn is_completion_trigger(
4030 &self,
4031 text: &str,
4032 trigger_in_words: bool,
4033 cx: &mut ViewContext<Self>,
4034 ) -> bool {
4035 let position = self.selections.newest_anchor().head();
4036 let multibuffer = self.buffer.read(cx);
4037 let Some(buffer) = position
4038 .buffer_id
4039 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4040 else {
4041 return false;
4042 };
4043
4044 if let Some(completion_provider) = &self.completion_provider {
4045 completion_provider.is_completion_trigger(
4046 &buffer,
4047 position.text_anchor,
4048 text,
4049 trigger_in_words,
4050 cx,
4051 )
4052 } else {
4053 false
4054 }
4055 }
4056
4057 /// If any empty selections is touching the start of its innermost containing autoclose
4058 /// region, expand it to select the brackets.
4059 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4060 let selections = self.selections.all::<usize>(cx);
4061 let buffer = self.buffer.read(cx).read(cx);
4062 let new_selections = self
4063 .selections_with_autoclose_regions(selections, &buffer)
4064 .map(|(mut selection, region)| {
4065 if !selection.is_empty() {
4066 return selection;
4067 }
4068
4069 if let Some(region) = region {
4070 let mut range = region.range.to_offset(&buffer);
4071 if selection.start == range.start && range.start >= region.pair.start.len() {
4072 range.start -= region.pair.start.len();
4073 if buffer.contains_str_at(range.start, ®ion.pair.start)
4074 && buffer.contains_str_at(range.end, ®ion.pair.end)
4075 {
4076 range.end += region.pair.end.len();
4077 selection.start = range.start;
4078 selection.end = range.end;
4079
4080 return selection;
4081 }
4082 }
4083 }
4084
4085 let always_treat_brackets_as_autoclosed = buffer
4086 .settings_at(selection.start, cx)
4087 .always_treat_brackets_as_autoclosed;
4088
4089 if !always_treat_brackets_as_autoclosed {
4090 return selection;
4091 }
4092
4093 if let Some(scope) = buffer.language_scope_at(selection.start) {
4094 for (pair, enabled) in scope.brackets() {
4095 if !enabled || !pair.close {
4096 continue;
4097 }
4098
4099 if buffer.contains_str_at(selection.start, &pair.end) {
4100 let pair_start_len = pair.start.len();
4101 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4102 {
4103 selection.start -= pair_start_len;
4104 selection.end += pair.end.len();
4105
4106 return selection;
4107 }
4108 }
4109 }
4110 }
4111
4112 selection
4113 })
4114 .collect();
4115
4116 drop(buffer);
4117 self.change_selections(None, cx, |selections| selections.select(new_selections));
4118 }
4119
4120 /// Iterate the given selections, and for each one, find the smallest surrounding
4121 /// autoclose region. This uses the ordering of the selections and the autoclose
4122 /// regions to avoid repeated comparisons.
4123 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4124 &'a self,
4125 selections: impl IntoIterator<Item = Selection<D>>,
4126 buffer: &'a MultiBufferSnapshot,
4127 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4128 let mut i = 0;
4129 let mut regions = self.autoclose_regions.as_slice();
4130 selections.into_iter().map(move |selection| {
4131 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4132
4133 let mut enclosing = None;
4134 while let Some(pair_state) = regions.get(i) {
4135 if pair_state.range.end.to_offset(buffer) < range.start {
4136 regions = ®ions[i + 1..];
4137 i = 0;
4138 } else if pair_state.range.start.to_offset(buffer) > range.end {
4139 break;
4140 } else {
4141 if pair_state.selection_id == selection.id {
4142 enclosing = Some(pair_state);
4143 }
4144 i += 1;
4145 }
4146 }
4147
4148 (selection, enclosing)
4149 })
4150 }
4151
4152 /// Remove any autoclose regions that no longer contain their selection.
4153 fn invalidate_autoclose_regions(
4154 &mut self,
4155 mut selections: &[Selection<Anchor>],
4156 buffer: &MultiBufferSnapshot,
4157 ) {
4158 self.autoclose_regions.retain(|state| {
4159 let mut i = 0;
4160 while let Some(selection) = selections.get(i) {
4161 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4162 selections = &selections[1..];
4163 continue;
4164 }
4165 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4166 break;
4167 }
4168 if selection.id == state.selection_id {
4169 return true;
4170 } else {
4171 i += 1;
4172 }
4173 }
4174 false
4175 });
4176 }
4177
4178 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4179 let offset = position.to_offset(buffer);
4180 let (word_range, kind) = buffer.surrounding_word(offset, true);
4181 if offset > word_range.start && kind == Some(CharKind::Word) {
4182 Some(
4183 buffer
4184 .text_for_range(word_range.start..offset)
4185 .collect::<String>(),
4186 )
4187 } else {
4188 None
4189 }
4190 }
4191
4192 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4193 self.refresh_inlay_hints(
4194 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4195 cx,
4196 );
4197 }
4198
4199 pub fn inlay_hints_enabled(&self) -> bool {
4200 self.inlay_hint_cache.enabled
4201 }
4202
4203 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4204 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4205 return;
4206 }
4207
4208 let reason_description = reason.description();
4209 let ignore_debounce = matches!(
4210 reason,
4211 InlayHintRefreshReason::SettingsChange(_)
4212 | InlayHintRefreshReason::Toggle(_)
4213 | InlayHintRefreshReason::ExcerptsRemoved(_)
4214 );
4215 let (invalidate_cache, required_languages) = match reason {
4216 InlayHintRefreshReason::Toggle(enabled) => {
4217 self.inlay_hint_cache.enabled = enabled;
4218 if enabled {
4219 (InvalidationStrategy::RefreshRequested, None)
4220 } else {
4221 self.inlay_hint_cache.clear();
4222 self.splice_inlays(
4223 self.visible_inlay_hints(cx)
4224 .iter()
4225 .map(|inlay| inlay.id)
4226 .collect(),
4227 Vec::new(),
4228 cx,
4229 );
4230 return;
4231 }
4232 }
4233 InlayHintRefreshReason::SettingsChange(new_settings) => {
4234 match self.inlay_hint_cache.update_settings(
4235 &self.buffer,
4236 new_settings,
4237 self.visible_inlay_hints(cx),
4238 cx,
4239 ) {
4240 ControlFlow::Break(Some(InlaySplice {
4241 to_remove,
4242 to_insert,
4243 })) => {
4244 self.splice_inlays(to_remove, to_insert, cx);
4245 return;
4246 }
4247 ControlFlow::Break(None) => return,
4248 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4249 }
4250 }
4251 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4252 if let Some(InlaySplice {
4253 to_remove,
4254 to_insert,
4255 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4256 {
4257 self.splice_inlays(to_remove, to_insert, cx);
4258 }
4259 return;
4260 }
4261 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4262 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4263 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4264 }
4265 InlayHintRefreshReason::RefreshRequested => {
4266 (InvalidationStrategy::RefreshRequested, None)
4267 }
4268 };
4269
4270 if let Some(InlaySplice {
4271 to_remove,
4272 to_insert,
4273 }) = self.inlay_hint_cache.spawn_hint_refresh(
4274 reason_description,
4275 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4276 invalidate_cache,
4277 ignore_debounce,
4278 cx,
4279 ) {
4280 self.splice_inlays(to_remove, to_insert, cx);
4281 }
4282 }
4283
4284 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4285 self.display_map
4286 .read(cx)
4287 .current_inlays()
4288 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4289 .cloned()
4290 .collect()
4291 }
4292
4293 pub fn excerpts_for_inlay_hints_query(
4294 &self,
4295 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4296 cx: &mut ViewContext<Editor>,
4297 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4298 let Some(project) = self.project.as_ref() else {
4299 return HashMap::default();
4300 };
4301 let project = project.read(cx);
4302 let multi_buffer = self.buffer().read(cx);
4303 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4304 let multi_buffer_visible_start = self
4305 .scroll_manager
4306 .anchor()
4307 .anchor
4308 .to_point(&multi_buffer_snapshot);
4309 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4310 multi_buffer_visible_start
4311 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4312 Bias::Left,
4313 );
4314 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4315 multi_buffer
4316 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4317 .into_iter()
4318 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4319 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4320 let buffer = buffer_handle.read(cx);
4321 let buffer_file = project::File::from_dyn(buffer.file())?;
4322 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4323 let worktree_entry = buffer_worktree
4324 .read(cx)
4325 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4326 if worktree_entry.is_ignored {
4327 return None;
4328 }
4329
4330 let language = buffer.language()?;
4331 if let Some(restrict_to_languages) = restrict_to_languages {
4332 if !restrict_to_languages.contains(language) {
4333 return None;
4334 }
4335 }
4336 Some((
4337 excerpt_id,
4338 (
4339 buffer_handle,
4340 buffer.version().clone(),
4341 excerpt_visible_range,
4342 ),
4343 ))
4344 })
4345 .collect()
4346 }
4347
4348 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4349 TextLayoutDetails {
4350 text_system: cx.text_system().clone(),
4351 editor_style: self.style.clone().unwrap(),
4352 rem_size: cx.rem_size(),
4353 scroll_anchor: self.scroll_manager.anchor(),
4354 visible_rows: self.visible_line_count(),
4355 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4356 }
4357 }
4358
4359 fn splice_inlays(
4360 &self,
4361 to_remove: Vec<InlayId>,
4362 to_insert: Vec<Inlay>,
4363 cx: &mut ViewContext<Self>,
4364 ) {
4365 self.display_map.update(cx, |display_map, cx| {
4366 display_map.splice_inlays(to_remove, to_insert, cx);
4367 });
4368 cx.notify();
4369 }
4370
4371 fn trigger_on_type_formatting(
4372 &self,
4373 input: String,
4374 cx: &mut ViewContext<Self>,
4375 ) -> Option<Task<Result<()>>> {
4376 if input.len() != 1 {
4377 return None;
4378 }
4379
4380 let project = self.project.as_ref()?;
4381 let position = self.selections.newest_anchor().head();
4382 let (buffer, buffer_position) = self
4383 .buffer
4384 .read(cx)
4385 .text_anchor_for_position(position, cx)?;
4386
4387 let settings = language_settings::language_settings(
4388 buffer
4389 .read(cx)
4390 .language_at(buffer_position)
4391 .map(|l| l.name()),
4392 buffer.read(cx).file(),
4393 cx,
4394 );
4395 if !settings.use_on_type_format {
4396 return None;
4397 }
4398
4399 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4400 // hence we do LSP request & edit on host side only — add formats to host's history.
4401 let push_to_lsp_host_history = true;
4402 // If this is not the host, append its history with new edits.
4403 let push_to_client_history = project.read(cx).is_via_collab();
4404
4405 let on_type_formatting = project.update(cx, |project, cx| {
4406 project.on_type_format(
4407 buffer.clone(),
4408 buffer_position,
4409 input,
4410 push_to_lsp_host_history,
4411 cx,
4412 )
4413 });
4414 Some(cx.spawn(|editor, mut cx| async move {
4415 if let Some(transaction) = on_type_formatting.await? {
4416 if push_to_client_history {
4417 buffer
4418 .update(&mut cx, |buffer, _| {
4419 buffer.push_transaction(transaction, Instant::now());
4420 })
4421 .ok();
4422 }
4423 editor.update(&mut cx, |editor, cx| {
4424 editor.refresh_document_highlights(cx);
4425 })?;
4426 }
4427 Ok(())
4428 }))
4429 }
4430
4431 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4432 if self.pending_rename.is_some() {
4433 return;
4434 }
4435
4436 let Some(provider) = self.completion_provider.as_ref() else {
4437 return;
4438 };
4439
4440 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4441 return;
4442 }
4443
4444 let position = self.selections.newest_anchor().head();
4445 let (buffer, buffer_position) =
4446 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4447 output
4448 } else {
4449 return;
4450 };
4451
4452 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4453 let is_followup_invoke = {
4454 let context_menu_state = self.context_menu.read();
4455 matches!(
4456 context_menu_state.deref(),
4457 Some(ContextMenu::Completions(_))
4458 )
4459 };
4460 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4461 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4462 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4463 CompletionTriggerKind::TRIGGER_CHARACTER
4464 }
4465
4466 _ => CompletionTriggerKind::INVOKED,
4467 };
4468 let completion_context = CompletionContext {
4469 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4470 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4471 Some(String::from(trigger))
4472 } else {
4473 None
4474 }
4475 }),
4476 trigger_kind,
4477 };
4478 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4479 let sort_completions = provider.sort_completions();
4480
4481 let id = post_inc(&mut self.next_completion_id);
4482 let task = cx.spawn(|editor, mut cx| {
4483 async move {
4484 editor.update(&mut cx, |this, _| {
4485 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4486 })?;
4487 let completions = completions.await.log_err();
4488 let menu = if let Some(completions) = completions {
4489 let mut menu = CompletionsMenu::new(
4490 id,
4491 sort_completions,
4492 position,
4493 buffer.clone(),
4494 completions.into(),
4495 );
4496 menu.filter(query.as_deref(), cx.background_executor().clone())
4497 .await;
4498
4499 if menu.matches.is_empty() {
4500 None
4501 } else {
4502 Some(menu)
4503 }
4504 } else {
4505 None
4506 };
4507
4508 editor.update(&mut cx, |editor, cx| {
4509 let mut context_menu = editor.context_menu.write();
4510 match context_menu.as_ref() {
4511 None => {}
4512
4513 Some(ContextMenu::Completions(prev_menu)) => {
4514 if prev_menu.id > id {
4515 return;
4516 }
4517 }
4518
4519 _ => return,
4520 }
4521
4522 if editor.focus_handle.is_focused(cx) && menu.is_some() {
4523 let mut menu = menu.unwrap();
4524 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
4525 *context_menu = Some(ContextMenu::Completions(menu));
4526 drop(context_menu);
4527 editor.discard_inline_completion(false, cx);
4528 cx.notify();
4529 } else if editor.completion_tasks.len() <= 1 {
4530 // If there are no more completion tasks and the last menu was
4531 // empty, we should hide it. If it was already hidden, we should
4532 // also show the copilot completion when available.
4533 drop(context_menu);
4534 if editor.hide_context_menu(cx).is_none() {
4535 editor.update_visible_inline_completion(cx);
4536 }
4537 }
4538 })?;
4539
4540 Ok::<_, anyhow::Error>(())
4541 }
4542 .log_err()
4543 });
4544
4545 self.completion_tasks.push((id, task));
4546 }
4547
4548 pub fn confirm_completion(
4549 &mut self,
4550 action: &ConfirmCompletion,
4551 cx: &mut ViewContext<Self>,
4552 ) -> Option<Task<Result<()>>> {
4553 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4554 }
4555
4556 pub fn compose_completion(
4557 &mut self,
4558 action: &ComposeCompletion,
4559 cx: &mut ViewContext<Self>,
4560 ) -> Option<Task<Result<()>>> {
4561 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4562 }
4563
4564 fn do_completion(
4565 &mut self,
4566 item_ix: Option<usize>,
4567 intent: CompletionIntent,
4568 cx: &mut ViewContext<Editor>,
4569 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4570 use language::ToOffset as _;
4571
4572 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4573 menu
4574 } else {
4575 return None;
4576 };
4577
4578 let mat = completions_menu
4579 .matches
4580 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4581 let buffer_handle = completions_menu.buffer;
4582 let completions = completions_menu.completions.read();
4583 let completion = completions.get(mat.candidate_id)?;
4584 cx.stop_propagation();
4585
4586 let snippet;
4587 let text;
4588
4589 if completion.is_snippet() {
4590 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4591 text = snippet.as_ref().unwrap().text.clone();
4592 } else {
4593 snippet = None;
4594 text = completion.new_text.clone();
4595 };
4596 let selections = self.selections.all::<usize>(cx);
4597 let buffer = buffer_handle.read(cx);
4598 let old_range = completion.old_range.to_offset(buffer);
4599 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4600
4601 let newest_selection = self.selections.newest_anchor();
4602 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4603 return None;
4604 }
4605
4606 let lookbehind = newest_selection
4607 .start
4608 .text_anchor
4609 .to_offset(buffer)
4610 .saturating_sub(old_range.start);
4611 let lookahead = old_range
4612 .end
4613 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4614 let mut common_prefix_len = old_text
4615 .bytes()
4616 .zip(text.bytes())
4617 .take_while(|(a, b)| a == b)
4618 .count();
4619
4620 let snapshot = self.buffer.read(cx).snapshot(cx);
4621 let mut range_to_replace: Option<Range<isize>> = None;
4622 let mut ranges = Vec::new();
4623 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4624 for selection in &selections {
4625 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4626 let start = selection.start.saturating_sub(lookbehind);
4627 let end = selection.end + lookahead;
4628 if selection.id == newest_selection.id {
4629 range_to_replace = Some(
4630 ((start + common_prefix_len) as isize - selection.start as isize)
4631 ..(end as isize - selection.start as isize),
4632 );
4633 }
4634 ranges.push(start + common_prefix_len..end);
4635 } else {
4636 common_prefix_len = 0;
4637 ranges.clear();
4638 ranges.extend(selections.iter().map(|s| {
4639 if s.id == newest_selection.id {
4640 range_to_replace = Some(
4641 old_range.start.to_offset_utf16(&snapshot).0 as isize
4642 - selection.start as isize
4643 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4644 - selection.start as isize,
4645 );
4646 old_range.clone()
4647 } else {
4648 s.start..s.end
4649 }
4650 }));
4651 break;
4652 }
4653 if !self.linked_edit_ranges.is_empty() {
4654 let start_anchor = snapshot.anchor_before(selection.head());
4655 let end_anchor = snapshot.anchor_after(selection.tail());
4656 if let Some(ranges) = self
4657 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4658 {
4659 for (buffer, edits) in ranges {
4660 linked_edits.entry(buffer.clone()).or_default().extend(
4661 edits
4662 .into_iter()
4663 .map(|range| (range, text[common_prefix_len..].to_owned())),
4664 );
4665 }
4666 }
4667 }
4668 }
4669 let text = &text[common_prefix_len..];
4670
4671 cx.emit(EditorEvent::InputHandled {
4672 utf16_range_to_replace: range_to_replace,
4673 text: text.into(),
4674 });
4675
4676 self.transact(cx, |this, cx| {
4677 if let Some(mut snippet) = snippet {
4678 snippet.text = text.to_string();
4679 for tabstop in snippet
4680 .tabstops
4681 .iter_mut()
4682 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4683 {
4684 tabstop.start -= common_prefix_len as isize;
4685 tabstop.end -= common_prefix_len as isize;
4686 }
4687
4688 this.insert_snippet(&ranges, snippet, cx).log_err();
4689 } else {
4690 this.buffer.update(cx, |buffer, cx| {
4691 buffer.edit(
4692 ranges.iter().map(|range| (range.clone(), text)),
4693 this.autoindent_mode.clone(),
4694 cx,
4695 );
4696 });
4697 }
4698 for (buffer, edits) in linked_edits {
4699 buffer.update(cx, |buffer, cx| {
4700 let snapshot = buffer.snapshot();
4701 let edits = edits
4702 .into_iter()
4703 .map(|(range, text)| {
4704 use text::ToPoint as TP;
4705 let end_point = TP::to_point(&range.end, &snapshot);
4706 let start_point = TP::to_point(&range.start, &snapshot);
4707 (start_point..end_point, text)
4708 })
4709 .sorted_by_key(|(range, _)| range.start)
4710 .collect::<Vec<_>>();
4711 buffer.edit(edits, None, cx);
4712 })
4713 }
4714
4715 this.refresh_inline_completion(true, false, cx);
4716 });
4717
4718 let show_new_completions_on_confirm = completion
4719 .confirm
4720 .as_ref()
4721 .map_or(false, |confirm| confirm(intent, cx));
4722 if show_new_completions_on_confirm {
4723 self.show_completions(&ShowCompletions { trigger: None }, cx);
4724 }
4725
4726 let provider = self.completion_provider.as_ref()?;
4727 let apply_edits = provider.apply_additional_edits_for_completion(
4728 buffer_handle,
4729 completion.clone(),
4730 true,
4731 cx,
4732 );
4733
4734 let editor_settings = EditorSettings::get_global(cx);
4735 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4736 // After the code completion is finished, users often want to know what signatures are needed.
4737 // so we should automatically call signature_help
4738 self.show_signature_help(&ShowSignatureHelp, cx);
4739 }
4740
4741 Some(cx.foreground_executor().spawn(async move {
4742 apply_edits.await?;
4743 Ok(())
4744 }))
4745 }
4746
4747 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4748 let mut context_menu = self.context_menu.write();
4749 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4750 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4751 // Toggle if we're selecting the same one
4752 *context_menu = None;
4753 cx.notify();
4754 return;
4755 } else {
4756 // Otherwise, clear it and start a new one
4757 *context_menu = None;
4758 cx.notify();
4759 }
4760 }
4761 drop(context_menu);
4762 let snapshot = self.snapshot(cx);
4763 let deployed_from_indicator = action.deployed_from_indicator;
4764 let mut task = self.code_actions_task.take();
4765 let action = action.clone();
4766 cx.spawn(|editor, mut cx| async move {
4767 while let Some(prev_task) = task {
4768 prev_task.await.log_err();
4769 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4770 }
4771
4772 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4773 if editor.focus_handle.is_focused(cx) {
4774 let multibuffer_point = action
4775 .deployed_from_indicator
4776 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4777 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4778 let (buffer, buffer_row) = snapshot
4779 .buffer_snapshot
4780 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4781 .and_then(|(buffer_snapshot, range)| {
4782 editor
4783 .buffer
4784 .read(cx)
4785 .buffer(buffer_snapshot.remote_id())
4786 .map(|buffer| (buffer, range.start.row))
4787 })?;
4788 let (_, code_actions) = editor
4789 .available_code_actions
4790 .clone()
4791 .and_then(|(location, code_actions)| {
4792 let snapshot = location.buffer.read(cx).snapshot();
4793 let point_range = location.range.to_point(&snapshot);
4794 let point_range = point_range.start.row..=point_range.end.row;
4795 if point_range.contains(&buffer_row) {
4796 Some((location, code_actions))
4797 } else {
4798 None
4799 }
4800 })
4801 .unzip();
4802 let buffer_id = buffer.read(cx).remote_id();
4803 let tasks = editor
4804 .tasks
4805 .get(&(buffer_id, buffer_row))
4806 .map(|t| Arc::new(t.to_owned()));
4807 if tasks.is_none() && code_actions.is_none() {
4808 return None;
4809 }
4810
4811 editor.completion_tasks.clear();
4812 editor.discard_inline_completion(false, cx);
4813 let task_context =
4814 tasks
4815 .as_ref()
4816 .zip(editor.project.clone())
4817 .map(|(tasks, project)| {
4818 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4819 });
4820
4821 Some(cx.spawn(|editor, mut cx| async move {
4822 let task_context = match task_context {
4823 Some(task_context) => task_context.await,
4824 None => None,
4825 };
4826 let resolved_tasks =
4827 tasks.zip(task_context).map(|(tasks, task_context)| {
4828 Arc::new(ResolvedTasks {
4829 templates: tasks.resolve(&task_context).collect(),
4830 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4831 multibuffer_point.row,
4832 tasks.column,
4833 )),
4834 })
4835 });
4836 let spawn_straight_away = resolved_tasks
4837 .as_ref()
4838 .map_or(false, |tasks| tasks.templates.len() == 1)
4839 && code_actions
4840 .as_ref()
4841 .map_or(true, |actions| actions.is_empty());
4842 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4843 *editor.context_menu.write() =
4844 Some(ContextMenu::CodeActions(CodeActionsMenu {
4845 buffer,
4846 actions: CodeActionContents {
4847 tasks: resolved_tasks,
4848 actions: code_actions,
4849 },
4850 selected_item: Default::default(),
4851 scroll_handle: UniformListScrollHandle::default(),
4852 deployed_from_indicator,
4853 }));
4854 if spawn_straight_away {
4855 if let Some(task) = editor.confirm_code_action(
4856 &ConfirmCodeAction { item_ix: Some(0) },
4857 cx,
4858 ) {
4859 cx.notify();
4860 return task;
4861 }
4862 }
4863 cx.notify();
4864 Task::ready(Ok(()))
4865 }) {
4866 task.await
4867 } else {
4868 Ok(())
4869 }
4870 }))
4871 } else {
4872 Some(Task::ready(Ok(())))
4873 }
4874 })?;
4875 if let Some(task) = spawned_test_task {
4876 task.await?;
4877 }
4878
4879 Ok::<_, anyhow::Error>(())
4880 })
4881 .detach_and_log_err(cx);
4882 }
4883
4884 pub fn confirm_code_action(
4885 &mut self,
4886 action: &ConfirmCodeAction,
4887 cx: &mut ViewContext<Self>,
4888 ) -> Option<Task<Result<()>>> {
4889 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4890 menu
4891 } else {
4892 return None;
4893 };
4894 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4895 let action = actions_menu.actions.get(action_ix)?;
4896 let title = action.label();
4897 let buffer = actions_menu.buffer;
4898 let workspace = self.workspace()?;
4899
4900 match action {
4901 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4902 workspace.update(cx, |workspace, cx| {
4903 workspace::tasks::schedule_resolved_task(
4904 workspace,
4905 task_source_kind,
4906 resolved_task,
4907 false,
4908 cx,
4909 );
4910
4911 Some(Task::ready(Ok(())))
4912 })
4913 }
4914 CodeActionsItem::CodeAction {
4915 excerpt_id,
4916 action,
4917 provider,
4918 } => {
4919 let apply_code_action =
4920 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4921 let workspace = workspace.downgrade();
4922 Some(cx.spawn(|editor, cx| async move {
4923 let project_transaction = apply_code_action.await?;
4924 Self::open_project_transaction(
4925 &editor,
4926 workspace,
4927 project_transaction,
4928 title,
4929 cx,
4930 )
4931 .await
4932 }))
4933 }
4934 }
4935 }
4936
4937 pub async fn open_project_transaction(
4938 this: &WeakView<Editor>,
4939 workspace: WeakView<Workspace>,
4940 transaction: ProjectTransaction,
4941 title: String,
4942 mut cx: AsyncWindowContext,
4943 ) -> Result<()> {
4944 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4945 cx.update(|cx| {
4946 entries.sort_unstable_by_key(|(buffer, _)| {
4947 buffer.read(cx).file().map(|f| f.path().clone())
4948 });
4949 })?;
4950
4951 // If the project transaction's edits are all contained within this editor, then
4952 // avoid opening a new editor to display them.
4953
4954 if let Some((buffer, transaction)) = entries.first() {
4955 if entries.len() == 1 {
4956 let excerpt = this.update(&mut cx, |editor, cx| {
4957 editor
4958 .buffer()
4959 .read(cx)
4960 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4961 })?;
4962 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4963 if excerpted_buffer == *buffer {
4964 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4965 let excerpt_range = excerpt_range.to_offset(buffer);
4966 buffer
4967 .edited_ranges_for_transaction::<usize>(transaction)
4968 .all(|range| {
4969 excerpt_range.start <= range.start
4970 && excerpt_range.end >= range.end
4971 })
4972 })?;
4973
4974 if all_edits_within_excerpt {
4975 return Ok(());
4976 }
4977 }
4978 }
4979 }
4980 } else {
4981 return Ok(());
4982 }
4983
4984 let mut ranges_to_highlight = Vec::new();
4985 let excerpt_buffer = cx.new_model(|cx| {
4986 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4987 for (buffer_handle, transaction) in &entries {
4988 let buffer = buffer_handle.read(cx);
4989 ranges_to_highlight.extend(
4990 multibuffer.push_excerpts_with_context_lines(
4991 buffer_handle.clone(),
4992 buffer
4993 .edited_ranges_for_transaction::<usize>(transaction)
4994 .collect(),
4995 DEFAULT_MULTIBUFFER_CONTEXT,
4996 cx,
4997 ),
4998 );
4999 }
5000 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5001 multibuffer
5002 })?;
5003
5004 workspace.update(&mut cx, |workspace, cx| {
5005 let project = workspace.project().clone();
5006 let editor =
5007 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5008 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5009 editor.update(cx, |editor, cx| {
5010 editor.highlight_background::<Self>(
5011 &ranges_to_highlight,
5012 |theme| theme.editor_highlighted_line_background,
5013 cx,
5014 );
5015 });
5016 })?;
5017
5018 Ok(())
5019 }
5020
5021 pub fn clear_code_action_providers(&mut self) {
5022 self.code_action_providers.clear();
5023 self.available_code_actions.take();
5024 }
5025
5026 pub fn push_code_action_provider(
5027 &mut self,
5028 provider: Arc<dyn CodeActionProvider>,
5029 cx: &mut ViewContext<Self>,
5030 ) {
5031 self.code_action_providers.push(provider);
5032 self.refresh_code_actions(cx);
5033 }
5034
5035 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5036 let buffer = self.buffer.read(cx);
5037 let newest_selection = self.selections.newest_anchor().clone();
5038 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5039 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5040 if start_buffer != end_buffer {
5041 return None;
5042 }
5043
5044 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5045 cx.background_executor()
5046 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5047 .await;
5048
5049 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5050 let providers = this.code_action_providers.clone();
5051 let tasks = this
5052 .code_action_providers
5053 .iter()
5054 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5055 .collect::<Vec<_>>();
5056 (providers, tasks)
5057 })?;
5058
5059 let mut actions = Vec::new();
5060 for (provider, provider_actions) in
5061 providers.into_iter().zip(future::join_all(tasks).await)
5062 {
5063 if let Some(provider_actions) = provider_actions.log_err() {
5064 actions.extend(provider_actions.into_iter().map(|action| {
5065 AvailableCodeAction {
5066 excerpt_id: newest_selection.start.excerpt_id,
5067 action,
5068 provider: provider.clone(),
5069 }
5070 }));
5071 }
5072 }
5073
5074 this.update(&mut cx, |this, cx| {
5075 this.available_code_actions = if actions.is_empty() {
5076 None
5077 } else {
5078 Some((
5079 Location {
5080 buffer: start_buffer,
5081 range: start..end,
5082 },
5083 actions.into(),
5084 ))
5085 };
5086 cx.notify();
5087 })
5088 }));
5089 None
5090 }
5091
5092 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5093 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5094 self.show_git_blame_inline = false;
5095
5096 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5097 cx.background_executor().timer(delay).await;
5098
5099 this.update(&mut cx, |this, cx| {
5100 this.show_git_blame_inline = true;
5101 cx.notify();
5102 })
5103 .log_err();
5104 }));
5105 }
5106 }
5107
5108 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5109 if self.pending_rename.is_some() {
5110 return None;
5111 }
5112
5113 let provider = self.semantics_provider.clone()?;
5114 let buffer = self.buffer.read(cx);
5115 let newest_selection = self.selections.newest_anchor().clone();
5116 let cursor_position = newest_selection.head();
5117 let (cursor_buffer, cursor_buffer_position) =
5118 buffer.text_anchor_for_position(cursor_position, cx)?;
5119 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5120 if cursor_buffer != tail_buffer {
5121 return None;
5122 }
5123
5124 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5125 cx.background_executor()
5126 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5127 .await;
5128
5129 let highlights = if let Some(highlights) = cx
5130 .update(|cx| {
5131 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5132 })
5133 .ok()
5134 .flatten()
5135 {
5136 highlights.await.log_err()
5137 } else {
5138 None
5139 };
5140
5141 if let Some(highlights) = highlights {
5142 this.update(&mut cx, |this, cx| {
5143 if this.pending_rename.is_some() {
5144 return;
5145 }
5146
5147 let buffer_id = cursor_position.buffer_id;
5148 let buffer = this.buffer.read(cx);
5149 if !buffer
5150 .text_anchor_for_position(cursor_position, cx)
5151 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5152 {
5153 return;
5154 }
5155
5156 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5157 let mut write_ranges = Vec::new();
5158 let mut read_ranges = Vec::new();
5159 for highlight in highlights {
5160 for (excerpt_id, excerpt_range) in
5161 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5162 {
5163 let start = highlight
5164 .range
5165 .start
5166 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5167 let end = highlight
5168 .range
5169 .end
5170 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5171 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5172 continue;
5173 }
5174
5175 let range = Anchor {
5176 buffer_id,
5177 excerpt_id,
5178 text_anchor: start,
5179 }..Anchor {
5180 buffer_id,
5181 excerpt_id,
5182 text_anchor: end,
5183 };
5184 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5185 write_ranges.push(range);
5186 } else {
5187 read_ranges.push(range);
5188 }
5189 }
5190 }
5191
5192 this.highlight_background::<DocumentHighlightRead>(
5193 &read_ranges,
5194 |theme| theme.editor_document_highlight_read_background,
5195 cx,
5196 );
5197 this.highlight_background::<DocumentHighlightWrite>(
5198 &write_ranges,
5199 |theme| theme.editor_document_highlight_write_background,
5200 cx,
5201 );
5202 cx.notify();
5203 })
5204 .log_err();
5205 }
5206 }));
5207 None
5208 }
5209
5210 pub fn refresh_inline_completion(
5211 &mut self,
5212 debounce: bool,
5213 user_requested: bool,
5214 cx: &mut ViewContext<Self>,
5215 ) -> Option<()> {
5216 let provider = self.inline_completion_provider()?;
5217 let cursor = self.selections.newest_anchor().head();
5218 let (buffer, cursor_buffer_position) =
5219 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5220
5221 if !user_requested
5222 && (!self.enable_inline_completions
5223 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5224 {
5225 self.discard_inline_completion(false, cx);
5226 return None;
5227 }
5228
5229 self.update_visible_inline_completion(cx);
5230 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5231 Some(())
5232 }
5233
5234 fn cycle_inline_completion(
5235 &mut self,
5236 direction: Direction,
5237 cx: &mut ViewContext<Self>,
5238 ) -> Option<()> {
5239 let provider = self.inline_completion_provider()?;
5240 let cursor = self.selections.newest_anchor().head();
5241 let (buffer, cursor_buffer_position) =
5242 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5243 if !self.enable_inline_completions
5244 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5245 {
5246 return None;
5247 }
5248
5249 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5250 self.update_visible_inline_completion(cx);
5251
5252 Some(())
5253 }
5254
5255 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5256 if !self.has_active_inline_completion(cx) {
5257 self.refresh_inline_completion(false, true, cx);
5258 return;
5259 }
5260
5261 self.update_visible_inline_completion(cx);
5262 }
5263
5264 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5265 self.show_cursor_names(cx);
5266 }
5267
5268 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5269 self.show_cursor_names = true;
5270 cx.notify();
5271 cx.spawn(|this, mut cx| async move {
5272 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5273 this.update(&mut cx, |this, cx| {
5274 this.show_cursor_names = false;
5275 cx.notify()
5276 })
5277 .ok()
5278 })
5279 .detach();
5280 }
5281
5282 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5283 if self.has_active_inline_completion(cx) {
5284 self.cycle_inline_completion(Direction::Next, cx);
5285 } else {
5286 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5287 if is_copilot_disabled {
5288 cx.propagate();
5289 }
5290 }
5291 }
5292
5293 pub fn previous_inline_completion(
5294 &mut self,
5295 _: &PreviousInlineCompletion,
5296 cx: &mut ViewContext<Self>,
5297 ) {
5298 if self.has_active_inline_completion(cx) {
5299 self.cycle_inline_completion(Direction::Prev, cx);
5300 } else {
5301 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5302 if is_copilot_disabled {
5303 cx.propagate();
5304 }
5305 }
5306 }
5307
5308 pub fn accept_inline_completion(
5309 &mut self,
5310 _: &AcceptInlineCompletion,
5311 cx: &mut ViewContext<Self>,
5312 ) {
5313 let Some(completion) = self.take_active_inline_completion(cx) else {
5314 return;
5315 };
5316 if let Some(provider) = self.inline_completion_provider() {
5317 provider.accept(cx);
5318 }
5319
5320 cx.emit(EditorEvent::InputHandled {
5321 utf16_range_to_replace: None,
5322 text: completion.text.to_string().into(),
5323 });
5324
5325 if let Some(range) = completion.delete_range {
5326 self.change_selections(None, cx, |s| s.select_ranges([range]))
5327 }
5328 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5329 self.refresh_inline_completion(true, true, cx);
5330 cx.notify();
5331 }
5332
5333 pub fn accept_partial_inline_completion(
5334 &mut self,
5335 _: &AcceptPartialInlineCompletion,
5336 cx: &mut ViewContext<Self>,
5337 ) {
5338 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5339 if let Some(completion) = self.take_active_inline_completion(cx) {
5340 let mut partial_completion = completion
5341 .text
5342 .chars()
5343 .by_ref()
5344 .take_while(|c| c.is_alphabetic())
5345 .collect::<String>();
5346 if partial_completion.is_empty() {
5347 partial_completion = completion
5348 .text
5349 .chars()
5350 .by_ref()
5351 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5352 .collect::<String>();
5353 }
5354
5355 cx.emit(EditorEvent::InputHandled {
5356 utf16_range_to_replace: None,
5357 text: partial_completion.clone().into(),
5358 });
5359
5360 if let Some(range) = completion.delete_range {
5361 self.change_selections(None, cx, |s| s.select_ranges([range]))
5362 }
5363 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5364
5365 self.refresh_inline_completion(true, true, cx);
5366 cx.notify();
5367 }
5368 }
5369 }
5370
5371 fn discard_inline_completion(
5372 &mut self,
5373 should_report_inline_completion_event: bool,
5374 cx: &mut ViewContext<Self>,
5375 ) -> bool {
5376 if let Some(provider) = self.inline_completion_provider() {
5377 provider.discard(should_report_inline_completion_event, cx);
5378 }
5379
5380 self.take_active_inline_completion(cx).is_some()
5381 }
5382
5383 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5384 if let Some(completion) = self.active_inline_completion.as_ref() {
5385 let buffer = self.buffer.read(cx).read(cx);
5386 completion.position.is_valid(&buffer)
5387 } else {
5388 false
5389 }
5390 }
5391
5392 fn take_active_inline_completion(
5393 &mut self,
5394 cx: &mut ViewContext<Self>,
5395 ) -> Option<CompletionState> {
5396 let completion = self.active_inline_completion.take()?;
5397 let render_inlay_ids = completion.render_inlay_ids.clone();
5398 self.display_map.update(cx, |map, cx| {
5399 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5400 });
5401 let buffer = self.buffer.read(cx).read(cx);
5402
5403 if completion.position.is_valid(&buffer) {
5404 Some(completion)
5405 } else {
5406 None
5407 }
5408 }
5409
5410 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5411 let selection = self.selections.newest_anchor();
5412 let cursor = selection.head();
5413
5414 let excerpt_id = cursor.excerpt_id;
5415
5416 if self.context_menu.read().is_none()
5417 && self.completion_tasks.is_empty()
5418 && selection.start == selection.end
5419 {
5420 if let Some(provider) = self.inline_completion_provider() {
5421 if let Some((buffer, cursor_buffer_position)) =
5422 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5423 {
5424 if let Some(proposal) =
5425 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5426 {
5427 let mut to_remove = Vec::new();
5428 if let Some(completion) = self.active_inline_completion.take() {
5429 to_remove.extend(completion.render_inlay_ids.iter());
5430 }
5431
5432 let to_add = proposal
5433 .inlays
5434 .iter()
5435 .filter_map(|inlay| {
5436 let snapshot = self.buffer.read(cx).snapshot(cx);
5437 let id = post_inc(&mut self.next_inlay_id);
5438 match inlay {
5439 InlayProposal::Hint(position, hint) => {
5440 let position =
5441 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5442 Some(Inlay::hint(id, position, hint))
5443 }
5444 InlayProposal::Suggestion(position, text) => {
5445 let position =
5446 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5447 Some(Inlay::suggestion(id, position, text.clone()))
5448 }
5449 }
5450 })
5451 .collect_vec();
5452
5453 self.active_inline_completion = Some(CompletionState {
5454 position: cursor,
5455 text: proposal.text,
5456 delete_range: proposal.delete_range.and_then(|range| {
5457 let snapshot = self.buffer.read(cx).snapshot(cx);
5458 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5459 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5460 Some(start?..end?)
5461 }),
5462 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5463 });
5464
5465 self.display_map
5466 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5467
5468 cx.notify();
5469 return;
5470 }
5471 }
5472 }
5473 }
5474
5475 self.discard_inline_completion(false, cx);
5476 }
5477
5478 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5479 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5480 }
5481
5482 fn render_code_actions_indicator(
5483 &self,
5484 _style: &EditorStyle,
5485 row: DisplayRow,
5486 is_active: bool,
5487 cx: &mut ViewContext<Self>,
5488 ) -> Option<IconButton> {
5489 if self.available_code_actions.is_some() {
5490 Some(
5491 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5492 .shape(ui::IconButtonShape::Square)
5493 .icon_size(IconSize::XSmall)
5494 .icon_color(Color::Muted)
5495 .selected(is_active)
5496 .tooltip({
5497 let focus_handle = self.focus_handle.clone();
5498 move |cx| {
5499 Tooltip::for_action_in(
5500 "Toggle Code Actions",
5501 &ToggleCodeActions {
5502 deployed_from_indicator: None,
5503 },
5504 &focus_handle,
5505 cx,
5506 )
5507 }
5508 })
5509 .on_click(cx.listener(move |editor, _e, cx| {
5510 editor.focus(cx);
5511 editor.toggle_code_actions(
5512 &ToggleCodeActions {
5513 deployed_from_indicator: Some(row),
5514 },
5515 cx,
5516 );
5517 })),
5518 )
5519 } else {
5520 None
5521 }
5522 }
5523
5524 fn clear_tasks(&mut self) {
5525 self.tasks.clear()
5526 }
5527
5528 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5529 if self.tasks.insert(key, value).is_some() {
5530 // This case should hopefully be rare, but just in case...
5531 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5532 }
5533 }
5534
5535 fn build_tasks_context(
5536 project: &Model<Project>,
5537 buffer: &Model<Buffer>,
5538 buffer_row: u32,
5539 tasks: &Arc<RunnableTasks>,
5540 cx: &mut ViewContext<Self>,
5541 ) -> Task<Option<task::TaskContext>> {
5542 let position = Point::new(buffer_row, tasks.column);
5543 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5544 let location = Location {
5545 buffer: buffer.clone(),
5546 range: range_start..range_start,
5547 };
5548 // Fill in the environmental variables from the tree-sitter captures
5549 let mut captured_task_variables = TaskVariables::default();
5550 for (capture_name, value) in tasks.extra_variables.clone() {
5551 captured_task_variables.insert(
5552 task::VariableName::Custom(capture_name.into()),
5553 value.clone(),
5554 );
5555 }
5556 project.update(cx, |project, cx| {
5557 project.task_store().update(cx, |task_store, cx| {
5558 task_store.task_context_for_location(captured_task_variables, location, cx)
5559 })
5560 })
5561 }
5562
5563 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5564 let Some((workspace, _)) = self.workspace.clone() else {
5565 return;
5566 };
5567 let Some(project) = self.project.clone() else {
5568 return;
5569 };
5570
5571 // Try to find a closest, enclosing node using tree-sitter that has a
5572 // task
5573 let Some((buffer, buffer_row, tasks)) = self
5574 .find_enclosing_node_task(cx)
5575 // Or find the task that's closest in row-distance.
5576 .or_else(|| self.find_closest_task(cx))
5577 else {
5578 return;
5579 };
5580
5581 let reveal_strategy = action.reveal;
5582 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5583 cx.spawn(|_, mut cx| async move {
5584 let context = task_context.await?;
5585 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5586
5587 let resolved = resolved_task.resolved.as_mut()?;
5588 resolved.reveal = reveal_strategy;
5589
5590 workspace
5591 .update(&mut cx, |workspace, cx| {
5592 workspace::tasks::schedule_resolved_task(
5593 workspace,
5594 task_source_kind,
5595 resolved_task,
5596 false,
5597 cx,
5598 );
5599 })
5600 .ok()
5601 })
5602 .detach();
5603 }
5604
5605 fn find_closest_task(
5606 &mut self,
5607 cx: &mut ViewContext<Self>,
5608 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5609 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5610
5611 let ((buffer_id, row), tasks) = self
5612 .tasks
5613 .iter()
5614 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5615
5616 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5617 let tasks = Arc::new(tasks.to_owned());
5618 Some((buffer, *row, tasks))
5619 }
5620
5621 fn find_enclosing_node_task(
5622 &mut self,
5623 cx: &mut ViewContext<Self>,
5624 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5625 let snapshot = self.buffer.read(cx).snapshot(cx);
5626 let offset = self.selections.newest::<usize>(cx).head();
5627 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5628 let buffer_id = excerpt.buffer().remote_id();
5629
5630 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5631 let mut cursor = layer.node().walk();
5632
5633 while cursor.goto_first_child_for_byte(offset).is_some() {
5634 if cursor.node().end_byte() == offset {
5635 cursor.goto_next_sibling();
5636 }
5637 }
5638
5639 // Ascend to the smallest ancestor that contains the range and has a task.
5640 loop {
5641 let node = cursor.node();
5642 let node_range = node.byte_range();
5643 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5644
5645 // Check if this node contains our offset
5646 if node_range.start <= offset && node_range.end >= offset {
5647 // If it contains offset, check for task
5648 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5649 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5650 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5651 }
5652 }
5653
5654 if !cursor.goto_parent() {
5655 break;
5656 }
5657 }
5658 None
5659 }
5660
5661 fn render_run_indicator(
5662 &self,
5663 _style: &EditorStyle,
5664 is_active: bool,
5665 row: DisplayRow,
5666 cx: &mut ViewContext<Self>,
5667 ) -> IconButton {
5668 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5669 .shape(ui::IconButtonShape::Square)
5670 .icon_size(IconSize::XSmall)
5671 .icon_color(Color::Muted)
5672 .selected(is_active)
5673 .on_click(cx.listener(move |editor, _e, cx| {
5674 editor.focus(cx);
5675 editor.toggle_code_actions(
5676 &ToggleCodeActions {
5677 deployed_from_indicator: Some(row),
5678 },
5679 cx,
5680 );
5681 }))
5682 }
5683
5684 pub fn context_menu_visible(&self) -> bool {
5685 self.context_menu
5686 .read()
5687 .as_ref()
5688 .map_or(false, |menu| menu.visible())
5689 }
5690
5691 fn render_context_menu(
5692 &self,
5693 cursor_position: DisplayPoint,
5694 style: &EditorStyle,
5695 max_height: Pixels,
5696 cx: &mut ViewContext<Editor>,
5697 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5698 self.context_menu.read().as_ref().map(|menu| {
5699 menu.render(
5700 cursor_position,
5701 style,
5702 max_height,
5703 self.workspace.as_ref().map(|(w, _)| w.clone()),
5704 cx,
5705 )
5706 })
5707 }
5708
5709 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5710 cx.notify();
5711 self.completion_tasks.clear();
5712 let context_menu = self.context_menu.write().take();
5713 if context_menu.is_some() {
5714 self.update_visible_inline_completion(cx);
5715 }
5716 context_menu
5717 }
5718
5719 fn show_snippet_choices(
5720 &mut self,
5721 choices: &Vec<String>,
5722 selection: Range<Anchor>,
5723 cx: &mut ViewContext<Self>,
5724 ) {
5725 if selection.start.buffer_id.is_none() {
5726 return;
5727 }
5728 let buffer_id = selection.start.buffer_id.unwrap();
5729 let buffer = self.buffer().read(cx).buffer(buffer_id);
5730 let id = post_inc(&mut self.next_completion_id);
5731
5732 if let Some(buffer) = buffer {
5733 *self.context_menu.write() = Some(ContextMenu::Completions(
5734 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5735 .suppress_documentation_resolution(),
5736 ));
5737 }
5738 }
5739
5740 pub fn insert_snippet(
5741 &mut self,
5742 insertion_ranges: &[Range<usize>],
5743 snippet: Snippet,
5744 cx: &mut ViewContext<Self>,
5745 ) -> Result<()> {
5746 struct Tabstop<T> {
5747 is_end_tabstop: bool,
5748 ranges: Vec<Range<T>>,
5749 choices: Option<Vec<String>>,
5750 }
5751
5752 let tabstops = self.buffer.update(cx, |buffer, cx| {
5753 let snippet_text: Arc<str> = snippet.text.clone().into();
5754 buffer.edit(
5755 insertion_ranges
5756 .iter()
5757 .cloned()
5758 .map(|range| (range, snippet_text.clone())),
5759 Some(AutoindentMode::EachLine),
5760 cx,
5761 );
5762
5763 let snapshot = &*buffer.read(cx);
5764 let snippet = &snippet;
5765 snippet
5766 .tabstops
5767 .iter()
5768 .map(|tabstop| {
5769 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5770 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5771 });
5772 let mut tabstop_ranges = tabstop
5773 .ranges
5774 .iter()
5775 .flat_map(|tabstop_range| {
5776 let mut delta = 0_isize;
5777 insertion_ranges.iter().map(move |insertion_range| {
5778 let insertion_start = insertion_range.start as isize + delta;
5779 delta +=
5780 snippet.text.len() as isize - insertion_range.len() as isize;
5781
5782 let start = ((insertion_start + tabstop_range.start) as usize)
5783 .min(snapshot.len());
5784 let end = ((insertion_start + tabstop_range.end) as usize)
5785 .min(snapshot.len());
5786 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5787 })
5788 })
5789 .collect::<Vec<_>>();
5790 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5791
5792 Tabstop {
5793 is_end_tabstop,
5794 ranges: tabstop_ranges,
5795 choices: tabstop.choices.clone(),
5796 }
5797 })
5798 .collect::<Vec<_>>()
5799 });
5800 if let Some(tabstop) = tabstops.first() {
5801 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5802 s.select_ranges(tabstop.ranges.iter().cloned());
5803 });
5804
5805 if let Some(choices) = &tabstop.choices {
5806 if let Some(selection) = tabstop.ranges.first() {
5807 self.show_snippet_choices(choices, selection.clone(), cx)
5808 }
5809 }
5810
5811 // If we're already at the last tabstop and it's at the end of the snippet,
5812 // we're done, we don't need to keep the state around.
5813 if !tabstop.is_end_tabstop {
5814 let choices = tabstops
5815 .iter()
5816 .map(|tabstop| tabstop.choices.clone())
5817 .collect();
5818
5819 let ranges = tabstops
5820 .into_iter()
5821 .map(|tabstop| tabstop.ranges)
5822 .collect::<Vec<_>>();
5823
5824 self.snippet_stack.push(SnippetState {
5825 active_index: 0,
5826 ranges,
5827 choices,
5828 });
5829 }
5830
5831 // Check whether the just-entered snippet ends with an auto-closable bracket.
5832 if self.autoclose_regions.is_empty() {
5833 let snapshot = self.buffer.read(cx).snapshot(cx);
5834 for selection in &mut self.selections.all::<Point>(cx) {
5835 let selection_head = selection.head();
5836 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5837 continue;
5838 };
5839
5840 let mut bracket_pair = None;
5841 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5842 let prev_chars = snapshot
5843 .reversed_chars_at(selection_head)
5844 .collect::<String>();
5845 for (pair, enabled) in scope.brackets() {
5846 if enabled
5847 && pair.close
5848 && prev_chars.starts_with(pair.start.as_str())
5849 && next_chars.starts_with(pair.end.as_str())
5850 {
5851 bracket_pair = Some(pair.clone());
5852 break;
5853 }
5854 }
5855 if let Some(pair) = bracket_pair {
5856 let start = snapshot.anchor_after(selection_head);
5857 let end = snapshot.anchor_after(selection_head);
5858 self.autoclose_regions.push(AutocloseRegion {
5859 selection_id: selection.id,
5860 range: start..end,
5861 pair,
5862 });
5863 }
5864 }
5865 }
5866 }
5867 Ok(())
5868 }
5869
5870 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5871 self.move_to_snippet_tabstop(Bias::Right, cx)
5872 }
5873
5874 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5875 self.move_to_snippet_tabstop(Bias::Left, cx)
5876 }
5877
5878 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5879 if let Some(mut snippet) = self.snippet_stack.pop() {
5880 match bias {
5881 Bias::Left => {
5882 if snippet.active_index > 0 {
5883 snippet.active_index -= 1;
5884 } else {
5885 self.snippet_stack.push(snippet);
5886 return false;
5887 }
5888 }
5889 Bias::Right => {
5890 if snippet.active_index + 1 < snippet.ranges.len() {
5891 snippet.active_index += 1;
5892 } else {
5893 self.snippet_stack.push(snippet);
5894 return false;
5895 }
5896 }
5897 }
5898 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5899 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5900 s.select_anchor_ranges(current_ranges.iter().cloned())
5901 });
5902
5903 if let Some(choices) = &snippet.choices[snippet.active_index] {
5904 if let Some(selection) = current_ranges.first() {
5905 self.show_snippet_choices(&choices, selection.clone(), cx);
5906 }
5907 }
5908
5909 // If snippet state is not at the last tabstop, push it back on the stack
5910 if snippet.active_index + 1 < snippet.ranges.len() {
5911 self.snippet_stack.push(snippet);
5912 }
5913 return true;
5914 }
5915 }
5916
5917 false
5918 }
5919
5920 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5921 self.transact(cx, |this, cx| {
5922 this.select_all(&SelectAll, cx);
5923 this.insert("", cx);
5924 });
5925 }
5926
5927 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5928 self.transact(cx, |this, cx| {
5929 this.select_autoclose_pair(cx);
5930 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5931 if !this.linked_edit_ranges.is_empty() {
5932 let selections = this.selections.all::<MultiBufferPoint>(cx);
5933 let snapshot = this.buffer.read(cx).snapshot(cx);
5934
5935 for selection in selections.iter() {
5936 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5937 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5938 if selection_start.buffer_id != selection_end.buffer_id {
5939 continue;
5940 }
5941 if let Some(ranges) =
5942 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5943 {
5944 for (buffer, entries) in ranges {
5945 linked_ranges.entry(buffer).or_default().extend(entries);
5946 }
5947 }
5948 }
5949 }
5950
5951 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5952 if !this.selections.line_mode {
5953 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5954 for selection in &mut selections {
5955 if selection.is_empty() {
5956 let old_head = selection.head();
5957 let mut new_head =
5958 movement::left(&display_map, old_head.to_display_point(&display_map))
5959 .to_point(&display_map);
5960 if let Some((buffer, line_buffer_range)) = display_map
5961 .buffer_snapshot
5962 .buffer_line_for_row(MultiBufferRow(old_head.row))
5963 {
5964 let indent_size =
5965 buffer.indent_size_for_line(line_buffer_range.start.row);
5966 let indent_len = match indent_size.kind {
5967 IndentKind::Space => {
5968 buffer.settings_at(line_buffer_range.start, cx).tab_size
5969 }
5970 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5971 };
5972 if old_head.column <= indent_size.len && old_head.column > 0 {
5973 let indent_len = indent_len.get();
5974 new_head = cmp::min(
5975 new_head,
5976 MultiBufferPoint::new(
5977 old_head.row,
5978 ((old_head.column - 1) / indent_len) * indent_len,
5979 ),
5980 );
5981 }
5982 }
5983
5984 selection.set_head(new_head, SelectionGoal::None);
5985 }
5986 }
5987 }
5988
5989 this.signature_help_state.set_backspace_pressed(true);
5990 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5991 this.insert("", cx);
5992 let empty_str: Arc<str> = Arc::from("");
5993 for (buffer, edits) in linked_ranges {
5994 let snapshot = buffer.read(cx).snapshot();
5995 use text::ToPoint as TP;
5996
5997 let edits = edits
5998 .into_iter()
5999 .map(|range| {
6000 let end_point = TP::to_point(&range.end, &snapshot);
6001 let mut start_point = TP::to_point(&range.start, &snapshot);
6002
6003 if end_point == start_point {
6004 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6005 .saturating_sub(1);
6006 start_point = TP::to_point(&offset, &snapshot);
6007 };
6008
6009 (start_point..end_point, empty_str.clone())
6010 })
6011 .sorted_by_key(|(range, _)| range.start)
6012 .collect::<Vec<_>>();
6013 buffer.update(cx, |this, cx| {
6014 this.edit(edits, None, cx);
6015 })
6016 }
6017 this.refresh_inline_completion(true, false, cx);
6018 linked_editing_ranges::refresh_linked_ranges(this, cx);
6019 });
6020 }
6021
6022 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6023 self.transact(cx, |this, cx| {
6024 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6025 let line_mode = s.line_mode;
6026 s.move_with(|map, selection| {
6027 if selection.is_empty() && !line_mode {
6028 let cursor = movement::right(map, selection.head());
6029 selection.end = cursor;
6030 selection.reversed = true;
6031 selection.goal = SelectionGoal::None;
6032 }
6033 })
6034 });
6035 this.insert("", cx);
6036 this.refresh_inline_completion(true, false, cx);
6037 });
6038 }
6039
6040 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6041 if self.move_to_prev_snippet_tabstop(cx) {
6042 return;
6043 }
6044
6045 self.outdent(&Outdent, cx);
6046 }
6047
6048 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6049 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6050 return;
6051 }
6052
6053 let mut selections = self.selections.all_adjusted(cx);
6054 let buffer = self.buffer.read(cx);
6055 let snapshot = buffer.snapshot(cx);
6056 let rows_iter = selections.iter().map(|s| s.head().row);
6057 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6058
6059 let mut edits = Vec::new();
6060 let mut prev_edited_row = 0;
6061 let mut row_delta = 0;
6062 for selection in &mut selections {
6063 if selection.start.row != prev_edited_row {
6064 row_delta = 0;
6065 }
6066 prev_edited_row = selection.end.row;
6067
6068 // If the selection is non-empty, then increase the indentation of the selected lines.
6069 if !selection.is_empty() {
6070 row_delta =
6071 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6072 continue;
6073 }
6074
6075 // If the selection is empty and the cursor is in the leading whitespace before the
6076 // suggested indentation, then auto-indent the line.
6077 let cursor = selection.head();
6078 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6079 if let Some(suggested_indent) =
6080 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6081 {
6082 if cursor.column < suggested_indent.len
6083 && cursor.column <= current_indent.len
6084 && current_indent.len <= suggested_indent.len
6085 {
6086 selection.start = Point::new(cursor.row, suggested_indent.len);
6087 selection.end = selection.start;
6088 if row_delta == 0 {
6089 edits.extend(Buffer::edit_for_indent_size_adjustment(
6090 cursor.row,
6091 current_indent,
6092 suggested_indent,
6093 ));
6094 row_delta = suggested_indent.len - current_indent.len;
6095 }
6096 continue;
6097 }
6098 }
6099
6100 // Otherwise, insert a hard or soft tab.
6101 let settings = buffer.settings_at(cursor, cx);
6102 let tab_size = if settings.hard_tabs {
6103 IndentSize::tab()
6104 } else {
6105 let tab_size = settings.tab_size.get();
6106 let char_column = snapshot
6107 .text_for_range(Point::new(cursor.row, 0)..cursor)
6108 .flat_map(str::chars)
6109 .count()
6110 + row_delta as usize;
6111 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6112 IndentSize::spaces(chars_to_next_tab_stop)
6113 };
6114 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6115 selection.end = selection.start;
6116 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6117 row_delta += tab_size.len;
6118 }
6119
6120 self.transact(cx, |this, cx| {
6121 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6122 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6123 this.refresh_inline_completion(true, false, cx);
6124 });
6125 }
6126
6127 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6128 if self.read_only(cx) {
6129 return;
6130 }
6131 let mut selections = self.selections.all::<Point>(cx);
6132 let mut prev_edited_row = 0;
6133 let mut row_delta = 0;
6134 let mut edits = Vec::new();
6135 let buffer = self.buffer.read(cx);
6136 let snapshot = buffer.snapshot(cx);
6137 for selection in &mut selections {
6138 if selection.start.row != prev_edited_row {
6139 row_delta = 0;
6140 }
6141 prev_edited_row = selection.end.row;
6142
6143 row_delta =
6144 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6145 }
6146
6147 self.transact(cx, |this, cx| {
6148 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6149 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6150 });
6151 }
6152
6153 fn indent_selection(
6154 buffer: &MultiBuffer,
6155 snapshot: &MultiBufferSnapshot,
6156 selection: &mut Selection<Point>,
6157 edits: &mut Vec<(Range<Point>, String)>,
6158 delta_for_start_row: u32,
6159 cx: &AppContext,
6160 ) -> u32 {
6161 let settings = buffer.settings_at(selection.start, cx);
6162 let tab_size = settings.tab_size.get();
6163 let indent_kind = if settings.hard_tabs {
6164 IndentKind::Tab
6165 } else {
6166 IndentKind::Space
6167 };
6168 let mut start_row = selection.start.row;
6169 let mut end_row = selection.end.row + 1;
6170
6171 // If a selection ends at the beginning of a line, don't indent
6172 // that last line.
6173 if selection.end.column == 0 && selection.end.row > selection.start.row {
6174 end_row -= 1;
6175 }
6176
6177 // Avoid re-indenting a row that has already been indented by a
6178 // previous selection, but still update this selection's column
6179 // to reflect that indentation.
6180 if delta_for_start_row > 0 {
6181 start_row += 1;
6182 selection.start.column += delta_for_start_row;
6183 if selection.end.row == selection.start.row {
6184 selection.end.column += delta_for_start_row;
6185 }
6186 }
6187
6188 let mut delta_for_end_row = 0;
6189 let has_multiple_rows = start_row + 1 != end_row;
6190 for row in start_row..end_row {
6191 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6192 let indent_delta = match (current_indent.kind, indent_kind) {
6193 (IndentKind::Space, IndentKind::Space) => {
6194 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6195 IndentSize::spaces(columns_to_next_tab_stop)
6196 }
6197 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6198 (_, IndentKind::Tab) => IndentSize::tab(),
6199 };
6200
6201 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6202 0
6203 } else {
6204 selection.start.column
6205 };
6206 let row_start = Point::new(row, start);
6207 edits.push((
6208 row_start..row_start,
6209 indent_delta.chars().collect::<String>(),
6210 ));
6211
6212 // Update this selection's endpoints to reflect the indentation.
6213 if row == selection.start.row {
6214 selection.start.column += indent_delta.len;
6215 }
6216 if row == selection.end.row {
6217 selection.end.column += indent_delta.len;
6218 delta_for_end_row = indent_delta.len;
6219 }
6220 }
6221
6222 if selection.start.row == selection.end.row {
6223 delta_for_start_row + delta_for_end_row
6224 } else {
6225 delta_for_end_row
6226 }
6227 }
6228
6229 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6230 if self.read_only(cx) {
6231 return;
6232 }
6233 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6234 let selections = self.selections.all::<Point>(cx);
6235 let mut deletion_ranges = Vec::new();
6236 let mut last_outdent = None;
6237 {
6238 let buffer = self.buffer.read(cx);
6239 let snapshot = buffer.snapshot(cx);
6240 for selection in &selections {
6241 let settings = buffer.settings_at(selection.start, cx);
6242 let tab_size = settings.tab_size.get();
6243 let mut rows = selection.spanned_rows(false, &display_map);
6244
6245 // Avoid re-outdenting a row that has already been outdented by a
6246 // previous selection.
6247 if let Some(last_row) = last_outdent {
6248 if last_row == rows.start {
6249 rows.start = rows.start.next_row();
6250 }
6251 }
6252 let has_multiple_rows = rows.len() > 1;
6253 for row in rows.iter_rows() {
6254 let indent_size = snapshot.indent_size_for_line(row);
6255 if indent_size.len > 0 {
6256 let deletion_len = match indent_size.kind {
6257 IndentKind::Space => {
6258 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6259 if columns_to_prev_tab_stop == 0 {
6260 tab_size
6261 } else {
6262 columns_to_prev_tab_stop
6263 }
6264 }
6265 IndentKind::Tab => 1,
6266 };
6267 let start = if has_multiple_rows
6268 || deletion_len > selection.start.column
6269 || indent_size.len < selection.start.column
6270 {
6271 0
6272 } else {
6273 selection.start.column - deletion_len
6274 };
6275 deletion_ranges.push(
6276 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6277 );
6278 last_outdent = Some(row);
6279 }
6280 }
6281 }
6282 }
6283
6284 self.transact(cx, |this, cx| {
6285 this.buffer.update(cx, |buffer, cx| {
6286 let empty_str: Arc<str> = Arc::default();
6287 buffer.edit(
6288 deletion_ranges
6289 .into_iter()
6290 .map(|range| (range, empty_str.clone())),
6291 None,
6292 cx,
6293 );
6294 });
6295 let selections = this.selections.all::<usize>(cx);
6296 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6297 });
6298 }
6299
6300 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
6301 if self.read_only(cx) {
6302 return;
6303 }
6304 let selections = self
6305 .selections
6306 .all::<usize>(cx)
6307 .into_iter()
6308 .map(|s| s.range());
6309
6310 self.transact(cx, |this, cx| {
6311 this.buffer.update(cx, |buffer, cx| {
6312 buffer.autoindent_ranges(selections, cx);
6313 });
6314 let selections = this.selections.all::<usize>(cx);
6315 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6316 });
6317 }
6318
6319 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6321 let selections = self.selections.all::<Point>(cx);
6322
6323 let mut new_cursors = Vec::new();
6324 let mut edit_ranges = Vec::new();
6325 let mut selections = selections.iter().peekable();
6326 while let Some(selection) = selections.next() {
6327 let mut rows = selection.spanned_rows(false, &display_map);
6328 let goal_display_column = selection.head().to_display_point(&display_map).column();
6329
6330 // Accumulate contiguous regions of rows that we want to delete.
6331 while let Some(next_selection) = selections.peek() {
6332 let next_rows = next_selection.spanned_rows(false, &display_map);
6333 if next_rows.start <= rows.end {
6334 rows.end = next_rows.end;
6335 selections.next().unwrap();
6336 } else {
6337 break;
6338 }
6339 }
6340
6341 let buffer = &display_map.buffer_snapshot;
6342 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6343 let edit_end;
6344 let cursor_buffer_row;
6345 if buffer.max_point().row >= rows.end.0 {
6346 // If there's a line after the range, delete the \n from the end of the row range
6347 // and position the cursor on the next line.
6348 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6349 cursor_buffer_row = rows.end;
6350 } else {
6351 // If there isn't a line after the range, delete the \n from the line before the
6352 // start of the row range and position the cursor there.
6353 edit_start = edit_start.saturating_sub(1);
6354 edit_end = buffer.len();
6355 cursor_buffer_row = rows.start.previous_row();
6356 }
6357
6358 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6359 *cursor.column_mut() =
6360 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6361
6362 new_cursors.push((
6363 selection.id,
6364 buffer.anchor_after(cursor.to_point(&display_map)),
6365 ));
6366 edit_ranges.push(edit_start..edit_end);
6367 }
6368
6369 self.transact(cx, |this, cx| {
6370 let buffer = this.buffer.update(cx, |buffer, cx| {
6371 let empty_str: Arc<str> = Arc::default();
6372 buffer.edit(
6373 edit_ranges
6374 .into_iter()
6375 .map(|range| (range, empty_str.clone())),
6376 None,
6377 cx,
6378 );
6379 buffer.snapshot(cx)
6380 });
6381 let new_selections = new_cursors
6382 .into_iter()
6383 .map(|(id, cursor)| {
6384 let cursor = cursor.to_point(&buffer);
6385 Selection {
6386 id,
6387 start: cursor,
6388 end: cursor,
6389 reversed: false,
6390 goal: SelectionGoal::None,
6391 }
6392 })
6393 .collect();
6394
6395 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6396 s.select(new_selections);
6397 });
6398 });
6399 }
6400
6401 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6402 if self.read_only(cx) {
6403 return;
6404 }
6405 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6406 for selection in self.selections.all::<Point>(cx) {
6407 let start = MultiBufferRow(selection.start.row);
6408 // Treat single line selections as if they include the next line. Otherwise this action
6409 // would do nothing for single line selections individual cursors.
6410 let end = if selection.start.row == selection.end.row {
6411 MultiBufferRow(selection.start.row + 1)
6412 } else {
6413 MultiBufferRow(selection.end.row)
6414 };
6415
6416 if let Some(last_row_range) = row_ranges.last_mut() {
6417 if start <= last_row_range.end {
6418 last_row_range.end = end;
6419 continue;
6420 }
6421 }
6422 row_ranges.push(start..end);
6423 }
6424
6425 let snapshot = self.buffer.read(cx).snapshot(cx);
6426 let mut cursor_positions = Vec::new();
6427 for row_range in &row_ranges {
6428 let anchor = snapshot.anchor_before(Point::new(
6429 row_range.end.previous_row().0,
6430 snapshot.line_len(row_range.end.previous_row()),
6431 ));
6432 cursor_positions.push(anchor..anchor);
6433 }
6434
6435 self.transact(cx, |this, cx| {
6436 for row_range in row_ranges.into_iter().rev() {
6437 for row in row_range.iter_rows().rev() {
6438 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6439 let next_line_row = row.next_row();
6440 let indent = snapshot.indent_size_for_line(next_line_row);
6441 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6442
6443 let replace = if snapshot.line_len(next_line_row) > indent.len {
6444 " "
6445 } else {
6446 ""
6447 };
6448
6449 this.buffer.update(cx, |buffer, cx| {
6450 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6451 });
6452 }
6453 }
6454
6455 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6456 s.select_anchor_ranges(cursor_positions)
6457 });
6458 });
6459 }
6460
6461 pub fn sort_lines_case_sensitive(
6462 &mut self,
6463 _: &SortLinesCaseSensitive,
6464 cx: &mut ViewContext<Self>,
6465 ) {
6466 self.manipulate_lines(cx, |lines| lines.sort())
6467 }
6468
6469 pub fn sort_lines_case_insensitive(
6470 &mut self,
6471 _: &SortLinesCaseInsensitive,
6472 cx: &mut ViewContext<Self>,
6473 ) {
6474 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6475 }
6476
6477 pub fn unique_lines_case_insensitive(
6478 &mut self,
6479 _: &UniqueLinesCaseInsensitive,
6480 cx: &mut ViewContext<Self>,
6481 ) {
6482 self.manipulate_lines(cx, |lines| {
6483 let mut seen = HashSet::default();
6484 lines.retain(|line| seen.insert(line.to_lowercase()));
6485 })
6486 }
6487
6488 pub fn unique_lines_case_sensitive(
6489 &mut self,
6490 _: &UniqueLinesCaseSensitive,
6491 cx: &mut ViewContext<Self>,
6492 ) {
6493 self.manipulate_lines(cx, |lines| {
6494 let mut seen = HashSet::default();
6495 lines.retain(|line| seen.insert(*line));
6496 })
6497 }
6498
6499 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6500 let mut revert_changes = HashMap::default();
6501 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6502 for hunk in hunks_for_rows(
6503 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6504 &multi_buffer_snapshot,
6505 ) {
6506 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6507 }
6508 if !revert_changes.is_empty() {
6509 self.transact(cx, |editor, cx| {
6510 editor.revert(revert_changes, cx);
6511 });
6512 }
6513 }
6514
6515 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6516 let Some(project) = self.project.clone() else {
6517 return;
6518 };
6519 self.reload(project, cx).detach_and_notify_err(cx);
6520 }
6521
6522 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6523 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6524 if !revert_changes.is_empty() {
6525 self.transact(cx, |editor, cx| {
6526 editor.revert(revert_changes, cx);
6527 });
6528 }
6529 }
6530
6531 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6532 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6533 let project_path = buffer.read(cx).project_path(cx)?;
6534 let project = self.project.as_ref()?.read(cx);
6535 let entry = project.entry_for_path(&project_path, cx)?;
6536 let parent = match &entry.canonical_path {
6537 Some(canonical_path) => canonical_path.to_path_buf(),
6538 None => project.absolute_path(&project_path, cx)?,
6539 }
6540 .parent()?
6541 .to_path_buf();
6542 Some(parent)
6543 }) {
6544 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6545 }
6546 }
6547
6548 fn gather_revert_changes(
6549 &mut self,
6550 selections: &[Selection<Anchor>],
6551 cx: &mut ViewContext<'_, Editor>,
6552 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6553 let mut revert_changes = HashMap::default();
6554 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6555 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6556 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6557 }
6558 revert_changes
6559 }
6560
6561 pub fn prepare_revert_change(
6562 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6563 multi_buffer: &Model<MultiBuffer>,
6564 hunk: &MultiBufferDiffHunk,
6565 cx: &AppContext,
6566 ) -> Option<()> {
6567 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6568 let buffer = buffer.read(cx);
6569 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6570 let buffer_snapshot = buffer.snapshot();
6571 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6572 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6573 probe
6574 .0
6575 .start
6576 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6577 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6578 }) {
6579 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6580 Some(())
6581 } else {
6582 None
6583 }
6584 }
6585
6586 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6587 self.manipulate_lines(cx, |lines| lines.reverse())
6588 }
6589
6590 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6591 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6592 }
6593
6594 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6595 where
6596 Fn: FnMut(&mut Vec<&str>),
6597 {
6598 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6599 let buffer = self.buffer.read(cx).snapshot(cx);
6600
6601 let mut edits = Vec::new();
6602
6603 let selections = self.selections.all::<Point>(cx);
6604 let mut selections = selections.iter().peekable();
6605 let mut contiguous_row_selections = Vec::new();
6606 let mut new_selections = Vec::new();
6607 let mut added_lines = 0;
6608 let mut removed_lines = 0;
6609
6610 while let Some(selection) = selections.next() {
6611 let (start_row, end_row) = consume_contiguous_rows(
6612 &mut contiguous_row_selections,
6613 selection,
6614 &display_map,
6615 &mut selections,
6616 );
6617
6618 let start_point = Point::new(start_row.0, 0);
6619 let end_point = Point::new(
6620 end_row.previous_row().0,
6621 buffer.line_len(end_row.previous_row()),
6622 );
6623 let text = buffer
6624 .text_for_range(start_point..end_point)
6625 .collect::<String>();
6626
6627 let mut lines = text.split('\n').collect_vec();
6628
6629 let lines_before = lines.len();
6630 callback(&mut lines);
6631 let lines_after = lines.len();
6632
6633 edits.push((start_point..end_point, lines.join("\n")));
6634
6635 // Selections must change based on added and removed line count
6636 let start_row =
6637 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6638 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6639 new_selections.push(Selection {
6640 id: selection.id,
6641 start: start_row,
6642 end: end_row,
6643 goal: SelectionGoal::None,
6644 reversed: selection.reversed,
6645 });
6646
6647 if lines_after > lines_before {
6648 added_lines += lines_after - lines_before;
6649 } else if lines_before > lines_after {
6650 removed_lines += lines_before - lines_after;
6651 }
6652 }
6653
6654 self.transact(cx, |this, cx| {
6655 let buffer = this.buffer.update(cx, |buffer, cx| {
6656 buffer.edit(edits, None, cx);
6657 buffer.snapshot(cx)
6658 });
6659
6660 // Recalculate offsets on newly edited buffer
6661 let new_selections = new_selections
6662 .iter()
6663 .map(|s| {
6664 let start_point = Point::new(s.start.0, 0);
6665 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6666 Selection {
6667 id: s.id,
6668 start: buffer.point_to_offset(start_point),
6669 end: buffer.point_to_offset(end_point),
6670 goal: s.goal,
6671 reversed: s.reversed,
6672 }
6673 })
6674 .collect();
6675
6676 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6677 s.select(new_selections);
6678 });
6679
6680 this.request_autoscroll(Autoscroll::fit(), cx);
6681 });
6682 }
6683
6684 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6685 self.manipulate_text(cx, |text| text.to_uppercase())
6686 }
6687
6688 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6689 self.manipulate_text(cx, |text| text.to_lowercase())
6690 }
6691
6692 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6693 self.manipulate_text(cx, |text| {
6694 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6695 // https://github.com/rutrum/convert-case/issues/16
6696 text.split('\n')
6697 .map(|line| line.to_case(Case::Title))
6698 .join("\n")
6699 })
6700 }
6701
6702 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6703 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6704 }
6705
6706 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6707 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6708 }
6709
6710 pub fn convert_to_upper_camel_case(
6711 &mut self,
6712 _: &ConvertToUpperCamelCase,
6713 cx: &mut ViewContext<Self>,
6714 ) {
6715 self.manipulate_text(cx, |text| {
6716 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6717 // https://github.com/rutrum/convert-case/issues/16
6718 text.split('\n')
6719 .map(|line| line.to_case(Case::UpperCamel))
6720 .join("\n")
6721 })
6722 }
6723
6724 pub fn convert_to_lower_camel_case(
6725 &mut self,
6726 _: &ConvertToLowerCamelCase,
6727 cx: &mut ViewContext<Self>,
6728 ) {
6729 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6730 }
6731
6732 pub fn convert_to_opposite_case(
6733 &mut self,
6734 _: &ConvertToOppositeCase,
6735 cx: &mut ViewContext<Self>,
6736 ) {
6737 self.manipulate_text(cx, |text| {
6738 text.chars()
6739 .fold(String::with_capacity(text.len()), |mut t, c| {
6740 if c.is_uppercase() {
6741 t.extend(c.to_lowercase());
6742 } else {
6743 t.extend(c.to_uppercase());
6744 }
6745 t
6746 })
6747 })
6748 }
6749
6750 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6751 where
6752 Fn: FnMut(&str) -> String,
6753 {
6754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6755 let buffer = self.buffer.read(cx).snapshot(cx);
6756
6757 let mut new_selections = Vec::new();
6758 let mut edits = Vec::new();
6759 let mut selection_adjustment = 0i32;
6760
6761 for selection in self.selections.all::<usize>(cx) {
6762 let selection_is_empty = selection.is_empty();
6763
6764 let (start, end) = if selection_is_empty {
6765 let word_range = movement::surrounding_word(
6766 &display_map,
6767 selection.start.to_display_point(&display_map),
6768 );
6769 let start = word_range.start.to_offset(&display_map, Bias::Left);
6770 let end = word_range.end.to_offset(&display_map, Bias::Left);
6771 (start, end)
6772 } else {
6773 (selection.start, selection.end)
6774 };
6775
6776 let text = buffer.text_for_range(start..end).collect::<String>();
6777 let old_length = text.len() as i32;
6778 let text = callback(&text);
6779
6780 new_selections.push(Selection {
6781 start: (start as i32 - selection_adjustment) as usize,
6782 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6783 goal: SelectionGoal::None,
6784 ..selection
6785 });
6786
6787 selection_adjustment += old_length - text.len() as i32;
6788
6789 edits.push((start..end, text));
6790 }
6791
6792 self.transact(cx, |this, cx| {
6793 this.buffer.update(cx, |buffer, cx| {
6794 buffer.edit(edits, None, cx);
6795 });
6796
6797 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6798 s.select(new_selections);
6799 });
6800
6801 this.request_autoscroll(Autoscroll::fit(), cx);
6802 });
6803 }
6804
6805 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6806 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6807 let buffer = &display_map.buffer_snapshot;
6808 let selections = self.selections.all::<Point>(cx);
6809
6810 let mut edits = Vec::new();
6811 let mut selections_iter = selections.iter().peekable();
6812 while let Some(selection) = selections_iter.next() {
6813 // Avoid duplicating the same lines twice.
6814 let mut rows = selection.spanned_rows(false, &display_map);
6815
6816 while let Some(next_selection) = selections_iter.peek() {
6817 let next_rows = next_selection.spanned_rows(false, &display_map);
6818 if next_rows.start < rows.end {
6819 rows.end = next_rows.end;
6820 selections_iter.next().unwrap();
6821 } else {
6822 break;
6823 }
6824 }
6825
6826 // Copy the text from the selected row region and splice it either at the start
6827 // or end of the region.
6828 let start = Point::new(rows.start.0, 0);
6829 let end = Point::new(
6830 rows.end.previous_row().0,
6831 buffer.line_len(rows.end.previous_row()),
6832 );
6833 let text = buffer
6834 .text_for_range(start..end)
6835 .chain(Some("\n"))
6836 .collect::<String>();
6837 let insert_location = if upwards {
6838 Point::new(rows.end.0, 0)
6839 } else {
6840 start
6841 };
6842 edits.push((insert_location..insert_location, text));
6843 }
6844
6845 self.transact(cx, |this, cx| {
6846 this.buffer.update(cx, |buffer, cx| {
6847 buffer.edit(edits, None, cx);
6848 });
6849
6850 this.request_autoscroll(Autoscroll::fit(), cx);
6851 });
6852 }
6853
6854 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6855 self.duplicate_line(true, cx);
6856 }
6857
6858 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6859 self.duplicate_line(false, cx);
6860 }
6861
6862 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6863 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6864 let buffer = self.buffer.read(cx).snapshot(cx);
6865
6866 let mut edits = Vec::new();
6867 let mut unfold_ranges = Vec::new();
6868 let mut refold_creases = Vec::new();
6869
6870 let selections = self.selections.all::<Point>(cx);
6871 let mut selections = selections.iter().peekable();
6872 let mut contiguous_row_selections = Vec::new();
6873 let mut new_selections = Vec::new();
6874
6875 while let Some(selection) = selections.next() {
6876 // Find all the selections that span a contiguous row range
6877 let (start_row, end_row) = consume_contiguous_rows(
6878 &mut contiguous_row_selections,
6879 selection,
6880 &display_map,
6881 &mut selections,
6882 );
6883
6884 // Move the text spanned by the row range to be before the line preceding the row range
6885 if start_row.0 > 0 {
6886 let range_to_move = Point::new(
6887 start_row.previous_row().0,
6888 buffer.line_len(start_row.previous_row()),
6889 )
6890 ..Point::new(
6891 end_row.previous_row().0,
6892 buffer.line_len(end_row.previous_row()),
6893 );
6894 let insertion_point = display_map
6895 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6896 .0;
6897
6898 // Don't move lines across excerpts
6899 if buffer
6900 .excerpt_boundaries_in_range((
6901 Bound::Excluded(insertion_point),
6902 Bound::Included(range_to_move.end),
6903 ))
6904 .next()
6905 .is_none()
6906 {
6907 let text = buffer
6908 .text_for_range(range_to_move.clone())
6909 .flat_map(|s| s.chars())
6910 .skip(1)
6911 .chain(['\n'])
6912 .collect::<String>();
6913
6914 edits.push((
6915 buffer.anchor_after(range_to_move.start)
6916 ..buffer.anchor_before(range_to_move.end),
6917 String::new(),
6918 ));
6919 let insertion_anchor = buffer.anchor_after(insertion_point);
6920 edits.push((insertion_anchor..insertion_anchor, text));
6921
6922 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6923
6924 // Move selections up
6925 new_selections.extend(contiguous_row_selections.drain(..).map(
6926 |mut selection| {
6927 selection.start.row -= row_delta;
6928 selection.end.row -= row_delta;
6929 selection
6930 },
6931 ));
6932
6933 // Move folds up
6934 unfold_ranges.push(range_to_move.clone());
6935 for fold in display_map.folds_in_range(
6936 buffer.anchor_before(range_to_move.start)
6937 ..buffer.anchor_after(range_to_move.end),
6938 ) {
6939 let mut start = fold.range.start.to_point(&buffer);
6940 let mut end = fold.range.end.to_point(&buffer);
6941 start.row -= row_delta;
6942 end.row -= row_delta;
6943 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6944 }
6945 }
6946 }
6947
6948 // If we didn't move line(s), preserve the existing selections
6949 new_selections.append(&mut contiguous_row_selections);
6950 }
6951
6952 self.transact(cx, |this, cx| {
6953 this.unfold_ranges(&unfold_ranges, true, true, cx);
6954 this.buffer.update(cx, |buffer, cx| {
6955 for (range, text) in edits {
6956 buffer.edit([(range, text)], None, cx);
6957 }
6958 });
6959 this.fold_creases(refold_creases, true, cx);
6960 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6961 s.select(new_selections);
6962 })
6963 });
6964 }
6965
6966 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6968 let buffer = self.buffer.read(cx).snapshot(cx);
6969
6970 let mut edits = Vec::new();
6971 let mut unfold_ranges = Vec::new();
6972 let mut refold_creases = Vec::new();
6973
6974 let selections = self.selections.all::<Point>(cx);
6975 let mut selections = selections.iter().peekable();
6976 let mut contiguous_row_selections = Vec::new();
6977 let mut new_selections = Vec::new();
6978
6979 while let Some(selection) = selections.next() {
6980 // Find all the selections that span a contiguous row range
6981 let (start_row, end_row) = consume_contiguous_rows(
6982 &mut contiguous_row_selections,
6983 selection,
6984 &display_map,
6985 &mut selections,
6986 );
6987
6988 // Move the text spanned by the row range to be after the last line of the row range
6989 if end_row.0 <= buffer.max_point().row {
6990 let range_to_move =
6991 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6992 let insertion_point = display_map
6993 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6994 .0;
6995
6996 // Don't move lines across excerpt boundaries
6997 if buffer
6998 .excerpt_boundaries_in_range((
6999 Bound::Excluded(range_to_move.start),
7000 Bound::Included(insertion_point),
7001 ))
7002 .next()
7003 .is_none()
7004 {
7005 let mut text = String::from("\n");
7006 text.extend(buffer.text_for_range(range_to_move.clone()));
7007 text.pop(); // Drop trailing newline
7008 edits.push((
7009 buffer.anchor_after(range_to_move.start)
7010 ..buffer.anchor_before(range_to_move.end),
7011 String::new(),
7012 ));
7013 let insertion_anchor = buffer.anchor_after(insertion_point);
7014 edits.push((insertion_anchor..insertion_anchor, text));
7015
7016 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7017
7018 // Move selections down
7019 new_selections.extend(contiguous_row_selections.drain(..).map(
7020 |mut selection| {
7021 selection.start.row += row_delta;
7022 selection.end.row += row_delta;
7023 selection
7024 },
7025 ));
7026
7027 // Move folds down
7028 unfold_ranges.push(range_to_move.clone());
7029 for fold in display_map.folds_in_range(
7030 buffer.anchor_before(range_to_move.start)
7031 ..buffer.anchor_after(range_to_move.end),
7032 ) {
7033 let mut start = fold.range.start.to_point(&buffer);
7034 let mut end = fold.range.end.to_point(&buffer);
7035 start.row += row_delta;
7036 end.row += row_delta;
7037 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7038 }
7039 }
7040 }
7041
7042 // If we didn't move line(s), preserve the existing selections
7043 new_selections.append(&mut contiguous_row_selections);
7044 }
7045
7046 self.transact(cx, |this, cx| {
7047 this.unfold_ranges(&unfold_ranges, true, true, cx);
7048 this.buffer.update(cx, |buffer, cx| {
7049 for (range, text) in edits {
7050 buffer.edit([(range, text)], None, cx);
7051 }
7052 });
7053 this.fold_creases(refold_creases, true, cx);
7054 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7055 });
7056 }
7057
7058 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7059 let text_layout_details = &self.text_layout_details(cx);
7060 self.transact(cx, |this, cx| {
7061 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7062 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7063 let line_mode = s.line_mode;
7064 s.move_with(|display_map, selection| {
7065 if !selection.is_empty() || line_mode {
7066 return;
7067 }
7068
7069 let mut head = selection.head();
7070 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7071 if head.column() == display_map.line_len(head.row()) {
7072 transpose_offset = display_map
7073 .buffer_snapshot
7074 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7075 }
7076
7077 if transpose_offset == 0 {
7078 return;
7079 }
7080
7081 *head.column_mut() += 1;
7082 head = display_map.clip_point(head, Bias::Right);
7083 let goal = SelectionGoal::HorizontalPosition(
7084 display_map
7085 .x_for_display_point(head, text_layout_details)
7086 .into(),
7087 );
7088 selection.collapse_to(head, goal);
7089
7090 let transpose_start = display_map
7091 .buffer_snapshot
7092 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7093 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7094 let transpose_end = display_map
7095 .buffer_snapshot
7096 .clip_offset(transpose_offset + 1, Bias::Right);
7097 if let Some(ch) =
7098 display_map.buffer_snapshot.chars_at(transpose_start).next()
7099 {
7100 edits.push((transpose_start..transpose_offset, String::new()));
7101 edits.push((transpose_end..transpose_end, ch.to_string()));
7102 }
7103 }
7104 });
7105 edits
7106 });
7107 this.buffer
7108 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7109 let selections = this.selections.all::<usize>(cx);
7110 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7111 s.select(selections);
7112 });
7113 });
7114 }
7115
7116 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7117 self.rewrap_impl(IsVimMode::No, cx)
7118 }
7119
7120 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7121 let buffer = self.buffer.read(cx).snapshot(cx);
7122 let selections = self.selections.all::<Point>(cx);
7123 let mut selections = selections.iter().peekable();
7124
7125 let mut edits = Vec::new();
7126 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7127
7128 while let Some(selection) = selections.next() {
7129 let mut start_row = selection.start.row;
7130 let mut end_row = selection.end.row;
7131
7132 // Skip selections that overlap with a range that has already been rewrapped.
7133 let selection_range = start_row..end_row;
7134 if rewrapped_row_ranges
7135 .iter()
7136 .any(|range| range.overlaps(&selection_range))
7137 {
7138 continue;
7139 }
7140
7141 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7142
7143 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7144 match language_scope.language_name().0.as_ref() {
7145 "Markdown" | "Plain Text" => {
7146 should_rewrap = true;
7147 }
7148 _ => {}
7149 }
7150 }
7151
7152 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7153
7154 // Since not all lines in the selection may be at the same indent
7155 // level, choose the indent size that is the most common between all
7156 // of the lines.
7157 //
7158 // If there is a tie, we use the deepest indent.
7159 let (indent_size, indent_end) = {
7160 let mut indent_size_occurrences = HashMap::default();
7161 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7162
7163 for row in start_row..=end_row {
7164 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7165 rows_by_indent_size.entry(indent).or_default().push(row);
7166 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7167 }
7168
7169 let indent_size = indent_size_occurrences
7170 .into_iter()
7171 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7172 .map(|(indent, _)| indent)
7173 .unwrap_or_default();
7174 let row = rows_by_indent_size[&indent_size][0];
7175 let indent_end = Point::new(row, indent_size.len);
7176
7177 (indent_size, indent_end)
7178 };
7179
7180 let mut line_prefix = indent_size.chars().collect::<String>();
7181
7182 if let Some(comment_prefix) =
7183 buffer
7184 .language_scope_at(selection.head())
7185 .and_then(|language| {
7186 language
7187 .line_comment_prefixes()
7188 .iter()
7189 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7190 .cloned()
7191 })
7192 {
7193 line_prefix.push_str(&comment_prefix);
7194 should_rewrap = true;
7195 }
7196
7197 if !should_rewrap {
7198 continue;
7199 }
7200
7201 if selection.is_empty() {
7202 'expand_upwards: while start_row > 0 {
7203 let prev_row = start_row - 1;
7204 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7205 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7206 {
7207 start_row = prev_row;
7208 } else {
7209 break 'expand_upwards;
7210 }
7211 }
7212
7213 'expand_downwards: while end_row < buffer.max_point().row {
7214 let next_row = end_row + 1;
7215 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7216 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7217 {
7218 end_row = next_row;
7219 } else {
7220 break 'expand_downwards;
7221 }
7222 }
7223 }
7224
7225 let start = Point::new(start_row, 0);
7226 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7227 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7228 let Some(lines_without_prefixes) = selection_text
7229 .lines()
7230 .map(|line| {
7231 line.strip_prefix(&line_prefix)
7232 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7233 .ok_or_else(|| {
7234 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7235 })
7236 })
7237 .collect::<Result<Vec<_>, _>>()
7238 .log_err()
7239 else {
7240 continue;
7241 };
7242
7243 let wrap_column = buffer
7244 .settings_at(Point::new(start_row, 0), cx)
7245 .preferred_line_length as usize;
7246 let wrapped_text = wrap_with_prefix(
7247 line_prefix,
7248 lines_without_prefixes.join(" "),
7249 wrap_column,
7250 tab_size,
7251 );
7252
7253 // TODO: should always use char-based diff while still supporting cursor behavior that
7254 // matches vim.
7255 let diff = match is_vim_mode {
7256 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7257 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7258 };
7259 let mut offset = start.to_offset(&buffer);
7260 let mut moved_since_edit = true;
7261
7262 for change in diff.iter_all_changes() {
7263 let value = change.value();
7264 match change.tag() {
7265 ChangeTag::Equal => {
7266 offset += value.len();
7267 moved_since_edit = true;
7268 }
7269 ChangeTag::Delete => {
7270 let start = buffer.anchor_after(offset);
7271 let end = buffer.anchor_before(offset + value.len());
7272
7273 if moved_since_edit {
7274 edits.push((start..end, String::new()));
7275 } else {
7276 edits.last_mut().unwrap().0.end = end;
7277 }
7278
7279 offset += value.len();
7280 moved_since_edit = false;
7281 }
7282 ChangeTag::Insert => {
7283 if moved_since_edit {
7284 let anchor = buffer.anchor_after(offset);
7285 edits.push((anchor..anchor, value.to_string()));
7286 } else {
7287 edits.last_mut().unwrap().1.push_str(value);
7288 }
7289
7290 moved_since_edit = false;
7291 }
7292 }
7293 }
7294
7295 rewrapped_row_ranges.push(start_row..=end_row);
7296 }
7297
7298 self.buffer
7299 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7300 }
7301
7302 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
7303 let mut text = String::new();
7304 let buffer = self.buffer.read(cx).snapshot(cx);
7305 let mut selections = self.selections.all::<Point>(cx);
7306 let mut clipboard_selections = Vec::with_capacity(selections.len());
7307 {
7308 let max_point = buffer.max_point();
7309 let mut is_first = true;
7310 for selection in &mut selections {
7311 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7312 if is_entire_line {
7313 selection.start = Point::new(selection.start.row, 0);
7314 if !selection.is_empty() && selection.end.column == 0 {
7315 selection.end = cmp::min(max_point, selection.end);
7316 } else {
7317 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7318 }
7319 selection.goal = SelectionGoal::None;
7320 }
7321 if is_first {
7322 is_first = false;
7323 } else {
7324 text += "\n";
7325 }
7326 let mut len = 0;
7327 for chunk in buffer.text_for_range(selection.start..selection.end) {
7328 text.push_str(chunk);
7329 len += chunk.len();
7330 }
7331 clipboard_selections.push(ClipboardSelection {
7332 len,
7333 is_entire_line,
7334 first_line_indent: buffer
7335 .indent_size_for_line(MultiBufferRow(selection.start.row))
7336 .len,
7337 });
7338 }
7339 }
7340
7341 self.transact(cx, |this, cx| {
7342 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7343 s.select(selections);
7344 });
7345 this.insert("", cx);
7346 });
7347 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7348 }
7349
7350 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7351 let item = self.cut_common(cx);
7352 cx.write_to_clipboard(item);
7353 }
7354
7355 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
7356 self.change_selections(None, cx, |s| {
7357 s.move_with(|snapshot, sel| {
7358 if sel.is_empty() {
7359 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7360 }
7361 });
7362 });
7363 let item = self.cut_common(cx);
7364 cx.set_global(KillRing(item))
7365 }
7366
7367 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7368 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7369 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7370 (kill_ring.text().to_string(), kill_ring.metadata_json())
7371 } else {
7372 return;
7373 }
7374 } else {
7375 return;
7376 };
7377 self.do_paste(&text, metadata, false, cx);
7378 }
7379
7380 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7381 let selections = self.selections.all::<Point>(cx);
7382 let buffer = self.buffer.read(cx).read(cx);
7383 let mut text = String::new();
7384
7385 let mut clipboard_selections = Vec::with_capacity(selections.len());
7386 {
7387 let max_point = buffer.max_point();
7388 let mut is_first = true;
7389 for selection in selections.iter() {
7390 let mut start = selection.start;
7391 let mut end = selection.end;
7392 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7393 if is_entire_line {
7394 start = Point::new(start.row, 0);
7395 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7396 }
7397 if is_first {
7398 is_first = false;
7399 } else {
7400 text += "\n";
7401 }
7402 let mut len = 0;
7403 for chunk in buffer.text_for_range(start..end) {
7404 text.push_str(chunk);
7405 len += chunk.len();
7406 }
7407 clipboard_selections.push(ClipboardSelection {
7408 len,
7409 is_entire_line,
7410 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7411 });
7412 }
7413 }
7414
7415 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7416 text,
7417 clipboard_selections,
7418 ));
7419 }
7420
7421 pub fn do_paste(
7422 &mut self,
7423 text: &String,
7424 clipboard_selections: Option<Vec<ClipboardSelection>>,
7425 handle_entire_lines: bool,
7426 cx: &mut ViewContext<Self>,
7427 ) {
7428 if self.read_only(cx) {
7429 return;
7430 }
7431
7432 let clipboard_text = Cow::Borrowed(text);
7433
7434 self.transact(cx, |this, cx| {
7435 if let Some(mut clipboard_selections) = clipboard_selections {
7436 let old_selections = this.selections.all::<usize>(cx);
7437 let all_selections_were_entire_line =
7438 clipboard_selections.iter().all(|s| s.is_entire_line);
7439 let first_selection_indent_column =
7440 clipboard_selections.first().map(|s| s.first_line_indent);
7441 if clipboard_selections.len() != old_selections.len() {
7442 clipboard_selections.drain(..);
7443 }
7444 let cursor_offset = this.selections.last::<usize>(cx).head();
7445 let mut auto_indent_on_paste = true;
7446
7447 this.buffer.update(cx, |buffer, cx| {
7448 let snapshot = buffer.read(cx);
7449 auto_indent_on_paste =
7450 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7451
7452 let mut start_offset = 0;
7453 let mut edits = Vec::new();
7454 let mut original_indent_columns = Vec::new();
7455 for (ix, selection) in old_selections.iter().enumerate() {
7456 let to_insert;
7457 let entire_line;
7458 let original_indent_column;
7459 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7460 let end_offset = start_offset + clipboard_selection.len;
7461 to_insert = &clipboard_text[start_offset..end_offset];
7462 entire_line = clipboard_selection.is_entire_line;
7463 start_offset = end_offset + 1;
7464 original_indent_column = Some(clipboard_selection.first_line_indent);
7465 } else {
7466 to_insert = clipboard_text.as_str();
7467 entire_line = all_selections_were_entire_line;
7468 original_indent_column = first_selection_indent_column
7469 }
7470
7471 // If the corresponding selection was empty when this slice of the
7472 // clipboard text was written, then the entire line containing the
7473 // selection was copied. If this selection is also currently empty,
7474 // then paste the line before the current line of the buffer.
7475 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7476 let column = selection.start.to_point(&snapshot).column as usize;
7477 let line_start = selection.start - column;
7478 line_start..line_start
7479 } else {
7480 selection.range()
7481 };
7482
7483 edits.push((range, to_insert));
7484 original_indent_columns.extend(original_indent_column);
7485 }
7486 drop(snapshot);
7487
7488 buffer.edit(
7489 edits,
7490 if auto_indent_on_paste {
7491 Some(AutoindentMode::Block {
7492 original_indent_columns,
7493 })
7494 } else {
7495 None
7496 },
7497 cx,
7498 );
7499 });
7500
7501 let selections = this.selections.all::<usize>(cx);
7502 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7503 } else {
7504 this.insert(&clipboard_text, cx);
7505 }
7506 });
7507 }
7508
7509 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7510 if let Some(item) = cx.read_from_clipboard() {
7511 let entries = item.entries();
7512
7513 match entries.first() {
7514 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7515 // of all the pasted entries.
7516 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7517 .do_paste(
7518 clipboard_string.text(),
7519 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7520 true,
7521 cx,
7522 ),
7523 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7524 }
7525 }
7526 }
7527
7528 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7529 if self.read_only(cx) {
7530 return;
7531 }
7532
7533 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7534 if let Some((selections, _)) =
7535 self.selection_history.transaction(transaction_id).cloned()
7536 {
7537 self.change_selections(None, cx, |s| {
7538 s.select_anchors(selections.to_vec());
7539 });
7540 }
7541 self.request_autoscroll(Autoscroll::fit(), cx);
7542 self.unmark_text(cx);
7543 self.refresh_inline_completion(true, false, cx);
7544 cx.emit(EditorEvent::Edited { transaction_id });
7545 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7546 }
7547 }
7548
7549 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7550 if self.read_only(cx) {
7551 return;
7552 }
7553
7554 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7555 if let Some((_, Some(selections))) =
7556 self.selection_history.transaction(transaction_id).cloned()
7557 {
7558 self.change_selections(None, cx, |s| {
7559 s.select_anchors(selections.to_vec());
7560 });
7561 }
7562 self.request_autoscroll(Autoscroll::fit(), cx);
7563 self.unmark_text(cx);
7564 self.refresh_inline_completion(true, false, cx);
7565 cx.emit(EditorEvent::Edited { transaction_id });
7566 }
7567 }
7568
7569 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7570 self.buffer
7571 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7572 }
7573
7574 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7575 self.buffer
7576 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7577 }
7578
7579 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 let line_mode = s.line_mode;
7582 s.move_with(|map, selection| {
7583 let cursor = if selection.is_empty() && !line_mode {
7584 movement::left(map, selection.start)
7585 } else {
7586 selection.start
7587 };
7588 selection.collapse_to(cursor, SelectionGoal::None);
7589 });
7590 })
7591 }
7592
7593 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7594 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7595 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7596 })
7597 }
7598
7599 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7600 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7601 let line_mode = s.line_mode;
7602 s.move_with(|map, selection| {
7603 let cursor = if selection.is_empty() && !line_mode {
7604 movement::right(map, selection.end)
7605 } else {
7606 selection.end
7607 };
7608 selection.collapse_to(cursor, SelectionGoal::None)
7609 });
7610 })
7611 }
7612
7613 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7614 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7615 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7616 })
7617 }
7618
7619 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7620 if self.take_rename(true, cx).is_some() {
7621 return;
7622 }
7623
7624 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7625 cx.propagate();
7626 return;
7627 }
7628
7629 let text_layout_details = &self.text_layout_details(cx);
7630 let selection_count = self.selections.count();
7631 let first_selection = self.selections.first_anchor();
7632
7633 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7634 let line_mode = s.line_mode;
7635 s.move_with(|map, selection| {
7636 if !selection.is_empty() && !line_mode {
7637 selection.goal = SelectionGoal::None;
7638 }
7639 let (cursor, goal) = movement::up(
7640 map,
7641 selection.start,
7642 selection.goal,
7643 false,
7644 text_layout_details,
7645 );
7646 selection.collapse_to(cursor, goal);
7647 });
7648 });
7649
7650 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7651 {
7652 cx.propagate();
7653 }
7654 }
7655
7656 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7657 if self.take_rename(true, cx).is_some() {
7658 return;
7659 }
7660
7661 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7662 cx.propagate();
7663 return;
7664 }
7665
7666 let text_layout_details = &self.text_layout_details(cx);
7667
7668 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7669 let line_mode = s.line_mode;
7670 s.move_with(|map, selection| {
7671 if !selection.is_empty() && !line_mode {
7672 selection.goal = SelectionGoal::None;
7673 }
7674 let (cursor, goal) = movement::up_by_rows(
7675 map,
7676 selection.start,
7677 action.lines,
7678 selection.goal,
7679 false,
7680 text_layout_details,
7681 );
7682 selection.collapse_to(cursor, goal);
7683 });
7684 })
7685 }
7686
7687 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7688 if self.take_rename(true, cx).is_some() {
7689 return;
7690 }
7691
7692 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7693 cx.propagate();
7694 return;
7695 }
7696
7697 let text_layout_details = &self.text_layout_details(cx);
7698
7699 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7700 let line_mode = s.line_mode;
7701 s.move_with(|map, selection| {
7702 if !selection.is_empty() && !line_mode {
7703 selection.goal = SelectionGoal::None;
7704 }
7705 let (cursor, goal) = movement::down_by_rows(
7706 map,
7707 selection.start,
7708 action.lines,
7709 selection.goal,
7710 false,
7711 text_layout_details,
7712 );
7713 selection.collapse_to(cursor, goal);
7714 });
7715 })
7716 }
7717
7718 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7719 let text_layout_details = &self.text_layout_details(cx);
7720 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7721 s.move_heads_with(|map, head, goal| {
7722 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7723 })
7724 })
7725 }
7726
7727 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7728 let text_layout_details = &self.text_layout_details(cx);
7729 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7730 s.move_heads_with(|map, head, goal| {
7731 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7732 })
7733 })
7734 }
7735
7736 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7737 let Some(row_count) = self.visible_row_count() else {
7738 return;
7739 };
7740
7741 let text_layout_details = &self.text_layout_details(cx);
7742
7743 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7744 s.move_heads_with(|map, head, goal| {
7745 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7746 })
7747 })
7748 }
7749
7750 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7751 if self.take_rename(true, cx).is_some() {
7752 return;
7753 }
7754
7755 if self
7756 .context_menu
7757 .write()
7758 .as_mut()
7759 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7760 .unwrap_or(false)
7761 {
7762 return;
7763 }
7764
7765 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7766 cx.propagate();
7767 return;
7768 }
7769
7770 let Some(row_count) = self.visible_row_count() else {
7771 return;
7772 };
7773
7774 let autoscroll = if action.center_cursor {
7775 Autoscroll::center()
7776 } else {
7777 Autoscroll::fit()
7778 };
7779
7780 let text_layout_details = &self.text_layout_details(cx);
7781
7782 self.change_selections(Some(autoscroll), cx, |s| {
7783 let line_mode = s.line_mode;
7784 s.move_with(|map, selection| {
7785 if !selection.is_empty() && !line_mode {
7786 selection.goal = SelectionGoal::None;
7787 }
7788 let (cursor, goal) = movement::up_by_rows(
7789 map,
7790 selection.end,
7791 row_count,
7792 selection.goal,
7793 false,
7794 text_layout_details,
7795 );
7796 selection.collapse_to(cursor, goal);
7797 });
7798 });
7799 }
7800
7801 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7802 let text_layout_details = &self.text_layout_details(cx);
7803 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7804 s.move_heads_with(|map, head, goal| {
7805 movement::up(map, head, goal, false, text_layout_details)
7806 })
7807 })
7808 }
7809
7810 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7811 self.take_rename(true, cx);
7812
7813 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7814 cx.propagate();
7815 return;
7816 }
7817
7818 let text_layout_details = &self.text_layout_details(cx);
7819 let selection_count = self.selections.count();
7820 let first_selection = self.selections.first_anchor();
7821
7822 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7823 let line_mode = s.line_mode;
7824 s.move_with(|map, selection| {
7825 if !selection.is_empty() && !line_mode {
7826 selection.goal = SelectionGoal::None;
7827 }
7828 let (cursor, goal) = movement::down(
7829 map,
7830 selection.end,
7831 selection.goal,
7832 false,
7833 text_layout_details,
7834 );
7835 selection.collapse_to(cursor, goal);
7836 });
7837 });
7838
7839 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7840 {
7841 cx.propagate();
7842 }
7843 }
7844
7845 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7846 let Some(row_count) = self.visible_row_count() else {
7847 return;
7848 };
7849
7850 let text_layout_details = &self.text_layout_details(cx);
7851
7852 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7853 s.move_heads_with(|map, head, goal| {
7854 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7855 })
7856 })
7857 }
7858
7859 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7860 if self.take_rename(true, cx).is_some() {
7861 return;
7862 }
7863
7864 if self
7865 .context_menu
7866 .write()
7867 .as_mut()
7868 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7869 .unwrap_or(false)
7870 {
7871 return;
7872 }
7873
7874 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7875 cx.propagate();
7876 return;
7877 }
7878
7879 let Some(row_count) = self.visible_row_count() else {
7880 return;
7881 };
7882
7883 let autoscroll = if action.center_cursor {
7884 Autoscroll::center()
7885 } else {
7886 Autoscroll::fit()
7887 };
7888
7889 let text_layout_details = &self.text_layout_details(cx);
7890 self.change_selections(Some(autoscroll), cx, |s| {
7891 let line_mode = s.line_mode;
7892 s.move_with(|map, selection| {
7893 if !selection.is_empty() && !line_mode {
7894 selection.goal = SelectionGoal::None;
7895 }
7896 let (cursor, goal) = movement::down_by_rows(
7897 map,
7898 selection.end,
7899 row_count,
7900 selection.goal,
7901 false,
7902 text_layout_details,
7903 );
7904 selection.collapse_to(cursor, goal);
7905 });
7906 });
7907 }
7908
7909 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7910 let text_layout_details = &self.text_layout_details(cx);
7911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7912 s.move_heads_with(|map, head, goal| {
7913 movement::down(map, head, goal, false, text_layout_details)
7914 })
7915 });
7916 }
7917
7918 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7919 if let Some(context_menu) = self.context_menu.write().as_mut() {
7920 context_menu.select_first(self.completion_provider.as_deref(), cx);
7921 }
7922 }
7923
7924 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7925 if let Some(context_menu) = self.context_menu.write().as_mut() {
7926 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7927 }
7928 }
7929
7930 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7931 if let Some(context_menu) = self.context_menu.write().as_mut() {
7932 context_menu.select_next(self.completion_provider.as_deref(), cx);
7933 }
7934 }
7935
7936 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7937 if let Some(context_menu) = self.context_menu.write().as_mut() {
7938 context_menu.select_last(self.completion_provider.as_deref(), cx);
7939 }
7940 }
7941
7942 pub fn move_to_previous_word_start(
7943 &mut self,
7944 _: &MoveToPreviousWordStart,
7945 cx: &mut ViewContext<Self>,
7946 ) {
7947 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7948 s.move_cursors_with(|map, head, _| {
7949 (
7950 movement::previous_word_start(map, head),
7951 SelectionGoal::None,
7952 )
7953 });
7954 })
7955 }
7956
7957 pub fn move_to_previous_subword_start(
7958 &mut self,
7959 _: &MoveToPreviousSubwordStart,
7960 cx: &mut ViewContext<Self>,
7961 ) {
7962 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7963 s.move_cursors_with(|map, head, _| {
7964 (
7965 movement::previous_subword_start(map, head),
7966 SelectionGoal::None,
7967 )
7968 });
7969 })
7970 }
7971
7972 pub fn select_to_previous_word_start(
7973 &mut self,
7974 _: &SelectToPreviousWordStart,
7975 cx: &mut ViewContext<Self>,
7976 ) {
7977 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7978 s.move_heads_with(|map, head, _| {
7979 (
7980 movement::previous_word_start(map, head),
7981 SelectionGoal::None,
7982 )
7983 });
7984 })
7985 }
7986
7987 pub fn select_to_previous_subword_start(
7988 &mut self,
7989 _: &SelectToPreviousSubwordStart,
7990 cx: &mut ViewContext<Self>,
7991 ) {
7992 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7993 s.move_heads_with(|map, head, _| {
7994 (
7995 movement::previous_subword_start(map, head),
7996 SelectionGoal::None,
7997 )
7998 });
7999 })
8000 }
8001
8002 pub fn delete_to_previous_word_start(
8003 &mut self,
8004 action: &DeleteToPreviousWordStart,
8005 cx: &mut ViewContext<Self>,
8006 ) {
8007 self.transact(cx, |this, cx| {
8008 this.select_autoclose_pair(cx);
8009 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8010 let line_mode = s.line_mode;
8011 s.move_with(|map, selection| {
8012 if selection.is_empty() && !line_mode {
8013 let cursor = if action.ignore_newlines {
8014 movement::previous_word_start(map, selection.head())
8015 } else {
8016 movement::previous_word_start_or_newline(map, selection.head())
8017 };
8018 selection.set_head(cursor, SelectionGoal::None);
8019 }
8020 });
8021 });
8022 this.insert("", cx);
8023 });
8024 }
8025
8026 pub fn delete_to_previous_subword_start(
8027 &mut self,
8028 _: &DeleteToPreviousSubwordStart,
8029 cx: &mut ViewContext<Self>,
8030 ) {
8031 self.transact(cx, |this, cx| {
8032 this.select_autoclose_pair(cx);
8033 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8034 let line_mode = s.line_mode;
8035 s.move_with(|map, selection| {
8036 if selection.is_empty() && !line_mode {
8037 let cursor = movement::previous_subword_start(map, selection.head());
8038 selection.set_head(cursor, SelectionGoal::None);
8039 }
8040 });
8041 });
8042 this.insert("", cx);
8043 });
8044 }
8045
8046 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8047 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8048 s.move_cursors_with(|map, head, _| {
8049 (movement::next_word_end(map, head), SelectionGoal::None)
8050 });
8051 })
8052 }
8053
8054 pub fn move_to_next_subword_end(
8055 &mut self,
8056 _: &MoveToNextSubwordEnd,
8057 cx: &mut ViewContext<Self>,
8058 ) {
8059 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8060 s.move_cursors_with(|map, head, _| {
8061 (movement::next_subword_end(map, head), SelectionGoal::None)
8062 });
8063 })
8064 }
8065
8066 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8068 s.move_heads_with(|map, head, _| {
8069 (movement::next_word_end(map, head), SelectionGoal::None)
8070 });
8071 })
8072 }
8073
8074 pub fn select_to_next_subword_end(
8075 &mut self,
8076 _: &SelectToNextSubwordEnd,
8077 cx: &mut ViewContext<Self>,
8078 ) {
8079 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8080 s.move_heads_with(|map, head, _| {
8081 (movement::next_subword_end(map, head), SelectionGoal::None)
8082 });
8083 })
8084 }
8085
8086 pub fn delete_to_next_word_end(
8087 &mut self,
8088 action: &DeleteToNextWordEnd,
8089 cx: &mut ViewContext<Self>,
8090 ) {
8091 self.transact(cx, |this, cx| {
8092 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8093 let line_mode = s.line_mode;
8094 s.move_with(|map, selection| {
8095 if selection.is_empty() && !line_mode {
8096 let cursor = if action.ignore_newlines {
8097 movement::next_word_end(map, selection.head())
8098 } else {
8099 movement::next_word_end_or_newline(map, selection.head())
8100 };
8101 selection.set_head(cursor, SelectionGoal::None);
8102 }
8103 });
8104 });
8105 this.insert("", cx);
8106 });
8107 }
8108
8109 pub fn delete_to_next_subword_end(
8110 &mut self,
8111 _: &DeleteToNextSubwordEnd,
8112 cx: &mut ViewContext<Self>,
8113 ) {
8114 self.transact(cx, |this, cx| {
8115 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8116 s.move_with(|map, selection| {
8117 if selection.is_empty() {
8118 let cursor = movement::next_subword_end(map, selection.head());
8119 selection.set_head(cursor, SelectionGoal::None);
8120 }
8121 });
8122 });
8123 this.insert("", cx);
8124 });
8125 }
8126
8127 pub fn move_to_beginning_of_line(
8128 &mut self,
8129 action: &MoveToBeginningOfLine,
8130 cx: &mut ViewContext<Self>,
8131 ) {
8132 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8133 s.move_cursors_with(|map, head, _| {
8134 (
8135 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8136 SelectionGoal::None,
8137 )
8138 });
8139 })
8140 }
8141
8142 pub fn select_to_beginning_of_line(
8143 &mut self,
8144 action: &SelectToBeginningOfLine,
8145 cx: &mut ViewContext<Self>,
8146 ) {
8147 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8148 s.move_heads_with(|map, head, _| {
8149 (
8150 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8151 SelectionGoal::None,
8152 )
8153 });
8154 });
8155 }
8156
8157 pub fn delete_to_beginning_of_line(
8158 &mut self,
8159 _: &DeleteToBeginningOfLine,
8160 cx: &mut ViewContext<Self>,
8161 ) {
8162 self.transact(cx, |this, cx| {
8163 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8164 s.move_with(|_, selection| {
8165 selection.reversed = true;
8166 });
8167 });
8168
8169 this.select_to_beginning_of_line(
8170 &SelectToBeginningOfLine {
8171 stop_at_soft_wraps: false,
8172 },
8173 cx,
8174 );
8175 this.backspace(&Backspace, cx);
8176 });
8177 }
8178
8179 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8180 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8181 s.move_cursors_with(|map, head, _| {
8182 (
8183 movement::line_end(map, head, action.stop_at_soft_wraps),
8184 SelectionGoal::None,
8185 )
8186 });
8187 })
8188 }
8189
8190 pub fn select_to_end_of_line(
8191 &mut self,
8192 action: &SelectToEndOfLine,
8193 cx: &mut ViewContext<Self>,
8194 ) {
8195 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8196 s.move_heads_with(|map, head, _| {
8197 (
8198 movement::line_end(map, head, action.stop_at_soft_wraps),
8199 SelectionGoal::None,
8200 )
8201 });
8202 })
8203 }
8204
8205 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8206 self.transact(cx, |this, cx| {
8207 this.select_to_end_of_line(
8208 &SelectToEndOfLine {
8209 stop_at_soft_wraps: false,
8210 },
8211 cx,
8212 );
8213 this.delete(&Delete, cx);
8214 });
8215 }
8216
8217 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8218 self.transact(cx, |this, cx| {
8219 this.select_to_end_of_line(
8220 &SelectToEndOfLine {
8221 stop_at_soft_wraps: false,
8222 },
8223 cx,
8224 );
8225 this.cut(&Cut, cx);
8226 });
8227 }
8228
8229 pub fn move_to_start_of_paragraph(
8230 &mut self,
8231 _: &MoveToStartOfParagraph,
8232 cx: &mut ViewContext<Self>,
8233 ) {
8234 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8235 cx.propagate();
8236 return;
8237 }
8238
8239 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8240 s.move_with(|map, selection| {
8241 selection.collapse_to(
8242 movement::start_of_paragraph(map, selection.head(), 1),
8243 SelectionGoal::None,
8244 )
8245 });
8246 })
8247 }
8248
8249 pub fn move_to_end_of_paragraph(
8250 &mut self,
8251 _: &MoveToEndOfParagraph,
8252 cx: &mut ViewContext<Self>,
8253 ) {
8254 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8255 cx.propagate();
8256 return;
8257 }
8258
8259 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8260 s.move_with(|map, selection| {
8261 selection.collapse_to(
8262 movement::end_of_paragraph(map, selection.head(), 1),
8263 SelectionGoal::None,
8264 )
8265 });
8266 })
8267 }
8268
8269 pub fn select_to_start_of_paragraph(
8270 &mut self,
8271 _: &SelectToStartOfParagraph,
8272 cx: &mut ViewContext<Self>,
8273 ) {
8274 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8275 cx.propagate();
8276 return;
8277 }
8278
8279 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8280 s.move_heads_with(|map, head, _| {
8281 (
8282 movement::start_of_paragraph(map, head, 1),
8283 SelectionGoal::None,
8284 )
8285 });
8286 })
8287 }
8288
8289 pub fn select_to_end_of_paragraph(
8290 &mut self,
8291 _: &SelectToEndOfParagraph,
8292 cx: &mut ViewContext<Self>,
8293 ) {
8294 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8295 cx.propagate();
8296 return;
8297 }
8298
8299 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8300 s.move_heads_with(|map, head, _| {
8301 (
8302 movement::end_of_paragraph(map, head, 1),
8303 SelectionGoal::None,
8304 )
8305 });
8306 })
8307 }
8308
8309 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8310 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8311 cx.propagate();
8312 return;
8313 }
8314
8315 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8316 s.select_ranges(vec![0..0]);
8317 });
8318 }
8319
8320 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8321 let mut selection = self.selections.last::<Point>(cx);
8322 selection.set_head(Point::zero(), SelectionGoal::None);
8323
8324 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8325 s.select(vec![selection]);
8326 });
8327 }
8328
8329 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8330 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8331 cx.propagate();
8332 return;
8333 }
8334
8335 let cursor = self.buffer.read(cx).read(cx).len();
8336 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8337 s.select_ranges(vec![cursor..cursor])
8338 });
8339 }
8340
8341 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8342 self.nav_history = nav_history;
8343 }
8344
8345 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8346 self.nav_history.as_ref()
8347 }
8348
8349 fn push_to_nav_history(
8350 &mut self,
8351 cursor_anchor: Anchor,
8352 new_position: Option<Point>,
8353 cx: &mut ViewContext<Self>,
8354 ) {
8355 if let Some(nav_history) = self.nav_history.as_mut() {
8356 let buffer = self.buffer.read(cx).read(cx);
8357 let cursor_position = cursor_anchor.to_point(&buffer);
8358 let scroll_state = self.scroll_manager.anchor();
8359 let scroll_top_row = scroll_state.top_row(&buffer);
8360 drop(buffer);
8361
8362 if let Some(new_position) = new_position {
8363 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8364 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8365 return;
8366 }
8367 }
8368
8369 nav_history.push(
8370 Some(NavigationData {
8371 cursor_anchor,
8372 cursor_position,
8373 scroll_anchor: scroll_state,
8374 scroll_top_row,
8375 }),
8376 cx,
8377 );
8378 }
8379 }
8380
8381 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8382 let buffer = self.buffer.read(cx).snapshot(cx);
8383 let mut selection = self.selections.first::<usize>(cx);
8384 selection.set_head(buffer.len(), SelectionGoal::None);
8385 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8386 s.select(vec![selection]);
8387 });
8388 }
8389
8390 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8391 let end = self.buffer.read(cx).read(cx).len();
8392 self.change_selections(None, cx, |s| {
8393 s.select_ranges(vec![0..end]);
8394 });
8395 }
8396
8397 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8399 let mut selections = self.selections.all::<Point>(cx);
8400 let max_point = display_map.buffer_snapshot.max_point();
8401 for selection in &mut selections {
8402 let rows = selection.spanned_rows(true, &display_map);
8403 selection.start = Point::new(rows.start.0, 0);
8404 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8405 selection.reversed = false;
8406 }
8407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8408 s.select(selections);
8409 });
8410 }
8411
8412 pub fn split_selection_into_lines(
8413 &mut self,
8414 _: &SplitSelectionIntoLines,
8415 cx: &mut ViewContext<Self>,
8416 ) {
8417 let mut to_unfold = Vec::new();
8418 let mut new_selection_ranges = Vec::new();
8419 {
8420 let selections = self.selections.all::<Point>(cx);
8421 let buffer = self.buffer.read(cx).read(cx);
8422 for selection in selections {
8423 for row in selection.start.row..selection.end.row {
8424 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8425 new_selection_ranges.push(cursor..cursor);
8426 }
8427 new_selection_ranges.push(selection.end..selection.end);
8428 to_unfold.push(selection.start..selection.end);
8429 }
8430 }
8431 self.unfold_ranges(&to_unfold, true, true, cx);
8432 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8433 s.select_ranges(new_selection_ranges);
8434 });
8435 }
8436
8437 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8438 self.add_selection(true, cx);
8439 }
8440
8441 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8442 self.add_selection(false, cx);
8443 }
8444
8445 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8446 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8447 let mut selections = self.selections.all::<Point>(cx);
8448 let text_layout_details = self.text_layout_details(cx);
8449 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8450 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8451 let range = oldest_selection.display_range(&display_map).sorted();
8452
8453 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8454 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8455 let positions = start_x.min(end_x)..start_x.max(end_x);
8456
8457 selections.clear();
8458 let mut stack = Vec::new();
8459 for row in range.start.row().0..=range.end.row().0 {
8460 if let Some(selection) = self.selections.build_columnar_selection(
8461 &display_map,
8462 DisplayRow(row),
8463 &positions,
8464 oldest_selection.reversed,
8465 &text_layout_details,
8466 ) {
8467 stack.push(selection.id);
8468 selections.push(selection);
8469 }
8470 }
8471
8472 if above {
8473 stack.reverse();
8474 }
8475
8476 AddSelectionsState { above, stack }
8477 });
8478
8479 let last_added_selection = *state.stack.last().unwrap();
8480 let mut new_selections = Vec::new();
8481 if above == state.above {
8482 let end_row = if above {
8483 DisplayRow(0)
8484 } else {
8485 display_map.max_point().row()
8486 };
8487
8488 'outer: for selection in selections {
8489 if selection.id == last_added_selection {
8490 let range = selection.display_range(&display_map).sorted();
8491 debug_assert_eq!(range.start.row(), range.end.row());
8492 let mut row = range.start.row();
8493 let positions =
8494 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8495 px(start)..px(end)
8496 } else {
8497 let start_x =
8498 display_map.x_for_display_point(range.start, &text_layout_details);
8499 let end_x =
8500 display_map.x_for_display_point(range.end, &text_layout_details);
8501 start_x.min(end_x)..start_x.max(end_x)
8502 };
8503
8504 while row != end_row {
8505 if above {
8506 row.0 -= 1;
8507 } else {
8508 row.0 += 1;
8509 }
8510
8511 if let Some(new_selection) = self.selections.build_columnar_selection(
8512 &display_map,
8513 row,
8514 &positions,
8515 selection.reversed,
8516 &text_layout_details,
8517 ) {
8518 state.stack.push(new_selection.id);
8519 if above {
8520 new_selections.push(new_selection);
8521 new_selections.push(selection);
8522 } else {
8523 new_selections.push(selection);
8524 new_selections.push(new_selection);
8525 }
8526
8527 continue 'outer;
8528 }
8529 }
8530 }
8531
8532 new_selections.push(selection);
8533 }
8534 } else {
8535 new_selections = selections;
8536 new_selections.retain(|s| s.id != last_added_selection);
8537 state.stack.pop();
8538 }
8539
8540 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8541 s.select(new_selections);
8542 });
8543 if state.stack.len() > 1 {
8544 self.add_selections_state = Some(state);
8545 }
8546 }
8547
8548 pub fn select_next_match_internal(
8549 &mut self,
8550 display_map: &DisplaySnapshot,
8551 replace_newest: bool,
8552 autoscroll: Option<Autoscroll>,
8553 cx: &mut ViewContext<Self>,
8554 ) -> Result<()> {
8555 fn select_next_match_ranges(
8556 this: &mut Editor,
8557 range: Range<usize>,
8558 replace_newest: bool,
8559 auto_scroll: Option<Autoscroll>,
8560 cx: &mut ViewContext<Editor>,
8561 ) {
8562 this.unfold_ranges(&[range.clone()], false, true, cx);
8563 this.change_selections(auto_scroll, cx, |s| {
8564 if replace_newest {
8565 s.delete(s.newest_anchor().id);
8566 }
8567 s.insert_range(range.clone());
8568 });
8569 }
8570
8571 let buffer = &display_map.buffer_snapshot;
8572 let mut selections = self.selections.all::<usize>(cx);
8573 if let Some(mut select_next_state) = self.select_next_state.take() {
8574 let query = &select_next_state.query;
8575 if !select_next_state.done {
8576 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8577 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8578 let mut next_selected_range = None;
8579
8580 let bytes_after_last_selection =
8581 buffer.bytes_in_range(last_selection.end..buffer.len());
8582 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8583 let query_matches = query
8584 .stream_find_iter(bytes_after_last_selection)
8585 .map(|result| (last_selection.end, result))
8586 .chain(
8587 query
8588 .stream_find_iter(bytes_before_first_selection)
8589 .map(|result| (0, result)),
8590 );
8591
8592 for (start_offset, query_match) in query_matches {
8593 let query_match = query_match.unwrap(); // can only fail due to I/O
8594 let offset_range =
8595 start_offset + query_match.start()..start_offset + query_match.end();
8596 let display_range = offset_range.start.to_display_point(display_map)
8597 ..offset_range.end.to_display_point(display_map);
8598
8599 if !select_next_state.wordwise
8600 || (!movement::is_inside_word(display_map, display_range.start)
8601 && !movement::is_inside_word(display_map, display_range.end))
8602 {
8603 // TODO: This is n^2, because we might check all the selections
8604 if !selections
8605 .iter()
8606 .any(|selection| selection.range().overlaps(&offset_range))
8607 {
8608 next_selected_range = Some(offset_range);
8609 break;
8610 }
8611 }
8612 }
8613
8614 if let Some(next_selected_range) = next_selected_range {
8615 select_next_match_ranges(
8616 self,
8617 next_selected_range,
8618 replace_newest,
8619 autoscroll,
8620 cx,
8621 );
8622 } else {
8623 select_next_state.done = true;
8624 }
8625 }
8626
8627 self.select_next_state = Some(select_next_state);
8628 } else {
8629 let mut only_carets = true;
8630 let mut same_text_selected = true;
8631 let mut selected_text = None;
8632
8633 let mut selections_iter = selections.iter().peekable();
8634 while let Some(selection) = selections_iter.next() {
8635 if selection.start != selection.end {
8636 only_carets = false;
8637 }
8638
8639 if same_text_selected {
8640 if selected_text.is_none() {
8641 selected_text =
8642 Some(buffer.text_for_range(selection.range()).collect::<String>());
8643 }
8644
8645 if let Some(next_selection) = selections_iter.peek() {
8646 if next_selection.range().len() == selection.range().len() {
8647 let next_selected_text = buffer
8648 .text_for_range(next_selection.range())
8649 .collect::<String>();
8650 if Some(next_selected_text) != selected_text {
8651 same_text_selected = false;
8652 selected_text = None;
8653 }
8654 } else {
8655 same_text_selected = false;
8656 selected_text = None;
8657 }
8658 }
8659 }
8660 }
8661
8662 if only_carets {
8663 for selection in &mut selections {
8664 let word_range = movement::surrounding_word(
8665 display_map,
8666 selection.start.to_display_point(display_map),
8667 );
8668 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8669 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8670 selection.goal = SelectionGoal::None;
8671 selection.reversed = false;
8672 select_next_match_ranges(
8673 self,
8674 selection.start..selection.end,
8675 replace_newest,
8676 autoscroll,
8677 cx,
8678 );
8679 }
8680
8681 if selections.len() == 1 {
8682 let selection = selections
8683 .last()
8684 .expect("ensured that there's only one selection");
8685 let query = buffer
8686 .text_for_range(selection.start..selection.end)
8687 .collect::<String>();
8688 let is_empty = query.is_empty();
8689 let select_state = SelectNextState {
8690 query: AhoCorasick::new(&[query])?,
8691 wordwise: true,
8692 done: is_empty,
8693 };
8694 self.select_next_state = Some(select_state);
8695 } else {
8696 self.select_next_state = None;
8697 }
8698 } else if let Some(selected_text) = selected_text {
8699 self.select_next_state = Some(SelectNextState {
8700 query: AhoCorasick::new(&[selected_text])?,
8701 wordwise: false,
8702 done: false,
8703 });
8704 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8705 }
8706 }
8707 Ok(())
8708 }
8709
8710 pub fn select_all_matches(
8711 &mut self,
8712 _action: &SelectAllMatches,
8713 cx: &mut ViewContext<Self>,
8714 ) -> Result<()> {
8715 self.push_to_selection_history();
8716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8717
8718 self.select_next_match_internal(&display_map, false, None, cx)?;
8719 let Some(select_next_state) = self.select_next_state.as_mut() else {
8720 return Ok(());
8721 };
8722 if select_next_state.done {
8723 return Ok(());
8724 }
8725
8726 let mut new_selections = self.selections.all::<usize>(cx);
8727
8728 let buffer = &display_map.buffer_snapshot;
8729 let query_matches = select_next_state
8730 .query
8731 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8732
8733 for query_match in query_matches {
8734 let query_match = query_match.unwrap(); // can only fail due to I/O
8735 let offset_range = query_match.start()..query_match.end();
8736 let display_range = offset_range.start.to_display_point(&display_map)
8737 ..offset_range.end.to_display_point(&display_map);
8738
8739 if !select_next_state.wordwise
8740 || (!movement::is_inside_word(&display_map, display_range.start)
8741 && !movement::is_inside_word(&display_map, display_range.end))
8742 {
8743 self.selections.change_with(cx, |selections| {
8744 new_selections.push(Selection {
8745 id: selections.new_selection_id(),
8746 start: offset_range.start,
8747 end: offset_range.end,
8748 reversed: false,
8749 goal: SelectionGoal::None,
8750 });
8751 });
8752 }
8753 }
8754
8755 new_selections.sort_by_key(|selection| selection.start);
8756 let mut ix = 0;
8757 while ix + 1 < new_selections.len() {
8758 let current_selection = &new_selections[ix];
8759 let next_selection = &new_selections[ix + 1];
8760 if current_selection.range().overlaps(&next_selection.range()) {
8761 if current_selection.id < next_selection.id {
8762 new_selections.remove(ix + 1);
8763 } else {
8764 new_selections.remove(ix);
8765 }
8766 } else {
8767 ix += 1;
8768 }
8769 }
8770
8771 select_next_state.done = true;
8772 self.unfold_ranges(
8773 &new_selections
8774 .iter()
8775 .map(|selection| selection.range())
8776 .collect::<Vec<_>>(),
8777 false,
8778 false,
8779 cx,
8780 );
8781 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8782 selections.select(new_selections)
8783 });
8784
8785 Ok(())
8786 }
8787
8788 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8789 self.push_to_selection_history();
8790 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8791 self.select_next_match_internal(
8792 &display_map,
8793 action.replace_newest,
8794 Some(Autoscroll::newest()),
8795 cx,
8796 )?;
8797 Ok(())
8798 }
8799
8800 pub fn select_previous(
8801 &mut self,
8802 action: &SelectPrevious,
8803 cx: &mut ViewContext<Self>,
8804 ) -> Result<()> {
8805 self.push_to_selection_history();
8806 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8807 let buffer = &display_map.buffer_snapshot;
8808 let mut selections = self.selections.all::<usize>(cx);
8809 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8810 let query = &select_prev_state.query;
8811 if !select_prev_state.done {
8812 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8813 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8814 let mut next_selected_range = None;
8815 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8816 let bytes_before_last_selection =
8817 buffer.reversed_bytes_in_range(0..last_selection.start);
8818 let bytes_after_first_selection =
8819 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8820 let query_matches = query
8821 .stream_find_iter(bytes_before_last_selection)
8822 .map(|result| (last_selection.start, result))
8823 .chain(
8824 query
8825 .stream_find_iter(bytes_after_first_selection)
8826 .map(|result| (buffer.len(), result)),
8827 );
8828 for (end_offset, query_match) in query_matches {
8829 let query_match = query_match.unwrap(); // can only fail due to I/O
8830 let offset_range =
8831 end_offset - query_match.end()..end_offset - query_match.start();
8832 let display_range = offset_range.start.to_display_point(&display_map)
8833 ..offset_range.end.to_display_point(&display_map);
8834
8835 if !select_prev_state.wordwise
8836 || (!movement::is_inside_word(&display_map, display_range.start)
8837 && !movement::is_inside_word(&display_map, display_range.end))
8838 {
8839 next_selected_range = Some(offset_range);
8840 break;
8841 }
8842 }
8843
8844 if let Some(next_selected_range) = next_selected_range {
8845 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8846 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8847 if action.replace_newest {
8848 s.delete(s.newest_anchor().id);
8849 }
8850 s.insert_range(next_selected_range);
8851 });
8852 } else {
8853 select_prev_state.done = true;
8854 }
8855 }
8856
8857 self.select_prev_state = Some(select_prev_state);
8858 } else {
8859 let mut only_carets = true;
8860 let mut same_text_selected = true;
8861 let mut selected_text = None;
8862
8863 let mut selections_iter = selections.iter().peekable();
8864 while let Some(selection) = selections_iter.next() {
8865 if selection.start != selection.end {
8866 only_carets = false;
8867 }
8868
8869 if same_text_selected {
8870 if selected_text.is_none() {
8871 selected_text =
8872 Some(buffer.text_for_range(selection.range()).collect::<String>());
8873 }
8874
8875 if let Some(next_selection) = selections_iter.peek() {
8876 if next_selection.range().len() == selection.range().len() {
8877 let next_selected_text = buffer
8878 .text_for_range(next_selection.range())
8879 .collect::<String>();
8880 if Some(next_selected_text) != selected_text {
8881 same_text_selected = false;
8882 selected_text = None;
8883 }
8884 } else {
8885 same_text_selected = false;
8886 selected_text = None;
8887 }
8888 }
8889 }
8890 }
8891
8892 if only_carets {
8893 for selection in &mut selections {
8894 let word_range = movement::surrounding_word(
8895 &display_map,
8896 selection.start.to_display_point(&display_map),
8897 );
8898 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8899 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8900 selection.goal = SelectionGoal::None;
8901 selection.reversed = false;
8902 }
8903 if selections.len() == 1 {
8904 let selection = selections
8905 .last()
8906 .expect("ensured that there's only one selection");
8907 let query = buffer
8908 .text_for_range(selection.start..selection.end)
8909 .collect::<String>();
8910 let is_empty = query.is_empty();
8911 let select_state = SelectNextState {
8912 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8913 wordwise: true,
8914 done: is_empty,
8915 };
8916 self.select_prev_state = Some(select_state);
8917 } else {
8918 self.select_prev_state = None;
8919 }
8920
8921 self.unfold_ranges(
8922 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8923 false,
8924 true,
8925 cx,
8926 );
8927 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8928 s.select(selections);
8929 });
8930 } else if let Some(selected_text) = selected_text {
8931 self.select_prev_state = Some(SelectNextState {
8932 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8933 wordwise: false,
8934 done: false,
8935 });
8936 self.select_previous(action, cx)?;
8937 }
8938 }
8939 Ok(())
8940 }
8941
8942 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8943 if self.read_only(cx) {
8944 return;
8945 }
8946 let text_layout_details = &self.text_layout_details(cx);
8947 self.transact(cx, |this, cx| {
8948 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8949 let mut edits = Vec::new();
8950 let mut selection_edit_ranges = Vec::new();
8951 let mut last_toggled_row = None;
8952 let snapshot = this.buffer.read(cx).read(cx);
8953 let empty_str: Arc<str> = Arc::default();
8954 let mut suffixes_inserted = Vec::new();
8955 let ignore_indent = action.ignore_indent;
8956
8957 fn comment_prefix_range(
8958 snapshot: &MultiBufferSnapshot,
8959 row: MultiBufferRow,
8960 comment_prefix: &str,
8961 comment_prefix_whitespace: &str,
8962 ignore_indent: bool,
8963 ) -> Range<Point> {
8964 let indent_size = if ignore_indent {
8965 0
8966 } else {
8967 snapshot.indent_size_for_line(row).len
8968 };
8969
8970 let start = Point::new(row.0, indent_size);
8971
8972 let mut line_bytes = snapshot
8973 .bytes_in_range(start..snapshot.max_point())
8974 .flatten()
8975 .copied();
8976
8977 // If this line currently begins with the line comment prefix, then record
8978 // the range containing the prefix.
8979 if line_bytes
8980 .by_ref()
8981 .take(comment_prefix.len())
8982 .eq(comment_prefix.bytes())
8983 {
8984 // Include any whitespace that matches the comment prefix.
8985 let matching_whitespace_len = line_bytes
8986 .zip(comment_prefix_whitespace.bytes())
8987 .take_while(|(a, b)| a == b)
8988 .count() as u32;
8989 let end = Point::new(
8990 start.row,
8991 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8992 );
8993 start..end
8994 } else {
8995 start..start
8996 }
8997 }
8998
8999 fn comment_suffix_range(
9000 snapshot: &MultiBufferSnapshot,
9001 row: MultiBufferRow,
9002 comment_suffix: &str,
9003 comment_suffix_has_leading_space: bool,
9004 ) -> Range<Point> {
9005 let end = Point::new(row.0, snapshot.line_len(row));
9006 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9007
9008 let mut line_end_bytes = snapshot
9009 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9010 .flatten()
9011 .copied();
9012
9013 let leading_space_len = if suffix_start_column > 0
9014 && line_end_bytes.next() == Some(b' ')
9015 && comment_suffix_has_leading_space
9016 {
9017 1
9018 } else {
9019 0
9020 };
9021
9022 // If this line currently begins with the line comment prefix, then record
9023 // the range containing the prefix.
9024 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9025 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9026 start..end
9027 } else {
9028 end..end
9029 }
9030 }
9031
9032 // TODO: Handle selections that cross excerpts
9033 for selection in &mut selections {
9034 let start_column = snapshot
9035 .indent_size_for_line(MultiBufferRow(selection.start.row))
9036 .len;
9037 let language = if let Some(language) =
9038 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9039 {
9040 language
9041 } else {
9042 continue;
9043 };
9044
9045 selection_edit_ranges.clear();
9046
9047 // If multiple selections contain a given row, avoid processing that
9048 // row more than once.
9049 let mut start_row = MultiBufferRow(selection.start.row);
9050 if last_toggled_row == Some(start_row) {
9051 start_row = start_row.next_row();
9052 }
9053 let end_row =
9054 if selection.end.row > selection.start.row && selection.end.column == 0 {
9055 MultiBufferRow(selection.end.row - 1)
9056 } else {
9057 MultiBufferRow(selection.end.row)
9058 };
9059 last_toggled_row = Some(end_row);
9060
9061 if start_row > end_row {
9062 continue;
9063 }
9064
9065 // If the language has line comments, toggle those.
9066 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9067
9068 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9069 if ignore_indent {
9070 full_comment_prefixes = full_comment_prefixes
9071 .into_iter()
9072 .map(|s| Arc::from(s.trim_end()))
9073 .collect();
9074 }
9075
9076 if !full_comment_prefixes.is_empty() {
9077 let first_prefix = full_comment_prefixes
9078 .first()
9079 .expect("prefixes is non-empty");
9080 let prefix_trimmed_lengths = full_comment_prefixes
9081 .iter()
9082 .map(|p| p.trim_end_matches(' ').len())
9083 .collect::<SmallVec<[usize; 4]>>();
9084
9085 let mut all_selection_lines_are_comments = true;
9086
9087 for row in start_row.0..=end_row.0 {
9088 let row = MultiBufferRow(row);
9089 if start_row < end_row && snapshot.is_line_blank(row) {
9090 continue;
9091 }
9092
9093 let prefix_range = full_comment_prefixes
9094 .iter()
9095 .zip(prefix_trimmed_lengths.iter().copied())
9096 .map(|(prefix, trimmed_prefix_len)| {
9097 comment_prefix_range(
9098 snapshot.deref(),
9099 row,
9100 &prefix[..trimmed_prefix_len],
9101 &prefix[trimmed_prefix_len..],
9102 ignore_indent,
9103 )
9104 })
9105 .max_by_key(|range| range.end.column - range.start.column)
9106 .expect("prefixes is non-empty");
9107
9108 if prefix_range.is_empty() {
9109 all_selection_lines_are_comments = false;
9110 }
9111
9112 selection_edit_ranges.push(prefix_range);
9113 }
9114
9115 if all_selection_lines_are_comments {
9116 edits.extend(
9117 selection_edit_ranges
9118 .iter()
9119 .cloned()
9120 .map(|range| (range, empty_str.clone())),
9121 );
9122 } else {
9123 let min_column = selection_edit_ranges
9124 .iter()
9125 .map(|range| range.start.column)
9126 .min()
9127 .unwrap_or(0);
9128 edits.extend(selection_edit_ranges.iter().map(|range| {
9129 let position = Point::new(range.start.row, min_column);
9130 (position..position, first_prefix.clone())
9131 }));
9132 }
9133 } else if let Some((full_comment_prefix, comment_suffix)) =
9134 language.block_comment_delimiters()
9135 {
9136 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9137 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9138 let prefix_range = comment_prefix_range(
9139 snapshot.deref(),
9140 start_row,
9141 comment_prefix,
9142 comment_prefix_whitespace,
9143 ignore_indent,
9144 );
9145 let suffix_range = comment_suffix_range(
9146 snapshot.deref(),
9147 end_row,
9148 comment_suffix.trim_start_matches(' '),
9149 comment_suffix.starts_with(' '),
9150 );
9151
9152 if prefix_range.is_empty() || suffix_range.is_empty() {
9153 edits.push((
9154 prefix_range.start..prefix_range.start,
9155 full_comment_prefix.clone(),
9156 ));
9157 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9158 suffixes_inserted.push((end_row, comment_suffix.len()));
9159 } else {
9160 edits.push((prefix_range, empty_str.clone()));
9161 edits.push((suffix_range, empty_str.clone()));
9162 }
9163 } else {
9164 continue;
9165 }
9166 }
9167
9168 drop(snapshot);
9169 this.buffer.update(cx, |buffer, cx| {
9170 buffer.edit(edits, None, cx);
9171 });
9172
9173 // Adjust selections so that they end before any comment suffixes that
9174 // were inserted.
9175 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9176 let mut selections = this.selections.all::<Point>(cx);
9177 let snapshot = this.buffer.read(cx).read(cx);
9178 for selection in &mut selections {
9179 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9180 match row.cmp(&MultiBufferRow(selection.end.row)) {
9181 Ordering::Less => {
9182 suffixes_inserted.next();
9183 continue;
9184 }
9185 Ordering::Greater => break,
9186 Ordering::Equal => {
9187 if selection.end.column == snapshot.line_len(row) {
9188 if selection.is_empty() {
9189 selection.start.column -= suffix_len as u32;
9190 }
9191 selection.end.column -= suffix_len as u32;
9192 }
9193 break;
9194 }
9195 }
9196 }
9197 }
9198
9199 drop(snapshot);
9200 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9201
9202 let selections = this.selections.all::<Point>(cx);
9203 let selections_on_single_row = selections.windows(2).all(|selections| {
9204 selections[0].start.row == selections[1].start.row
9205 && selections[0].end.row == selections[1].end.row
9206 && selections[0].start.row == selections[0].end.row
9207 });
9208 let selections_selecting = selections
9209 .iter()
9210 .any(|selection| selection.start != selection.end);
9211 let advance_downwards = action.advance_downwards
9212 && selections_on_single_row
9213 && !selections_selecting
9214 && !matches!(this.mode, EditorMode::SingleLine { .. });
9215
9216 if advance_downwards {
9217 let snapshot = this.buffer.read(cx).snapshot(cx);
9218
9219 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9220 s.move_cursors_with(|display_snapshot, display_point, _| {
9221 let mut point = display_point.to_point(display_snapshot);
9222 point.row += 1;
9223 point = snapshot.clip_point(point, Bias::Left);
9224 let display_point = point.to_display_point(display_snapshot);
9225 let goal = SelectionGoal::HorizontalPosition(
9226 display_snapshot
9227 .x_for_display_point(display_point, text_layout_details)
9228 .into(),
9229 );
9230 (display_point, goal)
9231 })
9232 });
9233 }
9234 });
9235 }
9236
9237 pub fn select_enclosing_symbol(
9238 &mut self,
9239 _: &SelectEnclosingSymbol,
9240 cx: &mut ViewContext<Self>,
9241 ) {
9242 let buffer = self.buffer.read(cx).snapshot(cx);
9243 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9244
9245 fn update_selection(
9246 selection: &Selection<usize>,
9247 buffer_snap: &MultiBufferSnapshot,
9248 ) -> Option<Selection<usize>> {
9249 let cursor = selection.head();
9250 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9251 for symbol in symbols.iter().rev() {
9252 let start = symbol.range.start.to_offset(buffer_snap);
9253 let end = symbol.range.end.to_offset(buffer_snap);
9254 let new_range = start..end;
9255 if start < selection.start || end > selection.end {
9256 return Some(Selection {
9257 id: selection.id,
9258 start: new_range.start,
9259 end: new_range.end,
9260 goal: SelectionGoal::None,
9261 reversed: selection.reversed,
9262 });
9263 }
9264 }
9265 None
9266 }
9267
9268 let mut selected_larger_symbol = false;
9269 let new_selections = old_selections
9270 .iter()
9271 .map(|selection| match update_selection(selection, &buffer) {
9272 Some(new_selection) => {
9273 if new_selection.range() != selection.range() {
9274 selected_larger_symbol = true;
9275 }
9276 new_selection
9277 }
9278 None => selection.clone(),
9279 })
9280 .collect::<Vec<_>>();
9281
9282 if selected_larger_symbol {
9283 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9284 s.select(new_selections);
9285 });
9286 }
9287 }
9288
9289 pub fn select_larger_syntax_node(
9290 &mut self,
9291 _: &SelectLargerSyntaxNode,
9292 cx: &mut ViewContext<Self>,
9293 ) {
9294 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9295 let buffer = self.buffer.read(cx).snapshot(cx);
9296 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9297
9298 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9299 let mut selected_larger_node = false;
9300 let new_selections = old_selections
9301 .iter()
9302 .map(|selection| {
9303 let old_range = selection.start..selection.end;
9304 let mut new_range = old_range.clone();
9305 while let Some(containing_range) =
9306 buffer.range_for_syntax_ancestor(new_range.clone())
9307 {
9308 new_range = containing_range;
9309 if !display_map.intersects_fold(new_range.start)
9310 && !display_map.intersects_fold(new_range.end)
9311 {
9312 break;
9313 }
9314 }
9315
9316 selected_larger_node |= new_range != old_range;
9317 Selection {
9318 id: selection.id,
9319 start: new_range.start,
9320 end: new_range.end,
9321 goal: SelectionGoal::None,
9322 reversed: selection.reversed,
9323 }
9324 })
9325 .collect::<Vec<_>>();
9326
9327 if selected_larger_node {
9328 stack.push(old_selections);
9329 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9330 s.select(new_selections);
9331 });
9332 }
9333 self.select_larger_syntax_node_stack = stack;
9334 }
9335
9336 pub fn select_smaller_syntax_node(
9337 &mut self,
9338 _: &SelectSmallerSyntaxNode,
9339 cx: &mut ViewContext<Self>,
9340 ) {
9341 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9342 if let Some(selections) = stack.pop() {
9343 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9344 s.select(selections.to_vec());
9345 });
9346 }
9347 self.select_larger_syntax_node_stack = stack;
9348 }
9349
9350 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9351 if !EditorSettings::get_global(cx).gutter.runnables {
9352 self.clear_tasks();
9353 return Task::ready(());
9354 }
9355 let project = self.project.as_ref().map(Model::downgrade);
9356 cx.spawn(|this, mut cx| async move {
9357 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9358 let Some(project) = project.and_then(|p| p.upgrade()) else {
9359 return;
9360 };
9361 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9362 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9363 }) else {
9364 return;
9365 };
9366
9367 let hide_runnables = project
9368 .update(&mut cx, |project, cx| {
9369 // Do not display any test indicators in non-dev server remote projects.
9370 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9371 })
9372 .unwrap_or(true);
9373 if hide_runnables {
9374 return;
9375 }
9376 let new_rows =
9377 cx.background_executor()
9378 .spawn({
9379 let snapshot = display_snapshot.clone();
9380 async move {
9381 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9382 }
9383 })
9384 .await;
9385 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9386
9387 this.update(&mut cx, |this, _| {
9388 this.clear_tasks();
9389 for (key, value) in rows {
9390 this.insert_tasks(key, value);
9391 }
9392 })
9393 .ok();
9394 })
9395 }
9396 fn fetch_runnable_ranges(
9397 snapshot: &DisplaySnapshot,
9398 range: Range<Anchor>,
9399 ) -> Vec<language::RunnableRange> {
9400 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9401 }
9402
9403 fn runnable_rows(
9404 project: Model<Project>,
9405 snapshot: DisplaySnapshot,
9406 runnable_ranges: Vec<RunnableRange>,
9407 mut cx: AsyncWindowContext,
9408 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9409 runnable_ranges
9410 .into_iter()
9411 .filter_map(|mut runnable| {
9412 let tasks = cx
9413 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9414 .ok()?;
9415 if tasks.is_empty() {
9416 return None;
9417 }
9418
9419 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9420
9421 let row = snapshot
9422 .buffer_snapshot
9423 .buffer_line_for_row(MultiBufferRow(point.row))?
9424 .1
9425 .start
9426 .row;
9427
9428 let context_range =
9429 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9430 Some((
9431 (runnable.buffer_id, row),
9432 RunnableTasks {
9433 templates: tasks,
9434 offset: MultiBufferOffset(runnable.run_range.start),
9435 context_range,
9436 column: point.column,
9437 extra_variables: runnable.extra_captures,
9438 },
9439 ))
9440 })
9441 .collect()
9442 }
9443
9444 fn templates_with_tags(
9445 project: &Model<Project>,
9446 runnable: &mut Runnable,
9447 cx: &WindowContext<'_>,
9448 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9449 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9450 let (worktree_id, file) = project
9451 .buffer_for_id(runnable.buffer, cx)
9452 .and_then(|buffer| buffer.read(cx).file())
9453 .map(|file| (file.worktree_id(cx), file.clone()))
9454 .unzip();
9455
9456 (
9457 project.task_store().read(cx).task_inventory().cloned(),
9458 worktree_id,
9459 file,
9460 )
9461 });
9462
9463 let tags = mem::take(&mut runnable.tags);
9464 let mut tags: Vec<_> = tags
9465 .into_iter()
9466 .flat_map(|tag| {
9467 let tag = tag.0.clone();
9468 inventory
9469 .as_ref()
9470 .into_iter()
9471 .flat_map(|inventory| {
9472 inventory.read(cx).list_tasks(
9473 file.clone(),
9474 Some(runnable.language.clone()),
9475 worktree_id,
9476 cx,
9477 )
9478 })
9479 .filter(move |(_, template)| {
9480 template.tags.iter().any(|source_tag| source_tag == &tag)
9481 })
9482 })
9483 .sorted_by_key(|(kind, _)| kind.to_owned())
9484 .collect();
9485 if let Some((leading_tag_source, _)) = tags.first() {
9486 // Strongest source wins; if we have worktree tag binding, prefer that to
9487 // global and language bindings;
9488 // if we have a global binding, prefer that to language binding.
9489 let first_mismatch = tags
9490 .iter()
9491 .position(|(tag_source, _)| tag_source != leading_tag_source);
9492 if let Some(index) = first_mismatch {
9493 tags.truncate(index);
9494 }
9495 }
9496
9497 tags
9498 }
9499
9500 pub fn move_to_enclosing_bracket(
9501 &mut self,
9502 _: &MoveToEnclosingBracket,
9503 cx: &mut ViewContext<Self>,
9504 ) {
9505 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9506 s.move_offsets_with(|snapshot, selection| {
9507 let Some(enclosing_bracket_ranges) =
9508 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9509 else {
9510 return;
9511 };
9512
9513 let mut best_length = usize::MAX;
9514 let mut best_inside = false;
9515 let mut best_in_bracket_range = false;
9516 let mut best_destination = None;
9517 for (open, close) in enclosing_bracket_ranges {
9518 let close = close.to_inclusive();
9519 let length = close.end() - open.start;
9520 let inside = selection.start >= open.end && selection.end <= *close.start();
9521 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9522 || close.contains(&selection.head());
9523
9524 // If best is next to a bracket and current isn't, skip
9525 if !in_bracket_range && best_in_bracket_range {
9526 continue;
9527 }
9528
9529 // Prefer smaller lengths unless best is inside and current isn't
9530 if length > best_length && (best_inside || !inside) {
9531 continue;
9532 }
9533
9534 best_length = length;
9535 best_inside = inside;
9536 best_in_bracket_range = in_bracket_range;
9537 best_destination = Some(
9538 if close.contains(&selection.start) && close.contains(&selection.end) {
9539 if inside {
9540 open.end
9541 } else {
9542 open.start
9543 }
9544 } else if inside {
9545 *close.start()
9546 } else {
9547 *close.end()
9548 },
9549 );
9550 }
9551
9552 if let Some(destination) = best_destination {
9553 selection.collapse_to(destination, SelectionGoal::None);
9554 }
9555 })
9556 });
9557 }
9558
9559 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9560 self.end_selection(cx);
9561 self.selection_history.mode = SelectionHistoryMode::Undoing;
9562 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9563 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9564 self.select_next_state = entry.select_next_state;
9565 self.select_prev_state = entry.select_prev_state;
9566 self.add_selections_state = entry.add_selections_state;
9567 self.request_autoscroll(Autoscroll::newest(), cx);
9568 }
9569 self.selection_history.mode = SelectionHistoryMode::Normal;
9570 }
9571
9572 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9573 self.end_selection(cx);
9574 self.selection_history.mode = SelectionHistoryMode::Redoing;
9575 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9576 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9577 self.select_next_state = entry.select_next_state;
9578 self.select_prev_state = entry.select_prev_state;
9579 self.add_selections_state = entry.add_selections_state;
9580 self.request_autoscroll(Autoscroll::newest(), cx);
9581 }
9582 self.selection_history.mode = SelectionHistoryMode::Normal;
9583 }
9584
9585 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9586 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9587 }
9588
9589 pub fn expand_excerpts_down(
9590 &mut self,
9591 action: &ExpandExcerptsDown,
9592 cx: &mut ViewContext<Self>,
9593 ) {
9594 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9595 }
9596
9597 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9598 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9599 }
9600
9601 pub fn expand_excerpts_for_direction(
9602 &mut self,
9603 lines: u32,
9604 direction: ExpandExcerptDirection,
9605 cx: &mut ViewContext<Self>,
9606 ) {
9607 let selections = self.selections.disjoint_anchors();
9608
9609 let lines = if lines == 0 {
9610 EditorSettings::get_global(cx).expand_excerpt_lines
9611 } else {
9612 lines
9613 };
9614
9615 self.buffer.update(cx, |buffer, cx| {
9616 buffer.expand_excerpts(
9617 selections
9618 .iter()
9619 .map(|selection| selection.head().excerpt_id)
9620 .dedup(),
9621 lines,
9622 direction,
9623 cx,
9624 )
9625 })
9626 }
9627
9628 pub fn expand_excerpt(
9629 &mut self,
9630 excerpt: ExcerptId,
9631 direction: ExpandExcerptDirection,
9632 cx: &mut ViewContext<Self>,
9633 ) {
9634 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9635 self.buffer.update(cx, |buffer, cx| {
9636 buffer.expand_excerpts([excerpt], lines, direction, cx)
9637 })
9638 }
9639
9640 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9641 self.go_to_diagnostic_impl(Direction::Next, cx)
9642 }
9643
9644 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9645 self.go_to_diagnostic_impl(Direction::Prev, cx)
9646 }
9647
9648 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9649 let buffer = self.buffer.read(cx).snapshot(cx);
9650 let selection = self.selections.newest::<usize>(cx);
9651
9652 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9653 if direction == Direction::Next {
9654 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9655 let (group_id, jump_to) = popover.activation_info();
9656 if self.activate_diagnostics(group_id, cx) {
9657 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9658 let mut new_selection = s.newest_anchor().clone();
9659 new_selection.collapse_to(jump_to, SelectionGoal::None);
9660 s.select_anchors(vec![new_selection.clone()]);
9661 });
9662 }
9663 return;
9664 }
9665 }
9666
9667 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9668 active_diagnostics
9669 .primary_range
9670 .to_offset(&buffer)
9671 .to_inclusive()
9672 });
9673 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9674 if active_primary_range.contains(&selection.head()) {
9675 *active_primary_range.start()
9676 } else {
9677 selection.head()
9678 }
9679 } else {
9680 selection.head()
9681 };
9682 let snapshot = self.snapshot(cx);
9683 loop {
9684 let diagnostics = if direction == Direction::Prev {
9685 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9686 } else {
9687 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9688 }
9689 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9690 let group = diagnostics
9691 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9692 // be sorted in a stable way
9693 // skip until we are at current active diagnostic, if it exists
9694 .skip_while(|entry| {
9695 (match direction {
9696 Direction::Prev => entry.range.start >= search_start,
9697 Direction::Next => entry.range.start <= search_start,
9698 }) && self
9699 .active_diagnostics
9700 .as_ref()
9701 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9702 })
9703 .find_map(|entry| {
9704 if entry.diagnostic.is_primary
9705 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9706 && !entry.range.is_empty()
9707 // if we match with the active diagnostic, skip it
9708 && Some(entry.diagnostic.group_id)
9709 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9710 {
9711 Some((entry.range, entry.diagnostic.group_id))
9712 } else {
9713 None
9714 }
9715 });
9716
9717 if let Some((primary_range, group_id)) = group {
9718 if self.activate_diagnostics(group_id, cx) {
9719 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9720 s.select(vec![Selection {
9721 id: selection.id,
9722 start: primary_range.start,
9723 end: primary_range.start,
9724 reversed: false,
9725 goal: SelectionGoal::None,
9726 }]);
9727 });
9728 }
9729 break;
9730 } else {
9731 // Cycle around to the start of the buffer, potentially moving back to the start of
9732 // the currently active diagnostic.
9733 active_primary_range.take();
9734 if direction == Direction::Prev {
9735 if search_start == buffer.len() {
9736 break;
9737 } else {
9738 search_start = buffer.len();
9739 }
9740 } else if search_start == 0 {
9741 break;
9742 } else {
9743 search_start = 0;
9744 }
9745 }
9746 }
9747 }
9748
9749 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9750 let snapshot = self
9751 .display_map
9752 .update(cx, |display_map, cx| display_map.snapshot(cx));
9753 let selection = self.selections.newest::<Point>(cx);
9754 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9755 }
9756
9757 fn go_to_hunk_after_position(
9758 &mut self,
9759 snapshot: &DisplaySnapshot,
9760 position: Point,
9761 cx: &mut ViewContext<'_, Editor>,
9762 ) -> Option<MultiBufferDiffHunk> {
9763 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9764 snapshot,
9765 position,
9766 false,
9767 snapshot
9768 .buffer_snapshot
9769 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9770 cx,
9771 ) {
9772 return Some(hunk);
9773 }
9774
9775 let wrapped_point = Point::zero();
9776 self.go_to_next_hunk_in_direction(
9777 snapshot,
9778 wrapped_point,
9779 true,
9780 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9781 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9782 ),
9783 cx,
9784 )
9785 }
9786
9787 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9788 let snapshot = self
9789 .display_map
9790 .update(cx, |display_map, cx| display_map.snapshot(cx));
9791 let selection = self.selections.newest::<Point>(cx);
9792
9793 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9794 }
9795
9796 fn go_to_hunk_before_position(
9797 &mut self,
9798 snapshot: &DisplaySnapshot,
9799 position: Point,
9800 cx: &mut ViewContext<'_, Editor>,
9801 ) -> Option<MultiBufferDiffHunk> {
9802 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9803 snapshot,
9804 position,
9805 false,
9806 snapshot
9807 .buffer_snapshot
9808 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9809 cx,
9810 ) {
9811 return Some(hunk);
9812 }
9813
9814 let wrapped_point = snapshot.buffer_snapshot.max_point();
9815 self.go_to_next_hunk_in_direction(
9816 snapshot,
9817 wrapped_point,
9818 true,
9819 snapshot
9820 .buffer_snapshot
9821 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9822 cx,
9823 )
9824 }
9825
9826 fn go_to_next_hunk_in_direction(
9827 &mut self,
9828 snapshot: &DisplaySnapshot,
9829 initial_point: Point,
9830 is_wrapped: bool,
9831 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9832 cx: &mut ViewContext<Editor>,
9833 ) -> Option<MultiBufferDiffHunk> {
9834 let display_point = initial_point.to_display_point(snapshot);
9835 let mut hunks = hunks
9836 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9837 .filter(|(display_hunk, _)| {
9838 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9839 })
9840 .dedup();
9841
9842 if let Some((display_hunk, hunk)) = hunks.next() {
9843 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9844 let row = display_hunk.start_display_row();
9845 let point = DisplayPoint::new(row, 0);
9846 s.select_display_ranges([point..point]);
9847 });
9848
9849 Some(hunk)
9850 } else {
9851 None
9852 }
9853 }
9854
9855 pub fn go_to_definition(
9856 &mut self,
9857 _: &GoToDefinition,
9858 cx: &mut ViewContext<Self>,
9859 ) -> Task<Result<Navigated>> {
9860 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9861 cx.spawn(|editor, mut cx| async move {
9862 if definition.await? == Navigated::Yes {
9863 return Ok(Navigated::Yes);
9864 }
9865 match editor.update(&mut cx, |editor, cx| {
9866 editor.find_all_references(&FindAllReferences, cx)
9867 })? {
9868 Some(references) => references.await,
9869 None => Ok(Navigated::No),
9870 }
9871 })
9872 }
9873
9874 pub fn go_to_declaration(
9875 &mut self,
9876 _: &GoToDeclaration,
9877 cx: &mut ViewContext<Self>,
9878 ) -> Task<Result<Navigated>> {
9879 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9880 }
9881
9882 pub fn go_to_declaration_split(
9883 &mut self,
9884 _: &GoToDeclaration,
9885 cx: &mut ViewContext<Self>,
9886 ) -> Task<Result<Navigated>> {
9887 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9888 }
9889
9890 pub fn go_to_implementation(
9891 &mut self,
9892 _: &GoToImplementation,
9893 cx: &mut ViewContext<Self>,
9894 ) -> Task<Result<Navigated>> {
9895 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9896 }
9897
9898 pub fn go_to_implementation_split(
9899 &mut self,
9900 _: &GoToImplementationSplit,
9901 cx: &mut ViewContext<Self>,
9902 ) -> Task<Result<Navigated>> {
9903 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9904 }
9905
9906 pub fn go_to_type_definition(
9907 &mut self,
9908 _: &GoToTypeDefinition,
9909 cx: &mut ViewContext<Self>,
9910 ) -> Task<Result<Navigated>> {
9911 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9912 }
9913
9914 pub fn go_to_definition_split(
9915 &mut self,
9916 _: &GoToDefinitionSplit,
9917 cx: &mut ViewContext<Self>,
9918 ) -> Task<Result<Navigated>> {
9919 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9920 }
9921
9922 pub fn go_to_type_definition_split(
9923 &mut self,
9924 _: &GoToTypeDefinitionSplit,
9925 cx: &mut ViewContext<Self>,
9926 ) -> Task<Result<Navigated>> {
9927 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9928 }
9929
9930 fn go_to_definition_of_kind(
9931 &mut self,
9932 kind: GotoDefinitionKind,
9933 split: bool,
9934 cx: &mut ViewContext<Self>,
9935 ) -> Task<Result<Navigated>> {
9936 let Some(provider) = self.semantics_provider.clone() else {
9937 return Task::ready(Ok(Navigated::No));
9938 };
9939 let head = self.selections.newest::<usize>(cx).head();
9940 let buffer = self.buffer.read(cx);
9941 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9942 text_anchor
9943 } else {
9944 return Task::ready(Ok(Navigated::No));
9945 };
9946
9947 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9948 return Task::ready(Ok(Navigated::No));
9949 };
9950
9951 cx.spawn(|editor, mut cx| async move {
9952 let definitions = definitions.await?;
9953 let navigated = editor
9954 .update(&mut cx, |editor, cx| {
9955 editor.navigate_to_hover_links(
9956 Some(kind),
9957 definitions
9958 .into_iter()
9959 .filter(|location| {
9960 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9961 })
9962 .map(HoverLink::Text)
9963 .collect::<Vec<_>>(),
9964 split,
9965 cx,
9966 )
9967 })?
9968 .await?;
9969 anyhow::Ok(navigated)
9970 })
9971 }
9972
9973 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9974 let position = self.selections.newest_anchor().head();
9975 let Some((buffer, buffer_position)) =
9976 self.buffer.read(cx).text_anchor_for_position(position, cx)
9977 else {
9978 return;
9979 };
9980
9981 cx.spawn(|editor, mut cx| async move {
9982 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9983 editor.update(&mut cx, |_, cx| {
9984 cx.open_url(&url);
9985 })
9986 } else {
9987 Ok(())
9988 }
9989 })
9990 .detach();
9991 }
9992
9993 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9994 let Some(workspace) = self.workspace() else {
9995 return;
9996 };
9997
9998 let position = self.selections.newest_anchor().head();
9999
10000 let Some((buffer, buffer_position)) =
10001 self.buffer.read(cx).text_anchor_for_position(position, cx)
10002 else {
10003 return;
10004 };
10005
10006 let project = self.project.clone();
10007
10008 cx.spawn(|_, mut cx| async move {
10009 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10010
10011 if let Some((_, path)) = result {
10012 workspace
10013 .update(&mut cx, |workspace, cx| {
10014 workspace.open_resolved_path(path, cx)
10015 })?
10016 .await?;
10017 }
10018 anyhow::Ok(())
10019 })
10020 .detach();
10021 }
10022
10023 pub(crate) fn navigate_to_hover_links(
10024 &mut self,
10025 kind: Option<GotoDefinitionKind>,
10026 mut definitions: Vec<HoverLink>,
10027 split: bool,
10028 cx: &mut ViewContext<Editor>,
10029 ) -> Task<Result<Navigated>> {
10030 // If there is one definition, just open it directly
10031 if definitions.len() == 1 {
10032 let definition = definitions.pop().unwrap();
10033
10034 enum TargetTaskResult {
10035 Location(Option<Location>),
10036 AlreadyNavigated,
10037 }
10038
10039 let target_task = match definition {
10040 HoverLink::Text(link) => {
10041 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10042 }
10043 HoverLink::InlayHint(lsp_location, server_id) => {
10044 let computation = self.compute_target_location(lsp_location, server_id, cx);
10045 cx.background_executor().spawn(async move {
10046 let location = computation.await?;
10047 Ok(TargetTaskResult::Location(location))
10048 })
10049 }
10050 HoverLink::Url(url) => {
10051 cx.open_url(&url);
10052 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10053 }
10054 HoverLink::File(path) => {
10055 if let Some(workspace) = self.workspace() {
10056 cx.spawn(|_, mut cx| async move {
10057 workspace
10058 .update(&mut cx, |workspace, cx| {
10059 workspace.open_resolved_path(path, cx)
10060 })?
10061 .await
10062 .map(|_| TargetTaskResult::AlreadyNavigated)
10063 })
10064 } else {
10065 Task::ready(Ok(TargetTaskResult::Location(None)))
10066 }
10067 }
10068 };
10069 cx.spawn(|editor, mut cx| async move {
10070 let target = match target_task.await.context("target resolution task")? {
10071 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10072 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10073 TargetTaskResult::Location(Some(target)) => target,
10074 };
10075
10076 editor.update(&mut cx, |editor, cx| {
10077 let Some(workspace) = editor.workspace() else {
10078 return Navigated::No;
10079 };
10080 let pane = workspace.read(cx).active_pane().clone();
10081
10082 let range = target.range.to_offset(target.buffer.read(cx));
10083 let range = editor.range_for_match(&range);
10084
10085 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10086 let buffer = target.buffer.read(cx);
10087 let range = check_multiline_range(buffer, range);
10088 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10089 s.select_ranges([range]);
10090 });
10091 } else {
10092 cx.window_context().defer(move |cx| {
10093 let target_editor: View<Self> =
10094 workspace.update(cx, |workspace, cx| {
10095 let pane = if split {
10096 workspace.adjacent_pane(cx)
10097 } else {
10098 workspace.active_pane().clone()
10099 };
10100
10101 workspace.open_project_item(
10102 pane,
10103 target.buffer.clone(),
10104 true,
10105 true,
10106 cx,
10107 )
10108 });
10109 target_editor.update(cx, |target_editor, cx| {
10110 // When selecting a definition in a different buffer, disable the nav history
10111 // to avoid creating a history entry at the previous cursor location.
10112 pane.update(cx, |pane, _| pane.disable_history());
10113 let buffer = target.buffer.read(cx);
10114 let range = check_multiline_range(buffer, range);
10115 target_editor.change_selections(
10116 Some(Autoscroll::focused()),
10117 cx,
10118 |s| {
10119 s.select_ranges([range]);
10120 },
10121 );
10122 pane.update(cx, |pane, _| pane.enable_history());
10123 });
10124 });
10125 }
10126 Navigated::Yes
10127 })
10128 })
10129 } else if !definitions.is_empty() {
10130 cx.spawn(|editor, mut cx| async move {
10131 let (title, location_tasks, workspace) = editor
10132 .update(&mut cx, |editor, cx| {
10133 let tab_kind = match kind {
10134 Some(GotoDefinitionKind::Implementation) => "Implementations",
10135 _ => "Definitions",
10136 };
10137 let title = definitions
10138 .iter()
10139 .find_map(|definition| match definition {
10140 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10141 let buffer = origin.buffer.read(cx);
10142 format!(
10143 "{} for {}",
10144 tab_kind,
10145 buffer
10146 .text_for_range(origin.range.clone())
10147 .collect::<String>()
10148 )
10149 }),
10150 HoverLink::InlayHint(_, _) => None,
10151 HoverLink::Url(_) => None,
10152 HoverLink::File(_) => None,
10153 })
10154 .unwrap_or(tab_kind.to_string());
10155 let location_tasks = definitions
10156 .into_iter()
10157 .map(|definition| match definition {
10158 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10159 HoverLink::InlayHint(lsp_location, server_id) => {
10160 editor.compute_target_location(lsp_location, server_id, cx)
10161 }
10162 HoverLink::Url(_) => Task::ready(Ok(None)),
10163 HoverLink::File(_) => Task::ready(Ok(None)),
10164 })
10165 .collect::<Vec<_>>();
10166 (title, location_tasks, editor.workspace().clone())
10167 })
10168 .context("location tasks preparation")?;
10169
10170 let locations = future::join_all(location_tasks)
10171 .await
10172 .into_iter()
10173 .filter_map(|location| location.transpose())
10174 .collect::<Result<_>>()
10175 .context("location tasks")?;
10176
10177 let Some(workspace) = workspace else {
10178 return Ok(Navigated::No);
10179 };
10180 let opened = workspace
10181 .update(&mut cx, |workspace, cx| {
10182 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10183 })
10184 .ok();
10185
10186 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10187 })
10188 } else {
10189 Task::ready(Ok(Navigated::No))
10190 }
10191 }
10192
10193 fn compute_target_location(
10194 &self,
10195 lsp_location: lsp::Location,
10196 server_id: LanguageServerId,
10197 cx: &mut ViewContext<Self>,
10198 ) -> Task<anyhow::Result<Option<Location>>> {
10199 let Some(project) = self.project.clone() else {
10200 return Task::Ready(Some(Ok(None)));
10201 };
10202
10203 cx.spawn(move |editor, mut cx| async move {
10204 let location_task = editor.update(&mut cx, |_, cx| {
10205 project.update(cx, |project, cx| {
10206 let language_server_name = project
10207 .language_server_statuses(cx)
10208 .find(|(id, _)| server_id == *id)
10209 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10210 language_server_name.map(|language_server_name| {
10211 project.open_local_buffer_via_lsp(
10212 lsp_location.uri.clone(),
10213 server_id,
10214 language_server_name,
10215 cx,
10216 )
10217 })
10218 })
10219 })?;
10220 let location = match location_task {
10221 Some(task) => Some({
10222 let target_buffer_handle = task.await.context("open local buffer")?;
10223 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10224 let target_start = target_buffer
10225 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10226 let target_end = target_buffer
10227 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10228 target_buffer.anchor_after(target_start)
10229 ..target_buffer.anchor_before(target_end)
10230 })?;
10231 Location {
10232 buffer: target_buffer_handle,
10233 range,
10234 }
10235 }),
10236 None => None,
10237 };
10238 Ok(location)
10239 })
10240 }
10241
10242 pub fn find_all_references(
10243 &mut self,
10244 _: &FindAllReferences,
10245 cx: &mut ViewContext<Self>,
10246 ) -> Option<Task<Result<Navigated>>> {
10247 let selection = self.selections.newest::<usize>(cx);
10248 let multi_buffer = self.buffer.read(cx);
10249 let head = selection.head();
10250
10251 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10252 let head_anchor = multi_buffer_snapshot.anchor_at(
10253 head,
10254 if head < selection.tail() {
10255 Bias::Right
10256 } else {
10257 Bias::Left
10258 },
10259 );
10260
10261 match self
10262 .find_all_references_task_sources
10263 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10264 {
10265 Ok(_) => {
10266 log::info!(
10267 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10268 );
10269 return None;
10270 }
10271 Err(i) => {
10272 self.find_all_references_task_sources.insert(i, head_anchor);
10273 }
10274 }
10275
10276 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10277 let workspace = self.workspace()?;
10278 let project = workspace.read(cx).project().clone();
10279 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10280 Some(cx.spawn(|editor, mut cx| async move {
10281 let _cleanup = defer({
10282 let mut cx = cx.clone();
10283 move || {
10284 let _ = editor.update(&mut cx, |editor, _| {
10285 if let Ok(i) =
10286 editor
10287 .find_all_references_task_sources
10288 .binary_search_by(|anchor| {
10289 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10290 })
10291 {
10292 editor.find_all_references_task_sources.remove(i);
10293 }
10294 });
10295 }
10296 });
10297
10298 let locations = references.await?;
10299 if locations.is_empty() {
10300 return anyhow::Ok(Navigated::No);
10301 }
10302
10303 workspace.update(&mut cx, |workspace, cx| {
10304 let title = locations
10305 .first()
10306 .as_ref()
10307 .map(|location| {
10308 let buffer = location.buffer.read(cx);
10309 format!(
10310 "References to `{}`",
10311 buffer
10312 .text_for_range(location.range.clone())
10313 .collect::<String>()
10314 )
10315 })
10316 .unwrap();
10317 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10318 Navigated::Yes
10319 })
10320 }))
10321 }
10322
10323 /// Opens a multibuffer with the given project locations in it
10324 pub fn open_locations_in_multibuffer(
10325 workspace: &mut Workspace,
10326 mut locations: Vec<Location>,
10327 title: String,
10328 split: bool,
10329 cx: &mut ViewContext<Workspace>,
10330 ) {
10331 // If there are multiple definitions, open them in a multibuffer
10332 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10333 let mut locations = locations.into_iter().peekable();
10334 let mut ranges_to_highlight = Vec::new();
10335 let capability = workspace.project().read(cx).capability();
10336
10337 let excerpt_buffer = cx.new_model(|cx| {
10338 let mut multibuffer = MultiBuffer::new(capability);
10339 while let Some(location) = locations.next() {
10340 let buffer = location.buffer.read(cx);
10341 let mut ranges_for_buffer = Vec::new();
10342 let range = location.range.to_offset(buffer);
10343 ranges_for_buffer.push(range.clone());
10344
10345 while let Some(next_location) = locations.peek() {
10346 if next_location.buffer == location.buffer {
10347 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10348 locations.next();
10349 } else {
10350 break;
10351 }
10352 }
10353
10354 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10355 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10356 location.buffer.clone(),
10357 ranges_for_buffer,
10358 DEFAULT_MULTIBUFFER_CONTEXT,
10359 cx,
10360 ))
10361 }
10362
10363 multibuffer.with_title(title)
10364 });
10365
10366 let editor = cx.new_view(|cx| {
10367 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10368 });
10369 editor.update(cx, |editor, cx| {
10370 if let Some(first_range) = ranges_to_highlight.first() {
10371 editor.change_selections(None, cx, |selections| {
10372 selections.clear_disjoint();
10373 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10374 });
10375 }
10376 editor.highlight_background::<Self>(
10377 &ranges_to_highlight,
10378 |theme| theme.editor_highlighted_line_background,
10379 cx,
10380 );
10381 });
10382
10383 let item = Box::new(editor);
10384 let item_id = item.item_id();
10385
10386 if split {
10387 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10388 } else {
10389 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10390 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10391 pane.close_current_preview_item(cx)
10392 } else {
10393 None
10394 }
10395 });
10396 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10397 }
10398 workspace.active_pane().update(cx, |pane, cx| {
10399 pane.set_preview_item_id(Some(item_id), cx);
10400 });
10401 }
10402
10403 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10404 use language::ToOffset as _;
10405
10406 let provider = self.semantics_provider.clone()?;
10407 let selection = self.selections.newest_anchor().clone();
10408 let (cursor_buffer, cursor_buffer_position) = self
10409 .buffer
10410 .read(cx)
10411 .text_anchor_for_position(selection.head(), cx)?;
10412 let (tail_buffer, cursor_buffer_position_end) = self
10413 .buffer
10414 .read(cx)
10415 .text_anchor_for_position(selection.tail(), cx)?;
10416 if tail_buffer != cursor_buffer {
10417 return None;
10418 }
10419
10420 let snapshot = cursor_buffer.read(cx).snapshot();
10421 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10422 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10423 let prepare_rename = provider
10424 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10425 .unwrap_or_else(|| Task::ready(Ok(None)));
10426 drop(snapshot);
10427
10428 Some(cx.spawn(|this, mut cx| async move {
10429 let rename_range = if let Some(range) = prepare_rename.await? {
10430 Some(range)
10431 } else {
10432 this.update(&mut cx, |this, cx| {
10433 let buffer = this.buffer.read(cx).snapshot(cx);
10434 let mut buffer_highlights = this
10435 .document_highlights_for_position(selection.head(), &buffer)
10436 .filter(|highlight| {
10437 highlight.start.excerpt_id == selection.head().excerpt_id
10438 && highlight.end.excerpt_id == selection.head().excerpt_id
10439 });
10440 buffer_highlights
10441 .next()
10442 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10443 })?
10444 };
10445 if let Some(rename_range) = rename_range {
10446 this.update(&mut cx, |this, cx| {
10447 let snapshot = cursor_buffer.read(cx).snapshot();
10448 let rename_buffer_range = rename_range.to_offset(&snapshot);
10449 let cursor_offset_in_rename_range =
10450 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10451 let cursor_offset_in_rename_range_end =
10452 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10453
10454 this.take_rename(false, cx);
10455 let buffer = this.buffer.read(cx).read(cx);
10456 let cursor_offset = selection.head().to_offset(&buffer);
10457 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10458 let rename_end = rename_start + rename_buffer_range.len();
10459 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10460 let mut old_highlight_id = None;
10461 let old_name: Arc<str> = buffer
10462 .chunks(rename_start..rename_end, true)
10463 .map(|chunk| {
10464 if old_highlight_id.is_none() {
10465 old_highlight_id = chunk.syntax_highlight_id;
10466 }
10467 chunk.text
10468 })
10469 .collect::<String>()
10470 .into();
10471
10472 drop(buffer);
10473
10474 // Position the selection in the rename editor so that it matches the current selection.
10475 this.show_local_selections = false;
10476 let rename_editor = cx.new_view(|cx| {
10477 let mut editor = Editor::single_line(cx);
10478 editor.buffer.update(cx, |buffer, cx| {
10479 buffer.edit([(0..0, old_name.clone())], None, cx)
10480 });
10481 let rename_selection_range = match cursor_offset_in_rename_range
10482 .cmp(&cursor_offset_in_rename_range_end)
10483 {
10484 Ordering::Equal => {
10485 editor.select_all(&SelectAll, cx);
10486 return editor;
10487 }
10488 Ordering::Less => {
10489 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10490 }
10491 Ordering::Greater => {
10492 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10493 }
10494 };
10495 if rename_selection_range.end > old_name.len() {
10496 editor.select_all(&SelectAll, cx);
10497 } else {
10498 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10499 s.select_ranges([rename_selection_range]);
10500 });
10501 }
10502 editor
10503 });
10504 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10505 if e == &EditorEvent::Focused {
10506 cx.emit(EditorEvent::FocusedIn)
10507 }
10508 })
10509 .detach();
10510
10511 let write_highlights =
10512 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10513 let read_highlights =
10514 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10515 let ranges = write_highlights
10516 .iter()
10517 .flat_map(|(_, ranges)| ranges.iter())
10518 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10519 .cloned()
10520 .collect();
10521
10522 this.highlight_text::<Rename>(
10523 ranges,
10524 HighlightStyle {
10525 fade_out: Some(0.6),
10526 ..Default::default()
10527 },
10528 cx,
10529 );
10530 let rename_focus_handle = rename_editor.focus_handle(cx);
10531 cx.focus(&rename_focus_handle);
10532 let block_id = this.insert_blocks(
10533 [BlockProperties {
10534 style: BlockStyle::Flex,
10535 placement: BlockPlacement::Below(range.start),
10536 height: 1,
10537 render: Arc::new({
10538 let rename_editor = rename_editor.clone();
10539 move |cx: &mut BlockContext| {
10540 let mut text_style = cx.editor_style.text.clone();
10541 if let Some(highlight_style) = old_highlight_id
10542 .and_then(|h| h.style(&cx.editor_style.syntax))
10543 {
10544 text_style = text_style.highlight(highlight_style);
10545 }
10546 div()
10547 .block_mouse_down()
10548 .pl(cx.anchor_x)
10549 .child(EditorElement::new(
10550 &rename_editor,
10551 EditorStyle {
10552 background: cx.theme().system().transparent,
10553 local_player: cx.editor_style.local_player,
10554 text: text_style,
10555 scrollbar_width: cx.editor_style.scrollbar_width,
10556 syntax: cx.editor_style.syntax.clone(),
10557 status: cx.editor_style.status.clone(),
10558 inlay_hints_style: HighlightStyle {
10559 font_weight: Some(FontWeight::BOLD),
10560 ..make_inlay_hints_style(cx)
10561 },
10562 suggestions_style: HighlightStyle {
10563 color: Some(cx.theme().status().predictive),
10564 ..HighlightStyle::default()
10565 },
10566 ..EditorStyle::default()
10567 },
10568 ))
10569 .into_any_element()
10570 }
10571 }),
10572 priority: 0,
10573 }],
10574 Some(Autoscroll::fit()),
10575 cx,
10576 )[0];
10577 this.pending_rename = Some(RenameState {
10578 range,
10579 old_name,
10580 editor: rename_editor,
10581 block_id,
10582 });
10583 })?;
10584 }
10585
10586 Ok(())
10587 }))
10588 }
10589
10590 pub fn confirm_rename(
10591 &mut self,
10592 _: &ConfirmRename,
10593 cx: &mut ViewContext<Self>,
10594 ) -> Option<Task<Result<()>>> {
10595 let rename = self.take_rename(false, cx)?;
10596 let workspace = self.workspace()?.downgrade();
10597 let (buffer, start) = self
10598 .buffer
10599 .read(cx)
10600 .text_anchor_for_position(rename.range.start, cx)?;
10601 let (end_buffer, _) = self
10602 .buffer
10603 .read(cx)
10604 .text_anchor_for_position(rename.range.end, cx)?;
10605 if buffer != end_buffer {
10606 return None;
10607 }
10608
10609 let old_name = rename.old_name;
10610 let new_name = rename.editor.read(cx).text(cx);
10611
10612 let rename = self.semantics_provider.as_ref()?.perform_rename(
10613 &buffer,
10614 start,
10615 new_name.clone(),
10616 cx,
10617 )?;
10618
10619 Some(cx.spawn(|editor, mut cx| async move {
10620 let project_transaction = rename.await?;
10621 Self::open_project_transaction(
10622 &editor,
10623 workspace,
10624 project_transaction,
10625 format!("Rename: {} → {}", old_name, new_name),
10626 cx.clone(),
10627 )
10628 .await?;
10629
10630 editor.update(&mut cx, |editor, cx| {
10631 editor.refresh_document_highlights(cx);
10632 })?;
10633 Ok(())
10634 }))
10635 }
10636
10637 fn take_rename(
10638 &mut self,
10639 moving_cursor: bool,
10640 cx: &mut ViewContext<Self>,
10641 ) -> Option<RenameState> {
10642 let rename = self.pending_rename.take()?;
10643 if rename.editor.focus_handle(cx).is_focused(cx) {
10644 cx.focus(&self.focus_handle);
10645 }
10646
10647 self.remove_blocks(
10648 [rename.block_id].into_iter().collect(),
10649 Some(Autoscroll::fit()),
10650 cx,
10651 );
10652 self.clear_highlights::<Rename>(cx);
10653 self.show_local_selections = true;
10654
10655 if moving_cursor {
10656 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10657 editor.selections.newest::<usize>(cx).head()
10658 });
10659
10660 // Update the selection to match the position of the selection inside
10661 // the rename editor.
10662 let snapshot = self.buffer.read(cx).read(cx);
10663 let rename_range = rename.range.to_offset(&snapshot);
10664 let cursor_in_editor = snapshot
10665 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10666 .min(rename_range.end);
10667 drop(snapshot);
10668
10669 self.change_selections(None, cx, |s| {
10670 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10671 });
10672 } else {
10673 self.refresh_document_highlights(cx);
10674 }
10675
10676 Some(rename)
10677 }
10678
10679 pub fn pending_rename(&self) -> Option<&RenameState> {
10680 self.pending_rename.as_ref()
10681 }
10682
10683 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10684 let project = match &self.project {
10685 Some(project) => project.clone(),
10686 None => return None,
10687 };
10688
10689 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10690 }
10691
10692 fn format_selections(
10693 &mut self,
10694 _: &FormatSelections,
10695 cx: &mut ViewContext<Self>,
10696 ) -> Option<Task<Result<()>>> {
10697 let project = match &self.project {
10698 Some(project) => project.clone(),
10699 None => return None,
10700 };
10701
10702 let selections = self
10703 .selections
10704 .all_adjusted(cx)
10705 .into_iter()
10706 .filter(|s| !s.is_empty())
10707 .collect_vec();
10708
10709 Some(self.perform_format(
10710 project,
10711 FormatTrigger::Manual,
10712 FormatTarget::Ranges(selections),
10713 cx,
10714 ))
10715 }
10716
10717 fn perform_format(
10718 &mut self,
10719 project: Model<Project>,
10720 trigger: FormatTrigger,
10721 target: FormatTarget,
10722 cx: &mut ViewContext<Self>,
10723 ) -> Task<Result<()>> {
10724 let buffer = self.buffer().clone();
10725 let mut buffers = buffer.read(cx).all_buffers();
10726 if trigger == FormatTrigger::Save {
10727 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10728 }
10729
10730 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10731 let format = project.update(cx, |project, cx| {
10732 project.format(buffers, true, trigger, target, cx)
10733 });
10734
10735 cx.spawn(|_, mut cx| async move {
10736 let transaction = futures::select_biased! {
10737 () = timeout => {
10738 log::warn!("timed out waiting for formatting");
10739 None
10740 }
10741 transaction = format.log_err().fuse() => transaction,
10742 };
10743
10744 buffer
10745 .update(&mut cx, |buffer, cx| {
10746 if let Some(transaction) = transaction {
10747 if !buffer.is_singleton() {
10748 buffer.push_transaction(&transaction.0, cx);
10749 }
10750 }
10751
10752 cx.notify();
10753 })
10754 .ok();
10755
10756 Ok(())
10757 })
10758 }
10759
10760 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10761 if let Some(project) = self.project.clone() {
10762 self.buffer.update(cx, |multi_buffer, cx| {
10763 project.update(cx, |project, cx| {
10764 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10765 });
10766 })
10767 }
10768 }
10769
10770 fn cancel_language_server_work(
10771 &mut self,
10772 _: &actions::CancelLanguageServerWork,
10773 cx: &mut ViewContext<Self>,
10774 ) {
10775 if let Some(project) = self.project.clone() {
10776 self.buffer.update(cx, |multi_buffer, cx| {
10777 project.update(cx, |project, cx| {
10778 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10779 });
10780 })
10781 }
10782 }
10783
10784 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10785 cx.show_character_palette();
10786 }
10787
10788 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10789 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10790 let buffer = self.buffer.read(cx).snapshot(cx);
10791 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10792 let is_valid = buffer
10793 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10794 .any(|entry| {
10795 entry.diagnostic.is_primary
10796 && !entry.range.is_empty()
10797 && entry.range.start == primary_range_start
10798 && entry.diagnostic.message == active_diagnostics.primary_message
10799 });
10800
10801 if is_valid != active_diagnostics.is_valid {
10802 active_diagnostics.is_valid = is_valid;
10803 let mut new_styles = HashMap::default();
10804 for (block_id, diagnostic) in &active_diagnostics.blocks {
10805 new_styles.insert(
10806 *block_id,
10807 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10808 );
10809 }
10810 self.display_map.update(cx, |display_map, _cx| {
10811 display_map.replace_blocks(new_styles)
10812 });
10813 }
10814 }
10815 }
10816
10817 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10818 self.dismiss_diagnostics(cx);
10819 let snapshot = self.snapshot(cx);
10820 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10821 let buffer = self.buffer.read(cx).snapshot(cx);
10822
10823 let mut primary_range = None;
10824 let mut primary_message = None;
10825 let mut group_end = Point::zero();
10826 let diagnostic_group = buffer
10827 .diagnostic_group::<MultiBufferPoint>(group_id)
10828 .filter_map(|entry| {
10829 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10830 && (entry.range.start.row == entry.range.end.row
10831 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10832 {
10833 return None;
10834 }
10835 if entry.range.end > group_end {
10836 group_end = entry.range.end;
10837 }
10838 if entry.diagnostic.is_primary {
10839 primary_range = Some(entry.range.clone());
10840 primary_message = Some(entry.diagnostic.message.clone());
10841 }
10842 Some(entry)
10843 })
10844 .collect::<Vec<_>>();
10845 let primary_range = primary_range?;
10846 let primary_message = primary_message?;
10847 let primary_range =
10848 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10849
10850 let blocks = display_map
10851 .insert_blocks(
10852 diagnostic_group.iter().map(|entry| {
10853 let diagnostic = entry.diagnostic.clone();
10854 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10855 BlockProperties {
10856 style: BlockStyle::Fixed,
10857 placement: BlockPlacement::Below(
10858 buffer.anchor_after(entry.range.start),
10859 ),
10860 height: message_height,
10861 render: diagnostic_block_renderer(diagnostic, None, true, true),
10862 priority: 0,
10863 }
10864 }),
10865 cx,
10866 )
10867 .into_iter()
10868 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10869 .collect();
10870
10871 Some(ActiveDiagnosticGroup {
10872 primary_range,
10873 primary_message,
10874 group_id,
10875 blocks,
10876 is_valid: true,
10877 })
10878 });
10879 self.active_diagnostics.is_some()
10880 }
10881
10882 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10883 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10884 self.display_map.update(cx, |display_map, cx| {
10885 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10886 });
10887 cx.notify();
10888 }
10889 }
10890
10891 pub fn set_selections_from_remote(
10892 &mut self,
10893 selections: Vec<Selection<Anchor>>,
10894 pending_selection: Option<Selection<Anchor>>,
10895 cx: &mut ViewContext<Self>,
10896 ) {
10897 let old_cursor_position = self.selections.newest_anchor().head();
10898 self.selections.change_with(cx, |s| {
10899 s.select_anchors(selections);
10900 if let Some(pending_selection) = pending_selection {
10901 s.set_pending(pending_selection, SelectMode::Character);
10902 } else {
10903 s.clear_pending();
10904 }
10905 });
10906 self.selections_did_change(false, &old_cursor_position, true, cx);
10907 }
10908
10909 fn push_to_selection_history(&mut self) {
10910 self.selection_history.push(SelectionHistoryEntry {
10911 selections: self.selections.disjoint_anchors(),
10912 select_next_state: self.select_next_state.clone(),
10913 select_prev_state: self.select_prev_state.clone(),
10914 add_selections_state: self.add_selections_state.clone(),
10915 });
10916 }
10917
10918 pub fn transact(
10919 &mut self,
10920 cx: &mut ViewContext<Self>,
10921 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10922 ) -> Option<TransactionId> {
10923 self.start_transaction_at(Instant::now(), cx);
10924 update(self, cx);
10925 self.end_transaction_at(Instant::now(), cx)
10926 }
10927
10928 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10929 self.end_selection(cx);
10930 if let Some(tx_id) = self
10931 .buffer
10932 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10933 {
10934 self.selection_history
10935 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10936 cx.emit(EditorEvent::TransactionBegun {
10937 transaction_id: tx_id,
10938 })
10939 }
10940 }
10941
10942 fn end_transaction_at(
10943 &mut self,
10944 now: Instant,
10945 cx: &mut ViewContext<Self>,
10946 ) -> Option<TransactionId> {
10947 if let Some(transaction_id) = self
10948 .buffer
10949 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10950 {
10951 if let Some((_, end_selections)) =
10952 self.selection_history.transaction_mut(transaction_id)
10953 {
10954 *end_selections = Some(self.selections.disjoint_anchors());
10955 } else {
10956 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10957 }
10958
10959 cx.emit(EditorEvent::Edited { transaction_id });
10960 Some(transaction_id)
10961 } else {
10962 None
10963 }
10964 }
10965
10966 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10967 let selection = self.selections.newest::<Point>(cx);
10968
10969 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10970 let range = if selection.is_empty() {
10971 let point = selection.head().to_display_point(&display_map);
10972 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10973 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10974 .to_point(&display_map);
10975 start..end
10976 } else {
10977 selection.range()
10978 };
10979 if display_map.folds_in_range(range).next().is_some() {
10980 self.unfold_lines(&Default::default(), cx)
10981 } else {
10982 self.fold(&Default::default(), cx)
10983 }
10984 }
10985
10986 pub fn toggle_fold_recursive(
10987 &mut self,
10988 _: &actions::ToggleFoldRecursive,
10989 cx: &mut ViewContext<Self>,
10990 ) {
10991 let selection = self.selections.newest::<Point>(cx);
10992
10993 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10994 let range = if selection.is_empty() {
10995 let point = selection.head().to_display_point(&display_map);
10996 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10997 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10998 .to_point(&display_map);
10999 start..end
11000 } else {
11001 selection.range()
11002 };
11003 if display_map.folds_in_range(range).next().is_some() {
11004 self.unfold_recursive(&Default::default(), cx)
11005 } else {
11006 self.fold_recursive(&Default::default(), cx)
11007 }
11008 }
11009
11010 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11011 let mut to_fold = Vec::new();
11012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11013 let selections = self.selections.all_adjusted(cx);
11014
11015 for selection in selections {
11016 let range = selection.range().sorted();
11017 let buffer_start_row = range.start.row;
11018
11019 if range.start.row != range.end.row {
11020 let mut found = false;
11021 let mut row = range.start.row;
11022 while row <= range.end.row {
11023 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11024 found = true;
11025 row = crease.range().end.row + 1;
11026 to_fold.push(crease);
11027 } else {
11028 row += 1
11029 }
11030 }
11031 if found {
11032 continue;
11033 }
11034 }
11035
11036 for row in (0..=range.start.row).rev() {
11037 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11038 if crease.range().end.row >= buffer_start_row {
11039 to_fold.push(crease);
11040 if row <= range.start.row {
11041 break;
11042 }
11043 }
11044 }
11045 }
11046 }
11047
11048 self.fold_creases(to_fold, true, cx);
11049 }
11050
11051 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11052 let fold_at_level = fold_at.level;
11053 let snapshot = self.buffer.read(cx).snapshot(cx);
11054 let mut to_fold = Vec::new();
11055 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11056
11057 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11058 while start_row < end_row {
11059 match self
11060 .snapshot(cx)
11061 .crease_for_buffer_row(MultiBufferRow(start_row))
11062 {
11063 Some(crease) => {
11064 let nested_start_row = crease.range().start.row + 1;
11065 let nested_end_row = crease.range().end.row;
11066
11067 if current_level < fold_at_level {
11068 stack.push((nested_start_row, nested_end_row, current_level + 1));
11069 } else if current_level == fold_at_level {
11070 to_fold.push(crease);
11071 }
11072
11073 start_row = nested_end_row + 1;
11074 }
11075 None => start_row += 1,
11076 }
11077 }
11078 }
11079
11080 self.fold_creases(to_fold, true, cx);
11081 }
11082
11083 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11084 let mut fold_ranges = Vec::new();
11085 let snapshot = self.buffer.read(cx).snapshot(cx);
11086
11087 for row in 0..snapshot.max_buffer_row().0 {
11088 if let Some(foldable_range) =
11089 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11090 {
11091 fold_ranges.push(foldable_range);
11092 }
11093 }
11094
11095 self.fold_creases(fold_ranges, true, cx);
11096 }
11097
11098 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11099 let mut to_fold = Vec::new();
11100 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11101 let selections = self.selections.all_adjusted(cx);
11102
11103 for selection in selections {
11104 let range = selection.range().sorted();
11105 let buffer_start_row = range.start.row;
11106
11107 if range.start.row != range.end.row {
11108 let mut found = false;
11109 for row in range.start.row..=range.end.row {
11110 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11111 found = true;
11112 to_fold.push(crease);
11113 }
11114 }
11115 if found {
11116 continue;
11117 }
11118 }
11119
11120 for row in (0..=range.start.row).rev() {
11121 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11122 if crease.range().end.row >= buffer_start_row {
11123 to_fold.push(crease);
11124 } else {
11125 break;
11126 }
11127 }
11128 }
11129 }
11130
11131 self.fold_creases(to_fold, true, cx);
11132 }
11133
11134 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11135 let buffer_row = fold_at.buffer_row;
11136 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11137
11138 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11139 let autoscroll = self
11140 .selections
11141 .all::<Point>(cx)
11142 .iter()
11143 .any(|selection| crease.range().overlaps(&selection.range()));
11144
11145 self.fold_creases(vec![crease], autoscroll, cx);
11146 }
11147 }
11148
11149 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11151 let buffer = &display_map.buffer_snapshot;
11152 let selections = self.selections.all::<Point>(cx);
11153 let ranges = selections
11154 .iter()
11155 .map(|s| {
11156 let range = s.display_range(&display_map).sorted();
11157 let mut start = range.start.to_point(&display_map);
11158 let mut end = range.end.to_point(&display_map);
11159 start.column = 0;
11160 end.column = buffer.line_len(MultiBufferRow(end.row));
11161 start..end
11162 })
11163 .collect::<Vec<_>>();
11164
11165 self.unfold_ranges(&ranges, true, true, cx);
11166 }
11167
11168 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11169 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11170 let selections = self.selections.all::<Point>(cx);
11171 let ranges = selections
11172 .iter()
11173 .map(|s| {
11174 let mut range = s.display_range(&display_map).sorted();
11175 *range.start.column_mut() = 0;
11176 *range.end.column_mut() = display_map.line_len(range.end.row());
11177 let start = range.start.to_point(&display_map);
11178 let end = range.end.to_point(&display_map);
11179 start..end
11180 })
11181 .collect::<Vec<_>>();
11182
11183 self.unfold_ranges(&ranges, true, true, cx);
11184 }
11185
11186 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11188
11189 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11190 ..Point::new(
11191 unfold_at.buffer_row.0,
11192 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11193 );
11194
11195 let autoscroll = self
11196 .selections
11197 .all::<Point>(cx)
11198 .iter()
11199 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11200
11201 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11202 }
11203
11204 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11205 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11206 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11207 }
11208
11209 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11210 let selections = self.selections.all::<Point>(cx);
11211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11212 let line_mode = self.selections.line_mode;
11213 let ranges = selections
11214 .into_iter()
11215 .map(|s| {
11216 if line_mode {
11217 let start = Point::new(s.start.row, 0);
11218 let end = Point::new(
11219 s.end.row,
11220 display_map
11221 .buffer_snapshot
11222 .line_len(MultiBufferRow(s.end.row)),
11223 );
11224 Crease::simple(start..end, display_map.fold_placeholder.clone())
11225 } else {
11226 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11227 }
11228 })
11229 .collect::<Vec<_>>();
11230 self.fold_creases(ranges, true, cx);
11231 }
11232
11233 pub fn fold_creases<T: ToOffset + Clone>(
11234 &mut self,
11235 creases: Vec<Crease<T>>,
11236 auto_scroll: bool,
11237 cx: &mut ViewContext<Self>,
11238 ) {
11239 if creases.is_empty() {
11240 return;
11241 }
11242
11243 let mut buffers_affected = HashMap::default();
11244 let multi_buffer = self.buffer().read(cx);
11245 for crease in &creases {
11246 if let Some((_, buffer, _)) =
11247 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11248 {
11249 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11250 };
11251 }
11252
11253 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11254
11255 if auto_scroll {
11256 self.request_autoscroll(Autoscroll::fit(), cx);
11257 }
11258
11259 for buffer in buffers_affected.into_values() {
11260 self.sync_expanded_diff_hunks(buffer, cx);
11261 }
11262
11263 cx.notify();
11264
11265 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11266 // Clear diagnostics block when folding a range that contains it.
11267 let snapshot = self.snapshot(cx);
11268 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11269 drop(snapshot);
11270 self.active_diagnostics = Some(active_diagnostics);
11271 self.dismiss_diagnostics(cx);
11272 } else {
11273 self.active_diagnostics = Some(active_diagnostics);
11274 }
11275 }
11276
11277 self.scrollbar_marker_state.dirty = true;
11278 }
11279
11280 /// Removes any folds whose ranges intersect any of the given ranges.
11281 pub fn unfold_ranges<T: ToOffset + Clone>(
11282 &mut self,
11283 ranges: &[Range<T>],
11284 inclusive: bool,
11285 auto_scroll: bool,
11286 cx: &mut ViewContext<Self>,
11287 ) {
11288 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11289 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11290 });
11291 }
11292
11293 /// Removes any folds with the given ranges.
11294 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11295 &mut self,
11296 ranges: &[Range<T>],
11297 type_id: TypeId,
11298 auto_scroll: bool,
11299 cx: &mut ViewContext<Self>,
11300 ) {
11301 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11302 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11303 });
11304 }
11305
11306 fn remove_folds_with<T: ToOffset + Clone>(
11307 &mut self,
11308 ranges: &[Range<T>],
11309 auto_scroll: bool,
11310 cx: &mut ViewContext<Self>,
11311 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11312 ) {
11313 if ranges.is_empty() {
11314 return;
11315 }
11316
11317 let mut buffers_affected = HashMap::default();
11318 let multi_buffer = self.buffer().read(cx);
11319 for range in ranges {
11320 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11321 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11322 };
11323 }
11324
11325 self.display_map.update(cx, update);
11326
11327 if auto_scroll {
11328 self.request_autoscroll(Autoscroll::fit(), cx);
11329 }
11330
11331 for buffer in buffers_affected.into_values() {
11332 self.sync_expanded_diff_hunks(buffer, cx);
11333 }
11334
11335 cx.notify();
11336 self.scrollbar_marker_state.dirty = true;
11337 self.active_indent_guides_state.dirty = true;
11338 }
11339
11340 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11341 self.display_map.read(cx).fold_placeholder.clone()
11342 }
11343
11344 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11345 if hovered != self.gutter_hovered {
11346 self.gutter_hovered = hovered;
11347 cx.notify();
11348 }
11349 }
11350
11351 pub fn insert_blocks(
11352 &mut self,
11353 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11354 autoscroll: Option<Autoscroll>,
11355 cx: &mut ViewContext<Self>,
11356 ) -> Vec<CustomBlockId> {
11357 let blocks = self
11358 .display_map
11359 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11360 if let Some(autoscroll) = autoscroll {
11361 self.request_autoscroll(autoscroll, cx);
11362 }
11363 cx.notify();
11364 blocks
11365 }
11366
11367 pub fn resize_blocks(
11368 &mut self,
11369 heights: HashMap<CustomBlockId, u32>,
11370 autoscroll: Option<Autoscroll>,
11371 cx: &mut ViewContext<Self>,
11372 ) {
11373 self.display_map
11374 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11375 if let Some(autoscroll) = autoscroll {
11376 self.request_autoscroll(autoscroll, cx);
11377 }
11378 cx.notify();
11379 }
11380
11381 pub fn replace_blocks(
11382 &mut self,
11383 renderers: HashMap<CustomBlockId, RenderBlock>,
11384 autoscroll: Option<Autoscroll>,
11385 cx: &mut ViewContext<Self>,
11386 ) {
11387 self.display_map
11388 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11389 if let Some(autoscroll) = autoscroll {
11390 self.request_autoscroll(autoscroll, cx);
11391 }
11392 cx.notify();
11393 }
11394
11395 pub fn remove_blocks(
11396 &mut self,
11397 block_ids: HashSet<CustomBlockId>,
11398 autoscroll: Option<Autoscroll>,
11399 cx: &mut ViewContext<Self>,
11400 ) {
11401 self.display_map.update(cx, |display_map, cx| {
11402 display_map.remove_blocks(block_ids, cx)
11403 });
11404 if let Some(autoscroll) = autoscroll {
11405 self.request_autoscroll(autoscroll, cx);
11406 }
11407 cx.notify();
11408 }
11409
11410 pub fn row_for_block(
11411 &self,
11412 block_id: CustomBlockId,
11413 cx: &mut ViewContext<Self>,
11414 ) -> Option<DisplayRow> {
11415 self.display_map
11416 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11417 }
11418
11419 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11420 self.focused_block = Some(focused_block);
11421 }
11422
11423 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11424 self.focused_block.take()
11425 }
11426
11427 pub fn insert_creases(
11428 &mut self,
11429 creases: impl IntoIterator<Item = Crease<Anchor>>,
11430 cx: &mut ViewContext<Self>,
11431 ) -> Vec<CreaseId> {
11432 self.display_map
11433 .update(cx, |map, cx| map.insert_creases(creases, cx))
11434 }
11435
11436 pub fn remove_creases(
11437 &mut self,
11438 ids: impl IntoIterator<Item = CreaseId>,
11439 cx: &mut ViewContext<Self>,
11440 ) {
11441 self.display_map
11442 .update(cx, |map, cx| map.remove_creases(ids, cx));
11443 }
11444
11445 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11446 self.display_map
11447 .update(cx, |map, cx| map.snapshot(cx))
11448 .longest_row()
11449 }
11450
11451 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11452 self.display_map
11453 .update(cx, |map, cx| map.snapshot(cx))
11454 .max_point()
11455 }
11456
11457 pub fn text(&self, cx: &AppContext) -> String {
11458 self.buffer.read(cx).read(cx).text()
11459 }
11460
11461 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11462 let text = self.text(cx);
11463 let text = text.trim();
11464
11465 if text.is_empty() {
11466 return None;
11467 }
11468
11469 Some(text.to_string())
11470 }
11471
11472 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11473 self.transact(cx, |this, cx| {
11474 this.buffer
11475 .read(cx)
11476 .as_singleton()
11477 .expect("you can only call set_text on editors for singleton buffers")
11478 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11479 });
11480 }
11481
11482 pub fn display_text(&self, cx: &mut AppContext) -> String {
11483 self.display_map
11484 .update(cx, |map, cx| map.snapshot(cx))
11485 .text()
11486 }
11487
11488 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11489 let mut wrap_guides = smallvec::smallvec![];
11490
11491 if self.show_wrap_guides == Some(false) {
11492 return wrap_guides;
11493 }
11494
11495 let settings = self.buffer.read(cx).settings_at(0, cx);
11496 if settings.show_wrap_guides {
11497 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11498 wrap_guides.push((soft_wrap as usize, true));
11499 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11500 wrap_guides.push((soft_wrap as usize, true));
11501 }
11502 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11503 }
11504
11505 wrap_guides
11506 }
11507
11508 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11509 let settings = self.buffer.read(cx).settings_at(0, cx);
11510 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11511 match mode {
11512 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11513 SoftWrap::None
11514 }
11515 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11516 language_settings::SoftWrap::PreferredLineLength => {
11517 SoftWrap::Column(settings.preferred_line_length)
11518 }
11519 language_settings::SoftWrap::Bounded => {
11520 SoftWrap::Bounded(settings.preferred_line_length)
11521 }
11522 }
11523 }
11524
11525 pub fn set_soft_wrap_mode(
11526 &mut self,
11527 mode: language_settings::SoftWrap,
11528 cx: &mut ViewContext<Self>,
11529 ) {
11530 self.soft_wrap_mode_override = Some(mode);
11531 cx.notify();
11532 }
11533
11534 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11535 self.text_style_refinement = Some(style);
11536 }
11537
11538 /// called by the Element so we know what style we were most recently rendered with.
11539 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11540 let rem_size = cx.rem_size();
11541 self.display_map.update(cx, |map, cx| {
11542 map.set_font(
11543 style.text.font(),
11544 style.text.font_size.to_pixels(rem_size),
11545 cx,
11546 )
11547 });
11548 self.style = Some(style);
11549 }
11550
11551 pub fn style(&self) -> Option<&EditorStyle> {
11552 self.style.as_ref()
11553 }
11554
11555 // Called by the element. This method is not designed to be called outside of the editor
11556 // element's layout code because it does not notify when rewrapping is computed synchronously.
11557 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11558 self.display_map
11559 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11560 }
11561
11562 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11563 if self.soft_wrap_mode_override.is_some() {
11564 self.soft_wrap_mode_override.take();
11565 } else {
11566 let soft_wrap = match self.soft_wrap_mode(cx) {
11567 SoftWrap::GitDiff => return,
11568 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11569 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11570 language_settings::SoftWrap::None
11571 }
11572 };
11573 self.soft_wrap_mode_override = Some(soft_wrap);
11574 }
11575 cx.notify();
11576 }
11577
11578 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11579 let Some(workspace) = self.workspace() else {
11580 return;
11581 };
11582 let fs = workspace.read(cx).app_state().fs.clone();
11583 let current_show = TabBarSettings::get_global(cx).show;
11584 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11585 setting.show = Some(!current_show);
11586 });
11587 }
11588
11589 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11590 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11591 self.buffer
11592 .read(cx)
11593 .settings_at(0, cx)
11594 .indent_guides
11595 .enabled
11596 });
11597 self.show_indent_guides = Some(!currently_enabled);
11598 cx.notify();
11599 }
11600
11601 fn should_show_indent_guides(&self) -> Option<bool> {
11602 self.show_indent_guides
11603 }
11604
11605 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11606 let mut editor_settings = EditorSettings::get_global(cx).clone();
11607 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11608 EditorSettings::override_global(editor_settings, cx);
11609 }
11610
11611 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11612 self.use_relative_line_numbers
11613 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11614 }
11615
11616 pub fn toggle_relative_line_numbers(
11617 &mut self,
11618 _: &ToggleRelativeLineNumbers,
11619 cx: &mut ViewContext<Self>,
11620 ) {
11621 let is_relative = self.should_use_relative_line_numbers(cx);
11622 self.set_relative_line_number(Some(!is_relative), cx)
11623 }
11624
11625 pub fn set_relative_line_number(
11626 &mut self,
11627 is_relative: Option<bool>,
11628 cx: &mut ViewContext<Self>,
11629 ) {
11630 self.use_relative_line_numbers = is_relative;
11631 cx.notify();
11632 }
11633
11634 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11635 self.show_gutter = show_gutter;
11636 cx.notify();
11637 }
11638
11639 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11640 self.show_line_numbers = Some(show_line_numbers);
11641 cx.notify();
11642 }
11643
11644 pub fn set_show_git_diff_gutter(
11645 &mut self,
11646 show_git_diff_gutter: bool,
11647 cx: &mut ViewContext<Self>,
11648 ) {
11649 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11650 cx.notify();
11651 }
11652
11653 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11654 self.show_code_actions = Some(show_code_actions);
11655 cx.notify();
11656 }
11657
11658 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11659 self.show_runnables = Some(show_runnables);
11660 cx.notify();
11661 }
11662
11663 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11664 if self.display_map.read(cx).masked != masked {
11665 self.display_map.update(cx, |map, _| map.masked = masked);
11666 }
11667 cx.notify()
11668 }
11669
11670 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11671 self.show_wrap_guides = Some(show_wrap_guides);
11672 cx.notify();
11673 }
11674
11675 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11676 self.show_indent_guides = Some(show_indent_guides);
11677 cx.notify();
11678 }
11679
11680 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11681 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11682 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11683 if let Some(dir) = file.abs_path(cx).parent() {
11684 return Some(dir.to_owned());
11685 }
11686 }
11687
11688 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11689 return Some(project_path.path.to_path_buf());
11690 }
11691 }
11692
11693 None
11694 }
11695
11696 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11697 self.active_excerpt(cx)?
11698 .1
11699 .read(cx)
11700 .file()
11701 .and_then(|f| f.as_local())
11702 }
11703
11704 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11705 if let Some(target) = self.target_file(cx) {
11706 cx.reveal_path(&target.abs_path(cx));
11707 }
11708 }
11709
11710 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11711 if let Some(file) = self.target_file(cx) {
11712 if let Some(path) = file.abs_path(cx).to_str() {
11713 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11714 }
11715 }
11716 }
11717
11718 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11719 if let Some(file) = self.target_file(cx) {
11720 if let Some(path) = file.path().to_str() {
11721 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11722 }
11723 }
11724 }
11725
11726 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11727 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11728
11729 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11730 self.start_git_blame(true, cx);
11731 }
11732
11733 cx.notify();
11734 }
11735
11736 pub fn toggle_git_blame_inline(
11737 &mut self,
11738 _: &ToggleGitBlameInline,
11739 cx: &mut ViewContext<Self>,
11740 ) {
11741 self.toggle_git_blame_inline_internal(true, cx);
11742 cx.notify();
11743 }
11744
11745 pub fn git_blame_inline_enabled(&self) -> bool {
11746 self.git_blame_inline_enabled
11747 }
11748
11749 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11750 self.show_selection_menu = self
11751 .show_selection_menu
11752 .map(|show_selections_menu| !show_selections_menu)
11753 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11754
11755 cx.notify();
11756 }
11757
11758 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11759 self.show_selection_menu
11760 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11761 }
11762
11763 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11764 if let Some(project) = self.project.as_ref() {
11765 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11766 return;
11767 };
11768
11769 if buffer.read(cx).file().is_none() {
11770 return;
11771 }
11772
11773 let focused = self.focus_handle(cx).contains_focused(cx);
11774
11775 let project = project.clone();
11776 let blame =
11777 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11778 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11779 self.blame = Some(blame);
11780 }
11781 }
11782
11783 fn toggle_git_blame_inline_internal(
11784 &mut self,
11785 user_triggered: bool,
11786 cx: &mut ViewContext<Self>,
11787 ) {
11788 if self.git_blame_inline_enabled {
11789 self.git_blame_inline_enabled = false;
11790 self.show_git_blame_inline = false;
11791 self.show_git_blame_inline_delay_task.take();
11792 } else {
11793 self.git_blame_inline_enabled = true;
11794 self.start_git_blame_inline(user_triggered, cx);
11795 }
11796
11797 cx.notify();
11798 }
11799
11800 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11801 self.start_git_blame(user_triggered, cx);
11802
11803 if ProjectSettings::get_global(cx)
11804 .git
11805 .inline_blame_delay()
11806 .is_some()
11807 {
11808 self.start_inline_blame_timer(cx);
11809 } else {
11810 self.show_git_blame_inline = true
11811 }
11812 }
11813
11814 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11815 self.blame.as_ref()
11816 }
11817
11818 pub fn show_git_blame_gutter(&self) -> bool {
11819 self.show_git_blame_gutter
11820 }
11821
11822 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11823 self.show_git_blame_gutter && self.has_blame_entries(cx)
11824 }
11825
11826 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11827 self.show_git_blame_inline
11828 && self.focus_handle.is_focused(cx)
11829 && !self.newest_selection_head_on_empty_line(cx)
11830 && self.has_blame_entries(cx)
11831 }
11832
11833 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11834 self.blame()
11835 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11836 }
11837
11838 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11839 let cursor_anchor = self.selections.newest_anchor().head();
11840
11841 let snapshot = self.buffer.read(cx).snapshot(cx);
11842 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11843
11844 snapshot.line_len(buffer_row) == 0
11845 }
11846
11847 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11848 let buffer_and_selection = maybe!({
11849 let selection = self.selections.newest::<Point>(cx);
11850 let selection_range = selection.range();
11851
11852 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11853 (buffer, selection_range.start.row..selection_range.end.row)
11854 } else {
11855 let buffer_ranges = self
11856 .buffer()
11857 .read(cx)
11858 .range_to_buffer_ranges(selection_range, cx);
11859
11860 let (buffer, range, _) = if selection.reversed {
11861 buffer_ranges.first()
11862 } else {
11863 buffer_ranges.last()
11864 }?;
11865
11866 let snapshot = buffer.read(cx).snapshot();
11867 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11868 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11869 (buffer.clone(), selection)
11870 };
11871
11872 Some((buffer, selection))
11873 });
11874
11875 let Some((buffer, selection)) = buffer_and_selection else {
11876 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11877 };
11878
11879 let Some(project) = self.project.as_ref() else {
11880 return Task::ready(Err(anyhow!("editor does not have project")));
11881 };
11882
11883 project.update(cx, |project, cx| {
11884 project.get_permalink_to_line(&buffer, selection, cx)
11885 })
11886 }
11887
11888 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11889 let permalink_task = self.get_permalink_to_line(cx);
11890 let workspace = self.workspace();
11891
11892 cx.spawn(|_, mut cx| async move {
11893 match permalink_task.await {
11894 Ok(permalink) => {
11895 cx.update(|cx| {
11896 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11897 })
11898 .ok();
11899 }
11900 Err(err) => {
11901 let message = format!("Failed to copy permalink: {err}");
11902
11903 Err::<(), anyhow::Error>(err).log_err();
11904
11905 if let Some(workspace) = workspace {
11906 workspace
11907 .update(&mut cx, |workspace, cx| {
11908 struct CopyPermalinkToLine;
11909
11910 workspace.show_toast(
11911 Toast::new(
11912 NotificationId::unique::<CopyPermalinkToLine>(),
11913 message,
11914 ),
11915 cx,
11916 )
11917 })
11918 .ok();
11919 }
11920 }
11921 }
11922 })
11923 .detach();
11924 }
11925
11926 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11927 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11928 if let Some(file) = self.target_file(cx) {
11929 if let Some(path) = file.path().to_str() {
11930 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11931 }
11932 }
11933 }
11934
11935 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11936 let permalink_task = self.get_permalink_to_line(cx);
11937 let workspace = self.workspace();
11938
11939 cx.spawn(|_, mut cx| async move {
11940 match permalink_task.await {
11941 Ok(permalink) => {
11942 cx.update(|cx| {
11943 cx.open_url(permalink.as_ref());
11944 })
11945 .ok();
11946 }
11947 Err(err) => {
11948 let message = format!("Failed to open permalink: {err}");
11949
11950 Err::<(), anyhow::Error>(err).log_err();
11951
11952 if let Some(workspace) = workspace {
11953 workspace
11954 .update(&mut cx, |workspace, cx| {
11955 struct OpenPermalinkToLine;
11956
11957 workspace.show_toast(
11958 Toast::new(
11959 NotificationId::unique::<OpenPermalinkToLine>(),
11960 message,
11961 ),
11962 cx,
11963 )
11964 })
11965 .ok();
11966 }
11967 }
11968 }
11969 })
11970 .detach();
11971 }
11972
11973 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11974 /// last highlight added will be used.
11975 ///
11976 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11977 pub fn highlight_rows<T: 'static>(
11978 &mut self,
11979 range: Range<Anchor>,
11980 color: Hsla,
11981 should_autoscroll: bool,
11982 cx: &mut ViewContext<Self>,
11983 ) {
11984 let snapshot = self.buffer().read(cx).snapshot(cx);
11985 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11986 let ix = row_highlights.binary_search_by(|highlight| {
11987 Ordering::Equal
11988 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11989 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11990 });
11991
11992 if let Err(mut ix) = ix {
11993 let index = post_inc(&mut self.highlight_order);
11994
11995 // If this range intersects with the preceding highlight, then merge it with
11996 // the preceding highlight. Otherwise insert a new highlight.
11997 let mut merged = false;
11998 if ix > 0 {
11999 let prev_highlight = &mut row_highlights[ix - 1];
12000 if prev_highlight
12001 .range
12002 .end
12003 .cmp(&range.start, &snapshot)
12004 .is_ge()
12005 {
12006 ix -= 1;
12007 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12008 prev_highlight.range.end = range.end;
12009 }
12010 merged = true;
12011 prev_highlight.index = index;
12012 prev_highlight.color = color;
12013 prev_highlight.should_autoscroll = should_autoscroll;
12014 }
12015 }
12016
12017 if !merged {
12018 row_highlights.insert(
12019 ix,
12020 RowHighlight {
12021 range: range.clone(),
12022 index,
12023 color,
12024 should_autoscroll,
12025 },
12026 );
12027 }
12028
12029 // If any of the following highlights intersect with this one, merge them.
12030 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12031 let highlight = &row_highlights[ix];
12032 if next_highlight
12033 .range
12034 .start
12035 .cmp(&highlight.range.end, &snapshot)
12036 .is_le()
12037 {
12038 if next_highlight
12039 .range
12040 .end
12041 .cmp(&highlight.range.end, &snapshot)
12042 .is_gt()
12043 {
12044 row_highlights[ix].range.end = next_highlight.range.end;
12045 }
12046 row_highlights.remove(ix + 1);
12047 } else {
12048 break;
12049 }
12050 }
12051 }
12052 }
12053
12054 /// Remove any highlighted row ranges of the given type that intersect the
12055 /// given ranges.
12056 pub fn remove_highlighted_rows<T: 'static>(
12057 &mut self,
12058 ranges_to_remove: Vec<Range<Anchor>>,
12059 cx: &mut ViewContext<Self>,
12060 ) {
12061 let snapshot = self.buffer().read(cx).snapshot(cx);
12062 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12063 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12064 row_highlights.retain(|highlight| {
12065 while let Some(range_to_remove) = ranges_to_remove.peek() {
12066 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12067 Ordering::Less | Ordering::Equal => {
12068 ranges_to_remove.next();
12069 }
12070 Ordering::Greater => {
12071 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12072 Ordering::Less | Ordering::Equal => {
12073 return false;
12074 }
12075 Ordering::Greater => break,
12076 }
12077 }
12078 }
12079 }
12080
12081 true
12082 })
12083 }
12084
12085 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12086 pub fn clear_row_highlights<T: 'static>(&mut self) {
12087 self.highlighted_rows.remove(&TypeId::of::<T>());
12088 }
12089
12090 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12091 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12092 self.highlighted_rows
12093 .get(&TypeId::of::<T>())
12094 .map_or(&[] as &[_], |vec| vec.as_slice())
12095 .iter()
12096 .map(|highlight| (highlight.range.clone(), highlight.color))
12097 }
12098
12099 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12100 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12101 /// Allows to ignore certain kinds of highlights.
12102 pub fn highlighted_display_rows(
12103 &mut self,
12104 cx: &mut WindowContext,
12105 ) -> BTreeMap<DisplayRow, Hsla> {
12106 let snapshot = self.snapshot(cx);
12107 let mut used_highlight_orders = HashMap::default();
12108 self.highlighted_rows
12109 .iter()
12110 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12111 .fold(
12112 BTreeMap::<DisplayRow, Hsla>::new(),
12113 |mut unique_rows, highlight| {
12114 let start = highlight.range.start.to_display_point(&snapshot);
12115 let end = highlight.range.end.to_display_point(&snapshot);
12116 let start_row = start.row().0;
12117 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12118 && end.column() == 0
12119 {
12120 end.row().0.saturating_sub(1)
12121 } else {
12122 end.row().0
12123 };
12124 for row in start_row..=end_row {
12125 let used_index =
12126 used_highlight_orders.entry(row).or_insert(highlight.index);
12127 if highlight.index >= *used_index {
12128 *used_index = highlight.index;
12129 unique_rows.insert(DisplayRow(row), highlight.color);
12130 }
12131 }
12132 unique_rows
12133 },
12134 )
12135 }
12136
12137 pub fn highlighted_display_row_for_autoscroll(
12138 &self,
12139 snapshot: &DisplaySnapshot,
12140 ) -> Option<DisplayRow> {
12141 self.highlighted_rows
12142 .values()
12143 .flat_map(|highlighted_rows| highlighted_rows.iter())
12144 .filter_map(|highlight| {
12145 if highlight.should_autoscroll {
12146 Some(highlight.range.start.to_display_point(snapshot).row())
12147 } else {
12148 None
12149 }
12150 })
12151 .min()
12152 }
12153
12154 pub fn set_search_within_ranges(
12155 &mut self,
12156 ranges: &[Range<Anchor>],
12157 cx: &mut ViewContext<Self>,
12158 ) {
12159 self.highlight_background::<SearchWithinRange>(
12160 ranges,
12161 |colors| colors.editor_document_highlight_read_background,
12162 cx,
12163 )
12164 }
12165
12166 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12167 self.breadcrumb_header = Some(new_header);
12168 }
12169
12170 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12171 self.clear_background_highlights::<SearchWithinRange>(cx);
12172 }
12173
12174 pub fn highlight_background<T: 'static>(
12175 &mut self,
12176 ranges: &[Range<Anchor>],
12177 color_fetcher: fn(&ThemeColors) -> Hsla,
12178 cx: &mut ViewContext<Self>,
12179 ) {
12180 self.background_highlights
12181 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12182 self.scrollbar_marker_state.dirty = true;
12183 cx.notify();
12184 }
12185
12186 pub fn clear_background_highlights<T: 'static>(
12187 &mut self,
12188 cx: &mut ViewContext<Self>,
12189 ) -> Option<BackgroundHighlight> {
12190 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12191 if !text_highlights.1.is_empty() {
12192 self.scrollbar_marker_state.dirty = true;
12193 cx.notify();
12194 }
12195 Some(text_highlights)
12196 }
12197
12198 pub fn highlight_gutter<T: 'static>(
12199 &mut self,
12200 ranges: &[Range<Anchor>],
12201 color_fetcher: fn(&AppContext) -> Hsla,
12202 cx: &mut ViewContext<Self>,
12203 ) {
12204 self.gutter_highlights
12205 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12206 cx.notify();
12207 }
12208
12209 pub fn clear_gutter_highlights<T: 'static>(
12210 &mut self,
12211 cx: &mut ViewContext<Self>,
12212 ) -> Option<GutterHighlight> {
12213 cx.notify();
12214 self.gutter_highlights.remove(&TypeId::of::<T>())
12215 }
12216
12217 #[cfg(feature = "test-support")]
12218 pub fn all_text_background_highlights(
12219 &mut self,
12220 cx: &mut ViewContext<Self>,
12221 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12222 let snapshot = self.snapshot(cx);
12223 let buffer = &snapshot.buffer_snapshot;
12224 let start = buffer.anchor_before(0);
12225 let end = buffer.anchor_after(buffer.len());
12226 let theme = cx.theme().colors();
12227 self.background_highlights_in_range(start..end, &snapshot, theme)
12228 }
12229
12230 #[cfg(feature = "test-support")]
12231 pub fn search_background_highlights(
12232 &mut self,
12233 cx: &mut ViewContext<Self>,
12234 ) -> Vec<Range<Point>> {
12235 let snapshot = self.buffer().read(cx).snapshot(cx);
12236
12237 let highlights = self
12238 .background_highlights
12239 .get(&TypeId::of::<items::BufferSearchHighlights>());
12240
12241 if let Some((_color, ranges)) = highlights {
12242 ranges
12243 .iter()
12244 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12245 .collect_vec()
12246 } else {
12247 vec![]
12248 }
12249 }
12250
12251 fn document_highlights_for_position<'a>(
12252 &'a self,
12253 position: Anchor,
12254 buffer: &'a MultiBufferSnapshot,
12255 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12256 let read_highlights = self
12257 .background_highlights
12258 .get(&TypeId::of::<DocumentHighlightRead>())
12259 .map(|h| &h.1);
12260 let write_highlights = self
12261 .background_highlights
12262 .get(&TypeId::of::<DocumentHighlightWrite>())
12263 .map(|h| &h.1);
12264 let left_position = position.bias_left(buffer);
12265 let right_position = position.bias_right(buffer);
12266 read_highlights
12267 .into_iter()
12268 .chain(write_highlights)
12269 .flat_map(move |ranges| {
12270 let start_ix = match ranges.binary_search_by(|probe| {
12271 let cmp = probe.end.cmp(&left_position, buffer);
12272 if cmp.is_ge() {
12273 Ordering::Greater
12274 } else {
12275 Ordering::Less
12276 }
12277 }) {
12278 Ok(i) | Err(i) => i,
12279 };
12280
12281 ranges[start_ix..]
12282 .iter()
12283 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12284 })
12285 }
12286
12287 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12288 self.background_highlights
12289 .get(&TypeId::of::<T>())
12290 .map_or(false, |(_, highlights)| !highlights.is_empty())
12291 }
12292
12293 pub fn background_highlights_in_range(
12294 &self,
12295 search_range: Range<Anchor>,
12296 display_snapshot: &DisplaySnapshot,
12297 theme: &ThemeColors,
12298 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12299 let mut results = Vec::new();
12300 for (color_fetcher, ranges) in self.background_highlights.values() {
12301 let color = color_fetcher(theme);
12302 let start_ix = match ranges.binary_search_by(|probe| {
12303 let cmp = probe
12304 .end
12305 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12306 if cmp.is_gt() {
12307 Ordering::Greater
12308 } else {
12309 Ordering::Less
12310 }
12311 }) {
12312 Ok(i) | Err(i) => i,
12313 };
12314 for range in &ranges[start_ix..] {
12315 if range
12316 .start
12317 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12318 .is_ge()
12319 {
12320 break;
12321 }
12322
12323 let start = range.start.to_display_point(display_snapshot);
12324 let end = range.end.to_display_point(display_snapshot);
12325 results.push((start..end, color))
12326 }
12327 }
12328 results
12329 }
12330
12331 pub fn background_highlight_row_ranges<T: 'static>(
12332 &self,
12333 search_range: Range<Anchor>,
12334 display_snapshot: &DisplaySnapshot,
12335 count: usize,
12336 ) -> Vec<RangeInclusive<DisplayPoint>> {
12337 let mut results = Vec::new();
12338 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12339 return vec![];
12340 };
12341
12342 let start_ix = match ranges.binary_search_by(|probe| {
12343 let cmp = probe
12344 .end
12345 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12346 if cmp.is_gt() {
12347 Ordering::Greater
12348 } else {
12349 Ordering::Less
12350 }
12351 }) {
12352 Ok(i) | Err(i) => i,
12353 };
12354 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12355 if let (Some(start_display), Some(end_display)) = (start, end) {
12356 results.push(
12357 start_display.to_display_point(display_snapshot)
12358 ..=end_display.to_display_point(display_snapshot),
12359 );
12360 }
12361 };
12362 let mut start_row: Option<Point> = None;
12363 let mut end_row: Option<Point> = None;
12364 if ranges.len() > count {
12365 return Vec::new();
12366 }
12367 for range in &ranges[start_ix..] {
12368 if range
12369 .start
12370 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12371 .is_ge()
12372 {
12373 break;
12374 }
12375 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12376 if let Some(current_row) = &end_row {
12377 if end.row == current_row.row {
12378 continue;
12379 }
12380 }
12381 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12382 if start_row.is_none() {
12383 assert_eq!(end_row, None);
12384 start_row = Some(start);
12385 end_row = Some(end);
12386 continue;
12387 }
12388 if let Some(current_end) = end_row.as_mut() {
12389 if start.row > current_end.row + 1 {
12390 push_region(start_row, end_row);
12391 start_row = Some(start);
12392 end_row = Some(end);
12393 } else {
12394 // Merge two hunks.
12395 *current_end = end;
12396 }
12397 } else {
12398 unreachable!();
12399 }
12400 }
12401 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12402 push_region(start_row, end_row);
12403 results
12404 }
12405
12406 pub fn gutter_highlights_in_range(
12407 &self,
12408 search_range: Range<Anchor>,
12409 display_snapshot: &DisplaySnapshot,
12410 cx: &AppContext,
12411 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12412 let mut results = Vec::new();
12413 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12414 let color = color_fetcher(cx);
12415 let start_ix = match ranges.binary_search_by(|probe| {
12416 let cmp = probe
12417 .end
12418 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12419 if cmp.is_gt() {
12420 Ordering::Greater
12421 } else {
12422 Ordering::Less
12423 }
12424 }) {
12425 Ok(i) | Err(i) => i,
12426 };
12427 for range in &ranges[start_ix..] {
12428 if range
12429 .start
12430 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12431 .is_ge()
12432 {
12433 break;
12434 }
12435
12436 let start = range.start.to_display_point(display_snapshot);
12437 let end = range.end.to_display_point(display_snapshot);
12438 results.push((start..end, color))
12439 }
12440 }
12441 results
12442 }
12443
12444 /// Get the text ranges corresponding to the redaction query
12445 pub fn redacted_ranges(
12446 &self,
12447 search_range: Range<Anchor>,
12448 display_snapshot: &DisplaySnapshot,
12449 cx: &WindowContext,
12450 ) -> Vec<Range<DisplayPoint>> {
12451 display_snapshot
12452 .buffer_snapshot
12453 .redacted_ranges(search_range, |file| {
12454 if let Some(file) = file {
12455 file.is_private()
12456 && EditorSettings::get(
12457 Some(SettingsLocation {
12458 worktree_id: file.worktree_id(cx),
12459 path: file.path().as_ref(),
12460 }),
12461 cx,
12462 )
12463 .redact_private_values
12464 } else {
12465 false
12466 }
12467 })
12468 .map(|range| {
12469 range.start.to_display_point(display_snapshot)
12470 ..range.end.to_display_point(display_snapshot)
12471 })
12472 .collect()
12473 }
12474
12475 pub fn highlight_text<T: 'static>(
12476 &mut self,
12477 ranges: Vec<Range<Anchor>>,
12478 style: HighlightStyle,
12479 cx: &mut ViewContext<Self>,
12480 ) {
12481 self.display_map.update(cx, |map, _| {
12482 map.highlight_text(TypeId::of::<T>(), ranges, style)
12483 });
12484 cx.notify();
12485 }
12486
12487 pub(crate) fn highlight_inlays<T: 'static>(
12488 &mut self,
12489 highlights: Vec<InlayHighlight>,
12490 style: HighlightStyle,
12491 cx: &mut ViewContext<Self>,
12492 ) {
12493 self.display_map.update(cx, |map, _| {
12494 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12495 });
12496 cx.notify();
12497 }
12498
12499 pub fn text_highlights<'a, T: 'static>(
12500 &'a self,
12501 cx: &'a AppContext,
12502 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12503 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12504 }
12505
12506 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12507 let cleared = self
12508 .display_map
12509 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12510 if cleared {
12511 cx.notify();
12512 }
12513 }
12514
12515 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12516 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12517 && self.focus_handle.is_focused(cx)
12518 }
12519
12520 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12521 self.show_cursor_when_unfocused = is_enabled;
12522 cx.notify();
12523 }
12524
12525 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12526 cx.notify();
12527 }
12528
12529 fn on_buffer_event(
12530 &mut self,
12531 multibuffer: Model<MultiBuffer>,
12532 event: &multi_buffer::Event,
12533 cx: &mut ViewContext<Self>,
12534 ) {
12535 match event {
12536 multi_buffer::Event::Edited {
12537 singleton_buffer_edited,
12538 } => {
12539 self.scrollbar_marker_state.dirty = true;
12540 self.active_indent_guides_state.dirty = true;
12541 self.refresh_active_diagnostics(cx);
12542 self.refresh_code_actions(cx);
12543 if self.has_active_inline_completion(cx) {
12544 self.update_visible_inline_completion(cx);
12545 }
12546 cx.emit(EditorEvent::BufferEdited);
12547 cx.emit(SearchEvent::MatchesInvalidated);
12548 if *singleton_buffer_edited {
12549 if let Some(project) = &self.project {
12550 let project = project.read(cx);
12551 #[allow(clippy::mutable_key_type)]
12552 let languages_affected = multibuffer
12553 .read(cx)
12554 .all_buffers()
12555 .into_iter()
12556 .filter_map(|buffer| {
12557 let buffer = buffer.read(cx);
12558 let language = buffer.language()?;
12559 if project.is_local()
12560 && project.language_servers_for_buffer(buffer, cx).count() == 0
12561 {
12562 None
12563 } else {
12564 Some(language)
12565 }
12566 })
12567 .cloned()
12568 .collect::<HashSet<_>>();
12569 if !languages_affected.is_empty() {
12570 self.refresh_inlay_hints(
12571 InlayHintRefreshReason::BufferEdited(languages_affected),
12572 cx,
12573 );
12574 }
12575 }
12576 }
12577
12578 let Some(project) = &self.project else { return };
12579 let (telemetry, is_via_ssh) = {
12580 let project = project.read(cx);
12581 let telemetry = project.client().telemetry().clone();
12582 let is_via_ssh = project.is_via_ssh();
12583 (telemetry, is_via_ssh)
12584 };
12585 refresh_linked_ranges(self, cx);
12586 telemetry.log_edit_event("editor", is_via_ssh);
12587 }
12588 multi_buffer::Event::ExcerptsAdded {
12589 buffer,
12590 predecessor,
12591 excerpts,
12592 } => {
12593 self.tasks_update_task = Some(self.refresh_runnables(cx));
12594 cx.emit(EditorEvent::ExcerptsAdded {
12595 buffer: buffer.clone(),
12596 predecessor: *predecessor,
12597 excerpts: excerpts.clone(),
12598 });
12599 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12600 }
12601 multi_buffer::Event::ExcerptsRemoved { ids } => {
12602 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12603 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12604 }
12605 multi_buffer::Event::ExcerptsEdited { ids } => {
12606 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12607 }
12608 multi_buffer::Event::ExcerptsExpanded { ids } => {
12609 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12610 }
12611 multi_buffer::Event::Reparsed(buffer_id) => {
12612 self.tasks_update_task = Some(self.refresh_runnables(cx));
12613
12614 cx.emit(EditorEvent::Reparsed(*buffer_id));
12615 }
12616 multi_buffer::Event::LanguageChanged(buffer_id) => {
12617 linked_editing_ranges::refresh_linked_ranges(self, cx);
12618 cx.emit(EditorEvent::Reparsed(*buffer_id));
12619 cx.notify();
12620 }
12621 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12622 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12623 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12624 cx.emit(EditorEvent::TitleChanged)
12625 }
12626 multi_buffer::Event::DiffBaseChanged => {
12627 self.scrollbar_marker_state.dirty = true;
12628 cx.emit(EditorEvent::DiffBaseChanged);
12629 cx.notify();
12630 }
12631 multi_buffer::Event::DiffUpdated { buffer } => {
12632 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12633 cx.notify();
12634 }
12635 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12636 multi_buffer::Event::DiagnosticsUpdated => {
12637 self.refresh_active_diagnostics(cx);
12638 self.scrollbar_marker_state.dirty = true;
12639 cx.notify();
12640 }
12641 _ => {}
12642 };
12643 }
12644
12645 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12646 cx.notify();
12647 }
12648
12649 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12650 self.tasks_update_task = Some(self.refresh_runnables(cx));
12651 self.refresh_inline_completion(true, false, cx);
12652 self.refresh_inlay_hints(
12653 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12654 self.selections.newest_anchor().head(),
12655 &self.buffer.read(cx).snapshot(cx),
12656 cx,
12657 )),
12658 cx,
12659 );
12660
12661 let old_cursor_shape = self.cursor_shape;
12662
12663 {
12664 let editor_settings = EditorSettings::get_global(cx);
12665 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12666 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12667 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12668 }
12669
12670 if old_cursor_shape != self.cursor_shape {
12671 cx.emit(EditorEvent::CursorShapeChanged);
12672 }
12673
12674 let project_settings = ProjectSettings::get_global(cx);
12675 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12676
12677 if self.mode == EditorMode::Full {
12678 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12679 if self.git_blame_inline_enabled != inline_blame_enabled {
12680 self.toggle_git_blame_inline_internal(false, cx);
12681 }
12682 }
12683
12684 cx.notify();
12685 }
12686
12687 pub fn set_searchable(&mut self, searchable: bool) {
12688 self.searchable = searchable;
12689 }
12690
12691 pub fn searchable(&self) -> bool {
12692 self.searchable
12693 }
12694
12695 fn open_proposed_changes_editor(
12696 &mut self,
12697 _: &OpenProposedChangesEditor,
12698 cx: &mut ViewContext<Self>,
12699 ) {
12700 let Some(workspace) = self.workspace() else {
12701 cx.propagate();
12702 return;
12703 };
12704
12705 let selections = self.selections.all::<usize>(cx);
12706 let buffer = self.buffer.read(cx);
12707 let mut new_selections_by_buffer = HashMap::default();
12708 for selection in selections {
12709 for (buffer, range, _) in
12710 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12711 {
12712 let mut range = range.to_point(buffer.read(cx));
12713 range.start.column = 0;
12714 range.end.column = buffer.read(cx).line_len(range.end.row);
12715 new_selections_by_buffer
12716 .entry(buffer)
12717 .or_insert(Vec::new())
12718 .push(range)
12719 }
12720 }
12721
12722 let proposed_changes_buffers = new_selections_by_buffer
12723 .into_iter()
12724 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12725 .collect::<Vec<_>>();
12726 let proposed_changes_editor = cx.new_view(|cx| {
12727 ProposedChangesEditor::new(
12728 "Proposed changes",
12729 proposed_changes_buffers,
12730 self.project.clone(),
12731 cx,
12732 )
12733 });
12734
12735 cx.window_context().defer(move |cx| {
12736 workspace.update(cx, |workspace, cx| {
12737 workspace.active_pane().update(cx, |pane, cx| {
12738 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12739 });
12740 });
12741 });
12742 }
12743
12744 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12745 self.open_excerpts_common(None, true, cx)
12746 }
12747
12748 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12749 self.open_excerpts_common(None, false, cx)
12750 }
12751
12752 fn open_excerpts_common(
12753 &mut self,
12754 jump_data: Option<JumpData>,
12755 split: bool,
12756 cx: &mut ViewContext<Self>,
12757 ) {
12758 let Some(workspace) = self.workspace() else {
12759 cx.propagate();
12760 return;
12761 };
12762
12763 if self.buffer.read(cx).is_singleton() {
12764 cx.propagate();
12765 return;
12766 }
12767
12768 let mut new_selections_by_buffer = HashMap::default();
12769 match &jump_data {
12770 Some(jump_data) => {
12771 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12772 if let Some(buffer) = multi_buffer_snapshot
12773 .buffer_id_for_excerpt(jump_data.excerpt_id)
12774 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12775 {
12776 let buffer_snapshot = buffer.read(cx).snapshot();
12777 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12778 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12779 } else {
12780 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12781 };
12782 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12783 new_selections_by_buffer.insert(
12784 buffer,
12785 (
12786 vec![jump_to_offset..jump_to_offset],
12787 Some(jump_data.line_offset_from_top),
12788 ),
12789 );
12790 }
12791 }
12792 None => {
12793 let selections = self.selections.all::<usize>(cx);
12794 let buffer = self.buffer.read(cx);
12795 for selection in selections {
12796 for (mut buffer_handle, mut range, _) in
12797 buffer.range_to_buffer_ranges(selection.range(), cx)
12798 {
12799 // When editing branch buffers, jump to the corresponding location
12800 // in their base buffer.
12801 let buffer = buffer_handle.read(cx);
12802 if let Some(base_buffer) = buffer.diff_base_buffer() {
12803 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12804 buffer_handle = base_buffer;
12805 }
12806
12807 if selection.reversed {
12808 mem::swap(&mut range.start, &mut range.end);
12809 }
12810 new_selections_by_buffer
12811 .entry(buffer_handle)
12812 .or_insert((Vec::new(), None))
12813 .0
12814 .push(range)
12815 }
12816 }
12817 }
12818 }
12819
12820 if new_selections_by_buffer.is_empty() {
12821 return;
12822 }
12823
12824 // We defer the pane interaction because we ourselves are a workspace item
12825 // and activating a new item causes the pane to call a method on us reentrantly,
12826 // which panics if we're on the stack.
12827 cx.window_context().defer(move |cx| {
12828 workspace.update(cx, |workspace, cx| {
12829 let pane = if split {
12830 workspace.adjacent_pane(cx)
12831 } else {
12832 workspace.active_pane().clone()
12833 };
12834
12835 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12836 let editor =
12837 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12838 editor.update(cx, |editor, cx| {
12839 let autoscroll = match scroll_offset {
12840 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12841 None => Autoscroll::newest(),
12842 };
12843 let nav_history = editor.nav_history.take();
12844 editor.change_selections(Some(autoscroll), cx, |s| {
12845 s.select_ranges(ranges);
12846 });
12847 editor.nav_history = nav_history;
12848 });
12849 }
12850 })
12851 });
12852 }
12853
12854 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12855 let snapshot = self.buffer.read(cx).read(cx);
12856 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12857 Some(
12858 ranges
12859 .iter()
12860 .map(move |range| {
12861 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12862 })
12863 .collect(),
12864 )
12865 }
12866
12867 fn selection_replacement_ranges(
12868 &self,
12869 range: Range<OffsetUtf16>,
12870 cx: &mut AppContext,
12871 ) -> Vec<Range<OffsetUtf16>> {
12872 let selections = self.selections.all::<OffsetUtf16>(cx);
12873 let newest_selection = selections
12874 .iter()
12875 .max_by_key(|selection| selection.id)
12876 .unwrap();
12877 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12878 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12879 let snapshot = self.buffer.read(cx).read(cx);
12880 selections
12881 .into_iter()
12882 .map(|mut selection| {
12883 selection.start.0 =
12884 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12885 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12886 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12887 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12888 })
12889 .collect()
12890 }
12891
12892 fn report_editor_event(
12893 &self,
12894 operation: &'static str,
12895 file_extension: Option<String>,
12896 cx: &AppContext,
12897 ) {
12898 if cfg!(any(test, feature = "test-support")) {
12899 return;
12900 }
12901
12902 let Some(project) = &self.project else { return };
12903
12904 // If None, we are in a file without an extension
12905 let file = self
12906 .buffer
12907 .read(cx)
12908 .as_singleton()
12909 .and_then(|b| b.read(cx).file());
12910 let file_extension = file_extension.or(file
12911 .as_ref()
12912 .and_then(|file| Path::new(file.file_name(cx)).extension())
12913 .and_then(|e| e.to_str())
12914 .map(|a| a.to_string()));
12915
12916 let vim_mode = cx
12917 .global::<SettingsStore>()
12918 .raw_user_settings()
12919 .get("vim_mode")
12920 == Some(&serde_json::Value::Bool(true));
12921
12922 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12923 == language::language_settings::InlineCompletionProvider::Copilot;
12924 let copilot_enabled_for_language = self
12925 .buffer
12926 .read(cx)
12927 .settings_at(0, cx)
12928 .show_inline_completions;
12929
12930 let project = project.read(cx);
12931 let telemetry = project.client().telemetry().clone();
12932 telemetry.report_editor_event(
12933 file_extension,
12934 vim_mode,
12935 operation,
12936 copilot_enabled,
12937 copilot_enabled_for_language,
12938 project.is_via_ssh(),
12939 )
12940 }
12941
12942 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12943 /// with each line being an array of {text, highlight} objects.
12944 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12945 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12946 return;
12947 };
12948
12949 #[derive(Serialize)]
12950 struct Chunk<'a> {
12951 text: String,
12952 highlight: Option<&'a str>,
12953 }
12954
12955 let snapshot = buffer.read(cx).snapshot();
12956 let range = self
12957 .selected_text_range(false, cx)
12958 .and_then(|selection| {
12959 if selection.range.is_empty() {
12960 None
12961 } else {
12962 Some(selection.range)
12963 }
12964 })
12965 .unwrap_or_else(|| 0..snapshot.len());
12966
12967 let chunks = snapshot.chunks(range, true);
12968 let mut lines = Vec::new();
12969 let mut line: VecDeque<Chunk> = VecDeque::new();
12970
12971 let Some(style) = self.style.as_ref() else {
12972 return;
12973 };
12974
12975 for chunk in chunks {
12976 let highlight = chunk
12977 .syntax_highlight_id
12978 .and_then(|id| id.name(&style.syntax));
12979 let mut chunk_lines = chunk.text.split('\n').peekable();
12980 while let Some(text) = chunk_lines.next() {
12981 let mut merged_with_last_token = false;
12982 if let Some(last_token) = line.back_mut() {
12983 if last_token.highlight == highlight {
12984 last_token.text.push_str(text);
12985 merged_with_last_token = true;
12986 }
12987 }
12988
12989 if !merged_with_last_token {
12990 line.push_back(Chunk {
12991 text: text.into(),
12992 highlight,
12993 });
12994 }
12995
12996 if chunk_lines.peek().is_some() {
12997 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12998 line.pop_front();
12999 }
13000 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13001 line.pop_back();
13002 }
13003
13004 lines.push(mem::take(&mut line));
13005 }
13006 }
13007 }
13008
13009 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13010 return;
13011 };
13012 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13013 }
13014
13015 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13016 &self.inlay_hint_cache
13017 }
13018
13019 pub fn replay_insert_event(
13020 &mut self,
13021 text: &str,
13022 relative_utf16_range: Option<Range<isize>>,
13023 cx: &mut ViewContext<Self>,
13024 ) {
13025 if !self.input_enabled {
13026 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13027 return;
13028 }
13029 if let Some(relative_utf16_range) = relative_utf16_range {
13030 let selections = self.selections.all::<OffsetUtf16>(cx);
13031 self.change_selections(None, cx, |s| {
13032 let new_ranges = selections.into_iter().map(|range| {
13033 let start = OffsetUtf16(
13034 range
13035 .head()
13036 .0
13037 .saturating_add_signed(relative_utf16_range.start),
13038 );
13039 let end = OffsetUtf16(
13040 range
13041 .head()
13042 .0
13043 .saturating_add_signed(relative_utf16_range.end),
13044 );
13045 start..end
13046 });
13047 s.select_ranges(new_ranges);
13048 });
13049 }
13050
13051 self.handle_input(text, cx);
13052 }
13053
13054 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13055 let Some(provider) = self.semantics_provider.as_ref() else {
13056 return false;
13057 };
13058
13059 let mut supports = false;
13060 self.buffer().read(cx).for_each_buffer(|buffer| {
13061 supports |= provider.supports_inlay_hints(buffer, cx);
13062 });
13063 supports
13064 }
13065
13066 pub fn focus(&self, cx: &mut WindowContext) {
13067 cx.focus(&self.focus_handle)
13068 }
13069
13070 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13071 self.focus_handle.is_focused(cx)
13072 }
13073
13074 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13075 cx.emit(EditorEvent::Focused);
13076
13077 if let Some(descendant) = self
13078 .last_focused_descendant
13079 .take()
13080 .and_then(|descendant| descendant.upgrade())
13081 {
13082 cx.focus(&descendant);
13083 } else {
13084 if let Some(blame) = self.blame.as_ref() {
13085 blame.update(cx, GitBlame::focus)
13086 }
13087
13088 self.blink_manager.update(cx, BlinkManager::enable);
13089 self.show_cursor_names(cx);
13090 self.buffer.update(cx, |buffer, cx| {
13091 buffer.finalize_last_transaction(cx);
13092 if self.leader_peer_id.is_none() {
13093 buffer.set_active_selections(
13094 &self.selections.disjoint_anchors(),
13095 self.selections.line_mode,
13096 self.cursor_shape,
13097 cx,
13098 );
13099 }
13100 });
13101 }
13102 }
13103
13104 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13105 cx.emit(EditorEvent::FocusedIn)
13106 }
13107
13108 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13109 if event.blurred != self.focus_handle {
13110 self.last_focused_descendant = Some(event.blurred);
13111 }
13112 }
13113
13114 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13115 self.blink_manager.update(cx, BlinkManager::disable);
13116 self.buffer
13117 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13118
13119 if let Some(blame) = self.blame.as_ref() {
13120 blame.update(cx, GitBlame::blur)
13121 }
13122 if !self.hover_state.focused(cx) {
13123 hide_hover(self, cx);
13124 }
13125
13126 self.hide_context_menu(cx);
13127 cx.emit(EditorEvent::Blurred);
13128 cx.notify();
13129 }
13130
13131 pub fn register_action<A: Action>(
13132 &mut self,
13133 listener: impl Fn(&A, &mut WindowContext) + 'static,
13134 ) -> Subscription {
13135 let id = self.next_editor_action_id.post_inc();
13136 let listener = Arc::new(listener);
13137 self.editor_actions.borrow_mut().insert(
13138 id,
13139 Box::new(move |cx| {
13140 let cx = cx.window_context();
13141 let listener = listener.clone();
13142 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13143 let action = action.downcast_ref().unwrap();
13144 if phase == DispatchPhase::Bubble {
13145 listener(action, cx)
13146 }
13147 })
13148 }),
13149 );
13150
13151 let editor_actions = self.editor_actions.clone();
13152 Subscription::new(move || {
13153 editor_actions.borrow_mut().remove(&id);
13154 })
13155 }
13156
13157 pub fn file_header_size(&self) -> u32 {
13158 FILE_HEADER_HEIGHT
13159 }
13160
13161 pub fn revert(
13162 &mut self,
13163 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13164 cx: &mut ViewContext<Self>,
13165 ) {
13166 self.buffer().update(cx, |multi_buffer, cx| {
13167 for (buffer_id, changes) in revert_changes {
13168 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13169 buffer.update(cx, |buffer, cx| {
13170 buffer.edit(
13171 changes.into_iter().map(|(range, text)| {
13172 (range, text.to_string().map(Arc::<str>::from))
13173 }),
13174 None,
13175 cx,
13176 );
13177 });
13178 }
13179 }
13180 });
13181 self.change_selections(None, cx, |selections| selections.refresh());
13182 }
13183
13184 pub fn to_pixel_point(
13185 &mut self,
13186 source: multi_buffer::Anchor,
13187 editor_snapshot: &EditorSnapshot,
13188 cx: &mut ViewContext<Self>,
13189 ) -> Option<gpui::Point<Pixels>> {
13190 let source_point = source.to_display_point(editor_snapshot);
13191 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13192 }
13193
13194 pub fn display_to_pixel_point(
13195 &mut self,
13196 source: DisplayPoint,
13197 editor_snapshot: &EditorSnapshot,
13198 cx: &mut ViewContext<Self>,
13199 ) -> Option<gpui::Point<Pixels>> {
13200 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13201 let text_layout_details = self.text_layout_details(cx);
13202 let scroll_top = text_layout_details
13203 .scroll_anchor
13204 .scroll_position(editor_snapshot)
13205 .y;
13206
13207 if source.row().as_f32() < scroll_top.floor() {
13208 return None;
13209 }
13210 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13211 let source_y = line_height * (source.row().as_f32() - scroll_top);
13212 Some(gpui::Point::new(source_x, source_y))
13213 }
13214
13215 pub fn has_active_completions_menu(&self) -> bool {
13216 self.context_menu.read().as_ref().map_or(false, |menu| {
13217 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13218 })
13219 }
13220
13221 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13222 self.addons
13223 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13224 }
13225
13226 pub fn unregister_addon<T: Addon>(&mut self) {
13227 self.addons.remove(&std::any::TypeId::of::<T>());
13228 }
13229
13230 pub fn addon<T: Addon>(&self) -> Option<&T> {
13231 let type_id = std::any::TypeId::of::<T>();
13232 self.addons
13233 .get(&type_id)
13234 .and_then(|item| item.to_any().downcast_ref::<T>())
13235 }
13236}
13237
13238fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13239 let tab_size = tab_size.get() as usize;
13240 let mut width = offset;
13241
13242 for ch in text.chars() {
13243 width += if ch == '\t' {
13244 tab_size - (width % tab_size)
13245 } else {
13246 1
13247 };
13248 }
13249
13250 width - offset
13251}
13252
13253#[cfg(test)]
13254mod tests {
13255 use super::*;
13256
13257 #[test]
13258 fn test_string_size_with_expanded_tabs() {
13259 let nz = |val| NonZeroU32::new(val).unwrap();
13260 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13261 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13262 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13263 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13264 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13265 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13266 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13267 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13268 }
13269}
13270
13271/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13272struct WordBreakingTokenizer<'a> {
13273 input: &'a str,
13274}
13275
13276impl<'a> WordBreakingTokenizer<'a> {
13277 fn new(input: &'a str) -> Self {
13278 Self { input }
13279 }
13280}
13281
13282fn is_char_ideographic(ch: char) -> bool {
13283 use unicode_script::Script::*;
13284 use unicode_script::UnicodeScript;
13285 matches!(ch.script(), Han | Tangut | Yi)
13286}
13287
13288fn is_grapheme_ideographic(text: &str) -> bool {
13289 text.chars().any(is_char_ideographic)
13290}
13291
13292fn is_grapheme_whitespace(text: &str) -> bool {
13293 text.chars().any(|x| x.is_whitespace())
13294}
13295
13296fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13297 text.chars().next().map_or(false, |ch| {
13298 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13299 })
13300}
13301
13302#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13303struct WordBreakToken<'a> {
13304 token: &'a str,
13305 grapheme_len: usize,
13306 is_whitespace: bool,
13307}
13308
13309impl<'a> Iterator for WordBreakingTokenizer<'a> {
13310 /// Yields a span, the count of graphemes in the token, and whether it was
13311 /// whitespace. Note that it also breaks at word boundaries.
13312 type Item = WordBreakToken<'a>;
13313
13314 fn next(&mut self) -> Option<Self::Item> {
13315 use unicode_segmentation::UnicodeSegmentation;
13316 if self.input.is_empty() {
13317 return None;
13318 }
13319
13320 let mut iter = self.input.graphemes(true).peekable();
13321 let mut offset = 0;
13322 let mut graphemes = 0;
13323 if let Some(first_grapheme) = iter.next() {
13324 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13325 offset += first_grapheme.len();
13326 graphemes += 1;
13327 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13328 if let Some(grapheme) = iter.peek().copied() {
13329 if should_stay_with_preceding_ideograph(grapheme) {
13330 offset += grapheme.len();
13331 graphemes += 1;
13332 }
13333 }
13334 } else {
13335 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13336 let mut next_word_bound = words.peek().copied();
13337 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13338 next_word_bound = words.next();
13339 }
13340 while let Some(grapheme) = iter.peek().copied() {
13341 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13342 break;
13343 };
13344 if is_grapheme_whitespace(grapheme) != is_whitespace {
13345 break;
13346 };
13347 offset += grapheme.len();
13348 graphemes += 1;
13349 iter.next();
13350 }
13351 }
13352 let token = &self.input[..offset];
13353 self.input = &self.input[offset..];
13354 if is_whitespace {
13355 Some(WordBreakToken {
13356 token: " ",
13357 grapheme_len: 1,
13358 is_whitespace: true,
13359 })
13360 } else {
13361 Some(WordBreakToken {
13362 token,
13363 grapheme_len: graphemes,
13364 is_whitespace: false,
13365 })
13366 }
13367 } else {
13368 None
13369 }
13370 }
13371}
13372
13373#[test]
13374fn test_word_breaking_tokenizer() {
13375 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13376 ("", &[]),
13377 (" ", &[(" ", 1, true)]),
13378 ("Ʒ", &[("Ʒ", 1, false)]),
13379 ("Ǽ", &[("Ǽ", 1, false)]),
13380 ("⋑", &[("⋑", 1, false)]),
13381 ("⋑⋑", &[("⋑⋑", 2, false)]),
13382 (
13383 "原理,进而",
13384 &[
13385 ("原", 1, false),
13386 ("理,", 2, false),
13387 ("进", 1, false),
13388 ("而", 1, false),
13389 ],
13390 ),
13391 (
13392 "hello world",
13393 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13394 ),
13395 (
13396 "hello, world",
13397 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13398 ),
13399 (
13400 " hello world",
13401 &[
13402 (" ", 1, true),
13403 ("hello", 5, false),
13404 (" ", 1, true),
13405 ("world", 5, false),
13406 ],
13407 ),
13408 (
13409 "这是什么 \n 钢笔",
13410 &[
13411 ("这", 1, false),
13412 ("是", 1, false),
13413 ("什", 1, false),
13414 ("么", 1, false),
13415 (" ", 1, true),
13416 ("钢", 1, false),
13417 ("笔", 1, false),
13418 ],
13419 ),
13420 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13421 ];
13422
13423 for (input, result) in tests {
13424 assert_eq!(
13425 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13426 result
13427 .iter()
13428 .copied()
13429 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13430 token,
13431 grapheme_len,
13432 is_whitespace,
13433 })
13434 .collect::<Vec<_>>()
13435 );
13436 }
13437}
13438
13439fn wrap_with_prefix(
13440 line_prefix: String,
13441 unwrapped_text: String,
13442 wrap_column: usize,
13443 tab_size: NonZeroU32,
13444) -> String {
13445 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13446 let mut wrapped_text = String::new();
13447 let mut current_line = line_prefix.clone();
13448
13449 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13450 let mut current_line_len = line_prefix_len;
13451 for WordBreakToken {
13452 token,
13453 grapheme_len,
13454 is_whitespace,
13455 } in tokenizer
13456 {
13457 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13458 wrapped_text.push_str(current_line.trim_end());
13459 wrapped_text.push('\n');
13460 current_line.truncate(line_prefix.len());
13461 current_line_len = line_prefix_len;
13462 if !is_whitespace {
13463 current_line.push_str(token);
13464 current_line_len += grapheme_len;
13465 }
13466 } else if !is_whitespace {
13467 current_line.push_str(token);
13468 current_line_len += grapheme_len;
13469 } else if current_line_len != line_prefix_len {
13470 current_line.push(' ');
13471 current_line_len += 1;
13472 }
13473 }
13474
13475 if !current_line.is_empty() {
13476 wrapped_text.push_str(¤t_line);
13477 }
13478 wrapped_text
13479}
13480
13481#[test]
13482fn test_wrap_with_prefix() {
13483 assert_eq!(
13484 wrap_with_prefix(
13485 "# ".to_string(),
13486 "abcdefg".to_string(),
13487 4,
13488 NonZeroU32::new(4).unwrap()
13489 ),
13490 "# abcdefg"
13491 );
13492 assert_eq!(
13493 wrap_with_prefix(
13494 "".to_string(),
13495 "\thello world".to_string(),
13496 8,
13497 NonZeroU32::new(4).unwrap()
13498 ),
13499 "hello\nworld"
13500 );
13501 assert_eq!(
13502 wrap_with_prefix(
13503 "// ".to_string(),
13504 "xx \nyy zz aa bb cc".to_string(),
13505 12,
13506 NonZeroU32::new(4).unwrap()
13507 ),
13508 "// xx yy zz\n// aa bb cc"
13509 );
13510 assert_eq!(
13511 wrap_with_prefix(
13512 String::new(),
13513 "这是什么 \n 钢笔".to_string(),
13514 3,
13515 NonZeroU32::new(4).unwrap()
13516 ),
13517 "这是什\n么 钢\n笔"
13518 );
13519}
13520
13521fn hunks_for_selections(
13522 multi_buffer_snapshot: &MultiBufferSnapshot,
13523 selections: &[Selection<Anchor>],
13524) -> Vec<MultiBufferDiffHunk> {
13525 let buffer_rows_for_selections = selections.iter().map(|selection| {
13526 let head = selection.head();
13527 let tail = selection.tail();
13528 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13529 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13530 if start > end {
13531 end..start
13532 } else {
13533 start..end
13534 }
13535 });
13536
13537 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13538}
13539
13540pub fn hunks_for_rows(
13541 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13542 multi_buffer_snapshot: &MultiBufferSnapshot,
13543) -> Vec<MultiBufferDiffHunk> {
13544 let mut hunks = Vec::new();
13545 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13546 HashMap::default();
13547 for selected_multi_buffer_rows in rows {
13548 let query_rows =
13549 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13550 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13551 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13552 // when the caret is just above or just below the deleted hunk.
13553 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13554 let related_to_selection = if allow_adjacent {
13555 hunk.row_range.overlaps(&query_rows)
13556 || hunk.row_range.start == query_rows.end
13557 || hunk.row_range.end == query_rows.start
13558 } else {
13559 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13560 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13561 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13562 || selected_multi_buffer_rows.end == hunk.row_range.start
13563 };
13564 if related_to_selection {
13565 if !processed_buffer_rows
13566 .entry(hunk.buffer_id)
13567 .or_default()
13568 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13569 {
13570 continue;
13571 }
13572 hunks.push(hunk);
13573 }
13574 }
13575 }
13576
13577 hunks
13578}
13579
13580pub trait CollaborationHub {
13581 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13582 fn user_participant_indices<'a>(
13583 &self,
13584 cx: &'a AppContext,
13585 ) -> &'a HashMap<u64, ParticipantIndex>;
13586 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13587}
13588
13589impl CollaborationHub for Model<Project> {
13590 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13591 self.read(cx).collaborators()
13592 }
13593
13594 fn user_participant_indices<'a>(
13595 &self,
13596 cx: &'a AppContext,
13597 ) -> &'a HashMap<u64, ParticipantIndex> {
13598 self.read(cx).user_store().read(cx).participant_indices()
13599 }
13600
13601 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13602 let this = self.read(cx);
13603 let user_ids = this.collaborators().values().map(|c| c.user_id);
13604 this.user_store().read_with(cx, |user_store, cx| {
13605 user_store.participant_names(user_ids, cx)
13606 })
13607 }
13608}
13609
13610pub trait SemanticsProvider {
13611 fn hover(
13612 &self,
13613 buffer: &Model<Buffer>,
13614 position: text::Anchor,
13615 cx: &mut AppContext,
13616 ) -> Option<Task<Vec<project::Hover>>>;
13617
13618 fn inlay_hints(
13619 &self,
13620 buffer_handle: Model<Buffer>,
13621 range: Range<text::Anchor>,
13622 cx: &mut AppContext,
13623 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13624
13625 fn resolve_inlay_hint(
13626 &self,
13627 hint: InlayHint,
13628 buffer_handle: Model<Buffer>,
13629 server_id: LanguageServerId,
13630 cx: &mut AppContext,
13631 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13632
13633 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13634
13635 fn document_highlights(
13636 &self,
13637 buffer: &Model<Buffer>,
13638 position: text::Anchor,
13639 cx: &mut AppContext,
13640 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13641
13642 fn definitions(
13643 &self,
13644 buffer: &Model<Buffer>,
13645 position: text::Anchor,
13646 kind: GotoDefinitionKind,
13647 cx: &mut AppContext,
13648 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13649
13650 fn range_for_rename(
13651 &self,
13652 buffer: &Model<Buffer>,
13653 position: text::Anchor,
13654 cx: &mut AppContext,
13655 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13656
13657 fn perform_rename(
13658 &self,
13659 buffer: &Model<Buffer>,
13660 position: text::Anchor,
13661 new_name: String,
13662 cx: &mut AppContext,
13663 ) -> Option<Task<Result<ProjectTransaction>>>;
13664}
13665
13666pub trait CompletionProvider {
13667 fn completions(
13668 &self,
13669 buffer: &Model<Buffer>,
13670 buffer_position: text::Anchor,
13671 trigger: CompletionContext,
13672 cx: &mut ViewContext<Editor>,
13673 ) -> Task<Result<Vec<Completion>>>;
13674
13675 fn resolve_completions(
13676 &self,
13677 buffer: Model<Buffer>,
13678 completion_indices: Vec<usize>,
13679 completions: Arc<RwLock<Box<[Completion]>>>,
13680 cx: &mut ViewContext<Editor>,
13681 ) -> Task<Result<bool>>;
13682
13683 fn apply_additional_edits_for_completion(
13684 &self,
13685 buffer: Model<Buffer>,
13686 completion: Completion,
13687 push_to_history: bool,
13688 cx: &mut ViewContext<Editor>,
13689 ) -> Task<Result<Option<language::Transaction>>>;
13690
13691 fn is_completion_trigger(
13692 &self,
13693 buffer: &Model<Buffer>,
13694 position: language::Anchor,
13695 text: &str,
13696 trigger_in_words: bool,
13697 cx: &mut ViewContext<Editor>,
13698 ) -> bool;
13699
13700 fn sort_completions(&self) -> bool {
13701 true
13702 }
13703}
13704
13705pub trait CodeActionProvider {
13706 fn code_actions(
13707 &self,
13708 buffer: &Model<Buffer>,
13709 range: Range<text::Anchor>,
13710 cx: &mut WindowContext,
13711 ) -> Task<Result<Vec<CodeAction>>>;
13712
13713 fn apply_code_action(
13714 &self,
13715 buffer_handle: Model<Buffer>,
13716 action: CodeAction,
13717 excerpt_id: ExcerptId,
13718 push_to_history: bool,
13719 cx: &mut WindowContext,
13720 ) -> Task<Result<ProjectTransaction>>;
13721}
13722
13723impl CodeActionProvider for Model<Project> {
13724 fn code_actions(
13725 &self,
13726 buffer: &Model<Buffer>,
13727 range: Range<text::Anchor>,
13728 cx: &mut WindowContext,
13729 ) -> Task<Result<Vec<CodeAction>>> {
13730 self.update(cx, |project, cx| {
13731 project.code_actions(buffer, range, None, cx)
13732 })
13733 }
13734
13735 fn apply_code_action(
13736 &self,
13737 buffer_handle: Model<Buffer>,
13738 action: CodeAction,
13739 _excerpt_id: ExcerptId,
13740 push_to_history: bool,
13741 cx: &mut WindowContext,
13742 ) -> Task<Result<ProjectTransaction>> {
13743 self.update(cx, |project, cx| {
13744 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13745 })
13746 }
13747}
13748
13749fn snippet_completions(
13750 project: &Project,
13751 buffer: &Model<Buffer>,
13752 buffer_position: text::Anchor,
13753 cx: &mut AppContext,
13754) -> Vec<Completion> {
13755 let language = buffer.read(cx).language_at(buffer_position);
13756 let language_name = language.as_ref().map(|language| language.lsp_id());
13757 let snippet_store = project.snippets().read(cx);
13758 let snippets = snippet_store.snippets_for(language_name, cx);
13759
13760 if snippets.is_empty() {
13761 return vec![];
13762 }
13763 let snapshot = buffer.read(cx).text_snapshot();
13764 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13765
13766 let scope = language.map(|language| language.default_scope());
13767 let classifier = CharClassifier::new(scope).for_completion(true);
13768 let mut last_word = chars
13769 .take_while(|c| classifier.is_word(*c))
13770 .collect::<String>();
13771 last_word = last_word.chars().rev().collect();
13772 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13773 let to_lsp = |point: &text::Anchor| {
13774 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13775 point_to_lsp(end)
13776 };
13777 let lsp_end = to_lsp(&buffer_position);
13778 snippets
13779 .into_iter()
13780 .filter_map(|snippet| {
13781 let matching_prefix = snippet
13782 .prefix
13783 .iter()
13784 .find(|prefix| prefix.starts_with(&last_word))?;
13785 let start = as_offset - last_word.len();
13786 let start = snapshot.anchor_before(start);
13787 let range = start..buffer_position;
13788 let lsp_start = to_lsp(&start);
13789 let lsp_range = lsp::Range {
13790 start: lsp_start,
13791 end: lsp_end,
13792 };
13793 Some(Completion {
13794 old_range: range,
13795 new_text: snippet.body.clone(),
13796 label: CodeLabel {
13797 text: matching_prefix.clone(),
13798 runs: vec![],
13799 filter_range: 0..matching_prefix.len(),
13800 },
13801 server_id: LanguageServerId(usize::MAX),
13802 documentation: snippet.description.clone().map(Documentation::SingleLine),
13803 lsp_completion: lsp::CompletionItem {
13804 label: snippet.prefix.first().unwrap().clone(),
13805 kind: Some(CompletionItemKind::SNIPPET),
13806 label_details: snippet.description.as_ref().map(|description| {
13807 lsp::CompletionItemLabelDetails {
13808 detail: Some(description.clone()),
13809 description: None,
13810 }
13811 }),
13812 insert_text_format: Some(InsertTextFormat::SNIPPET),
13813 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13814 lsp::InsertReplaceEdit {
13815 new_text: snippet.body.clone(),
13816 insert: lsp_range,
13817 replace: lsp_range,
13818 },
13819 )),
13820 filter_text: Some(snippet.body.clone()),
13821 sort_text: Some(char::MAX.to_string()),
13822 ..Default::default()
13823 },
13824 confirm: None,
13825 })
13826 })
13827 .collect()
13828}
13829
13830impl CompletionProvider for Model<Project> {
13831 fn completions(
13832 &self,
13833 buffer: &Model<Buffer>,
13834 buffer_position: text::Anchor,
13835 options: CompletionContext,
13836 cx: &mut ViewContext<Editor>,
13837 ) -> Task<Result<Vec<Completion>>> {
13838 self.update(cx, |project, cx| {
13839 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13840 let project_completions = project.completions(buffer, buffer_position, options, cx);
13841 cx.background_executor().spawn(async move {
13842 let mut completions = project_completions.await?;
13843 //let snippets = snippets.into_iter().;
13844 completions.extend(snippets);
13845 Ok(completions)
13846 })
13847 })
13848 }
13849
13850 fn resolve_completions(
13851 &self,
13852 buffer: Model<Buffer>,
13853 completion_indices: Vec<usize>,
13854 completions: Arc<RwLock<Box<[Completion]>>>,
13855 cx: &mut ViewContext<Editor>,
13856 ) -> Task<Result<bool>> {
13857 self.update(cx, |project, cx| {
13858 project.resolve_completions(buffer, completion_indices, completions, cx)
13859 })
13860 }
13861
13862 fn apply_additional_edits_for_completion(
13863 &self,
13864 buffer: Model<Buffer>,
13865 completion: Completion,
13866 push_to_history: bool,
13867 cx: &mut ViewContext<Editor>,
13868 ) -> Task<Result<Option<language::Transaction>>> {
13869 self.update(cx, |project, cx| {
13870 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13871 })
13872 }
13873
13874 fn is_completion_trigger(
13875 &self,
13876 buffer: &Model<Buffer>,
13877 position: language::Anchor,
13878 text: &str,
13879 trigger_in_words: bool,
13880 cx: &mut ViewContext<Editor>,
13881 ) -> bool {
13882 if !EditorSettings::get_global(cx).show_completions_on_input {
13883 return false;
13884 }
13885
13886 let mut chars = text.chars();
13887 let char = if let Some(char) = chars.next() {
13888 char
13889 } else {
13890 return false;
13891 };
13892 if chars.next().is_some() {
13893 return false;
13894 }
13895
13896 let buffer = buffer.read(cx);
13897 let classifier = buffer
13898 .snapshot()
13899 .char_classifier_at(position)
13900 .for_completion(true);
13901 if trigger_in_words && classifier.is_word(char) {
13902 return true;
13903 }
13904
13905 buffer.completion_triggers().contains(text)
13906 }
13907}
13908
13909impl SemanticsProvider for Model<Project> {
13910 fn hover(
13911 &self,
13912 buffer: &Model<Buffer>,
13913 position: text::Anchor,
13914 cx: &mut AppContext,
13915 ) -> Option<Task<Vec<project::Hover>>> {
13916 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13917 }
13918
13919 fn document_highlights(
13920 &self,
13921 buffer: &Model<Buffer>,
13922 position: text::Anchor,
13923 cx: &mut AppContext,
13924 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13925 Some(self.update(cx, |project, cx| {
13926 project.document_highlights(buffer, position, cx)
13927 }))
13928 }
13929
13930 fn definitions(
13931 &self,
13932 buffer: &Model<Buffer>,
13933 position: text::Anchor,
13934 kind: GotoDefinitionKind,
13935 cx: &mut AppContext,
13936 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13937 Some(self.update(cx, |project, cx| match kind {
13938 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13939 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13940 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13941 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13942 }))
13943 }
13944
13945 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13946 // TODO: make this work for remote projects
13947 self.read(cx)
13948 .language_servers_for_buffer(buffer.read(cx), cx)
13949 .any(
13950 |(_, server)| match server.capabilities().inlay_hint_provider {
13951 Some(lsp::OneOf::Left(enabled)) => enabled,
13952 Some(lsp::OneOf::Right(_)) => true,
13953 None => false,
13954 },
13955 )
13956 }
13957
13958 fn inlay_hints(
13959 &self,
13960 buffer_handle: Model<Buffer>,
13961 range: Range<text::Anchor>,
13962 cx: &mut AppContext,
13963 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13964 Some(self.update(cx, |project, cx| {
13965 project.inlay_hints(buffer_handle, range, cx)
13966 }))
13967 }
13968
13969 fn resolve_inlay_hint(
13970 &self,
13971 hint: InlayHint,
13972 buffer_handle: Model<Buffer>,
13973 server_id: LanguageServerId,
13974 cx: &mut AppContext,
13975 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13976 Some(self.update(cx, |project, cx| {
13977 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13978 }))
13979 }
13980
13981 fn range_for_rename(
13982 &self,
13983 buffer: &Model<Buffer>,
13984 position: text::Anchor,
13985 cx: &mut AppContext,
13986 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13987 Some(self.update(cx, |project, cx| {
13988 project.prepare_rename(buffer.clone(), position, cx)
13989 }))
13990 }
13991
13992 fn perform_rename(
13993 &self,
13994 buffer: &Model<Buffer>,
13995 position: text::Anchor,
13996 new_name: String,
13997 cx: &mut AppContext,
13998 ) -> Option<Task<Result<ProjectTransaction>>> {
13999 Some(self.update(cx, |project, cx| {
14000 project.perform_rename(buffer.clone(), position, new_name, cx)
14001 }))
14002 }
14003}
14004
14005fn inlay_hint_settings(
14006 location: Anchor,
14007 snapshot: &MultiBufferSnapshot,
14008 cx: &mut ViewContext<'_, Editor>,
14009) -> InlayHintSettings {
14010 let file = snapshot.file_at(location);
14011 let language = snapshot.language_at(location).map(|l| l.name());
14012 language_settings(language, file, cx).inlay_hints
14013}
14014
14015fn consume_contiguous_rows(
14016 contiguous_row_selections: &mut Vec<Selection<Point>>,
14017 selection: &Selection<Point>,
14018 display_map: &DisplaySnapshot,
14019 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14020) -> (MultiBufferRow, MultiBufferRow) {
14021 contiguous_row_selections.push(selection.clone());
14022 let start_row = MultiBufferRow(selection.start.row);
14023 let mut end_row = ending_row(selection, display_map);
14024
14025 while let Some(next_selection) = selections.peek() {
14026 if next_selection.start.row <= end_row.0 {
14027 end_row = ending_row(next_selection, display_map);
14028 contiguous_row_selections.push(selections.next().unwrap().clone());
14029 } else {
14030 break;
14031 }
14032 }
14033 (start_row, end_row)
14034}
14035
14036fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14037 if next_selection.end.column > 0 || next_selection.is_empty() {
14038 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14039 } else {
14040 MultiBufferRow(next_selection.end.row)
14041 }
14042}
14043
14044impl EditorSnapshot {
14045 pub fn remote_selections_in_range<'a>(
14046 &'a self,
14047 range: &'a Range<Anchor>,
14048 collaboration_hub: &dyn CollaborationHub,
14049 cx: &'a AppContext,
14050 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14051 let participant_names = collaboration_hub.user_names(cx);
14052 let participant_indices = collaboration_hub.user_participant_indices(cx);
14053 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14054 let collaborators_by_replica_id = collaborators_by_peer_id
14055 .iter()
14056 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14057 .collect::<HashMap<_, _>>();
14058 self.buffer_snapshot
14059 .selections_in_range(range, false)
14060 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14061 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14062 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14063 let user_name = participant_names.get(&collaborator.user_id).cloned();
14064 Some(RemoteSelection {
14065 replica_id,
14066 selection,
14067 cursor_shape,
14068 line_mode,
14069 participant_index,
14070 peer_id: collaborator.peer_id,
14071 user_name,
14072 })
14073 })
14074 }
14075
14076 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14077 self.display_snapshot.buffer_snapshot.language_at(position)
14078 }
14079
14080 pub fn is_focused(&self) -> bool {
14081 self.is_focused
14082 }
14083
14084 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14085 self.placeholder_text.as_ref()
14086 }
14087
14088 pub fn scroll_position(&self) -> gpui::Point<f32> {
14089 self.scroll_anchor.scroll_position(&self.display_snapshot)
14090 }
14091
14092 fn gutter_dimensions(
14093 &self,
14094 font_id: FontId,
14095 font_size: Pixels,
14096 em_width: Pixels,
14097 em_advance: Pixels,
14098 max_line_number_width: Pixels,
14099 cx: &AppContext,
14100 ) -> GutterDimensions {
14101 if !self.show_gutter {
14102 return GutterDimensions::default();
14103 }
14104 let descent = cx.text_system().descent(font_id, font_size);
14105
14106 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14107 matches!(
14108 ProjectSettings::get_global(cx).git.git_gutter,
14109 Some(GitGutterSetting::TrackedFiles)
14110 )
14111 });
14112 let gutter_settings = EditorSettings::get_global(cx).gutter;
14113 let show_line_numbers = self
14114 .show_line_numbers
14115 .unwrap_or(gutter_settings.line_numbers);
14116 let line_gutter_width = if show_line_numbers {
14117 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14118 let min_width_for_number_on_gutter = em_advance * 4.0;
14119 max_line_number_width.max(min_width_for_number_on_gutter)
14120 } else {
14121 0.0.into()
14122 };
14123
14124 let show_code_actions = self
14125 .show_code_actions
14126 .unwrap_or(gutter_settings.code_actions);
14127
14128 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14129
14130 let git_blame_entries_width =
14131 self.git_blame_gutter_max_author_length
14132 .map(|max_author_length| {
14133 // Length of the author name, but also space for the commit hash,
14134 // the spacing and the timestamp.
14135 let max_char_count = max_author_length
14136 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14137 + 7 // length of commit sha
14138 + 14 // length of max relative timestamp ("60 minutes ago")
14139 + 4; // gaps and margins
14140
14141 em_advance * max_char_count
14142 });
14143
14144 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14145 left_padding += if show_code_actions || show_runnables {
14146 em_width * 3.0
14147 } else if show_git_gutter && show_line_numbers {
14148 em_width * 2.0
14149 } else if show_git_gutter || show_line_numbers {
14150 em_width
14151 } else {
14152 px(0.)
14153 };
14154
14155 let right_padding = if gutter_settings.folds && show_line_numbers {
14156 em_width * 4.0
14157 } else if gutter_settings.folds {
14158 em_width * 3.0
14159 } else if show_line_numbers {
14160 em_width
14161 } else {
14162 px(0.)
14163 };
14164
14165 GutterDimensions {
14166 left_padding,
14167 right_padding,
14168 width: line_gutter_width + left_padding + right_padding,
14169 margin: -descent,
14170 git_blame_entries_width,
14171 }
14172 }
14173
14174 pub fn render_crease_toggle(
14175 &self,
14176 buffer_row: MultiBufferRow,
14177 row_contains_cursor: bool,
14178 editor: View<Editor>,
14179 cx: &mut WindowContext,
14180 ) -> Option<AnyElement> {
14181 let folded = self.is_line_folded(buffer_row);
14182 let mut is_foldable = false;
14183
14184 if let Some(crease) = self
14185 .crease_snapshot
14186 .query_row(buffer_row, &self.buffer_snapshot)
14187 {
14188 is_foldable = true;
14189 match crease {
14190 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14191 if let Some(render_toggle) = render_toggle {
14192 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14193 if folded {
14194 editor.update(cx, |editor, cx| {
14195 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14196 });
14197 } else {
14198 editor.update(cx, |editor, cx| {
14199 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14200 });
14201 }
14202 });
14203 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14204 }
14205 }
14206 }
14207 }
14208
14209 is_foldable |= self.starts_indent(buffer_row);
14210
14211 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14212 Some(
14213 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14214 .selected(folded)
14215 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14216 if folded {
14217 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14218 } else {
14219 this.fold_at(&FoldAt { buffer_row }, cx);
14220 }
14221 }))
14222 .into_any_element(),
14223 )
14224 } else {
14225 None
14226 }
14227 }
14228
14229 pub fn render_crease_trailer(
14230 &self,
14231 buffer_row: MultiBufferRow,
14232 cx: &mut WindowContext,
14233 ) -> Option<AnyElement> {
14234 let folded = self.is_line_folded(buffer_row);
14235 if let Crease::Inline { render_trailer, .. } = self
14236 .crease_snapshot
14237 .query_row(buffer_row, &self.buffer_snapshot)?
14238 {
14239 let render_trailer = render_trailer.as_ref()?;
14240 Some(render_trailer(buffer_row, folded, cx))
14241 } else {
14242 None
14243 }
14244 }
14245}
14246
14247impl Deref for EditorSnapshot {
14248 type Target = DisplaySnapshot;
14249
14250 fn deref(&self) -> &Self::Target {
14251 &self.display_snapshot
14252 }
14253}
14254
14255#[derive(Clone, Debug, PartialEq, Eq)]
14256pub enum EditorEvent {
14257 InputIgnored {
14258 text: Arc<str>,
14259 },
14260 InputHandled {
14261 utf16_range_to_replace: Option<Range<isize>>,
14262 text: Arc<str>,
14263 },
14264 ExcerptsAdded {
14265 buffer: Model<Buffer>,
14266 predecessor: ExcerptId,
14267 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14268 },
14269 ExcerptsRemoved {
14270 ids: Vec<ExcerptId>,
14271 },
14272 ExcerptsEdited {
14273 ids: Vec<ExcerptId>,
14274 },
14275 ExcerptsExpanded {
14276 ids: Vec<ExcerptId>,
14277 },
14278 BufferEdited,
14279 Edited {
14280 transaction_id: clock::Lamport,
14281 },
14282 Reparsed(BufferId),
14283 Focused,
14284 FocusedIn,
14285 Blurred,
14286 DirtyChanged,
14287 Saved,
14288 TitleChanged,
14289 DiffBaseChanged,
14290 SelectionsChanged {
14291 local: bool,
14292 },
14293 ScrollPositionChanged {
14294 local: bool,
14295 autoscroll: bool,
14296 },
14297 Closed,
14298 TransactionUndone {
14299 transaction_id: clock::Lamport,
14300 },
14301 TransactionBegun {
14302 transaction_id: clock::Lamport,
14303 },
14304 Reloaded,
14305 CursorShapeChanged,
14306}
14307
14308impl EventEmitter<EditorEvent> for Editor {}
14309
14310impl FocusableView for Editor {
14311 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14312 self.focus_handle.clone()
14313 }
14314}
14315
14316impl Render for Editor {
14317 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14318 let settings = ThemeSettings::get_global(cx);
14319
14320 let mut text_style = match self.mode {
14321 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14322 color: cx.theme().colors().editor_foreground,
14323 font_family: settings.ui_font.family.clone(),
14324 font_features: settings.ui_font.features.clone(),
14325 font_fallbacks: settings.ui_font.fallbacks.clone(),
14326 font_size: rems(0.875).into(),
14327 font_weight: settings.ui_font.weight,
14328 line_height: relative(settings.buffer_line_height.value()),
14329 ..Default::default()
14330 },
14331 EditorMode::Full => TextStyle {
14332 color: cx.theme().colors().editor_foreground,
14333 font_family: settings.buffer_font.family.clone(),
14334 font_features: settings.buffer_font.features.clone(),
14335 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14336 font_size: settings.buffer_font_size(cx).into(),
14337 font_weight: settings.buffer_font.weight,
14338 line_height: relative(settings.buffer_line_height.value()),
14339 ..Default::default()
14340 },
14341 };
14342 if let Some(text_style_refinement) = &self.text_style_refinement {
14343 text_style.refine(text_style_refinement)
14344 }
14345
14346 let background = match self.mode {
14347 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14348 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14349 EditorMode::Full => cx.theme().colors().editor_background,
14350 };
14351
14352 EditorElement::new(
14353 cx.view(),
14354 EditorStyle {
14355 background,
14356 local_player: cx.theme().players().local(),
14357 text: text_style,
14358 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14359 syntax: cx.theme().syntax().clone(),
14360 status: cx.theme().status().clone(),
14361 inlay_hints_style: make_inlay_hints_style(cx),
14362 suggestions_style: HighlightStyle {
14363 color: Some(cx.theme().status().predictive),
14364 ..HighlightStyle::default()
14365 },
14366 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14367 },
14368 )
14369 }
14370}
14371
14372impl ViewInputHandler for Editor {
14373 fn text_for_range(
14374 &mut self,
14375 range_utf16: Range<usize>,
14376 adjusted_range: &mut Option<Range<usize>>,
14377 cx: &mut ViewContext<Self>,
14378 ) -> Option<String> {
14379 let snapshot = self.buffer.read(cx).read(cx);
14380 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14381 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14382 if (start.0..end.0) != range_utf16 {
14383 adjusted_range.replace(start.0..end.0);
14384 }
14385 Some(snapshot.text_for_range(start..end).collect())
14386 }
14387
14388 fn selected_text_range(
14389 &mut self,
14390 ignore_disabled_input: bool,
14391 cx: &mut ViewContext<Self>,
14392 ) -> Option<UTF16Selection> {
14393 // Prevent the IME menu from appearing when holding down an alphabetic key
14394 // while input is disabled.
14395 if !ignore_disabled_input && !self.input_enabled {
14396 return None;
14397 }
14398
14399 let selection = self.selections.newest::<OffsetUtf16>(cx);
14400 let range = selection.range();
14401
14402 Some(UTF16Selection {
14403 range: range.start.0..range.end.0,
14404 reversed: selection.reversed,
14405 })
14406 }
14407
14408 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14409 let snapshot = self.buffer.read(cx).read(cx);
14410 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14411 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14412 }
14413
14414 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14415 self.clear_highlights::<InputComposition>(cx);
14416 self.ime_transaction.take();
14417 }
14418
14419 fn replace_text_in_range(
14420 &mut self,
14421 range_utf16: Option<Range<usize>>,
14422 text: &str,
14423 cx: &mut ViewContext<Self>,
14424 ) {
14425 if !self.input_enabled {
14426 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14427 return;
14428 }
14429
14430 self.transact(cx, |this, cx| {
14431 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14432 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14433 Some(this.selection_replacement_ranges(range_utf16, cx))
14434 } else {
14435 this.marked_text_ranges(cx)
14436 };
14437
14438 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14439 let newest_selection_id = this.selections.newest_anchor().id;
14440 this.selections
14441 .all::<OffsetUtf16>(cx)
14442 .iter()
14443 .zip(ranges_to_replace.iter())
14444 .find_map(|(selection, range)| {
14445 if selection.id == newest_selection_id {
14446 Some(
14447 (range.start.0 as isize - selection.head().0 as isize)
14448 ..(range.end.0 as isize - selection.head().0 as isize),
14449 )
14450 } else {
14451 None
14452 }
14453 })
14454 });
14455
14456 cx.emit(EditorEvent::InputHandled {
14457 utf16_range_to_replace: range_to_replace,
14458 text: text.into(),
14459 });
14460
14461 if let Some(new_selected_ranges) = new_selected_ranges {
14462 this.change_selections(None, cx, |selections| {
14463 selections.select_ranges(new_selected_ranges)
14464 });
14465 this.backspace(&Default::default(), cx);
14466 }
14467
14468 this.handle_input(text, cx);
14469 });
14470
14471 if let Some(transaction) = self.ime_transaction {
14472 self.buffer.update(cx, |buffer, cx| {
14473 buffer.group_until_transaction(transaction, cx);
14474 });
14475 }
14476
14477 self.unmark_text(cx);
14478 }
14479
14480 fn replace_and_mark_text_in_range(
14481 &mut self,
14482 range_utf16: Option<Range<usize>>,
14483 text: &str,
14484 new_selected_range_utf16: Option<Range<usize>>,
14485 cx: &mut ViewContext<Self>,
14486 ) {
14487 if !self.input_enabled {
14488 return;
14489 }
14490
14491 let transaction = self.transact(cx, |this, cx| {
14492 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14493 let snapshot = this.buffer.read(cx).read(cx);
14494 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14495 for marked_range in &mut marked_ranges {
14496 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14497 marked_range.start.0 += relative_range_utf16.start;
14498 marked_range.start =
14499 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14500 marked_range.end =
14501 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14502 }
14503 }
14504 Some(marked_ranges)
14505 } else if let Some(range_utf16) = range_utf16 {
14506 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14507 Some(this.selection_replacement_ranges(range_utf16, cx))
14508 } else {
14509 None
14510 };
14511
14512 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14513 let newest_selection_id = this.selections.newest_anchor().id;
14514 this.selections
14515 .all::<OffsetUtf16>(cx)
14516 .iter()
14517 .zip(ranges_to_replace.iter())
14518 .find_map(|(selection, range)| {
14519 if selection.id == newest_selection_id {
14520 Some(
14521 (range.start.0 as isize - selection.head().0 as isize)
14522 ..(range.end.0 as isize - selection.head().0 as isize),
14523 )
14524 } else {
14525 None
14526 }
14527 })
14528 });
14529
14530 cx.emit(EditorEvent::InputHandled {
14531 utf16_range_to_replace: range_to_replace,
14532 text: text.into(),
14533 });
14534
14535 if let Some(ranges) = ranges_to_replace {
14536 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14537 }
14538
14539 let marked_ranges = {
14540 let snapshot = this.buffer.read(cx).read(cx);
14541 this.selections
14542 .disjoint_anchors()
14543 .iter()
14544 .map(|selection| {
14545 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14546 })
14547 .collect::<Vec<_>>()
14548 };
14549
14550 if text.is_empty() {
14551 this.unmark_text(cx);
14552 } else {
14553 this.highlight_text::<InputComposition>(
14554 marked_ranges.clone(),
14555 HighlightStyle {
14556 underline: Some(UnderlineStyle {
14557 thickness: px(1.),
14558 color: None,
14559 wavy: false,
14560 }),
14561 ..Default::default()
14562 },
14563 cx,
14564 );
14565 }
14566
14567 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14568 let use_autoclose = this.use_autoclose;
14569 let use_auto_surround = this.use_auto_surround;
14570 this.set_use_autoclose(false);
14571 this.set_use_auto_surround(false);
14572 this.handle_input(text, cx);
14573 this.set_use_autoclose(use_autoclose);
14574 this.set_use_auto_surround(use_auto_surround);
14575
14576 if let Some(new_selected_range) = new_selected_range_utf16 {
14577 let snapshot = this.buffer.read(cx).read(cx);
14578 let new_selected_ranges = marked_ranges
14579 .into_iter()
14580 .map(|marked_range| {
14581 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14582 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14583 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14584 snapshot.clip_offset_utf16(new_start, Bias::Left)
14585 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14586 })
14587 .collect::<Vec<_>>();
14588
14589 drop(snapshot);
14590 this.change_selections(None, cx, |selections| {
14591 selections.select_ranges(new_selected_ranges)
14592 });
14593 }
14594 });
14595
14596 self.ime_transaction = self.ime_transaction.or(transaction);
14597 if let Some(transaction) = self.ime_transaction {
14598 self.buffer.update(cx, |buffer, cx| {
14599 buffer.group_until_transaction(transaction, cx);
14600 });
14601 }
14602
14603 if self.text_highlights::<InputComposition>(cx).is_none() {
14604 self.ime_transaction.take();
14605 }
14606 }
14607
14608 fn bounds_for_range(
14609 &mut self,
14610 range_utf16: Range<usize>,
14611 element_bounds: gpui::Bounds<Pixels>,
14612 cx: &mut ViewContext<Self>,
14613 ) -> Option<gpui::Bounds<Pixels>> {
14614 let text_layout_details = self.text_layout_details(cx);
14615 let style = &text_layout_details.editor_style;
14616 let font_id = cx.text_system().resolve_font(&style.text.font());
14617 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14618 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14619
14620 let em_width = cx
14621 .text_system()
14622 .typographic_bounds(font_id, font_size, 'm')
14623 .unwrap()
14624 .size
14625 .width;
14626
14627 let snapshot = self.snapshot(cx);
14628 let scroll_position = snapshot.scroll_position();
14629 let scroll_left = scroll_position.x * em_width;
14630
14631 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14632 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14633 + self.gutter_dimensions.width
14634 + self.gutter_dimensions.margin;
14635 let y = line_height * (start.row().as_f32() - scroll_position.y);
14636
14637 Some(Bounds {
14638 origin: element_bounds.origin + point(x, y),
14639 size: size(em_width, line_height),
14640 })
14641 }
14642}
14643
14644trait SelectionExt {
14645 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14646 fn spanned_rows(
14647 &self,
14648 include_end_if_at_line_start: bool,
14649 map: &DisplaySnapshot,
14650 ) -> Range<MultiBufferRow>;
14651}
14652
14653impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14654 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14655 let start = self
14656 .start
14657 .to_point(&map.buffer_snapshot)
14658 .to_display_point(map);
14659 let end = self
14660 .end
14661 .to_point(&map.buffer_snapshot)
14662 .to_display_point(map);
14663 if self.reversed {
14664 end..start
14665 } else {
14666 start..end
14667 }
14668 }
14669
14670 fn spanned_rows(
14671 &self,
14672 include_end_if_at_line_start: bool,
14673 map: &DisplaySnapshot,
14674 ) -> Range<MultiBufferRow> {
14675 let start = self.start.to_point(&map.buffer_snapshot);
14676 let mut end = self.end.to_point(&map.buffer_snapshot);
14677 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14678 end.row -= 1;
14679 }
14680
14681 let buffer_start = map.prev_line_boundary(start).0;
14682 let buffer_end = map.next_line_boundary(end).0;
14683 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14684 }
14685}
14686
14687impl<T: InvalidationRegion> InvalidationStack<T> {
14688 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14689 where
14690 S: Clone + ToOffset,
14691 {
14692 while let Some(region) = self.last() {
14693 let all_selections_inside_invalidation_ranges =
14694 if selections.len() == region.ranges().len() {
14695 selections
14696 .iter()
14697 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14698 .all(|(selection, invalidation_range)| {
14699 let head = selection.head().to_offset(buffer);
14700 invalidation_range.start <= head && invalidation_range.end >= head
14701 })
14702 } else {
14703 false
14704 };
14705
14706 if all_selections_inside_invalidation_ranges {
14707 break;
14708 } else {
14709 self.pop();
14710 }
14711 }
14712 }
14713}
14714
14715impl<T> Default for InvalidationStack<T> {
14716 fn default() -> Self {
14717 Self(Default::default())
14718 }
14719}
14720
14721impl<T> Deref for InvalidationStack<T> {
14722 type Target = Vec<T>;
14723
14724 fn deref(&self) -> &Self::Target {
14725 &self.0
14726 }
14727}
14728
14729impl<T> DerefMut for InvalidationStack<T> {
14730 fn deref_mut(&mut self) -> &mut Self::Target {
14731 &mut self.0
14732 }
14733}
14734
14735impl InvalidationRegion for SnippetState {
14736 fn ranges(&self) -> &[Range<Anchor>] {
14737 &self.ranges[self.active_index]
14738 }
14739}
14740
14741pub fn diagnostic_block_renderer(
14742 diagnostic: Diagnostic,
14743 max_message_rows: Option<u8>,
14744 allow_closing: bool,
14745 _is_valid: bool,
14746) -> RenderBlock {
14747 let (text_without_backticks, code_ranges) =
14748 highlight_diagnostic_message(&diagnostic, max_message_rows);
14749
14750 Arc::new(move |cx: &mut BlockContext| {
14751 let group_id: SharedString = cx.block_id.to_string().into();
14752
14753 let mut text_style = cx.text_style().clone();
14754 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14755 let theme_settings = ThemeSettings::get_global(cx);
14756 text_style.font_family = theme_settings.buffer_font.family.clone();
14757 text_style.font_style = theme_settings.buffer_font.style;
14758 text_style.font_features = theme_settings.buffer_font.features.clone();
14759 text_style.font_weight = theme_settings.buffer_font.weight;
14760
14761 let multi_line_diagnostic = diagnostic.message.contains('\n');
14762
14763 let buttons = |diagnostic: &Diagnostic| {
14764 if multi_line_diagnostic {
14765 v_flex()
14766 } else {
14767 h_flex()
14768 }
14769 .when(allow_closing, |div| {
14770 div.children(diagnostic.is_primary.then(|| {
14771 IconButton::new("close-block", IconName::XCircle)
14772 .icon_color(Color::Muted)
14773 .size(ButtonSize::Compact)
14774 .style(ButtonStyle::Transparent)
14775 .visible_on_hover(group_id.clone())
14776 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14777 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14778 }))
14779 })
14780 .child(
14781 IconButton::new("copy-block", IconName::Copy)
14782 .icon_color(Color::Muted)
14783 .size(ButtonSize::Compact)
14784 .style(ButtonStyle::Transparent)
14785 .visible_on_hover(group_id.clone())
14786 .on_click({
14787 let message = diagnostic.message.clone();
14788 move |_click, cx| {
14789 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14790 }
14791 })
14792 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14793 )
14794 };
14795
14796 let icon_size = buttons(&diagnostic)
14797 .into_any_element()
14798 .layout_as_root(AvailableSpace::min_size(), cx);
14799
14800 h_flex()
14801 .id(cx.block_id)
14802 .group(group_id.clone())
14803 .relative()
14804 .size_full()
14805 .block_mouse_down()
14806 .pl(cx.gutter_dimensions.width)
14807 .w(cx.max_width - cx.gutter_dimensions.full_width())
14808 .child(
14809 div()
14810 .flex()
14811 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14812 .flex_shrink(),
14813 )
14814 .child(buttons(&diagnostic))
14815 .child(div().flex().flex_shrink_0().child(
14816 StyledText::new(text_without_backticks.clone()).with_highlights(
14817 &text_style,
14818 code_ranges.iter().map(|range| {
14819 (
14820 range.clone(),
14821 HighlightStyle {
14822 font_weight: Some(FontWeight::BOLD),
14823 ..Default::default()
14824 },
14825 )
14826 }),
14827 ),
14828 ))
14829 .into_any_element()
14830 })
14831}
14832
14833pub fn highlight_diagnostic_message(
14834 diagnostic: &Diagnostic,
14835 mut max_message_rows: Option<u8>,
14836) -> (SharedString, Vec<Range<usize>>) {
14837 let mut text_without_backticks = String::new();
14838 let mut code_ranges = Vec::new();
14839
14840 if let Some(source) = &diagnostic.source {
14841 text_without_backticks.push_str(source);
14842 code_ranges.push(0..source.len());
14843 text_without_backticks.push_str(": ");
14844 }
14845
14846 let mut prev_offset = 0;
14847 let mut in_code_block = false;
14848 let has_row_limit = max_message_rows.is_some();
14849 let mut newline_indices = diagnostic
14850 .message
14851 .match_indices('\n')
14852 .filter(|_| has_row_limit)
14853 .map(|(ix, _)| ix)
14854 .fuse()
14855 .peekable();
14856
14857 for (quote_ix, _) in diagnostic
14858 .message
14859 .match_indices('`')
14860 .chain([(diagnostic.message.len(), "")])
14861 {
14862 let mut first_newline_ix = None;
14863 let mut last_newline_ix = None;
14864 while let Some(newline_ix) = newline_indices.peek() {
14865 if *newline_ix < quote_ix {
14866 if first_newline_ix.is_none() {
14867 first_newline_ix = Some(*newline_ix);
14868 }
14869 last_newline_ix = Some(*newline_ix);
14870
14871 if let Some(rows_left) = &mut max_message_rows {
14872 if *rows_left == 0 {
14873 break;
14874 } else {
14875 *rows_left -= 1;
14876 }
14877 }
14878 let _ = newline_indices.next();
14879 } else {
14880 break;
14881 }
14882 }
14883 let prev_len = text_without_backticks.len();
14884 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14885 text_without_backticks.push_str(new_text);
14886 if in_code_block {
14887 code_ranges.push(prev_len..text_without_backticks.len());
14888 }
14889 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14890 in_code_block = !in_code_block;
14891 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14892 text_without_backticks.push_str("...");
14893 break;
14894 }
14895 }
14896
14897 (text_without_backticks.into(), code_ranges)
14898}
14899
14900fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14901 match severity {
14902 DiagnosticSeverity::ERROR => colors.error,
14903 DiagnosticSeverity::WARNING => colors.warning,
14904 DiagnosticSeverity::INFORMATION => colors.info,
14905 DiagnosticSeverity::HINT => colors.info,
14906 _ => colors.ignored,
14907 }
14908}
14909
14910pub fn styled_runs_for_code_label<'a>(
14911 label: &'a CodeLabel,
14912 syntax_theme: &'a theme::SyntaxTheme,
14913) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14914 let fade_out = HighlightStyle {
14915 fade_out: Some(0.35),
14916 ..Default::default()
14917 };
14918
14919 let mut prev_end = label.filter_range.end;
14920 label
14921 .runs
14922 .iter()
14923 .enumerate()
14924 .flat_map(move |(ix, (range, highlight_id))| {
14925 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14926 style
14927 } else {
14928 return Default::default();
14929 };
14930 let mut muted_style = style;
14931 muted_style.highlight(fade_out);
14932
14933 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14934 if range.start >= label.filter_range.end {
14935 if range.start > prev_end {
14936 runs.push((prev_end..range.start, fade_out));
14937 }
14938 runs.push((range.clone(), muted_style));
14939 } else if range.end <= label.filter_range.end {
14940 runs.push((range.clone(), style));
14941 } else {
14942 runs.push((range.start..label.filter_range.end, style));
14943 runs.push((label.filter_range.end..range.end, muted_style));
14944 }
14945 prev_end = cmp::max(prev_end, range.end);
14946
14947 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14948 runs.push((prev_end..label.text.len(), fade_out));
14949 }
14950
14951 runs
14952 })
14953}
14954
14955pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14956 let mut prev_index = 0;
14957 let mut prev_codepoint: Option<char> = None;
14958 text.char_indices()
14959 .chain([(text.len(), '\0')])
14960 .filter_map(move |(index, codepoint)| {
14961 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14962 let is_boundary = index == text.len()
14963 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14964 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14965 if is_boundary {
14966 let chunk = &text[prev_index..index];
14967 prev_index = index;
14968 Some(chunk)
14969 } else {
14970 None
14971 }
14972 })
14973}
14974
14975pub trait RangeToAnchorExt: Sized {
14976 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14977
14978 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14979 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14980 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14981 }
14982}
14983
14984impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14985 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14986 let start_offset = self.start.to_offset(snapshot);
14987 let end_offset = self.end.to_offset(snapshot);
14988 if start_offset == end_offset {
14989 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14990 } else {
14991 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14992 }
14993 }
14994}
14995
14996pub trait RowExt {
14997 fn as_f32(&self) -> f32;
14998
14999 fn next_row(&self) -> Self;
15000
15001 fn previous_row(&self) -> Self;
15002
15003 fn minus(&self, other: Self) -> u32;
15004}
15005
15006impl RowExt for DisplayRow {
15007 fn as_f32(&self) -> f32 {
15008 self.0 as f32
15009 }
15010
15011 fn next_row(&self) -> Self {
15012 Self(self.0 + 1)
15013 }
15014
15015 fn previous_row(&self) -> Self {
15016 Self(self.0.saturating_sub(1))
15017 }
15018
15019 fn minus(&self, other: Self) -> u32 {
15020 self.0 - other.0
15021 }
15022}
15023
15024impl RowExt for MultiBufferRow {
15025 fn as_f32(&self) -> f32 {
15026 self.0 as f32
15027 }
15028
15029 fn next_row(&self) -> Self {
15030 Self(self.0 + 1)
15031 }
15032
15033 fn previous_row(&self) -> Self {
15034 Self(self.0.saturating_sub(1))
15035 }
15036
15037 fn minus(&self, other: Self) -> u32 {
15038 self.0 - other.0
15039 }
15040}
15041
15042trait RowRangeExt {
15043 type Row;
15044
15045 fn len(&self) -> usize;
15046
15047 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15048}
15049
15050impl RowRangeExt for Range<MultiBufferRow> {
15051 type Row = MultiBufferRow;
15052
15053 fn len(&self) -> usize {
15054 (self.end.0 - self.start.0) as usize
15055 }
15056
15057 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15058 (self.start.0..self.end.0).map(MultiBufferRow)
15059 }
15060}
15061
15062impl RowRangeExt for Range<DisplayRow> {
15063 type Row = DisplayRow;
15064
15065 fn len(&self) -> usize {
15066 (self.end.0 - self.start.0) as usize
15067 }
15068
15069 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15070 (self.start.0..self.end.0).map(DisplayRow)
15071 }
15072}
15073
15074fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15075 if hunk.diff_base_byte_range.is_empty() {
15076 DiffHunkStatus::Added
15077 } else if hunk.row_range.is_empty() {
15078 DiffHunkStatus::Removed
15079 } else {
15080 DiffHunkStatus::Modified
15081 }
15082}
15083
15084/// If select range has more than one line, we
15085/// just point the cursor to range.start.
15086fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15087 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15088 range
15089 } else {
15090 range.start..range.start
15091 }
15092}
15093
15094pub struct KillRing(ClipboardItem);
15095impl Global for KillRing {}
15096
15097const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);