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 delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6301 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6302 let selections = self.selections.all::<Point>(cx);
6303
6304 let mut new_cursors = Vec::new();
6305 let mut edit_ranges = Vec::new();
6306 let mut selections = selections.iter().peekable();
6307 while let Some(selection) = selections.next() {
6308 let mut rows = selection.spanned_rows(false, &display_map);
6309 let goal_display_column = selection.head().to_display_point(&display_map).column();
6310
6311 // Accumulate contiguous regions of rows that we want to delete.
6312 while let Some(next_selection) = selections.peek() {
6313 let next_rows = next_selection.spanned_rows(false, &display_map);
6314 if next_rows.start <= rows.end {
6315 rows.end = next_rows.end;
6316 selections.next().unwrap();
6317 } else {
6318 break;
6319 }
6320 }
6321
6322 let buffer = &display_map.buffer_snapshot;
6323 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6324 let edit_end;
6325 let cursor_buffer_row;
6326 if buffer.max_point().row >= rows.end.0 {
6327 // If there's a line after the range, delete the \n from the end of the row range
6328 // and position the cursor on the next line.
6329 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6330 cursor_buffer_row = rows.end;
6331 } else {
6332 // If there isn't a line after the range, delete the \n from the line before the
6333 // start of the row range and position the cursor there.
6334 edit_start = edit_start.saturating_sub(1);
6335 edit_end = buffer.len();
6336 cursor_buffer_row = rows.start.previous_row();
6337 }
6338
6339 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6340 *cursor.column_mut() =
6341 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6342
6343 new_cursors.push((
6344 selection.id,
6345 buffer.anchor_after(cursor.to_point(&display_map)),
6346 ));
6347 edit_ranges.push(edit_start..edit_end);
6348 }
6349
6350 self.transact(cx, |this, cx| {
6351 let buffer = this.buffer.update(cx, |buffer, cx| {
6352 let empty_str: Arc<str> = Arc::default();
6353 buffer.edit(
6354 edit_ranges
6355 .into_iter()
6356 .map(|range| (range, empty_str.clone())),
6357 None,
6358 cx,
6359 );
6360 buffer.snapshot(cx)
6361 });
6362 let new_selections = new_cursors
6363 .into_iter()
6364 .map(|(id, cursor)| {
6365 let cursor = cursor.to_point(&buffer);
6366 Selection {
6367 id,
6368 start: cursor,
6369 end: cursor,
6370 reversed: false,
6371 goal: SelectionGoal::None,
6372 }
6373 })
6374 .collect();
6375
6376 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6377 s.select(new_selections);
6378 });
6379 });
6380 }
6381
6382 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6383 if self.read_only(cx) {
6384 return;
6385 }
6386 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6387 for selection in self.selections.all::<Point>(cx) {
6388 let start = MultiBufferRow(selection.start.row);
6389 // Treat single line selections as if they include the next line. Otherwise this action
6390 // would do nothing for single line selections individual cursors.
6391 let end = if selection.start.row == selection.end.row {
6392 MultiBufferRow(selection.start.row + 1)
6393 } else {
6394 MultiBufferRow(selection.end.row)
6395 };
6396
6397 if let Some(last_row_range) = row_ranges.last_mut() {
6398 if start <= last_row_range.end {
6399 last_row_range.end = end;
6400 continue;
6401 }
6402 }
6403 row_ranges.push(start..end);
6404 }
6405
6406 let snapshot = self.buffer.read(cx).snapshot(cx);
6407 let mut cursor_positions = Vec::new();
6408 for row_range in &row_ranges {
6409 let anchor = snapshot.anchor_before(Point::new(
6410 row_range.end.previous_row().0,
6411 snapshot.line_len(row_range.end.previous_row()),
6412 ));
6413 cursor_positions.push(anchor..anchor);
6414 }
6415
6416 self.transact(cx, |this, cx| {
6417 for row_range in row_ranges.into_iter().rev() {
6418 for row in row_range.iter_rows().rev() {
6419 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6420 let next_line_row = row.next_row();
6421 let indent = snapshot.indent_size_for_line(next_line_row);
6422 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6423
6424 let replace = if snapshot.line_len(next_line_row) > indent.len {
6425 " "
6426 } else {
6427 ""
6428 };
6429
6430 this.buffer.update(cx, |buffer, cx| {
6431 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6432 });
6433 }
6434 }
6435
6436 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6437 s.select_anchor_ranges(cursor_positions)
6438 });
6439 });
6440 }
6441
6442 pub fn sort_lines_case_sensitive(
6443 &mut self,
6444 _: &SortLinesCaseSensitive,
6445 cx: &mut ViewContext<Self>,
6446 ) {
6447 self.manipulate_lines(cx, |lines| lines.sort())
6448 }
6449
6450 pub fn sort_lines_case_insensitive(
6451 &mut self,
6452 _: &SortLinesCaseInsensitive,
6453 cx: &mut ViewContext<Self>,
6454 ) {
6455 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6456 }
6457
6458 pub fn unique_lines_case_insensitive(
6459 &mut self,
6460 _: &UniqueLinesCaseInsensitive,
6461 cx: &mut ViewContext<Self>,
6462 ) {
6463 self.manipulate_lines(cx, |lines| {
6464 let mut seen = HashSet::default();
6465 lines.retain(|line| seen.insert(line.to_lowercase()));
6466 })
6467 }
6468
6469 pub fn unique_lines_case_sensitive(
6470 &mut self,
6471 _: &UniqueLinesCaseSensitive,
6472 cx: &mut ViewContext<Self>,
6473 ) {
6474 self.manipulate_lines(cx, |lines| {
6475 let mut seen = HashSet::default();
6476 lines.retain(|line| seen.insert(*line));
6477 })
6478 }
6479
6480 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6481 let mut revert_changes = HashMap::default();
6482 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6483 for hunk in hunks_for_rows(
6484 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6485 &multi_buffer_snapshot,
6486 ) {
6487 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6488 }
6489 if !revert_changes.is_empty() {
6490 self.transact(cx, |editor, cx| {
6491 editor.revert(revert_changes, cx);
6492 });
6493 }
6494 }
6495
6496 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6497 let Some(project) = self.project.clone() else {
6498 return;
6499 };
6500 self.reload(project, cx).detach_and_notify_err(cx);
6501 }
6502
6503 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6504 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6505 if !revert_changes.is_empty() {
6506 self.transact(cx, |editor, cx| {
6507 editor.revert(revert_changes, cx);
6508 });
6509 }
6510 }
6511
6512 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6513 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6514 let project_path = buffer.read(cx).project_path(cx)?;
6515 let project = self.project.as_ref()?.read(cx);
6516 let entry = project.entry_for_path(&project_path, cx)?;
6517 let parent = match &entry.canonical_path {
6518 Some(canonical_path) => canonical_path.to_path_buf(),
6519 None => project.absolute_path(&project_path, cx)?,
6520 }
6521 .parent()?
6522 .to_path_buf();
6523 Some(parent)
6524 }) {
6525 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6526 }
6527 }
6528
6529 fn gather_revert_changes(
6530 &mut self,
6531 selections: &[Selection<Anchor>],
6532 cx: &mut ViewContext<'_, Editor>,
6533 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6534 let mut revert_changes = HashMap::default();
6535 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6536 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6537 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6538 }
6539 revert_changes
6540 }
6541
6542 pub fn prepare_revert_change(
6543 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6544 multi_buffer: &Model<MultiBuffer>,
6545 hunk: &MultiBufferDiffHunk,
6546 cx: &AppContext,
6547 ) -> Option<()> {
6548 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6549 let buffer = buffer.read(cx);
6550 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6551 let buffer_snapshot = buffer.snapshot();
6552 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6553 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6554 probe
6555 .0
6556 .start
6557 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6558 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6559 }) {
6560 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6561 Some(())
6562 } else {
6563 None
6564 }
6565 }
6566
6567 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6568 self.manipulate_lines(cx, |lines| lines.reverse())
6569 }
6570
6571 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6572 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6573 }
6574
6575 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6576 where
6577 Fn: FnMut(&mut Vec<&str>),
6578 {
6579 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6580 let buffer = self.buffer.read(cx).snapshot(cx);
6581
6582 let mut edits = Vec::new();
6583
6584 let selections = self.selections.all::<Point>(cx);
6585 let mut selections = selections.iter().peekable();
6586 let mut contiguous_row_selections = Vec::new();
6587 let mut new_selections = Vec::new();
6588 let mut added_lines = 0;
6589 let mut removed_lines = 0;
6590
6591 while let Some(selection) = selections.next() {
6592 let (start_row, end_row) = consume_contiguous_rows(
6593 &mut contiguous_row_selections,
6594 selection,
6595 &display_map,
6596 &mut selections,
6597 );
6598
6599 let start_point = Point::new(start_row.0, 0);
6600 let end_point = Point::new(
6601 end_row.previous_row().0,
6602 buffer.line_len(end_row.previous_row()),
6603 );
6604 let text = buffer
6605 .text_for_range(start_point..end_point)
6606 .collect::<String>();
6607
6608 let mut lines = text.split('\n').collect_vec();
6609
6610 let lines_before = lines.len();
6611 callback(&mut lines);
6612 let lines_after = lines.len();
6613
6614 edits.push((start_point..end_point, lines.join("\n")));
6615
6616 // Selections must change based on added and removed line count
6617 let start_row =
6618 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6619 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6620 new_selections.push(Selection {
6621 id: selection.id,
6622 start: start_row,
6623 end: end_row,
6624 goal: SelectionGoal::None,
6625 reversed: selection.reversed,
6626 });
6627
6628 if lines_after > lines_before {
6629 added_lines += lines_after - lines_before;
6630 } else if lines_before > lines_after {
6631 removed_lines += lines_before - lines_after;
6632 }
6633 }
6634
6635 self.transact(cx, |this, cx| {
6636 let buffer = this.buffer.update(cx, |buffer, cx| {
6637 buffer.edit(edits, None, cx);
6638 buffer.snapshot(cx)
6639 });
6640
6641 // Recalculate offsets on newly edited buffer
6642 let new_selections = new_selections
6643 .iter()
6644 .map(|s| {
6645 let start_point = Point::new(s.start.0, 0);
6646 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6647 Selection {
6648 id: s.id,
6649 start: buffer.point_to_offset(start_point),
6650 end: buffer.point_to_offset(end_point),
6651 goal: s.goal,
6652 reversed: s.reversed,
6653 }
6654 })
6655 .collect();
6656
6657 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6658 s.select(new_selections);
6659 });
6660
6661 this.request_autoscroll(Autoscroll::fit(), cx);
6662 });
6663 }
6664
6665 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6666 self.manipulate_text(cx, |text| text.to_uppercase())
6667 }
6668
6669 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6670 self.manipulate_text(cx, |text| text.to_lowercase())
6671 }
6672
6673 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6674 self.manipulate_text(cx, |text| {
6675 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6676 // https://github.com/rutrum/convert-case/issues/16
6677 text.split('\n')
6678 .map(|line| line.to_case(Case::Title))
6679 .join("\n")
6680 })
6681 }
6682
6683 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6684 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6685 }
6686
6687 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6688 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6689 }
6690
6691 pub fn convert_to_upper_camel_case(
6692 &mut self,
6693 _: &ConvertToUpperCamelCase,
6694 cx: &mut ViewContext<Self>,
6695 ) {
6696 self.manipulate_text(cx, |text| {
6697 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6698 // https://github.com/rutrum/convert-case/issues/16
6699 text.split('\n')
6700 .map(|line| line.to_case(Case::UpperCamel))
6701 .join("\n")
6702 })
6703 }
6704
6705 pub fn convert_to_lower_camel_case(
6706 &mut self,
6707 _: &ConvertToLowerCamelCase,
6708 cx: &mut ViewContext<Self>,
6709 ) {
6710 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6711 }
6712
6713 pub fn convert_to_opposite_case(
6714 &mut self,
6715 _: &ConvertToOppositeCase,
6716 cx: &mut ViewContext<Self>,
6717 ) {
6718 self.manipulate_text(cx, |text| {
6719 text.chars()
6720 .fold(String::with_capacity(text.len()), |mut t, c| {
6721 if c.is_uppercase() {
6722 t.extend(c.to_lowercase());
6723 } else {
6724 t.extend(c.to_uppercase());
6725 }
6726 t
6727 })
6728 })
6729 }
6730
6731 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6732 where
6733 Fn: FnMut(&str) -> String,
6734 {
6735 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6736 let buffer = self.buffer.read(cx).snapshot(cx);
6737
6738 let mut new_selections = Vec::new();
6739 let mut edits = Vec::new();
6740 let mut selection_adjustment = 0i32;
6741
6742 for selection in self.selections.all::<usize>(cx) {
6743 let selection_is_empty = selection.is_empty();
6744
6745 let (start, end) = if selection_is_empty {
6746 let word_range = movement::surrounding_word(
6747 &display_map,
6748 selection.start.to_display_point(&display_map),
6749 );
6750 let start = word_range.start.to_offset(&display_map, Bias::Left);
6751 let end = word_range.end.to_offset(&display_map, Bias::Left);
6752 (start, end)
6753 } else {
6754 (selection.start, selection.end)
6755 };
6756
6757 let text = buffer.text_for_range(start..end).collect::<String>();
6758 let old_length = text.len() as i32;
6759 let text = callback(&text);
6760
6761 new_selections.push(Selection {
6762 start: (start as i32 - selection_adjustment) as usize,
6763 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6764 goal: SelectionGoal::None,
6765 ..selection
6766 });
6767
6768 selection_adjustment += old_length - text.len() as i32;
6769
6770 edits.push((start..end, text));
6771 }
6772
6773 self.transact(cx, |this, cx| {
6774 this.buffer.update(cx, |buffer, cx| {
6775 buffer.edit(edits, None, cx);
6776 });
6777
6778 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6779 s.select(new_selections);
6780 });
6781
6782 this.request_autoscroll(Autoscroll::fit(), cx);
6783 });
6784 }
6785
6786 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6787 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6788 let buffer = &display_map.buffer_snapshot;
6789 let selections = self.selections.all::<Point>(cx);
6790
6791 let mut edits = Vec::new();
6792 let mut selections_iter = selections.iter().peekable();
6793 while let Some(selection) = selections_iter.next() {
6794 // Avoid duplicating the same lines twice.
6795 let mut rows = selection.spanned_rows(false, &display_map);
6796
6797 while let Some(next_selection) = selections_iter.peek() {
6798 let next_rows = next_selection.spanned_rows(false, &display_map);
6799 if next_rows.start < rows.end {
6800 rows.end = next_rows.end;
6801 selections_iter.next().unwrap();
6802 } else {
6803 break;
6804 }
6805 }
6806
6807 // Copy the text from the selected row region and splice it either at the start
6808 // or end of the region.
6809 let start = Point::new(rows.start.0, 0);
6810 let end = Point::new(
6811 rows.end.previous_row().0,
6812 buffer.line_len(rows.end.previous_row()),
6813 );
6814 let text = buffer
6815 .text_for_range(start..end)
6816 .chain(Some("\n"))
6817 .collect::<String>();
6818 let insert_location = if upwards {
6819 Point::new(rows.end.0, 0)
6820 } else {
6821 start
6822 };
6823 edits.push((insert_location..insert_location, text));
6824 }
6825
6826 self.transact(cx, |this, cx| {
6827 this.buffer.update(cx, |buffer, cx| {
6828 buffer.edit(edits, None, cx);
6829 });
6830
6831 this.request_autoscroll(Autoscroll::fit(), cx);
6832 });
6833 }
6834
6835 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6836 self.duplicate_line(true, cx);
6837 }
6838
6839 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6840 self.duplicate_line(false, cx);
6841 }
6842
6843 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6845 let buffer = self.buffer.read(cx).snapshot(cx);
6846
6847 let mut edits = Vec::new();
6848 let mut unfold_ranges = Vec::new();
6849 let mut refold_creases = Vec::new();
6850
6851 let selections = self.selections.all::<Point>(cx);
6852 let mut selections = selections.iter().peekable();
6853 let mut contiguous_row_selections = Vec::new();
6854 let mut new_selections = Vec::new();
6855
6856 while let Some(selection) = selections.next() {
6857 // Find all the selections that span a contiguous row range
6858 let (start_row, end_row) = consume_contiguous_rows(
6859 &mut contiguous_row_selections,
6860 selection,
6861 &display_map,
6862 &mut selections,
6863 );
6864
6865 // Move the text spanned by the row range to be before the line preceding the row range
6866 if start_row.0 > 0 {
6867 let range_to_move = Point::new(
6868 start_row.previous_row().0,
6869 buffer.line_len(start_row.previous_row()),
6870 )
6871 ..Point::new(
6872 end_row.previous_row().0,
6873 buffer.line_len(end_row.previous_row()),
6874 );
6875 let insertion_point = display_map
6876 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6877 .0;
6878
6879 // Don't move lines across excerpts
6880 if buffer
6881 .excerpt_boundaries_in_range((
6882 Bound::Excluded(insertion_point),
6883 Bound::Included(range_to_move.end),
6884 ))
6885 .next()
6886 .is_none()
6887 {
6888 let text = buffer
6889 .text_for_range(range_to_move.clone())
6890 .flat_map(|s| s.chars())
6891 .skip(1)
6892 .chain(['\n'])
6893 .collect::<String>();
6894
6895 edits.push((
6896 buffer.anchor_after(range_to_move.start)
6897 ..buffer.anchor_before(range_to_move.end),
6898 String::new(),
6899 ));
6900 let insertion_anchor = buffer.anchor_after(insertion_point);
6901 edits.push((insertion_anchor..insertion_anchor, text));
6902
6903 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6904
6905 // Move selections up
6906 new_selections.extend(contiguous_row_selections.drain(..).map(
6907 |mut selection| {
6908 selection.start.row -= row_delta;
6909 selection.end.row -= row_delta;
6910 selection
6911 },
6912 ));
6913
6914 // Move folds up
6915 unfold_ranges.push(range_to_move.clone());
6916 for fold in display_map.folds_in_range(
6917 buffer.anchor_before(range_to_move.start)
6918 ..buffer.anchor_after(range_to_move.end),
6919 ) {
6920 let mut start = fold.range.start.to_point(&buffer);
6921 let mut end = fold.range.end.to_point(&buffer);
6922 start.row -= row_delta;
6923 end.row -= row_delta;
6924 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6925 }
6926 }
6927 }
6928
6929 // If we didn't move line(s), preserve the existing selections
6930 new_selections.append(&mut contiguous_row_selections);
6931 }
6932
6933 self.transact(cx, |this, cx| {
6934 this.unfold_ranges(&unfold_ranges, true, true, cx);
6935 this.buffer.update(cx, |buffer, cx| {
6936 for (range, text) in edits {
6937 buffer.edit([(range, text)], None, cx);
6938 }
6939 });
6940 this.fold_creases(refold_creases, true, cx);
6941 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6942 s.select(new_selections);
6943 })
6944 });
6945 }
6946
6947 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6948 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6949 let buffer = self.buffer.read(cx).snapshot(cx);
6950
6951 let mut edits = Vec::new();
6952 let mut unfold_ranges = Vec::new();
6953 let mut refold_creases = Vec::new();
6954
6955 let selections = self.selections.all::<Point>(cx);
6956 let mut selections = selections.iter().peekable();
6957 let mut contiguous_row_selections = Vec::new();
6958 let mut new_selections = Vec::new();
6959
6960 while let Some(selection) = selections.next() {
6961 // Find all the selections that span a contiguous row range
6962 let (start_row, end_row) = consume_contiguous_rows(
6963 &mut contiguous_row_selections,
6964 selection,
6965 &display_map,
6966 &mut selections,
6967 );
6968
6969 // Move the text spanned by the row range to be after the last line of the row range
6970 if end_row.0 <= buffer.max_point().row {
6971 let range_to_move =
6972 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6973 let insertion_point = display_map
6974 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6975 .0;
6976
6977 // Don't move lines across excerpt boundaries
6978 if buffer
6979 .excerpt_boundaries_in_range((
6980 Bound::Excluded(range_to_move.start),
6981 Bound::Included(insertion_point),
6982 ))
6983 .next()
6984 .is_none()
6985 {
6986 let mut text = String::from("\n");
6987 text.extend(buffer.text_for_range(range_to_move.clone()));
6988 text.pop(); // Drop trailing newline
6989 edits.push((
6990 buffer.anchor_after(range_to_move.start)
6991 ..buffer.anchor_before(range_to_move.end),
6992 String::new(),
6993 ));
6994 let insertion_anchor = buffer.anchor_after(insertion_point);
6995 edits.push((insertion_anchor..insertion_anchor, text));
6996
6997 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6998
6999 // Move selections down
7000 new_selections.extend(contiguous_row_selections.drain(..).map(
7001 |mut selection| {
7002 selection.start.row += row_delta;
7003 selection.end.row += row_delta;
7004 selection
7005 },
7006 ));
7007
7008 // Move folds down
7009 unfold_ranges.push(range_to_move.clone());
7010 for fold in display_map.folds_in_range(
7011 buffer.anchor_before(range_to_move.start)
7012 ..buffer.anchor_after(range_to_move.end),
7013 ) {
7014 let mut start = fold.range.start.to_point(&buffer);
7015 let mut end = fold.range.end.to_point(&buffer);
7016 start.row += row_delta;
7017 end.row += row_delta;
7018 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7019 }
7020 }
7021 }
7022
7023 // If we didn't move line(s), preserve the existing selections
7024 new_selections.append(&mut contiguous_row_selections);
7025 }
7026
7027 self.transact(cx, |this, cx| {
7028 this.unfold_ranges(&unfold_ranges, true, true, cx);
7029 this.buffer.update(cx, |buffer, cx| {
7030 for (range, text) in edits {
7031 buffer.edit([(range, text)], None, cx);
7032 }
7033 });
7034 this.fold_creases(refold_creases, true, cx);
7035 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7036 });
7037 }
7038
7039 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7040 let text_layout_details = &self.text_layout_details(cx);
7041 self.transact(cx, |this, cx| {
7042 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7043 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7044 let line_mode = s.line_mode;
7045 s.move_with(|display_map, selection| {
7046 if !selection.is_empty() || line_mode {
7047 return;
7048 }
7049
7050 let mut head = selection.head();
7051 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7052 if head.column() == display_map.line_len(head.row()) {
7053 transpose_offset = display_map
7054 .buffer_snapshot
7055 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7056 }
7057
7058 if transpose_offset == 0 {
7059 return;
7060 }
7061
7062 *head.column_mut() += 1;
7063 head = display_map.clip_point(head, Bias::Right);
7064 let goal = SelectionGoal::HorizontalPosition(
7065 display_map
7066 .x_for_display_point(head, text_layout_details)
7067 .into(),
7068 );
7069 selection.collapse_to(head, goal);
7070
7071 let transpose_start = display_map
7072 .buffer_snapshot
7073 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7074 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7075 let transpose_end = display_map
7076 .buffer_snapshot
7077 .clip_offset(transpose_offset + 1, Bias::Right);
7078 if let Some(ch) =
7079 display_map.buffer_snapshot.chars_at(transpose_start).next()
7080 {
7081 edits.push((transpose_start..transpose_offset, String::new()));
7082 edits.push((transpose_end..transpose_end, ch.to_string()));
7083 }
7084 }
7085 });
7086 edits
7087 });
7088 this.buffer
7089 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7090 let selections = this.selections.all::<usize>(cx);
7091 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7092 s.select(selections);
7093 });
7094 });
7095 }
7096
7097 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7098 self.rewrap_impl(IsVimMode::No, cx)
7099 }
7100
7101 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7102 let buffer = self.buffer.read(cx).snapshot(cx);
7103 let selections = self.selections.all::<Point>(cx);
7104 let mut selections = selections.iter().peekable();
7105
7106 let mut edits = Vec::new();
7107 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7108
7109 while let Some(selection) = selections.next() {
7110 let mut start_row = selection.start.row;
7111 let mut end_row = selection.end.row;
7112
7113 // Skip selections that overlap with a range that has already been rewrapped.
7114 let selection_range = start_row..end_row;
7115 if rewrapped_row_ranges
7116 .iter()
7117 .any(|range| range.overlaps(&selection_range))
7118 {
7119 continue;
7120 }
7121
7122 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7123
7124 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7125 match language_scope.language_name().0.as_ref() {
7126 "Markdown" | "Plain Text" => {
7127 should_rewrap = true;
7128 }
7129 _ => {}
7130 }
7131 }
7132
7133 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7134
7135 // Since not all lines in the selection may be at the same indent
7136 // level, choose the indent size that is the most common between all
7137 // of the lines.
7138 //
7139 // If there is a tie, we use the deepest indent.
7140 let (indent_size, indent_end) = {
7141 let mut indent_size_occurrences = HashMap::default();
7142 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7143
7144 for row in start_row..=end_row {
7145 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7146 rows_by_indent_size.entry(indent).or_default().push(row);
7147 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7148 }
7149
7150 let indent_size = indent_size_occurrences
7151 .into_iter()
7152 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7153 .map(|(indent, _)| indent)
7154 .unwrap_or_default();
7155 let row = rows_by_indent_size[&indent_size][0];
7156 let indent_end = Point::new(row, indent_size.len);
7157
7158 (indent_size, indent_end)
7159 };
7160
7161 let mut line_prefix = indent_size.chars().collect::<String>();
7162
7163 if let Some(comment_prefix) =
7164 buffer
7165 .language_scope_at(selection.head())
7166 .and_then(|language| {
7167 language
7168 .line_comment_prefixes()
7169 .iter()
7170 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7171 .cloned()
7172 })
7173 {
7174 line_prefix.push_str(&comment_prefix);
7175 should_rewrap = true;
7176 }
7177
7178 if !should_rewrap {
7179 continue;
7180 }
7181
7182 if selection.is_empty() {
7183 'expand_upwards: while start_row > 0 {
7184 let prev_row = start_row - 1;
7185 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7186 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7187 {
7188 start_row = prev_row;
7189 } else {
7190 break 'expand_upwards;
7191 }
7192 }
7193
7194 'expand_downwards: while end_row < buffer.max_point().row {
7195 let next_row = end_row + 1;
7196 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7197 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7198 {
7199 end_row = next_row;
7200 } else {
7201 break 'expand_downwards;
7202 }
7203 }
7204 }
7205
7206 let start = Point::new(start_row, 0);
7207 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7208 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7209 let Some(lines_without_prefixes) = selection_text
7210 .lines()
7211 .map(|line| {
7212 line.strip_prefix(&line_prefix)
7213 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7214 .ok_or_else(|| {
7215 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7216 })
7217 })
7218 .collect::<Result<Vec<_>, _>>()
7219 .log_err()
7220 else {
7221 continue;
7222 };
7223
7224 let wrap_column = buffer
7225 .settings_at(Point::new(start_row, 0), cx)
7226 .preferred_line_length as usize;
7227 let wrapped_text = wrap_with_prefix(
7228 line_prefix,
7229 lines_without_prefixes.join(" "),
7230 wrap_column,
7231 tab_size,
7232 );
7233
7234 // TODO: should always use char-based diff while still supporting cursor behavior that
7235 // matches vim.
7236 let diff = match is_vim_mode {
7237 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7238 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7239 };
7240 let mut offset = start.to_offset(&buffer);
7241 let mut moved_since_edit = true;
7242
7243 for change in diff.iter_all_changes() {
7244 let value = change.value();
7245 match change.tag() {
7246 ChangeTag::Equal => {
7247 offset += value.len();
7248 moved_since_edit = true;
7249 }
7250 ChangeTag::Delete => {
7251 let start = buffer.anchor_after(offset);
7252 let end = buffer.anchor_before(offset + value.len());
7253
7254 if moved_since_edit {
7255 edits.push((start..end, String::new()));
7256 } else {
7257 edits.last_mut().unwrap().0.end = end;
7258 }
7259
7260 offset += value.len();
7261 moved_since_edit = false;
7262 }
7263 ChangeTag::Insert => {
7264 if moved_since_edit {
7265 let anchor = buffer.anchor_after(offset);
7266 edits.push((anchor..anchor, value.to_string()));
7267 } else {
7268 edits.last_mut().unwrap().1.push_str(value);
7269 }
7270
7271 moved_since_edit = false;
7272 }
7273 }
7274 }
7275
7276 rewrapped_row_ranges.push(start_row..=end_row);
7277 }
7278
7279 self.buffer
7280 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7281 }
7282
7283 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
7284 let mut text = String::new();
7285 let buffer = self.buffer.read(cx).snapshot(cx);
7286 let mut selections = self.selections.all::<Point>(cx);
7287 let mut clipboard_selections = Vec::with_capacity(selections.len());
7288 {
7289 let max_point = buffer.max_point();
7290 let mut is_first = true;
7291 for selection in &mut selections {
7292 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7293 if is_entire_line {
7294 selection.start = Point::new(selection.start.row, 0);
7295 if !selection.is_empty() && selection.end.column == 0 {
7296 selection.end = cmp::min(max_point, selection.end);
7297 } else {
7298 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7299 }
7300 selection.goal = SelectionGoal::None;
7301 }
7302 if is_first {
7303 is_first = false;
7304 } else {
7305 text += "\n";
7306 }
7307 let mut len = 0;
7308 for chunk in buffer.text_for_range(selection.start..selection.end) {
7309 text.push_str(chunk);
7310 len += chunk.len();
7311 }
7312 clipboard_selections.push(ClipboardSelection {
7313 len,
7314 is_entire_line,
7315 first_line_indent: buffer
7316 .indent_size_for_line(MultiBufferRow(selection.start.row))
7317 .len,
7318 });
7319 }
7320 }
7321
7322 self.transact(cx, |this, cx| {
7323 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7324 s.select(selections);
7325 });
7326 this.insert("", cx);
7327 });
7328 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7329 }
7330
7331 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7332 let item = self.cut_common(cx);
7333 cx.write_to_clipboard(item);
7334 }
7335
7336 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
7337 self.change_selections(None, cx, |s| {
7338 s.move_with(|snapshot, sel| {
7339 if sel.is_empty() {
7340 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7341 }
7342 });
7343 });
7344 let item = self.cut_common(cx);
7345 cx.set_global(KillRing(item))
7346 }
7347
7348 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7349 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7350 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7351 (kill_ring.text().to_string(), kill_ring.metadata_json())
7352 } else {
7353 return;
7354 }
7355 } else {
7356 return;
7357 };
7358 self.do_paste(&text, metadata, false, cx);
7359 }
7360
7361 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7362 let selections = self.selections.all::<Point>(cx);
7363 let buffer = self.buffer.read(cx).read(cx);
7364 let mut text = String::new();
7365
7366 let mut clipboard_selections = Vec::with_capacity(selections.len());
7367 {
7368 let max_point = buffer.max_point();
7369 let mut is_first = true;
7370 for selection in selections.iter() {
7371 let mut start = selection.start;
7372 let mut end = selection.end;
7373 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7374 if is_entire_line {
7375 start = Point::new(start.row, 0);
7376 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7377 }
7378 if is_first {
7379 is_first = false;
7380 } else {
7381 text += "\n";
7382 }
7383 let mut len = 0;
7384 for chunk in buffer.text_for_range(start..end) {
7385 text.push_str(chunk);
7386 len += chunk.len();
7387 }
7388 clipboard_selections.push(ClipboardSelection {
7389 len,
7390 is_entire_line,
7391 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7392 });
7393 }
7394 }
7395
7396 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7397 text,
7398 clipboard_selections,
7399 ));
7400 }
7401
7402 pub fn do_paste(
7403 &mut self,
7404 text: &String,
7405 clipboard_selections: Option<Vec<ClipboardSelection>>,
7406 handle_entire_lines: bool,
7407 cx: &mut ViewContext<Self>,
7408 ) {
7409 if self.read_only(cx) {
7410 return;
7411 }
7412
7413 let clipboard_text = Cow::Borrowed(text);
7414
7415 self.transact(cx, |this, cx| {
7416 if let Some(mut clipboard_selections) = clipboard_selections {
7417 let old_selections = this.selections.all::<usize>(cx);
7418 let all_selections_were_entire_line =
7419 clipboard_selections.iter().all(|s| s.is_entire_line);
7420 let first_selection_indent_column =
7421 clipboard_selections.first().map(|s| s.first_line_indent);
7422 if clipboard_selections.len() != old_selections.len() {
7423 clipboard_selections.drain(..);
7424 }
7425 let cursor_offset = this.selections.last::<usize>(cx).head();
7426 let mut auto_indent_on_paste = true;
7427
7428 this.buffer.update(cx, |buffer, cx| {
7429 let snapshot = buffer.read(cx);
7430 auto_indent_on_paste =
7431 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7432
7433 let mut start_offset = 0;
7434 let mut edits = Vec::new();
7435 let mut original_indent_columns = Vec::new();
7436 for (ix, selection) in old_selections.iter().enumerate() {
7437 let to_insert;
7438 let entire_line;
7439 let original_indent_column;
7440 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7441 let end_offset = start_offset + clipboard_selection.len;
7442 to_insert = &clipboard_text[start_offset..end_offset];
7443 entire_line = clipboard_selection.is_entire_line;
7444 start_offset = end_offset + 1;
7445 original_indent_column = Some(clipboard_selection.first_line_indent);
7446 } else {
7447 to_insert = clipboard_text.as_str();
7448 entire_line = all_selections_were_entire_line;
7449 original_indent_column = first_selection_indent_column
7450 }
7451
7452 // If the corresponding selection was empty when this slice of the
7453 // clipboard text was written, then the entire line containing the
7454 // selection was copied. If this selection is also currently empty,
7455 // then paste the line before the current line of the buffer.
7456 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7457 let column = selection.start.to_point(&snapshot).column as usize;
7458 let line_start = selection.start - column;
7459 line_start..line_start
7460 } else {
7461 selection.range()
7462 };
7463
7464 edits.push((range, to_insert));
7465 original_indent_columns.extend(original_indent_column);
7466 }
7467 drop(snapshot);
7468
7469 buffer.edit(
7470 edits,
7471 if auto_indent_on_paste {
7472 Some(AutoindentMode::Block {
7473 original_indent_columns,
7474 })
7475 } else {
7476 None
7477 },
7478 cx,
7479 );
7480 });
7481
7482 let selections = this.selections.all::<usize>(cx);
7483 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7484 } else {
7485 this.insert(&clipboard_text, cx);
7486 }
7487 });
7488 }
7489
7490 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7491 if let Some(item) = cx.read_from_clipboard() {
7492 let entries = item.entries();
7493
7494 match entries.first() {
7495 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7496 // of all the pasted entries.
7497 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7498 .do_paste(
7499 clipboard_string.text(),
7500 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7501 true,
7502 cx,
7503 ),
7504 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7505 }
7506 }
7507 }
7508
7509 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7510 if self.read_only(cx) {
7511 return;
7512 }
7513
7514 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7515 if let Some((selections, _)) =
7516 self.selection_history.transaction(transaction_id).cloned()
7517 {
7518 self.change_selections(None, cx, |s| {
7519 s.select_anchors(selections.to_vec());
7520 });
7521 }
7522 self.request_autoscroll(Autoscroll::fit(), cx);
7523 self.unmark_text(cx);
7524 self.refresh_inline_completion(true, false, cx);
7525 cx.emit(EditorEvent::Edited { transaction_id });
7526 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7527 }
7528 }
7529
7530 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7531 if self.read_only(cx) {
7532 return;
7533 }
7534
7535 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7536 if let Some((_, Some(selections))) =
7537 self.selection_history.transaction(transaction_id).cloned()
7538 {
7539 self.change_selections(None, cx, |s| {
7540 s.select_anchors(selections.to_vec());
7541 });
7542 }
7543 self.request_autoscroll(Autoscroll::fit(), cx);
7544 self.unmark_text(cx);
7545 self.refresh_inline_completion(true, false, cx);
7546 cx.emit(EditorEvent::Edited { transaction_id });
7547 }
7548 }
7549
7550 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7551 self.buffer
7552 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7553 }
7554
7555 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7556 self.buffer
7557 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7558 }
7559
7560 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7561 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7562 let line_mode = s.line_mode;
7563 s.move_with(|map, selection| {
7564 let cursor = if selection.is_empty() && !line_mode {
7565 movement::left(map, selection.start)
7566 } else {
7567 selection.start
7568 };
7569 selection.collapse_to(cursor, SelectionGoal::None);
7570 });
7571 })
7572 }
7573
7574 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7576 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7577 })
7578 }
7579
7580 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7581 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7582 let line_mode = s.line_mode;
7583 s.move_with(|map, selection| {
7584 let cursor = if selection.is_empty() && !line_mode {
7585 movement::right(map, selection.end)
7586 } else {
7587 selection.end
7588 };
7589 selection.collapse_to(cursor, SelectionGoal::None)
7590 });
7591 })
7592 }
7593
7594 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7595 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7596 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7597 })
7598 }
7599
7600 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7601 if self.take_rename(true, cx).is_some() {
7602 return;
7603 }
7604
7605 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7606 cx.propagate();
7607 return;
7608 }
7609
7610 let text_layout_details = &self.text_layout_details(cx);
7611 let selection_count = self.selections.count();
7612 let first_selection = self.selections.first_anchor();
7613
7614 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7615 let line_mode = s.line_mode;
7616 s.move_with(|map, selection| {
7617 if !selection.is_empty() && !line_mode {
7618 selection.goal = SelectionGoal::None;
7619 }
7620 let (cursor, goal) = movement::up(
7621 map,
7622 selection.start,
7623 selection.goal,
7624 false,
7625 text_layout_details,
7626 );
7627 selection.collapse_to(cursor, goal);
7628 });
7629 });
7630
7631 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7632 {
7633 cx.propagate();
7634 }
7635 }
7636
7637 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7638 if self.take_rename(true, cx).is_some() {
7639 return;
7640 }
7641
7642 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7643 cx.propagate();
7644 return;
7645 }
7646
7647 let text_layout_details = &self.text_layout_details(cx);
7648
7649 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7650 let line_mode = s.line_mode;
7651 s.move_with(|map, selection| {
7652 if !selection.is_empty() && !line_mode {
7653 selection.goal = SelectionGoal::None;
7654 }
7655 let (cursor, goal) = movement::up_by_rows(
7656 map,
7657 selection.start,
7658 action.lines,
7659 selection.goal,
7660 false,
7661 text_layout_details,
7662 );
7663 selection.collapse_to(cursor, goal);
7664 });
7665 })
7666 }
7667
7668 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7669 if self.take_rename(true, cx).is_some() {
7670 return;
7671 }
7672
7673 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7674 cx.propagate();
7675 return;
7676 }
7677
7678 let text_layout_details = &self.text_layout_details(cx);
7679
7680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7681 let line_mode = s.line_mode;
7682 s.move_with(|map, selection| {
7683 if !selection.is_empty() && !line_mode {
7684 selection.goal = SelectionGoal::None;
7685 }
7686 let (cursor, goal) = movement::down_by_rows(
7687 map,
7688 selection.start,
7689 action.lines,
7690 selection.goal,
7691 false,
7692 text_layout_details,
7693 );
7694 selection.collapse_to(cursor, goal);
7695 });
7696 })
7697 }
7698
7699 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7700 let text_layout_details = &self.text_layout_details(cx);
7701 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7702 s.move_heads_with(|map, head, goal| {
7703 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7704 })
7705 })
7706 }
7707
7708 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7709 let text_layout_details = &self.text_layout_details(cx);
7710 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7711 s.move_heads_with(|map, head, goal| {
7712 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7713 })
7714 })
7715 }
7716
7717 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7718 let Some(row_count) = self.visible_row_count() else {
7719 return;
7720 };
7721
7722 let text_layout_details = &self.text_layout_details(cx);
7723
7724 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7725 s.move_heads_with(|map, head, goal| {
7726 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7727 })
7728 })
7729 }
7730
7731 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7732 if self.take_rename(true, cx).is_some() {
7733 return;
7734 }
7735
7736 if self
7737 .context_menu
7738 .write()
7739 .as_mut()
7740 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7741 .unwrap_or(false)
7742 {
7743 return;
7744 }
7745
7746 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7747 cx.propagate();
7748 return;
7749 }
7750
7751 let Some(row_count) = self.visible_row_count() else {
7752 return;
7753 };
7754
7755 let autoscroll = if action.center_cursor {
7756 Autoscroll::center()
7757 } else {
7758 Autoscroll::fit()
7759 };
7760
7761 let text_layout_details = &self.text_layout_details(cx);
7762
7763 self.change_selections(Some(autoscroll), cx, |s| {
7764 let line_mode = s.line_mode;
7765 s.move_with(|map, selection| {
7766 if !selection.is_empty() && !line_mode {
7767 selection.goal = SelectionGoal::None;
7768 }
7769 let (cursor, goal) = movement::up_by_rows(
7770 map,
7771 selection.end,
7772 row_count,
7773 selection.goal,
7774 false,
7775 text_layout_details,
7776 );
7777 selection.collapse_to(cursor, goal);
7778 });
7779 });
7780 }
7781
7782 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7783 let text_layout_details = &self.text_layout_details(cx);
7784 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7785 s.move_heads_with(|map, head, goal| {
7786 movement::up(map, head, goal, false, text_layout_details)
7787 })
7788 })
7789 }
7790
7791 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7792 self.take_rename(true, cx);
7793
7794 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7795 cx.propagate();
7796 return;
7797 }
7798
7799 let text_layout_details = &self.text_layout_details(cx);
7800 let selection_count = self.selections.count();
7801 let first_selection = self.selections.first_anchor();
7802
7803 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7804 let line_mode = s.line_mode;
7805 s.move_with(|map, selection| {
7806 if !selection.is_empty() && !line_mode {
7807 selection.goal = SelectionGoal::None;
7808 }
7809 let (cursor, goal) = movement::down(
7810 map,
7811 selection.end,
7812 selection.goal,
7813 false,
7814 text_layout_details,
7815 );
7816 selection.collapse_to(cursor, goal);
7817 });
7818 });
7819
7820 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7821 {
7822 cx.propagate();
7823 }
7824 }
7825
7826 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7827 let Some(row_count) = self.visible_row_count() else {
7828 return;
7829 };
7830
7831 let text_layout_details = &self.text_layout_details(cx);
7832
7833 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7834 s.move_heads_with(|map, head, goal| {
7835 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7836 })
7837 })
7838 }
7839
7840 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7841 if self.take_rename(true, cx).is_some() {
7842 return;
7843 }
7844
7845 if self
7846 .context_menu
7847 .write()
7848 .as_mut()
7849 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7850 .unwrap_or(false)
7851 {
7852 return;
7853 }
7854
7855 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7856 cx.propagate();
7857 return;
7858 }
7859
7860 let Some(row_count) = self.visible_row_count() else {
7861 return;
7862 };
7863
7864 let autoscroll = if action.center_cursor {
7865 Autoscroll::center()
7866 } else {
7867 Autoscroll::fit()
7868 };
7869
7870 let text_layout_details = &self.text_layout_details(cx);
7871 self.change_selections(Some(autoscroll), cx, |s| {
7872 let line_mode = s.line_mode;
7873 s.move_with(|map, selection| {
7874 if !selection.is_empty() && !line_mode {
7875 selection.goal = SelectionGoal::None;
7876 }
7877 let (cursor, goal) = movement::down_by_rows(
7878 map,
7879 selection.end,
7880 row_count,
7881 selection.goal,
7882 false,
7883 text_layout_details,
7884 );
7885 selection.collapse_to(cursor, goal);
7886 });
7887 });
7888 }
7889
7890 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7891 let text_layout_details = &self.text_layout_details(cx);
7892 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7893 s.move_heads_with(|map, head, goal| {
7894 movement::down(map, head, goal, false, text_layout_details)
7895 })
7896 });
7897 }
7898
7899 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7900 if let Some(context_menu) = self.context_menu.write().as_mut() {
7901 context_menu.select_first(self.completion_provider.as_deref(), cx);
7902 }
7903 }
7904
7905 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7906 if let Some(context_menu) = self.context_menu.write().as_mut() {
7907 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7908 }
7909 }
7910
7911 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7912 if let Some(context_menu) = self.context_menu.write().as_mut() {
7913 context_menu.select_next(self.completion_provider.as_deref(), cx);
7914 }
7915 }
7916
7917 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7918 if let Some(context_menu) = self.context_menu.write().as_mut() {
7919 context_menu.select_last(self.completion_provider.as_deref(), cx);
7920 }
7921 }
7922
7923 pub fn move_to_previous_word_start(
7924 &mut self,
7925 _: &MoveToPreviousWordStart,
7926 cx: &mut ViewContext<Self>,
7927 ) {
7928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7929 s.move_cursors_with(|map, head, _| {
7930 (
7931 movement::previous_word_start(map, head),
7932 SelectionGoal::None,
7933 )
7934 });
7935 })
7936 }
7937
7938 pub fn move_to_previous_subword_start(
7939 &mut self,
7940 _: &MoveToPreviousSubwordStart,
7941 cx: &mut ViewContext<Self>,
7942 ) {
7943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 s.move_cursors_with(|map, head, _| {
7945 (
7946 movement::previous_subword_start(map, head),
7947 SelectionGoal::None,
7948 )
7949 });
7950 })
7951 }
7952
7953 pub fn select_to_previous_word_start(
7954 &mut self,
7955 _: &SelectToPreviousWordStart,
7956 cx: &mut ViewContext<Self>,
7957 ) {
7958 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7959 s.move_heads_with(|map, head, _| {
7960 (
7961 movement::previous_word_start(map, head),
7962 SelectionGoal::None,
7963 )
7964 });
7965 })
7966 }
7967
7968 pub fn select_to_previous_subword_start(
7969 &mut self,
7970 _: &SelectToPreviousSubwordStart,
7971 cx: &mut ViewContext<Self>,
7972 ) {
7973 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7974 s.move_heads_with(|map, head, _| {
7975 (
7976 movement::previous_subword_start(map, head),
7977 SelectionGoal::None,
7978 )
7979 });
7980 })
7981 }
7982
7983 pub fn delete_to_previous_word_start(
7984 &mut self,
7985 action: &DeleteToPreviousWordStart,
7986 cx: &mut ViewContext<Self>,
7987 ) {
7988 self.transact(cx, |this, cx| {
7989 this.select_autoclose_pair(cx);
7990 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7991 let line_mode = s.line_mode;
7992 s.move_with(|map, selection| {
7993 if selection.is_empty() && !line_mode {
7994 let cursor = if action.ignore_newlines {
7995 movement::previous_word_start(map, selection.head())
7996 } else {
7997 movement::previous_word_start_or_newline(map, selection.head())
7998 };
7999 selection.set_head(cursor, SelectionGoal::None);
8000 }
8001 });
8002 });
8003 this.insert("", cx);
8004 });
8005 }
8006
8007 pub fn delete_to_previous_subword_start(
8008 &mut self,
8009 _: &DeleteToPreviousSubwordStart,
8010 cx: &mut ViewContext<Self>,
8011 ) {
8012 self.transact(cx, |this, cx| {
8013 this.select_autoclose_pair(cx);
8014 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8015 let line_mode = s.line_mode;
8016 s.move_with(|map, selection| {
8017 if selection.is_empty() && !line_mode {
8018 let cursor = movement::previous_subword_start(map, selection.head());
8019 selection.set_head(cursor, SelectionGoal::None);
8020 }
8021 });
8022 });
8023 this.insert("", cx);
8024 });
8025 }
8026
8027 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8028 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8029 s.move_cursors_with(|map, head, _| {
8030 (movement::next_word_end(map, head), SelectionGoal::None)
8031 });
8032 })
8033 }
8034
8035 pub fn move_to_next_subword_end(
8036 &mut self,
8037 _: &MoveToNextSubwordEnd,
8038 cx: &mut ViewContext<Self>,
8039 ) {
8040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8041 s.move_cursors_with(|map, head, _| {
8042 (movement::next_subword_end(map, head), SelectionGoal::None)
8043 });
8044 })
8045 }
8046
8047 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8048 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8049 s.move_heads_with(|map, head, _| {
8050 (movement::next_word_end(map, head), SelectionGoal::None)
8051 });
8052 })
8053 }
8054
8055 pub fn select_to_next_subword_end(
8056 &mut self,
8057 _: &SelectToNextSubwordEnd,
8058 cx: &mut ViewContext<Self>,
8059 ) {
8060 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8061 s.move_heads_with(|map, head, _| {
8062 (movement::next_subword_end(map, head), SelectionGoal::None)
8063 });
8064 })
8065 }
8066
8067 pub fn delete_to_next_word_end(
8068 &mut self,
8069 action: &DeleteToNextWordEnd,
8070 cx: &mut ViewContext<Self>,
8071 ) {
8072 self.transact(cx, |this, cx| {
8073 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8074 let line_mode = s.line_mode;
8075 s.move_with(|map, selection| {
8076 if selection.is_empty() && !line_mode {
8077 let cursor = if action.ignore_newlines {
8078 movement::next_word_end(map, selection.head())
8079 } else {
8080 movement::next_word_end_or_newline(map, selection.head())
8081 };
8082 selection.set_head(cursor, SelectionGoal::None);
8083 }
8084 });
8085 });
8086 this.insert("", cx);
8087 });
8088 }
8089
8090 pub fn delete_to_next_subword_end(
8091 &mut self,
8092 _: &DeleteToNextSubwordEnd,
8093 cx: &mut ViewContext<Self>,
8094 ) {
8095 self.transact(cx, |this, cx| {
8096 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8097 s.move_with(|map, selection| {
8098 if selection.is_empty() {
8099 let cursor = movement::next_subword_end(map, selection.head());
8100 selection.set_head(cursor, SelectionGoal::None);
8101 }
8102 });
8103 });
8104 this.insert("", cx);
8105 });
8106 }
8107
8108 pub fn move_to_beginning_of_line(
8109 &mut self,
8110 action: &MoveToBeginningOfLine,
8111 cx: &mut ViewContext<Self>,
8112 ) {
8113 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8114 s.move_cursors_with(|map, head, _| {
8115 (
8116 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8117 SelectionGoal::None,
8118 )
8119 });
8120 })
8121 }
8122
8123 pub fn select_to_beginning_of_line(
8124 &mut self,
8125 action: &SelectToBeginningOfLine,
8126 cx: &mut ViewContext<Self>,
8127 ) {
8128 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8129 s.move_heads_with(|map, head, _| {
8130 (
8131 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8132 SelectionGoal::None,
8133 )
8134 });
8135 });
8136 }
8137
8138 pub fn delete_to_beginning_of_line(
8139 &mut self,
8140 _: &DeleteToBeginningOfLine,
8141 cx: &mut ViewContext<Self>,
8142 ) {
8143 self.transact(cx, |this, cx| {
8144 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8145 s.move_with(|_, selection| {
8146 selection.reversed = true;
8147 });
8148 });
8149
8150 this.select_to_beginning_of_line(
8151 &SelectToBeginningOfLine {
8152 stop_at_soft_wraps: false,
8153 },
8154 cx,
8155 );
8156 this.backspace(&Backspace, cx);
8157 });
8158 }
8159
8160 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8161 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8162 s.move_cursors_with(|map, head, _| {
8163 (
8164 movement::line_end(map, head, action.stop_at_soft_wraps),
8165 SelectionGoal::None,
8166 )
8167 });
8168 })
8169 }
8170
8171 pub fn select_to_end_of_line(
8172 &mut self,
8173 action: &SelectToEndOfLine,
8174 cx: &mut ViewContext<Self>,
8175 ) {
8176 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8177 s.move_heads_with(|map, head, _| {
8178 (
8179 movement::line_end(map, head, action.stop_at_soft_wraps),
8180 SelectionGoal::None,
8181 )
8182 });
8183 })
8184 }
8185
8186 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8187 self.transact(cx, |this, cx| {
8188 this.select_to_end_of_line(
8189 &SelectToEndOfLine {
8190 stop_at_soft_wraps: false,
8191 },
8192 cx,
8193 );
8194 this.delete(&Delete, cx);
8195 });
8196 }
8197
8198 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8199 self.transact(cx, |this, cx| {
8200 this.select_to_end_of_line(
8201 &SelectToEndOfLine {
8202 stop_at_soft_wraps: false,
8203 },
8204 cx,
8205 );
8206 this.cut(&Cut, cx);
8207 });
8208 }
8209
8210 pub fn move_to_start_of_paragraph(
8211 &mut self,
8212 _: &MoveToStartOfParagraph,
8213 cx: &mut ViewContext<Self>,
8214 ) {
8215 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8216 cx.propagate();
8217 return;
8218 }
8219
8220 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8221 s.move_with(|map, selection| {
8222 selection.collapse_to(
8223 movement::start_of_paragraph(map, selection.head(), 1),
8224 SelectionGoal::None,
8225 )
8226 });
8227 })
8228 }
8229
8230 pub fn move_to_end_of_paragraph(
8231 &mut self,
8232 _: &MoveToEndOfParagraph,
8233 cx: &mut ViewContext<Self>,
8234 ) {
8235 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8236 cx.propagate();
8237 return;
8238 }
8239
8240 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8241 s.move_with(|map, selection| {
8242 selection.collapse_to(
8243 movement::end_of_paragraph(map, selection.head(), 1),
8244 SelectionGoal::None,
8245 )
8246 });
8247 })
8248 }
8249
8250 pub fn select_to_start_of_paragraph(
8251 &mut self,
8252 _: &SelectToStartOfParagraph,
8253 cx: &mut ViewContext<Self>,
8254 ) {
8255 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8256 cx.propagate();
8257 return;
8258 }
8259
8260 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8261 s.move_heads_with(|map, head, _| {
8262 (
8263 movement::start_of_paragraph(map, head, 1),
8264 SelectionGoal::None,
8265 )
8266 });
8267 })
8268 }
8269
8270 pub fn select_to_end_of_paragraph(
8271 &mut self,
8272 _: &SelectToEndOfParagraph,
8273 cx: &mut ViewContext<Self>,
8274 ) {
8275 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8276 cx.propagate();
8277 return;
8278 }
8279
8280 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8281 s.move_heads_with(|map, head, _| {
8282 (
8283 movement::end_of_paragraph(map, head, 1),
8284 SelectionGoal::None,
8285 )
8286 });
8287 })
8288 }
8289
8290 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8291 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8292 cx.propagate();
8293 return;
8294 }
8295
8296 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8297 s.select_ranges(vec![0..0]);
8298 });
8299 }
8300
8301 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8302 let mut selection = self.selections.last::<Point>(cx);
8303 selection.set_head(Point::zero(), SelectionGoal::None);
8304
8305 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8306 s.select(vec![selection]);
8307 });
8308 }
8309
8310 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8311 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8312 cx.propagate();
8313 return;
8314 }
8315
8316 let cursor = self.buffer.read(cx).read(cx).len();
8317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8318 s.select_ranges(vec![cursor..cursor])
8319 });
8320 }
8321
8322 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8323 self.nav_history = nav_history;
8324 }
8325
8326 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8327 self.nav_history.as_ref()
8328 }
8329
8330 fn push_to_nav_history(
8331 &mut self,
8332 cursor_anchor: Anchor,
8333 new_position: Option<Point>,
8334 cx: &mut ViewContext<Self>,
8335 ) {
8336 if let Some(nav_history) = self.nav_history.as_mut() {
8337 let buffer = self.buffer.read(cx).read(cx);
8338 let cursor_position = cursor_anchor.to_point(&buffer);
8339 let scroll_state = self.scroll_manager.anchor();
8340 let scroll_top_row = scroll_state.top_row(&buffer);
8341 drop(buffer);
8342
8343 if let Some(new_position) = new_position {
8344 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8345 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8346 return;
8347 }
8348 }
8349
8350 nav_history.push(
8351 Some(NavigationData {
8352 cursor_anchor,
8353 cursor_position,
8354 scroll_anchor: scroll_state,
8355 scroll_top_row,
8356 }),
8357 cx,
8358 );
8359 }
8360 }
8361
8362 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8363 let buffer = self.buffer.read(cx).snapshot(cx);
8364 let mut selection = self.selections.first::<usize>(cx);
8365 selection.set_head(buffer.len(), SelectionGoal::None);
8366 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8367 s.select(vec![selection]);
8368 });
8369 }
8370
8371 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8372 let end = self.buffer.read(cx).read(cx).len();
8373 self.change_selections(None, cx, |s| {
8374 s.select_ranges(vec![0..end]);
8375 });
8376 }
8377
8378 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8379 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8380 let mut selections = self.selections.all::<Point>(cx);
8381 let max_point = display_map.buffer_snapshot.max_point();
8382 for selection in &mut selections {
8383 let rows = selection.spanned_rows(true, &display_map);
8384 selection.start = Point::new(rows.start.0, 0);
8385 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8386 selection.reversed = false;
8387 }
8388 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8389 s.select(selections);
8390 });
8391 }
8392
8393 pub fn split_selection_into_lines(
8394 &mut self,
8395 _: &SplitSelectionIntoLines,
8396 cx: &mut ViewContext<Self>,
8397 ) {
8398 let mut to_unfold = Vec::new();
8399 let mut new_selection_ranges = Vec::new();
8400 {
8401 let selections = self.selections.all::<Point>(cx);
8402 let buffer = self.buffer.read(cx).read(cx);
8403 for selection in selections {
8404 for row in selection.start.row..selection.end.row {
8405 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8406 new_selection_ranges.push(cursor..cursor);
8407 }
8408 new_selection_ranges.push(selection.end..selection.end);
8409 to_unfold.push(selection.start..selection.end);
8410 }
8411 }
8412 self.unfold_ranges(&to_unfold, true, true, cx);
8413 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8414 s.select_ranges(new_selection_ranges);
8415 });
8416 }
8417
8418 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8419 self.add_selection(true, cx);
8420 }
8421
8422 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8423 self.add_selection(false, cx);
8424 }
8425
8426 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8427 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8428 let mut selections = self.selections.all::<Point>(cx);
8429 let text_layout_details = self.text_layout_details(cx);
8430 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8431 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8432 let range = oldest_selection.display_range(&display_map).sorted();
8433
8434 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8435 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8436 let positions = start_x.min(end_x)..start_x.max(end_x);
8437
8438 selections.clear();
8439 let mut stack = Vec::new();
8440 for row in range.start.row().0..=range.end.row().0 {
8441 if let Some(selection) = self.selections.build_columnar_selection(
8442 &display_map,
8443 DisplayRow(row),
8444 &positions,
8445 oldest_selection.reversed,
8446 &text_layout_details,
8447 ) {
8448 stack.push(selection.id);
8449 selections.push(selection);
8450 }
8451 }
8452
8453 if above {
8454 stack.reverse();
8455 }
8456
8457 AddSelectionsState { above, stack }
8458 });
8459
8460 let last_added_selection = *state.stack.last().unwrap();
8461 let mut new_selections = Vec::new();
8462 if above == state.above {
8463 let end_row = if above {
8464 DisplayRow(0)
8465 } else {
8466 display_map.max_point().row()
8467 };
8468
8469 'outer: for selection in selections {
8470 if selection.id == last_added_selection {
8471 let range = selection.display_range(&display_map).sorted();
8472 debug_assert_eq!(range.start.row(), range.end.row());
8473 let mut row = range.start.row();
8474 let positions =
8475 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8476 px(start)..px(end)
8477 } else {
8478 let start_x =
8479 display_map.x_for_display_point(range.start, &text_layout_details);
8480 let end_x =
8481 display_map.x_for_display_point(range.end, &text_layout_details);
8482 start_x.min(end_x)..start_x.max(end_x)
8483 };
8484
8485 while row != end_row {
8486 if above {
8487 row.0 -= 1;
8488 } else {
8489 row.0 += 1;
8490 }
8491
8492 if let Some(new_selection) = self.selections.build_columnar_selection(
8493 &display_map,
8494 row,
8495 &positions,
8496 selection.reversed,
8497 &text_layout_details,
8498 ) {
8499 state.stack.push(new_selection.id);
8500 if above {
8501 new_selections.push(new_selection);
8502 new_selections.push(selection);
8503 } else {
8504 new_selections.push(selection);
8505 new_selections.push(new_selection);
8506 }
8507
8508 continue 'outer;
8509 }
8510 }
8511 }
8512
8513 new_selections.push(selection);
8514 }
8515 } else {
8516 new_selections = selections;
8517 new_selections.retain(|s| s.id != last_added_selection);
8518 state.stack.pop();
8519 }
8520
8521 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8522 s.select(new_selections);
8523 });
8524 if state.stack.len() > 1 {
8525 self.add_selections_state = Some(state);
8526 }
8527 }
8528
8529 pub fn select_next_match_internal(
8530 &mut self,
8531 display_map: &DisplaySnapshot,
8532 replace_newest: bool,
8533 autoscroll: Option<Autoscroll>,
8534 cx: &mut ViewContext<Self>,
8535 ) -> Result<()> {
8536 fn select_next_match_ranges(
8537 this: &mut Editor,
8538 range: Range<usize>,
8539 replace_newest: bool,
8540 auto_scroll: Option<Autoscroll>,
8541 cx: &mut ViewContext<Editor>,
8542 ) {
8543 this.unfold_ranges(&[range.clone()], false, true, cx);
8544 this.change_selections(auto_scroll, cx, |s| {
8545 if replace_newest {
8546 s.delete(s.newest_anchor().id);
8547 }
8548 s.insert_range(range.clone());
8549 });
8550 }
8551
8552 let buffer = &display_map.buffer_snapshot;
8553 let mut selections = self.selections.all::<usize>(cx);
8554 if let Some(mut select_next_state) = self.select_next_state.take() {
8555 let query = &select_next_state.query;
8556 if !select_next_state.done {
8557 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8558 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8559 let mut next_selected_range = None;
8560
8561 let bytes_after_last_selection =
8562 buffer.bytes_in_range(last_selection.end..buffer.len());
8563 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8564 let query_matches = query
8565 .stream_find_iter(bytes_after_last_selection)
8566 .map(|result| (last_selection.end, result))
8567 .chain(
8568 query
8569 .stream_find_iter(bytes_before_first_selection)
8570 .map(|result| (0, result)),
8571 );
8572
8573 for (start_offset, query_match) in query_matches {
8574 let query_match = query_match.unwrap(); // can only fail due to I/O
8575 let offset_range =
8576 start_offset + query_match.start()..start_offset + query_match.end();
8577 let display_range = offset_range.start.to_display_point(display_map)
8578 ..offset_range.end.to_display_point(display_map);
8579
8580 if !select_next_state.wordwise
8581 || (!movement::is_inside_word(display_map, display_range.start)
8582 && !movement::is_inside_word(display_map, display_range.end))
8583 {
8584 // TODO: This is n^2, because we might check all the selections
8585 if !selections
8586 .iter()
8587 .any(|selection| selection.range().overlaps(&offset_range))
8588 {
8589 next_selected_range = Some(offset_range);
8590 break;
8591 }
8592 }
8593 }
8594
8595 if let Some(next_selected_range) = next_selected_range {
8596 select_next_match_ranges(
8597 self,
8598 next_selected_range,
8599 replace_newest,
8600 autoscroll,
8601 cx,
8602 );
8603 } else {
8604 select_next_state.done = true;
8605 }
8606 }
8607
8608 self.select_next_state = Some(select_next_state);
8609 } else {
8610 let mut only_carets = true;
8611 let mut same_text_selected = true;
8612 let mut selected_text = None;
8613
8614 let mut selections_iter = selections.iter().peekable();
8615 while let Some(selection) = selections_iter.next() {
8616 if selection.start != selection.end {
8617 only_carets = false;
8618 }
8619
8620 if same_text_selected {
8621 if selected_text.is_none() {
8622 selected_text =
8623 Some(buffer.text_for_range(selection.range()).collect::<String>());
8624 }
8625
8626 if let Some(next_selection) = selections_iter.peek() {
8627 if next_selection.range().len() == selection.range().len() {
8628 let next_selected_text = buffer
8629 .text_for_range(next_selection.range())
8630 .collect::<String>();
8631 if Some(next_selected_text) != selected_text {
8632 same_text_selected = false;
8633 selected_text = None;
8634 }
8635 } else {
8636 same_text_selected = false;
8637 selected_text = None;
8638 }
8639 }
8640 }
8641 }
8642
8643 if only_carets {
8644 for selection in &mut selections {
8645 let word_range = movement::surrounding_word(
8646 display_map,
8647 selection.start.to_display_point(display_map),
8648 );
8649 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8650 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8651 selection.goal = SelectionGoal::None;
8652 selection.reversed = false;
8653 select_next_match_ranges(
8654 self,
8655 selection.start..selection.end,
8656 replace_newest,
8657 autoscroll,
8658 cx,
8659 );
8660 }
8661
8662 if selections.len() == 1 {
8663 let selection = selections
8664 .last()
8665 .expect("ensured that there's only one selection");
8666 let query = buffer
8667 .text_for_range(selection.start..selection.end)
8668 .collect::<String>();
8669 let is_empty = query.is_empty();
8670 let select_state = SelectNextState {
8671 query: AhoCorasick::new(&[query])?,
8672 wordwise: true,
8673 done: is_empty,
8674 };
8675 self.select_next_state = Some(select_state);
8676 } else {
8677 self.select_next_state = None;
8678 }
8679 } else if let Some(selected_text) = selected_text {
8680 self.select_next_state = Some(SelectNextState {
8681 query: AhoCorasick::new(&[selected_text])?,
8682 wordwise: false,
8683 done: false,
8684 });
8685 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8686 }
8687 }
8688 Ok(())
8689 }
8690
8691 pub fn select_all_matches(
8692 &mut self,
8693 _action: &SelectAllMatches,
8694 cx: &mut ViewContext<Self>,
8695 ) -> Result<()> {
8696 self.push_to_selection_history();
8697 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8698
8699 self.select_next_match_internal(&display_map, false, None, cx)?;
8700 let Some(select_next_state) = self.select_next_state.as_mut() else {
8701 return Ok(());
8702 };
8703 if select_next_state.done {
8704 return Ok(());
8705 }
8706
8707 let mut new_selections = self.selections.all::<usize>(cx);
8708
8709 let buffer = &display_map.buffer_snapshot;
8710 let query_matches = select_next_state
8711 .query
8712 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8713
8714 for query_match in query_matches {
8715 let query_match = query_match.unwrap(); // can only fail due to I/O
8716 let offset_range = query_match.start()..query_match.end();
8717 let display_range = offset_range.start.to_display_point(&display_map)
8718 ..offset_range.end.to_display_point(&display_map);
8719
8720 if !select_next_state.wordwise
8721 || (!movement::is_inside_word(&display_map, display_range.start)
8722 && !movement::is_inside_word(&display_map, display_range.end))
8723 {
8724 self.selections.change_with(cx, |selections| {
8725 new_selections.push(Selection {
8726 id: selections.new_selection_id(),
8727 start: offset_range.start,
8728 end: offset_range.end,
8729 reversed: false,
8730 goal: SelectionGoal::None,
8731 });
8732 });
8733 }
8734 }
8735
8736 new_selections.sort_by_key(|selection| selection.start);
8737 let mut ix = 0;
8738 while ix + 1 < new_selections.len() {
8739 let current_selection = &new_selections[ix];
8740 let next_selection = &new_selections[ix + 1];
8741 if current_selection.range().overlaps(&next_selection.range()) {
8742 if current_selection.id < next_selection.id {
8743 new_selections.remove(ix + 1);
8744 } else {
8745 new_selections.remove(ix);
8746 }
8747 } else {
8748 ix += 1;
8749 }
8750 }
8751
8752 select_next_state.done = true;
8753 self.unfold_ranges(
8754 &new_selections
8755 .iter()
8756 .map(|selection| selection.range())
8757 .collect::<Vec<_>>(),
8758 false,
8759 false,
8760 cx,
8761 );
8762 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8763 selections.select(new_selections)
8764 });
8765
8766 Ok(())
8767 }
8768
8769 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8770 self.push_to_selection_history();
8771 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8772 self.select_next_match_internal(
8773 &display_map,
8774 action.replace_newest,
8775 Some(Autoscroll::newest()),
8776 cx,
8777 )?;
8778 Ok(())
8779 }
8780
8781 pub fn select_previous(
8782 &mut self,
8783 action: &SelectPrevious,
8784 cx: &mut ViewContext<Self>,
8785 ) -> Result<()> {
8786 self.push_to_selection_history();
8787 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8788 let buffer = &display_map.buffer_snapshot;
8789 let mut selections = self.selections.all::<usize>(cx);
8790 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8791 let query = &select_prev_state.query;
8792 if !select_prev_state.done {
8793 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8794 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8795 let mut next_selected_range = None;
8796 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8797 let bytes_before_last_selection =
8798 buffer.reversed_bytes_in_range(0..last_selection.start);
8799 let bytes_after_first_selection =
8800 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8801 let query_matches = query
8802 .stream_find_iter(bytes_before_last_selection)
8803 .map(|result| (last_selection.start, result))
8804 .chain(
8805 query
8806 .stream_find_iter(bytes_after_first_selection)
8807 .map(|result| (buffer.len(), result)),
8808 );
8809 for (end_offset, query_match) in query_matches {
8810 let query_match = query_match.unwrap(); // can only fail due to I/O
8811 let offset_range =
8812 end_offset - query_match.end()..end_offset - query_match.start();
8813 let display_range = offset_range.start.to_display_point(&display_map)
8814 ..offset_range.end.to_display_point(&display_map);
8815
8816 if !select_prev_state.wordwise
8817 || (!movement::is_inside_word(&display_map, display_range.start)
8818 && !movement::is_inside_word(&display_map, display_range.end))
8819 {
8820 next_selected_range = Some(offset_range);
8821 break;
8822 }
8823 }
8824
8825 if let Some(next_selected_range) = next_selected_range {
8826 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8827 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8828 if action.replace_newest {
8829 s.delete(s.newest_anchor().id);
8830 }
8831 s.insert_range(next_selected_range);
8832 });
8833 } else {
8834 select_prev_state.done = true;
8835 }
8836 }
8837
8838 self.select_prev_state = Some(select_prev_state);
8839 } else {
8840 let mut only_carets = true;
8841 let mut same_text_selected = true;
8842 let mut selected_text = None;
8843
8844 let mut selections_iter = selections.iter().peekable();
8845 while let Some(selection) = selections_iter.next() {
8846 if selection.start != selection.end {
8847 only_carets = false;
8848 }
8849
8850 if same_text_selected {
8851 if selected_text.is_none() {
8852 selected_text =
8853 Some(buffer.text_for_range(selection.range()).collect::<String>());
8854 }
8855
8856 if let Some(next_selection) = selections_iter.peek() {
8857 if next_selection.range().len() == selection.range().len() {
8858 let next_selected_text = buffer
8859 .text_for_range(next_selection.range())
8860 .collect::<String>();
8861 if Some(next_selected_text) != selected_text {
8862 same_text_selected = false;
8863 selected_text = None;
8864 }
8865 } else {
8866 same_text_selected = false;
8867 selected_text = None;
8868 }
8869 }
8870 }
8871 }
8872
8873 if only_carets {
8874 for selection in &mut selections {
8875 let word_range = movement::surrounding_word(
8876 &display_map,
8877 selection.start.to_display_point(&display_map),
8878 );
8879 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8880 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8881 selection.goal = SelectionGoal::None;
8882 selection.reversed = false;
8883 }
8884 if selections.len() == 1 {
8885 let selection = selections
8886 .last()
8887 .expect("ensured that there's only one selection");
8888 let query = buffer
8889 .text_for_range(selection.start..selection.end)
8890 .collect::<String>();
8891 let is_empty = query.is_empty();
8892 let select_state = SelectNextState {
8893 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8894 wordwise: true,
8895 done: is_empty,
8896 };
8897 self.select_prev_state = Some(select_state);
8898 } else {
8899 self.select_prev_state = None;
8900 }
8901
8902 self.unfold_ranges(
8903 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8904 false,
8905 true,
8906 cx,
8907 );
8908 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8909 s.select(selections);
8910 });
8911 } else if let Some(selected_text) = selected_text {
8912 self.select_prev_state = Some(SelectNextState {
8913 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8914 wordwise: false,
8915 done: false,
8916 });
8917 self.select_previous(action, cx)?;
8918 }
8919 }
8920 Ok(())
8921 }
8922
8923 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8924 if self.read_only(cx) {
8925 return;
8926 }
8927 let text_layout_details = &self.text_layout_details(cx);
8928 self.transact(cx, |this, cx| {
8929 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8930 let mut edits = Vec::new();
8931 let mut selection_edit_ranges = Vec::new();
8932 let mut last_toggled_row = None;
8933 let snapshot = this.buffer.read(cx).read(cx);
8934 let empty_str: Arc<str> = Arc::default();
8935 let mut suffixes_inserted = Vec::new();
8936 let ignore_indent = action.ignore_indent;
8937
8938 fn comment_prefix_range(
8939 snapshot: &MultiBufferSnapshot,
8940 row: MultiBufferRow,
8941 comment_prefix: &str,
8942 comment_prefix_whitespace: &str,
8943 ignore_indent: bool,
8944 ) -> Range<Point> {
8945 let indent_size = if ignore_indent {
8946 0
8947 } else {
8948 snapshot.indent_size_for_line(row).len
8949 };
8950
8951 let start = Point::new(row.0, indent_size);
8952
8953 let mut line_bytes = snapshot
8954 .bytes_in_range(start..snapshot.max_point())
8955 .flatten()
8956 .copied();
8957
8958 // If this line currently begins with the line comment prefix, then record
8959 // the range containing the prefix.
8960 if line_bytes
8961 .by_ref()
8962 .take(comment_prefix.len())
8963 .eq(comment_prefix.bytes())
8964 {
8965 // Include any whitespace that matches the comment prefix.
8966 let matching_whitespace_len = line_bytes
8967 .zip(comment_prefix_whitespace.bytes())
8968 .take_while(|(a, b)| a == b)
8969 .count() as u32;
8970 let end = Point::new(
8971 start.row,
8972 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8973 );
8974 start..end
8975 } else {
8976 start..start
8977 }
8978 }
8979
8980 fn comment_suffix_range(
8981 snapshot: &MultiBufferSnapshot,
8982 row: MultiBufferRow,
8983 comment_suffix: &str,
8984 comment_suffix_has_leading_space: bool,
8985 ) -> Range<Point> {
8986 let end = Point::new(row.0, snapshot.line_len(row));
8987 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8988
8989 let mut line_end_bytes = snapshot
8990 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8991 .flatten()
8992 .copied();
8993
8994 let leading_space_len = if suffix_start_column > 0
8995 && line_end_bytes.next() == Some(b' ')
8996 && comment_suffix_has_leading_space
8997 {
8998 1
8999 } else {
9000 0
9001 };
9002
9003 // If this line currently begins with the line comment prefix, then record
9004 // the range containing the prefix.
9005 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9006 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9007 start..end
9008 } else {
9009 end..end
9010 }
9011 }
9012
9013 // TODO: Handle selections that cross excerpts
9014 for selection in &mut selections {
9015 let start_column = snapshot
9016 .indent_size_for_line(MultiBufferRow(selection.start.row))
9017 .len;
9018 let language = if let Some(language) =
9019 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9020 {
9021 language
9022 } else {
9023 continue;
9024 };
9025
9026 selection_edit_ranges.clear();
9027
9028 // If multiple selections contain a given row, avoid processing that
9029 // row more than once.
9030 let mut start_row = MultiBufferRow(selection.start.row);
9031 if last_toggled_row == Some(start_row) {
9032 start_row = start_row.next_row();
9033 }
9034 let end_row =
9035 if selection.end.row > selection.start.row && selection.end.column == 0 {
9036 MultiBufferRow(selection.end.row - 1)
9037 } else {
9038 MultiBufferRow(selection.end.row)
9039 };
9040 last_toggled_row = Some(end_row);
9041
9042 if start_row > end_row {
9043 continue;
9044 }
9045
9046 // If the language has line comments, toggle those.
9047 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9048
9049 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9050 if ignore_indent {
9051 full_comment_prefixes = full_comment_prefixes
9052 .into_iter()
9053 .map(|s| Arc::from(s.trim_end()))
9054 .collect();
9055 }
9056
9057 if !full_comment_prefixes.is_empty() {
9058 let first_prefix = full_comment_prefixes
9059 .first()
9060 .expect("prefixes is non-empty");
9061 let prefix_trimmed_lengths = full_comment_prefixes
9062 .iter()
9063 .map(|p| p.trim_end_matches(' ').len())
9064 .collect::<SmallVec<[usize; 4]>>();
9065
9066 let mut all_selection_lines_are_comments = true;
9067
9068 for row in start_row.0..=end_row.0 {
9069 let row = MultiBufferRow(row);
9070 if start_row < end_row && snapshot.is_line_blank(row) {
9071 continue;
9072 }
9073
9074 let prefix_range = full_comment_prefixes
9075 .iter()
9076 .zip(prefix_trimmed_lengths.iter().copied())
9077 .map(|(prefix, trimmed_prefix_len)| {
9078 comment_prefix_range(
9079 snapshot.deref(),
9080 row,
9081 &prefix[..trimmed_prefix_len],
9082 &prefix[trimmed_prefix_len..],
9083 ignore_indent,
9084 )
9085 })
9086 .max_by_key(|range| range.end.column - range.start.column)
9087 .expect("prefixes is non-empty");
9088
9089 if prefix_range.is_empty() {
9090 all_selection_lines_are_comments = false;
9091 }
9092
9093 selection_edit_ranges.push(prefix_range);
9094 }
9095
9096 if all_selection_lines_are_comments {
9097 edits.extend(
9098 selection_edit_ranges
9099 .iter()
9100 .cloned()
9101 .map(|range| (range, empty_str.clone())),
9102 );
9103 } else {
9104 let min_column = selection_edit_ranges
9105 .iter()
9106 .map(|range| range.start.column)
9107 .min()
9108 .unwrap_or(0);
9109 edits.extend(selection_edit_ranges.iter().map(|range| {
9110 let position = Point::new(range.start.row, min_column);
9111 (position..position, first_prefix.clone())
9112 }));
9113 }
9114 } else if let Some((full_comment_prefix, comment_suffix)) =
9115 language.block_comment_delimiters()
9116 {
9117 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9118 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9119 let prefix_range = comment_prefix_range(
9120 snapshot.deref(),
9121 start_row,
9122 comment_prefix,
9123 comment_prefix_whitespace,
9124 ignore_indent,
9125 );
9126 let suffix_range = comment_suffix_range(
9127 snapshot.deref(),
9128 end_row,
9129 comment_suffix.trim_start_matches(' '),
9130 comment_suffix.starts_with(' '),
9131 );
9132
9133 if prefix_range.is_empty() || suffix_range.is_empty() {
9134 edits.push((
9135 prefix_range.start..prefix_range.start,
9136 full_comment_prefix.clone(),
9137 ));
9138 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9139 suffixes_inserted.push((end_row, comment_suffix.len()));
9140 } else {
9141 edits.push((prefix_range, empty_str.clone()));
9142 edits.push((suffix_range, empty_str.clone()));
9143 }
9144 } else {
9145 continue;
9146 }
9147 }
9148
9149 drop(snapshot);
9150 this.buffer.update(cx, |buffer, cx| {
9151 buffer.edit(edits, None, cx);
9152 });
9153
9154 // Adjust selections so that they end before any comment suffixes that
9155 // were inserted.
9156 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9157 let mut selections = this.selections.all::<Point>(cx);
9158 let snapshot = this.buffer.read(cx).read(cx);
9159 for selection in &mut selections {
9160 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9161 match row.cmp(&MultiBufferRow(selection.end.row)) {
9162 Ordering::Less => {
9163 suffixes_inserted.next();
9164 continue;
9165 }
9166 Ordering::Greater => break,
9167 Ordering::Equal => {
9168 if selection.end.column == snapshot.line_len(row) {
9169 if selection.is_empty() {
9170 selection.start.column -= suffix_len as u32;
9171 }
9172 selection.end.column -= suffix_len as u32;
9173 }
9174 break;
9175 }
9176 }
9177 }
9178 }
9179
9180 drop(snapshot);
9181 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9182
9183 let selections = this.selections.all::<Point>(cx);
9184 let selections_on_single_row = selections.windows(2).all(|selections| {
9185 selections[0].start.row == selections[1].start.row
9186 && selections[0].end.row == selections[1].end.row
9187 && selections[0].start.row == selections[0].end.row
9188 });
9189 let selections_selecting = selections
9190 .iter()
9191 .any(|selection| selection.start != selection.end);
9192 let advance_downwards = action.advance_downwards
9193 && selections_on_single_row
9194 && !selections_selecting
9195 && !matches!(this.mode, EditorMode::SingleLine { .. });
9196
9197 if advance_downwards {
9198 let snapshot = this.buffer.read(cx).snapshot(cx);
9199
9200 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9201 s.move_cursors_with(|display_snapshot, display_point, _| {
9202 let mut point = display_point.to_point(display_snapshot);
9203 point.row += 1;
9204 point = snapshot.clip_point(point, Bias::Left);
9205 let display_point = point.to_display_point(display_snapshot);
9206 let goal = SelectionGoal::HorizontalPosition(
9207 display_snapshot
9208 .x_for_display_point(display_point, text_layout_details)
9209 .into(),
9210 );
9211 (display_point, goal)
9212 })
9213 });
9214 }
9215 });
9216 }
9217
9218 pub fn select_enclosing_symbol(
9219 &mut self,
9220 _: &SelectEnclosingSymbol,
9221 cx: &mut ViewContext<Self>,
9222 ) {
9223 let buffer = self.buffer.read(cx).snapshot(cx);
9224 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9225
9226 fn update_selection(
9227 selection: &Selection<usize>,
9228 buffer_snap: &MultiBufferSnapshot,
9229 ) -> Option<Selection<usize>> {
9230 let cursor = selection.head();
9231 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9232 for symbol in symbols.iter().rev() {
9233 let start = symbol.range.start.to_offset(buffer_snap);
9234 let end = symbol.range.end.to_offset(buffer_snap);
9235 let new_range = start..end;
9236 if start < selection.start || end > selection.end {
9237 return Some(Selection {
9238 id: selection.id,
9239 start: new_range.start,
9240 end: new_range.end,
9241 goal: SelectionGoal::None,
9242 reversed: selection.reversed,
9243 });
9244 }
9245 }
9246 None
9247 }
9248
9249 let mut selected_larger_symbol = false;
9250 let new_selections = old_selections
9251 .iter()
9252 .map(|selection| match update_selection(selection, &buffer) {
9253 Some(new_selection) => {
9254 if new_selection.range() != selection.range() {
9255 selected_larger_symbol = true;
9256 }
9257 new_selection
9258 }
9259 None => selection.clone(),
9260 })
9261 .collect::<Vec<_>>();
9262
9263 if selected_larger_symbol {
9264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9265 s.select(new_selections);
9266 });
9267 }
9268 }
9269
9270 pub fn select_larger_syntax_node(
9271 &mut self,
9272 _: &SelectLargerSyntaxNode,
9273 cx: &mut ViewContext<Self>,
9274 ) {
9275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9276 let buffer = self.buffer.read(cx).snapshot(cx);
9277 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9278
9279 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9280 let mut selected_larger_node = false;
9281 let new_selections = old_selections
9282 .iter()
9283 .map(|selection| {
9284 let old_range = selection.start..selection.end;
9285 let mut new_range = old_range.clone();
9286 while let Some(containing_range) =
9287 buffer.range_for_syntax_ancestor(new_range.clone())
9288 {
9289 new_range = containing_range;
9290 if !display_map.intersects_fold(new_range.start)
9291 && !display_map.intersects_fold(new_range.end)
9292 {
9293 break;
9294 }
9295 }
9296
9297 selected_larger_node |= new_range != old_range;
9298 Selection {
9299 id: selection.id,
9300 start: new_range.start,
9301 end: new_range.end,
9302 goal: SelectionGoal::None,
9303 reversed: selection.reversed,
9304 }
9305 })
9306 .collect::<Vec<_>>();
9307
9308 if selected_larger_node {
9309 stack.push(old_selections);
9310 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9311 s.select(new_selections);
9312 });
9313 }
9314 self.select_larger_syntax_node_stack = stack;
9315 }
9316
9317 pub fn select_smaller_syntax_node(
9318 &mut self,
9319 _: &SelectSmallerSyntaxNode,
9320 cx: &mut ViewContext<Self>,
9321 ) {
9322 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9323 if let Some(selections) = stack.pop() {
9324 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9325 s.select(selections.to_vec());
9326 });
9327 }
9328 self.select_larger_syntax_node_stack = stack;
9329 }
9330
9331 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9332 if !EditorSettings::get_global(cx).gutter.runnables {
9333 self.clear_tasks();
9334 return Task::ready(());
9335 }
9336 let project = self.project.as_ref().map(Model::downgrade);
9337 cx.spawn(|this, mut cx| async move {
9338 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9339 let Some(project) = project.and_then(|p| p.upgrade()) else {
9340 return;
9341 };
9342 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9343 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9344 }) else {
9345 return;
9346 };
9347
9348 let hide_runnables = project
9349 .update(&mut cx, |project, cx| {
9350 // Do not display any test indicators in non-dev server remote projects.
9351 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9352 })
9353 .unwrap_or(true);
9354 if hide_runnables {
9355 return;
9356 }
9357 let new_rows =
9358 cx.background_executor()
9359 .spawn({
9360 let snapshot = display_snapshot.clone();
9361 async move {
9362 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9363 }
9364 })
9365 .await;
9366 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9367
9368 this.update(&mut cx, |this, _| {
9369 this.clear_tasks();
9370 for (key, value) in rows {
9371 this.insert_tasks(key, value);
9372 }
9373 })
9374 .ok();
9375 })
9376 }
9377 fn fetch_runnable_ranges(
9378 snapshot: &DisplaySnapshot,
9379 range: Range<Anchor>,
9380 ) -> Vec<language::RunnableRange> {
9381 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9382 }
9383
9384 fn runnable_rows(
9385 project: Model<Project>,
9386 snapshot: DisplaySnapshot,
9387 runnable_ranges: Vec<RunnableRange>,
9388 mut cx: AsyncWindowContext,
9389 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9390 runnable_ranges
9391 .into_iter()
9392 .filter_map(|mut runnable| {
9393 let tasks = cx
9394 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9395 .ok()?;
9396 if tasks.is_empty() {
9397 return None;
9398 }
9399
9400 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9401
9402 let row = snapshot
9403 .buffer_snapshot
9404 .buffer_line_for_row(MultiBufferRow(point.row))?
9405 .1
9406 .start
9407 .row;
9408
9409 let context_range =
9410 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9411 Some((
9412 (runnable.buffer_id, row),
9413 RunnableTasks {
9414 templates: tasks,
9415 offset: MultiBufferOffset(runnable.run_range.start),
9416 context_range,
9417 column: point.column,
9418 extra_variables: runnable.extra_captures,
9419 },
9420 ))
9421 })
9422 .collect()
9423 }
9424
9425 fn templates_with_tags(
9426 project: &Model<Project>,
9427 runnable: &mut Runnable,
9428 cx: &WindowContext<'_>,
9429 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9430 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9431 let (worktree_id, file) = project
9432 .buffer_for_id(runnable.buffer, cx)
9433 .and_then(|buffer| buffer.read(cx).file())
9434 .map(|file| (file.worktree_id(cx), file.clone()))
9435 .unzip();
9436
9437 (
9438 project.task_store().read(cx).task_inventory().cloned(),
9439 worktree_id,
9440 file,
9441 )
9442 });
9443
9444 let tags = mem::take(&mut runnable.tags);
9445 let mut tags: Vec<_> = tags
9446 .into_iter()
9447 .flat_map(|tag| {
9448 let tag = tag.0.clone();
9449 inventory
9450 .as_ref()
9451 .into_iter()
9452 .flat_map(|inventory| {
9453 inventory.read(cx).list_tasks(
9454 file.clone(),
9455 Some(runnable.language.clone()),
9456 worktree_id,
9457 cx,
9458 )
9459 })
9460 .filter(move |(_, template)| {
9461 template.tags.iter().any(|source_tag| source_tag == &tag)
9462 })
9463 })
9464 .sorted_by_key(|(kind, _)| kind.to_owned())
9465 .collect();
9466 if let Some((leading_tag_source, _)) = tags.first() {
9467 // Strongest source wins; if we have worktree tag binding, prefer that to
9468 // global and language bindings;
9469 // if we have a global binding, prefer that to language binding.
9470 let first_mismatch = tags
9471 .iter()
9472 .position(|(tag_source, _)| tag_source != leading_tag_source);
9473 if let Some(index) = first_mismatch {
9474 tags.truncate(index);
9475 }
9476 }
9477
9478 tags
9479 }
9480
9481 pub fn move_to_enclosing_bracket(
9482 &mut self,
9483 _: &MoveToEnclosingBracket,
9484 cx: &mut ViewContext<Self>,
9485 ) {
9486 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9487 s.move_offsets_with(|snapshot, selection| {
9488 let Some(enclosing_bracket_ranges) =
9489 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9490 else {
9491 return;
9492 };
9493
9494 let mut best_length = usize::MAX;
9495 let mut best_inside = false;
9496 let mut best_in_bracket_range = false;
9497 let mut best_destination = None;
9498 for (open, close) in enclosing_bracket_ranges {
9499 let close = close.to_inclusive();
9500 let length = close.end() - open.start;
9501 let inside = selection.start >= open.end && selection.end <= *close.start();
9502 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9503 || close.contains(&selection.head());
9504
9505 // If best is next to a bracket and current isn't, skip
9506 if !in_bracket_range && best_in_bracket_range {
9507 continue;
9508 }
9509
9510 // Prefer smaller lengths unless best is inside and current isn't
9511 if length > best_length && (best_inside || !inside) {
9512 continue;
9513 }
9514
9515 best_length = length;
9516 best_inside = inside;
9517 best_in_bracket_range = in_bracket_range;
9518 best_destination = Some(
9519 if close.contains(&selection.start) && close.contains(&selection.end) {
9520 if inside {
9521 open.end
9522 } else {
9523 open.start
9524 }
9525 } else if inside {
9526 *close.start()
9527 } else {
9528 *close.end()
9529 },
9530 );
9531 }
9532
9533 if let Some(destination) = best_destination {
9534 selection.collapse_to(destination, SelectionGoal::None);
9535 }
9536 })
9537 });
9538 }
9539
9540 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9541 self.end_selection(cx);
9542 self.selection_history.mode = SelectionHistoryMode::Undoing;
9543 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9544 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9545 self.select_next_state = entry.select_next_state;
9546 self.select_prev_state = entry.select_prev_state;
9547 self.add_selections_state = entry.add_selections_state;
9548 self.request_autoscroll(Autoscroll::newest(), cx);
9549 }
9550 self.selection_history.mode = SelectionHistoryMode::Normal;
9551 }
9552
9553 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9554 self.end_selection(cx);
9555 self.selection_history.mode = SelectionHistoryMode::Redoing;
9556 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9557 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9558 self.select_next_state = entry.select_next_state;
9559 self.select_prev_state = entry.select_prev_state;
9560 self.add_selections_state = entry.add_selections_state;
9561 self.request_autoscroll(Autoscroll::newest(), cx);
9562 }
9563 self.selection_history.mode = SelectionHistoryMode::Normal;
9564 }
9565
9566 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9567 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9568 }
9569
9570 pub fn expand_excerpts_down(
9571 &mut self,
9572 action: &ExpandExcerptsDown,
9573 cx: &mut ViewContext<Self>,
9574 ) {
9575 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9576 }
9577
9578 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9579 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9580 }
9581
9582 pub fn expand_excerpts_for_direction(
9583 &mut self,
9584 lines: u32,
9585 direction: ExpandExcerptDirection,
9586 cx: &mut ViewContext<Self>,
9587 ) {
9588 let selections = self.selections.disjoint_anchors();
9589
9590 let lines = if lines == 0 {
9591 EditorSettings::get_global(cx).expand_excerpt_lines
9592 } else {
9593 lines
9594 };
9595
9596 self.buffer.update(cx, |buffer, cx| {
9597 buffer.expand_excerpts(
9598 selections
9599 .iter()
9600 .map(|selection| selection.head().excerpt_id)
9601 .dedup(),
9602 lines,
9603 direction,
9604 cx,
9605 )
9606 })
9607 }
9608
9609 pub fn expand_excerpt(
9610 &mut self,
9611 excerpt: ExcerptId,
9612 direction: ExpandExcerptDirection,
9613 cx: &mut ViewContext<Self>,
9614 ) {
9615 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9616 self.buffer.update(cx, |buffer, cx| {
9617 buffer.expand_excerpts([excerpt], lines, direction, cx)
9618 })
9619 }
9620
9621 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9622 self.go_to_diagnostic_impl(Direction::Next, cx)
9623 }
9624
9625 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9626 self.go_to_diagnostic_impl(Direction::Prev, cx)
9627 }
9628
9629 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9630 let buffer = self.buffer.read(cx).snapshot(cx);
9631 let selection = self.selections.newest::<usize>(cx);
9632
9633 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9634 if direction == Direction::Next {
9635 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9636 let (group_id, jump_to) = popover.activation_info();
9637 if self.activate_diagnostics(group_id, cx) {
9638 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9639 let mut new_selection = s.newest_anchor().clone();
9640 new_selection.collapse_to(jump_to, SelectionGoal::None);
9641 s.select_anchors(vec![new_selection.clone()]);
9642 });
9643 }
9644 return;
9645 }
9646 }
9647
9648 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9649 active_diagnostics
9650 .primary_range
9651 .to_offset(&buffer)
9652 .to_inclusive()
9653 });
9654 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9655 if active_primary_range.contains(&selection.head()) {
9656 *active_primary_range.start()
9657 } else {
9658 selection.head()
9659 }
9660 } else {
9661 selection.head()
9662 };
9663 let snapshot = self.snapshot(cx);
9664 loop {
9665 let diagnostics = if direction == Direction::Prev {
9666 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9667 } else {
9668 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9669 }
9670 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9671 let group = diagnostics
9672 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9673 // be sorted in a stable way
9674 // skip until we are at current active diagnostic, if it exists
9675 .skip_while(|entry| {
9676 (match direction {
9677 Direction::Prev => entry.range.start >= search_start,
9678 Direction::Next => entry.range.start <= search_start,
9679 }) && self
9680 .active_diagnostics
9681 .as_ref()
9682 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9683 })
9684 .find_map(|entry| {
9685 if entry.diagnostic.is_primary
9686 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9687 && !entry.range.is_empty()
9688 // if we match with the active diagnostic, skip it
9689 && Some(entry.diagnostic.group_id)
9690 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9691 {
9692 Some((entry.range, entry.diagnostic.group_id))
9693 } else {
9694 None
9695 }
9696 });
9697
9698 if let Some((primary_range, group_id)) = group {
9699 if self.activate_diagnostics(group_id, cx) {
9700 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9701 s.select(vec![Selection {
9702 id: selection.id,
9703 start: primary_range.start,
9704 end: primary_range.start,
9705 reversed: false,
9706 goal: SelectionGoal::None,
9707 }]);
9708 });
9709 }
9710 break;
9711 } else {
9712 // Cycle around to the start of the buffer, potentially moving back to the start of
9713 // the currently active diagnostic.
9714 active_primary_range.take();
9715 if direction == Direction::Prev {
9716 if search_start == buffer.len() {
9717 break;
9718 } else {
9719 search_start = buffer.len();
9720 }
9721 } else if search_start == 0 {
9722 break;
9723 } else {
9724 search_start = 0;
9725 }
9726 }
9727 }
9728 }
9729
9730 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9731 let snapshot = self
9732 .display_map
9733 .update(cx, |display_map, cx| display_map.snapshot(cx));
9734 let selection = self.selections.newest::<Point>(cx);
9735 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9736 }
9737
9738 fn go_to_hunk_after_position(
9739 &mut self,
9740 snapshot: &DisplaySnapshot,
9741 position: Point,
9742 cx: &mut ViewContext<'_, Editor>,
9743 ) -> Option<MultiBufferDiffHunk> {
9744 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9745 snapshot,
9746 position,
9747 false,
9748 snapshot
9749 .buffer_snapshot
9750 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9751 cx,
9752 ) {
9753 return Some(hunk);
9754 }
9755
9756 let wrapped_point = Point::zero();
9757 self.go_to_next_hunk_in_direction(
9758 snapshot,
9759 wrapped_point,
9760 true,
9761 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9762 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9763 ),
9764 cx,
9765 )
9766 }
9767
9768 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9769 let snapshot = self
9770 .display_map
9771 .update(cx, |display_map, cx| display_map.snapshot(cx));
9772 let selection = self.selections.newest::<Point>(cx);
9773
9774 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9775 }
9776
9777 fn go_to_hunk_before_position(
9778 &mut self,
9779 snapshot: &DisplaySnapshot,
9780 position: Point,
9781 cx: &mut ViewContext<'_, Editor>,
9782 ) -> Option<MultiBufferDiffHunk> {
9783 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9784 snapshot,
9785 position,
9786 false,
9787 snapshot
9788 .buffer_snapshot
9789 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9790 cx,
9791 ) {
9792 return Some(hunk);
9793 }
9794
9795 let wrapped_point = snapshot.buffer_snapshot.max_point();
9796 self.go_to_next_hunk_in_direction(
9797 snapshot,
9798 wrapped_point,
9799 true,
9800 snapshot
9801 .buffer_snapshot
9802 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9803 cx,
9804 )
9805 }
9806
9807 fn go_to_next_hunk_in_direction(
9808 &mut self,
9809 snapshot: &DisplaySnapshot,
9810 initial_point: Point,
9811 is_wrapped: bool,
9812 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9813 cx: &mut ViewContext<Editor>,
9814 ) -> Option<MultiBufferDiffHunk> {
9815 let display_point = initial_point.to_display_point(snapshot);
9816 let mut hunks = hunks
9817 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9818 .filter(|(display_hunk, _)| {
9819 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9820 })
9821 .dedup();
9822
9823 if let Some((display_hunk, hunk)) = hunks.next() {
9824 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9825 let row = display_hunk.start_display_row();
9826 let point = DisplayPoint::new(row, 0);
9827 s.select_display_ranges([point..point]);
9828 });
9829
9830 Some(hunk)
9831 } else {
9832 None
9833 }
9834 }
9835
9836 pub fn go_to_definition(
9837 &mut self,
9838 _: &GoToDefinition,
9839 cx: &mut ViewContext<Self>,
9840 ) -> Task<Result<Navigated>> {
9841 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9842 cx.spawn(|editor, mut cx| async move {
9843 if definition.await? == Navigated::Yes {
9844 return Ok(Navigated::Yes);
9845 }
9846 match editor.update(&mut cx, |editor, cx| {
9847 editor.find_all_references(&FindAllReferences, cx)
9848 })? {
9849 Some(references) => references.await,
9850 None => Ok(Navigated::No),
9851 }
9852 })
9853 }
9854
9855 pub fn go_to_declaration(
9856 &mut self,
9857 _: &GoToDeclaration,
9858 cx: &mut ViewContext<Self>,
9859 ) -> Task<Result<Navigated>> {
9860 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9861 }
9862
9863 pub fn go_to_declaration_split(
9864 &mut self,
9865 _: &GoToDeclaration,
9866 cx: &mut ViewContext<Self>,
9867 ) -> Task<Result<Navigated>> {
9868 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9869 }
9870
9871 pub fn go_to_implementation(
9872 &mut self,
9873 _: &GoToImplementation,
9874 cx: &mut ViewContext<Self>,
9875 ) -> Task<Result<Navigated>> {
9876 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9877 }
9878
9879 pub fn go_to_implementation_split(
9880 &mut self,
9881 _: &GoToImplementationSplit,
9882 cx: &mut ViewContext<Self>,
9883 ) -> Task<Result<Navigated>> {
9884 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9885 }
9886
9887 pub fn go_to_type_definition(
9888 &mut self,
9889 _: &GoToTypeDefinition,
9890 cx: &mut ViewContext<Self>,
9891 ) -> Task<Result<Navigated>> {
9892 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9893 }
9894
9895 pub fn go_to_definition_split(
9896 &mut self,
9897 _: &GoToDefinitionSplit,
9898 cx: &mut ViewContext<Self>,
9899 ) -> Task<Result<Navigated>> {
9900 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9901 }
9902
9903 pub fn go_to_type_definition_split(
9904 &mut self,
9905 _: &GoToTypeDefinitionSplit,
9906 cx: &mut ViewContext<Self>,
9907 ) -> Task<Result<Navigated>> {
9908 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9909 }
9910
9911 fn go_to_definition_of_kind(
9912 &mut self,
9913 kind: GotoDefinitionKind,
9914 split: bool,
9915 cx: &mut ViewContext<Self>,
9916 ) -> Task<Result<Navigated>> {
9917 let Some(provider) = self.semantics_provider.clone() else {
9918 return Task::ready(Ok(Navigated::No));
9919 };
9920 let head = self.selections.newest::<usize>(cx).head();
9921 let buffer = self.buffer.read(cx);
9922 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9923 text_anchor
9924 } else {
9925 return Task::ready(Ok(Navigated::No));
9926 };
9927
9928 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9929 return Task::ready(Ok(Navigated::No));
9930 };
9931
9932 cx.spawn(|editor, mut cx| async move {
9933 let definitions = definitions.await?;
9934 let navigated = editor
9935 .update(&mut cx, |editor, cx| {
9936 editor.navigate_to_hover_links(
9937 Some(kind),
9938 definitions
9939 .into_iter()
9940 .filter(|location| {
9941 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9942 })
9943 .map(HoverLink::Text)
9944 .collect::<Vec<_>>(),
9945 split,
9946 cx,
9947 )
9948 })?
9949 .await?;
9950 anyhow::Ok(navigated)
9951 })
9952 }
9953
9954 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9955 let position = self.selections.newest_anchor().head();
9956 let Some((buffer, buffer_position)) =
9957 self.buffer.read(cx).text_anchor_for_position(position, cx)
9958 else {
9959 return;
9960 };
9961
9962 cx.spawn(|editor, mut cx| async move {
9963 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9964 editor.update(&mut cx, |_, cx| {
9965 cx.open_url(&url);
9966 })
9967 } else {
9968 Ok(())
9969 }
9970 })
9971 .detach();
9972 }
9973
9974 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9975 let Some(workspace) = self.workspace() else {
9976 return;
9977 };
9978
9979 let position = self.selections.newest_anchor().head();
9980
9981 let Some((buffer, buffer_position)) =
9982 self.buffer.read(cx).text_anchor_for_position(position, cx)
9983 else {
9984 return;
9985 };
9986
9987 let project = self.project.clone();
9988
9989 cx.spawn(|_, mut cx| async move {
9990 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9991
9992 if let Some((_, path)) = result {
9993 workspace
9994 .update(&mut cx, |workspace, cx| {
9995 workspace.open_resolved_path(path, cx)
9996 })?
9997 .await?;
9998 }
9999 anyhow::Ok(())
10000 })
10001 .detach();
10002 }
10003
10004 pub(crate) fn navigate_to_hover_links(
10005 &mut self,
10006 kind: Option<GotoDefinitionKind>,
10007 mut definitions: Vec<HoverLink>,
10008 split: bool,
10009 cx: &mut ViewContext<Editor>,
10010 ) -> Task<Result<Navigated>> {
10011 // If there is one definition, just open it directly
10012 if definitions.len() == 1 {
10013 let definition = definitions.pop().unwrap();
10014
10015 enum TargetTaskResult {
10016 Location(Option<Location>),
10017 AlreadyNavigated,
10018 }
10019
10020 let target_task = match definition {
10021 HoverLink::Text(link) => {
10022 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10023 }
10024 HoverLink::InlayHint(lsp_location, server_id) => {
10025 let computation = self.compute_target_location(lsp_location, server_id, cx);
10026 cx.background_executor().spawn(async move {
10027 let location = computation.await?;
10028 Ok(TargetTaskResult::Location(location))
10029 })
10030 }
10031 HoverLink::Url(url) => {
10032 cx.open_url(&url);
10033 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10034 }
10035 HoverLink::File(path) => {
10036 if let Some(workspace) = self.workspace() {
10037 cx.spawn(|_, mut cx| async move {
10038 workspace
10039 .update(&mut cx, |workspace, cx| {
10040 workspace.open_resolved_path(path, cx)
10041 })?
10042 .await
10043 .map(|_| TargetTaskResult::AlreadyNavigated)
10044 })
10045 } else {
10046 Task::ready(Ok(TargetTaskResult::Location(None)))
10047 }
10048 }
10049 };
10050 cx.spawn(|editor, mut cx| async move {
10051 let target = match target_task.await.context("target resolution task")? {
10052 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10053 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10054 TargetTaskResult::Location(Some(target)) => target,
10055 };
10056
10057 editor.update(&mut cx, |editor, cx| {
10058 let Some(workspace) = editor.workspace() else {
10059 return Navigated::No;
10060 };
10061 let pane = workspace.read(cx).active_pane().clone();
10062
10063 let range = target.range.to_offset(target.buffer.read(cx));
10064 let range = editor.range_for_match(&range);
10065
10066 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10067 let buffer = target.buffer.read(cx);
10068 let range = check_multiline_range(buffer, range);
10069 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10070 s.select_ranges([range]);
10071 });
10072 } else {
10073 cx.window_context().defer(move |cx| {
10074 let target_editor: View<Self> =
10075 workspace.update(cx, |workspace, cx| {
10076 let pane = if split {
10077 workspace.adjacent_pane(cx)
10078 } else {
10079 workspace.active_pane().clone()
10080 };
10081
10082 workspace.open_project_item(
10083 pane,
10084 target.buffer.clone(),
10085 true,
10086 true,
10087 cx,
10088 )
10089 });
10090 target_editor.update(cx, |target_editor, cx| {
10091 // When selecting a definition in a different buffer, disable the nav history
10092 // to avoid creating a history entry at the previous cursor location.
10093 pane.update(cx, |pane, _| pane.disable_history());
10094 let buffer = target.buffer.read(cx);
10095 let range = check_multiline_range(buffer, range);
10096 target_editor.change_selections(
10097 Some(Autoscroll::focused()),
10098 cx,
10099 |s| {
10100 s.select_ranges([range]);
10101 },
10102 );
10103 pane.update(cx, |pane, _| pane.enable_history());
10104 });
10105 });
10106 }
10107 Navigated::Yes
10108 })
10109 })
10110 } else if !definitions.is_empty() {
10111 cx.spawn(|editor, mut cx| async move {
10112 let (title, location_tasks, workspace) = editor
10113 .update(&mut cx, |editor, cx| {
10114 let tab_kind = match kind {
10115 Some(GotoDefinitionKind::Implementation) => "Implementations",
10116 _ => "Definitions",
10117 };
10118 let title = definitions
10119 .iter()
10120 .find_map(|definition| match definition {
10121 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10122 let buffer = origin.buffer.read(cx);
10123 format!(
10124 "{} for {}",
10125 tab_kind,
10126 buffer
10127 .text_for_range(origin.range.clone())
10128 .collect::<String>()
10129 )
10130 }),
10131 HoverLink::InlayHint(_, _) => None,
10132 HoverLink::Url(_) => None,
10133 HoverLink::File(_) => None,
10134 })
10135 .unwrap_or(tab_kind.to_string());
10136 let location_tasks = definitions
10137 .into_iter()
10138 .map(|definition| match definition {
10139 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10140 HoverLink::InlayHint(lsp_location, server_id) => {
10141 editor.compute_target_location(lsp_location, server_id, cx)
10142 }
10143 HoverLink::Url(_) => Task::ready(Ok(None)),
10144 HoverLink::File(_) => Task::ready(Ok(None)),
10145 })
10146 .collect::<Vec<_>>();
10147 (title, location_tasks, editor.workspace().clone())
10148 })
10149 .context("location tasks preparation")?;
10150
10151 let locations = future::join_all(location_tasks)
10152 .await
10153 .into_iter()
10154 .filter_map(|location| location.transpose())
10155 .collect::<Result<_>>()
10156 .context("location tasks")?;
10157
10158 let Some(workspace) = workspace else {
10159 return Ok(Navigated::No);
10160 };
10161 let opened = workspace
10162 .update(&mut cx, |workspace, cx| {
10163 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10164 })
10165 .ok();
10166
10167 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10168 })
10169 } else {
10170 Task::ready(Ok(Navigated::No))
10171 }
10172 }
10173
10174 fn compute_target_location(
10175 &self,
10176 lsp_location: lsp::Location,
10177 server_id: LanguageServerId,
10178 cx: &mut ViewContext<Self>,
10179 ) -> Task<anyhow::Result<Option<Location>>> {
10180 let Some(project) = self.project.clone() else {
10181 return Task::Ready(Some(Ok(None)));
10182 };
10183
10184 cx.spawn(move |editor, mut cx| async move {
10185 let location_task = editor.update(&mut cx, |_, cx| {
10186 project.update(cx, |project, cx| {
10187 let language_server_name = project
10188 .language_server_statuses(cx)
10189 .find(|(id, _)| server_id == *id)
10190 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10191 language_server_name.map(|language_server_name| {
10192 project.open_local_buffer_via_lsp(
10193 lsp_location.uri.clone(),
10194 server_id,
10195 language_server_name,
10196 cx,
10197 )
10198 })
10199 })
10200 })?;
10201 let location = match location_task {
10202 Some(task) => Some({
10203 let target_buffer_handle = task.await.context("open local buffer")?;
10204 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10205 let target_start = target_buffer
10206 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10207 let target_end = target_buffer
10208 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10209 target_buffer.anchor_after(target_start)
10210 ..target_buffer.anchor_before(target_end)
10211 })?;
10212 Location {
10213 buffer: target_buffer_handle,
10214 range,
10215 }
10216 }),
10217 None => None,
10218 };
10219 Ok(location)
10220 })
10221 }
10222
10223 pub fn find_all_references(
10224 &mut self,
10225 _: &FindAllReferences,
10226 cx: &mut ViewContext<Self>,
10227 ) -> Option<Task<Result<Navigated>>> {
10228 let selection = self.selections.newest::<usize>(cx);
10229 let multi_buffer = self.buffer.read(cx);
10230 let head = selection.head();
10231
10232 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10233 let head_anchor = multi_buffer_snapshot.anchor_at(
10234 head,
10235 if head < selection.tail() {
10236 Bias::Right
10237 } else {
10238 Bias::Left
10239 },
10240 );
10241
10242 match self
10243 .find_all_references_task_sources
10244 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10245 {
10246 Ok(_) => {
10247 log::info!(
10248 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10249 );
10250 return None;
10251 }
10252 Err(i) => {
10253 self.find_all_references_task_sources.insert(i, head_anchor);
10254 }
10255 }
10256
10257 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10258 let workspace = self.workspace()?;
10259 let project = workspace.read(cx).project().clone();
10260 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10261 Some(cx.spawn(|editor, mut cx| async move {
10262 let _cleanup = defer({
10263 let mut cx = cx.clone();
10264 move || {
10265 let _ = editor.update(&mut cx, |editor, _| {
10266 if let Ok(i) =
10267 editor
10268 .find_all_references_task_sources
10269 .binary_search_by(|anchor| {
10270 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10271 })
10272 {
10273 editor.find_all_references_task_sources.remove(i);
10274 }
10275 });
10276 }
10277 });
10278
10279 let locations = references.await?;
10280 if locations.is_empty() {
10281 return anyhow::Ok(Navigated::No);
10282 }
10283
10284 workspace.update(&mut cx, |workspace, cx| {
10285 let title = locations
10286 .first()
10287 .as_ref()
10288 .map(|location| {
10289 let buffer = location.buffer.read(cx);
10290 format!(
10291 "References to `{}`",
10292 buffer
10293 .text_for_range(location.range.clone())
10294 .collect::<String>()
10295 )
10296 })
10297 .unwrap();
10298 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10299 Navigated::Yes
10300 })
10301 }))
10302 }
10303
10304 /// Opens a multibuffer with the given project locations in it
10305 pub fn open_locations_in_multibuffer(
10306 workspace: &mut Workspace,
10307 mut locations: Vec<Location>,
10308 title: String,
10309 split: bool,
10310 cx: &mut ViewContext<Workspace>,
10311 ) {
10312 // If there are multiple definitions, open them in a multibuffer
10313 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10314 let mut locations = locations.into_iter().peekable();
10315 let mut ranges_to_highlight = Vec::new();
10316 let capability = workspace.project().read(cx).capability();
10317
10318 let excerpt_buffer = cx.new_model(|cx| {
10319 let mut multibuffer = MultiBuffer::new(capability);
10320 while let Some(location) = locations.next() {
10321 let buffer = location.buffer.read(cx);
10322 let mut ranges_for_buffer = Vec::new();
10323 let range = location.range.to_offset(buffer);
10324 ranges_for_buffer.push(range.clone());
10325
10326 while let Some(next_location) = locations.peek() {
10327 if next_location.buffer == location.buffer {
10328 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10329 locations.next();
10330 } else {
10331 break;
10332 }
10333 }
10334
10335 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10336 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10337 location.buffer.clone(),
10338 ranges_for_buffer,
10339 DEFAULT_MULTIBUFFER_CONTEXT,
10340 cx,
10341 ))
10342 }
10343
10344 multibuffer.with_title(title)
10345 });
10346
10347 let editor = cx.new_view(|cx| {
10348 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10349 });
10350 editor.update(cx, |editor, cx| {
10351 if let Some(first_range) = ranges_to_highlight.first() {
10352 editor.change_selections(None, cx, |selections| {
10353 selections.clear_disjoint();
10354 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10355 });
10356 }
10357 editor.highlight_background::<Self>(
10358 &ranges_to_highlight,
10359 |theme| theme.editor_highlighted_line_background,
10360 cx,
10361 );
10362 });
10363
10364 let item = Box::new(editor);
10365 let item_id = item.item_id();
10366
10367 if split {
10368 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10369 } else {
10370 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10371 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10372 pane.close_current_preview_item(cx)
10373 } else {
10374 None
10375 }
10376 });
10377 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10378 }
10379 workspace.active_pane().update(cx, |pane, cx| {
10380 pane.set_preview_item_id(Some(item_id), cx);
10381 });
10382 }
10383
10384 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10385 use language::ToOffset as _;
10386
10387 let provider = self.semantics_provider.clone()?;
10388 let selection = self.selections.newest_anchor().clone();
10389 let (cursor_buffer, cursor_buffer_position) = self
10390 .buffer
10391 .read(cx)
10392 .text_anchor_for_position(selection.head(), cx)?;
10393 let (tail_buffer, cursor_buffer_position_end) = self
10394 .buffer
10395 .read(cx)
10396 .text_anchor_for_position(selection.tail(), cx)?;
10397 if tail_buffer != cursor_buffer {
10398 return None;
10399 }
10400
10401 let snapshot = cursor_buffer.read(cx).snapshot();
10402 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10403 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10404 let prepare_rename = provider
10405 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10406 .unwrap_or_else(|| Task::ready(Ok(None)));
10407 drop(snapshot);
10408
10409 Some(cx.spawn(|this, mut cx| async move {
10410 let rename_range = if let Some(range) = prepare_rename.await? {
10411 Some(range)
10412 } else {
10413 this.update(&mut cx, |this, cx| {
10414 let buffer = this.buffer.read(cx).snapshot(cx);
10415 let mut buffer_highlights = this
10416 .document_highlights_for_position(selection.head(), &buffer)
10417 .filter(|highlight| {
10418 highlight.start.excerpt_id == selection.head().excerpt_id
10419 && highlight.end.excerpt_id == selection.head().excerpt_id
10420 });
10421 buffer_highlights
10422 .next()
10423 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10424 })?
10425 };
10426 if let Some(rename_range) = rename_range {
10427 this.update(&mut cx, |this, cx| {
10428 let snapshot = cursor_buffer.read(cx).snapshot();
10429 let rename_buffer_range = rename_range.to_offset(&snapshot);
10430 let cursor_offset_in_rename_range =
10431 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10432 let cursor_offset_in_rename_range_end =
10433 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10434
10435 this.take_rename(false, cx);
10436 let buffer = this.buffer.read(cx).read(cx);
10437 let cursor_offset = selection.head().to_offset(&buffer);
10438 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10439 let rename_end = rename_start + rename_buffer_range.len();
10440 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10441 let mut old_highlight_id = None;
10442 let old_name: Arc<str> = buffer
10443 .chunks(rename_start..rename_end, true)
10444 .map(|chunk| {
10445 if old_highlight_id.is_none() {
10446 old_highlight_id = chunk.syntax_highlight_id;
10447 }
10448 chunk.text
10449 })
10450 .collect::<String>()
10451 .into();
10452
10453 drop(buffer);
10454
10455 // Position the selection in the rename editor so that it matches the current selection.
10456 this.show_local_selections = false;
10457 let rename_editor = cx.new_view(|cx| {
10458 let mut editor = Editor::single_line(cx);
10459 editor.buffer.update(cx, |buffer, cx| {
10460 buffer.edit([(0..0, old_name.clone())], None, cx)
10461 });
10462 let rename_selection_range = match cursor_offset_in_rename_range
10463 .cmp(&cursor_offset_in_rename_range_end)
10464 {
10465 Ordering::Equal => {
10466 editor.select_all(&SelectAll, cx);
10467 return editor;
10468 }
10469 Ordering::Less => {
10470 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10471 }
10472 Ordering::Greater => {
10473 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10474 }
10475 };
10476 if rename_selection_range.end > old_name.len() {
10477 editor.select_all(&SelectAll, cx);
10478 } else {
10479 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10480 s.select_ranges([rename_selection_range]);
10481 });
10482 }
10483 editor
10484 });
10485 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10486 if e == &EditorEvent::Focused {
10487 cx.emit(EditorEvent::FocusedIn)
10488 }
10489 })
10490 .detach();
10491
10492 let write_highlights =
10493 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10494 let read_highlights =
10495 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10496 let ranges = write_highlights
10497 .iter()
10498 .flat_map(|(_, ranges)| ranges.iter())
10499 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10500 .cloned()
10501 .collect();
10502
10503 this.highlight_text::<Rename>(
10504 ranges,
10505 HighlightStyle {
10506 fade_out: Some(0.6),
10507 ..Default::default()
10508 },
10509 cx,
10510 );
10511 let rename_focus_handle = rename_editor.focus_handle(cx);
10512 cx.focus(&rename_focus_handle);
10513 let block_id = this.insert_blocks(
10514 [BlockProperties {
10515 style: BlockStyle::Flex,
10516 placement: BlockPlacement::Below(range.start),
10517 height: 1,
10518 render: Arc::new({
10519 let rename_editor = rename_editor.clone();
10520 move |cx: &mut BlockContext| {
10521 let mut text_style = cx.editor_style.text.clone();
10522 if let Some(highlight_style) = old_highlight_id
10523 .and_then(|h| h.style(&cx.editor_style.syntax))
10524 {
10525 text_style = text_style.highlight(highlight_style);
10526 }
10527 div()
10528 .block_mouse_down()
10529 .pl(cx.anchor_x)
10530 .child(EditorElement::new(
10531 &rename_editor,
10532 EditorStyle {
10533 background: cx.theme().system().transparent,
10534 local_player: cx.editor_style.local_player,
10535 text: text_style,
10536 scrollbar_width: cx.editor_style.scrollbar_width,
10537 syntax: cx.editor_style.syntax.clone(),
10538 status: cx.editor_style.status.clone(),
10539 inlay_hints_style: HighlightStyle {
10540 font_weight: Some(FontWeight::BOLD),
10541 ..make_inlay_hints_style(cx)
10542 },
10543 suggestions_style: HighlightStyle {
10544 color: Some(cx.theme().status().predictive),
10545 ..HighlightStyle::default()
10546 },
10547 ..EditorStyle::default()
10548 },
10549 ))
10550 .into_any_element()
10551 }
10552 }),
10553 priority: 0,
10554 }],
10555 Some(Autoscroll::fit()),
10556 cx,
10557 )[0];
10558 this.pending_rename = Some(RenameState {
10559 range,
10560 old_name,
10561 editor: rename_editor,
10562 block_id,
10563 });
10564 })?;
10565 }
10566
10567 Ok(())
10568 }))
10569 }
10570
10571 pub fn confirm_rename(
10572 &mut self,
10573 _: &ConfirmRename,
10574 cx: &mut ViewContext<Self>,
10575 ) -> Option<Task<Result<()>>> {
10576 let rename = self.take_rename(false, cx)?;
10577 let workspace = self.workspace()?.downgrade();
10578 let (buffer, start) = self
10579 .buffer
10580 .read(cx)
10581 .text_anchor_for_position(rename.range.start, cx)?;
10582 let (end_buffer, _) = self
10583 .buffer
10584 .read(cx)
10585 .text_anchor_for_position(rename.range.end, cx)?;
10586 if buffer != end_buffer {
10587 return None;
10588 }
10589
10590 let old_name = rename.old_name;
10591 let new_name = rename.editor.read(cx).text(cx);
10592
10593 let rename = self.semantics_provider.as_ref()?.perform_rename(
10594 &buffer,
10595 start,
10596 new_name.clone(),
10597 cx,
10598 )?;
10599
10600 Some(cx.spawn(|editor, mut cx| async move {
10601 let project_transaction = rename.await?;
10602 Self::open_project_transaction(
10603 &editor,
10604 workspace,
10605 project_transaction,
10606 format!("Rename: {} → {}", old_name, new_name),
10607 cx.clone(),
10608 )
10609 .await?;
10610
10611 editor.update(&mut cx, |editor, cx| {
10612 editor.refresh_document_highlights(cx);
10613 })?;
10614 Ok(())
10615 }))
10616 }
10617
10618 fn take_rename(
10619 &mut self,
10620 moving_cursor: bool,
10621 cx: &mut ViewContext<Self>,
10622 ) -> Option<RenameState> {
10623 let rename = self.pending_rename.take()?;
10624 if rename.editor.focus_handle(cx).is_focused(cx) {
10625 cx.focus(&self.focus_handle);
10626 }
10627
10628 self.remove_blocks(
10629 [rename.block_id].into_iter().collect(),
10630 Some(Autoscroll::fit()),
10631 cx,
10632 );
10633 self.clear_highlights::<Rename>(cx);
10634 self.show_local_selections = true;
10635
10636 if moving_cursor {
10637 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10638 editor.selections.newest::<usize>(cx).head()
10639 });
10640
10641 // Update the selection to match the position of the selection inside
10642 // the rename editor.
10643 let snapshot = self.buffer.read(cx).read(cx);
10644 let rename_range = rename.range.to_offset(&snapshot);
10645 let cursor_in_editor = snapshot
10646 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10647 .min(rename_range.end);
10648 drop(snapshot);
10649
10650 self.change_selections(None, cx, |s| {
10651 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10652 });
10653 } else {
10654 self.refresh_document_highlights(cx);
10655 }
10656
10657 Some(rename)
10658 }
10659
10660 pub fn pending_rename(&self) -> Option<&RenameState> {
10661 self.pending_rename.as_ref()
10662 }
10663
10664 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10665 let project = match &self.project {
10666 Some(project) => project.clone(),
10667 None => return None,
10668 };
10669
10670 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10671 }
10672
10673 fn format_selections(
10674 &mut self,
10675 _: &FormatSelections,
10676 cx: &mut ViewContext<Self>,
10677 ) -> Option<Task<Result<()>>> {
10678 let project = match &self.project {
10679 Some(project) => project.clone(),
10680 None => return None,
10681 };
10682
10683 let selections = self
10684 .selections
10685 .all_adjusted(cx)
10686 .into_iter()
10687 .filter(|s| !s.is_empty())
10688 .collect_vec();
10689
10690 Some(self.perform_format(
10691 project,
10692 FormatTrigger::Manual,
10693 FormatTarget::Ranges(selections),
10694 cx,
10695 ))
10696 }
10697
10698 fn perform_format(
10699 &mut self,
10700 project: Model<Project>,
10701 trigger: FormatTrigger,
10702 target: FormatTarget,
10703 cx: &mut ViewContext<Self>,
10704 ) -> Task<Result<()>> {
10705 let buffer = self.buffer().clone();
10706 let mut buffers = buffer.read(cx).all_buffers();
10707 if trigger == FormatTrigger::Save {
10708 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10709 }
10710
10711 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10712 let format = project.update(cx, |project, cx| {
10713 project.format(buffers, true, trigger, target, cx)
10714 });
10715
10716 cx.spawn(|_, mut cx| async move {
10717 let transaction = futures::select_biased! {
10718 () = timeout => {
10719 log::warn!("timed out waiting for formatting");
10720 None
10721 }
10722 transaction = format.log_err().fuse() => transaction,
10723 };
10724
10725 buffer
10726 .update(&mut cx, |buffer, cx| {
10727 if let Some(transaction) = transaction {
10728 if !buffer.is_singleton() {
10729 buffer.push_transaction(&transaction.0, cx);
10730 }
10731 }
10732
10733 cx.notify();
10734 })
10735 .ok();
10736
10737 Ok(())
10738 })
10739 }
10740
10741 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10742 if let Some(project) = self.project.clone() {
10743 self.buffer.update(cx, |multi_buffer, cx| {
10744 project.update(cx, |project, cx| {
10745 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10746 });
10747 })
10748 }
10749 }
10750
10751 fn cancel_language_server_work(
10752 &mut self,
10753 _: &actions::CancelLanguageServerWork,
10754 cx: &mut ViewContext<Self>,
10755 ) {
10756 if let Some(project) = self.project.clone() {
10757 self.buffer.update(cx, |multi_buffer, cx| {
10758 project.update(cx, |project, cx| {
10759 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10760 });
10761 })
10762 }
10763 }
10764
10765 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10766 cx.show_character_palette();
10767 }
10768
10769 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10770 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10771 let buffer = self.buffer.read(cx).snapshot(cx);
10772 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10773 let is_valid = buffer
10774 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10775 .any(|entry| {
10776 entry.diagnostic.is_primary
10777 && !entry.range.is_empty()
10778 && entry.range.start == primary_range_start
10779 && entry.diagnostic.message == active_diagnostics.primary_message
10780 });
10781
10782 if is_valid != active_diagnostics.is_valid {
10783 active_diagnostics.is_valid = is_valid;
10784 let mut new_styles = HashMap::default();
10785 for (block_id, diagnostic) in &active_diagnostics.blocks {
10786 new_styles.insert(
10787 *block_id,
10788 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10789 );
10790 }
10791 self.display_map.update(cx, |display_map, _cx| {
10792 display_map.replace_blocks(new_styles)
10793 });
10794 }
10795 }
10796 }
10797
10798 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10799 self.dismiss_diagnostics(cx);
10800 let snapshot = self.snapshot(cx);
10801 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10802 let buffer = self.buffer.read(cx).snapshot(cx);
10803
10804 let mut primary_range = None;
10805 let mut primary_message = None;
10806 let mut group_end = Point::zero();
10807 let diagnostic_group = buffer
10808 .diagnostic_group::<MultiBufferPoint>(group_id)
10809 .filter_map(|entry| {
10810 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10811 && (entry.range.start.row == entry.range.end.row
10812 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10813 {
10814 return None;
10815 }
10816 if entry.range.end > group_end {
10817 group_end = entry.range.end;
10818 }
10819 if entry.diagnostic.is_primary {
10820 primary_range = Some(entry.range.clone());
10821 primary_message = Some(entry.diagnostic.message.clone());
10822 }
10823 Some(entry)
10824 })
10825 .collect::<Vec<_>>();
10826 let primary_range = primary_range?;
10827 let primary_message = primary_message?;
10828 let primary_range =
10829 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10830
10831 let blocks = display_map
10832 .insert_blocks(
10833 diagnostic_group.iter().map(|entry| {
10834 let diagnostic = entry.diagnostic.clone();
10835 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10836 BlockProperties {
10837 style: BlockStyle::Fixed,
10838 placement: BlockPlacement::Below(
10839 buffer.anchor_after(entry.range.start),
10840 ),
10841 height: message_height,
10842 render: diagnostic_block_renderer(diagnostic, None, true, true),
10843 priority: 0,
10844 }
10845 }),
10846 cx,
10847 )
10848 .into_iter()
10849 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10850 .collect();
10851
10852 Some(ActiveDiagnosticGroup {
10853 primary_range,
10854 primary_message,
10855 group_id,
10856 blocks,
10857 is_valid: true,
10858 })
10859 });
10860 self.active_diagnostics.is_some()
10861 }
10862
10863 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10864 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10865 self.display_map.update(cx, |display_map, cx| {
10866 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10867 });
10868 cx.notify();
10869 }
10870 }
10871
10872 pub fn set_selections_from_remote(
10873 &mut self,
10874 selections: Vec<Selection<Anchor>>,
10875 pending_selection: Option<Selection<Anchor>>,
10876 cx: &mut ViewContext<Self>,
10877 ) {
10878 let old_cursor_position = self.selections.newest_anchor().head();
10879 self.selections.change_with(cx, |s| {
10880 s.select_anchors(selections);
10881 if let Some(pending_selection) = pending_selection {
10882 s.set_pending(pending_selection, SelectMode::Character);
10883 } else {
10884 s.clear_pending();
10885 }
10886 });
10887 self.selections_did_change(false, &old_cursor_position, true, cx);
10888 }
10889
10890 fn push_to_selection_history(&mut self) {
10891 self.selection_history.push(SelectionHistoryEntry {
10892 selections: self.selections.disjoint_anchors(),
10893 select_next_state: self.select_next_state.clone(),
10894 select_prev_state: self.select_prev_state.clone(),
10895 add_selections_state: self.add_selections_state.clone(),
10896 });
10897 }
10898
10899 pub fn transact(
10900 &mut self,
10901 cx: &mut ViewContext<Self>,
10902 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10903 ) -> Option<TransactionId> {
10904 self.start_transaction_at(Instant::now(), cx);
10905 update(self, cx);
10906 self.end_transaction_at(Instant::now(), cx)
10907 }
10908
10909 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10910 self.end_selection(cx);
10911 if let Some(tx_id) = self
10912 .buffer
10913 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10914 {
10915 self.selection_history
10916 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10917 cx.emit(EditorEvent::TransactionBegun {
10918 transaction_id: tx_id,
10919 })
10920 }
10921 }
10922
10923 fn end_transaction_at(
10924 &mut self,
10925 now: Instant,
10926 cx: &mut ViewContext<Self>,
10927 ) -> Option<TransactionId> {
10928 if let Some(transaction_id) = self
10929 .buffer
10930 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10931 {
10932 if let Some((_, end_selections)) =
10933 self.selection_history.transaction_mut(transaction_id)
10934 {
10935 *end_selections = Some(self.selections.disjoint_anchors());
10936 } else {
10937 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10938 }
10939
10940 cx.emit(EditorEvent::Edited { transaction_id });
10941 Some(transaction_id)
10942 } else {
10943 None
10944 }
10945 }
10946
10947 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10948 let selection = self.selections.newest::<Point>(cx);
10949
10950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10951 let range = if selection.is_empty() {
10952 let point = selection.head().to_display_point(&display_map);
10953 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10954 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10955 .to_point(&display_map);
10956 start..end
10957 } else {
10958 selection.range()
10959 };
10960 if display_map.folds_in_range(range).next().is_some() {
10961 self.unfold_lines(&Default::default(), cx)
10962 } else {
10963 self.fold(&Default::default(), cx)
10964 }
10965 }
10966
10967 pub fn toggle_fold_recursive(
10968 &mut self,
10969 _: &actions::ToggleFoldRecursive,
10970 cx: &mut ViewContext<Self>,
10971 ) {
10972 let selection = self.selections.newest::<Point>(cx);
10973
10974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10975 let range = if selection.is_empty() {
10976 let point = selection.head().to_display_point(&display_map);
10977 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10978 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10979 .to_point(&display_map);
10980 start..end
10981 } else {
10982 selection.range()
10983 };
10984 if display_map.folds_in_range(range).next().is_some() {
10985 self.unfold_recursive(&Default::default(), cx)
10986 } else {
10987 self.fold_recursive(&Default::default(), cx)
10988 }
10989 }
10990
10991 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10992 let mut to_fold = Vec::new();
10993 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10994 let selections = self.selections.all_adjusted(cx);
10995
10996 for selection in selections {
10997 let range = selection.range().sorted();
10998 let buffer_start_row = range.start.row;
10999
11000 if range.start.row != range.end.row {
11001 let mut found = false;
11002 let mut row = range.start.row;
11003 while row <= range.end.row {
11004 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11005 found = true;
11006 row = crease.range().end.row + 1;
11007 to_fold.push(crease);
11008 } else {
11009 row += 1
11010 }
11011 }
11012 if found {
11013 continue;
11014 }
11015 }
11016
11017 for row in (0..=range.start.row).rev() {
11018 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11019 if crease.range().end.row >= buffer_start_row {
11020 to_fold.push(crease);
11021 if row <= range.start.row {
11022 break;
11023 }
11024 }
11025 }
11026 }
11027 }
11028
11029 self.fold_creases(to_fold, true, cx);
11030 }
11031
11032 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11033 let fold_at_level = fold_at.level;
11034 let snapshot = self.buffer.read(cx).snapshot(cx);
11035 let mut to_fold = Vec::new();
11036 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11037
11038 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11039 while start_row < end_row {
11040 match self
11041 .snapshot(cx)
11042 .crease_for_buffer_row(MultiBufferRow(start_row))
11043 {
11044 Some(crease) => {
11045 let nested_start_row = crease.range().start.row + 1;
11046 let nested_end_row = crease.range().end.row;
11047
11048 if current_level < fold_at_level {
11049 stack.push((nested_start_row, nested_end_row, current_level + 1));
11050 } else if current_level == fold_at_level {
11051 to_fold.push(crease);
11052 }
11053
11054 start_row = nested_end_row + 1;
11055 }
11056 None => start_row += 1,
11057 }
11058 }
11059 }
11060
11061 self.fold_creases(to_fold, true, cx);
11062 }
11063
11064 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11065 let mut fold_ranges = Vec::new();
11066 let snapshot = self.buffer.read(cx).snapshot(cx);
11067
11068 for row in 0..snapshot.max_buffer_row().0 {
11069 if let Some(foldable_range) =
11070 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11071 {
11072 fold_ranges.push(foldable_range);
11073 }
11074 }
11075
11076 self.fold_creases(fold_ranges, true, cx);
11077 }
11078
11079 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11080 let mut to_fold = Vec::new();
11081 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11082 let selections = self.selections.all_adjusted(cx);
11083
11084 for selection in selections {
11085 let range = selection.range().sorted();
11086 let buffer_start_row = range.start.row;
11087
11088 if range.start.row != range.end.row {
11089 let mut found = false;
11090 for row in range.start.row..=range.end.row {
11091 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11092 found = true;
11093 to_fold.push(crease);
11094 }
11095 }
11096 if found {
11097 continue;
11098 }
11099 }
11100
11101 for row in (0..=range.start.row).rev() {
11102 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11103 if crease.range().end.row >= buffer_start_row {
11104 to_fold.push(crease);
11105 } else {
11106 break;
11107 }
11108 }
11109 }
11110 }
11111
11112 self.fold_creases(to_fold, true, cx);
11113 }
11114
11115 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11116 let buffer_row = fold_at.buffer_row;
11117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11118
11119 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11120 let autoscroll = self
11121 .selections
11122 .all::<Point>(cx)
11123 .iter()
11124 .any(|selection| crease.range().overlaps(&selection.range()));
11125
11126 self.fold_creases(vec![crease], autoscroll, cx);
11127 }
11128 }
11129
11130 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11131 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11132 let buffer = &display_map.buffer_snapshot;
11133 let selections = self.selections.all::<Point>(cx);
11134 let ranges = selections
11135 .iter()
11136 .map(|s| {
11137 let range = s.display_range(&display_map).sorted();
11138 let mut start = range.start.to_point(&display_map);
11139 let mut end = range.end.to_point(&display_map);
11140 start.column = 0;
11141 end.column = buffer.line_len(MultiBufferRow(end.row));
11142 start..end
11143 })
11144 .collect::<Vec<_>>();
11145
11146 self.unfold_ranges(&ranges, true, true, cx);
11147 }
11148
11149 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11151 let selections = self.selections.all::<Point>(cx);
11152 let ranges = selections
11153 .iter()
11154 .map(|s| {
11155 let mut range = s.display_range(&display_map).sorted();
11156 *range.start.column_mut() = 0;
11157 *range.end.column_mut() = display_map.line_len(range.end.row());
11158 let start = range.start.to_point(&display_map);
11159 let end = range.end.to_point(&display_map);
11160 start..end
11161 })
11162 .collect::<Vec<_>>();
11163
11164 self.unfold_ranges(&ranges, true, true, cx);
11165 }
11166
11167 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11168 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11169
11170 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11171 ..Point::new(
11172 unfold_at.buffer_row.0,
11173 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11174 );
11175
11176 let autoscroll = self
11177 .selections
11178 .all::<Point>(cx)
11179 .iter()
11180 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11181
11182 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11183 }
11184
11185 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11186 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11187 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11188 }
11189
11190 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11191 let selections = self.selections.all::<Point>(cx);
11192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11193 let line_mode = self.selections.line_mode;
11194 let ranges = selections
11195 .into_iter()
11196 .map(|s| {
11197 if line_mode {
11198 let start = Point::new(s.start.row, 0);
11199 let end = Point::new(
11200 s.end.row,
11201 display_map
11202 .buffer_snapshot
11203 .line_len(MultiBufferRow(s.end.row)),
11204 );
11205 Crease::simple(start..end, display_map.fold_placeholder.clone())
11206 } else {
11207 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11208 }
11209 })
11210 .collect::<Vec<_>>();
11211 self.fold_creases(ranges, true, cx);
11212 }
11213
11214 pub fn fold_creases<T: ToOffset + Clone>(
11215 &mut self,
11216 creases: Vec<Crease<T>>,
11217 auto_scroll: bool,
11218 cx: &mut ViewContext<Self>,
11219 ) {
11220 if creases.is_empty() {
11221 return;
11222 }
11223
11224 let mut buffers_affected = HashMap::default();
11225 let multi_buffer = self.buffer().read(cx);
11226 for crease in &creases {
11227 if let Some((_, buffer, _)) =
11228 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11229 {
11230 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11231 };
11232 }
11233
11234 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11235
11236 if auto_scroll {
11237 self.request_autoscroll(Autoscroll::fit(), cx);
11238 }
11239
11240 for buffer in buffers_affected.into_values() {
11241 self.sync_expanded_diff_hunks(buffer, cx);
11242 }
11243
11244 cx.notify();
11245
11246 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11247 // Clear diagnostics block when folding a range that contains it.
11248 let snapshot = self.snapshot(cx);
11249 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11250 drop(snapshot);
11251 self.active_diagnostics = Some(active_diagnostics);
11252 self.dismiss_diagnostics(cx);
11253 } else {
11254 self.active_diagnostics = Some(active_diagnostics);
11255 }
11256 }
11257
11258 self.scrollbar_marker_state.dirty = true;
11259 }
11260
11261 /// Removes any folds whose ranges intersect any of the given ranges.
11262 pub fn unfold_ranges<T: ToOffset + Clone>(
11263 &mut self,
11264 ranges: &[Range<T>],
11265 inclusive: bool,
11266 auto_scroll: bool,
11267 cx: &mut ViewContext<Self>,
11268 ) {
11269 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11270 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11271 });
11272 }
11273
11274 /// Removes any folds with the given ranges.
11275 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11276 &mut self,
11277 ranges: &[Range<T>],
11278 type_id: TypeId,
11279 auto_scroll: bool,
11280 cx: &mut ViewContext<Self>,
11281 ) {
11282 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11283 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11284 });
11285 }
11286
11287 fn remove_folds_with<T: ToOffset + Clone>(
11288 &mut self,
11289 ranges: &[Range<T>],
11290 auto_scroll: bool,
11291 cx: &mut ViewContext<Self>,
11292 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11293 ) {
11294 if ranges.is_empty() {
11295 return;
11296 }
11297
11298 let mut buffers_affected = HashMap::default();
11299 let multi_buffer = self.buffer().read(cx);
11300 for range in ranges {
11301 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11302 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11303 };
11304 }
11305
11306 self.display_map.update(cx, update);
11307
11308 if auto_scroll {
11309 self.request_autoscroll(Autoscroll::fit(), cx);
11310 }
11311
11312 for buffer in buffers_affected.into_values() {
11313 self.sync_expanded_diff_hunks(buffer, cx);
11314 }
11315
11316 cx.notify();
11317 self.scrollbar_marker_state.dirty = true;
11318 self.active_indent_guides_state.dirty = true;
11319 }
11320
11321 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11322 self.display_map.read(cx).fold_placeholder.clone()
11323 }
11324
11325 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11326 if hovered != self.gutter_hovered {
11327 self.gutter_hovered = hovered;
11328 cx.notify();
11329 }
11330 }
11331
11332 pub fn insert_blocks(
11333 &mut self,
11334 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11335 autoscroll: Option<Autoscroll>,
11336 cx: &mut ViewContext<Self>,
11337 ) -> Vec<CustomBlockId> {
11338 let blocks = self
11339 .display_map
11340 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11341 if let Some(autoscroll) = autoscroll {
11342 self.request_autoscroll(autoscroll, cx);
11343 }
11344 cx.notify();
11345 blocks
11346 }
11347
11348 pub fn resize_blocks(
11349 &mut self,
11350 heights: HashMap<CustomBlockId, u32>,
11351 autoscroll: Option<Autoscroll>,
11352 cx: &mut ViewContext<Self>,
11353 ) {
11354 self.display_map
11355 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11356 if let Some(autoscroll) = autoscroll {
11357 self.request_autoscroll(autoscroll, cx);
11358 }
11359 cx.notify();
11360 }
11361
11362 pub fn replace_blocks(
11363 &mut self,
11364 renderers: HashMap<CustomBlockId, RenderBlock>,
11365 autoscroll: Option<Autoscroll>,
11366 cx: &mut ViewContext<Self>,
11367 ) {
11368 self.display_map
11369 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11370 if let Some(autoscroll) = autoscroll {
11371 self.request_autoscroll(autoscroll, cx);
11372 }
11373 cx.notify();
11374 }
11375
11376 pub fn remove_blocks(
11377 &mut self,
11378 block_ids: HashSet<CustomBlockId>,
11379 autoscroll: Option<Autoscroll>,
11380 cx: &mut ViewContext<Self>,
11381 ) {
11382 self.display_map.update(cx, |display_map, cx| {
11383 display_map.remove_blocks(block_ids, cx)
11384 });
11385 if let Some(autoscroll) = autoscroll {
11386 self.request_autoscroll(autoscroll, cx);
11387 }
11388 cx.notify();
11389 }
11390
11391 pub fn row_for_block(
11392 &self,
11393 block_id: CustomBlockId,
11394 cx: &mut ViewContext<Self>,
11395 ) -> Option<DisplayRow> {
11396 self.display_map
11397 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11398 }
11399
11400 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11401 self.focused_block = Some(focused_block);
11402 }
11403
11404 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11405 self.focused_block.take()
11406 }
11407
11408 pub fn insert_creases(
11409 &mut self,
11410 creases: impl IntoIterator<Item = Crease<Anchor>>,
11411 cx: &mut ViewContext<Self>,
11412 ) -> Vec<CreaseId> {
11413 self.display_map
11414 .update(cx, |map, cx| map.insert_creases(creases, cx))
11415 }
11416
11417 pub fn remove_creases(
11418 &mut self,
11419 ids: impl IntoIterator<Item = CreaseId>,
11420 cx: &mut ViewContext<Self>,
11421 ) {
11422 self.display_map
11423 .update(cx, |map, cx| map.remove_creases(ids, cx));
11424 }
11425
11426 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11427 self.display_map
11428 .update(cx, |map, cx| map.snapshot(cx))
11429 .longest_row()
11430 }
11431
11432 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11433 self.display_map
11434 .update(cx, |map, cx| map.snapshot(cx))
11435 .max_point()
11436 }
11437
11438 pub fn text(&self, cx: &AppContext) -> String {
11439 self.buffer.read(cx).read(cx).text()
11440 }
11441
11442 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11443 let text = self.text(cx);
11444 let text = text.trim();
11445
11446 if text.is_empty() {
11447 return None;
11448 }
11449
11450 Some(text.to_string())
11451 }
11452
11453 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11454 self.transact(cx, |this, cx| {
11455 this.buffer
11456 .read(cx)
11457 .as_singleton()
11458 .expect("you can only call set_text on editors for singleton buffers")
11459 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11460 });
11461 }
11462
11463 pub fn display_text(&self, cx: &mut AppContext) -> String {
11464 self.display_map
11465 .update(cx, |map, cx| map.snapshot(cx))
11466 .text()
11467 }
11468
11469 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11470 let mut wrap_guides = smallvec::smallvec![];
11471
11472 if self.show_wrap_guides == Some(false) {
11473 return wrap_guides;
11474 }
11475
11476 let settings = self.buffer.read(cx).settings_at(0, cx);
11477 if settings.show_wrap_guides {
11478 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11479 wrap_guides.push((soft_wrap as usize, true));
11480 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11481 wrap_guides.push((soft_wrap as usize, true));
11482 }
11483 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11484 }
11485
11486 wrap_guides
11487 }
11488
11489 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11490 let settings = self.buffer.read(cx).settings_at(0, cx);
11491 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11492 match mode {
11493 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11494 SoftWrap::None
11495 }
11496 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11497 language_settings::SoftWrap::PreferredLineLength => {
11498 SoftWrap::Column(settings.preferred_line_length)
11499 }
11500 language_settings::SoftWrap::Bounded => {
11501 SoftWrap::Bounded(settings.preferred_line_length)
11502 }
11503 }
11504 }
11505
11506 pub fn set_soft_wrap_mode(
11507 &mut self,
11508 mode: language_settings::SoftWrap,
11509 cx: &mut ViewContext<Self>,
11510 ) {
11511 self.soft_wrap_mode_override = Some(mode);
11512 cx.notify();
11513 }
11514
11515 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11516 self.text_style_refinement = Some(style);
11517 }
11518
11519 /// called by the Element so we know what style we were most recently rendered with.
11520 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11521 let rem_size = cx.rem_size();
11522 self.display_map.update(cx, |map, cx| {
11523 map.set_font(
11524 style.text.font(),
11525 style.text.font_size.to_pixels(rem_size),
11526 cx,
11527 )
11528 });
11529 self.style = Some(style);
11530 }
11531
11532 pub fn style(&self) -> Option<&EditorStyle> {
11533 self.style.as_ref()
11534 }
11535
11536 // Called by the element. This method is not designed to be called outside of the editor
11537 // element's layout code because it does not notify when rewrapping is computed synchronously.
11538 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11539 self.display_map
11540 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11541 }
11542
11543 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11544 if self.soft_wrap_mode_override.is_some() {
11545 self.soft_wrap_mode_override.take();
11546 } else {
11547 let soft_wrap = match self.soft_wrap_mode(cx) {
11548 SoftWrap::GitDiff => return,
11549 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11550 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11551 language_settings::SoftWrap::None
11552 }
11553 };
11554 self.soft_wrap_mode_override = Some(soft_wrap);
11555 }
11556 cx.notify();
11557 }
11558
11559 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11560 let Some(workspace) = self.workspace() else {
11561 return;
11562 };
11563 let fs = workspace.read(cx).app_state().fs.clone();
11564 let current_show = TabBarSettings::get_global(cx).show;
11565 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11566 setting.show = Some(!current_show);
11567 });
11568 }
11569
11570 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11571 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11572 self.buffer
11573 .read(cx)
11574 .settings_at(0, cx)
11575 .indent_guides
11576 .enabled
11577 });
11578 self.show_indent_guides = Some(!currently_enabled);
11579 cx.notify();
11580 }
11581
11582 fn should_show_indent_guides(&self) -> Option<bool> {
11583 self.show_indent_guides
11584 }
11585
11586 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11587 let mut editor_settings = EditorSettings::get_global(cx).clone();
11588 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11589 EditorSettings::override_global(editor_settings, cx);
11590 }
11591
11592 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11593 self.use_relative_line_numbers
11594 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11595 }
11596
11597 pub fn toggle_relative_line_numbers(
11598 &mut self,
11599 _: &ToggleRelativeLineNumbers,
11600 cx: &mut ViewContext<Self>,
11601 ) {
11602 let is_relative = self.should_use_relative_line_numbers(cx);
11603 self.set_relative_line_number(Some(!is_relative), cx)
11604 }
11605
11606 pub fn set_relative_line_number(
11607 &mut self,
11608 is_relative: Option<bool>,
11609 cx: &mut ViewContext<Self>,
11610 ) {
11611 self.use_relative_line_numbers = is_relative;
11612 cx.notify();
11613 }
11614
11615 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11616 self.show_gutter = show_gutter;
11617 cx.notify();
11618 }
11619
11620 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11621 self.show_line_numbers = Some(show_line_numbers);
11622 cx.notify();
11623 }
11624
11625 pub fn set_show_git_diff_gutter(
11626 &mut self,
11627 show_git_diff_gutter: bool,
11628 cx: &mut ViewContext<Self>,
11629 ) {
11630 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11631 cx.notify();
11632 }
11633
11634 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11635 self.show_code_actions = Some(show_code_actions);
11636 cx.notify();
11637 }
11638
11639 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11640 self.show_runnables = Some(show_runnables);
11641 cx.notify();
11642 }
11643
11644 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11645 if self.display_map.read(cx).masked != masked {
11646 self.display_map.update(cx, |map, _| map.masked = masked);
11647 }
11648 cx.notify()
11649 }
11650
11651 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11652 self.show_wrap_guides = Some(show_wrap_guides);
11653 cx.notify();
11654 }
11655
11656 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11657 self.show_indent_guides = Some(show_indent_guides);
11658 cx.notify();
11659 }
11660
11661 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11662 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11663 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11664 if let Some(dir) = file.abs_path(cx).parent() {
11665 return Some(dir.to_owned());
11666 }
11667 }
11668
11669 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11670 return Some(project_path.path.to_path_buf());
11671 }
11672 }
11673
11674 None
11675 }
11676
11677 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11678 self.active_excerpt(cx)?
11679 .1
11680 .read(cx)
11681 .file()
11682 .and_then(|f| f.as_local())
11683 }
11684
11685 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11686 if let Some(target) = self.target_file(cx) {
11687 cx.reveal_path(&target.abs_path(cx));
11688 }
11689 }
11690
11691 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11692 if let Some(file) = self.target_file(cx) {
11693 if let Some(path) = file.abs_path(cx).to_str() {
11694 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11695 }
11696 }
11697 }
11698
11699 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11700 if let Some(file) = self.target_file(cx) {
11701 if let Some(path) = file.path().to_str() {
11702 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11703 }
11704 }
11705 }
11706
11707 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11708 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11709
11710 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11711 self.start_git_blame(true, cx);
11712 }
11713
11714 cx.notify();
11715 }
11716
11717 pub fn toggle_git_blame_inline(
11718 &mut self,
11719 _: &ToggleGitBlameInline,
11720 cx: &mut ViewContext<Self>,
11721 ) {
11722 self.toggle_git_blame_inline_internal(true, cx);
11723 cx.notify();
11724 }
11725
11726 pub fn git_blame_inline_enabled(&self) -> bool {
11727 self.git_blame_inline_enabled
11728 }
11729
11730 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11731 self.show_selection_menu = self
11732 .show_selection_menu
11733 .map(|show_selections_menu| !show_selections_menu)
11734 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11735
11736 cx.notify();
11737 }
11738
11739 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11740 self.show_selection_menu
11741 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11742 }
11743
11744 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11745 if let Some(project) = self.project.as_ref() {
11746 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11747 return;
11748 };
11749
11750 if buffer.read(cx).file().is_none() {
11751 return;
11752 }
11753
11754 let focused = self.focus_handle(cx).contains_focused(cx);
11755
11756 let project = project.clone();
11757 let blame =
11758 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11759 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11760 self.blame = Some(blame);
11761 }
11762 }
11763
11764 fn toggle_git_blame_inline_internal(
11765 &mut self,
11766 user_triggered: bool,
11767 cx: &mut ViewContext<Self>,
11768 ) {
11769 if self.git_blame_inline_enabled {
11770 self.git_blame_inline_enabled = false;
11771 self.show_git_blame_inline = false;
11772 self.show_git_blame_inline_delay_task.take();
11773 } else {
11774 self.git_blame_inline_enabled = true;
11775 self.start_git_blame_inline(user_triggered, cx);
11776 }
11777
11778 cx.notify();
11779 }
11780
11781 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11782 self.start_git_blame(user_triggered, cx);
11783
11784 if ProjectSettings::get_global(cx)
11785 .git
11786 .inline_blame_delay()
11787 .is_some()
11788 {
11789 self.start_inline_blame_timer(cx);
11790 } else {
11791 self.show_git_blame_inline = true
11792 }
11793 }
11794
11795 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11796 self.blame.as_ref()
11797 }
11798
11799 pub fn show_git_blame_gutter(&self) -> bool {
11800 self.show_git_blame_gutter
11801 }
11802
11803 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11804 self.show_git_blame_gutter && self.has_blame_entries(cx)
11805 }
11806
11807 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11808 self.show_git_blame_inline
11809 && self.focus_handle.is_focused(cx)
11810 && !self.newest_selection_head_on_empty_line(cx)
11811 && self.has_blame_entries(cx)
11812 }
11813
11814 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11815 self.blame()
11816 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11817 }
11818
11819 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11820 let cursor_anchor = self.selections.newest_anchor().head();
11821
11822 let snapshot = self.buffer.read(cx).snapshot(cx);
11823 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11824
11825 snapshot.line_len(buffer_row) == 0
11826 }
11827
11828 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11829 let buffer_and_selection = maybe!({
11830 let selection = self.selections.newest::<Point>(cx);
11831 let selection_range = selection.range();
11832
11833 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11834 (buffer, selection_range.start.row..selection_range.end.row)
11835 } else {
11836 let buffer_ranges = self
11837 .buffer()
11838 .read(cx)
11839 .range_to_buffer_ranges(selection_range, cx);
11840
11841 let (buffer, range, _) = if selection.reversed {
11842 buffer_ranges.first()
11843 } else {
11844 buffer_ranges.last()
11845 }?;
11846
11847 let snapshot = buffer.read(cx).snapshot();
11848 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11849 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11850 (buffer.clone(), selection)
11851 };
11852
11853 Some((buffer, selection))
11854 });
11855
11856 let Some((buffer, selection)) = buffer_and_selection else {
11857 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11858 };
11859
11860 let Some(project) = self.project.as_ref() else {
11861 return Task::ready(Err(anyhow!("editor does not have project")));
11862 };
11863
11864 project.update(cx, |project, cx| {
11865 project.get_permalink_to_line(&buffer, selection, cx)
11866 })
11867 }
11868
11869 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11870 let permalink_task = self.get_permalink_to_line(cx);
11871 let workspace = self.workspace();
11872
11873 cx.spawn(|_, mut cx| async move {
11874 match permalink_task.await {
11875 Ok(permalink) => {
11876 cx.update(|cx| {
11877 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11878 })
11879 .ok();
11880 }
11881 Err(err) => {
11882 let message = format!("Failed to copy permalink: {err}");
11883
11884 Err::<(), anyhow::Error>(err).log_err();
11885
11886 if let Some(workspace) = workspace {
11887 workspace
11888 .update(&mut cx, |workspace, cx| {
11889 struct CopyPermalinkToLine;
11890
11891 workspace.show_toast(
11892 Toast::new(
11893 NotificationId::unique::<CopyPermalinkToLine>(),
11894 message,
11895 ),
11896 cx,
11897 )
11898 })
11899 .ok();
11900 }
11901 }
11902 }
11903 })
11904 .detach();
11905 }
11906
11907 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11908 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11909 if let Some(file) = self.target_file(cx) {
11910 if let Some(path) = file.path().to_str() {
11911 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11912 }
11913 }
11914 }
11915
11916 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11917 let permalink_task = self.get_permalink_to_line(cx);
11918 let workspace = self.workspace();
11919
11920 cx.spawn(|_, mut cx| async move {
11921 match permalink_task.await {
11922 Ok(permalink) => {
11923 cx.update(|cx| {
11924 cx.open_url(permalink.as_ref());
11925 })
11926 .ok();
11927 }
11928 Err(err) => {
11929 let message = format!("Failed to open permalink: {err}");
11930
11931 Err::<(), anyhow::Error>(err).log_err();
11932
11933 if let Some(workspace) = workspace {
11934 workspace
11935 .update(&mut cx, |workspace, cx| {
11936 struct OpenPermalinkToLine;
11937
11938 workspace.show_toast(
11939 Toast::new(
11940 NotificationId::unique::<OpenPermalinkToLine>(),
11941 message,
11942 ),
11943 cx,
11944 )
11945 })
11946 .ok();
11947 }
11948 }
11949 }
11950 })
11951 .detach();
11952 }
11953
11954 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11955 /// last highlight added will be used.
11956 ///
11957 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11958 pub fn highlight_rows<T: 'static>(
11959 &mut self,
11960 range: Range<Anchor>,
11961 color: Hsla,
11962 should_autoscroll: bool,
11963 cx: &mut ViewContext<Self>,
11964 ) {
11965 let snapshot = self.buffer().read(cx).snapshot(cx);
11966 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11967 let ix = row_highlights.binary_search_by(|highlight| {
11968 Ordering::Equal
11969 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11970 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11971 });
11972
11973 if let Err(mut ix) = ix {
11974 let index = post_inc(&mut self.highlight_order);
11975
11976 // If this range intersects with the preceding highlight, then merge it with
11977 // the preceding highlight. Otherwise insert a new highlight.
11978 let mut merged = false;
11979 if ix > 0 {
11980 let prev_highlight = &mut row_highlights[ix - 1];
11981 if prev_highlight
11982 .range
11983 .end
11984 .cmp(&range.start, &snapshot)
11985 .is_ge()
11986 {
11987 ix -= 1;
11988 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11989 prev_highlight.range.end = range.end;
11990 }
11991 merged = true;
11992 prev_highlight.index = index;
11993 prev_highlight.color = color;
11994 prev_highlight.should_autoscroll = should_autoscroll;
11995 }
11996 }
11997
11998 if !merged {
11999 row_highlights.insert(
12000 ix,
12001 RowHighlight {
12002 range: range.clone(),
12003 index,
12004 color,
12005 should_autoscroll,
12006 },
12007 );
12008 }
12009
12010 // If any of the following highlights intersect with this one, merge them.
12011 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12012 let highlight = &row_highlights[ix];
12013 if next_highlight
12014 .range
12015 .start
12016 .cmp(&highlight.range.end, &snapshot)
12017 .is_le()
12018 {
12019 if next_highlight
12020 .range
12021 .end
12022 .cmp(&highlight.range.end, &snapshot)
12023 .is_gt()
12024 {
12025 row_highlights[ix].range.end = next_highlight.range.end;
12026 }
12027 row_highlights.remove(ix + 1);
12028 } else {
12029 break;
12030 }
12031 }
12032 }
12033 }
12034
12035 /// Remove any highlighted row ranges of the given type that intersect the
12036 /// given ranges.
12037 pub fn remove_highlighted_rows<T: 'static>(
12038 &mut self,
12039 ranges_to_remove: Vec<Range<Anchor>>,
12040 cx: &mut ViewContext<Self>,
12041 ) {
12042 let snapshot = self.buffer().read(cx).snapshot(cx);
12043 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12044 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12045 row_highlights.retain(|highlight| {
12046 while let Some(range_to_remove) = ranges_to_remove.peek() {
12047 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12048 Ordering::Less | Ordering::Equal => {
12049 ranges_to_remove.next();
12050 }
12051 Ordering::Greater => {
12052 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12053 Ordering::Less | Ordering::Equal => {
12054 return false;
12055 }
12056 Ordering::Greater => break,
12057 }
12058 }
12059 }
12060 }
12061
12062 true
12063 })
12064 }
12065
12066 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12067 pub fn clear_row_highlights<T: 'static>(&mut self) {
12068 self.highlighted_rows.remove(&TypeId::of::<T>());
12069 }
12070
12071 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12072 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12073 self.highlighted_rows
12074 .get(&TypeId::of::<T>())
12075 .map_or(&[] as &[_], |vec| vec.as_slice())
12076 .iter()
12077 .map(|highlight| (highlight.range.clone(), highlight.color))
12078 }
12079
12080 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12081 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12082 /// Allows to ignore certain kinds of highlights.
12083 pub fn highlighted_display_rows(
12084 &mut self,
12085 cx: &mut WindowContext,
12086 ) -> BTreeMap<DisplayRow, Hsla> {
12087 let snapshot = self.snapshot(cx);
12088 let mut used_highlight_orders = HashMap::default();
12089 self.highlighted_rows
12090 .iter()
12091 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12092 .fold(
12093 BTreeMap::<DisplayRow, Hsla>::new(),
12094 |mut unique_rows, highlight| {
12095 let start = highlight.range.start.to_display_point(&snapshot);
12096 let end = highlight.range.end.to_display_point(&snapshot);
12097 let start_row = start.row().0;
12098 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12099 && end.column() == 0
12100 {
12101 end.row().0.saturating_sub(1)
12102 } else {
12103 end.row().0
12104 };
12105 for row in start_row..=end_row {
12106 let used_index =
12107 used_highlight_orders.entry(row).or_insert(highlight.index);
12108 if highlight.index >= *used_index {
12109 *used_index = highlight.index;
12110 unique_rows.insert(DisplayRow(row), highlight.color);
12111 }
12112 }
12113 unique_rows
12114 },
12115 )
12116 }
12117
12118 pub fn highlighted_display_row_for_autoscroll(
12119 &self,
12120 snapshot: &DisplaySnapshot,
12121 ) -> Option<DisplayRow> {
12122 self.highlighted_rows
12123 .values()
12124 .flat_map(|highlighted_rows| highlighted_rows.iter())
12125 .filter_map(|highlight| {
12126 if highlight.should_autoscroll {
12127 Some(highlight.range.start.to_display_point(snapshot).row())
12128 } else {
12129 None
12130 }
12131 })
12132 .min()
12133 }
12134
12135 pub fn set_search_within_ranges(
12136 &mut self,
12137 ranges: &[Range<Anchor>],
12138 cx: &mut ViewContext<Self>,
12139 ) {
12140 self.highlight_background::<SearchWithinRange>(
12141 ranges,
12142 |colors| colors.editor_document_highlight_read_background,
12143 cx,
12144 )
12145 }
12146
12147 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12148 self.breadcrumb_header = Some(new_header);
12149 }
12150
12151 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12152 self.clear_background_highlights::<SearchWithinRange>(cx);
12153 }
12154
12155 pub fn highlight_background<T: 'static>(
12156 &mut self,
12157 ranges: &[Range<Anchor>],
12158 color_fetcher: fn(&ThemeColors) -> Hsla,
12159 cx: &mut ViewContext<Self>,
12160 ) {
12161 self.background_highlights
12162 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12163 self.scrollbar_marker_state.dirty = true;
12164 cx.notify();
12165 }
12166
12167 pub fn clear_background_highlights<T: 'static>(
12168 &mut self,
12169 cx: &mut ViewContext<Self>,
12170 ) -> Option<BackgroundHighlight> {
12171 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12172 if !text_highlights.1.is_empty() {
12173 self.scrollbar_marker_state.dirty = true;
12174 cx.notify();
12175 }
12176 Some(text_highlights)
12177 }
12178
12179 pub fn highlight_gutter<T: 'static>(
12180 &mut self,
12181 ranges: &[Range<Anchor>],
12182 color_fetcher: fn(&AppContext) -> Hsla,
12183 cx: &mut ViewContext<Self>,
12184 ) {
12185 self.gutter_highlights
12186 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12187 cx.notify();
12188 }
12189
12190 pub fn clear_gutter_highlights<T: 'static>(
12191 &mut self,
12192 cx: &mut ViewContext<Self>,
12193 ) -> Option<GutterHighlight> {
12194 cx.notify();
12195 self.gutter_highlights.remove(&TypeId::of::<T>())
12196 }
12197
12198 #[cfg(feature = "test-support")]
12199 pub fn all_text_background_highlights(
12200 &mut self,
12201 cx: &mut ViewContext<Self>,
12202 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12203 let snapshot = self.snapshot(cx);
12204 let buffer = &snapshot.buffer_snapshot;
12205 let start = buffer.anchor_before(0);
12206 let end = buffer.anchor_after(buffer.len());
12207 let theme = cx.theme().colors();
12208 self.background_highlights_in_range(start..end, &snapshot, theme)
12209 }
12210
12211 #[cfg(feature = "test-support")]
12212 pub fn search_background_highlights(
12213 &mut self,
12214 cx: &mut ViewContext<Self>,
12215 ) -> Vec<Range<Point>> {
12216 let snapshot = self.buffer().read(cx).snapshot(cx);
12217
12218 let highlights = self
12219 .background_highlights
12220 .get(&TypeId::of::<items::BufferSearchHighlights>());
12221
12222 if let Some((_color, ranges)) = highlights {
12223 ranges
12224 .iter()
12225 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12226 .collect_vec()
12227 } else {
12228 vec![]
12229 }
12230 }
12231
12232 fn document_highlights_for_position<'a>(
12233 &'a self,
12234 position: Anchor,
12235 buffer: &'a MultiBufferSnapshot,
12236 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12237 let read_highlights = self
12238 .background_highlights
12239 .get(&TypeId::of::<DocumentHighlightRead>())
12240 .map(|h| &h.1);
12241 let write_highlights = self
12242 .background_highlights
12243 .get(&TypeId::of::<DocumentHighlightWrite>())
12244 .map(|h| &h.1);
12245 let left_position = position.bias_left(buffer);
12246 let right_position = position.bias_right(buffer);
12247 read_highlights
12248 .into_iter()
12249 .chain(write_highlights)
12250 .flat_map(move |ranges| {
12251 let start_ix = match ranges.binary_search_by(|probe| {
12252 let cmp = probe.end.cmp(&left_position, buffer);
12253 if cmp.is_ge() {
12254 Ordering::Greater
12255 } else {
12256 Ordering::Less
12257 }
12258 }) {
12259 Ok(i) | Err(i) => i,
12260 };
12261
12262 ranges[start_ix..]
12263 .iter()
12264 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12265 })
12266 }
12267
12268 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12269 self.background_highlights
12270 .get(&TypeId::of::<T>())
12271 .map_or(false, |(_, highlights)| !highlights.is_empty())
12272 }
12273
12274 pub fn background_highlights_in_range(
12275 &self,
12276 search_range: Range<Anchor>,
12277 display_snapshot: &DisplaySnapshot,
12278 theme: &ThemeColors,
12279 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12280 let mut results = Vec::new();
12281 for (color_fetcher, ranges) in self.background_highlights.values() {
12282 let color = color_fetcher(theme);
12283 let start_ix = match ranges.binary_search_by(|probe| {
12284 let cmp = probe
12285 .end
12286 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12287 if cmp.is_gt() {
12288 Ordering::Greater
12289 } else {
12290 Ordering::Less
12291 }
12292 }) {
12293 Ok(i) | Err(i) => i,
12294 };
12295 for range in &ranges[start_ix..] {
12296 if range
12297 .start
12298 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12299 .is_ge()
12300 {
12301 break;
12302 }
12303
12304 let start = range.start.to_display_point(display_snapshot);
12305 let end = range.end.to_display_point(display_snapshot);
12306 results.push((start..end, color))
12307 }
12308 }
12309 results
12310 }
12311
12312 pub fn background_highlight_row_ranges<T: 'static>(
12313 &self,
12314 search_range: Range<Anchor>,
12315 display_snapshot: &DisplaySnapshot,
12316 count: usize,
12317 ) -> Vec<RangeInclusive<DisplayPoint>> {
12318 let mut results = Vec::new();
12319 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12320 return vec![];
12321 };
12322
12323 let start_ix = match ranges.binary_search_by(|probe| {
12324 let cmp = probe
12325 .end
12326 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12327 if cmp.is_gt() {
12328 Ordering::Greater
12329 } else {
12330 Ordering::Less
12331 }
12332 }) {
12333 Ok(i) | Err(i) => i,
12334 };
12335 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12336 if let (Some(start_display), Some(end_display)) = (start, end) {
12337 results.push(
12338 start_display.to_display_point(display_snapshot)
12339 ..=end_display.to_display_point(display_snapshot),
12340 );
12341 }
12342 };
12343 let mut start_row: Option<Point> = None;
12344 let mut end_row: Option<Point> = None;
12345 if ranges.len() > count {
12346 return Vec::new();
12347 }
12348 for range in &ranges[start_ix..] {
12349 if range
12350 .start
12351 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12352 .is_ge()
12353 {
12354 break;
12355 }
12356 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12357 if let Some(current_row) = &end_row {
12358 if end.row == current_row.row {
12359 continue;
12360 }
12361 }
12362 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12363 if start_row.is_none() {
12364 assert_eq!(end_row, None);
12365 start_row = Some(start);
12366 end_row = Some(end);
12367 continue;
12368 }
12369 if let Some(current_end) = end_row.as_mut() {
12370 if start.row > current_end.row + 1 {
12371 push_region(start_row, end_row);
12372 start_row = Some(start);
12373 end_row = Some(end);
12374 } else {
12375 // Merge two hunks.
12376 *current_end = end;
12377 }
12378 } else {
12379 unreachable!();
12380 }
12381 }
12382 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12383 push_region(start_row, end_row);
12384 results
12385 }
12386
12387 pub fn gutter_highlights_in_range(
12388 &self,
12389 search_range: Range<Anchor>,
12390 display_snapshot: &DisplaySnapshot,
12391 cx: &AppContext,
12392 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12393 let mut results = Vec::new();
12394 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12395 let color = color_fetcher(cx);
12396 let start_ix = match ranges.binary_search_by(|probe| {
12397 let cmp = probe
12398 .end
12399 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12400 if cmp.is_gt() {
12401 Ordering::Greater
12402 } else {
12403 Ordering::Less
12404 }
12405 }) {
12406 Ok(i) | Err(i) => i,
12407 };
12408 for range in &ranges[start_ix..] {
12409 if range
12410 .start
12411 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12412 .is_ge()
12413 {
12414 break;
12415 }
12416
12417 let start = range.start.to_display_point(display_snapshot);
12418 let end = range.end.to_display_point(display_snapshot);
12419 results.push((start..end, color))
12420 }
12421 }
12422 results
12423 }
12424
12425 /// Get the text ranges corresponding to the redaction query
12426 pub fn redacted_ranges(
12427 &self,
12428 search_range: Range<Anchor>,
12429 display_snapshot: &DisplaySnapshot,
12430 cx: &WindowContext,
12431 ) -> Vec<Range<DisplayPoint>> {
12432 display_snapshot
12433 .buffer_snapshot
12434 .redacted_ranges(search_range, |file| {
12435 if let Some(file) = file {
12436 file.is_private()
12437 && EditorSettings::get(
12438 Some(SettingsLocation {
12439 worktree_id: file.worktree_id(cx),
12440 path: file.path().as_ref(),
12441 }),
12442 cx,
12443 )
12444 .redact_private_values
12445 } else {
12446 false
12447 }
12448 })
12449 .map(|range| {
12450 range.start.to_display_point(display_snapshot)
12451 ..range.end.to_display_point(display_snapshot)
12452 })
12453 .collect()
12454 }
12455
12456 pub fn highlight_text<T: 'static>(
12457 &mut self,
12458 ranges: Vec<Range<Anchor>>,
12459 style: HighlightStyle,
12460 cx: &mut ViewContext<Self>,
12461 ) {
12462 self.display_map.update(cx, |map, _| {
12463 map.highlight_text(TypeId::of::<T>(), ranges, style)
12464 });
12465 cx.notify();
12466 }
12467
12468 pub(crate) fn highlight_inlays<T: 'static>(
12469 &mut self,
12470 highlights: Vec<InlayHighlight>,
12471 style: HighlightStyle,
12472 cx: &mut ViewContext<Self>,
12473 ) {
12474 self.display_map.update(cx, |map, _| {
12475 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12476 });
12477 cx.notify();
12478 }
12479
12480 pub fn text_highlights<'a, T: 'static>(
12481 &'a self,
12482 cx: &'a AppContext,
12483 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12484 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12485 }
12486
12487 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12488 let cleared = self
12489 .display_map
12490 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12491 if cleared {
12492 cx.notify();
12493 }
12494 }
12495
12496 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12497 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12498 && self.focus_handle.is_focused(cx)
12499 }
12500
12501 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12502 self.show_cursor_when_unfocused = is_enabled;
12503 cx.notify();
12504 }
12505
12506 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12507 cx.notify();
12508 }
12509
12510 fn on_buffer_event(
12511 &mut self,
12512 multibuffer: Model<MultiBuffer>,
12513 event: &multi_buffer::Event,
12514 cx: &mut ViewContext<Self>,
12515 ) {
12516 match event {
12517 multi_buffer::Event::Edited {
12518 singleton_buffer_edited,
12519 } => {
12520 self.scrollbar_marker_state.dirty = true;
12521 self.active_indent_guides_state.dirty = true;
12522 self.refresh_active_diagnostics(cx);
12523 self.refresh_code_actions(cx);
12524 if self.has_active_inline_completion(cx) {
12525 self.update_visible_inline_completion(cx);
12526 }
12527 cx.emit(EditorEvent::BufferEdited);
12528 cx.emit(SearchEvent::MatchesInvalidated);
12529 if *singleton_buffer_edited {
12530 if let Some(project) = &self.project {
12531 let project = project.read(cx);
12532 #[allow(clippy::mutable_key_type)]
12533 let languages_affected = multibuffer
12534 .read(cx)
12535 .all_buffers()
12536 .into_iter()
12537 .filter_map(|buffer| {
12538 let buffer = buffer.read(cx);
12539 let language = buffer.language()?;
12540 if project.is_local()
12541 && project.language_servers_for_buffer(buffer, cx).count() == 0
12542 {
12543 None
12544 } else {
12545 Some(language)
12546 }
12547 })
12548 .cloned()
12549 .collect::<HashSet<_>>();
12550 if !languages_affected.is_empty() {
12551 self.refresh_inlay_hints(
12552 InlayHintRefreshReason::BufferEdited(languages_affected),
12553 cx,
12554 );
12555 }
12556 }
12557 }
12558
12559 let Some(project) = &self.project else { return };
12560 let (telemetry, is_via_ssh) = {
12561 let project = project.read(cx);
12562 let telemetry = project.client().telemetry().clone();
12563 let is_via_ssh = project.is_via_ssh();
12564 (telemetry, is_via_ssh)
12565 };
12566 refresh_linked_ranges(self, cx);
12567 telemetry.log_edit_event("editor", is_via_ssh);
12568 }
12569 multi_buffer::Event::ExcerptsAdded {
12570 buffer,
12571 predecessor,
12572 excerpts,
12573 } => {
12574 self.tasks_update_task = Some(self.refresh_runnables(cx));
12575 cx.emit(EditorEvent::ExcerptsAdded {
12576 buffer: buffer.clone(),
12577 predecessor: *predecessor,
12578 excerpts: excerpts.clone(),
12579 });
12580 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12581 }
12582 multi_buffer::Event::ExcerptsRemoved { ids } => {
12583 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12584 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12585 }
12586 multi_buffer::Event::ExcerptsEdited { ids } => {
12587 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12588 }
12589 multi_buffer::Event::ExcerptsExpanded { ids } => {
12590 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12591 }
12592 multi_buffer::Event::Reparsed(buffer_id) => {
12593 self.tasks_update_task = Some(self.refresh_runnables(cx));
12594
12595 cx.emit(EditorEvent::Reparsed(*buffer_id));
12596 }
12597 multi_buffer::Event::LanguageChanged(buffer_id) => {
12598 linked_editing_ranges::refresh_linked_ranges(self, cx);
12599 cx.emit(EditorEvent::Reparsed(*buffer_id));
12600 cx.notify();
12601 }
12602 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12603 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12604 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12605 cx.emit(EditorEvent::TitleChanged)
12606 }
12607 multi_buffer::Event::DiffBaseChanged => {
12608 self.scrollbar_marker_state.dirty = true;
12609 cx.emit(EditorEvent::DiffBaseChanged);
12610 cx.notify();
12611 }
12612 multi_buffer::Event::DiffUpdated { buffer } => {
12613 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12614 cx.notify();
12615 }
12616 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12617 multi_buffer::Event::DiagnosticsUpdated => {
12618 self.refresh_active_diagnostics(cx);
12619 self.scrollbar_marker_state.dirty = true;
12620 cx.notify();
12621 }
12622 _ => {}
12623 };
12624 }
12625
12626 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12627 cx.notify();
12628 }
12629
12630 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12631 self.tasks_update_task = Some(self.refresh_runnables(cx));
12632 self.refresh_inline_completion(true, false, cx);
12633 self.refresh_inlay_hints(
12634 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12635 self.selections.newest_anchor().head(),
12636 &self.buffer.read(cx).snapshot(cx),
12637 cx,
12638 )),
12639 cx,
12640 );
12641
12642 let old_cursor_shape = self.cursor_shape;
12643
12644 {
12645 let editor_settings = EditorSettings::get_global(cx);
12646 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12647 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12648 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12649 }
12650
12651 if old_cursor_shape != self.cursor_shape {
12652 cx.emit(EditorEvent::CursorShapeChanged);
12653 }
12654
12655 let project_settings = ProjectSettings::get_global(cx);
12656 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12657
12658 if self.mode == EditorMode::Full {
12659 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12660 if self.git_blame_inline_enabled != inline_blame_enabled {
12661 self.toggle_git_blame_inline_internal(false, cx);
12662 }
12663 }
12664
12665 cx.notify();
12666 }
12667
12668 pub fn set_searchable(&mut self, searchable: bool) {
12669 self.searchable = searchable;
12670 }
12671
12672 pub fn searchable(&self) -> bool {
12673 self.searchable
12674 }
12675
12676 fn open_proposed_changes_editor(
12677 &mut self,
12678 _: &OpenProposedChangesEditor,
12679 cx: &mut ViewContext<Self>,
12680 ) {
12681 let Some(workspace) = self.workspace() else {
12682 cx.propagate();
12683 return;
12684 };
12685
12686 let selections = self.selections.all::<usize>(cx);
12687 let buffer = self.buffer.read(cx);
12688 let mut new_selections_by_buffer = HashMap::default();
12689 for selection in selections {
12690 for (buffer, range, _) in
12691 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12692 {
12693 let mut range = range.to_point(buffer.read(cx));
12694 range.start.column = 0;
12695 range.end.column = buffer.read(cx).line_len(range.end.row);
12696 new_selections_by_buffer
12697 .entry(buffer)
12698 .or_insert(Vec::new())
12699 .push(range)
12700 }
12701 }
12702
12703 let proposed_changes_buffers = new_selections_by_buffer
12704 .into_iter()
12705 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12706 .collect::<Vec<_>>();
12707 let proposed_changes_editor = cx.new_view(|cx| {
12708 ProposedChangesEditor::new(
12709 "Proposed changes",
12710 proposed_changes_buffers,
12711 self.project.clone(),
12712 cx,
12713 )
12714 });
12715
12716 cx.window_context().defer(move |cx| {
12717 workspace.update(cx, |workspace, cx| {
12718 workspace.active_pane().update(cx, |pane, cx| {
12719 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12720 });
12721 });
12722 });
12723 }
12724
12725 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12726 self.open_excerpts_common(None, true, cx)
12727 }
12728
12729 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12730 self.open_excerpts_common(None, false, cx)
12731 }
12732
12733 fn open_excerpts_common(
12734 &mut self,
12735 jump_data: Option<JumpData>,
12736 split: bool,
12737 cx: &mut ViewContext<Self>,
12738 ) {
12739 let Some(workspace) = self.workspace() else {
12740 cx.propagate();
12741 return;
12742 };
12743
12744 if self.buffer.read(cx).is_singleton() {
12745 cx.propagate();
12746 return;
12747 }
12748
12749 let mut new_selections_by_buffer = HashMap::default();
12750 match &jump_data {
12751 Some(jump_data) => {
12752 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12753 if let Some(buffer) = multi_buffer_snapshot
12754 .buffer_id_for_excerpt(jump_data.excerpt_id)
12755 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12756 {
12757 let buffer_snapshot = buffer.read(cx).snapshot();
12758 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12759 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12760 } else {
12761 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12762 };
12763 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12764 new_selections_by_buffer.insert(
12765 buffer,
12766 (
12767 vec![jump_to_offset..jump_to_offset],
12768 Some(jump_data.line_offset_from_top),
12769 ),
12770 );
12771 }
12772 }
12773 None => {
12774 let selections = self.selections.all::<usize>(cx);
12775 let buffer = self.buffer.read(cx);
12776 for selection in selections {
12777 for (mut buffer_handle, mut range, _) in
12778 buffer.range_to_buffer_ranges(selection.range(), cx)
12779 {
12780 // When editing branch buffers, jump to the corresponding location
12781 // in their base buffer.
12782 let buffer = buffer_handle.read(cx);
12783 if let Some(base_buffer) = buffer.diff_base_buffer() {
12784 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12785 buffer_handle = base_buffer;
12786 }
12787
12788 if selection.reversed {
12789 mem::swap(&mut range.start, &mut range.end);
12790 }
12791 new_selections_by_buffer
12792 .entry(buffer_handle)
12793 .or_insert((Vec::new(), None))
12794 .0
12795 .push(range)
12796 }
12797 }
12798 }
12799 }
12800
12801 if new_selections_by_buffer.is_empty() {
12802 return;
12803 }
12804
12805 // We defer the pane interaction because we ourselves are a workspace item
12806 // and activating a new item causes the pane to call a method on us reentrantly,
12807 // which panics if we're on the stack.
12808 cx.window_context().defer(move |cx| {
12809 workspace.update(cx, |workspace, cx| {
12810 let pane = if split {
12811 workspace.adjacent_pane(cx)
12812 } else {
12813 workspace.active_pane().clone()
12814 };
12815
12816 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12817 let editor =
12818 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12819 editor.update(cx, |editor, cx| {
12820 let autoscroll = match scroll_offset {
12821 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12822 None => Autoscroll::newest(),
12823 };
12824 let nav_history = editor.nav_history.take();
12825 editor.change_selections(Some(autoscroll), cx, |s| {
12826 s.select_ranges(ranges);
12827 });
12828 editor.nav_history = nav_history;
12829 });
12830 }
12831 })
12832 });
12833 }
12834
12835 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12836 let snapshot = self.buffer.read(cx).read(cx);
12837 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12838 Some(
12839 ranges
12840 .iter()
12841 .map(move |range| {
12842 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12843 })
12844 .collect(),
12845 )
12846 }
12847
12848 fn selection_replacement_ranges(
12849 &self,
12850 range: Range<OffsetUtf16>,
12851 cx: &mut AppContext,
12852 ) -> Vec<Range<OffsetUtf16>> {
12853 let selections = self.selections.all::<OffsetUtf16>(cx);
12854 let newest_selection = selections
12855 .iter()
12856 .max_by_key(|selection| selection.id)
12857 .unwrap();
12858 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12859 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12860 let snapshot = self.buffer.read(cx).read(cx);
12861 selections
12862 .into_iter()
12863 .map(|mut selection| {
12864 selection.start.0 =
12865 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12866 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12867 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12868 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12869 })
12870 .collect()
12871 }
12872
12873 fn report_editor_event(
12874 &self,
12875 operation: &'static str,
12876 file_extension: Option<String>,
12877 cx: &AppContext,
12878 ) {
12879 if cfg!(any(test, feature = "test-support")) {
12880 return;
12881 }
12882
12883 let Some(project) = &self.project else { return };
12884
12885 // If None, we are in a file without an extension
12886 let file = self
12887 .buffer
12888 .read(cx)
12889 .as_singleton()
12890 .and_then(|b| b.read(cx).file());
12891 let file_extension = file_extension.or(file
12892 .as_ref()
12893 .and_then(|file| Path::new(file.file_name(cx)).extension())
12894 .and_then(|e| e.to_str())
12895 .map(|a| a.to_string()));
12896
12897 let vim_mode = cx
12898 .global::<SettingsStore>()
12899 .raw_user_settings()
12900 .get("vim_mode")
12901 == Some(&serde_json::Value::Bool(true));
12902
12903 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12904 == language::language_settings::InlineCompletionProvider::Copilot;
12905 let copilot_enabled_for_language = self
12906 .buffer
12907 .read(cx)
12908 .settings_at(0, cx)
12909 .show_inline_completions;
12910
12911 let project = project.read(cx);
12912 let telemetry = project.client().telemetry().clone();
12913 telemetry.report_editor_event(
12914 file_extension,
12915 vim_mode,
12916 operation,
12917 copilot_enabled,
12918 copilot_enabled_for_language,
12919 project.is_via_ssh(),
12920 )
12921 }
12922
12923 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12924 /// with each line being an array of {text, highlight} objects.
12925 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12926 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12927 return;
12928 };
12929
12930 #[derive(Serialize)]
12931 struct Chunk<'a> {
12932 text: String,
12933 highlight: Option<&'a str>,
12934 }
12935
12936 let snapshot = buffer.read(cx).snapshot();
12937 let range = self
12938 .selected_text_range(false, cx)
12939 .and_then(|selection| {
12940 if selection.range.is_empty() {
12941 None
12942 } else {
12943 Some(selection.range)
12944 }
12945 })
12946 .unwrap_or_else(|| 0..snapshot.len());
12947
12948 let chunks = snapshot.chunks(range, true);
12949 let mut lines = Vec::new();
12950 let mut line: VecDeque<Chunk> = VecDeque::new();
12951
12952 let Some(style) = self.style.as_ref() else {
12953 return;
12954 };
12955
12956 for chunk in chunks {
12957 let highlight = chunk
12958 .syntax_highlight_id
12959 .and_then(|id| id.name(&style.syntax));
12960 let mut chunk_lines = chunk.text.split('\n').peekable();
12961 while let Some(text) = chunk_lines.next() {
12962 let mut merged_with_last_token = false;
12963 if let Some(last_token) = line.back_mut() {
12964 if last_token.highlight == highlight {
12965 last_token.text.push_str(text);
12966 merged_with_last_token = true;
12967 }
12968 }
12969
12970 if !merged_with_last_token {
12971 line.push_back(Chunk {
12972 text: text.into(),
12973 highlight,
12974 });
12975 }
12976
12977 if chunk_lines.peek().is_some() {
12978 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12979 line.pop_front();
12980 }
12981 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12982 line.pop_back();
12983 }
12984
12985 lines.push(mem::take(&mut line));
12986 }
12987 }
12988 }
12989
12990 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12991 return;
12992 };
12993 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12994 }
12995
12996 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12997 &self.inlay_hint_cache
12998 }
12999
13000 pub fn replay_insert_event(
13001 &mut self,
13002 text: &str,
13003 relative_utf16_range: Option<Range<isize>>,
13004 cx: &mut ViewContext<Self>,
13005 ) {
13006 if !self.input_enabled {
13007 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13008 return;
13009 }
13010 if let Some(relative_utf16_range) = relative_utf16_range {
13011 let selections = self.selections.all::<OffsetUtf16>(cx);
13012 self.change_selections(None, cx, |s| {
13013 let new_ranges = selections.into_iter().map(|range| {
13014 let start = OffsetUtf16(
13015 range
13016 .head()
13017 .0
13018 .saturating_add_signed(relative_utf16_range.start),
13019 );
13020 let end = OffsetUtf16(
13021 range
13022 .head()
13023 .0
13024 .saturating_add_signed(relative_utf16_range.end),
13025 );
13026 start..end
13027 });
13028 s.select_ranges(new_ranges);
13029 });
13030 }
13031
13032 self.handle_input(text, cx);
13033 }
13034
13035 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13036 let Some(provider) = self.semantics_provider.as_ref() else {
13037 return false;
13038 };
13039
13040 let mut supports = false;
13041 self.buffer().read(cx).for_each_buffer(|buffer| {
13042 supports |= provider.supports_inlay_hints(buffer, cx);
13043 });
13044 supports
13045 }
13046
13047 pub fn focus(&self, cx: &mut WindowContext) {
13048 cx.focus(&self.focus_handle)
13049 }
13050
13051 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13052 self.focus_handle.is_focused(cx)
13053 }
13054
13055 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13056 cx.emit(EditorEvent::Focused);
13057
13058 if let Some(descendant) = self
13059 .last_focused_descendant
13060 .take()
13061 .and_then(|descendant| descendant.upgrade())
13062 {
13063 cx.focus(&descendant);
13064 } else {
13065 if let Some(blame) = self.blame.as_ref() {
13066 blame.update(cx, GitBlame::focus)
13067 }
13068
13069 self.blink_manager.update(cx, BlinkManager::enable);
13070 self.show_cursor_names(cx);
13071 self.buffer.update(cx, |buffer, cx| {
13072 buffer.finalize_last_transaction(cx);
13073 if self.leader_peer_id.is_none() {
13074 buffer.set_active_selections(
13075 &self.selections.disjoint_anchors(),
13076 self.selections.line_mode,
13077 self.cursor_shape,
13078 cx,
13079 );
13080 }
13081 });
13082 }
13083 }
13084
13085 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13086 cx.emit(EditorEvent::FocusedIn)
13087 }
13088
13089 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13090 if event.blurred != self.focus_handle {
13091 self.last_focused_descendant = Some(event.blurred);
13092 }
13093 }
13094
13095 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13096 self.blink_manager.update(cx, BlinkManager::disable);
13097 self.buffer
13098 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13099
13100 if let Some(blame) = self.blame.as_ref() {
13101 blame.update(cx, GitBlame::blur)
13102 }
13103 if !self.hover_state.focused(cx) {
13104 hide_hover(self, cx);
13105 }
13106
13107 self.hide_context_menu(cx);
13108 cx.emit(EditorEvent::Blurred);
13109 cx.notify();
13110 }
13111
13112 pub fn register_action<A: Action>(
13113 &mut self,
13114 listener: impl Fn(&A, &mut WindowContext) + 'static,
13115 ) -> Subscription {
13116 let id = self.next_editor_action_id.post_inc();
13117 let listener = Arc::new(listener);
13118 self.editor_actions.borrow_mut().insert(
13119 id,
13120 Box::new(move |cx| {
13121 let cx = cx.window_context();
13122 let listener = listener.clone();
13123 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13124 let action = action.downcast_ref().unwrap();
13125 if phase == DispatchPhase::Bubble {
13126 listener(action, cx)
13127 }
13128 })
13129 }),
13130 );
13131
13132 let editor_actions = self.editor_actions.clone();
13133 Subscription::new(move || {
13134 editor_actions.borrow_mut().remove(&id);
13135 })
13136 }
13137
13138 pub fn file_header_size(&self) -> u32 {
13139 FILE_HEADER_HEIGHT
13140 }
13141
13142 pub fn revert(
13143 &mut self,
13144 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13145 cx: &mut ViewContext<Self>,
13146 ) {
13147 self.buffer().update(cx, |multi_buffer, cx| {
13148 for (buffer_id, changes) in revert_changes {
13149 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13150 buffer.update(cx, |buffer, cx| {
13151 buffer.edit(
13152 changes.into_iter().map(|(range, text)| {
13153 (range, text.to_string().map(Arc::<str>::from))
13154 }),
13155 None,
13156 cx,
13157 );
13158 });
13159 }
13160 }
13161 });
13162 self.change_selections(None, cx, |selections| selections.refresh());
13163 }
13164
13165 pub fn to_pixel_point(
13166 &mut self,
13167 source: multi_buffer::Anchor,
13168 editor_snapshot: &EditorSnapshot,
13169 cx: &mut ViewContext<Self>,
13170 ) -> Option<gpui::Point<Pixels>> {
13171 let source_point = source.to_display_point(editor_snapshot);
13172 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13173 }
13174
13175 pub fn display_to_pixel_point(
13176 &mut self,
13177 source: DisplayPoint,
13178 editor_snapshot: &EditorSnapshot,
13179 cx: &mut ViewContext<Self>,
13180 ) -> Option<gpui::Point<Pixels>> {
13181 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13182 let text_layout_details = self.text_layout_details(cx);
13183 let scroll_top = text_layout_details
13184 .scroll_anchor
13185 .scroll_position(editor_snapshot)
13186 .y;
13187
13188 if source.row().as_f32() < scroll_top.floor() {
13189 return None;
13190 }
13191 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13192 let source_y = line_height * (source.row().as_f32() - scroll_top);
13193 Some(gpui::Point::new(source_x, source_y))
13194 }
13195
13196 pub fn has_active_completions_menu(&self) -> bool {
13197 self.context_menu.read().as_ref().map_or(false, |menu| {
13198 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13199 })
13200 }
13201
13202 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13203 self.addons
13204 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13205 }
13206
13207 pub fn unregister_addon<T: Addon>(&mut self) {
13208 self.addons.remove(&std::any::TypeId::of::<T>());
13209 }
13210
13211 pub fn addon<T: Addon>(&self) -> Option<&T> {
13212 let type_id = std::any::TypeId::of::<T>();
13213 self.addons
13214 .get(&type_id)
13215 .and_then(|item| item.to_any().downcast_ref::<T>())
13216 }
13217}
13218
13219fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13220 let tab_size = tab_size.get() as usize;
13221 let mut width = offset;
13222
13223 for ch in text.chars() {
13224 width += if ch == '\t' {
13225 tab_size - (width % tab_size)
13226 } else {
13227 1
13228 };
13229 }
13230
13231 width - offset
13232}
13233
13234#[cfg(test)]
13235mod tests {
13236 use super::*;
13237
13238 #[test]
13239 fn test_string_size_with_expanded_tabs() {
13240 let nz = |val| NonZeroU32::new(val).unwrap();
13241 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13242 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13243 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13244 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13245 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13246 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13247 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13248 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13249 }
13250}
13251
13252/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13253struct WordBreakingTokenizer<'a> {
13254 input: &'a str,
13255}
13256
13257impl<'a> WordBreakingTokenizer<'a> {
13258 fn new(input: &'a str) -> Self {
13259 Self { input }
13260 }
13261}
13262
13263fn is_char_ideographic(ch: char) -> bool {
13264 use unicode_script::Script::*;
13265 use unicode_script::UnicodeScript;
13266 matches!(ch.script(), Han | Tangut | Yi)
13267}
13268
13269fn is_grapheme_ideographic(text: &str) -> bool {
13270 text.chars().any(is_char_ideographic)
13271}
13272
13273fn is_grapheme_whitespace(text: &str) -> bool {
13274 text.chars().any(|x| x.is_whitespace())
13275}
13276
13277fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13278 text.chars().next().map_or(false, |ch| {
13279 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13280 })
13281}
13282
13283#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13284struct WordBreakToken<'a> {
13285 token: &'a str,
13286 grapheme_len: usize,
13287 is_whitespace: bool,
13288}
13289
13290impl<'a> Iterator for WordBreakingTokenizer<'a> {
13291 /// Yields a span, the count of graphemes in the token, and whether it was
13292 /// whitespace. Note that it also breaks at word boundaries.
13293 type Item = WordBreakToken<'a>;
13294
13295 fn next(&mut self) -> Option<Self::Item> {
13296 use unicode_segmentation::UnicodeSegmentation;
13297 if self.input.is_empty() {
13298 return None;
13299 }
13300
13301 let mut iter = self.input.graphemes(true).peekable();
13302 let mut offset = 0;
13303 let mut graphemes = 0;
13304 if let Some(first_grapheme) = iter.next() {
13305 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13306 offset += first_grapheme.len();
13307 graphemes += 1;
13308 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13309 if let Some(grapheme) = iter.peek().copied() {
13310 if should_stay_with_preceding_ideograph(grapheme) {
13311 offset += grapheme.len();
13312 graphemes += 1;
13313 }
13314 }
13315 } else {
13316 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13317 let mut next_word_bound = words.peek().copied();
13318 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13319 next_word_bound = words.next();
13320 }
13321 while let Some(grapheme) = iter.peek().copied() {
13322 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13323 break;
13324 };
13325 if is_grapheme_whitespace(grapheme) != is_whitespace {
13326 break;
13327 };
13328 offset += grapheme.len();
13329 graphemes += 1;
13330 iter.next();
13331 }
13332 }
13333 let token = &self.input[..offset];
13334 self.input = &self.input[offset..];
13335 if is_whitespace {
13336 Some(WordBreakToken {
13337 token: " ",
13338 grapheme_len: 1,
13339 is_whitespace: true,
13340 })
13341 } else {
13342 Some(WordBreakToken {
13343 token,
13344 grapheme_len: graphemes,
13345 is_whitespace: false,
13346 })
13347 }
13348 } else {
13349 None
13350 }
13351 }
13352}
13353
13354#[test]
13355fn test_word_breaking_tokenizer() {
13356 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13357 ("", &[]),
13358 (" ", &[(" ", 1, true)]),
13359 ("Ʒ", &[("Ʒ", 1, false)]),
13360 ("Ǽ", &[("Ǽ", 1, false)]),
13361 ("⋑", &[("⋑", 1, false)]),
13362 ("⋑⋑", &[("⋑⋑", 2, false)]),
13363 (
13364 "原理,进而",
13365 &[
13366 ("原", 1, false),
13367 ("理,", 2, false),
13368 ("进", 1, false),
13369 ("而", 1, false),
13370 ],
13371 ),
13372 (
13373 "hello world",
13374 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13375 ),
13376 (
13377 "hello, world",
13378 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13379 ),
13380 (
13381 " hello world",
13382 &[
13383 (" ", 1, true),
13384 ("hello", 5, false),
13385 (" ", 1, true),
13386 ("world", 5, false),
13387 ],
13388 ),
13389 (
13390 "这是什么 \n 钢笔",
13391 &[
13392 ("这", 1, false),
13393 ("是", 1, false),
13394 ("什", 1, false),
13395 ("么", 1, false),
13396 (" ", 1, true),
13397 ("钢", 1, false),
13398 ("笔", 1, false),
13399 ],
13400 ),
13401 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13402 ];
13403
13404 for (input, result) in tests {
13405 assert_eq!(
13406 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13407 result
13408 .iter()
13409 .copied()
13410 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13411 token,
13412 grapheme_len,
13413 is_whitespace,
13414 })
13415 .collect::<Vec<_>>()
13416 );
13417 }
13418}
13419
13420fn wrap_with_prefix(
13421 line_prefix: String,
13422 unwrapped_text: String,
13423 wrap_column: usize,
13424 tab_size: NonZeroU32,
13425) -> String {
13426 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13427 let mut wrapped_text = String::new();
13428 let mut current_line = line_prefix.clone();
13429
13430 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13431 let mut current_line_len = line_prefix_len;
13432 for WordBreakToken {
13433 token,
13434 grapheme_len,
13435 is_whitespace,
13436 } in tokenizer
13437 {
13438 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13439 wrapped_text.push_str(current_line.trim_end());
13440 wrapped_text.push('\n');
13441 current_line.truncate(line_prefix.len());
13442 current_line_len = line_prefix_len;
13443 if !is_whitespace {
13444 current_line.push_str(token);
13445 current_line_len += grapheme_len;
13446 }
13447 } else if !is_whitespace {
13448 current_line.push_str(token);
13449 current_line_len += grapheme_len;
13450 } else if current_line_len != line_prefix_len {
13451 current_line.push(' ');
13452 current_line_len += 1;
13453 }
13454 }
13455
13456 if !current_line.is_empty() {
13457 wrapped_text.push_str(¤t_line);
13458 }
13459 wrapped_text
13460}
13461
13462#[test]
13463fn test_wrap_with_prefix() {
13464 assert_eq!(
13465 wrap_with_prefix(
13466 "# ".to_string(),
13467 "abcdefg".to_string(),
13468 4,
13469 NonZeroU32::new(4).unwrap()
13470 ),
13471 "# abcdefg"
13472 );
13473 assert_eq!(
13474 wrap_with_prefix(
13475 "".to_string(),
13476 "\thello world".to_string(),
13477 8,
13478 NonZeroU32::new(4).unwrap()
13479 ),
13480 "hello\nworld"
13481 );
13482 assert_eq!(
13483 wrap_with_prefix(
13484 "// ".to_string(),
13485 "xx \nyy zz aa bb cc".to_string(),
13486 12,
13487 NonZeroU32::new(4).unwrap()
13488 ),
13489 "// xx yy zz\n// aa bb cc"
13490 );
13491 assert_eq!(
13492 wrap_with_prefix(
13493 String::new(),
13494 "这是什么 \n 钢笔".to_string(),
13495 3,
13496 NonZeroU32::new(4).unwrap()
13497 ),
13498 "这是什\n么 钢\n笔"
13499 );
13500}
13501
13502fn hunks_for_selections(
13503 multi_buffer_snapshot: &MultiBufferSnapshot,
13504 selections: &[Selection<Anchor>],
13505) -> Vec<MultiBufferDiffHunk> {
13506 let buffer_rows_for_selections = selections.iter().map(|selection| {
13507 let head = selection.head();
13508 let tail = selection.tail();
13509 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13510 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13511 if start > end {
13512 end..start
13513 } else {
13514 start..end
13515 }
13516 });
13517
13518 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13519}
13520
13521pub fn hunks_for_rows(
13522 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13523 multi_buffer_snapshot: &MultiBufferSnapshot,
13524) -> Vec<MultiBufferDiffHunk> {
13525 let mut hunks = Vec::new();
13526 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13527 HashMap::default();
13528 for selected_multi_buffer_rows in rows {
13529 let query_rows =
13530 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13531 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13532 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13533 // when the caret is just above or just below the deleted hunk.
13534 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13535 let related_to_selection = if allow_adjacent {
13536 hunk.row_range.overlaps(&query_rows)
13537 || hunk.row_range.start == query_rows.end
13538 || hunk.row_range.end == query_rows.start
13539 } else {
13540 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13541 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13542 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13543 || selected_multi_buffer_rows.end == hunk.row_range.start
13544 };
13545 if related_to_selection {
13546 if !processed_buffer_rows
13547 .entry(hunk.buffer_id)
13548 .or_default()
13549 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13550 {
13551 continue;
13552 }
13553 hunks.push(hunk);
13554 }
13555 }
13556 }
13557
13558 hunks
13559}
13560
13561pub trait CollaborationHub {
13562 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13563 fn user_participant_indices<'a>(
13564 &self,
13565 cx: &'a AppContext,
13566 ) -> &'a HashMap<u64, ParticipantIndex>;
13567 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13568}
13569
13570impl CollaborationHub for Model<Project> {
13571 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13572 self.read(cx).collaborators()
13573 }
13574
13575 fn user_participant_indices<'a>(
13576 &self,
13577 cx: &'a AppContext,
13578 ) -> &'a HashMap<u64, ParticipantIndex> {
13579 self.read(cx).user_store().read(cx).participant_indices()
13580 }
13581
13582 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13583 let this = self.read(cx);
13584 let user_ids = this.collaborators().values().map(|c| c.user_id);
13585 this.user_store().read_with(cx, |user_store, cx| {
13586 user_store.participant_names(user_ids, cx)
13587 })
13588 }
13589}
13590
13591pub trait SemanticsProvider {
13592 fn hover(
13593 &self,
13594 buffer: &Model<Buffer>,
13595 position: text::Anchor,
13596 cx: &mut AppContext,
13597 ) -> Option<Task<Vec<project::Hover>>>;
13598
13599 fn inlay_hints(
13600 &self,
13601 buffer_handle: Model<Buffer>,
13602 range: Range<text::Anchor>,
13603 cx: &mut AppContext,
13604 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13605
13606 fn resolve_inlay_hint(
13607 &self,
13608 hint: InlayHint,
13609 buffer_handle: Model<Buffer>,
13610 server_id: LanguageServerId,
13611 cx: &mut AppContext,
13612 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13613
13614 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13615
13616 fn document_highlights(
13617 &self,
13618 buffer: &Model<Buffer>,
13619 position: text::Anchor,
13620 cx: &mut AppContext,
13621 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13622
13623 fn definitions(
13624 &self,
13625 buffer: &Model<Buffer>,
13626 position: text::Anchor,
13627 kind: GotoDefinitionKind,
13628 cx: &mut AppContext,
13629 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13630
13631 fn range_for_rename(
13632 &self,
13633 buffer: &Model<Buffer>,
13634 position: text::Anchor,
13635 cx: &mut AppContext,
13636 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13637
13638 fn perform_rename(
13639 &self,
13640 buffer: &Model<Buffer>,
13641 position: text::Anchor,
13642 new_name: String,
13643 cx: &mut AppContext,
13644 ) -> Option<Task<Result<ProjectTransaction>>>;
13645}
13646
13647pub trait CompletionProvider {
13648 fn completions(
13649 &self,
13650 buffer: &Model<Buffer>,
13651 buffer_position: text::Anchor,
13652 trigger: CompletionContext,
13653 cx: &mut ViewContext<Editor>,
13654 ) -> Task<Result<Vec<Completion>>>;
13655
13656 fn resolve_completions(
13657 &self,
13658 buffer: Model<Buffer>,
13659 completion_indices: Vec<usize>,
13660 completions: Arc<RwLock<Box<[Completion]>>>,
13661 cx: &mut ViewContext<Editor>,
13662 ) -> Task<Result<bool>>;
13663
13664 fn apply_additional_edits_for_completion(
13665 &self,
13666 buffer: Model<Buffer>,
13667 completion: Completion,
13668 push_to_history: bool,
13669 cx: &mut ViewContext<Editor>,
13670 ) -> Task<Result<Option<language::Transaction>>>;
13671
13672 fn is_completion_trigger(
13673 &self,
13674 buffer: &Model<Buffer>,
13675 position: language::Anchor,
13676 text: &str,
13677 trigger_in_words: bool,
13678 cx: &mut ViewContext<Editor>,
13679 ) -> bool;
13680
13681 fn sort_completions(&self) -> bool {
13682 true
13683 }
13684}
13685
13686pub trait CodeActionProvider {
13687 fn code_actions(
13688 &self,
13689 buffer: &Model<Buffer>,
13690 range: Range<text::Anchor>,
13691 cx: &mut WindowContext,
13692 ) -> Task<Result<Vec<CodeAction>>>;
13693
13694 fn apply_code_action(
13695 &self,
13696 buffer_handle: Model<Buffer>,
13697 action: CodeAction,
13698 excerpt_id: ExcerptId,
13699 push_to_history: bool,
13700 cx: &mut WindowContext,
13701 ) -> Task<Result<ProjectTransaction>>;
13702}
13703
13704impl CodeActionProvider for Model<Project> {
13705 fn code_actions(
13706 &self,
13707 buffer: &Model<Buffer>,
13708 range: Range<text::Anchor>,
13709 cx: &mut WindowContext,
13710 ) -> Task<Result<Vec<CodeAction>>> {
13711 self.update(cx, |project, cx| {
13712 project.code_actions(buffer, range, None, cx)
13713 })
13714 }
13715
13716 fn apply_code_action(
13717 &self,
13718 buffer_handle: Model<Buffer>,
13719 action: CodeAction,
13720 _excerpt_id: ExcerptId,
13721 push_to_history: bool,
13722 cx: &mut WindowContext,
13723 ) -> Task<Result<ProjectTransaction>> {
13724 self.update(cx, |project, cx| {
13725 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13726 })
13727 }
13728}
13729
13730fn snippet_completions(
13731 project: &Project,
13732 buffer: &Model<Buffer>,
13733 buffer_position: text::Anchor,
13734 cx: &mut AppContext,
13735) -> Vec<Completion> {
13736 let language = buffer.read(cx).language_at(buffer_position);
13737 let language_name = language.as_ref().map(|language| language.lsp_id());
13738 let snippet_store = project.snippets().read(cx);
13739 let snippets = snippet_store.snippets_for(language_name, cx);
13740
13741 if snippets.is_empty() {
13742 return vec![];
13743 }
13744 let snapshot = buffer.read(cx).text_snapshot();
13745 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13746
13747 let scope = language.map(|language| language.default_scope());
13748 let classifier = CharClassifier::new(scope).for_completion(true);
13749 let mut last_word = chars
13750 .take_while(|c| classifier.is_word(*c))
13751 .collect::<String>();
13752 last_word = last_word.chars().rev().collect();
13753 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13754 let to_lsp = |point: &text::Anchor| {
13755 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13756 point_to_lsp(end)
13757 };
13758 let lsp_end = to_lsp(&buffer_position);
13759 snippets
13760 .into_iter()
13761 .filter_map(|snippet| {
13762 let matching_prefix = snippet
13763 .prefix
13764 .iter()
13765 .find(|prefix| prefix.starts_with(&last_word))?;
13766 let start = as_offset - last_word.len();
13767 let start = snapshot.anchor_before(start);
13768 let range = start..buffer_position;
13769 let lsp_start = to_lsp(&start);
13770 let lsp_range = lsp::Range {
13771 start: lsp_start,
13772 end: lsp_end,
13773 };
13774 Some(Completion {
13775 old_range: range,
13776 new_text: snippet.body.clone(),
13777 label: CodeLabel {
13778 text: matching_prefix.clone(),
13779 runs: vec![],
13780 filter_range: 0..matching_prefix.len(),
13781 },
13782 server_id: LanguageServerId(usize::MAX),
13783 documentation: snippet.description.clone().map(Documentation::SingleLine),
13784 lsp_completion: lsp::CompletionItem {
13785 label: snippet.prefix.first().unwrap().clone(),
13786 kind: Some(CompletionItemKind::SNIPPET),
13787 label_details: snippet.description.as_ref().map(|description| {
13788 lsp::CompletionItemLabelDetails {
13789 detail: Some(description.clone()),
13790 description: None,
13791 }
13792 }),
13793 insert_text_format: Some(InsertTextFormat::SNIPPET),
13794 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13795 lsp::InsertReplaceEdit {
13796 new_text: snippet.body.clone(),
13797 insert: lsp_range,
13798 replace: lsp_range,
13799 },
13800 )),
13801 filter_text: Some(snippet.body.clone()),
13802 sort_text: Some(char::MAX.to_string()),
13803 ..Default::default()
13804 },
13805 confirm: None,
13806 })
13807 })
13808 .collect()
13809}
13810
13811impl CompletionProvider for Model<Project> {
13812 fn completions(
13813 &self,
13814 buffer: &Model<Buffer>,
13815 buffer_position: text::Anchor,
13816 options: CompletionContext,
13817 cx: &mut ViewContext<Editor>,
13818 ) -> Task<Result<Vec<Completion>>> {
13819 self.update(cx, |project, cx| {
13820 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13821 let project_completions = project.completions(buffer, buffer_position, options, cx);
13822 cx.background_executor().spawn(async move {
13823 let mut completions = project_completions.await?;
13824 //let snippets = snippets.into_iter().;
13825 completions.extend(snippets);
13826 Ok(completions)
13827 })
13828 })
13829 }
13830
13831 fn resolve_completions(
13832 &self,
13833 buffer: Model<Buffer>,
13834 completion_indices: Vec<usize>,
13835 completions: Arc<RwLock<Box<[Completion]>>>,
13836 cx: &mut ViewContext<Editor>,
13837 ) -> Task<Result<bool>> {
13838 self.update(cx, |project, cx| {
13839 project.resolve_completions(buffer, completion_indices, completions, cx)
13840 })
13841 }
13842
13843 fn apply_additional_edits_for_completion(
13844 &self,
13845 buffer: Model<Buffer>,
13846 completion: Completion,
13847 push_to_history: bool,
13848 cx: &mut ViewContext<Editor>,
13849 ) -> Task<Result<Option<language::Transaction>>> {
13850 self.update(cx, |project, cx| {
13851 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13852 })
13853 }
13854
13855 fn is_completion_trigger(
13856 &self,
13857 buffer: &Model<Buffer>,
13858 position: language::Anchor,
13859 text: &str,
13860 trigger_in_words: bool,
13861 cx: &mut ViewContext<Editor>,
13862 ) -> bool {
13863 if !EditorSettings::get_global(cx).show_completions_on_input {
13864 return false;
13865 }
13866
13867 let mut chars = text.chars();
13868 let char = if let Some(char) = chars.next() {
13869 char
13870 } else {
13871 return false;
13872 };
13873 if chars.next().is_some() {
13874 return false;
13875 }
13876
13877 let buffer = buffer.read(cx);
13878 let classifier = buffer
13879 .snapshot()
13880 .char_classifier_at(position)
13881 .for_completion(true);
13882 if trigger_in_words && classifier.is_word(char) {
13883 return true;
13884 }
13885
13886 buffer.completion_triggers().contains(text)
13887 }
13888}
13889
13890impl SemanticsProvider for Model<Project> {
13891 fn hover(
13892 &self,
13893 buffer: &Model<Buffer>,
13894 position: text::Anchor,
13895 cx: &mut AppContext,
13896 ) -> Option<Task<Vec<project::Hover>>> {
13897 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13898 }
13899
13900 fn document_highlights(
13901 &self,
13902 buffer: &Model<Buffer>,
13903 position: text::Anchor,
13904 cx: &mut AppContext,
13905 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13906 Some(self.update(cx, |project, cx| {
13907 project.document_highlights(buffer, position, cx)
13908 }))
13909 }
13910
13911 fn definitions(
13912 &self,
13913 buffer: &Model<Buffer>,
13914 position: text::Anchor,
13915 kind: GotoDefinitionKind,
13916 cx: &mut AppContext,
13917 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13918 Some(self.update(cx, |project, cx| match kind {
13919 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13920 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13921 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13922 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13923 }))
13924 }
13925
13926 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13927 // TODO: make this work for remote projects
13928 self.read(cx)
13929 .language_servers_for_buffer(buffer.read(cx), cx)
13930 .any(
13931 |(_, server)| match server.capabilities().inlay_hint_provider {
13932 Some(lsp::OneOf::Left(enabled)) => enabled,
13933 Some(lsp::OneOf::Right(_)) => true,
13934 None => false,
13935 },
13936 )
13937 }
13938
13939 fn inlay_hints(
13940 &self,
13941 buffer_handle: Model<Buffer>,
13942 range: Range<text::Anchor>,
13943 cx: &mut AppContext,
13944 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13945 Some(self.update(cx, |project, cx| {
13946 project.inlay_hints(buffer_handle, range, cx)
13947 }))
13948 }
13949
13950 fn resolve_inlay_hint(
13951 &self,
13952 hint: InlayHint,
13953 buffer_handle: Model<Buffer>,
13954 server_id: LanguageServerId,
13955 cx: &mut AppContext,
13956 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13957 Some(self.update(cx, |project, cx| {
13958 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13959 }))
13960 }
13961
13962 fn range_for_rename(
13963 &self,
13964 buffer: &Model<Buffer>,
13965 position: text::Anchor,
13966 cx: &mut AppContext,
13967 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13968 Some(self.update(cx, |project, cx| {
13969 project.prepare_rename(buffer.clone(), position, cx)
13970 }))
13971 }
13972
13973 fn perform_rename(
13974 &self,
13975 buffer: &Model<Buffer>,
13976 position: text::Anchor,
13977 new_name: String,
13978 cx: &mut AppContext,
13979 ) -> Option<Task<Result<ProjectTransaction>>> {
13980 Some(self.update(cx, |project, cx| {
13981 project.perform_rename(buffer.clone(), position, new_name, cx)
13982 }))
13983 }
13984}
13985
13986fn inlay_hint_settings(
13987 location: Anchor,
13988 snapshot: &MultiBufferSnapshot,
13989 cx: &mut ViewContext<'_, Editor>,
13990) -> InlayHintSettings {
13991 let file = snapshot.file_at(location);
13992 let language = snapshot.language_at(location).map(|l| l.name());
13993 language_settings(language, file, cx).inlay_hints
13994}
13995
13996fn consume_contiguous_rows(
13997 contiguous_row_selections: &mut Vec<Selection<Point>>,
13998 selection: &Selection<Point>,
13999 display_map: &DisplaySnapshot,
14000 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14001) -> (MultiBufferRow, MultiBufferRow) {
14002 contiguous_row_selections.push(selection.clone());
14003 let start_row = MultiBufferRow(selection.start.row);
14004 let mut end_row = ending_row(selection, display_map);
14005
14006 while let Some(next_selection) = selections.peek() {
14007 if next_selection.start.row <= end_row.0 {
14008 end_row = ending_row(next_selection, display_map);
14009 contiguous_row_selections.push(selections.next().unwrap().clone());
14010 } else {
14011 break;
14012 }
14013 }
14014 (start_row, end_row)
14015}
14016
14017fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14018 if next_selection.end.column > 0 || next_selection.is_empty() {
14019 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14020 } else {
14021 MultiBufferRow(next_selection.end.row)
14022 }
14023}
14024
14025impl EditorSnapshot {
14026 pub fn remote_selections_in_range<'a>(
14027 &'a self,
14028 range: &'a Range<Anchor>,
14029 collaboration_hub: &dyn CollaborationHub,
14030 cx: &'a AppContext,
14031 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14032 let participant_names = collaboration_hub.user_names(cx);
14033 let participant_indices = collaboration_hub.user_participant_indices(cx);
14034 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14035 let collaborators_by_replica_id = collaborators_by_peer_id
14036 .iter()
14037 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14038 .collect::<HashMap<_, _>>();
14039 self.buffer_snapshot
14040 .selections_in_range(range, false)
14041 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14042 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14043 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14044 let user_name = participant_names.get(&collaborator.user_id).cloned();
14045 Some(RemoteSelection {
14046 replica_id,
14047 selection,
14048 cursor_shape,
14049 line_mode,
14050 participant_index,
14051 peer_id: collaborator.peer_id,
14052 user_name,
14053 })
14054 })
14055 }
14056
14057 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14058 self.display_snapshot.buffer_snapshot.language_at(position)
14059 }
14060
14061 pub fn is_focused(&self) -> bool {
14062 self.is_focused
14063 }
14064
14065 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14066 self.placeholder_text.as_ref()
14067 }
14068
14069 pub fn scroll_position(&self) -> gpui::Point<f32> {
14070 self.scroll_anchor.scroll_position(&self.display_snapshot)
14071 }
14072
14073 fn gutter_dimensions(
14074 &self,
14075 font_id: FontId,
14076 font_size: Pixels,
14077 em_width: Pixels,
14078 em_advance: Pixels,
14079 max_line_number_width: Pixels,
14080 cx: &AppContext,
14081 ) -> GutterDimensions {
14082 if !self.show_gutter {
14083 return GutterDimensions::default();
14084 }
14085 let descent = cx.text_system().descent(font_id, font_size);
14086
14087 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14088 matches!(
14089 ProjectSettings::get_global(cx).git.git_gutter,
14090 Some(GitGutterSetting::TrackedFiles)
14091 )
14092 });
14093 let gutter_settings = EditorSettings::get_global(cx).gutter;
14094 let show_line_numbers = self
14095 .show_line_numbers
14096 .unwrap_or(gutter_settings.line_numbers);
14097 let line_gutter_width = if show_line_numbers {
14098 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14099 let min_width_for_number_on_gutter = em_advance * 4.0;
14100 max_line_number_width.max(min_width_for_number_on_gutter)
14101 } else {
14102 0.0.into()
14103 };
14104
14105 let show_code_actions = self
14106 .show_code_actions
14107 .unwrap_or(gutter_settings.code_actions);
14108
14109 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14110
14111 let git_blame_entries_width =
14112 self.git_blame_gutter_max_author_length
14113 .map(|max_author_length| {
14114 // Length of the author name, but also space for the commit hash,
14115 // the spacing and the timestamp.
14116 let max_char_count = max_author_length
14117 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14118 + 7 // length of commit sha
14119 + 14 // length of max relative timestamp ("60 minutes ago")
14120 + 4; // gaps and margins
14121
14122 em_advance * max_char_count
14123 });
14124
14125 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14126 left_padding += if show_code_actions || show_runnables {
14127 em_width * 3.0
14128 } else if show_git_gutter && show_line_numbers {
14129 em_width * 2.0
14130 } else if show_git_gutter || show_line_numbers {
14131 em_width
14132 } else {
14133 px(0.)
14134 };
14135
14136 let right_padding = if gutter_settings.folds && show_line_numbers {
14137 em_width * 4.0
14138 } else if gutter_settings.folds {
14139 em_width * 3.0
14140 } else if show_line_numbers {
14141 em_width
14142 } else {
14143 px(0.)
14144 };
14145
14146 GutterDimensions {
14147 left_padding,
14148 right_padding,
14149 width: line_gutter_width + left_padding + right_padding,
14150 margin: -descent,
14151 git_blame_entries_width,
14152 }
14153 }
14154
14155 pub fn render_crease_toggle(
14156 &self,
14157 buffer_row: MultiBufferRow,
14158 row_contains_cursor: bool,
14159 editor: View<Editor>,
14160 cx: &mut WindowContext,
14161 ) -> Option<AnyElement> {
14162 let folded = self.is_line_folded(buffer_row);
14163 let mut is_foldable = false;
14164
14165 if let Some(crease) = self
14166 .crease_snapshot
14167 .query_row(buffer_row, &self.buffer_snapshot)
14168 {
14169 is_foldable = true;
14170 match crease {
14171 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14172 if let Some(render_toggle) = render_toggle {
14173 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14174 if folded {
14175 editor.update(cx, |editor, cx| {
14176 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14177 });
14178 } else {
14179 editor.update(cx, |editor, cx| {
14180 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14181 });
14182 }
14183 });
14184 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14185 }
14186 }
14187 }
14188 }
14189
14190 is_foldable |= self.starts_indent(buffer_row);
14191
14192 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14193 Some(
14194 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14195 .selected(folded)
14196 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14197 if folded {
14198 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14199 } else {
14200 this.fold_at(&FoldAt { buffer_row }, cx);
14201 }
14202 }))
14203 .into_any_element(),
14204 )
14205 } else {
14206 None
14207 }
14208 }
14209
14210 pub fn render_crease_trailer(
14211 &self,
14212 buffer_row: MultiBufferRow,
14213 cx: &mut WindowContext,
14214 ) -> Option<AnyElement> {
14215 let folded = self.is_line_folded(buffer_row);
14216 if let Crease::Inline { render_trailer, .. } = self
14217 .crease_snapshot
14218 .query_row(buffer_row, &self.buffer_snapshot)?
14219 {
14220 let render_trailer = render_trailer.as_ref()?;
14221 Some(render_trailer(buffer_row, folded, cx))
14222 } else {
14223 None
14224 }
14225 }
14226}
14227
14228impl Deref for EditorSnapshot {
14229 type Target = DisplaySnapshot;
14230
14231 fn deref(&self) -> &Self::Target {
14232 &self.display_snapshot
14233 }
14234}
14235
14236#[derive(Clone, Debug, PartialEq, Eq)]
14237pub enum EditorEvent {
14238 InputIgnored {
14239 text: Arc<str>,
14240 },
14241 InputHandled {
14242 utf16_range_to_replace: Option<Range<isize>>,
14243 text: Arc<str>,
14244 },
14245 ExcerptsAdded {
14246 buffer: Model<Buffer>,
14247 predecessor: ExcerptId,
14248 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14249 },
14250 ExcerptsRemoved {
14251 ids: Vec<ExcerptId>,
14252 },
14253 ExcerptsEdited {
14254 ids: Vec<ExcerptId>,
14255 },
14256 ExcerptsExpanded {
14257 ids: Vec<ExcerptId>,
14258 },
14259 BufferEdited,
14260 Edited {
14261 transaction_id: clock::Lamport,
14262 },
14263 Reparsed(BufferId),
14264 Focused,
14265 FocusedIn,
14266 Blurred,
14267 DirtyChanged,
14268 Saved,
14269 TitleChanged,
14270 DiffBaseChanged,
14271 SelectionsChanged {
14272 local: bool,
14273 },
14274 ScrollPositionChanged {
14275 local: bool,
14276 autoscroll: bool,
14277 },
14278 Closed,
14279 TransactionUndone {
14280 transaction_id: clock::Lamport,
14281 },
14282 TransactionBegun {
14283 transaction_id: clock::Lamport,
14284 },
14285 Reloaded,
14286 CursorShapeChanged,
14287}
14288
14289impl EventEmitter<EditorEvent> for Editor {}
14290
14291impl FocusableView for Editor {
14292 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14293 self.focus_handle.clone()
14294 }
14295}
14296
14297impl Render for Editor {
14298 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14299 let settings = ThemeSettings::get_global(cx);
14300
14301 let mut text_style = match self.mode {
14302 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14303 color: cx.theme().colors().editor_foreground,
14304 font_family: settings.ui_font.family.clone(),
14305 font_features: settings.ui_font.features.clone(),
14306 font_fallbacks: settings.ui_font.fallbacks.clone(),
14307 font_size: rems(0.875).into(),
14308 font_weight: settings.ui_font.weight,
14309 line_height: relative(settings.buffer_line_height.value()),
14310 ..Default::default()
14311 },
14312 EditorMode::Full => TextStyle {
14313 color: cx.theme().colors().editor_foreground,
14314 font_family: settings.buffer_font.family.clone(),
14315 font_features: settings.buffer_font.features.clone(),
14316 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14317 font_size: settings.buffer_font_size(cx).into(),
14318 font_weight: settings.buffer_font.weight,
14319 line_height: relative(settings.buffer_line_height.value()),
14320 ..Default::default()
14321 },
14322 };
14323 if let Some(text_style_refinement) = &self.text_style_refinement {
14324 text_style.refine(text_style_refinement)
14325 }
14326
14327 let background = match self.mode {
14328 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14329 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14330 EditorMode::Full => cx.theme().colors().editor_background,
14331 };
14332
14333 EditorElement::new(
14334 cx.view(),
14335 EditorStyle {
14336 background,
14337 local_player: cx.theme().players().local(),
14338 text: text_style,
14339 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14340 syntax: cx.theme().syntax().clone(),
14341 status: cx.theme().status().clone(),
14342 inlay_hints_style: make_inlay_hints_style(cx),
14343 suggestions_style: HighlightStyle {
14344 color: Some(cx.theme().status().predictive),
14345 ..HighlightStyle::default()
14346 },
14347 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14348 },
14349 )
14350 }
14351}
14352
14353impl ViewInputHandler for Editor {
14354 fn text_for_range(
14355 &mut self,
14356 range_utf16: Range<usize>,
14357 adjusted_range: &mut Option<Range<usize>>,
14358 cx: &mut ViewContext<Self>,
14359 ) -> Option<String> {
14360 let snapshot = self.buffer.read(cx).read(cx);
14361 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14362 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14363 if (start.0..end.0) != range_utf16 {
14364 adjusted_range.replace(start.0..end.0);
14365 }
14366 Some(snapshot.text_for_range(start..end).collect())
14367 }
14368
14369 fn selected_text_range(
14370 &mut self,
14371 ignore_disabled_input: bool,
14372 cx: &mut ViewContext<Self>,
14373 ) -> Option<UTF16Selection> {
14374 // Prevent the IME menu from appearing when holding down an alphabetic key
14375 // while input is disabled.
14376 if !ignore_disabled_input && !self.input_enabled {
14377 return None;
14378 }
14379
14380 let selection = self.selections.newest::<OffsetUtf16>(cx);
14381 let range = selection.range();
14382
14383 Some(UTF16Selection {
14384 range: range.start.0..range.end.0,
14385 reversed: selection.reversed,
14386 })
14387 }
14388
14389 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14390 let snapshot = self.buffer.read(cx).read(cx);
14391 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14392 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14393 }
14394
14395 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14396 self.clear_highlights::<InputComposition>(cx);
14397 self.ime_transaction.take();
14398 }
14399
14400 fn replace_text_in_range(
14401 &mut self,
14402 range_utf16: Option<Range<usize>>,
14403 text: &str,
14404 cx: &mut ViewContext<Self>,
14405 ) {
14406 if !self.input_enabled {
14407 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14408 return;
14409 }
14410
14411 self.transact(cx, |this, cx| {
14412 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14413 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14414 Some(this.selection_replacement_ranges(range_utf16, cx))
14415 } else {
14416 this.marked_text_ranges(cx)
14417 };
14418
14419 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14420 let newest_selection_id = this.selections.newest_anchor().id;
14421 this.selections
14422 .all::<OffsetUtf16>(cx)
14423 .iter()
14424 .zip(ranges_to_replace.iter())
14425 .find_map(|(selection, range)| {
14426 if selection.id == newest_selection_id {
14427 Some(
14428 (range.start.0 as isize - selection.head().0 as isize)
14429 ..(range.end.0 as isize - selection.head().0 as isize),
14430 )
14431 } else {
14432 None
14433 }
14434 })
14435 });
14436
14437 cx.emit(EditorEvent::InputHandled {
14438 utf16_range_to_replace: range_to_replace,
14439 text: text.into(),
14440 });
14441
14442 if let Some(new_selected_ranges) = new_selected_ranges {
14443 this.change_selections(None, cx, |selections| {
14444 selections.select_ranges(new_selected_ranges)
14445 });
14446 this.backspace(&Default::default(), cx);
14447 }
14448
14449 this.handle_input(text, cx);
14450 });
14451
14452 if let Some(transaction) = self.ime_transaction {
14453 self.buffer.update(cx, |buffer, cx| {
14454 buffer.group_until_transaction(transaction, cx);
14455 });
14456 }
14457
14458 self.unmark_text(cx);
14459 }
14460
14461 fn replace_and_mark_text_in_range(
14462 &mut self,
14463 range_utf16: Option<Range<usize>>,
14464 text: &str,
14465 new_selected_range_utf16: Option<Range<usize>>,
14466 cx: &mut ViewContext<Self>,
14467 ) {
14468 if !self.input_enabled {
14469 return;
14470 }
14471
14472 let transaction = self.transact(cx, |this, cx| {
14473 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14474 let snapshot = this.buffer.read(cx).read(cx);
14475 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14476 for marked_range in &mut marked_ranges {
14477 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14478 marked_range.start.0 += relative_range_utf16.start;
14479 marked_range.start =
14480 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14481 marked_range.end =
14482 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14483 }
14484 }
14485 Some(marked_ranges)
14486 } else if let Some(range_utf16) = range_utf16 {
14487 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14488 Some(this.selection_replacement_ranges(range_utf16, cx))
14489 } else {
14490 None
14491 };
14492
14493 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14494 let newest_selection_id = this.selections.newest_anchor().id;
14495 this.selections
14496 .all::<OffsetUtf16>(cx)
14497 .iter()
14498 .zip(ranges_to_replace.iter())
14499 .find_map(|(selection, range)| {
14500 if selection.id == newest_selection_id {
14501 Some(
14502 (range.start.0 as isize - selection.head().0 as isize)
14503 ..(range.end.0 as isize - selection.head().0 as isize),
14504 )
14505 } else {
14506 None
14507 }
14508 })
14509 });
14510
14511 cx.emit(EditorEvent::InputHandled {
14512 utf16_range_to_replace: range_to_replace,
14513 text: text.into(),
14514 });
14515
14516 if let Some(ranges) = ranges_to_replace {
14517 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14518 }
14519
14520 let marked_ranges = {
14521 let snapshot = this.buffer.read(cx).read(cx);
14522 this.selections
14523 .disjoint_anchors()
14524 .iter()
14525 .map(|selection| {
14526 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14527 })
14528 .collect::<Vec<_>>()
14529 };
14530
14531 if text.is_empty() {
14532 this.unmark_text(cx);
14533 } else {
14534 this.highlight_text::<InputComposition>(
14535 marked_ranges.clone(),
14536 HighlightStyle {
14537 underline: Some(UnderlineStyle {
14538 thickness: px(1.),
14539 color: None,
14540 wavy: false,
14541 }),
14542 ..Default::default()
14543 },
14544 cx,
14545 );
14546 }
14547
14548 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14549 let use_autoclose = this.use_autoclose;
14550 let use_auto_surround = this.use_auto_surround;
14551 this.set_use_autoclose(false);
14552 this.set_use_auto_surround(false);
14553 this.handle_input(text, cx);
14554 this.set_use_autoclose(use_autoclose);
14555 this.set_use_auto_surround(use_auto_surround);
14556
14557 if let Some(new_selected_range) = new_selected_range_utf16 {
14558 let snapshot = this.buffer.read(cx).read(cx);
14559 let new_selected_ranges = marked_ranges
14560 .into_iter()
14561 .map(|marked_range| {
14562 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14563 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14564 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14565 snapshot.clip_offset_utf16(new_start, Bias::Left)
14566 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14567 })
14568 .collect::<Vec<_>>();
14569
14570 drop(snapshot);
14571 this.change_selections(None, cx, |selections| {
14572 selections.select_ranges(new_selected_ranges)
14573 });
14574 }
14575 });
14576
14577 self.ime_transaction = self.ime_transaction.or(transaction);
14578 if let Some(transaction) = self.ime_transaction {
14579 self.buffer.update(cx, |buffer, cx| {
14580 buffer.group_until_transaction(transaction, cx);
14581 });
14582 }
14583
14584 if self.text_highlights::<InputComposition>(cx).is_none() {
14585 self.ime_transaction.take();
14586 }
14587 }
14588
14589 fn bounds_for_range(
14590 &mut self,
14591 range_utf16: Range<usize>,
14592 element_bounds: gpui::Bounds<Pixels>,
14593 cx: &mut ViewContext<Self>,
14594 ) -> Option<gpui::Bounds<Pixels>> {
14595 let text_layout_details = self.text_layout_details(cx);
14596 let style = &text_layout_details.editor_style;
14597 let font_id = cx.text_system().resolve_font(&style.text.font());
14598 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14599 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14600
14601 let em_width = cx
14602 .text_system()
14603 .typographic_bounds(font_id, font_size, 'm')
14604 .unwrap()
14605 .size
14606 .width;
14607
14608 let snapshot = self.snapshot(cx);
14609 let scroll_position = snapshot.scroll_position();
14610 let scroll_left = scroll_position.x * em_width;
14611
14612 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14613 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14614 + self.gutter_dimensions.width
14615 + self.gutter_dimensions.margin;
14616 let y = line_height * (start.row().as_f32() - scroll_position.y);
14617
14618 Some(Bounds {
14619 origin: element_bounds.origin + point(x, y),
14620 size: size(em_width, line_height),
14621 })
14622 }
14623}
14624
14625trait SelectionExt {
14626 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14627 fn spanned_rows(
14628 &self,
14629 include_end_if_at_line_start: bool,
14630 map: &DisplaySnapshot,
14631 ) -> Range<MultiBufferRow>;
14632}
14633
14634impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14635 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14636 let start = self
14637 .start
14638 .to_point(&map.buffer_snapshot)
14639 .to_display_point(map);
14640 let end = self
14641 .end
14642 .to_point(&map.buffer_snapshot)
14643 .to_display_point(map);
14644 if self.reversed {
14645 end..start
14646 } else {
14647 start..end
14648 }
14649 }
14650
14651 fn spanned_rows(
14652 &self,
14653 include_end_if_at_line_start: bool,
14654 map: &DisplaySnapshot,
14655 ) -> Range<MultiBufferRow> {
14656 let start = self.start.to_point(&map.buffer_snapshot);
14657 let mut end = self.end.to_point(&map.buffer_snapshot);
14658 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14659 end.row -= 1;
14660 }
14661
14662 let buffer_start = map.prev_line_boundary(start).0;
14663 let buffer_end = map.next_line_boundary(end).0;
14664 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14665 }
14666}
14667
14668impl<T: InvalidationRegion> InvalidationStack<T> {
14669 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14670 where
14671 S: Clone + ToOffset,
14672 {
14673 while let Some(region) = self.last() {
14674 let all_selections_inside_invalidation_ranges =
14675 if selections.len() == region.ranges().len() {
14676 selections
14677 .iter()
14678 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14679 .all(|(selection, invalidation_range)| {
14680 let head = selection.head().to_offset(buffer);
14681 invalidation_range.start <= head && invalidation_range.end >= head
14682 })
14683 } else {
14684 false
14685 };
14686
14687 if all_selections_inside_invalidation_ranges {
14688 break;
14689 } else {
14690 self.pop();
14691 }
14692 }
14693 }
14694}
14695
14696impl<T> Default for InvalidationStack<T> {
14697 fn default() -> Self {
14698 Self(Default::default())
14699 }
14700}
14701
14702impl<T> Deref for InvalidationStack<T> {
14703 type Target = Vec<T>;
14704
14705 fn deref(&self) -> &Self::Target {
14706 &self.0
14707 }
14708}
14709
14710impl<T> DerefMut for InvalidationStack<T> {
14711 fn deref_mut(&mut self) -> &mut Self::Target {
14712 &mut self.0
14713 }
14714}
14715
14716impl InvalidationRegion for SnippetState {
14717 fn ranges(&self) -> &[Range<Anchor>] {
14718 &self.ranges[self.active_index]
14719 }
14720}
14721
14722pub fn diagnostic_block_renderer(
14723 diagnostic: Diagnostic,
14724 max_message_rows: Option<u8>,
14725 allow_closing: bool,
14726 _is_valid: bool,
14727) -> RenderBlock {
14728 let (text_without_backticks, code_ranges) =
14729 highlight_diagnostic_message(&diagnostic, max_message_rows);
14730
14731 Arc::new(move |cx: &mut BlockContext| {
14732 let group_id: SharedString = cx.block_id.to_string().into();
14733
14734 let mut text_style = cx.text_style().clone();
14735 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14736 let theme_settings = ThemeSettings::get_global(cx);
14737 text_style.font_family = theme_settings.buffer_font.family.clone();
14738 text_style.font_style = theme_settings.buffer_font.style;
14739 text_style.font_features = theme_settings.buffer_font.features.clone();
14740 text_style.font_weight = theme_settings.buffer_font.weight;
14741
14742 let multi_line_diagnostic = diagnostic.message.contains('\n');
14743
14744 let buttons = |diagnostic: &Diagnostic| {
14745 if multi_line_diagnostic {
14746 v_flex()
14747 } else {
14748 h_flex()
14749 }
14750 .when(allow_closing, |div| {
14751 div.children(diagnostic.is_primary.then(|| {
14752 IconButton::new("close-block", IconName::XCircle)
14753 .icon_color(Color::Muted)
14754 .size(ButtonSize::Compact)
14755 .style(ButtonStyle::Transparent)
14756 .visible_on_hover(group_id.clone())
14757 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14758 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14759 }))
14760 })
14761 .child(
14762 IconButton::new("copy-block", IconName::Copy)
14763 .icon_color(Color::Muted)
14764 .size(ButtonSize::Compact)
14765 .style(ButtonStyle::Transparent)
14766 .visible_on_hover(group_id.clone())
14767 .on_click({
14768 let message = diagnostic.message.clone();
14769 move |_click, cx| {
14770 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14771 }
14772 })
14773 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14774 )
14775 };
14776
14777 let icon_size = buttons(&diagnostic)
14778 .into_any_element()
14779 .layout_as_root(AvailableSpace::min_size(), cx);
14780
14781 h_flex()
14782 .id(cx.block_id)
14783 .group(group_id.clone())
14784 .relative()
14785 .size_full()
14786 .block_mouse_down()
14787 .pl(cx.gutter_dimensions.width)
14788 .w(cx.max_width - cx.gutter_dimensions.full_width())
14789 .child(
14790 div()
14791 .flex()
14792 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14793 .flex_shrink(),
14794 )
14795 .child(buttons(&diagnostic))
14796 .child(div().flex().flex_shrink_0().child(
14797 StyledText::new(text_without_backticks.clone()).with_highlights(
14798 &text_style,
14799 code_ranges.iter().map(|range| {
14800 (
14801 range.clone(),
14802 HighlightStyle {
14803 font_weight: Some(FontWeight::BOLD),
14804 ..Default::default()
14805 },
14806 )
14807 }),
14808 ),
14809 ))
14810 .into_any_element()
14811 })
14812}
14813
14814pub fn highlight_diagnostic_message(
14815 diagnostic: &Diagnostic,
14816 mut max_message_rows: Option<u8>,
14817) -> (SharedString, Vec<Range<usize>>) {
14818 let mut text_without_backticks = String::new();
14819 let mut code_ranges = Vec::new();
14820
14821 if let Some(source) = &diagnostic.source {
14822 text_without_backticks.push_str(source);
14823 code_ranges.push(0..source.len());
14824 text_without_backticks.push_str(": ");
14825 }
14826
14827 let mut prev_offset = 0;
14828 let mut in_code_block = false;
14829 let has_row_limit = max_message_rows.is_some();
14830 let mut newline_indices = diagnostic
14831 .message
14832 .match_indices('\n')
14833 .filter(|_| has_row_limit)
14834 .map(|(ix, _)| ix)
14835 .fuse()
14836 .peekable();
14837
14838 for (quote_ix, _) in diagnostic
14839 .message
14840 .match_indices('`')
14841 .chain([(diagnostic.message.len(), "")])
14842 {
14843 let mut first_newline_ix = None;
14844 let mut last_newline_ix = None;
14845 while let Some(newline_ix) = newline_indices.peek() {
14846 if *newline_ix < quote_ix {
14847 if first_newline_ix.is_none() {
14848 first_newline_ix = Some(*newline_ix);
14849 }
14850 last_newline_ix = Some(*newline_ix);
14851
14852 if let Some(rows_left) = &mut max_message_rows {
14853 if *rows_left == 0 {
14854 break;
14855 } else {
14856 *rows_left -= 1;
14857 }
14858 }
14859 let _ = newline_indices.next();
14860 } else {
14861 break;
14862 }
14863 }
14864 let prev_len = text_without_backticks.len();
14865 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14866 text_without_backticks.push_str(new_text);
14867 if in_code_block {
14868 code_ranges.push(prev_len..text_without_backticks.len());
14869 }
14870 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14871 in_code_block = !in_code_block;
14872 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14873 text_without_backticks.push_str("...");
14874 break;
14875 }
14876 }
14877
14878 (text_without_backticks.into(), code_ranges)
14879}
14880
14881fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14882 match severity {
14883 DiagnosticSeverity::ERROR => colors.error,
14884 DiagnosticSeverity::WARNING => colors.warning,
14885 DiagnosticSeverity::INFORMATION => colors.info,
14886 DiagnosticSeverity::HINT => colors.info,
14887 _ => colors.ignored,
14888 }
14889}
14890
14891pub fn styled_runs_for_code_label<'a>(
14892 label: &'a CodeLabel,
14893 syntax_theme: &'a theme::SyntaxTheme,
14894) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14895 let fade_out = HighlightStyle {
14896 fade_out: Some(0.35),
14897 ..Default::default()
14898 };
14899
14900 let mut prev_end = label.filter_range.end;
14901 label
14902 .runs
14903 .iter()
14904 .enumerate()
14905 .flat_map(move |(ix, (range, highlight_id))| {
14906 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14907 style
14908 } else {
14909 return Default::default();
14910 };
14911 let mut muted_style = style;
14912 muted_style.highlight(fade_out);
14913
14914 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14915 if range.start >= label.filter_range.end {
14916 if range.start > prev_end {
14917 runs.push((prev_end..range.start, fade_out));
14918 }
14919 runs.push((range.clone(), muted_style));
14920 } else if range.end <= label.filter_range.end {
14921 runs.push((range.clone(), style));
14922 } else {
14923 runs.push((range.start..label.filter_range.end, style));
14924 runs.push((label.filter_range.end..range.end, muted_style));
14925 }
14926 prev_end = cmp::max(prev_end, range.end);
14927
14928 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14929 runs.push((prev_end..label.text.len(), fade_out));
14930 }
14931
14932 runs
14933 })
14934}
14935
14936pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14937 let mut prev_index = 0;
14938 let mut prev_codepoint: Option<char> = None;
14939 text.char_indices()
14940 .chain([(text.len(), '\0')])
14941 .filter_map(move |(index, codepoint)| {
14942 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14943 let is_boundary = index == text.len()
14944 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14945 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14946 if is_boundary {
14947 let chunk = &text[prev_index..index];
14948 prev_index = index;
14949 Some(chunk)
14950 } else {
14951 None
14952 }
14953 })
14954}
14955
14956pub trait RangeToAnchorExt: Sized {
14957 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14958
14959 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14960 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14961 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14962 }
14963}
14964
14965impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14966 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14967 let start_offset = self.start.to_offset(snapshot);
14968 let end_offset = self.end.to_offset(snapshot);
14969 if start_offset == end_offset {
14970 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14971 } else {
14972 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14973 }
14974 }
14975}
14976
14977pub trait RowExt {
14978 fn as_f32(&self) -> f32;
14979
14980 fn next_row(&self) -> Self;
14981
14982 fn previous_row(&self) -> Self;
14983
14984 fn minus(&self, other: Self) -> u32;
14985}
14986
14987impl RowExt for DisplayRow {
14988 fn as_f32(&self) -> f32 {
14989 self.0 as f32
14990 }
14991
14992 fn next_row(&self) -> Self {
14993 Self(self.0 + 1)
14994 }
14995
14996 fn previous_row(&self) -> Self {
14997 Self(self.0.saturating_sub(1))
14998 }
14999
15000 fn minus(&self, other: Self) -> u32 {
15001 self.0 - other.0
15002 }
15003}
15004
15005impl RowExt for MultiBufferRow {
15006 fn as_f32(&self) -> f32 {
15007 self.0 as f32
15008 }
15009
15010 fn next_row(&self) -> Self {
15011 Self(self.0 + 1)
15012 }
15013
15014 fn previous_row(&self) -> Self {
15015 Self(self.0.saturating_sub(1))
15016 }
15017
15018 fn minus(&self, other: Self) -> u32 {
15019 self.0 - other.0
15020 }
15021}
15022
15023trait RowRangeExt {
15024 type Row;
15025
15026 fn len(&self) -> usize;
15027
15028 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15029}
15030
15031impl RowRangeExt for Range<MultiBufferRow> {
15032 type Row = MultiBufferRow;
15033
15034 fn len(&self) -> usize {
15035 (self.end.0 - self.start.0) as usize
15036 }
15037
15038 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15039 (self.start.0..self.end.0).map(MultiBufferRow)
15040 }
15041}
15042
15043impl RowRangeExt for Range<DisplayRow> {
15044 type Row = DisplayRow;
15045
15046 fn len(&self) -> usize {
15047 (self.end.0 - self.start.0) as usize
15048 }
15049
15050 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15051 (self.start.0..self.end.0).map(DisplayRow)
15052 }
15053}
15054
15055fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15056 if hunk.diff_base_byte_range.is_empty() {
15057 DiffHunkStatus::Added
15058 } else if hunk.row_range.is_empty() {
15059 DiffHunkStatus::Removed
15060 } else {
15061 DiffHunkStatus::Modified
15062 }
15063}
15064
15065/// If select range has more than one line, we
15066/// just point the cursor to range.start.
15067fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15068 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15069 range
15070 } else {
15071 range.start..range.start
15072 }
15073}
15074
15075pub struct KillRing(ClipboardItem);
15076impl Global for KillRing {}
15077
15078const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);