1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
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, HighlightStyle, Hsla, InteractiveText, KeyContext,
78 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
79 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
80 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_provider::*;
90pub use items::MAX_TAB_TITLE_LEN;
91use itertools::Itertools;
92use language::{
93 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{
99 point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
100};
101use linked_editing_ranges::refresh_linked_ranges;
102pub use proposed_changes_editor::{
103 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
104};
105use similar::{ChangeTag, TextDiff};
106use std::iter::Peekable;
107use task::{ResolvedTask, TaskTemplate, TaskVariables};
108
109use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
110pub use lsp::CompletionContext;
111use lsp::{
112 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
113 LanguageServerId,
114};
115use mouse_context_menu::MouseContextMenu;
116use movement::TextLayoutDetails;
117pub use multi_buffer::{
118 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
119 ToPoint,
120};
121use multi_buffer::{
122 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
123};
124use ordered_float::OrderedFloat;
125use parking_lot::{Mutex, RwLock};
126use project::{
127 lsp_store::{FormatTarget, FormatTrigger},
128 project_settings::{GitGutterSetting, ProjectSettings},
129 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
130 LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
131};
132use rand::prelude::*;
133use rpc::{proto::*, ErrorExt};
134use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
135use selections_collection::{
136 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
137};
138use serde::{Deserialize, Serialize};
139use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
140use smallvec::SmallVec;
141use snippet::Snippet;
142use std::{
143 any::TypeId,
144 borrow::Cow,
145 cell::RefCell,
146 cmp::{self, Ordering, Reverse},
147 mem,
148 num::NonZeroU32,
149 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
150 path::{Path, PathBuf},
151 rc::Rc,
152 sync::Arc,
153 time::{Duration, Instant},
154};
155pub use sum_tree::Bias;
156use sum_tree::TreeMap;
157use text::{BufferId, OffsetUtf16, Rope};
158use theme::{
159 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
160 ThemeColors, ThemeSettings,
161};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 ListItem, Popover, PopoverMenuHandle, Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::find_url;
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188#[doc(hidden)]
189pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
190
191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
193
194pub fn render_parsed_markdown(
195 element_id: impl Into<ElementId>,
196 parsed: &language::ParsedMarkdown,
197 editor_style: &EditorStyle,
198 workspace: Option<WeakView<Workspace>>,
199 cx: &mut WindowContext,
200) -> InteractiveText {
201 let code_span_background_color = cx
202 .theme()
203 .colors()
204 .editor_document_highlight_read_background;
205
206 let highlights = gpui::combine_highlights(
207 parsed.highlights.iter().filter_map(|(range, highlight)| {
208 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
209 Some((range.clone(), highlight))
210 }),
211 parsed
212 .regions
213 .iter()
214 .zip(&parsed.region_ranges)
215 .filter_map(|(region, range)| {
216 if region.code {
217 Some((
218 range.clone(),
219 HighlightStyle {
220 background_color: Some(code_span_background_color),
221 ..Default::default()
222 },
223 ))
224 } else {
225 None
226 }
227 }),
228 );
229
230 let mut links = Vec::new();
231 let mut link_ranges = Vec::new();
232 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
233 if let Some(link) = region.link.clone() {
234 links.push(link);
235 link_ranges.push(range.clone());
236 }
237 }
238
239 InteractiveText::new(
240 element_id,
241 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
242 )
243 .on_click(link_ranges, move |clicked_range_ix, cx| {
244 match &links[clicked_range_ix] {
245 markdown::Link::Web { url } => cx.open_url(url),
246 markdown::Link::Path { path } => {
247 if let Some(workspace) = &workspace {
248 _ = workspace.update(cx, |workspace, cx| {
249 workspace.open_abs_path(path.clone(), false, cx).detach();
250 });
251 }
252 }
253 }
254 })
255}
256
257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
258pub(crate) enum InlayId {
259 Suggestion(usize),
260 Hint(usize),
261}
262
263impl InlayId {
264 fn id(&self) -> usize {
265 match self {
266 Self::Suggestion(id) => *id,
267 Self::Hint(id) => *id,
268 }
269 }
270}
271
272enum DiffRowHighlight {}
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Copy, Clone, PartialEq, Eq)]
278pub enum Direction {
279 Prev,
280 Next,
281}
282
283#[derive(Debug, Copy, Clone, PartialEq, Eq)]
284pub enum Navigated {
285 Yes,
286 No,
287}
288
289impl Navigated {
290 pub fn from_bool(yes: bool) -> Navigated {
291 if yes {
292 Navigated::Yes
293 } else {
294 Navigated::No
295 }
296 }
297}
298
299pub fn init_settings(cx: &mut AppContext) {
300 EditorSettings::register(cx);
301}
302
303pub fn init(cx: &mut AppContext) {
304 init_settings(cx);
305
306 workspace::register_project_item::<Editor>(cx);
307 workspace::FollowableViewRegistry::register::<Editor>(cx);
308 workspace::register_serializable_item::<Editor>(cx);
309
310 cx.observe_new_views(
311 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
312 workspace.register_action(Editor::new_file);
313 workspace.register_action(Editor::new_file_vertical);
314 workspace.register_action(Editor::new_file_horizontal);
315 },
316 )
317 .detach();
318
319 cx.on_action(move |_: &workspace::NewFile, cx| {
320 let app_state = workspace::AppState::global(cx);
321 if let Some(app_state) = app_state.upgrade() {
322 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
323 Editor::new_file(workspace, &Default::default(), cx)
324 })
325 .detach();
326 }
327 });
328 cx.on_action(move |_: &workspace::NewWindow, cx| {
329 let app_state = workspace::AppState::global(cx);
330 if let Some(app_state) = app_state.upgrade() {
331 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
332 Editor::new_file(workspace, &Default::default(), cx)
333 })
334 .detach();
335 }
336 });
337}
338
339pub struct SearchWithinRange;
340
341trait InvalidationRegion {
342 fn ranges(&self) -> &[Range<Anchor>];
343}
344
345#[derive(Clone, Debug, PartialEq)]
346pub enum SelectPhase {
347 Begin {
348 position: DisplayPoint,
349 add: bool,
350 click_count: usize,
351 },
352 BeginColumnar {
353 position: DisplayPoint,
354 reset: bool,
355 goal_column: u32,
356 },
357 Extend {
358 position: DisplayPoint,
359 click_count: usize,
360 },
361 Update {
362 position: DisplayPoint,
363 goal_column: u32,
364 scroll_delta: gpui::Point<f32>,
365 },
366 End,
367}
368
369#[derive(Clone, Debug)]
370pub enum SelectMode {
371 Character,
372 Word(Range<Anchor>),
373 Line(Range<Anchor>),
374 All,
375}
376
377#[derive(Copy, Clone, PartialEq, Eq, Debug)]
378pub enum EditorMode {
379 SingleLine { auto_width: bool },
380 AutoHeight { max_lines: usize },
381 Full,
382}
383
384#[derive(Copy, Clone, Debug)]
385pub enum SoftWrap {
386 /// Prefer not to wrap at all.
387 ///
388 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
389 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
390 GitDiff,
391 /// Prefer a single line generally, unless an overly long line is encountered.
392 None,
393 /// Soft wrap lines that exceed the editor width.
394 EditorWidth,
395 /// Soft wrap lines at the preferred line length.
396 Column(u32),
397 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
398 Bounded(u32),
399}
400
401#[derive(Clone)]
402pub struct EditorStyle {
403 pub background: Hsla,
404 pub local_player: PlayerColor,
405 pub text: TextStyle,
406 pub scrollbar_width: Pixels,
407 pub syntax: Arc<SyntaxTheme>,
408 pub status: StatusColors,
409 pub inlay_hints_style: HighlightStyle,
410 pub suggestions_style: HighlightStyle,
411 pub unnecessary_code_fade: f32,
412}
413
414impl Default for EditorStyle {
415 fn default() -> Self {
416 Self {
417 background: Hsla::default(),
418 local_player: PlayerColor::default(),
419 text: TextStyle::default(),
420 scrollbar_width: Pixels::default(),
421 syntax: Default::default(),
422 // HACK: Status colors don't have a real default.
423 // We should look into removing the status colors from the editor
424 // style and retrieve them directly from the theme.
425 status: StatusColors::dark(),
426 inlay_hints_style: HighlightStyle::default(),
427 suggestions_style: HighlightStyle::default(),
428 unnecessary_code_fade: Default::default(),
429 }
430 }
431}
432
433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
434 let show_background = language_settings::language_settings(None, None, cx)
435 .inlay_hints
436 .show_background;
437
438 HighlightStyle {
439 color: Some(cx.theme().status().hint),
440 background_color: show_background.then(|| cx.theme().status().hint_background),
441 ..HighlightStyle::default()
442 }
443}
444
445type CompletionId = usize;
446
447#[derive(Clone, Debug)]
448struct CompletionState {
449 // render_inlay_ids represents the inlay hints that are inserted
450 // for rendering the inline completions. They may be discontinuous
451 // in the event that the completion provider returns some intersection
452 // with the existing content.
453 render_inlay_ids: Vec<InlayId>,
454 // text is the resulting rope that is inserted when the user accepts a completion.
455 text: Rope,
456 // position is the position of the cursor when the completion was triggered.
457 position: multi_buffer::Anchor,
458 // delete_range is the range of text that this completion state covers.
459 // if the completion is accepted, this range should be deleted.
460 delete_range: Option<Range<multi_buffer::Anchor>>,
461}
462
463#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
464struct EditorActionId(usize);
465
466impl EditorActionId {
467 pub fn post_inc(&mut self) -> Self {
468 let answer = self.0;
469
470 *self = Self(answer + 1);
471
472 Self(answer)
473 }
474}
475
476// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
477// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
478
479type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
480type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
481
482#[derive(Default)]
483struct ScrollbarMarkerState {
484 scrollbar_size: Size<Pixels>,
485 dirty: bool,
486 markers: Arc<[PaintQuad]>,
487 pending_refresh: Option<Task<Result<()>>>,
488}
489
490impl ScrollbarMarkerState {
491 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
492 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
493 }
494}
495
496#[derive(Clone, Debug)]
497struct RunnableTasks {
498 templates: Vec<(TaskSourceKind, TaskTemplate)>,
499 offset: MultiBufferOffset,
500 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
501 column: u32,
502 // Values of all named captures, including those starting with '_'
503 extra_variables: HashMap<String, String>,
504 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
505 context_range: Range<BufferOffset>,
506}
507
508impl RunnableTasks {
509 fn resolve<'a>(
510 &'a self,
511 cx: &'a task::TaskContext,
512 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
513 self.templates.iter().filter_map(|(kind, template)| {
514 template
515 .resolve_task(&kind.to_id_base(), cx)
516 .map(|task| (kind.clone(), task))
517 })
518 }
519}
520
521#[derive(Clone)]
522struct ResolvedTasks {
523 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
524 position: Anchor,
525}
526#[derive(Copy, Clone, Debug)]
527struct MultiBufferOffset(usize);
528#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
529struct BufferOffset(usize);
530
531// Addons allow storing per-editor state in other crates (e.g. Vim)
532pub trait Addon: 'static {
533 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
534
535 fn to_any(&self) -> &dyn std::any::Any;
536}
537
538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
539///
540/// See the [module level documentation](self) for more information.
541pub struct Editor {
542 focus_handle: FocusHandle,
543 last_focused_descendant: Option<WeakFocusHandle>,
544 /// The text buffer being edited
545 buffer: Model<MultiBuffer>,
546 /// Map of how text in the buffer should be displayed.
547 /// Handles soft wraps, folds, fake inlay text insertions, etc.
548 pub display_map: Model<DisplayMap>,
549 pub selections: SelectionsCollection,
550 pub scroll_manager: ScrollManager,
551 /// When inline assist editors are linked, they all render cursors because
552 /// typing enters text into each of them, even the ones that aren't focused.
553 pub(crate) show_cursor_when_unfocused: bool,
554 columnar_selection_tail: Option<Anchor>,
555 add_selections_state: Option<AddSelectionsState>,
556 select_next_state: Option<SelectNextState>,
557 select_prev_state: Option<SelectNextState>,
558 selection_history: SelectionHistory,
559 autoclose_regions: Vec<AutocloseRegion>,
560 snippet_stack: InvalidationStack<SnippetState>,
561 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
562 ime_transaction: Option<TransactionId>,
563 active_diagnostics: Option<ActiveDiagnosticGroup>,
564 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
565
566 project: Option<Model<Project>>,
567 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
568 completion_provider: Option<Box<dyn CompletionProvider>>,
569 collaboration_hub: Option<Box<dyn CollaborationHub>>,
570 blink_manager: Model<BlinkManager>,
571 show_cursor_names: bool,
572 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
573 pub show_local_selections: bool,
574 mode: EditorMode,
575 show_breadcrumbs: bool,
576 show_gutter: bool,
577 show_line_numbers: Option<bool>,
578 use_relative_line_numbers: Option<bool>,
579 show_git_diff_gutter: Option<bool>,
580 show_code_actions: Option<bool>,
581 show_runnables: Option<bool>,
582 show_wrap_guides: Option<bool>,
583 show_indent_guides: Option<bool>,
584 placeholder_text: Option<Arc<str>>,
585 highlight_order: usize,
586 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
587 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
588 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
589 scrollbar_marker_state: ScrollbarMarkerState,
590 active_indent_guides_state: ActiveIndentGuidesState,
591 nav_history: Option<ItemNavHistory>,
592 context_menu: RwLock<Option<ContextMenu>>,
593 mouse_context_menu: Option<MouseContextMenu>,
594 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
595 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
596 signature_help_state: SignatureHelpState,
597 auto_signature_help: Option<bool>,
598 find_all_references_task_sources: Vec<Anchor>,
599 next_completion_id: CompletionId,
600 completion_documentation_pre_resolve_debounce: DebouncedDelay,
601 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
602 code_actions_task: Option<Task<Result<()>>>,
603 document_highlights_task: Option<Task<()>>,
604 linked_editing_range_task: Option<Task<Option<()>>>,
605 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
606 pending_rename: Option<RenameState>,
607 searchable: bool,
608 cursor_shape: CursorShape,
609 current_line_highlight: Option<CurrentLineHighlight>,
610 collapse_matches: bool,
611 autoindent_mode: Option<AutoindentMode>,
612 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
613 input_enabled: bool,
614 use_modal_editing: bool,
615 read_only: bool,
616 leader_peer_id: Option<PeerId>,
617 remote_id: Option<ViewId>,
618 hover_state: HoverState,
619 gutter_hovered: bool,
620 hovered_link_state: Option<HoveredLinkState>,
621 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
622 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
623 active_inline_completion: Option<CompletionState>,
624 // enable_inline_completions is a switch that Vim can use to disable
625 // inline completions based on its mode.
626 enable_inline_completions: bool,
627 show_inline_completions_override: Option<bool>,
628 inlay_hint_cache: InlayHintCache,
629 expanded_hunks: ExpandedHunks,
630 next_inlay_id: usize,
631 _subscriptions: Vec<Subscription>,
632 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
633 gutter_dimensions: GutterDimensions,
634 style: Option<EditorStyle>,
635 text_style_refinement: Option<TextStyleRefinement>,
636 next_editor_action_id: EditorActionId,
637 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
638 use_autoclose: bool,
639 use_auto_surround: bool,
640 auto_replace_emoji_shortcode: bool,
641 show_git_blame_gutter: bool,
642 show_git_blame_inline: bool,
643 show_git_blame_inline_delay_task: Option<Task<()>>,
644 git_blame_inline_enabled: bool,
645 serialize_dirty_buffers: bool,
646 show_selection_menu: Option<bool>,
647 blame: Option<Model<GitBlame>>,
648 blame_subscription: Option<Subscription>,
649 custom_context_menu: Option<
650 Box<
651 dyn 'static
652 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
653 >,
654 >,
655 last_bounds: Option<Bounds<Pixels>>,
656 expect_bounds_change: Option<Bounds<Pixels>>,
657 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
658 tasks_update_task: Option<Task<()>>,
659 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
660 breadcrumb_header: Option<String>,
661 focused_block: Option<FocusedBlock>,
662 next_scroll_position: NextScrollCursorCenterTopBottom,
663 addons: HashMap<TypeId, Box<dyn Addon>>,
664 _scroll_cursor_center_top_bottom_task: Task<()>,
665}
666
667#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
668enum NextScrollCursorCenterTopBottom {
669 #[default]
670 Center,
671 Top,
672 Bottom,
673}
674
675impl NextScrollCursorCenterTopBottom {
676 fn next(&self) -> Self {
677 match self {
678 Self::Center => Self::Top,
679 Self::Top => Self::Bottom,
680 Self::Bottom => Self::Center,
681 }
682 }
683}
684
685#[derive(Clone)]
686pub struct EditorSnapshot {
687 pub mode: EditorMode,
688 show_gutter: bool,
689 show_line_numbers: Option<bool>,
690 show_git_diff_gutter: Option<bool>,
691 show_code_actions: Option<bool>,
692 show_runnables: Option<bool>,
693 git_blame_gutter_max_author_length: Option<usize>,
694 pub display_snapshot: DisplaySnapshot,
695 pub placeholder_text: Option<Arc<str>>,
696 is_focused: bool,
697 scroll_anchor: ScrollAnchor,
698 ongoing_scroll: OngoingScroll,
699 current_line_highlight: CurrentLineHighlight,
700 gutter_hovered: bool,
701}
702
703const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
704
705#[derive(Default, Debug, Clone, Copy)]
706pub struct GutterDimensions {
707 pub left_padding: Pixels,
708 pub right_padding: Pixels,
709 pub width: Pixels,
710 pub margin: Pixels,
711 pub git_blame_entries_width: Option<Pixels>,
712}
713
714impl GutterDimensions {
715 /// The full width of the space taken up by the gutter.
716 pub fn full_width(&self) -> Pixels {
717 self.margin + self.width
718 }
719
720 /// The width of the space reserved for the fold indicators,
721 /// use alongside 'justify_end' and `gutter_width` to
722 /// right align content with the line numbers
723 pub fn fold_area_width(&self) -> Pixels {
724 self.margin + self.right_padding
725 }
726}
727
728#[derive(Debug)]
729pub struct RemoteSelection {
730 pub replica_id: ReplicaId,
731 pub selection: Selection<Anchor>,
732 pub cursor_shape: CursorShape,
733 pub peer_id: PeerId,
734 pub line_mode: bool,
735 pub participant_index: Option<ParticipantIndex>,
736 pub user_name: Option<SharedString>,
737}
738
739#[derive(Clone, Debug)]
740struct SelectionHistoryEntry {
741 selections: Arc<[Selection<Anchor>]>,
742 select_next_state: Option<SelectNextState>,
743 select_prev_state: Option<SelectNextState>,
744 add_selections_state: Option<AddSelectionsState>,
745}
746
747enum SelectionHistoryMode {
748 Normal,
749 Undoing,
750 Redoing,
751}
752
753#[derive(Clone, PartialEq, Eq, Hash)]
754struct HoveredCursor {
755 replica_id: u16,
756 selection_id: usize,
757}
758
759impl Default for SelectionHistoryMode {
760 fn default() -> Self {
761 Self::Normal
762 }
763}
764
765#[derive(Default)]
766struct SelectionHistory {
767 #[allow(clippy::type_complexity)]
768 selections_by_transaction:
769 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
770 mode: SelectionHistoryMode,
771 undo_stack: VecDeque<SelectionHistoryEntry>,
772 redo_stack: VecDeque<SelectionHistoryEntry>,
773}
774
775impl SelectionHistory {
776 fn insert_transaction(
777 &mut self,
778 transaction_id: TransactionId,
779 selections: Arc<[Selection<Anchor>]>,
780 ) {
781 self.selections_by_transaction
782 .insert(transaction_id, (selections, None));
783 }
784
785 #[allow(clippy::type_complexity)]
786 fn transaction(
787 &self,
788 transaction_id: TransactionId,
789 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
790 self.selections_by_transaction.get(&transaction_id)
791 }
792
793 #[allow(clippy::type_complexity)]
794 fn transaction_mut(
795 &mut self,
796 transaction_id: TransactionId,
797 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
798 self.selections_by_transaction.get_mut(&transaction_id)
799 }
800
801 fn push(&mut self, entry: SelectionHistoryEntry) {
802 if !entry.selections.is_empty() {
803 match self.mode {
804 SelectionHistoryMode::Normal => {
805 self.push_undo(entry);
806 self.redo_stack.clear();
807 }
808 SelectionHistoryMode::Undoing => self.push_redo(entry),
809 SelectionHistoryMode::Redoing => self.push_undo(entry),
810 }
811 }
812 }
813
814 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
815 if self
816 .undo_stack
817 .back()
818 .map_or(true, |e| e.selections != entry.selections)
819 {
820 self.undo_stack.push_back(entry);
821 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
822 self.undo_stack.pop_front();
823 }
824 }
825 }
826
827 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
828 if self
829 .redo_stack
830 .back()
831 .map_or(true, |e| e.selections != entry.selections)
832 {
833 self.redo_stack.push_back(entry);
834 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
835 self.redo_stack.pop_front();
836 }
837 }
838 }
839}
840
841struct RowHighlight {
842 index: usize,
843 range: Range<Anchor>,
844 color: Hsla,
845 should_autoscroll: bool,
846}
847
848#[derive(Clone, Debug)]
849struct AddSelectionsState {
850 above: bool,
851 stack: Vec<usize>,
852}
853
854#[derive(Clone)]
855struct SelectNextState {
856 query: AhoCorasick,
857 wordwise: bool,
858 done: bool,
859}
860
861impl std::fmt::Debug for SelectNextState {
862 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
863 f.debug_struct(std::any::type_name::<Self>())
864 .field("wordwise", &self.wordwise)
865 .field("done", &self.done)
866 .finish()
867 }
868}
869
870#[derive(Debug)]
871struct AutocloseRegion {
872 selection_id: usize,
873 range: Range<Anchor>,
874 pair: BracketPair,
875}
876
877#[derive(Debug)]
878struct SnippetState {
879 ranges: Vec<Vec<Range<Anchor>>>,
880 active_index: usize,
881}
882
883#[doc(hidden)]
884pub struct RenameState {
885 pub range: Range<Anchor>,
886 pub old_name: Arc<str>,
887 pub editor: View<Editor>,
888 block_id: CustomBlockId,
889}
890
891struct InvalidationStack<T>(Vec<T>);
892
893struct RegisteredInlineCompletionProvider {
894 provider: Arc<dyn InlineCompletionProviderHandle>,
895 _subscription: Subscription,
896}
897
898enum ContextMenu {
899 Completions(CompletionsMenu),
900 CodeActions(CodeActionsMenu),
901}
902
903impl ContextMenu {
904 fn select_first(
905 &mut self,
906 provider: Option<&dyn CompletionProvider>,
907 cx: &mut ViewContext<Editor>,
908 ) -> bool {
909 if self.visible() {
910 match self {
911 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
912 ContextMenu::CodeActions(menu) => menu.select_first(cx),
913 }
914 true
915 } else {
916 false
917 }
918 }
919
920 fn select_prev(
921 &mut self,
922 provider: Option<&dyn CompletionProvider>,
923 cx: &mut ViewContext<Editor>,
924 ) -> bool {
925 if self.visible() {
926 match self {
927 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
928 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
929 }
930 true
931 } else {
932 false
933 }
934 }
935
936 fn select_next(
937 &mut self,
938 provider: Option<&dyn CompletionProvider>,
939 cx: &mut ViewContext<Editor>,
940 ) -> bool {
941 if self.visible() {
942 match self {
943 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
944 ContextMenu::CodeActions(menu) => menu.select_next(cx),
945 }
946 true
947 } else {
948 false
949 }
950 }
951
952 fn select_last(
953 &mut self,
954 provider: Option<&dyn CompletionProvider>,
955 cx: &mut ViewContext<Editor>,
956 ) -> bool {
957 if self.visible() {
958 match self {
959 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
960 ContextMenu::CodeActions(menu) => menu.select_last(cx),
961 }
962 true
963 } else {
964 false
965 }
966 }
967
968 fn visible(&self) -> bool {
969 match self {
970 ContextMenu::Completions(menu) => menu.visible(),
971 ContextMenu::CodeActions(menu) => menu.visible(),
972 }
973 }
974
975 fn render(
976 &self,
977 cursor_position: DisplayPoint,
978 style: &EditorStyle,
979 max_height: Pixels,
980 workspace: Option<WeakView<Workspace>>,
981 cx: &mut ViewContext<Editor>,
982 ) -> (ContextMenuOrigin, AnyElement) {
983 match self {
984 ContextMenu::Completions(menu) => (
985 ContextMenuOrigin::EditorPoint(cursor_position),
986 menu.render(style, max_height, workspace, cx),
987 ),
988 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
989 }
990 }
991}
992
993enum ContextMenuOrigin {
994 EditorPoint(DisplayPoint),
995 GutterIndicator(DisplayRow),
996}
997
998#[derive(Clone)]
999struct CompletionsMenu {
1000 id: CompletionId,
1001 sort_completions: bool,
1002 initial_position: Anchor,
1003 buffer: Model<Buffer>,
1004 completions: Arc<RwLock<Box<[Completion]>>>,
1005 match_candidates: Arc<[StringMatchCandidate]>,
1006 matches: Arc<[StringMatch]>,
1007 selected_item: usize,
1008 scroll_handle: UniformListScrollHandle,
1009 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
1010}
1011
1012impl CompletionsMenu {
1013 fn select_first(
1014 &mut self,
1015 provider: Option<&dyn CompletionProvider>,
1016 cx: &mut ViewContext<Editor>,
1017 ) {
1018 self.selected_item = 0;
1019 self.scroll_handle.scroll_to_item(self.selected_item);
1020 self.attempt_resolve_selected_completion_documentation(provider, cx);
1021 cx.notify();
1022 }
1023
1024 fn select_prev(
1025 &mut self,
1026 provider: Option<&dyn CompletionProvider>,
1027 cx: &mut ViewContext<Editor>,
1028 ) {
1029 if self.selected_item > 0 {
1030 self.selected_item -= 1;
1031 } else {
1032 self.selected_item = self.matches.len() - 1;
1033 }
1034 self.scroll_handle.scroll_to_item(self.selected_item);
1035 self.attempt_resolve_selected_completion_documentation(provider, cx);
1036 cx.notify();
1037 }
1038
1039 fn select_next(
1040 &mut self,
1041 provider: Option<&dyn CompletionProvider>,
1042 cx: &mut ViewContext<Editor>,
1043 ) {
1044 if self.selected_item + 1 < self.matches.len() {
1045 self.selected_item += 1;
1046 } else {
1047 self.selected_item = 0;
1048 }
1049 self.scroll_handle.scroll_to_item(self.selected_item);
1050 self.attempt_resolve_selected_completion_documentation(provider, cx);
1051 cx.notify();
1052 }
1053
1054 fn select_last(
1055 &mut self,
1056 provider: Option<&dyn CompletionProvider>,
1057 cx: &mut ViewContext<Editor>,
1058 ) {
1059 self.selected_item = self.matches.len() - 1;
1060 self.scroll_handle.scroll_to_item(self.selected_item);
1061 self.attempt_resolve_selected_completion_documentation(provider, cx);
1062 cx.notify();
1063 }
1064
1065 fn pre_resolve_completion_documentation(
1066 buffer: Model<Buffer>,
1067 completions: Arc<RwLock<Box<[Completion]>>>,
1068 matches: Arc<[StringMatch]>,
1069 editor: &Editor,
1070 cx: &mut ViewContext<Editor>,
1071 ) -> Task<()> {
1072 let settings = EditorSettings::get_global(cx);
1073 if !settings.show_completion_documentation {
1074 return Task::ready(());
1075 }
1076
1077 let Some(provider) = editor.completion_provider.as_ref() else {
1078 return Task::ready(());
1079 };
1080
1081 let resolve_task = provider.resolve_completions(
1082 buffer,
1083 matches.iter().map(|m| m.candidate_id).collect(),
1084 completions.clone(),
1085 cx,
1086 );
1087
1088 cx.spawn(move |this, mut cx| async move {
1089 if let Some(true) = resolve_task.await.log_err() {
1090 this.update(&mut cx, |_, cx| cx.notify()).ok();
1091 }
1092 })
1093 }
1094
1095 fn attempt_resolve_selected_completion_documentation(
1096 &mut self,
1097 provider: Option<&dyn CompletionProvider>,
1098 cx: &mut ViewContext<Editor>,
1099 ) {
1100 let settings = EditorSettings::get_global(cx);
1101 if !settings.show_completion_documentation {
1102 return;
1103 }
1104
1105 let completion_index = self.matches[self.selected_item].candidate_id;
1106 let Some(provider) = provider else {
1107 return;
1108 };
1109
1110 let resolve_task = provider.resolve_completions(
1111 self.buffer.clone(),
1112 vec![completion_index],
1113 self.completions.clone(),
1114 cx,
1115 );
1116
1117 let delay_ms =
1118 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1119 let delay = Duration::from_millis(delay_ms);
1120
1121 self.selected_completion_documentation_resolve_debounce
1122 .lock()
1123 .fire_new(delay, cx, |_, cx| {
1124 cx.spawn(move |this, mut cx| async move {
1125 if let Some(true) = resolve_task.await.log_err() {
1126 this.update(&mut cx, |_, cx| cx.notify()).ok();
1127 }
1128 })
1129 });
1130 }
1131
1132 fn visible(&self) -> bool {
1133 !self.matches.is_empty()
1134 }
1135
1136 fn render(
1137 &self,
1138 style: &EditorStyle,
1139 max_height: Pixels,
1140 workspace: Option<WeakView<Workspace>>,
1141 cx: &mut ViewContext<Editor>,
1142 ) -> AnyElement {
1143 let settings = EditorSettings::get_global(cx);
1144 let show_completion_documentation = settings.show_completion_documentation;
1145
1146 let widest_completion_ix = self
1147 .matches
1148 .iter()
1149 .enumerate()
1150 .max_by_key(|(_, mat)| {
1151 let completions = self.completions.read();
1152 let completion = &completions[mat.candidate_id];
1153 let documentation = &completion.documentation;
1154
1155 let mut len = completion.label.text.chars().count();
1156 if let Some(Documentation::SingleLine(text)) = documentation {
1157 if show_completion_documentation {
1158 len += text.chars().count();
1159 }
1160 }
1161
1162 len
1163 })
1164 .map(|(ix, _)| ix);
1165
1166 let completions = self.completions.clone();
1167 let matches = self.matches.clone();
1168 let selected_item = self.selected_item;
1169 let style = style.clone();
1170
1171 let multiline_docs = if show_completion_documentation {
1172 let mat = &self.matches[selected_item];
1173 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1174 Some(Documentation::MultiLinePlainText(text)) => {
1175 Some(div().child(SharedString::from(text.clone())))
1176 }
1177 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1178 Some(div().child(render_parsed_markdown(
1179 "completions_markdown",
1180 parsed,
1181 &style,
1182 workspace,
1183 cx,
1184 )))
1185 }
1186 _ => None,
1187 };
1188 multiline_docs.map(|div| {
1189 div.id("multiline_docs")
1190 .max_h(max_height)
1191 .flex_1()
1192 .px_1p5()
1193 .py_1()
1194 .min_w(px(260.))
1195 .max_w(px(640.))
1196 .w(px(500.))
1197 .overflow_y_scroll()
1198 .occlude()
1199 })
1200 } else {
1201 None
1202 };
1203
1204 let list = uniform_list(
1205 cx.view().clone(),
1206 "completions",
1207 matches.len(),
1208 move |_editor, range, cx| {
1209 let start_ix = range.start;
1210 let completions_guard = completions.read();
1211
1212 matches[range]
1213 .iter()
1214 .enumerate()
1215 .map(|(ix, mat)| {
1216 let item_ix = start_ix + ix;
1217 let candidate_id = mat.candidate_id;
1218 let completion = &completions_guard[candidate_id];
1219
1220 let documentation = if show_completion_documentation {
1221 &completion.documentation
1222 } else {
1223 &None
1224 };
1225
1226 let highlights = gpui::combine_highlights(
1227 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1228 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1229 |(range, mut highlight)| {
1230 // Ignore font weight for syntax highlighting, as we'll use it
1231 // for fuzzy matches.
1232 highlight.font_weight = None;
1233
1234 if completion.lsp_completion.deprecated.unwrap_or(false) {
1235 highlight.strikethrough = Some(StrikethroughStyle {
1236 thickness: 1.0.into(),
1237 ..Default::default()
1238 });
1239 highlight.color = Some(cx.theme().colors().text_muted);
1240 }
1241
1242 (range, highlight)
1243 },
1244 ),
1245 );
1246 let completion_label = StyledText::new(completion.label.text.clone())
1247 .with_highlights(&style.text, highlights);
1248 let documentation_label =
1249 if let Some(Documentation::SingleLine(text)) = documentation {
1250 if text.trim().is_empty() {
1251 None
1252 } else {
1253 Some(
1254 Label::new(text.clone())
1255 .ml_4()
1256 .size(LabelSize::Small)
1257 .color(Color::Muted),
1258 )
1259 }
1260 } else {
1261 None
1262 };
1263
1264 let color_swatch = completion
1265 .color()
1266 .map(|color| div().size_4().bg(color).rounded_sm());
1267
1268 div().min_w(px(220.)).max_w(px(540.)).child(
1269 ListItem::new(mat.candidate_id)
1270 .inset(true)
1271 .selected(item_ix == selected_item)
1272 .on_click(cx.listener(move |editor, _event, cx| {
1273 cx.stop_propagation();
1274 if let Some(task) = editor.confirm_completion(
1275 &ConfirmCompletion {
1276 item_ix: Some(item_ix),
1277 },
1278 cx,
1279 ) {
1280 task.detach_and_log_err(cx)
1281 }
1282 }))
1283 .start_slot::<Div>(color_swatch)
1284 .child(h_flex().overflow_hidden().child(completion_label))
1285 .end_slot::<Label>(documentation_label),
1286 )
1287 })
1288 .collect()
1289 },
1290 )
1291 .occlude()
1292 .max_h(max_height)
1293 .track_scroll(self.scroll_handle.clone())
1294 .with_width_from_item(widest_completion_ix)
1295 .with_sizing_behavior(ListSizingBehavior::Infer);
1296
1297 Popover::new()
1298 .child(list)
1299 .when_some(multiline_docs, |popover, multiline_docs| {
1300 popover.aside(multiline_docs)
1301 })
1302 .into_any_element()
1303 }
1304
1305 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1306 let mut matches = if let Some(query) = query {
1307 fuzzy::match_strings(
1308 &self.match_candidates,
1309 query,
1310 query.chars().any(|c| c.is_uppercase()),
1311 100,
1312 &Default::default(),
1313 executor,
1314 )
1315 .await
1316 } else {
1317 self.match_candidates
1318 .iter()
1319 .enumerate()
1320 .map(|(candidate_id, candidate)| StringMatch {
1321 candidate_id,
1322 score: Default::default(),
1323 positions: Default::default(),
1324 string: candidate.string.clone(),
1325 })
1326 .collect()
1327 };
1328
1329 // Remove all candidates where the query's start does not match the start of any word in the candidate
1330 if let Some(query) = query {
1331 if let Some(query_start) = query.chars().next() {
1332 matches.retain(|string_match| {
1333 split_words(&string_match.string).any(|word| {
1334 // Check that the first codepoint of the word as lowercase matches the first
1335 // codepoint of the query as lowercase
1336 word.chars()
1337 .flat_map(|codepoint| codepoint.to_lowercase())
1338 .zip(query_start.to_lowercase())
1339 .all(|(word_cp, query_cp)| word_cp == query_cp)
1340 })
1341 });
1342 }
1343 }
1344
1345 let completions = self.completions.read();
1346 if self.sort_completions {
1347 matches.sort_unstable_by_key(|mat| {
1348 // We do want to strike a balance here between what the language server tells us
1349 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1350 // `Creat` and there is a local variable called `CreateComponent`).
1351 // So what we do is: we bucket all matches into two buckets
1352 // - Strong matches
1353 // - Weak matches
1354 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1355 // and the Weak matches are the rest.
1356 //
1357 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1358 // matches, we prefer language-server sort_text first.
1359 //
1360 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1361 // Rest of the matches(weak) can be sorted as language-server expects.
1362
1363 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1364 enum MatchScore<'a> {
1365 Strong {
1366 score: Reverse<OrderedFloat<f64>>,
1367 sort_text: Option<&'a str>,
1368 sort_key: (usize, &'a str),
1369 },
1370 Weak {
1371 sort_text: Option<&'a str>,
1372 score: Reverse<OrderedFloat<f64>>,
1373 sort_key: (usize, &'a str),
1374 },
1375 }
1376
1377 let completion = &completions[mat.candidate_id];
1378 let sort_key = completion.sort_key();
1379 let sort_text = completion.lsp_completion.sort_text.as_deref();
1380 let score = Reverse(OrderedFloat(mat.score));
1381
1382 if mat.score >= 0.2 {
1383 MatchScore::Strong {
1384 score,
1385 sort_text,
1386 sort_key,
1387 }
1388 } else {
1389 MatchScore::Weak {
1390 sort_text,
1391 score,
1392 sort_key,
1393 }
1394 }
1395 });
1396 }
1397
1398 for mat in &mut matches {
1399 let completion = &completions[mat.candidate_id];
1400 mat.string.clone_from(&completion.label.text);
1401 for position in &mut mat.positions {
1402 *position += completion.label.filter_range.start;
1403 }
1404 }
1405 drop(completions);
1406
1407 self.matches = matches.into();
1408 self.selected_item = 0;
1409 }
1410}
1411
1412struct AvailableCodeAction {
1413 excerpt_id: ExcerptId,
1414 action: CodeAction,
1415 provider: Arc<dyn CodeActionProvider>,
1416}
1417
1418#[derive(Clone)]
1419struct CodeActionContents {
1420 tasks: Option<Arc<ResolvedTasks>>,
1421 actions: Option<Arc<[AvailableCodeAction]>>,
1422}
1423
1424impl CodeActionContents {
1425 fn len(&self) -> usize {
1426 match (&self.tasks, &self.actions) {
1427 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1428 (Some(tasks), None) => tasks.templates.len(),
1429 (None, Some(actions)) => actions.len(),
1430 (None, None) => 0,
1431 }
1432 }
1433
1434 fn is_empty(&self) -> bool {
1435 match (&self.tasks, &self.actions) {
1436 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1437 (Some(tasks), None) => tasks.templates.is_empty(),
1438 (None, Some(actions)) => actions.is_empty(),
1439 (None, None) => true,
1440 }
1441 }
1442
1443 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1444 self.tasks
1445 .iter()
1446 .flat_map(|tasks| {
1447 tasks
1448 .templates
1449 .iter()
1450 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1451 })
1452 .chain(self.actions.iter().flat_map(|actions| {
1453 actions.iter().map(|available| CodeActionsItem::CodeAction {
1454 excerpt_id: available.excerpt_id,
1455 action: available.action.clone(),
1456 provider: available.provider.clone(),
1457 })
1458 }))
1459 }
1460 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1461 match (&self.tasks, &self.actions) {
1462 (Some(tasks), Some(actions)) => {
1463 if index < tasks.templates.len() {
1464 tasks
1465 .templates
1466 .get(index)
1467 .cloned()
1468 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1469 } else {
1470 actions.get(index - tasks.templates.len()).map(|available| {
1471 CodeActionsItem::CodeAction {
1472 excerpt_id: available.excerpt_id,
1473 action: available.action.clone(),
1474 provider: available.provider.clone(),
1475 }
1476 })
1477 }
1478 }
1479 (Some(tasks), None) => tasks
1480 .templates
1481 .get(index)
1482 .cloned()
1483 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1484 (None, Some(actions)) => {
1485 actions
1486 .get(index)
1487 .map(|available| CodeActionsItem::CodeAction {
1488 excerpt_id: available.excerpt_id,
1489 action: available.action.clone(),
1490 provider: available.provider.clone(),
1491 })
1492 }
1493 (None, None) => None,
1494 }
1495 }
1496}
1497
1498#[allow(clippy::large_enum_variant)]
1499#[derive(Clone)]
1500enum CodeActionsItem {
1501 Task(TaskSourceKind, ResolvedTask),
1502 CodeAction {
1503 excerpt_id: ExcerptId,
1504 action: CodeAction,
1505 provider: Arc<dyn CodeActionProvider>,
1506 },
1507}
1508
1509impl CodeActionsItem {
1510 fn as_task(&self) -> Option<&ResolvedTask> {
1511 let Self::Task(_, task) = self else {
1512 return None;
1513 };
1514 Some(task)
1515 }
1516 fn as_code_action(&self) -> Option<&CodeAction> {
1517 let Self::CodeAction { action, .. } = self else {
1518 return None;
1519 };
1520 Some(action)
1521 }
1522 fn label(&self) -> String {
1523 match self {
1524 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1525 Self::Task(_, task) => task.resolved_label.clone(),
1526 }
1527 }
1528}
1529
1530struct CodeActionsMenu {
1531 actions: CodeActionContents,
1532 buffer: Model<Buffer>,
1533 selected_item: usize,
1534 scroll_handle: UniformListScrollHandle,
1535 deployed_from_indicator: Option<DisplayRow>,
1536}
1537
1538impl CodeActionsMenu {
1539 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1540 self.selected_item = 0;
1541 self.scroll_handle.scroll_to_item(self.selected_item);
1542 cx.notify()
1543 }
1544
1545 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1546 if self.selected_item > 0 {
1547 self.selected_item -= 1;
1548 } else {
1549 self.selected_item = self.actions.len() - 1;
1550 }
1551 self.scroll_handle.scroll_to_item(self.selected_item);
1552 cx.notify();
1553 }
1554
1555 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1556 if self.selected_item + 1 < self.actions.len() {
1557 self.selected_item += 1;
1558 } else {
1559 self.selected_item = 0;
1560 }
1561 self.scroll_handle.scroll_to_item(self.selected_item);
1562 cx.notify();
1563 }
1564
1565 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1566 self.selected_item = self.actions.len() - 1;
1567 self.scroll_handle.scroll_to_item(self.selected_item);
1568 cx.notify()
1569 }
1570
1571 fn visible(&self) -> bool {
1572 !self.actions.is_empty()
1573 }
1574
1575 fn render(
1576 &self,
1577 cursor_position: DisplayPoint,
1578 _style: &EditorStyle,
1579 max_height: Pixels,
1580 cx: &mut ViewContext<Editor>,
1581 ) -> (ContextMenuOrigin, AnyElement) {
1582 let actions = self.actions.clone();
1583 let selected_item = self.selected_item;
1584 let element = uniform_list(
1585 cx.view().clone(),
1586 "code_actions_menu",
1587 self.actions.len(),
1588 move |_this, range, cx| {
1589 actions
1590 .iter()
1591 .skip(range.start)
1592 .take(range.end - range.start)
1593 .enumerate()
1594 .map(|(ix, action)| {
1595 let item_ix = range.start + ix;
1596 let selected = selected_item == item_ix;
1597 let colors = cx.theme().colors();
1598 div()
1599 .px_1()
1600 .rounded_md()
1601 .text_color(colors.text)
1602 .when(selected, |style| {
1603 style
1604 .bg(colors.element_active)
1605 .text_color(colors.text_accent)
1606 })
1607 .hover(|style| {
1608 style
1609 .bg(colors.element_hover)
1610 .text_color(colors.text_accent)
1611 })
1612 .whitespace_nowrap()
1613 .when_some(action.as_code_action(), |this, action| {
1614 this.on_mouse_down(
1615 MouseButton::Left,
1616 cx.listener(move |editor, _, cx| {
1617 cx.stop_propagation();
1618 if let Some(task) = editor.confirm_code_action(
1619 &ConfirmCodeAction {
1620 item_ix: Some(item_ix),
1621 },
1622 cx,
1623 ) {
1624 task.detach_and_log_err(cx)
1625 }
1626 }),
1627 )
1628 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1629 .child(SharedString::from(action.lsp_action.title.clone()))
1630 })
1631 .when_some(action.as_task(), |this, task| {
1632 this.on_mouse_down(
1633 MouseButton::Left,
1634 cx.listener(move |editor, _, cx| {
1635 cx.stop_propagation();
1636 if let Some(task) = editor.confirm_code_action(
1637 &ConfirmCodeAction {
1638 item_ix: Some(item_ix),
1639 },
1640 cx,
1641 ) {
1642 task.detach_and_log_err(cx)
1643 }
1644 }),
1645 )
1646 .child(SharedString::from(task.resolved_label.clone()))
1647 })
1648 })
1649 .collect()
1650 },
1651 )
1652 .elevation_1(cx)
1653 .p_1()
1654 .max_h(max_height)
1655 .occlude()
1656 .track_scroll(self.scroll_handle.clone())
1657 .with_width_from_item(
1658 self.actions
1659 .iter()
1660 .enumerate()
1661 .max_by_key(|(_, action)| match action {
1662 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1663 CodeActionsItem::CodeAction { action, .. } => {
1664 action.lsp_action.title.chars().count()
1665 }
1666 })
1667 .map(|(ix, _)| ix),
1668 )
1669 .with_sizing_behavior(ListSizingBehavior::Infer)
1670 .into_any_element();
1671
1672 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1673 ContextMenuOrigin::GutterIndicator(row)
1674 } else {
1675 ContextMenuOrigin::EditorPoint(cursor_position)
1676 };
1677
1678 (cursor_position, element)
1679 }
1680}
1681
1682#[derive(Debug)]
1683struct ActiveDiagnosticGroup {
1684 primary_range: Range<Anchor>,
1685 primary_message: String,
1686 group_id: usize,
1687 blocks: HashMap<CustomBlockId, Diagnostic>,
1688 is_valid: bool,
1689}
1690
1691#[derive(Serialize, Deserialize, Clone, Debug)]
1692pub struct ClipboardSelection {
1693 pub len: usize,
1694 pub is_entire_line: bool,
1695 pub first_line_indent: u32,
1696}
1697
1698#[derive(Debug)]
1699pub(crate) struct NavigationData {
1700 cursor_anchor: Anchor,
1701 cursor_position: Point,
1702 scroll_anchor: ScrollAnchor,
1703 scroll_top_row: u32,
1704}
1705
1706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1707pub enum GotoDefinitionKind {
1708 Symbol,
1709 Declaration,
1710 Type,
1711 Implementation,
1712}
1713
1714#[derive(Debug, Clone)]
1715enum InlayHintRefreshReason {
1716 Toggle(bool),
1717 SettingsChange(InlayHintSettings),
1718 NewLinesShown,
1719 BufferEdited(HashSet<Arc<Language>>),
1720 RefreshRequested,
1721 ExcerptsRemoved(Vec<ExcerptId>),
1722}
1723
1724impl InlayHintRefreshReason {
1725 fn description(&self) -> &'static str {
1726 match self {
1727 Self::Toggle(_) => "toggle",
1728 Self::SettingsChange(_) => "settings change",
1729 Self::NewLinesShown => "new lines shown",
1730 Self::BufferEdited(_) => "buffer edited",
1731 Self::RefreshRequested => "refresh requested",
1732 Self::ExcerptsRemoved(_) => "excerpts removed",
1733 }
1734 }
1735}
1736
1737pub(crate) struct FocusedBlock {
1738 id: BlockId,
1739 focus_handle: WeakFocusHandle,
1740}
1741
1742impl Editor {
1743 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1744 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1745 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1746 Self::new(
1747 EditorMode::SingleLine { auto_width: false },
1748 buffer,
1749 None,
1750 false,
1751 cx,
1752 )
1753 }
1754
1755 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1756 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1757 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1758 Self::new(EditorMode::Full, buffer, None, false, cx)
1759 }
1760
1761 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1762 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1763 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1764 Self::new(
1765 EditorMode::SingleLine { auto_width: true },
1766 buffer,
1767 None,
1768 false,
1769 cx,
1770 )
1771 }
1772
1773 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1774 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1775 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1776 Self::new(
1777 EditorMode::AutoHeight { max_lines },
1778 buffer,
1779 None,
1780 false,
1781 cx,
1782 )
1783 }
1784
1785 pub fn for_buffer(
1786 buffer: Model<Buffer>,
1787 project: Option<Model<Project>>,
1788 cx: &mut ViewContext<Self>,
1789 ) -> Self {
1790 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1791 Self::new(EditorMode::Full, buffer, project, false, cx)
1792 }
1793
1794 pub fn for_multibuffer(
1795 buffer: Model<MultiBuffer>,
1796 project: Option<Model<Project>>,
1797 show_excerpt_controls: bool,
1798 cx: &mut ViewContext<Self>,
1799 ) -> Self {
1800 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1801 }
1802
1803 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1804 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1805 let mut clone = Self::new(
1806 self.mode,
1807 self.buffer.clone(),
1808 self.project.clone(),
1809 show_excerpt_controls,
1810 cx,
1811 );
1812 self.display_map.update(cx, |display_map, cx| {
1813 let snapshot = display_map.snapshot(cx);
1814 clone.display_map.update(cx, |display_map, cx| {
1815 display_map.set_state(&snapshot, cx);
1816 });
1817 });
1818 clone.selections.clone_state(&self.selections);
1819 clone.scroll_manager.clone_state(&self.scroll_manager);
1820 clone.searchable = self.searchable;
1821 clone
1822 }
1823
1824 pub fn new(
1825 mode: EditorMode,
1826 buffer: Model<MultiBuffer>,
1827 project: Option<Model<Project>>,
1828 show_excerpt_controls: bool,
1829 cx: &mut ViewContext<Self>,
1830 ) -> Self {
1831 let style = cx.text_style();
1832 let font_size = style.font_size.to_pixels(cx.rem_size());
1833 let editor = cx.view().downgrade();
1834 let fold_placeholder = FoldPlaceholder {
1835 constrain_width: true,
1836 render: Arc::new(move |fold_id, fold_range, cx| {
1837 let editor = editor.clone();
1838 div()
1839 .id(fold_id)
1840 .bg(cx.theme().colors().ghost_element_background)
1841 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1842 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1843 .rounded_sm()
1844 .size_full()
1845 .cursor_pointer()
1846 .child("⋯")
1847 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1848 .on_click(move |_, cx| {
1849 editor
1850 .update(cx, |editor, cx| {
1851 editor.unfold_ranges(
1852 &[fold_range.start..fold_range.end],
1853 true,
1854 false,
1855 cx,
1856 );
1857 cx.stop_propagation();
1858 })
1859 .ok();
1860 })
1861 .into_any()
1862 }),
1863 merge_adjacent: true,
1864 ..Default::default()
1865 };
1866 let display_map = cx.new_model(|cx| {
1867 DisplayMap::new(
1868 buffer.clone(),
1869 style.font(),
1870 font_size,
1871 None,
1872 show_excerpt_controls,
1873 FILE_HEADER_HEIGHT,
1874 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1875 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1876 fold_placeholder,
1877 cx,
1878 )
1879 });
1880
1881 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1882
1883 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1884
1885 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1886 .then(|| language_settings::SoftWrap::None);
1887
1888 let mut project_subscriptions = Vec::new();
1889 if mode == EditorMode::Full {
1890 if let Some(project) = project.as_ref() {
1891 if buffer.read(cx).is_singleton() {
1892 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1893 cx.emit(EditorEvent::TitleChanged);
1894 }));
1895 }
1896 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1897 if let project::Event::RefreshInlayHints = event {
1898 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1899 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1900 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1901 let focus_handle = editor.focus_handle(cx);
1902 if focus_handle.is_focused(cx) {
1903 let snapshot = buffer.read(cx).snapshot();
1904 for (range, snippet) in snippet_edits {
1905 let editor_range =
1906 language::range_from_lsp(*range).to_offset(&snapshot);
1907 editor
1908 .insert_snippet(&[editor_range], snippet.clone(), cx)
1909 .ok();
1910 }
1911 }
1912 }
1913 }
1914 }));
1915 if let Some(task_inventory) = project
1916 .read(cx)
1917 .task_store()
1918 .read(cx)
1919 .task_inventory()
1920 .cloned()
1921 {
1922 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1923 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1924 }));
1925 }
1926 }
1927 }
1928
1929 let inlay_hint_settings = inlay_hint_settings(
1930 selections.newest_anchor().head(),
1931 &buffer.read(cx).snapshot(cx),
1932 cx,
1933 );
1934 let focus_handle = cx.focus_handle();
1935 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1936 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1937 .detach();
1938 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1939 .detach();
1940 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1941
1942 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1943 Some(false)
1944 } else {
1945 None
1946 };
1947
1948 let mut code_action_providers = Vec::new();
1949 if let Some(project) = project.clone() {
1950 code_action_providers.push(Arc::new(project) as Arc<_>);
1951 }
1952
1953 let mut this = Self {
1954 focus_handle,
1955 show_cursor_when_unfocused: false,
1956 last_focused_descendant: None,
1957 buffer: buffer.clone(),
1958 display_map: display_map.clone(),
1959 selections,
1960 scroll_manager: ScrollManager::new(cx),
1961 columnar_selection_tail: None,
1962 add_selections_state: None,
1963 select_next_state: None,
1964 select_prev_state: None,
1965 selection_history: Default::default(),
1966 autoclose_regions: Default::default(),
1967 snippet_stack: Default::default(),
1968 select_larger_syntax_node_stack: Vec::new(),
1969 ime_transaction: Default::default(),
1970 active_diagnostics: None,
1971 soft_wrap_mode_override,
1972 completion_provider: project.clone().map(|project| Box::new(project) as _),
1973 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1974 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1975 project,
1976 blink_manager: blink_manager.clone(),
1977 show_local_selections: true,
1978 mode,
1979 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1980 show_gutter: mode == EditorMode::Full,
1981 show_line_numbers: None,
1982 use_relative_line_numbers: None,
1983 show_git_diff_gutter: None,
1984 show_code_actions: None,
1985 show_runnables: None,
1986 show_wrap_guides: None,
1987 show_indent_guides,
1988 placeholder_text: None,
1989 highlight_order: 0,
1990 highlighted_rows: HashMap::default(),
1991 background_highlights: Default::default(),
1992 gutter_highlights: TreeMap::default(),
1993 scrollbar_marker_state: ScrollbarMarkerState::default(),
1994 active_indent_guides_state: ActiveIndentGuidesState::default(),
1995 nav_history: None,
1996 context_menu: RwLock::new(None),
1997 mouse_context_menu: None,
1998 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1999 completion_tasks: Default::default(),
2000 signature_help_state: SignatureHelpState::default(),
2001 auto_signature_help: None,
2002 find_all_references_task_sources: Vec::new(),
2003 next_completion_id: 0,
2004 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2005 next_inlay_id: 0,
2006 code_action_providers,
2007 available_code_actions: Default::default(),
2008 code_actions_task: Default::default(),
2009 document_highlights_task: Default::default(),
2010 linked_editing_range_task: Default::default(),
2011 pending_rename: Default::default(),
2012 searchable: true,
2013 cursor_shape: EditorSettings::get_global(cx)
2014 .cursor_shape
2015 .unwrap_or_default(),
2016 current_line_highlight: None,
2017 autoindent_mode: Some(AutoindentMode::EachLine),
2018 collapse_matches: false,
2019 workspace: None,
2020 input_enabled: true,
2021 use_modal_editing: mode == EditorMode::Full,
2022 read_only: false,
2023 use_autoclose: true,
2024 use_auto_surround: true,
2025 auto_replace_emoji_shortcode: false,
2026 leader_peer_id: None,
2027 remote_id: None,
2028 hover_state: Default::default(),
2029 hovered_link_state: Default::default(),
2030 inline_completion_provider: None,
2031 active_inline_completion: None,
2032 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2033 expanded_hunks: ExpandedHunks::default(),
2034 gutter_hovered: false,
2035 pixel_position_of_newest_cursor: None,
2036 last_bounds: None,
2037 expect_bounds_change: None,
2038 gutter_dimensions: GutterDimensions::default(),
2039 style: None,
2040 show_cursor_names: false,
2041 hovered_cursors: Default::default(),
2042 next_editor_action_id: EditorActionId::default(),
2043 editor_actions: Rc::default(),
2044 show_inline_completions_override: None,
2045 enable_inline_completions: true,
2046 custom_context_menu: None,
2047 show_git_blame_gutter: false,
2048 show_git_blame_inline: false,
2049 show_selection_menu: None,
2050 show_git_blame_inline_delay_task: None,
2051 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2052 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2053 .session
2054 .restore_unsaved_buffers,
2055 blame: None,
2056 blame_subscription: None,
2057 tasks: Default::default(),
2058 _subscriptions: vec![
2059 cx.observe(&buffer, Self::on_buffer_changed),
2060 cx.subscribe(&buffer, Self::on_buffer_event),
2061 cx.observe(&display_map, Self::on_display_map_changed),
2062 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2063 cx.observe_global::<SettingsStore>(Self::settings_changed),
2064 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2065 cx.observe_window_activation(|editor, cx| {
2066 let active = cx.is_window_active();
2067 editor.blink_manager.update(cx, |blink_manager, cx| {
2068 if active {
2069 blink_manager.enable(cx);
2070 } else {
2071 blink_manager.disable(cx);
2072 }
2073 });
2074 }),
2075 ],
2076 tasks_update_task: None,
2077 linked_edit_ranges: Default::default(),
2078 previous_search_ranges: None,
2079 breadcrumb_header: None,
2080 focused_block: None,
2081 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2082 addons: HashMap::default(),
2083 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2084 text_style_refinement: None,
2085 };
2086 this.tasks_update_task = Some(this.refresh_runnables(cx));
2087 this._subscriptions.extend(project_subscriptions);
2088
2089 this.end_selection(cx);
2090 this.scroll_manager.show_scrollbar(cx);
2091
2092 if mode == EditorMode::Full {
2093 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2094 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2095
2096 if this.git_blame_inline_enabled {
2097 this.git_blame_inline_enabled = true;
2098 this.start_git_blame_inline(false, cx);
2099 }
2100 }
2101
2102 this.report_editor_event("open", None, cx);
2103 this
2104 }
2105
2106 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2107 self.mouse_context_menu
2108 .as_ref()
2109 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2110 }
2111
2112 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2113 let mut key_context = KeyContext::new_with_defaults();
2114 key_context.add("Editor");
2115 let mode = match self.mode {
2116 EditorMode::SingleLine { .. } => "single_line",
2117 EditorMode::AutoHeight { .. } => "auto_height",
2118 EditorMode::Full => "full",
2119 };
2120
2121 if EditorSettings::jupyter_enabled(cx) {
2122 key_context.add("jupyter");
2123 }
2124
2125 key_context.set("mode", mode);
2126 if self.pending_rename.is_some() {
2127 key_context.add("renaming");
2128 }
2129 if self.context_menu_visible() {
2130 match self.context_menu.read().as_ref() {
2131 Some(ContextMenu::Completions(_)) => {
2132 key_context.add("menu");
2133 key_context.add("showing_completions")
2134 }
2135 Some(ContextMenu::CodeActions(_)) => {
2136 key_context.add("menu");
2137 key_context.add("showing_code_actions")
2138 }
2139 None => {}
2140 }
2141 }
2142
2143 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2144 if !self.focus_handle(cx).contains_focused(cx)
2145 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2146 {
2147 for addon in self.addons.values() {
2148 addon.extend_key_context(&mut key_context, cx)
2149 }
2150 }
2151
2152 if let Some(extension) = self
2153 .buffer
2154 .read(cx)
2155 .as_singleton()
2156 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2157 {
2158 key_context.set("extension", extension.to_string());
2159 }
2160
2161 if self.has_active_inline_completion(cx) {
2162 key_context.add("copilot_suggestion");
2163 key_context.add("inline_completion");
2164 }
2165
2166 key_context
2167 }
2168
2169 pub fn new_file(
2170 workspace: &mut Workspace,
2171 _: &workspace::NewFile,
2172 cx: &mut ViewContext<Workspace>,
2173 ) {
2174 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2175 "Failed to create buffer",
2176 cx,
2177 |e, _| match e.error_code() {
2178 ErrorCode::RemoteUpgradeRequired => Some(format!(
2179 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2180 e.error_tag("required").unwrap_or("the latest version")
2181 )),
2182 _ => None,
2183 },
2184 );
2185 }
2186
2187 pub fn new_in_workspace(
2188 workspace: &mut Workspace,
2189 cx: &mut ViewContext<Workspace>,
2190 ) -> Task<Result<View<Editor>>> {
2191 let project = workspace.project().clone();
2192 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2193
2194 cx.spawn(|workspace, mut cx| async move {
2195 let buffer = create.await?;
2196 workspace.update(&mut cx, |workspace, cx| {
2197 let editor =
2198 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2199 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2200 editor
2201 })
2202 })
2203 }
2204
2205 fn new_file_vertical(
2206 workspace: &mut Workspace,
2207 _: &workspace::NewFileSplitVertical,
2208 cx: &mut ViewContext<Workspace>,
2209 ) {
2210 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2211 }
2212
2213 fn new_file_horizontal(
2214 workspace: &mut Workspace,
2215 _: &workspace::NewFileSplitHorizontal,
2216 cx: &mut ViewContext<Workspace>,
2217 ) {
2218 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2219 }
2220
2221 fn new_file_in_direction(
2222 workspace: &mut Workspace,
2223 direction: SplitDirection,
2224 cx: &mut ViewContext<Workspace>,
2225 ) {
2226 let project = workspace.project().clone();
2227 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2228
2229 cx.spawn(|workspace, mut cx| async move {
2230 let buffer = create.await?;
2231 workspace.update(&mut cx, move |workspace, cx| {
2232 workspace.split_item(
2233 direction,
2234 Box::new(
2235 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2236 ),
2237 cx,
2238 )
2239 })?;
2240 anyhow::Ok(())
2241 })
2242 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2243 ErrorCode::RemoteUpgradeRequired => Some(format!(
2244 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2245 e.error_tag("required").unwrap_or("the latest version")
2246 )),
2247 _ => None,
2248 });
2249 }
2250
2251 pub fn leader_peer_id(&self) -> Option<PeerId> {
2252 self.leader_peer_id
2253 }
2254
2255 pub fn buffer(&self) -> &Model<MultiBuffer> {
2256 &self.buffer
2257 }
2258
2259 pub fn workspace(&self) -> Option<View<Workspace>> {
2260 self.workspace.as_ref()?.0.upgrade()
2261 }
2262
2263 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2264 self.buffer().read(cx).title(cx)
2265 }
2266
2267 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2268 let git_blame_gutter_max_author_length = self
2269 .render_git_blame_gutter(cx)
2270 .then(|| {
2271 if let Some(blame) = self.blame.as_ref() {
2272 let max_author_length =
2273 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2274 Some(max_author_length)
2275 } else {
2276 None
2277 }
2278 })
2279 .flatten();
2280
2281 EditorSnapshot {
2282 mode: self.mode,
2283 show_gutter: self.show_gutter,
2284 show_line_numbers: self.show_line_numbers,
2285 show_git_diff_gutter: self.show_git_diff_gutter,
2286 show_code_actions: self.show_code_actions,
2287 show_runnables: self.show_runnables,
2288 git_blame_gutter_max_author_length,
2289 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2290 scroll_anchor: self.scroll_manager.anchor(),
2291 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2292 placeholder_text: self.placeholder_text.clone(),
2293 is_focused: self.focus_handle.is_focused(cx),
2294 current_line_highlight: self
2295 .current_line_highlight
2296 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2297 gutter_hovered: self.gutter_hovered,
2298 }
2299 }
2300
2301 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2302 self.buffer.read(cx).language_at(point, cx)
2303 }
2304
2305 pub fn file_at<T: ToOffset>(
2306 &self,
2307 point: T,
2308 cx: &AppContext,
2309 ) -> Option<Arc<dyn language::File>> {
2310 self.buffer.read(cx).read(cx).file_at(point).cloned()
2311 }
2312
2313 pub fn active_excerpt(
2314 &self,
2315 cx: &AppContext,
2316 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2317 self.buffer
2318 .read(cx)
2319 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2320 }
2321
2322 pub fn mode(&self) -> EditorMode {
2323 self.mode
2324 }
2325
2326 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2327 self.collaboration_hub.as_deref()
2328 }
2329
2330 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2331 self.collaboration_hub = Some(hub);
2332 }
2333
2334 pub fn set_custom_context_menu(
2335 &mut self,
2336 f: impl 'static
2337 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2338 ) {
2339 self.custom_context_menu = Some(Box::new(f))
2340 }
2341
2342 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2343 self.completion_provider = provider;
2344 }
2345
2346 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2347 self.semantics_provider.clone()
2348 }
2349
2350 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2351 self.semantics_provider = provider;
2352 }
2353
2354 pub fn set_inline_completion_provider<T>(
2355 &mut self,
2356 provider: Option<Model<T>>,
2357 cx: &mut ViewContext<Self>,
2358 ) where
2359 T: InlineCompletionProvider,
2360 {
2361 self.inline_completion_provider =
2362 provider.map(|provider| RegisteredInlineCompletionProvider {
2363 _subscription: cx.observe(&provider, |this, _, cx| {
2364 if this.focus_handle.is_focused(cx) {
2365 this.update_visible_inline_completion(cx);
2366 }
2367 }),
2368 provider: Arc::new(provider),
2369 });
2370 self.refresh_inline_completion(false, false, cx);
2371 }
2372
2373 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2374 self.placeholder_text.as_deref()
2375 }
2376
2377 pub fn set_placeholder_text(
2378 &mut self,
2379 placeholder_text: impl Into<Arc<str>>,
2380 cx: &mut ViewContext<Self>,
2381 ) {
2382 let placeholder_text = Some(placeholder_text.into());
2383 if self.placeholder_text != placeholder_text {
2384 self.placeholder_text = placeholder_text;
2385 cx.notify();
2386 }
2387 }
2388
2389 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2390 self.cursor_shape = cursor_shape;
2391
2392 // Disrupt blink for immediate user feedback that the cursor shape has changed
2393 self.blink_manager.update(cx, BlinkManager::show_cursor);
2394
2395 cx.notify();
2396 }
2397
2398 pub fn set_current_line_highlight(
2399 &mut self,
2400 current_line_highlight: Option<CurrentLineHighlight>,
2401 ) {
2402 self.current_line_highlight = current_line_highlight;
2403 }
2404
2405 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2406 self.collapse_matches = collapse_matches;
2407 }
2408
2409 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2410 if self.collapse_matches {
2411 return range.start..range.start;
2412 }
2413 range.clone()
2414 }
2415
2416 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2417 if self.display_map.read(cx).clip_at_line_ends != clip {
2418 self.display_map
2419 .update(cx, |map, _| map.clip_at_line_ends = clip);
2420 }
2421 }
2422
2423 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2424 self.input_enabled = input_enabled;
2425 }
2426
2427 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2428 self.enable_inline_completions = enabled;
2429 }
2430
2431 pub fn set_autoindent(&mut self, autoindent: bool) {
2432 if autoindent {
2433 self.autoindent_mode = Some(AutoindentMode::EachLine);
2434 } else {
2435 self.autoindent_mode = None;
2436 }
2437 }
2438
2439 pub fn read_only(&self, cx: &AppContext) -> bool {
2440 self.read_only || self.buffer.read(cx).read_only()
2441 }
2442
2443 pub fn set_read_only(&mut self, read_only: bool) {
2444 self.read_only = read_only;
2445 }
2446
2447 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2448 self.use_autoclose = autoclose;
2449 }
2450
2451 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2452 self.use_auto_surround = auto_surround;
2453 }
2454
2455 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2456 self.auto_replace_emoji_shortcode = auto_replace;
2457 }
2458
2459 pub fn toggle_inline_completions(
2460 &mut self,
2461 _: &ToggleInlineCompletions,
2462 cx: &mut ViewContext<Self>,
2463 ) {
2464 if self.show_inline_completions_override.is_some() {
2465 self.set_show_inline_completions(None, cx);
2466 } else {
2467 let cursor = self.selections.newest_anchor().head();
2468 if let Some((buffer, cursor_buffer_position)) =
2469 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2470 {
2471 let show_inline_completions =
2472 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2473 self.set_show_inline_completions(Some(show_inline_completions), cx);
2474 }
2475 }
2476 }
2477
2478 pub fn set_show_inline_completions(
2479 &mut self,
2480 show_inline_completions: Option<bool>,
2481 cx: &mut ViewContext<Self>,
2482 ) {
2483 self.show_inline_completions_override = show_inline_completions;
2484 self.refresh_inline_completion(false, true, cx);
2485 }
2486
2487 fn should_show_inline_completions(
2488 &self,
2489 buffer: &Model<Buffer>,
2490 buffer_position: language::Anchor,
2491 cx: &AppContext,
2492 ) -> bool {
2493 if let Some(provider) = self.inline_completion_provider() {
2494 if let Some(show_inline_completions) = self.show_inline_completions_override {
2495 show_inline_completions
2496 } else {
2497 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2498 }
2499 } else {
2500 false
2501 }
2502 }
2503
2504 pub fn set_use_modal_editing(&mut self, to: bool) {
2505 self.use_modal_editing = to;
2506 }
2507
2508 pub fn use_modal_editing(&self) -> bool {
2509 self.use_modal_editing
2510 }
2511
2512 fn selections_did_change(
2513 &mut self,
2514 local: bool,
2515 old_cursor_position: &Anchor,
2516 show_completions: bool,
2517 cx: &mut ViewContext<Self>,
2518 ) {
2519 cx.invalidate_character_coordinates();
2520
2521 // Copy selections to primary selection buffer
2522 #[cfg(target_os = "linux")]
2523 if local {
2524 let selections = self.selections.all::<usize>(cx);
2525 let buffer_handle = self.buffer.read(cx).read(cx);
2526
2527 let mut text = String::new();
2528 for (index, selection) in selections.iter().enumerate() {
2529 let text_for_selection = buffer_handle
2530 .text_for_range(selection.start..selection.end)
2531 .collect::<String>();
2532
2533 text.push_str(&text_for_selection);
2534 if index != selections.len() - 1 {
2535 text.push('\n');
2536 }
2537 }
2538
2539 if !text.is_empty() {
2540 cx.write_to_primary(ClipboardItem::new_string(text));
2541 }
2542 }
2543
2544 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2545 self.buffer.update(cx, |buffer, cx| {
2546 buffer.set_active_selections(
2547 &self.selections.disjoint_anchors(),
2548 self.selections.line_mode,
2549 self.cursor_shape,
2550 cx,
2551 )
2552 });
2553 }
2554 let display_map = self
2555 .display_map
2556 .update(cx, |display_map, cx| display_map.snapshot(cx));
2557 let buffer = &display_map.buffer_snapshot;
2558 self.add_selections_state = None;
2559 self.select_next_state = None;
2560 self.select_prev_state = None;
2561 self.select_larger_syntax_node_stack.clear();
2562 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2563 self.snippet_stack
2564 .invalidate(&self.selections.disjoint_anchors(), buffer);
2565 self.take_rename(false, cx);
2566
2567 let new_cursor_position = self.selections.newest_anchor().head();
2568
2569 self.push_to_nav_history(
2570 *old_cursor_position,
2571 Some(new_cursor_position.to_point(buffer)),
2572 cx,
2573 );
2574
2575 if local {
2576 let new_cursor_position = self.selections.newest_anchor().head();
2577 let mut context_menu = self.context_menu.write();
2578 let completion_menu = match context_menu.as_ref() {
2579 Some(ContextMenu::Completions(menu)) => Some(menu),
2580
2581 _ => {
2582 *context_menu = None;
2583 None
2584 }
2585 };
2586
2587 if let Some(completion_menu) = completion_menu {
2588 let cursor_position = new_cursor_position.to_offset(buffer);
2589 let (word_range, kind) =
2590 buffer.surrounding_word(completion_menu.initial_position, true);
2591 if kind == Some(CharKind::Word)
2592 && word_range.to_inclusive().contains(&cursor_position)
2593 {
2594 let mut completion_menu = completion_menu.clone();
2595 drop(context_menu);
2596
2597 let query = Self::completion_query(buffer, cursor_position);
2598 cx.spawn(move |this, mut cx| async move {
2599 completion_menu
2600 .filter(query.as_deref(), cx.background_executor().clone())
2601 .await;
2602
2603 this.update(&mut cx, |this, cx| {
2604 let mut context_menu = this.context_menu.write();
2605 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2606 return;
2607 };
2608
2609 if menu.id > completion_menu.id {
2610 return;
2611 }
2612
2613 *context_menu = Some(ContextMenu::Completions(completion_menu));
2614 drop(context_menu);
2615 cx.notify();
2616 })
2617 })
2618 .detach();
2619
2620 if show_completions {
2621 self.show_completions(&ShowCompletions { trigger: None }, cx);
2622 }
2623 } else {
2624 drop(context_menu);
2625 self.hide_context_menu(cx);
2626 }
2627 } else {
2628 drop(context_menu);
2629 }
2630
2631 hide_hover(self, cx);
2632
2633 if old_cursor_position.to_display_point(&display_map).row()
2634 != new_cursor_position.to_display_point(&display_map).row()
2635 {
2636 self.available_code_actions.take();
2637 }
2638 self.refresh_code_actions(cx);
2639 self.refresh_document_highlights(cx);
2640 refresh_matching_bracket_highlights(self, cx);
2641 self.discard_inline_completion(false, cx);
2642 linked_editing_ranges::refresh_linked_ranges(self, cx);
2643 if self.git_blame_inline_enabled {
2644 self.start_inline_blame_timer(cx);
2645 }
2646 }
2647
2648 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2649 cx.emit(EditorEvent::SelectionsChanged { local });
2650
2651 if self.selections.disjoint_anchors().len() == 1 {
2652 cx.emit(SearchEvent::ActiveMatchChanged)
2653 }
2654 cx.notify();
2655 }
2656
2657 pub fn change_selections<R>(
2658 &mut self,
2659 autoscroll: Option<Autoscroll>,
2660 cx: &mut ViewContext<Self>,
2661 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2662 ) -> R {
2663 self.change_selections_inner(autoscroll, true, cx, change)
2664 }
2665
2666 pub fn change_selections_inner<R>(
2667 &mut self,
2668 autoscroll: Option<Autoscroll>,
2669 request_completions: bool,
2670 cx: &mut ViewContext<Self>,
2671 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2672 ) -> R {
2673 let old_cursor_position = self.selections.newest_anchor().head();
2674 self.push_to_selection_history();
2675
2676 let (changed, result) = self.selections.change_with(cx, change);
2677
2678 if changed {
2679 if let Some(autoscroll) = autoscroll {
2680 self.request_autoscroll(autoscroll, cx);
2681 }
2682 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2683
2684 if self.should_open_signature_help_automatically(
2685 &old_cursor_position,
2686 self.signature_help_state.backspace_pressed(),
2687 cx,
2688 ) {
2689 self.show_signature_help(&ShowSignatureHelp, cx);
2690 }
2691 self.signature_help_state.set_backspace_pressed(false);
2692 }
2693
2694 result
2695 }
2696
2697 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2698 where
2699 I: IntoIterator<Item = (Range<S>, T)>,
2700 S: ToOffset,
2701 T: Into<Arc<str>>,
2702 {
2703 if self.read_only(cx) {
2704 return;
2705 }
2706
2707 self.buffer
2708 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2709 }
2710
2711 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2712 where
2713 I: IntoIterator<Item = (Range<S>, T)>,
2714 S: ToOffset,
2715 T: Into<Arc<str>>,
2716 {
2717 if self.read_only(cx) {
2718 return;
2719 }
2720
2721 self.buffer.update(cx, |buffer, cx| {
2722 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2723 });
2724 }
2725
2726 pub fn edit_with_block_indent<I, S, T>(
2727 &mut self,
2728 edits: I,
2729 original_indent_columns: Vec<u32>,
2730 cx: &mut ViewContext<Self>,
2731 ) where
2732 I: IntoIterator<Item = (Range<S>, T)>,
2733 S: ToOffset,
2734 T: Into<Arc<str>>,
2735 {
2736 if self.read_only(cx) {
2737 return;
2738 }
2739
2740 self.buffer.update(cx, |buffer, cx| {
2741 buffer.edit(
2742 edits,
2743 Some(AutoindentMode::Block {
2744 original_indent_columns,
2745 }),
2746 cx,
2747 )
2748 });
2749 }
2750
2751 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2752 self.hide_context_menu(cx);
2753
2754 match phase {
2755 SelectPhase::Begin {
2756 position,
2757 add,
2758 click_count,
2759 } => self.begin_selection(position, add, click_count, cx),
2760 SelectPhase::BeginColumnar {
2761 position,
2762 goal_column,
2763 reset,
2764 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2765 SelectPhase::Extend {
2766 position,
2767 click_count,
2768 } => self.extend_selection(position, click_count, cx),
2769 SelectPhase::Update {
2770 position,
2771 goal_column,
2772 scroll_delta,
2773 } => self.update_selection(position, goal_column, scroll_delta, cx),
2774 SelectPhase::End => self.end_selection(cx),
2775 }
2776 }
2777
2778 fn extend_selection(
2779 &mut self,
2780 position: DisplayPoint,
2781 click_count: usize,
2782 cx: &mut ViewContext<Self>,
2783 ) {
2784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2785 let tail = self.selections.newest::<usize>(cx).tail();
2786 self.begin_selection(position, false, click_count, cx);
2787
2788 let position = position.to_offset(&display_map, Bias::Left);
2789 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2790
2791 let mut pending_selection = self
2792 .selections
2793 .pending_anchor()
2794 .expect("extend_selection not called with pending selection");
2795 if position >= tail {
2796 pending_selection.start = tail_anchor;
2797 } else {
2798 pending_selection.end = tail_anchor;
2799 pending_selection.reversed = true;
2800 }
2801
2802 let mut pending_mode = self.selections.pending_mode().unwrap();
2803 match &mut pending_mode {
2804 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2805 _ => {}
2806 }
2807
2808 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2809 s.set_pending(pending_selection, pending_mode)
2810 });
2811 }
2812
2813 fn begin_selection(
2814 &mut self,
2815 position: DisplayPoint,
2816 add: bool,
2817 click_count: usize,
2818 cx: &mut ViewContext<Self>,
2819 ) {
2820 if !self.focus_handle.is_focused(cx) {
2821 self.last_focused_descendant = None;
2822 cx.focus(&self.focus_handle);
2823 }
2824
2825 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2826 let buffer = &display_map.buffer_snapshot;
2827 let newest_selection = self.selections.newest_anchor().clone();
2828 let position = display_map.clip_point(position, Bias::Left);
2829
2830 let start;
2831 let end;
2832 let mode;
2833 let auto_scroll;
2834 match click_count {
2835 1 => {
2836 start = buffer.anchor_before(position.to_point(&display_map));
2837 end = start;
2838 mode = SelectMode::Character;
2839 auto_scroll = true;
2840 }
2841 2 => {
2842 let range = movement::surrounding_word(&display_map, position);
2843 start = buffer.anchor_before(range.start.to_point(&display_map));
2844 end = buffer.anchor_before(range.end.to_point(&display_map));
2845 mode = SelectMode::Word(start..end);
2846 auto_scroll = true;
2847 }
2848 3 => {
2849 let position = display_map
2850 .clip_point(position, Bias::Left)
2851 .to_point(&display_map);
2852 let line_start = display_map.prev_line_boundary(position).0;
2853 let next_line_start = buffer.clip_point(
2854 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2855 Bias::Left,
2856 );
2857 start = buffer.anchor_before(line_start);
2858 end = buffer.anchor_before(next_line_start);
2859 mode = SelectMode::Line(start..end);
2860 auto_scroll = true;
2861 }
2862 _ => {
2863 start = buffer.anchor_before(0);
2864 end = buffer.anchor_before(buffer.len());
2865 mode = SelectMode::All;
2866 auto_scroll = false;
2867 }
2868 }
2869
2870 let point_to_delete: Option<usize> = {
2871 let selected_points: Vec<Selection<Point>> =
2872 self.selections.disjoint_in_range(start..end, cx);
2873
2874 if !add || click_count > 1 {
2875 None
2876 } else if !selected_points.is_empty() {
2877 Some(selected_points[0].id)
2878 } else {
2879 let clicked_point_already_selected =
2880 self.selections.disjoint.iter().find(|selection| {
2881 selection.start.to_point(buffer) == start.to_point(buffer)
2882 || selection.end.to_point(buffer) == end.to_point(buffer)
2883 });
2884
2885 clicked_point_already_selected.map(|selection| selection.id)
2886 }
2887 };
2888
2889 let selections_count = self.selections.count();
2890
2891 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2892 if let Some(point_to_delete) = point_to_delete {
2893 s.delete(point_to_delete);
2894
2895 if selections_count == 1 {
2896 s.set_pending_anchor_range(start..end, mode);
2897 }
2898 } else {
2899 if !add {
2900 s.clear_disjoint();
2901 } else if click_count > 1 {
2902 s.delete(newest_selection.id)
2903 }
2904
2905 s.set_pending_anchor_range(start..end, mode);
2906 }
2907 });
2908 }
2909
2910 fn begin_columnar_selection(
2911 &mut self,
2912 position: DisplayPoint,
2913 goal_column: u32,
2914 reset: bool,
2915 cx: &mut ViewContext<Self>,
2916 ) {
2917 if !self.focus_handle.is_focused(cx) {
2918 self.last_focused_descendant = None;
2919 cx.focus(&self.focus_handle);
2920 }
2921
2922 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2923
2924 if reset {
2925 let pointer_position = display_map
2926 .buffer_snapshot
2927 .anchor_before(position.to_point(&display_map));
2928
2929 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2930 s.clear_disjoint();
2931 s.set_pending_anchor_range(
2932 pointer_position..pointer_position,
2933 SelectMode::Character,
2934 );
2935 });
2936 }
2937
2938 let tail = self.selections.newest::<Point>(cx).tail();
2939 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2940
2941 if !reset {
2942 self.select_columns(
2943 tail.to_display_point(&display_map),
2944 position,
2945 goal_column,
2946 &display_map,
2947 cx,
2948 );
2949 }
2950 }
2951
2952 fn update_selection(
2953 &mut self,
2954 position: DisplayPoint,
2955 goal_column: u32,
2956 scroll_delta: gpui::Point<f32>,
2957 cx: &mut ViewContext<Self>,
2958 ) {
2959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2960
2961 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2962 let tail = tail.to_display_point(&display_map);
2963 self.select_columns(tail, position, goal_column, &display_map, cx);
2964 } else if let Some(mut pending) = self.selections.pending_anchor() {
2965 let buffer = self.buffer.read(cx).snapshot(cx);
2966 let head;
2967 let tail;
2968 let mode = self.selections.pending_mode().unwrap();
2969 match &mode {
2970 SelectMode::Character => {
2971 head = position.to_point(&display_map);
2972 tail = pending.tail().to_point(&buffer);
2973 }
2974 SelectMode::Word(original_range) => {
2975 let original_display_range = original_range.start.to_display_point(&display_map)
2976 ..original_range.end.to_display_point(&display_map);
2977 let original_buffer_range = original_display_range.start.to_point(&display_map)
2978 ..original_display_range.end.to_point(&display_map);
2979 if movement::is_inside_word(&display_map, position)
2980 || original_display_range.contains(&position)
2981 {
2982 let word_range = movement::surrounding_word(&display_map, position);
2983 if word_range.start < original_display_range.start {
2984 head = word_range.start.to_point(&display_map);
2985 } else {
2986 head = word_range.end.to_point(&display_map);
2987 }
2988 } else {
2989 head = position.to_point(&display_map);
2990 }
2991
2992 if head <= original_buffer_range.start {
2993 tail = original_buffer_range.end;
2994 } else {
2995 tail = original_buffer_range.start;
2996 }
2997 }
2998 SelectMode::Line(original_range) => {
2999 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3000
3001 let position = display_map
3002 .clip_point(position, Bias::Left)
3003 .to_point(&display_map);
3004 let line_start = display_map.prev_line_boundary(position).0;
3005 let next_line_start = buffer.clip_point(
3006 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3007 Bias::Left,
3008 );
3009
3010 if line_start < original_range.start {
3011 head = line_start
3012 } else {
3013 head = next_line_start
3014 }
3015
3016 if head <= original_range.start {
3017 tail = original_range.end;
3018 } else {
3019 tail = original_range.start;
3020 }
3021 }
3022 SelectMode::All => {
3023 return;
3024 }
3025 };
3026
3027 if head < tail {
3028 pending.start = buffer.anchor_before(head);
3029 pending.end = buffer.anchor_before(tail);
3030 pending.reversed = true;
3031 } else {
3032 pending.start = buffer.anchor_before(tail);
3033 pending.end = buffer.anchor_before(head);
3034 pending.reversed = false;
3035 }
3036
3037 self.change_selections(None, cx, |s| {
3038 s.set_pending(pending, mode);
3039 });
3040 } else {
3041 log::error!("update_selection dispatched with no pending selection");
3042 return;
3043 }
3044
3045 self.apply_scroll_delta(scroll_delta, cx);
3046 cx.notify();
3047 }
3048
3049 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3050 self.columnar_selection_tail.take();
3051 if self.selections.pending_anchor().is_some() {
3052 let selections = self.selections.all::<usize>(cx);
3053 self.change_selections(None, cx, |s| {
3054 s.select(selections);
3055 s.clear_pending();
3056 });
3057 }
3058 }
3059
3060 fn select_columns(
3061 &mut self,
3062 tail: DisplayPoint,
3063 head: DisplayPoint,
3064 goal_column: u32,
3065 display_map: &DisplaySnapshot,
3066 cx: &mut ViewContext<Self>,
3067 ) {
3068 let start_row = cmp::min(tail.row(), head.row());
3069 let end_row = cmp::max(tail.row(), head.row());
3070 let start_column = cmp::min(tail.column(), goal_column);
3071 let end_column = cmp::max(tail.column(), goal_column);
3072 let reversed = start_column < tail.column();
3073
3074 let selection_ranges = (start_row.0..=end_row.0)
3075 .map(DisplayRow)
3076 .filter_map(|row| {
3077 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3078 let start = display_map
3079 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3080 .to_point(display_map);
3081 let end = display_map
3082 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3083 .to_point(display_map);
3084 if reversed {
3085 Some(end..start)
3086 } else {
3087 Some(start..end)
3088 }
3089 } else {
3090 None
3091 }
3092 })
3093 .collect::<Vec<_>>();
3094
3095 self.change_selections(None, cx, |s| {
3096 s.select_ranges(selection_ranges);
3097 });
3098 cx.notify();
3099 }
3100
3101 pub fn has_pending_nonempty_selection(&self) -> bool {
3102 let pending_nonempty_selection = match self.selections.pending_anchor() {
3103 Some(Selection { start, end, .. }) => start != end,
3104 None => false,
3105 };
3106
3107 pending_nonempty_selection
3108 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3109 }
3110
3111 pub fn has_pending_selection(&self) -> bool {
3112 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3113 }
3114
3115 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3116 if self.clear_expanded_diff_hunks(cx) {
3117 cx.notify();
3118 return;
3119 }
3120 if self.dismiss_menus_and_popups(true, cx) {
3121 return;
3122 }
3123
3124 if self.mode == EditorMode::Full
3125 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3126 {
3127 return;
3128 }
3129
3130 cx.propagate();
3131 }
3132
3133 pub fn dismiss_menus_and_popups(
3134 &mut self,
3135 should_report_inline_completion_event: bool,
3136 cx: &mut ViewContext<Self>,
3137 ) -> bool {
3138 if self.take_rename(false, cx).is_some() {
3139 return true;
3140 }
3141
3142 if hide_hover(self, cx) {
3143 return true;
3144 }
3145
3146 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3147 return true;
3148 }
3149
3150 if self.hide_context_menu(cx).is_some() {
3151 return true;
3152 }
3153
3154 if self.mouse_context_menu.take().is_some() {
3155 return true;
3156 }
3157
3158 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3159 return true;
3160 }
3161
3162 if self.snippet_stack.pop().is_some() {
3163 return true;
3164 }
3165
3166 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3167 self.dismiss_diagnostics(cx);
3168 return true;
3169 }
3170
3171 false
3172 }
3173
3174 fn linked_editing_ranges_for(
3175 &self,
3176 selection: Range<text::Anchor>,
3177 cx: &AppContext,
3178 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3179 if self.linked_edit_ranges.is_empty() {
3180 return None;
3181 }
3182 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3183 selection.end.buffer_id.and_then(|end_buffer_id| {
3184 if selection.start.buffer_id != Some(end_buffer_id) {
3185 return None;
3186 }
3187 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3188 let snapshot = buffer.read(cx).snapshot();
3189 self.linked_edit_ranges
3190 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3191 .map(|ranges| (ranges, snapshot, buffer))
3192 })?;
3193 use text::ToOffset as TO;
3194 // find offset from the start of current range to current cursor position
3195 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3196
3197 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3198 let start_difference = start_offset - start_byte_offset;
3199 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3200 let end_difference = end_offset - start_byte_offset;
3201 // Current range has associated linked ranges.
3202 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3203 for range in linked_ranges.iter() {
3204 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3205 let end_offset = start_offset + end_difference;
3206 let start_offset = start_offset + start_difference;
3207 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3208 continue;
3209 }
3210 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3211 if s.start.buffer_id != selection.start.buffer_id
3212 || s.end.buffer_id != selection.end.buffer_id
3213 {
3214 return false;
3215 }
3216 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3217 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3218 }) {
3219 continue;
3220 }
3221 let start = buffer_snapshot.anchor_after(start_offset);
3222 let end = buffer_snapshot.anchor_after(end_offset);
3223 linked_edits
3224 .entry(buffer.clone())
3225 .or_default()
3226 .push(start..end);
3227 }
3228 Some(linked_edits)
3229 }
3230
3231 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3232 let text: Arc<str> = text.into();
3233
3234 if self.read_only(cx) {
3235 return;
3236 }
3237
3238 let selections = self.selections.all_adjusted(cx);
3239 let mut bracket_inserted = false;
3240 let mut edits = Vec::new();
3241 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3242 let mut new_selections = Vec::with_capacity(selections.len());
3243 let mut new_autoclose_regions = Vec::new();
3244 let snapshot = self.buffer.read(cx).read(cx);
3245
3246 for (selection, autoclose_region) in
3247 self.selections_with_autoclose_regions(selections, &snapshot)
3248 {
3249 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3250 // Determine if the inserted text matches the opening or closing
3251 // bracket of any of this language's bracket pairs.
3252 let mut bracket_pair = None;
3253 let mut is_bracket_pair_start = false;
3254 let mut is_bracket_pair_end = false;
3255 if !text.is_empty() {
3256 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3257 // and they are removing the character that triggered IME popup.
3258 for (pair, enabled) in scope.brackets() {
3259 if !pair.close && !pair.surround {
3260 continue;
3261 }
3262
3263 if enabled && pair.start.ends_with(text.as_ref()) {
3264 let prefix_len = pair.start.len() - text.len();
3265 let preceding_text_matches_prefix = prefix_len == 0
3266 || (selection.start.column >= (prefix_len as u32)
3267 && snapshot.contains_str_at(
3268 Point::new(
3269 selection.start.row,
3270 selection.start.column - (prefix_len as u32),
3271 ),
3272 &pair.start[..prefix_len],
3273 ));
3274 if preceding_text_matches_prefix {
3275 bracket_pair = Some(pair.clone());
3276 is_bracket_pair_start = true;
3277 break;
3278 }
3279 }
3280 if pair.end.as_str() == text.as_ref() {
3281 bracket_pair = Some(pair.clone());
3282 is_bracket_pair_end = true;
3283 break;
3284 }
3285 }
3286 }
3287
3288 if let Some(bracket_pair) = bracket_pair {
3289 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3290 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3291 let auto_surround =
3292 self.use_auto_surround && snapshot_settings.use_auto_surround;
3293 if selection.is_empty() {
3294 if is_bracket_pair_start {
3295 // If the inserted text is a suffix of an opening bracket and the
3296 // selection is preceded by the rest of the opening bracket, then
3297 // insert the closing bracket.
3298 let following_text_allows_autoclose = snapshot
3299 .chars_at(selection.start)
3300 .next()
3301 .map_or(true, |c| scope.should_autoclose_before(c));
3302
3303 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3304 && bracket_pair.start.len() == 1
3305 {
3306 let target = bracket_pair.start.chars().next().unwrap();
3307 let current_line_count = snapshot
3308 .reversed_chars_at(selection.start)
3309 .take_while(|&c| c != '\n')
3310 .filter(|&c| c == target)
3311 .count();
3312 current_line_count % 2 == 1
3313 } else {
3314 false
3315 };
3316
3317 if autoclose
3318 && bracket_pair.close
3319 && following_text_allows_autoclose
3320 && !is_closing_quote
3321 {
3322 let anchor = snapshot.anchor_before(selection.end);
3323 new_selections.push((selection.map(|_| anchor), text.len()));
3324 new_autoclose_regions.push((
3325 anchor,
3326 text.len(),
3327 selection.id,
3328 bracket_pair.clone(),
3329 ));
3330 edits.push((
3331 selection.range(),
3332 format!("{}{}", text, bracket_pair.end).into(),
3333 ));
3334 bracket_inserted = true;
3335 continue;
3336 }
3337 }
3338
3339 if let Some(region) = autoclose_region {
3340 // If the selection is followed by an auto-inserted closing bracket,
3341 // then don't insert that closing bracket again; just move the selection
3342 // past the closing bracket.
3343 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3344 && text.as_ref() == region.pair.end.as_str();
3345 if should_skip {
3346 let anchor = snapshot.anchor_after(selection.end);
3347 new_selections
3348 .push((selection.map(|_| anchor), region.pair.end.len()));
3349 continue;
3350 }
3351 }
3352
3353 let always_treat_brackets_as_autoclosed = snapshot
3354 .settings_at(selection.start, cx)
3355 .always_treat_brackets_as_autoclosed;
3356 if always_treat_brackets_as_autoclosed
3357 && is_bracket_pair_end
3358 && snapshot.contains_str_at(selection.end, text.as_ref())
3359 {
3360 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3361 // and the inserted text is a closing bracket and the selection is followed
3362 // by the closing bracket then move the selection past the closing bracket.
3363 let anchor = snapshot.anchor_after(selection.end);
3364 new_selections.push((selection.map(|_| anchor), text.len()));
3365 continue;
3366 }
3367 }
3368 // If an opening bracket is 1 character long and is typed while
3369 // text is selected, then surround that text with the bracket pair.
3370 else if auto_surround
3371 && bracket_pair.surround
3372 && is_bracket_pair_start
3373 && bracket_pair.start.chars().count() == 1
3374 {
3375 edits.push((selection.start..selection.start, text.clone()));
3376 edits.push((
3377 selection.end..selection.end,
3378 bracket_pair.end.as_str().into(),
3379 ));
3380 bracket_inserted = true;
3381 new_selections.push((
3382 Selection {
3383 id: selection.id,
3384 start: snapshot.anchor_after(selection.start),
3385 end: snapshot.anchor_before(selection.end),
3386 reversed: selection.reversed,
3387 goal: selection.goal,
3388 },
3389 0,
3390 ));
3391 continue;
3392 }
3393 }
3394 }
3395
3396 if self.auto_replace_emoji_shortcode
3397 && selection.is_empty()
3398 && text.as_ref().ends_with(':')
3399 {
3400 if let Some(possible_emoji_short_code) =
3401 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3402 {
3403 if !possible_emoji_short_code.is_empty() {
3404 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3405 let emoji_shortcode_start = Point::new(
3406 selection.start.row,
3407 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3408 );
3409
3410 // Remove shortcode from buffer
3411 edits.push((
3412 emoji_shortcode_start..selection.start,
3413 "".to_string().into(),
3414 ));
3415 new_selections.push((
3416 Selection {
3417 id: selection.id,
3418 start: snapshot.anchor_after(emoji_shortcode_start),
3419 end: snapshot.anchor_before(selection.start),
3420 reversed: selection.reversed,
3421 goal: selection.goal,
3422 },
3423 0,
3424 ));
3425
3426 // Insert emoji
3427 let selection_start_anchor = snapshot.anchor_after(selection.start);
3428 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3429 edits.push((selection.start..selection.end, emoji.to_string().into()));
3430
3431 continue;
3432 }
3433 }
3434 }
3435 }
3436
3437 // If not handling any auto-close operation, then just replace the selected
3438 // text with the given input and move the selection to the end of the
3439 // newly inserted text.
3440 let anchor = snapshot.anchor_after(selection.end);
3441 if !self.linked_edit_ranges.is_empty() {
3442 let start_anchor = snapshot.anchor_before(selection.start);
3443
3444 let is_word_char = text.chars().next().map_or(true, |char| {
3445 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3446 classifier.is_word(char)
3447 });
3448
3449 if is_word_char {
3450 if let Some(ranges) = self
3451 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3452 {
3453 for (buffer, edits) in ranges {
3454 linked_edits
3455 .entry(buffer.clone())
3456 .or_default()
3457 .extend(edits.into_iter().map(|range| (range, text.clone())));
3458 }
3459 }
3460 }
3461 }
3462
3463 new_selections.push((selection.map(|_| anchor), 0));
3464 edits.push((selection.start..selection.end, text.clone()));
3465 }
3466
3467 drop(snapshot);
3468
3469 self.transact(cx, |this, cx| {
3470 this.buffer.update(cx, |buffer, cx| {
3471 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3472 });
3473 for (buffer, edits) in linked_edits {
3474 buffer.update(cx, |buffer, cx| {
3475 let snapshot = buffer.snapshot();
3476 let edits = edits
3477 .into_iter()
3478 .map(|(range, text)| {
3479 use text::ToPoint as TP;
3480 let end_point = TP::to_point(&range.end, &snapshot);
3481 let start_point = TP::to_point(&range.start, &snapshot);
3482 (start_point..end_point, text)
3483 })
3484 .sorted_by_key(|(range, _)| range.start)
3485 .collect::<Vec<_>>();
3486 buffer.edit(edits, None, cx);
3487 })
3488 }
3489 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3490 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3491 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3492 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3493 .zip(new_selection_deltas)
3494 .map(|(selection, delta)| Selection {
3495 id: selection.id,
3496 start: selection.start + delta,
3497 end: selection.end + delta,
3498 reversed: selection.reversed,
3499 goal: SelectionGoal::None,
3500 })
3501 .collect::<Vec<_>>();
3502
3503 let mut i = 0;
3504 for (position, delta, selection_id, pair) in new_autoclose_regions {
3505 let position = position.to_offset(&map.buffer_snapshot) + delta;
3506 let start = map.buffer_snapshot.anchor_before(position);
3507 let end = map.buffer_snapshot.anchor_after(position);
3508 while let Some(existing_state) = this.autoclose_regions.get(i) {
3509 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3510 Ordering::Less => i += 1,
3511 Ordering::Greater => break,
3512 Ordering::Equal => {
3513 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3514 Ordering::Less => i += 1,
3515 Ordering::Equal => break,
3516 Ordering::Greater => break,
3517 }
3518 }
3519 }
3520 }
3521 this.autoclose_regions.insert(
3522 i,
3523 AutocloseRegion {
3524 selection_id,
3525 range: start..end,
3526 pair,
3527 },
3528 );
3529 }
3530
3531 let had_active_inline_completion = this.has_active_inline_completion(cx);
3532 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3533 s.select(new_selections)
3534 });
3535
3536 if !bracket_inserted {
3537 if let Some(on_type_format_task) =
3538 this.trigger_on_type_formatting(text.to_string(), cx)
3539 {
3540 on_type_format_task.detach_and_log_err(cx);
3541 }
3542 }
3543
3544 let editor_settings = EditorSettings::get_global(cx);
3545 if bracket_inserted
3546 && (editor_settings.auto_signature_help
3547 || editor_settings.show_signature_help_after_edits)
3548 {
3549 this.show_signature_help(&ShowSignatureHelp, cx);
3550 }
3551
3552 let trigger_in_words = !had_active_inline_completion;
3553 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3554 linked_editing_ranges::refresh_linked_ranges(this, cx);
3555 this.refresh_inline_completion(true, false, cx);
3556 });
3557 }
3558
3559 fn find_possible_emoji_shortcode_at_position(
3560 snapshot: &MultiBufferSnapshot,
3561 position: Point,
3562 ) -> Option<String> {
3563 let mut chars = Vec::new();
3564 let mut found_colon = false;
3565 for char in snapshot.reversed_chars_at(position).take(100) {
3566 // Found a possible emoji shortcode in the middle of the buffer
3567 if found_colon {
3568 if char.is_whitespace() {
3569 chars.reverse();
3570 return Some(chars.iter().collect());
3571 }
3572 // If the previous character is not a whitespace, we are in the middle of a word
3573 // and we only want to complete the shortcode if the word is made up of other emojis
3574 let mut containing_word = String::new();
3575 for ch in snapshot
3576 .reversed_chars_at(position)
3577 .skip(chars.len() + 1)
3578 .take(100)
3579 {
3580 if ch.is_whitespace() {
3581 break;
3582 }
3583 containing_word.push(ch);
3584 }
3585 let containing_word = containing_word.chars().rev().collect::<String>();
3586 if util::word_consists_of_emojis(containing_word.as_str()) {
3587 chars.reverse();
3588 return Some(chars.iter().collect());
3589 }
3590 }
3591
3592 if char.is_whitespace() || !char.is_ascii() {
3593 return None;
3594 }
3595 if char == ':' {
3596 found_colon = true;
3597 } else {
3598 chars.push(char);
3599 }
3600 }
3601 // Found a possible emoji shortcode at the beginning of the buffer
3602 chars.reverse();
3603 Some(chars.iter().collect())
3604 }
3605
3606 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3607 self.transact(cx, |this, cx| {
3608 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3609 let selections = this.selections.all::<usize>(cx);
3610 let multi_buffer = this.buffer.read(cx);
3611 let buffer = multi_buffer.snapshot(cx);
3612 selections
3613 .iter()
3614 .map(|selection| {
3615 let start_point = selection.start.to_point(&buffer);
3616 let mut indent =
3617 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3618 indent.len = cmp::min(indent.len, start_point.column);
3619 let start = selection.start;
3620 let end = selection.end;
3621 let selection_is_empty = start == end;
3622 let language_scope = buffer.language_scope_at(start);
3623 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3624 &language_scope
3625 {
3626 let leading_whitespace_len = buffer
3627 .reversed_chars_at(start)
3628 .take_while(|c| c.is_whitespace() && *c != '\n')
3629 .map(|c| c.len_utf8())
3630 .sum::<usize>();
3631
3632 let trailing_whitespace_len = buffer
3633 .chars_at(end)
3634 .take_while(|c| c.is_whitespace() && *c != '\n')
3635 .map(|c| c.len_utf8())
3636 .sum::<usize>();
3637
3638 let insert_extra_newline =
3639 language.brackets().any(|(pair, enabled)| {
3640 let pair_start = pair.start.trim_end();
3641 let pair_end = pair.end.trim_start();
3642
3643 enabled
3644 && pair.newline
3645 && buffer.contains_str_at(
3646 end + trailing_whitespace_len,
3647 pair_end,
3648 )
3649 && buffer.contains_str_at(
3650 (start - leading_whitespace_len)
3651 .saturating_sub(pair_start.len()),
3652 pair_start,
3653 )
3654 });
3655
3656 // Comment extension on newline is allowed only for cursor selections
3657 let comment_delimiter = maybe!({
3658 if !selection_is_empty {
3659 return None;
3660 }
3661
3662 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3663 return None;
3664 }
3665
3666 let delimiters = language.line_comment_prefixes();
3667 let max_len_of_delimiter =
3668 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3669 let (snapshot, range) =
3670 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3671
3672 let mut index_of_first_non_whitespace = 0;
3673 let comment_candidate = snapshot
3674 .chars_for_range(range)
3675 .skip_while(|c| {
3676 let should_skip = c.is_whitespace();
3677 if should_skip {
3678 index_of_first_non_whitespace += 1;
3679 }
3680 should_skip
3681 })
3682 .take(max_len_of_delimiter)
3683 .collect::<String>();
3684 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3685 comment_candidate.starts_with(comment_prefix.as_ref())
3686 })?;
3687 let cursor_is_placed_after_comment_marker =
3688 index_of_first_non_whitespace + comment_prefix.len()
3689 <= start_point.column as usize;
3690 if cursor_is_placed_after_comment_marker {
3691 Some(comment_prefix.clone())
3692 } else {
3693 None
3694 }
3695 });
3696 (comment_delimiter, insert_extra_newline)
3697 } else {
3698 (None, false)
3699 };
3700
3701 let capacity_for_delimiter = comment_delimiter
3702 .as_deref()
3703 .map(str::len)
3704 .unwrap_or_default();
3705 let mut new_text =
3706 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3707 new_text.push('\n');
3708 new_text.extend(indent.chars());
3709 if let Some(delimiter) = &comment_delimiter {
3710 new_text.push_str(delimiter);
3711 }
3712 if insert_extra_newline {
3713 new_text = new_text.repeat(2);
3714 }
3715
3716 let anchor = buffer.anchor_after(end);
3717 let new_selection = selection.map(|_| anchor);
3718 (
3719 (start..end, new_text),
3720 (insert_extra_newline, new_selection),
3721 )
3722 })
3723 .unzip()
3724 };
3725
3726 this.edit_with_autoindent(edits, cx);
3727 let buffer = this.buffer.read(cx).snapshot(cx);
3728 let new_selections = selection_fixup_info
3729 .into_iter()
3730 .map(|(extra_newline_inserted, new_selection)| {
3731 let mut cursor = new_selection.end.to_point(&buffer);
3732 if extra_newline_inserted {
3733 cursor.row -= 1;
3734 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3735 }
3736 new_selection.map(|_| cursor)
3737 })
3738 .collect();
3739
3740 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3741 this.refresh_inline_completion(true, false, cx);
3742 });
3743 }
3744
3745 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3746 let buffer = self.buffer.read(cx);
3747 let snapshot = buffer.snapshot(cx);
3748
3749 let mut edits = Vec::new();
3750 let mut rows = Vec::new();
3751
3752 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3753 let cursor = selection.head();
3754 let row = cursor.row;
3755
3756 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3757
3758 let newline = "\n".to_string();
3759 edits.push((start_of_line..start_of_line, newline));
3760
3761 rows.push(row + rows_inserted as u32);
3762 }
3763
3764 self.transact(cx, |editor, cx| {
3765 editor.edit(edits, cx);
3766
3767 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3768 let mut index = 0;
3769 s.move_cursors_with(|map, _, _| {
3770 let row = rows[index];
3771 index += 1;
3772
3773 let point = Point::new(row, 0);
3774 let boundary = map.next_line_boundary(point).1;
3775 let clipped = map.clip_point(boundary, Bias::Left);
3776
3777 (clipped, SelectionGoal::None)
3778 });
3779 });
3780
3781 let mut indent_edits = Vec::new();
3782 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3783 for row in rows {
3784 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3785 for (row, indent) in indents {
3786 if indent.len == 0 {
3787 continue;
3788 }
3789
3790 let text = match indent.kind {
3791 IndentKind::Space => " ".repeat(indent.len as usize),
3792 IndentKind::Tab => "\t".repeat(indent.len as usize),
3793 };
3794 let point = Point::new(row.0, 0);
3795 indent_edits.push((point..point, text));
3796 }
3797 }
3798 editor.edit(indent_edits, cx);
3799 });
3800 }
3801
3802 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3803 let buffer = self.buffer.read(cx);
3804 let snapshot = buffer.snapshot(cx);
3805
3806 let mut edits = Vec::new();
3807 let mut rows = Vec::new();
3808 let mut rows_inserted = 0;
3809
3810 for selection in self.selections.all_adjusted(cx) {
3811 let cursor = selection.head();
3812 let row = cursor.row;
3813
3814 let point = Point::new(row + 1, 0);
3815 let start_of_line = snapshot.clip_point(point, Bias::Left);
3816
3817 let newline = "\n".to_string();
3818 edits.push((start_of_line..start_of_line, newline));
3819
3820 rows_inserted += 1;
3821 rows.push(row + rows_inserted);
3822 }
3823
3824 self.transact(cx, |editor, cx| {
3825 editor.edit(edits, cx);
3826
3827 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3828 let mut index = 0;
3829 s.move_cursors_with(|map, _, _| {
3830 let row = rows[index];
3831 index += 1;
3832
3833 let point = Point::new(row, 0);
3834 let boundary = map.next_line_boundary(point).1;
3835 let clipped = map.clip_point(boundary, Bias::Left);
3836
3837 (clipped, SelectionGoal::None)
3838 });
3839 });
3840
3841 let mut indent_edits = Vec::new();
3842 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3843 for row in rows {
3844 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3845 for (row, indent) in indents {
3846 if indent.len == 0 {
3847 continue;
3848 }
3849
3850 let text = match indent.kind {
3851 IndentKind::Space => " ".repeat(indent.len as usize),
3852 IndentKind::Tab => "\t".repeat(indent.len as usize),
3853 };
3854 let point = Point::new(row.0, 0);
3855 indent_edits.push((point..point, text));
3856 }
3857 }
3858 editor.edit(indent_edits, cx);
3859 });
3860 }
3861
3862 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3863 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3864 original_indent_columns: Vec::new(),
3865 });
3866 self.insert_with_autoindent_mode(text, autoindent, cx);
3867 }
3868
3869 fn insert_with_autoindent_mode(
3870 &mut self,
3871 text: &str,
3872 autoindent_mode: Option<AutoindentMode>,
3873 cx: &mut ViewContext<Self>,
3874 ) {
3875 if self.read_only(cx) {
3876 return;
3877 }
3878
3879 let text: Arc<str> = text.into();
3880 self.transact(cx, |this, cx| {
3881 let old_selections = this.selections.all_adjusted(cx);
3882 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3883 let anchors = {
3884 let snapshot = buffer.read(cx);
3885 old_selections
3886 .iter()
3887 .map(|s| {
3888 let anchor = snapshot.anchor_after(s.head());
3889 s.map(|_| anchor)
3890 })
3891 .collect::<Vec<_>>()
3892 };
3893 buffer.edit(
3894 old_selections
3895 .iter()
3896 .map(|s| (s.start..s.end, text.clone())),
3897 autoindent_mode,
3898 cx,
3899 );
3900 anchors
3901 });
3902
3903 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3904 s.select_anchors(selection_anchors);
3905 })
3906 });
3907 }
3908
3909 fn trigger_completion_on_input(
3910 &mut self,
3911 text: &str,
3912 trigger_in_words: bool,
3913 cx: &mut ViewContext<Self>,
3914 ) {
3915 if self.is_completion_trigger(text, trigger_in_words, cx) {
3916 self.show_completions(
3917 &ShowCompletions {
3918 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3919 },
3920 cx,
3921 );
3922 } else {
3923 self.hide_context_menu(cx);
3924 }
3925 }
3926
3927 fn is_completion_trigger(
3928 &self,
3929 text: &str,
3930 trigger_in_words: bool,
3931 cx: &mut ViewContext<Self>,
3932 ) -> bool {
3933 let position = self.selections.newest_anchor().head();
3934 let multibuffer = self.buffer.read(cx);
3935 let Some(buffer) = position
3936 .buffer_id
3937 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3938 else {
3939 return false;
3940 };
3941
3942 if let Some(completion_provider) = &self.completion_provider {
3943 completion_provider.is_completion_trigger(
3944 &buffer,
3945 position.text_anchor,
3946 text,
3947 trigger_in_words,
3948 cx,
3949 )
3950 } else {
3951 false
3952 }
3953 }
3954
3955 /// If any empty selections is touching the start of its innermost containing autoclose
3956 /// region, expand it to select the brackets.
3957 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3958 let selections = self.selections.all::<usize>(cx);
3959 let buffer = self.buffer.read(cx).read(cx);
3960 let new_selections = self
3961 .selections_with_autoclose_regions(selections, &buffer)
3962 .map(|(mut selection, region)| {
3963 if !selection.is_empty() {
3964 return selection;
3965 }
3966
3967 if let Some(region) = region {
3968 let mut range = region.range.to_offset(&buffer);
3969 if selection.start == range.start && range.start >= region.pair.start.len() {
3970 range.start -= region.pair.start.len();
3971 if buffer.contains_str_at(range.start, ®ion.pair.start)
3972 && buffer.contains_str_at(range.end, ®ion.pair.end)
3973 {
3974 range.end += region.pair.end.len();
3975 selection.start = range.start;
3976 selection.end = range.end;
3977
3978 return selection;
3979 }
3980 }
3981 }
3982
3983 let always_treat_brackets_as_autoclosed = buffer
3984 .settings_at(selection.start, cx)
3985 .always_treat_brackets_as_autoclosed;
3986
3987 if !always_treat_brackets_as_autoclosed {
3988 return selection;
3989 }
3990
3991 if let Some(scope) = buffer.language_scope_at(selection.start) {
3992 for (pair, enabled) in scope.brackets() {
3993 if !enabled || !pair.close {
3994 continue;
3995 }
3996
3997 if buffer.contains_str_at(selection.start, &pair.end) {
3998 let pair_start_len = pair.start.len();
3999 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4000 {
4001 selection.start -= pair_start_len;
4002 selection.end += pair.end.len();
4003
4004 return selection;
4005 }
4006 }
4007 }
4008 }
4009
4010 selection
4011 })
4012 .collect();
4013
4014 drop(buffer);
4015 self.change_selections(None, cx, |selections| selections.select(new_selections));
4016 }
4017
4018 /// Iterate the given selections, and for each one, find the smallest surrounding
4019 /// autoclose region. This uses the ordering of the selections and the autoclose
4020 /// regions to avoid repeated comparisons.
4021 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4022 &'a self,
4023 selections: impl IntoIterator<Item = Selection<D>>,
4024 buffer: &'a MultiBufferSnapshot,
4025 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4026 let mut i = 0;
4027 let mut regions = self.autoclose_regions.as_slice();
4028 selections.into_iter().map(move |selection| {
4029 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4030
4031 let mut enclosing = None;
4032 while let Some(pair_state) = regions.get(i) {
4033 if pair_state.range.end.to_offset(buffer) < range.start {
4034 regions = ®ions[i + 1..];
4035 i = 0;
4036 } else if pair_state.range.start.to_offset(buffer) > range.end {
4037 break;
4038 } else {
4039 if pair_state.selection_id == selection.id {
4040 enclosing = Some(pair_state);
4041 }
4042 i += 1;
4043 }
4044 }
4045
4046 (selection, enclosing)
4047 })
4048 }
4049
4050 /// Remove any autoclose regions that no longer contain their selection.
4051 fn invalidate_autoclose_regions(
4052 &mut self,
4053 mut selections: &[Selection<Anchor>],
4054 buffer: &MultiBufferSnapshot,
4055 ) {
4056 self.autoclose_regions.retain(|state| {
4057 let mut i = 0;
4058 while let Some(selection) = selections.get(i) {
4059 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4060 selections = &selections[1..];
4061 continue;
4062 }
4063 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4064 break;
4065 }
4066 if selection.id == state.selection_id {
4067 return true;
4068 } else {
4069 i += 1;
4070 }
4071 }
4072 false
4073 });
4074 }
4075
4076 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4077 let offset = position.to_offset(buffer);
4078 let (word_range, kind) = buffer.surrounding_word(offset, true);
4079 if offset > word_range.start && kind == Some(CharKind::Word) {
4080 Some(
4081 buffer
4082 .text_for_range(word_range.start..offset)
4083 .collect::<String>(),
4084 )
4085 } else {
4086 None
4087 }
4088 }
4089
4090 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4091 self.refresh_inlay_hints(
4092 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4093 cx,
4094 );
4095 }
4096
4097 pub fn inlay_hints_enabled(&self) -> bool {
4098 self.inlay_hint_cache.enabled
4099 }
4100
4101 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4102 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4103 return;
4104 }
4105
4106 let reason_description = reason.description();
4107 let ignore_debounce = matches!(
4108 reason,
4109 InlayHintRefreshReason::SettingsChange(_)
4110 | InlayHintRefreshReason::Toggle(_)
4111 | InlayHintRefreshReason::ExcerptsRemoved(_)
4112 );
4113 let (invalidate_cache, required_languages) = match reason {
4114 InlayHintRefreshReason::Toggle(enabled) => {
4115 self.inlay_hint_cache.enabled = enabled;
4116 if enabled {
4117 (InvalidationStrategy::RefreshRequested, None)
4118 } else {
4119 self.inlay_hint_cache.clear();
4120 self.splice_inlays(
4121 self.visible_inlay_hints(cx)
4122 .iter()
4123 .map(|inlay| inlay.id)
4124 .collect(),
4125 Vec::new(),
4126 cx,
4127 );
4128 return;
4129 }
4130 }
4131 InlayHintRefreshReason::SettingsChange(new_settings) => {
4132 match self.inlay_hint_cache.update_settings(
4133 &self.buffer,
4134 new_settings,
4135 self.visible_inlay_hints(cx),
4136 cx,
4137 ) {
4138 ControlFlow::Break(Some(InlaySplice {
4139 to_remove,
4140 to_insert,
4141 })) => {
4142 self.splice_inlays(to_remove, to_insert, cx);
4143 return;
4144 }
4145 ControlFlow::Break(None) => return,
4146 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4147 }
4148 }
4149 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4150 if let Some(InlaySplice {
4151 to_remove,
4152 to_insert,
4153 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4154 {
4155 self.splice_inlays(to_remove, to_insert, cx);
4156 }
4157 return;
4158 }
4159 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4160 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4161 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4162 }
4163 InlayHintRefreshReason::RefreshRequested => {
4164 (InvalidationStrategy::RefreshRequested, None)
4165 }
4166 };
4167
4168 if let Some(InlaySplice {
4169 to_remove,
4170 to_insert,
4171 }) = self.inlay_hint_cache.spawn_hint_refresh(
4172 reason_description,
4173 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4174 invalidate_cache,
4175 ignore_debounce,
4176 cx,
4177 ) {
4178 self.splice_inlays(to_remove, to_insert, cx);
4179 }
4180 }
4181
4182 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4183 self.display_map
4184 .read(cx)
4185 .current_inlays()
4186 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4187 .cloned()
4188 .collect()
4189 }
4190
4191 pub fn excerpts_for_inlay_hints_query(
4192 &self,
4193 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4194 cx: &mut ViewContext<Editor>,
4195 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4196 let Some(project) = self.project.as_ref() else {
4197 return HashMap::default();
4198 };
4199 let project = project.read(cx);
4200 let multi_buffer = self.buffer().read(cx);
4201 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4202 let multi_buffer_visible_start = self
4203 .scroll_manager
4204 .anchor()
4205 .anchor
4206 .to_point(&multi_buffer_snapshot);
4207 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4208 multi_buffer_visible_start
4209 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4210 Bias::Left,
4211 );
4212 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4213 multi_buffer
4214 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4215 .into_iter()
4216 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4217 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4218 let buffer = buffer_handle.read(cx);
4219 let buffer_file = project::File::from_dyn(buffer.file())?;
4220 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4221 let worktree_entry = buffer_worktree
4222 .read(cx)
4223 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4224 if worktree_entry.is_ignored {
4225 return None;
4226 }
4227
4228 let language = buffer.language()?;
4229 if let Some(restrict_to_languages) = restrict_to_languages {
4230 if !restrict_to_languages.contains(language) {
4231 return None;
4232 }
4233 }
4234 Some((
4235 excerpt_id,
4236 (
4237 buffer_handle,
4238 buffer.version().clone(),
4239 excerpt_visible_range,
4240 ),
4241 ))
4242 })
4243 .collect()
4244 }
4245
4246 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4247 TextLayoutDetails {
4248 text_system: cx.text_system().clone(),
4249 editor_style: self.style.clone().unwrap(),
4250 rem_size: cx.rem_size(),
4251 scroll_anchor: self.scroll_manager.anchor(),
4252 visible_rows: self.visible_line_count(),
4253 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4254 }
4255 }
4256
4257 fn splice_inlays(
4258 &self,
4259 to_remove: Vec<InlayId>,
4260 to_insert: Vec<Inlay>,
4261 cx: &mut ViewContext<Self>,
4262 ) {
4263 self.display_map.update(cx, |display_map, cx| {
4264 display_map.splice_inlays(to_remove, to_insert, cx);
4265 });
4266 cx.notify();
4267 }
4268
4269 fn trigger_on_type_formatting(
4270 &self,
4271 input: String,
4272 cx: &mut ViewContext<Self>,
4273 ) -> Option<Task<Result<()>>> {
4274 if input.len() != 1 {
4275 return None;
4276 }
4277
4278 let project = self.project.as_ref()?;
4279 let position = self.selections.newest_anchor().head();
4280 let (buffer, buffer_position) = self
4281 .buffer
4282 .read(cx)
4283 .text_anchor_for_position(position, cx)?;
4284
4285 let settings = language_settings::language_settings(
4286 buffer
4287 .read(cx)
4288 .language_at(buffer_position)
4289 .map(|l| l.name()),
4290 buffer.read(cx).file(),
4291 cx,
4292 );
4293 if !settings.use_on_type_format {
4294 return None;
4295 }
4296
4297 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4298 // hence we do LSP request & edit on host side only — add formats to host's history.
4299 let push_to_lsp_host_history = true;
4300 // If this is not the host, append its history with new edits.
4301 let push_to_client_history = project.read(cx).is_via_collab();
4302
4303 let on_type_formatting = project.update(cx, |project, cx| {
4304 project.on_type_format(
4305 buffer.clone(),
4306 buffer_position,
4307 input,
4308 push_to_lsp_host_history,
4309 cx,
4310 )
4311 });
4312 Some(cx.spawn(|editor, mut cx| async move {
4313 if let Some(transaction) = on_type_formatting.await? {
4314 if push_to_client_history {
4315 buffer
4316 .update(&mut cx, |buffer, _| {
4317 buffer.push_transaction(transaction, Instant::now());
4318 })
4319 .ok();
4320 }
4321 editor.update(&mut cx, |editor, cx| {
4322 editor.refresh_document_highlights(cx);
4323 })?;
4324 }
4325 Ok(())
4326 }))
4327 }
4328
4329 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4330 if self.pending_rename.is_some() {
4331 return;
4332 }
4333
4334 let Some(provider) = self.completion_provider.as_ref() else {
4335 return;
4336 };
4337
4338 let position = self.selections.newest_anchor().head();
4339 let (buffer, buffer_position) =
4340 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4341 output
4342 } else {
4343 return;
4344 };
4345
4346 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4347 let is_followup_invoke = {
4348 let context_menu_state = self.context_menu.read();
4349 matches!(
4350 context_menu_state.deref(),
4351 Some(ContextMenu::Completions(_))
4352 )
4353 };
4354 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4355 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4356 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4357 CompletionTriggerKind::TRIGGER_CHARACTER
4358 }
4359
4360 _ => CompletionTriggerKind::INVOKED,
4361 };
4362 let completion_context = CompletionContext {
4363 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4364 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4365 Some(String::from(trigger))
4366 } else {
4367 None
4368 }
4369 }),
4370 trigger_kind,
4371 };
4372 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4373 let sort_completions = provider.sort_completions();
4374
4375 let id = post_inc(&mut self.next_completion_id);
4376 let task = cx.spawn(|this, mut cx| {
4377 async move {
4378 this.update(&mut cx, |this, _| {
4379 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4380 })?;
4381 let completions = completions.await.log_err();
4382 let menu = if let Some(completions) = completions {
4383 let mut menu = CompletionsMenu {
4384 id,
4385 sort_completions,
4386 initial_position: position,
4387 match_candidates: completions
4388 .iter()
4389 .enumerate()
4390 .map(|(id, completion)| {
4391 StringMatchCandidate::new(
4392 id,
4393 completion.label.text[completion.label.filter_range.clone()]
4394 .into(),
4395 )
4396 })
4397 .collect(),
4398 buffer: buffer.clone(),
4399 completions: Arc::new(RwLock::new(completions.into())),
4400 matches: Vec::new().into(),
4401 selected_item: 0,
4402 scroll_handle: UniformListScrollHandle::new(),
4403 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4404 DebouncedDelay::new(),
4405 )),
4406 };
4407 menu.filter(query.as_deref(), cx.background_executor().clone())
4408 .await;
4409
4410 if menu.matches.is_empty() {
4411 None
4412 } else {
4413 this.update(&mut cx, |editor, cx| {
4414 let completions = menu.completions.clone();
4415 let matches = menu.matches.clone();
4416
4417 let delay_ms = EditorSettings::get_global(cx)
4418 .completion_documentation_secondary_query_debounce;
4419 let delay = Duration::from_millis(delay_ms);
4420 editor
4421 .completion_documentation_pre_resolve_debounce
4422 .fire_new(delay, cx, |editor, cx| {
4423 CompletionsMenu::pre_resolve_completion_documentation(
4424 buffer,
4425 completions,
4426 matches,
4427 editor,
4428 cx,
4429 )
4430 });
4431 })
4432 .ok();
4433 Some(menu)
4434 }
4435 } else {
4436 None
4437 };
4438
4439 this.update(&mut cx, |this, cx| {
4440 let mut context_menu = this.context_menu.write();
4441 match context_menu.as_ref() {
4442 None => {}
4443
4444 Some(ContextMenu::Completions(prev_menu)) => {
4445 if prev_menu.id > id {
4446 return;
4447 }
4448 }
4449
4450 _ => return,
4451 }
4452
4453 if this.focus_handle.is_focused(cx) && menu.is_some() {
4454 let menu = menu.unwrap();
4455 *context_menu = Some(ContextMenu::Completions(menu));
4456 drop(context_menu);
4457 this.discard_inline_completion(false, cx);
4458 cx.notify();
4459 } else if this.completion_tasks.len() <= 1 {
4460 // If there are no more completion tasks and the last menu was
4461 // empty, we should hide it. If it was already hidden, we should
4462 // also show the copilot completion when available.
4463 drop(context_menu);
4464 if this.hide_context_menu(cx).is_none() {
4465 this.update_visible_inline_completion(cx);
4466 }
4467 }
4468 })?;
4469
4470 Ok::<_, anyhow::Error>(())
4471 }
4472 .log_err()
4473 });
4474
4475 self.completion_tasks.push((id, task));
4476 }
4477
4478 pub fn confirm_completion(
4479 &mut self,
4480 action: &ConfirmCompletion,
4481 cx: &mut ViewContext<Self>,
4482 ) -> Option<Task<Result<()>>> {
4483 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4484 }
4485
4486 pub fn compose_completion(
4487 &mut self,
4488 action: &ComposeCompletion,
4489 cx: &mut ViewContext<Self>,
4490 ) -> Option<Task<Result<()>>> {
4491 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4492 }
4493
4494 fn do_completion(
4495 &mut self,
4496 item_ix: Option<usize>,
4497 intent: CompletionIntent,
4498 cx: &mut ViewContext<Editor>,
4499 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4500 use language::ToOffset as _;
4501
4502 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4503 menu
4504 } else {
4505 return None;
4506 };
4507
4508 let mat = completions_menu
4509 .matches
4510 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4511 let buffer_handle = completions_menu.buffer;
4512 let completions = completions_menu.completions.read();
4513 let completion = completions.get(mat.candidate_id)?;
4514 cx.stop_propagation();
4515
4516 let snippet;
4517 let text;
4518
4519 if completion.is_snippet() {
4520 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4521 text = snippet.as_ref().unwrap().text.clone();
4522 } else {
4523 snippet = None;
4524 text = completion.new_text.clone();
4525 };
4526 let selections = self.selections.all::<usize>(cx);
4527 let buffer = buffer_handle.read(cx);
4528 let old_range = completion.old_range.to_offset(buffer);
4529 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4530
4531 let newest_selection = self.selections.newest_anchor();
4532 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4533 return None;
4534 }
4535
4536 let lookbehind = newest_selection
4537 .start
4538 .text_anchor
4539 .to_offset(buffer)
4540 .saturating_sub(old_range.start);
4541 let lookahead = old_range
4542 .end
4543 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4544 let mut common_prefix_len = old_text
4545 .bytes()
4546 .zip(text.bytes())
4547 .take_while(|(a, b)| a == b)
4548 .count();
4549
4550 let snapshot = self.buffer.read(cx).snapshot(cx);
4551 let mut range_to_replace: Option<Range<isize>> = None;
4552 let mut ranges = Vec::new();
4553 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4554 for selection in &selections {
4555 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4556 let start = selection.start.saturating_sub(lookbehind);
4557 let end = selection.end + lookahead;
4558 if selection.id == newest_selection.id {
4559 range_to_replace = Some(
4560 ((start + common_prefix_len) as isize - selection.start as isize)
4561 ..(end as isize - selection.start as isize),
4562 );
4563 }
4564 ranges.push(start + common_prefix_len..end);
4565 } else {
4566 common_prefix_len = 0;
4567 ranges.clear();
4568 ranges.extend(selections.iter().map(|s| {
4569 if s.id == newest_selection.id {
4570 range_to_replace = Some(
4571 old_range.start.to_offset_utf16(&snapshot).0 as isize
4572 - selection.start as isize
4573 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4574 - selection.start as isize,
4575 );
4576 old_range.clone()
4577 } else {
4578 s.start..s.end
4579 }
4580 }));
4581 break;
4582 }
4583 if !self.linked_edit_ranges.is_empty() {
4584 let start_anchor = snapshot.anchor_before(selection.head());
4585 let end_anchor = snapshot.anchor_after(selection.tail());
4586 if let Some(ranges) = self
4587 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4588 {
4589 for (buffer, edits) in ranges {
4590 linked_edits.entry(buffer.clone()).or_default().extend(
4591 edits
4592 .into_iter()
4593 .map(|range| (range, text[common_prefix_len..].to_owned())),
4594 );
4595 }
4596 }
4597 }
4598 }
4599 let text = &text[common_prefix_len..];
4600
4601 cx.emit(EditorEvent::InputHandled {
4602 utf16_range_to_replace: range_to_replace,
4603 text: text.into(),
4604 });
4605
4606 self.transact(cx, |this, cx| {
4607 if let Some(mut snippet) = snippet {
4608 snippet.text = text.to_string();
4609 for tabstop in snippet.tabstops.iter_mut().flatten() {
4610 tabstop.start -= common_prefix_len as isize;
4611 tabstop.end -= common_prefix_len as isize;
4612 }
4613
4614 this.insert_snippet(&ranges, snippet, cx).log_err();
4615 } else {
4616 this.buffer.update(cx, |buffer, cx| {
4617 buffer.edit(
4618 ranges.iter().map(|range| (range.clone(), text)),
4619 this.autoindent_mode.clone(),
4620 cx,
4621 );
4622 });
4623 }
4624 for (buffer, edits) in linked_edits {
4625 buffer.update(cx, |buffer, cx| {
4626 let snapshot = buffer.snapshot();
4627 let edits = edits
4628 .into_iter()
4629 .map(|(range, text)| {
4630 use text::ToPoint as TP;
4631 let end_point = TP::to_point(&range.end, &snapshot);
4632 let start_point = TP::to_point(&range.start, &snapshot);
4633 (start_point..end_point, text)
4634 })
4635 .sorted_by_key(|(range, _)| range.start)
4636 .collect::<Vec<_>>();
4637 buffer.edit(edits, None, cx);
4638 })
4639 }
4640
4641 this.refresh_inline_completion(true, false, cx);
4642 });
4643
4644 let show_new_completions_on_confirm = completion
4645 .confirm
4646 .as_ref()
4647 .map_or(false, |confirm| confirm(intent, cx));
4648 if show_new_completions_on_confirm {
4649 self.show_completions(&ShowCompletions { trigger: None }, cx);
4650 }
4651
4652 let provider = self.completion_provider.as_ref()?;
4653 let apply_edits = provider.apply_additional_edits_for_completion(
4654 buffer_handle,
4655 completion.clone(),
4656 true,
4657 cx,
4658 );
4659
4660 let editor_settings = EditorSettings::get_global(cx);
4661 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4662 // After the code completion is finished, users often want to know what signatures are needed.
4663 // so we should automatically call signature_help
4664 self.show_signature_help(&ShowSignatureHelp, cx);
4665 }
4666
4667 Some(cx.foreground_executor().spawn(async move {
4668 apply_edits.await?;
4669 Ok(())
4670 }))
4671 }
4672
4673 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4674 let mut context_menu = self.context_menu.write();
4675 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4676 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4677 // Toggle if we're selecting the same one
4678 *context_menu = None;
4679 cx.notify();
4680 return;
4681 } else {
4682 // Otherwise, clear it and start a new one
4683 *context_menu = None;
4684 cx.notify();
4685 }
4686 }
4687 drop(context_menu);
4688 let snapshot = self.snapshot(cx);
4689 let deployed_from_indicator = action.deployed_from_indicator;
4690 let mut task = self.code_actions_task.take();
4691 let action = action.clone();
4692 cx.spawn(|editor, mut cx| async move {
4693 while let Some(prev_task) = task {
4694 prev_task.await.log_err();
4695 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4696 }
4697
4698 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4699 if editor.focus_handle.is_focused(cx) {
4700 let multibuffer_point = action
4701 .deployed_from_indicator
4702 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4703 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4704 let (buffer, buffer_row) = snapshot
4705 .buffer_snapshot
4706 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4707 .and_then(|(buffer_snapshot, range)| {
4708 editor
4709 .buffer
4710 .read(cx)
4711 .buffer(buffer_snapshot.remote_id())
4712 .map(|buffer| (buffer, range.start.row))
4713 })?;
4714 let (_, code_actions) = editor
4715 .available_code_actions
4716 .clone()
4717 .and_then(|(location, code_actions)| {
4718 let snapshot = location.buffer.read(cx).snapshot();
4719 let point_range = location.range.to_point(&snapshot);
4720 let point_range = point_range.start.row..=point_range.end.row;
4721 if point_range.contains(&buffer_row) {
4722 Some((location, code_actions))
4723 } else {
4724 None
4725 }
4726 })
4727 .unzip();
4728 let buffer_id = buffer.read(cx).remote_id();
4729 let tasks = editor
4730 .tasks
4731 .get(&(buffer_id, buffer_row))
4732 .map(|t| Arc::new(t.to_owned()));
4733 if tasks.is_none() && code_actions.is_none() {
4734 return None;
4735 }
4736
4737 editor.completion_tasks.clear();
4738 editor.discard_inline_completion(false, cx);
4739 let task_context =
4740 tasks
4741 .as_ref()
4742 .zip(editor.project.clone())
4743 .map(|(tasks, project)| {
4744 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4745 });
4746
4747 Some(cx.spawn(|editor, mut cx| async move {
4748 let task_context = match task_context {
4749 Some(task_context) => task_context.await,
4750 None => None,
4751 };
4752 let resolved_tasks =
4753 tasks.zip(task_context).map(|(tasks, task_context)| {
4754 Arc::new(ResolvedTasks {
4755 templates: tasks.resolve(&task_context).collect(),
4756 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4757 multibuffer_point.row,
4758 tasks.column,
4759 )),
4760 })
4761 });
4762 let spawn_straight_away = resolved_tasks
4763 .as_ref()
4764 .map_or(false, |tasks| tasks.templates.len() == 1)
4765 && code_actions
4766 .as_ref()
4767 .map_or(true, |actions| actions.is_empty());
4768 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4769 *editor.context_menu.write() =
4770 Some(ContextMenu::CodeActions(CodeActionsMenu {
4771 buffer,
4772 actions: CodeActionContents {
4773 tasks: resolved_tasks,
4774 actions: code_actions,
4775 },
4776 selected_item: Default::default(),
4777 scroll_handle: UniformListScrollHandle::default(),
4778 deployed_from_indicator,
4779 }));
4780 if spawn_straight_away {
4781 if let Some(task) = editor.confirm_code_action(
4782 &ConfirmCodeAction { item_ix: Some(0) },
4783 cx,
4784 ) {
4785 cx.notify();
4786 return task;
4787 }
4788 }
4789 cx.notify();
4790 Task::ready(Ok(()))
4791 }) {
4792 task.await
4793 } else {
4794 Ok(())
4795 }
4796 }))
4797 } else {
4798 Some(Task::ready(Ok(())))
4799 }
4800 })?;
4801 if let Some(task) = spawned_test_task {
4802 task.await?;
4803 }
4804
4805 Ok::<_, anyhow::Error>(())
4806 })
4807 .detach_and_log_err(cx);
4808 }
4809
4810 pub fn confirm_code_action(
4811 &mut self,
4812 action: &ConfirmCodeAction,
4813 cx: &mut ViewContext<Self>,
4814 ) -> Option<Task<Result<()>>> {
4815 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4816 menu
4817 } else {
4818 return None;
4819 };
4820 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4821 let action = actions_menu.actions.get(action_ix)?;
4822 let title = action.label();
4823 let buffer = actions_menu.buffer;
4824 let workspace = self.workspace()?;
4825
4826 match action {
4827 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4828 workspace.update(cx, |workspace, cx| {
4829 workspace::tasks::schedule_resolved_task(
4830 workspace,
4831 task_source_kind,
4832 resolved_task,
4833 false,
4834 cx,
4835 );
4836
4837 Some(Task::ready(Ok(())))
4838 })
4839 }
4840 CodeActionsItem::CodeAction {
4841 excerpt_id,
4842 action,
4843 provider,
4844 } => {
4845 let apply_code_action =
4846 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4847 let workspace = workspace.downgrade();
4848 Some(cx.spawn(|editor, cx| async move {
4849 let project_transaction = apply_code_action.await?;
4850 Self::open_project_transaction(
4851 &editor,
4852 workspace,
4853 project_transaction,
4854 title,
4855 cx,
4856 )
4857 .await
4858 }))
4859 }
4860 }
4861 }
4862
4863 pub async fn open_project_transaction(
4864 this: &WeakView<Editor>,
4865 workspace: WeakView<Workspace>,
4866 transaction: ProjectTransaction,
4867 title: String,
4868 mut cx: AsyncWindowContext,
4869 ) -> Result<()> {
4870 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4871 cx.update(|cx| {
4872 entries.sort_unstable_by_key(|(buffer, _)| {
4873 buffer.read(cx).file().map(|f| f.path().clone())
4874 });
4875 })?;
4876
4877 // If the project transaction's edits are all contained within this editor, then
4878 // avoid opening a new editor to display them.
4879
4880 if let Some((buffer, transaction)) = entries.first() {
4881 if entries.len() == 1 {
4882 let excerpt = this.update(&mut cx, |editor, cx| {
4883 editor
4884 .buffer()
4885 .read(cx)
4886 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4887 })?;
4888 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4889 if excerpted_buffer == *buffer {
4890 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4891 let excerpt_range = excerpt_range.to_offset(buffer);
4892 buffer
4893 .edited_ranges_for_transaction::<usize>(transaction)
4894 .all(|range| {
4895 excerpt_range.start <= range.start
4896 && excerpt_range.end >= range.end
4897 })
4898 })?;
4899
4900 if all_edits_within_excerpt {
4901 return Ok(());
4902 }
4903 }
4904 }
4905 }
4906 } else {
4907 return Ok(());
4908 }
4909
4910 let mut ranges_to_highlight = Vec::new();
4911 let excerpt_buffer = cx.new_model(|cx| {
4912 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4913 for (buffer_handle, transaction) in &entries {
4914 let buffer = buffer_handle.read(cx);
4915 ranges_to_highlight.extend(
4916 multibuffer.push_excerpts_with_context_lines(
4917 buffer_handle.clone(),
4918 buffer
4919 .edited_ranges_for_transaction::<usize>(transaction)
4920 .collect(),
4921 DEFAULT_MULTIBUFFER_CONTEXT,
4922 cx,
4923 ),
4924 );
4925 }
4926 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4927 multibuffer
4928 })?;
4929
4930 workspace.update(&mut cx, |workspace, cx| {
4931 let project = workspace.project().clone();
4932 let editor =
4933 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4934 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4935 editor.update(cx, |editor, cx| {
4936 editor.highlight_background::<Self>(
4937 &ranges_to_highlight,
4938 |theme| theme.editor_highlighted_line_background,
4939 cx,
4940 );
4941 });
4942 })?;
4943
4944 Ok(())
4945 }
4946
4947 pub fn clear_code_action_providers(&mut self) {
4948 self.code_action_providers.clear();
4949 self.available_code_actions.take();
4950 }
4951
4952 pub fn push_code_action_provider(
4953 &mut self,
4954 provider: Arc<dyn CodeActionProvider>,
4955 cx: &mut ViewContext<Self>,
4956 ) {
4957 self.code_action_providers.push(provider);
4958 self.refresh_code_actions(cx);
4959 }
4960
4961 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4962 let buffer = self.buffer.read(cx);
4963 let newest_selection = self.selections.newest_anchor().clone();
4964 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4965 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4966 if start_buffer != end_buffer {
4967 return None;
4968 }
4969
4970 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4971 cx.background_executor()
4972 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4973 .await;
4974
4975 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4976 let providers = this.code_action_providers.clone();
4977 let tasks = this
4978 .code_action_providers
4979 .iter()
4980 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4981 .collect::<Vec<_>>();
4982 (providers, tasks)
4983 })?;
4984
4985 let mut actions = Vec::new();
4986 for (provider, provider_actions) in
4987 providers.into_iter().zip(future::join_all(tasks).await)
4988 {
4989 if let Some(provider_actions) = provider_actions.log_err() {
4990 actions.extend(provider_actions.into_iter().map(|action| {
4991 AvailableCodeAction {
4992 excerpt_id: newest_selection.start.excerpt_id,
4993 action,
4994 provider: provider.clone(),
4995 }
4996 }));
4997 }
4998 }
4999
5000 this.update(&mut cx, |this, cx| {
5001 this.available_code_actions = if actions.is_empty() {
5002 None
5003 } else {
5004 Some((
5005 Location {
5006 buffer: start_buffer,
5007 range: start..end,
5008 },
5009 actions.into(),
5010 ))
5011 };
5012 cx.notify();
5013 })
5014 }));
5015 None
5016 }
5017
5018 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5019 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5020 self.show_git_blame_inline = false;
5021
5022 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5023 cx.background_executor().timer(delay).await;
5024
5025 this.update(&mut cx, |this, cx| {
5026 this.show_git_blame_inline = true;
5027 cx.notify();
5028 })
5029 .log_err();
5030 }));
5031 }
5032 }
5033
5034 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5035 if self.pending_rename.is_some() {
5036 return None;
5037 }
5038
5039 let provider = self.semantics_provider.clone()?;
5040 let buffer = self.buffer.read(cx);
5041 let newest_selection = self.selections.newest_anchor().clone();
5042 let cursor_position = newest_selection.head();
5043 let (cursor_buffer, cursor_buffer_position) =
5044 buffer.text_anchor_for_position(cursor_position, cx)?;
5045 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5046 if cursor_buffer != tail_buffer {
5047 return None;
5048 }
5049
5050 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5051 cx.background_executor()
5052 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5053 .await;
5054
5055 let highlights = if let Some(highlights) = cx
5056 .update(|cx| {
5057 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5058 })
5059 .ok()
5060 .flatten()
5061 {
5062 highlights.await.log_err()
5063 } else {
5064 None
5065 };
5066
5067 if let Some(highlights) = highlights {
5068 this.update(&mut cx, |this, cx| {
5069 if this.pending_rename.is_some() {
5070 return;
5071 }
5072
5073 let buffer_id = cursor_position.buffer_id;
5074 let buffer = this.buffer.read(cx);
5075 if !buffer
5076 .text_anchor_for_position(cursor_position, cx)
5077 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5078 {
5079 return;
5080 }
5081
5082 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5083 let mut write_ranges = Vec::new();
5084 let mut read_ranges = Vec::new();
5085 for highlight in highlights {
5086 for (excerpt_id, excerpt_range) in
5087 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5088 {
5089 let start = highlight
5090 .range
5091 .start
5092 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5093 let end = highlight
5094 .range
5095 .end
5096 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5097 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5098 continue;
5099 }
5100
5101 let range = Anchor {
5102 buffer_id,
5103 excerpt_id,
5104 text_anchor: start,
5105 }..Anchor {
5106 buffer_id,
5107 excerpt_id,
5108 text_anchor: end,
5109 };
5110 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5111 write_ranges.push(range);
5112 } else {
5113 read_ranges.push(range);
5114 }
5115 }
5116 }
5117
5118 this.highlight_background::<DocumentHighlightRead>(
5119 &read_ranges,
5120 |theme| theme.editor_document_highlight_read_background,
5121 cx,
5122 );
5123 this.highlight_background::<DocumentHighlightWrite>(
5124 &write_ranges,
5125 |theme| theme.editor_document_highlight_write_background,
5126 cx,
5127 );
5128 cx.notify();
5129 })
5130 .log_err();
5131 }
5132 }));
5133 None
5134 }
5135
5136 pub fn refresh_inline_completion(
5137 &mut self,
5138 debounce: bool,
5139 user_requested: bool,
5140 cx: &mut ViewContext<Self>,
5141 ) -> Option<()> {
5142 let provider = self.inline_completion_provider()?;
5143 let cursor = self.selections.newest_anchor().head();
5144 let (buffer, cursor_buffer_position) =
5145 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5146
5147 if !user_requested
5148 && (!self.enable_inline_completions
5149 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5150 {
5151 self.discard_inline_completion(false, cx);
5152 return None;
5153 }
5154
5155 self.update_visible_inline_completion(cx);
5156 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5157 Some(())
5158 }
5159
5160 fn cycle_inline_completion(
5161 &mut self,
5162 direction: Direction,
5163 cx: &mut ViewContext<Self>,
5164 ) -> Option<()> {
5165 let provider = self.inline_completion_provider()?;
5166 let cursor = self.selections.newest_anchor().head();
5167 let (buffer, cursor_buffer_position) =
5168 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5169 if !self.enable_inline_completions
5170 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5171 {
5172 return None;
5173 }
5174
5175 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5176 self.update_visible_inline_completion(cx);
5177
5178 Some(())
5179 }
5180
5181 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5182 if !self.has_active_inline_completion(cx) {
5183 self.refresh_inline_completion(false, true, cx);
5184 return;
5185 }
5186
5187 self.update_visible_inline_completion(cx);
5188 }
5189
5190 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5191 self.show_cursor_names(cx);
5192 }
5193
5194 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5195 self.show_cursor_names = true;
5196 cx.notify();
5197 cx.spawn(|this, mut cx| async move {
5198 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5199 this.update(&mut cx, |this, cx| {
5200 this.show_cursor_names = false;
5201 cx.notify()
5202 })
5203 .ok()
5204 })
5205 .detach();
5206 }
5207
5208 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5209 if self.has_active_inline_completion(cx) {
5210 self.cycle_inline_completion(Direction::Next, cx);
5211 } else {
5212 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5213 if is_copilot_disabled {
5214 cx.propagate();
5215 }
5216 }
5217 }
5218
5219 pub fn previous_inline_completion(
5220 &mut self,
5221 _: &PreviousInlineCompletion,
5222 cx: &mut ViewContext<Self>,
5223 ) {
5224 if self.has_active_inline_completion(cx) {
5225 self.cycle_inline_completion(Direction::Prev, cx);
5226 } else {
5227 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5228 if is_copilot_disabled {
5229 cx.propagate();
5230 }
5231 }
5232 }
5233
5234 pub fn accept_inline_completion(
5235 &mut self,
5236 _: &AcceptInlineCompletion,
5237 cx: &mut ViewContext<Self>,
5238 ) {
5239 let Some(completion) = self.take_active_inline_completion(cx) else {
5240 return;
5241 };
5242 if let Some(provider) = self.inline_completion_provider() {
5243 provider.accept(cx);
5244 }
5245
5246 cx.emit(EditorEvent::InputHandled {
5247 utf16_range_to_replace: None,
5248 text: completion.text.to_string().into(),
5249 });
5250
5251 if let Some(range) = completion.delete_range {
5252 self.change_selections(None, cx, |s| s.select_ranges([range]))
5253 }
5254 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5255 self.refresh_inline_completion(true, true, cx);
5256 cx.notify();
5257 }
5258
5259 pub fn accept_partial_inline_completion(
5260 &mut self,
5261 _: &AcceptPartialInlineCompletion,
5262 cx: &mut ViewContext<Self>,
5263 ) {
5264 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5265 if let Some(completion) = self.take_active_inline_completion(cx) {
5266 let mut partial_completion = completion
5267 .text
5268 .chars()
5269 .by_ref()
5270 .take_while(|c| c.is_alphabetic())
5271 .collect::<String>();
5272 if partial_completion.is_empty() {
5273 partial_completion = completion
5274 .text
5275 .chars()
5276 .by_ref()
5277 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5278 .collect::<String>();
5279 }
5280
5281 cx.emit(EditorEvent::InputHandled {
5282 utf16_range_to_replace: None,
5283 text: partial_completion.clone().into(),
5284 });
5285
5286 if let Some(range) = completion.delete_range {
5287 self.change_selections(None, cx, |s| s.select_ranges([range]))
5288 }
5289 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5290
5291 self.refresh_inline_completion(true, true, cx);
5292 cx.notify();
5293 }
5294 }
5295 }
5296
5297 fn discard_inline_completion(
5298 &mut self,
5299 should_report_inline_completion_event: bool,
5300 cx: &mut ViewContext<Self>,
5301 ) -> bool {
5302 if let Some(provider) = self.inline_completion_provider() {
5303 provider.discard(should_report_inline_completion_event, cx);
5304 }
5305
5306 self.take_active_inline_completion(cx).is_some()
5307 }
5308
5309 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5310 if let Some(completion) = self.active_inline_completion.as_ref() {
5311 let buffer = self.buffer.read(cx).read(cx);
5312 completion.position.is_valid(&buffer)
5313 } else {
5314 false
5315 }
5316 }
5317
5318 fn take_active_inline_completion(
5319 &mut self,
5320 cx: &mut ViewContext<Self>,
5321 ) -> Option<CompletionState> {
5322 let completion = self.active_inline_completion.take()?;
5323 let render_inlay_ids = completion.render_inlay_ids.clone();
5324 self.display_map.update(cx, |map, cx| {
5325 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5326 });
5327 let buffer = self.buffer.read(cx).read(cx);
5328
5329 if completion.position.is_valid(&buffer) {
5330 Some(completion)
5331 } else {
5332 None
5333 }
5334 }
5335
5336 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5337 let selection = self.selections.newest_anchor();
5338 let cursor = selection.head();
5339
5340 let excerpt_id = cursor.excerpt_id;
5341
5342 if self.context_menu.read().is_none()
5343 && self.completion_tasks.is_empty()
5344 && selection.start == selection.end
5345 {
5346 if let Some(provider) = self.inline_completion_provider() {
5347 if let Some((buffer, cursor_buffer_position)) =
5348 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5349 {
5350 if let Some(proposal) =
5351 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5352 {
5353 let mut to_remove = Vec::new();
5354 if let Some(completion) = self.active_inline_completion.take() {
5355 to_remove.extend(completion.render_inlay_ids.iter());
5356 }
5357
5358 let to_add = proposal
5359 .inlays
5360 .iter()
5361 .filter_map(|inlay| {
5362 let snapshot = self.buffer.read(cx).snapshot(cx);
5363 let id = post_inc(&mut self.next_inlay_id);
5364 match inlay {
5365 InlayProposal::Hint(position, hint) => {
5366 let position =
5367 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5368 Some(Inlay::hint(id, position, hint))
5369 }
5370 InlayProposal::Suggestion(position, text) => {
5371 let position =
5372 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5373 Some(Inlay::suggestion(id, position, text.clone()))
5374 }
5375 }
5376 })
5377 .collect_vec();
5378
5379 self.active_inline_completion = Some(CompletionState {
5380 position: cursor,
5381 text: proposal.text,
5382 delete_range: proposal.delete_range.and_then(|range| {
5383 let snapshot = self.buffer.read(cx).snapshot(cx);
5384 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5385 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5386 Some(start?..end?)
5387 }),
5388 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5389 });
5390
5391 self.display_map
5392 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5393
5394 cx.notify();
5395 return;
5396 }
5397 }
5398 }
5399 }
5400
5401 self.discard_inline_completion(false, cx);
5402 }
5403
5404 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5405 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5406 }
5407
5408 fn render_code_actions_indicator(
5409 &self,
5410 _style: &EditorStyle,
5411 row: DisplayRow,
5412 is_active: bool,
5413 cx: &mut ViewContext<Self>,
5414 ) -> Option<IconButton> {
5415 if self.available_code_actions.is_some() {
5416 Some(
5417 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5418 .shape(ui::IconButtonShape::Square)
5419 .icon_size(IconSize::XSmall)
5420 .icon_color(Color::Muted)
5421 .selected(is_active)
5422 .tooltip({
5423 let focus_handle = self.focus_handle.clone();
5424 move |cx| {
5425 Tooltip::for_action_in(
5426 "Toggle Code Actions",
5427 &ToggleCodeActions {
5428 deployed_from_indicator: None,
5429 },
5430 &focus_handle,
5431 cx,
5432 )
5433 }
5434 })
5435 .on_click(cx.listener(move |editor, _e, cx| {
5436 editor.focus(cx);
5437 editor.toggle_code_actions(
5438 &ToggleCodeActions {
5439 deployed_from_indicator: Some(row),
5440 },
5441 cx,
5442 );
5443 })),
5444 )
5445 } else {
5446 None
5447 }
5448 }
5449
5450 fn clear_tasks(&mut self) {
5451 self.tasks.clear()
5452 }
5453
5454 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5455 if self.tasks.insert(key, value).is_some() {
5456 // This case should hopefully be rare, but just in case...
5457 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5458 }
5459 }
5460
5461 fn build_tasks_context(
5462 project: &Model<Project>,
5463 buffer: &Model<Buffer>,
5464 buffer_row: u32,
5465 tasks: &Arc<RunnableTasks>,
5466 cx: &mut ViewContext<Self>,
5467 ) -> Task<Option<task::TaskContext>> {
5468 let position = Point::new(buffer_row, tasks.column);
5469 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5470 let location = Location {
5471 buffer: buffer.clone(),
5472 range: range_start..range_start,
5473 };
5474 // Fill in the environmental variables from the tree-sitter captures
5475 let mut captured_task_variables = TaskVariables::default();
5476 for (capture_name, value) in tasks.extra_variables.clone() {
5477 captured_task_variables.insert(
5478 task::VariableName::Custom(capture_name.into()),
5479 value.clone(),
5480 );
5481 }
5482 project.update(cx, |project, cx| {
5483 project.task_store().update(cx, |task_store, cx| {
5484 task_store.task_context_for_location(captured_task_variables, location, cx)
5485 })
5486 })
5487 }
5488
5489 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5490 let Some((workspace, _)) = self.workspace.clone() else {
5491 return;
5492 };
5493 let Some(project) = self.project.clone() else {
5494 return;
5495 };
5496
5497 // Try to find a closest, enclosing node using tree-sitter that has a
5498 // task
5499 let Some((buffer, buffer_row, tasks)) = self
5500 .find_enclosing_node_task(cx)
5501 // Or find the task that's closest in row-distance.
5502 .or_else(|| self.find_closest_task(cx))
5503 else {
5504 return;
5505 };
5506
5507 let reveal_strategy = action.reveal;
5508 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5509 cx.spawn(|_, mut cx| async move {
5510 let context = task_context.await?;
5511 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5512
5513 let resolved = resolved_task.resolved.as_mut()?;
5514 resolved.reveal = reveal_strategy;
5515
5516 workspace
5517 .update(&mut cx, |workspace, cx| {
5518 workspace::tasks::schedule_resolved_task(
5519 workspace,
5520 task_source_kind,
5521 resolved_task,
5522 false,
5523 cx,
5524 );
5525 })
5526 .ok()
5527 })
5528 .detach();
5529 }
5530
5531 fn find_closest_task(
5532 &mut self,
5533 cx: &mut ViewContext<Self>,
5534 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5535 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5536
5537 let ((buffer_id, row), tasks) = self
5538 .tasks
5539 .iter()
5540 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5541
5542 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5543 let tasks = Arc::new(tasks.to_owned());
5544 Some((buffer, *row, tasks))
5545 }
5546
5547 fn find_enclosing_node_task(
5548 &mut self,
5549 cx: &mut ViewContext<Self>,
5550 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5551 let snapshot = self.buffer.read(cx).snapshot(cx);
5552 let offset = self.selections.newest::<usize>(cx).head();
5553 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5554 let buffer_id = excerpt.buffer().remote_id();
5555
5556 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5557 let mut cursor = layer.node().walk();
5558
5559 while cursor.goto_first_child_for_byte(offset).is_some() {
5560 if cursor.node().end_byte() == offset {
5561 cursor.goto_next_sibling();
5562 }
5563 }
5564
5565 // Ascend to the smallest ancestor that contains the range and has a task.
5566 loop {
5567 let node = cursor.node();
5568 let node_range = node.byte_range();
5569 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5570
5571 // Check if this node contains our offset
5572 if node_range.start <= offset && node_range.end >= offset {
5573 // If it contains offset, check for task
5574 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5575 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5576 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5577 }
5578 }
5579
5580 if !cursor.goto_parent() {
5581 break;
5582 }
5583 }
5584 None
5585 }
5586
5587 fn render_run_indicator(
5588 &self,
5589 _style: &EditorStyle,
5590 is_active: bool,
5591 row: DisplayRow,
5592 cx: &mut ViewContext<Self>,
5593 ) -> IconButton {
5594 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5595 .shape(ui::IconButtonShape::Square)
5596 .icon_size(IconSize::XSmall)
5597 .icon_color(Color::Muted)
5598 .selected(is_active)
5599 .on_click(cx.listener(move |editor, _e, cx| {
5600 editor.focus(cx);
5601 editor.toggle_code_actions(
5602 &ToggleCodeActions {
5603 deployed_from_indicator: Some(row),
5604 },
5605 cx,
5606 );
5607 }))
5608 }
5609
5610 pub fn context_menu_visible(&self) -> bool {
5611 self.context_menu
5612 .read()
5613 .as_ref()
5614 .map_or(false, |menu| menu.visible())
5615 }
5616
5617 fn render_context_menu(
5618 &self,
5619 cursor_position: DisplayPoint,
5620 style: &EditorStyle,
5621 max_height: Pixels,
5622 cx: &mut ViewContext<Editor>,
5623 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5624 self.context_menu.read().as_ref().map(|menu| {
5625 menu.render(
5626 cursor_position,
5627 style,
5628 max_height,
5629 self.workspace.as_ref().map(|(w, _)| w.clone()),
5630 cx,
5631 )
5632 })
5633 }
5634
5635 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5636 cx.notify();
5637 self.completion_tasks.clear();
5638 let context_menu = self.context_menu.write().take();
5639 if context_menu.is_some() {
5640 self.update_visible_inline_completion(cx);
5641 }
5642 context_menu
5643 }
5644
5645 pub fn insert_snippet(
5646 &mut self,
5647 insertion_ranges: &[Range<usize>],
5648 snippet: Snippet,
5649 cx: &mut ViewContext<Self>,
5650 ) -> Result<()> {
5651 struct Tabstop<T> {
5652 is_end_tabstop: bool,
5653 ranges: Vec<Range<T>>,
5654 }
5655
5656 let tabstops = self.buffer.update(cx, |buffer, cx| {
5657 let snippet_text: Arc<str> = snippet.text.clone().into();
5658 buffer.edit(
5659 insertion_ranges
5660 .iter()
5661 .cloned()
5662 .map(|range| (range, snippet_text.clone())),
5663 Some(AutoindentMode::EachLine),
5664 cx,
5665 );
5666
5667 let snapshot = &*buffer.read(cx);
5668 let snippet = &snippet;
5669 snippet
5670 .tabstops
5671 .iter()
5672 .map(|tabstop| {
5673 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5674 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5675 });
5676 let mut tabstop_ranges = tabstop
5677 .iter()
5678 .flat_map(|tabstop_range| {
5679 let mut delta = 0_isize;
5680 insertion_ranges.iter().map(move |insertion_range| {
5681 let insertion_start = insertion_range.start as isize + delta;
5682 delta +=
5683 snippet.text.len() as isize - insertion_range.len() as isize;
5684
5685 let start = ((insertion_start + tabstop_range.start) as usize)
5686 .min(snapshot.len());
5687 let end = ((insertion_start + tabstop_range.end) as usize)
5688 .min(snapshot.len());
5689 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5690 })
5691 })
5692 .collect::<Vec<_>>();
5693 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5694
5695 Tabstop {
5696 is_end_tabstop,
5697 ranges: tabstop_ranges,
5698 }
5699 })
5700 .collect::<Vec<_>>()
5701 });
5702 if let Some(tabstop) = tabstops.first() {
5703 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5704 s.select_ranges(tabstop.ranges.iter().cloned());
5705 });
5706
5707 // If we're already at the last tabstop and it's at the end of the snippet,
5708 // we're done, we don't need to keep the state around.
5709 if !tabstop.is_end_tabstop {
5710 let ranges = tabstops
5711 .into_iter()
5712 .map(|tabstop| tabstop.ranges)
5713 .collect::<Vec<_>>();
5714 self.snippet_stack.push(SnippetState {
5715 active_index: 0,
5716 ranges,
5717 });
5718 }
5719
5720 // Check whether the just-entered snippet ends with an auto-closable bracket.
5721 if self.autoclose_regions.is_empty() {
5722 let snapshot = self.buffer.read(cx).snapshot(cx);
5723 for selection in &mut self.selections.all::<Point>(cx) {
5724 let selection_head = selection.head();
5725 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5726 continue;
5727 };
5728
5729 let mut bracket_pair = None;
5730 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5731 let prev_chars = snapshot
5732 .reversed_chars_at(selection_head)
5733 .collect::<String>();
5734 for (pair, enabled) in scope.brackets() {
5735 if enabled
5736 && pair.close
5737 && prev_chars.starts_with(pair.start.as_str())
5738 && next_chars.starts_with(pair.end.as_str())
5739 {
5740 bracket_pair = Some(pair.clone());
5741 break;
5742 }
5743 }
5744 if let Some(pair) = bracket_pair {
5745 let start = snapshot.anchor_after(selection_head);
5746 let end = snapshot.anchor_after(selection_head);
5747 self.autoclose_regions.push(AutocloseRegion {
5748 selection_id: selection.id,
5749 range: start..end,
5750 pair,
5751 });
5752 }
5753 }
5754 }
5755 }
5756 Ok(())
5757 }
5758
5759 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5760 self.move_to_snippet_tabstop(Bias::Right, cx)
5761 }
5762
5763 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5764 self.move_to_snippet_tabstop(Bias::Left, cx)
5765 }
5766
5767 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5768 if let Some(mut snippet) = self.snippet_stack.pop() {
5769 match bias {
5770 Bias::Left => {
5771 if snippet.active_index > 0 {
5772 snippet.active_index -= 1;
5773 } else {
5774 self.snippet_stack.push(snippet);
5775 return false;
5776 }
5777 }
5778 Bias::Right => {
5779 if snippet.active_index + 1 < snippet.ranges.len() {
5780 snippet.active_index += 1;
5781 } else {
5782 self.snippet_stack.push(snippet);
5783 return false;
5784 }
5785 }
5786 }
5787 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5788 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5789 s.select_anchor_ranges(current_ranges.iter().cloned())
5790 });
5791 // If snippet state is not at the last tabstop, push it back on the stack
5792 if snippet.active_index + 1 < snippet.ranges.len() {
5793 self.snippet_stack.push(snippet);
5794 }
5795 return true;
5796 }
5797 }
5798
5799 false
5800 }
5801
5802 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5803 self.transact(cx, |this, cx| {
5804 this.select_all(&SelectAll, cx);
5805 this.insert("", cx);
5806 });
5807 }
5808
5809 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5810 self.transact(cx, |this, cx| {
5811 this.select_autoclose_pair(cx);
5812 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5813 if !this.linked_edit_ranges.is_empty() {
5814 let selections = this.selections.all::<MultiBufferPoint>(cx);
5815 let snapshot = this.buffer.read(cx).snapshot(cx);
5816
5817 for selection in selections.iter() {
5818 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5819 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5820 if selection_start.buffer_id != selection_end.buffer_id {
5821 continue;
5822 }
5823 if let Some(ranges) =
5824 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5825 {
5826 for (buffer, entries) in ranges {
5827 linked_ranges.entry(buffer).or_default().extend(entries);
5828 }
5829 }
5830 }
5831 }
5832
5833 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5834 if !this.selections.line_mode {
5835 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5836 for selection in &mut selections {
5837 if selection.is_empty() {
5838 let old_head = selection.head();
5839 let mut new_head =
5840 movement::left(&display_map, old_head.to_display_point(&display_map))
5841 .to_point(&display_map);
5842 if let Some((buffer, line_buffer_range)) = display_map
5843 .buffer_snapshot
5844 .buffer_line_for_row(MultiBufferRow(old_head.row))
5845 {
5846 let indent_size =
5847 buffer.indent_size_for_line(line_buffer_range.start.row);
5848 let indent_len = match indent_size.kind {
5849 IndentKind::Space => {
5850 buffer.settings_at(line_buffer_range.start, cx).tab_size
5851 }
5852 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5853 };
5854 if old_head.column <= indent_size.len && old_head.column > 0 {
5855 let indent_len = indent_len.get();
5856 new_head = cmp::min(
5857 new_head,
5858 MultiBufferPoint::new(
5859 old_head.row,
5860 ((old_head.column - 1) / indent_len) * indent_len,
5861 ),
5862 );
5863 }
5864 }
5865
5866 selection.set_head(new_head, SelectionGoal::None);
5867 }
5868 }
5869 }
5870
5871 this.signature_help_state.set_backspace_pressed(true);
5872 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5873 this.insert("", cx);
5874 let empty_str: Arc<str> = Arc::from("");
5875 for (buffer, edits) in linked_ranges {
5876 let snapshot = buffer.read(cx).snapshot();
5877 use text::ToPoint as TP;
5878
5879 let edits = edits
5880 .into_iter()
5881 .map(|range| {
5882 let end_point = TP::to_point(&range.end, &snapshot);
5883 let mut start_point = TP::to_point(&range.start, &snapshot);
5884
5885 if end_point == start_point {
5886 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5887 .saturating_sub(1);
5888 start_point = TP::to_point(&offset, &snapshot);
5889 };
5890
5891 (start_point..end_point, empty_str.clone())
5892 })
5893 .sorted_by_key(|(range, _)| range.start)
5894 .collect::<Vec<_>>();
5895 buffer.update(cx, |this, cx| {
5896 this.edit(edits, None, cx);
5897 })
5898 }
5899 this.refresh_inline_completion(true, false, cx);
5900 linked_editing_ranges::refresh_linked_ranges(this, cx);
5901 });
5902 }
5903
5904 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5905 self.transact(cx, |this, cx| {
5906 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5907 let line_mode = s.line_mode;
5908 s.move_with(|map, selection| {
5909 if selection.is_empty() && !line_mode {
5910 let cursor = movement::right(map, selection.head());
5911 selection.end = cursor;
5912 selection.reversed = true;
5913 selection.goal = SelectionGoal::None;
5914 }
5915 })
5916 });
5917 this.insert("", cx);
5918 this.refresh_inline_completion(true, false, cx);
5919 });
5920 }
5921
5922 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5923 if self.move_to_prev_snippet_tabstop(cx) {
5924 return;
5925 }
5926
5927 self.outdent(&Outdent, cx);
5928 }
5929
5930 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5931 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5932 return;
5933 }
5934
5935 let mut selections = self.selections.all_adjusted(cx);
5936 let buffer = self.buffer.read(cx);
5937 let snapshot = buffer.snapshot(cx);
5938 let rows_iter = selections.iter().map(|s| s.head().row);
5939 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5940
5941 let mut edits = Vec::new();
5942 let mut prev_edited_row = 0;
5943 let mut row_delta = 0;
5944 for selection in &mut selections {
5945 if selection.start.row != prev_edited_row {
5946 row_delta = 0;
5947 }
5948 prev_edited_row = selection.end.row;
5949
5950 // If the selection is non-empty, then increase the indentation of the selected lines.
5951 if !selection.is_empty() {
5952 row_delta =
5953 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5954 continue;
5955 }
5956
5957 // If the selection is empty and the cursor is in the leading whitespace before the
5958 // suggested indentation, then auto-indent the line.
5959 let cursor = selection.head();
5960 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5961 if let Some(suggested_indent) =
5962 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5963 {
5964 if cursor.column < suggested_indent.len
5965 && cursor.column <= current_indent.len
5966 && current_indent.len <= suggested_indent.len
5967 {
5968 selection.start = Point::new(cursor.row, suggested_indent.len);
5969 selection.end = selection.start;
5970 if row_delta == 0 {
5971 edits.extend(Buffer::edit_for_indent_size_adjustment(
5972 cursor.row,
5973 current_indent,
5974 suggested_indent,
5975 ));
5976 row_delta = suggested_indent.len - current_indent.len;
5977 }
5978 continue;
5979 }
5980 }
5981
5982 // Otherwise, insert a hard or soft tab.
5983 let settings = buffer.settings_at(cursor, cx);
5984 let tab_size = if settings.hard_tabs {
5985 IndentSize::tab()
5986 } else {
5987 let tab_size = settings.tab_size.get();
5988 let char_column = snapshot
5989 .text_for_range(Point::new(cursor.row, 0)..cursor)
5990 .flat_map(str::chars)
5991 .count()
5992 + row_delta as usize;
5993 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5994 IndentSize::spaces(chars_to_next_tab_stop)
5995 };
5996 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5997 selection.end = selection.start;
5998 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5999 row_delta += tab_size.len;
6000 }
6001
6002 self.transact(cx, |this, cx| {
6003 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6004 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6005 this.refresh_inline_completion(true, false, cx);
6006 });
6007 }
6008
6009 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6010 if self.read_only(cx) {
6011 return;
6012 }
6013 let mut selections = self.selections.all::<Point>(cx);
6014 let mut prev_edited_row = 0;
6015 let mut row_delta = 0;
6016 let mut edits = Vec::new();
6017 let buffer = self.buffer.read(cx);
6018 let snapshot = buffer.snapshot(cx);
6019 for selection in &mut selections {
6020 if selection.start.row != prev_edited_row {
6021 row_delta = 0;
6022 }
6023 prev_edited_row = selection.end.row;
6024
6025 row_delta =
6026 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6027 }
6028
6029 self.transact(cx, |this, cx| {
6030 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6031 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6032 });
6033 }
6034
6035 fn indent_selection(
6036 buffer: &MultiBuffer,
6037 snapshot: &MultiBufferSnapshot,
6038 selection: &mut Selection<Point>,
6039 edits: &mut Vec<(Range<Point>, String)>,
6040 delta_for_start_row: u32,
6041 cx: &AppContext,
6042 ) -> u32 {
6043 let settings = buffer.settings_at(selection.start, cx);
6044 let tab_size = settings.tab_size.get();
6045 let indent_kind = if settings.hard_tabs {
6046 IndentKind::Tab
6047 } else {
6048 IndentKind::Space
6049 };
6050 let mut start_row = selection.start.row;
6051 let mut end_row = selection.end.row + 1;
6052
6053 // If a selection ends at the beginning of a line, don't indent
6054 // that last line.
6055 if selection.end.column == 0 && selection.end.row > selection.start.row {
6056 end_row -= 1;
6057 }
6058
6059 // Avoid re-indenting a row that has already been indented by a
6060 // previous selection, but still update this selection's column
6061 // to reflect that indentation.
6062 if delta_for_start_row > 0 {
6063 start_row += 1;
6064 selection.start.column += delta_for_start_row;
6065 if selection.end.row == selection.start.row {
6066 selection.end.column += delta_for_start_row;
6067 }
6068 }
6069
6070 let mut delta_for_end_row = 0;
6071 let has_multiple_rows = start_row + 1 != end_row;
6072 for row in start_row..end_row {
6073 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6074 let indent_delta = match (current_indent.kind, indent_kind) {
6075 (IndentKind::Space, IndentKind::Space) => {
6076 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6077 IndentSize::spaces(columns_to_next_tab_stop)
6078 }
6079 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6080 (_, IndentKind::Tab) => IndentSize::tab(),
6081 };
6082
6083 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6084 0
6085 } else {
6086 selection.start.column
6087 };
6088 let row_start = Point::new(row, start);
6089 edits.push((
6090 row_start..row_start,
6091 indent_delta.chars().collect::<String>(),
6092 ));
6093
6094 // Update this selection's endpoints to reflect the indentation.
6095 if row == selection.start.row {
6096 selection.start.column += indent_delta.len;
6097 }
6098 if row == selection.end.row {
6099 selection.end.column += indent_delta.len;
6100 delta_for_end_row = indent_delta.len;
6101 }
6102 }
6103
6104 if selection.start.row == selection.end.row {
6105 delta_for_start_row + delta_for_end_row
6106 } else {
6107 delta_for_end_row
6108 }
6109 }
6110
6111 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6112 if self.read_only(cx) {
6113 return;
6114 }
6115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6116 let selections = self.selections.all::<Point>(cx);
6117 let mut deletion_ranges = Vec::new();
6118 let mut last_outdent = None;
6119 {
6120 let buffer = self.buffer.read(cx);
6121 let snapshot = buffer.snapshot(cx);
6122 for selection in &selections {
6123 let settings = buffer.settings_at(selection.start, cx);
6124 let tab_size = settings.tab_size.get();
6125 let mut rows = selection.spanned_rows(false, &display_map);
6126
6127 // Avoid re-outdenting a row that has already been outdented by a
6128 // previous selection.
6129 if let Some(last_row) = last_outdent {
6130 if last_row == rows.start {
6131 rows.start = rows.start.next_row();
6132 }
6133 }
6134 let has_multiple_rows = rows.len() > 1;
6135 for row in rows.iter_rows() {
6136 let indent_size = snapshot.indent_size_for_line(row);
6137 if indent_size.len > 0 {
6138 let deletion_len = match indent_size.kind {
6139 IndentKind::Space => {
6140 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6141 if columns_to_prev_tab_stop == 0 {
6142 tab_size
6143 } else {
6144 columns_to_prev_tab_stop
6145 }
6146 }
6147 IndentKind::Tab => 1,
6148 };
6149 let start = if has_multiple_rows
6150 || deletion_len > selection.start.column
6151 || indent_size.len < selection.start.column
6152 {
6153 0
6154 } else {
6155 selection.start.column - deletion_len
6156 };
6157 deletion_ranges.push(
6158 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6159 );
6160 last_outdent = Some(row);
6161 }
6162 }
6163 }
6164 }
6165
6166 self.transact(cx, |this, cx| {
6167 this.buffer.update(cx, |buffer, cx| {
6168 let empty_str: Arc<str> = Arc::default();
6169 buffer.edit(
6170 deletion_ranges
6171 .into_iter()
6172 .map(|range| (range, empty_str.clone())),
6173 None,
6174 cx,
6175 );
6176 });
6177 let selections = this.selections.all::<usize>(cx);
6178 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6179 });
6180 }
6181
6182 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6183 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6184 let selections = self.selections.all::<Point>(cx);
6185
6186 let mut new_cursors = Vec::new();
6187 let mut edit_ranges = Vec::new();
6188 let mut selections = selections.iter().peekable();
6189 while let Some(selection) = selections.next() {
6190 let mut rows = selection.spanned_rows(false, &display_map);
6191 let goal_display_column = selection.head().to_display_point(&display_map).column();
6192
6193 // Accumulate contiguous regions of rows that we want to delete.
6194 while let Some(next_selection) = selections.peek() {
6195 let next_rows = next_selection.spanned_rows(false, &display_map);
6196 if next_rows.start <= rows.end {
6197 rows.end = next_rows.end;
6198 selections.next().unwrap();
6199 } else {
6200 break;
6201 }
6202 }
6203
6204 let buffer = &display_map.buffer_snapshot;
6205 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6206 let edit_end;
6207 let cursor_buffer_row;
6208 if buffer.max_point().row >= rows.end.0 {
6209 // If there's a line after the range, delete the \n from the end of the row range
6210 // and position the cursor on the next line.
6211 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6212 cursor_buffer_row = rows.end;
6213 } else {
6214 // If there isn't a line after the range, delete the \n from the line before the
6215 // start of the row range and position the cursor there.
6216 edit_start = edit_start.saturating_sub(1);
6217 edit_end = buffer.len();
6218 cursor_buffer_row = rows.start.previous_row();
6219 }
6220
6221 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6222 *cursor.column_mut() =
6223 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6224
6225 new_cursors.push((
6226 selection.id,
6227 buffer.anchor_after(cursor.to_point(&display_map)),
6228 ));
6229 edit_ranges.push(edit_start..edit_end);
6230 }
6231
6232 self.transact(cx, |this, cx| {
6233 let buffer = this.buffer.update(cx, |buffer, cx| {
6234 let empty_str: Arc<str> = Arc::default();
6235 buffer.edit(
6236 edit_ranges
6237 .into_iter()
6238 .map(|range| (range, empty_str.clone())),
6239 None,
6240 cx,
6241 );
6242 buffer.snapshot(cx)
6243 });
6244 let new_selections = new_cursors
6245 .into_iter()
6246 .map(|(id, cursor)| {
6247 let cursor = cursor.to_point(&buffer);
6248 Selection {
6249 id,
6250 start: cursor,
6251 end: cursor,
6252 reversed: false,
6253 goal: SelectionGoal::None,
6254 }
6255 })
6256 .collect();
6257
6258 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6259 s.select(new_selections);
6260 });
6261 });
6262 }
6263
6264 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6265 if self.read_only(cx) {
6266 return;
6267 }
6268 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6269 for selection in self.selections.all::<Point>(cx) {
6270 let start = MultiBufferRow(selection.start.row);
6271 let end = if selection.start.row == selection.end.row {
6272 MultiBufferRow(selection.start.row + 1)
6273 } else {
6274 MultiBufferRow(selection.end.row)
6275 };
6276
6277 if let Some(last_row_range) = row_ranges.last_mut() {
6278 if start <= last_row_range.end {
6279 last_row_range.end = end;
6280 continue;
6281 }
6282 }
6283 row_ranges.push(start..end);
6284 }
6285
6286 let snapshot = self.buffer.read(cx).snapshot(cx);
6287 let mut cursor_positions = Vec::new();
6288 for row_range in &row_ranges {
6289 let anchor = snapshot.anchor_before(Point::new(
6290 row_range.end.previous_row().0,
6291 snapshot.line_len(row_range.end.previous_row()),
6292 ));
6293 cursor_positions.push(anchor..anchor);
6294 }
6295
6296 self.transact(cx, |this, cx| {
6297 for row_range in row_ranges.into_iter().rev() {
6298 for row in row_range.iter_rows().rev() {
6299 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6300 let next_line_row = row.next_row();
6301 let indent = snapshot.indent_size_for_line(next_line_row);
6302 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6303
6304 let replace = if snapshot.line_len(next_line_row) > indent.len {
6305 " "
6306 } else {
6307 ""
6308 };
6309
6310 this.buffer.update(cx, |buffer, cx| {
6311 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6312 });
6313 }
6314 }
6315
6316 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6317 s.select_anchor_ranges(cursor_positions)
6318 });
6319 });
6320 }
6321
6322 pub fn sort_lines_case_sensitive(
6323 &mut self,
6324 _: &SortLinesCaseSensitive,
6325 cx: &mut ViewContext<Self>,
6326 ) {
6327 self.manipulate_lines(cx, |lines| lines.sort())
6328 }
6329
6330 pub fn sort_lines_case_insensitive(
6331 &mut self,
6332 _: &SortLinesCaseInsensitive,
6333 cx: &mut ViewContext<Self>,
6334 ) {
6335 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6336 }
6337
6338 pub fn unique_lines_case_insensitive(
6339 &mut self,
6340 _: &UniqueLinesCaseInsensitive,
6341 cx: &mut ViewContext<Self>,
6342 ) {
6343 self.manipulate_lines(cx, |lines| {
6344 let mut seen = HashSet::default();
6345 lines.retain(|line| seen.insert(line.to_lowercase()));
6346 })
6347 }
6348
6349 pub fn unique_lines_case_sensitive(
6350 &mut self,
6351 _: &UniqueLinesCaseSensitive,
6352 cx: &mut ViewContext<Self>,
6353 ) {
6354 self.manipulate_lines(cx, |lines| {
6355 let mut seen = HashSet::default();
6356 lines.retain(|line| seen.insert(*line));
6357 })
6358 }
6359
6360 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6361 let mut revert_changes = HashMap::default();
6362 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6363 for hunk in hunks_for_rows(
6364 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6365 &multi_buffer_snapshot,
6366 ) {
6367 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6368 }
6369 if !revert_changes.is_empty() {
6370 self.transact(cx, |editor, cx| {
6371 editor.revert(revert_changes, cx);
6372 });
6373 }
6374 }
6375
6376 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6377 let Some(project) = self.project.clone() else {
6378 return;
6379 };
6380 self.reload(project, cx).detach_and_notify_err(cx);
6381 }
6382
6383 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6384 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6385 if !revert_changes.is_empty() {
6386 self.transact(cx, |editor, cx| {
6387 editor.revert(revert_changes, cx);
6388 });
6389 }
6390 }
6391
6392 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6393 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6394 let project_path = buffer.read(cx).project_path(cx)?;
6395 let project = self.project.as_ref()?.read(cx);
6396 let entry = project.entry_for_path(&project_path, cx)?;
6397 let parent = match &entry.canonical_path {
6398 Some(canonical_path) => canonical_path.to_path_buf(),
6399 None => project.absolute_path(&project_path, cx)?,
6400 }
6401 .parent()?
6402 .to_path_buf();
6403 Some(parent)
6404 }) {
6405 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6406 }
6407 }
6408
6409 fn gather_revert_changes(
6410 &mut self,
6411 selections: &[Selection<Anchor>],
6412 cx: &mut ViewContext<'_, Editor>,
6413 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6414 let mut revert_changes = HashMap::default();
6415 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6416 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6417 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6418 }
6419 revert_changes
6420 }
6421
6422 pub fn prepare_revert_change(
6423 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6424 multi_buffer: &Model<MultiBuffer>,
6425 hunk: &MultiBufferDiffHunk,
6426 cx: &AppContext,
6427 ) -> Option<()> {
6428 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6429 let buffer = buffer.read(cx);
6430 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6431 let buffer_snapshot = buffer.snapshot();
6432 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6433 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6434 probe
6435 .0
6436 .start
6437 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6438 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6439 }) {
6440 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6441 Some(())
6442 } else {
6443 None
6444 }
6445 }
6446
6447 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6448 self.manipulate_lines(cx, |lines| lines.reverse())
6449 }
6450
6451 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6452 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6453 }
6454
6455 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6456 where
6457 Fn: FnMut(&mut Vec<&str>),
6458 {
6459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6460 let buffer = self.buffer.read(cx).snapshot(cx);
6461
6462 let mut edits = Vec::new();
6463
6464 let selections = self.selections.all::<Point>(cx);
6465 let mut selections = selections.iter().peekable();
6466 let mut contiguous_row_selections = Vec::new();
6467 let mut new_selections = Vec::new();
6468 let mut added_lines = 0;
6469 let mut removed_lines = 0;
6470
6471 while let Some(selection) = selections.next() {
6472 let (start_row, end_row) = consume_contiguous_rows(
6473 &mut contiguous_row_selections,
6474 selection,
6475 &display_map,
6476 &mut selections,
6477 );
6478
6479 let start_point = Point::new(start_row.0, 0);
6480 let end_point = Point::new(
6481 end_row.previous_row().0,
6482 buffer.line_len(end_row.previous_row()),
6483 );
6484 let text = buffer
6485 .text_for_range(start_point..end_point)
6486 .collect::<String>();
6487
6488 let mut lines = text.split('\n').collect_vec();
6489
6490 let lines_before = lines.len();
6491 callback(&mut lines);
6492 let lines_after = lines.len();
6493
6494 edits.push((start_point..end_point, lines.join("\n")));
6495
6496 // Selections must change based on added and removed line count
6497 let start_row =
6498 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6499 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6500 new_selections.push(Selection {
6501 id: selection.id,
6502 start: start_row,
6503 end: end_row,
6504 goal: SelectionGoal::None,
6505 reversed: selection.reversed,
6506 });
6507
6508 if lines_after > lines_before {
6509 added_lines += lines_after - lines_before;
6510 } else if lines_before > lines_after {
6511 removed_lines += lines_before - lines_after;
6512 }
6513 }
6514
6515 self.transact(cx, |this, cx| {
6516 let buffer = this.buffer.update(cx, |buffer, cx| {
6517 buffer.edit(edits, None, cx);
6518 buffer.snapshot(cx)
6519 });
6520
6521 // Recalculate offsets on newly edited buffer
6522 let new_selections = new_selections
6523 .iter()
6524 .map(|s| {
6525 let start_point = Point::new(s.start.0, 0);
6526 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6527 Selection {
6528 id: s.id,
6529 start: buffer.point_to_offset(start_point),
6530 end: buffer.point_to_offset(end_point),
6531 goal: s.goal,
6532 reversed: s.reversed,
6533 }
6534 })
6535 .collect();
6536
6537 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6538 s.select(new_selections);
6539 });
6540
6541 this.request_autoscroll(Autoscroll::fit(), cx);
6542 });
6543 }
6544
6545 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6546 self.manipulate_text(cx, |text| text.to_uppercase())
6547 }
6548
6549 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6550 self.manipulate_text(cx, |text| text.to_lowercase())
6551 }
6552
6553 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6554 self.manipulate_text(cx, |text| {
6555 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6556 // https://github.com/rutrum/convert-case/issues/16
6557 text.split('\n')
6558 .map(|line| line.to_case(Case::Title))
6559 .join("\n")
6560 })
6561 }
6562
6563 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6564 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6565 }
6566
6567 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6568 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6569 }
6570
6571 pub fn convert_to_upper_camel_case(
6572 &mut self,
6573 _: &ConvertToUpperCamelCase,
6574 cx: &mut ViewContext<Self>,
6575 ) {
6576 self.manipulate_text(cx, |text| {
6577 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6578 // https://github.com/rutrum/convert-case/issues/16
6579 text.split('\n')
6580 .map(|line| line.to_case(Case::UpperCamel))
6581 .join("\n")
6582 })
6583 }
6584
6585 pub fn convert_to_lower_camel_case(
6586 &mut self,
6587 _: &ConvertToLowerCamelCase,
6588 cx: &mut ViewContext<Self>,
6589 ) {
6590 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6591 }
6592
6593 pub fn convert_to_opposite_case(
6594 &mut self,
6595 _: &ConvertToOppositeCase,
6596 cx: &mut ViewContext<Self>,
6597 ) {
6598 self.manipulate_text(cx, |text| {
6599 text.chars()
6600 .fold(String::with_capacity(text.len()), |mut t, c| {
6601 if c.is_uppercase() {
6602 t.extend(c.to_lowercase());
6603 } else {
6604 t.extend(c.to_uppercase());
6605 }
6606 t
6607 })
6608 })
6609 }
6610
6611 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6612 where
6613 Fn: FnMut(&str) -> String,
6614 {
6615 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6616 let buffer = self.buffer.read(cx).snapshot(cx);
6617
6618 let mut new_selections = Vec::new();
6619 let mut edits = Vec::new();
6620 let mut selection_adjustment = 0i32;
6621
6622 for selection in self.selections.all::<usize>(cx) {
6623 let selection_is_empty = selection.is_empty();
6624
6625 let (start, end) = if selection_is_empty {
6626 let word_range = movement::surrounding_word(
6627 &display_map,
6628 selection.start.to_display_point(&display_map),
6629 );
6630 let start = word_range.start.to_offset(&display_map, Bias::Left);
6631 let end = word_range.end.to_offset(&display_map, Bias::Left);
6632 (start, end)
6633 } else {
6634 (selection.start, selection.end)
6635 };
6636
6637 let text = buffer.text_for_range(start..end).collect::<String>();
6638 let old_length = text.len() as i32;
6639 let text = callback(&text);
6640
6641 new_selections.push(Selection {
6642 start: (start as i32 - selection_adjustment) as usize,
6643 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6644 goal: SelectionGoal::None,
6645 ..selection
6646 });
6647
6648 selection_adjustment += old_length - text.len() as i32;
6649
6650 edits.push((start..end, text));
6651 }
6652
6653 self.transact(cx, |this, cx| {
6654 this.buffer.update(cx, |buffer, cx| {
6655 buffer.edit(edits, None, cx);
6656 });
6657
6658 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6659 s.select(new_selections);
6660 });
6661
6662 this.request_autoscroll(Autoscroll::fit(), cx);
6663 });
6664 }
6665
6666 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6667 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6668 let buffer = &display_map.buffer_snapshot;
6669 let selections = self.selections.all::<Point>(cx);
6670
6671 let mut edits = Vec::new();
6672 let mut selections_iter = selections.iter().peekable();
6673 while let Some(selection) = selections_iter.next() {
6674 // Avoid duplicating the same lines twice.
6675 let mut rows = selection.spanned_rows(false, &display_map);
6676
6677 while let Some(next_selection) = selections_iter.peek() {
6678 let next_rows = next_selection.spanned_rows(false, &display_map);
6679 if next_rows.start < rows.end {
6680 rows.end = next_rows.end;
6681 selections_iter.next().unwrap();
6682 } else {
6683 break;
6684 }
6685 }
6686
6687 // Copy the text from the selected row region and splice it either at the start
6688 // or end of the region.
6689 let start = Point::new(rows.start.0, 0);
6690 let end = Point::new(
6691 rows.end.previous_row().0,
6692 buffer.line_len(rows.end.previous_row()),
6693 );
6694 let text = buffer
6695 .text_for_range(start..end)
6696 .chain(Some("\n"))
6697 .collect::<String>();
6698 let insert_location = if upwards {
6699 Point::new(rows.end.0, 0)
6700 } else {
6701 start
6702 };
6703 edits.push((insert_location..insert_location, text));
6704 }
6705
6706 self.transact(cx, |this, cx| {
6707 this.buffer.update(cx, |buffer, cx| {
6708 buffer.edit(edits, None, cx);
6709 });
6710
6711 this.request_autoscroll(Autoscroll::fit(), cx);
6712 });
6713 }
6714
6715 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6716 self.duplicate_line(true, cx);
6717 }
6718
6719 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6720 self.duplicate_line(false, cx);
6721 }
6722
6723 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6724 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6725 let buffer = self.buffer.read(cx).snapshot(cx);
6726
6727 let mut edits = Vec::new();
6728 let mut unfold_ranges = Vec::new();
6729 let mut refold_ranges = Vec::new();
6730
6731 let selections = self.selections.all::<Point>(cx);
6732 let mut selections = selections.iter().peekable();
6733 let mut contiguous_row_selections = Vec::new();
6734 let mut new_selections = Vec::new();
6735
6736 while let Some(selection) = selections.next() {
6737 // Find all the selections that span a contiguous row range
6738 let (start_row, end_row) = consume_contiguous_rows(
6739 &mut contiguous_row_selections,
6740 selection,
6741 &display_map,
6742 &mut selections,
6743 );
6744
6745 // Move the text spanned by the row range to be before the line preceding the row range
6746 if start_row.0 > 0 {
6747 let range_to_move = Point::new(
6748 start_row.previous_row().0,
6749 buffer.line_len(start_row.previous_row()),
6750 )
6751 ..Point::new(
6752 end_row.previous_row().0,
6753 buffer.line_len(end_row.previous_row()),
6754 );
6755 let insertion_point = display_map
6756 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6757 .0;
6758
6759 // Don't move lines across excerpts
6760 if buffer
6761 .excerpt_boundaries_in_range((
6762 Bound::Excluded(insertion_point),
6763 Bound::Included(range_to_move.end),
6764 ))
6765 .next()
6766 .is_none()
6767 {
6768 let text = buffer
6769 .text_for_range(range_to_move.clone())
6770 .flat_map(|s| s.chars())
6771 .skip(1)
6772 .chain(['\n'])
6773 .collect::<String>();
6774
6775 edits.push((
6776 buffer.anchor_after(range_to_move.start)
6777 ..buffer.anchor_before(range_to_move.end),
6778 String::new(),
6779 ));
6780 let insertion_anchor = buffer.anchor_after(insertion_point);
6781 edits.push((insertion_anchor..insertion_anchor, text));
6782
6783 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6784
6785 // Move selections up
6786 new_selections.extend(contiguous_row_selections.drain(..).map(
6787 |mut selection| {
6788 selection.start.row -= row_delta;
6789 selection.end.row -= row_delta;
6790 selection
6791 },
6792 ));
6793
6794 // Move folds up
6795 unfold_ranges.push(range_to_move.clone());
6796 for fold in display_map.folds_in_range(
6797 buffer.anchor_before(range_to_move.start)
6798 ..buffer.anchor_after(range_to_move.end),
6799 ) {
6800 let mut start = fold.range.start.to_point(&buffer);
6801 let mut end = fold.range.end.to_point(&buffer);
6802 start.row -= row_delta;
6803 end.row -= row_delta;
6804 refold_ranges.push((start..end, fold.placeholder.clone()));
6805 }
6806 }
6807 }
6808
6809 // If we didn't move line(s), preserve the existing selections
6810 new_selections.append(&mut contiguous_row_selections);
6811 }
6812
6813 self.transact(cx, |this, cx| {
6814 this.unfold_ranges(&unfold_ranges, true, true, cx);
6815 this.buffer.update(cx, |buffer, cx| {
6816 for (range, text) in edits {
6817 buffer.edit([(range, text)], None, cx);
6818 }
6819 });
6820 this.fold_ranges(refold_ranges, true, cx);
6821 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6822 s.select(new_selections);
6823 })
6824 });
6825 }
6826
6827 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6828 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6829 let buffer = self.buffer.read(cx).snapshot(cx);
6830
6831 let mut edits = Vec::new();
6832 let mut unfold_ranges = Vec::new();
6833 let mut refold_ranges = Vec::new();
6834
6835 let selections = self.selections.all::<Point>(cx);
6836 let mut selections = selections.iter().peekable();
6837 let mut contiguous_row_selections = Vec::new();
6838 let mut new_selections = Vec::new();
6839
6840 while let Some(selection) = selections.next() {
6841 // Find all the selections that span a contiguous row range
6842 let (start_row, end_row) = consume_contiguous_rows(
6843 &mut contiguous_row_selections,
6844 selection,
6845 &display_map,
6846 &mut selections,
6847 );
6848
6849 // Move the text spanned by the row range to be after the last line of the row range
6850 if end_row.0 <= buffer.max_point().row {
6851 let range_to_move =
6852 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6853 let insertion_point = display_map
6854 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6855 .0;
6856
6857 // Don't move lines across excerpt boundaries
6858 if buffer
6859 .excerpt_boundaries_in_range((
6860 Bound::Excluded(range_to_move.start),
6861 Bound::Included(insertion_point),
6862 ))
6863 .next()
6864 .is_none()
6865 {
6866 let mut text = String::from("\n");
6867 text.extend(buffer.text_for_range(range_to_move.clone()));
6868 text.pop(); // Drop trailing newline
6869 edits.push((
6870 buffer.anchor_after(range_to_move.start)
6871 ..buffer.anchor_before(range_to_move.end),
6872 String::new(),
6873 ));
6874 let insertion_anchor = buffer.anchor_after(insertion_point);
6875 edits.push((insertion_anchor..insertion_anchor, text));
6876
6877 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6878
6879 // Move selections down
6880 new_selections.extend(contiguous_row_selections.drain(..).map(
6881 |mut selection| {
6882 selection.start.row += row_delta;
6883 selection.end.row += row_delta;
6884 selection
6885 },
6886 ));
6887
6888 // Move folds down
6889 unfold_ranges.push(range_to_move.clone());
6890 for fold in display_map.folds_in_range(
6891 buffer.anchor_before(range_to_move.start)
6892 ..buffer.anchor_after(range_to_move.end),
6893 ) {
6894 let mut start = fold.range.start.to_point(&buffer);
6895 let mut end = fold.range.end.to_point(&buffer);
6896 start.row += row_delta;
6897 end.row += row_delta;
6898 refold_ranges.push((start..end, fold.placeholder.clone()));
6899 }
6900 }
6901 }
6902
6903 // If we didn't move line(s), preserve the existing selections
6904 new_selections.append(&mut contiguous_row_selections);
6905 }
6906
6907 self.transact(cx, |this, cx| {
6908 this.unfold_ranges(&unfold_ranges, true, true, cx);
6909 this.buffer.update(cx, |buffer, cx| {
6910 for (range, text) in edits {
6911 buffer.edit([(range, text)], None, cx);
6912 }
6913 });
6914 this.fold_ranges(refold_ranges, true, cx);
6915 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6916 });
6917 }
6918
6919 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6920 let text_layout_details = &self.text_layout_details(cx);
6921 self.transact(cx, |this, cx| {
6922 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6923 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6924 let line_mode = s.line_mode;
6925 s.move_with(|display_map, selection| {
6926 if !selection.is_empty() || line_mode {
6927 return;
6928 }
6929
6930 let mut head = selection.head();
6931 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6932 if head.column() == display_map.line_len(head.row()) {
6933 transpose_offset = display_map
6934 .buffer_snapshot
6935 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6936 }
6937
6938 if transpose_offset == 0 {
6939 return;
6940 }
6941
6942 *head.column_mut() += 1;
6943 head = display_map.clip_point(head, Bias::Right);
6944 let goal = SelectionGoal::HorizontalPosition(
6945 display_map
6946 .x_for_display_point(head, text_layout_details)
6947 .into(),
6948 );
6949 selection.collapse_to(head, goal);
6950
6951 let transpose_start = display_map
6952 .buffer_snapshot
6953 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6954 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6955 let transpose_end = display_map
6956 .buffer_snapshot
6957 .clip_offset(transpose_offset + 1, Bias::Right);
6958 if let Some(ch) =
6959 display_map.buffer_snapshot.chars_at(transpose_start).next()
6960 {
6961 edits.push((transpose_start..transpose_offset, String::new()));
6962 edits.push((transpose_end..transpose_end, ch.to_string()));
6963 }
6964 }
6965 });
6966 edits
6967 });
6968 this.buffer
6969 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6970 let selections = this.selections.all::<usize>(cx);
6971 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6972 s.select(selections);
6973 });
6974 });
6975 }
6976
6977 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6978 self.rewrap_impl(true, cx)
6979 }
6980
6981 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6982 let buffer = self.buffer.read(cx).snapshot(cx);
6983 let selections = self.selections.all::<Point>(cx);
6984 let mut selections = selections.iter().peekable();
6985
6986 let mut edits = Vec::new();
6987 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6988
6989 while let Some(selection) = selections.next() {
6990 let mut start_row = selection.start.row;
6991 let mut end_row = selection.end.row;
6992
6993 // Skip selections that overlap with a range that has already been rewrapped.
6994 let selection_range = start_row..end_row;
6995 if rewrapped_row_ranges
6996 .iter()
6997 .any(|range| range.overlaps(&selection_range))
6998 {
6999 continue;
7000 }
7001
7002 let mut should_rewrap = !only_text;
7003
7004 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7005 match language_scope.language_name().0.as_ref() {
7006 "Markdown" | "Plain Text" => {
7007 should_rewrap = true;
7008 }
7009 _ => {}
7010 }
7011 }
7012
7013 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7014
7015 // Since not all lines in the selection may be at the same indent
7016 // level, choose the indent size that is the most common between all
7017 // of the lines.
7018 //
7019 // If there is a tie, we use the deepest indent.
7020 let (indent_size, indent_end) = {
7021 let mut indent_size_occurrences = HashMap::default();
7022 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7023
7024 for row in start_row..=end_row {
7025 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7026 rows_by_indent_size.entry(indent).or_default().push(row);
7027 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7028 }
7029
7030 let indent_size = indent_size_occurrences
7031 .into_iter()
7032 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7033 .map(|(indent, _)| indent)
7034 .unwrap_or_default();
7035 let row = rows_by_indent_size[&indent_size][0];
7036 let indent_end = Point::new(row, indent_size.len);
7037
7038 (indent_size, indent_end)
7039 };
7040
7041 let mut line_prefix = indent_size.chars().collect::<String>();
7042
7043 if let Some(comment_prefix) =
7044 buffer
7045 .language_scope_at(selection.head())
7046 .and_then(|language| {
7047 language
7048 .line_comment_prefixes()
7049 .iter()
7050 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7051 .cloned()
7052 })
7053 {
7054 line_prefix.push_str(&comment_prefix);
7055 should_rewrap = true;
7056 }
7057
7058 if !should_rewrap {
7059 continue;
7060 }
7061
7062 if selection.is_empty() {
7063 'expand_upwards: while start_row > 0 {
7064 let prev_row = start_row - 1;
7065 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7066 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7067 {
7068 start_row = prev_row;
7069 } else {
7070 break 'expand_upwards;
7071 }
7072 }
7073
7074 'expand_downwards: while end_row < buffer.max_point().row {
7075 let next_row = end_row + 1;
7076 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7077 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7078 {
7079 end_row = next_row;
7080 } else {
7081 break 'expand_downwards;
7082 }
7083 }
7084 }
7085
7086 let start = Point::new(start_row, 0);
7087 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7088 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7089 let Some(lines_without_prefixes) = selection_text
7090 .lines()
7091 .map(|line| {
7092 line.strip_prefix(&line_prefix)
7093 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7094 .ok_or_else(|| {
7095 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7096 })
7097 })
7098 .collect::<Result<Vec<_>, _>>()
7099 .log_err()
7100 else {
7101 continue;
7102 };
7103
7104 let wrap_column = buffer
7105 .settings_at(Point::new(start_row, 0), cx)
7106 .preferred_line_length as usize;
7107 let wrapped_text = wrap_with_prefix(
7108 line_prefix,
7109 lines_without_prefixes.join(" "),
7110 wrap_column,
7111 tab_size,
7112 );
7113
7114 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7115 let mut offset = start.to_offset(&buffer);
7116 let mut moved_since_edit = true;
7117
7118 for change in diff.iter_all_changes() {
7119 let value = change.value();
7120 match change.tag() {
7121 ChangeTag::Equal => {
7122 offset += value.len();
7123 moved_since_edit = true;
7124 }
7125 ChangeTag::Delete => {
7126 let start = buffer.anchor_after(offset);
7127 let end = buffer.anchor_before(offset + value.len());
7128
7129 if moved_since_edit {
7130 edits.push((start..end, String::new()));
7131 } else {
7132 edits.last_mut().unwrap().0.end = end;
7133 }
7134
7135 offset += value.len();
7136 moved_since_edit = false;
7137 }
7138 ChangeTag::Insert => {
7139 if moved_since_edit {
7140 let anchor = buffer.anchor_after(offset);
7141 edits.push((anchor..anchor, value.to_string()));
7142 } else {
7143 edits.last_mut().unwrap().1.push_str(value);
7144 }
7145
7146 moved_since_edit = false;
7147 }
7148 }
7149 }
7150
7151 rewrapped_row_ranges.push(start_row..=end_row);
7152 }
7153
7154 self.buffer
7155 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7156 }
7157
7158 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7159 let mut text = String::new();
7160 let buffer = self.buffer.read(cx).snapshot(cx);
7161 let mut selections = self.selections.all::<Point>(cx);
7162 let mut clipboard_selections = Vec::with_capacity(selections.len());
7163 {
7164 let max_point = buffer.max_point();
7165 let mut is_first = true;
7166 for selection in &mut selections {
7167 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7168 if is_entire_line {
7169 selection.start = Point::new(selection.start.row, 0);
7170 if !selection.is_empty() && selection.end.column == 0 {
7171 selection.end = cmp::min(max_point, selection.end);
7172 } else {
7173 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7174 }
7175 selection.goal = SelectionGoal::None;
7176 }
7177 if is_first {
7178 is_first = false;
7179 } else {
7180 text += "\n";
7181 }
7182 let mut len = 0;
7183 for chunk in buffer.text_for_range(selection.start..selection.end) {
7184 text.push_str(chunk);
7185 len += chunk.len();
7186 }
7187 clipboard_selections.push(ClipboardSelection {
7188 len,
7189 is_entire_line,
7190 first_line_indent: buffer
7191 .indent_size_for_line(MultiBufferRow(selection.start.row))
7192 .len,
7193 });
7194 }
7195 }
7196
7197 self.transact(cx, |this, cx| {
7198 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7199 s.select(selections);
7200 });
7201 this.insert("", cx);
7202 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7203 text,
7204 clipboard_selections,
7205 ));
7206 });
7207 }
7208
7209 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7210 let selections = self.selections.all::<Point>(cx);
7211 let buffer = self.buffer.read(cx).read(cx);
7212 let mut text = String::new();
7213
7214 let mut clipboard_selections = Vec::with_capacity(selections.len());
7215 {
7216 let max_point = buffer.max_point();
7217 let mut is_first = true;
7218 for selection in selections.iter() {
7219 let mut start = selection.start;
7220 let mut end = selection.end;
7221 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7222 if is_entire_line {
7223 start = Point::new(start.row, 0);
7224 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7225 }
7226 if is_first {
7227 is_first = false;
7228 } else {
7229 text += "\n";
7230 }
7231 let mut len = 0;
7232 for chunk in buffer.text_for_range(start..end) {
7233 text.push_str(chunk);
7234 len += chunk.len();
7235 }
7236 clipboard_selections.push(ClipboardSelection {
7237 len,
7238 is_entire_line,
7239 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7240 });
7241 }
7242 }
7243
7244 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7245 text,
7246 clipboard_selections,
7247 ));
7248 }
7249
7250 pub fn do_paste(
7251 &mut self,
7252 text: &String,
7253 clipboard_selections: Option<Vec<ClipboardSelection>>,
7254 handle_entire_lines: bool,
7255 cx: &mut ViewContext<Self>,
7256 ) {
7257 if self.read_only(cx) {
7258 return;
7259 }
7260
7261 let clipboard_text = Cow::Borrowed(text);
7262
7263 self.transact(cx, |this, cx| {
7264 if let Some(mut clipboard_selections) = clipboard_selections {
7265 let old_selections = this.selections.all::<usize>(cx);
7266 let all_selections_were_entire_line =
7267 clipboard_selections.iter().all(|s| s.is_entire_line);
7268 let first_selection_indent_column =
7269 clipboard_selections.first().map(|s| s.first_line_indent);
7270 if clipboard_selections.len() != old_selections.len() {
7271 clipboard_selections.drain(..);
7272 }
7273 let cursor_offset = this.selections.last::<usize>(cx).head();
7274 let mut auto_indent_on_paste = true;
7275
7276 this.buffer.update(cx, |buffer, cx| {
7277 let snapshot = buffer.read(cx);
7278 auto_indent_on_paste =
7279 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7280
7281 let mut start_offset = 0;
7282 let mut edits = Vec::new();
7283 let mut original_indent_columns = Vec::new();
7284 for (ix, selection) in old_selections.iter().enumerate() {
7285 let to_insert;
7286 let entire_line;
7287 let original_indent_column;
7288 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7289 let end_offset = start_offset + clipboard_selection.len;
7290 to_insert = &clipboard_text[start_offset..end_offset];
7291 entire_line = clipboard_selection.is_entire_line;
7292 start_offset = end_offset + 1;
7293 original_indent_column = Some(clipboard_selection.first_line_indent);
7294 } else {
7295 to_insert = clipboard_text.as_str();
7296 entire_line = all_selections_were_entire_line;
7297 original_indent_column = first_selection_indent_column
7298 }
7299
7300 // If the corresponding selection was empty when this slice of the
7301 // clipboard text was written, then the entire line containing the
7302 // selection was copied. If this selection is also currently empty,
7303 // then paste the line before the current line of the buffer.
7304 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7305 let column = selection.start.to_point(&snapshot).column as usize;
7306 let line_start = selection.start - column;
7307 line_start..line_start
7308 } else {
7309 selection.range()
7310 };
7311
7312 edits.push((range, to_insert));
7313 original_indent_columns.extend(original_indent_column);
7314 }
7315 drop(snapshot);
7316
7317 buffer.edit(
7318 edits,
7319 if auto_indent_on_paste {
7320 Some(AutoindentMode::Block {
7321 original_indent_columns,
7322 })
7323 } else {
7324 None
7325 },
7326 cx,
7327 );
7328 });
7329
7330 let selections = this.selections.all::<usize>(cx);
7331 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7332 } else {
7333 this.insert(&clipboard_text, cx);
7334 }
7335 });
7336 }
7337
7338 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7339 if let Some(item) = cx.read_from_clipboard() {
7340 let entries = item.entries();
7341
7342 match entries.first() {
7343 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7344 // of all the pasted entries.
7345 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7346 .do_paste(
7347 clipboard_string.text(),
7348 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7349 true,
7350 cx,
7351 ),
7352 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7353 }
7354 }
7355 }
7356
7357 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7358 if self.read_only(cx) {
7359 return;
7360 }
7361
7362 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7363 if let Some((selections, _)) =
7364 self.selection_history.transaction(transaction_id).cloned()
7365 {
7366 self.change_selections(None, cx, |s| {
7367 s.select_anchors(selections.to_vec());
7368 });
7369 }
7370 self.request_autoscroll(Autoscroll::fit(), cx);
7371 self.unmark_text(cx);
7372 self.refresh_inline_completion(true, false, cx);
7373 cx.emit(EditorEvent::Edited { transaction_id });
7374 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7375 }
7376 }
7377
7378 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7379 if self.read_only(cx) {
7380 return;
7381 }
7382
7383 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7384 if let Some((_, Some(selections))) =
7385 self.selection_history.transaction(transaction_id).cloned()
7386 {
7387 self.change_selections(None, cx, |s| {
7388 s.select_anchors(selections.to_vec());
7389 });
7390 }
7391 self.request_autoscroll(Autoscroll::fit(), cx);
7392 self.unmark_text(cx);
7393 self.refresh_inline_completion(true, false, cx);
7394 cx.emit(EditorEvent::Edited { transaction_id });
7395 }
7396 }
7397
7398 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7399 self.buffer
7400 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7401 }
7402
7403 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7404 self.buffer
7405 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7406 }
7407
7408 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7409 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7410 let line_mode = s.line_mode;
7411 s.move_with(|map, selection| {
7412 let cursor = if selection.is_empty() && !line_mode {
7413 movement::left(map, selection.start)
7414 } else {
7415 selection.start
7416 };
7417 selection.collapse_to(cursor, SelectionGoal::None);
7418 });
7419 })
7420 }
7421
7422 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7424 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7425 })
7426 }
7427
7428 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7429 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7430 let line_mode = s.line_mode;
7431 s.move_with(|map, selection| {
7432 let cursor = if selection.is_empty() && !line_mode {
7433 movement::right(map, selection.end)
7434 } else {
7435 selection.end
7436 };
7437 selection.collapse_to(cursor, SelectionGoal::None)
7438 });
7439 })
7440 }
7441
7442 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7443 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7444 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7445 })
7446 }
7447
7448 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7449 if self.take_rename(true, cx).is_some() {
7450 return;
7451 }
7452
7453 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7454 cx.propagate();
7455 return;
7456 }
7457
7458 let text_layout_details = &self.text_layout_details(cx);
7459 let selection_count = self.selections.count();
7460 let first_selection = self.selections.first_anchor();
7461
7462 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7463 let line_mode = s.line_mode;
7464 s.move_with(|map, selection| {
7465 if !selection.is_empty() && !line_mode {
7466 selection.goal = SelectionGoal::None;
7467 }
7468 let (cursor, goal) = movement::up(
7469 map,
7470 selection.start,
7471 selection.goal,
7472 false,
7473 text_layout_details,
7474 );
7475 selection.collapse_to(cursor, goal);
7476 });
7477 });
7478
7479 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7480 {
7481 cx.propagate();
7482 }
7483 }
7484
7485 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7486 if self.take_rename(true, cx).is_some() {
7487 return;
7488 }
7489
7490 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7491 cx.propagate();
7492 return;
7493 }
7494
7495 let text_layout_details = &self.text_layout_details(cx);
7496
7497 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7498 let line_mode = s.line_mode;
7499 s.move_with(|map, selection| {
7500 if !selection.is_empty() && !line_mode {
7501 selection.goal = SelectionGoal::None;
7502 }
7503 let (cursor, goal) = movement::up_by_rows(
7504 map,
7505 selection.start,
7506 action.lines,
7507 selection.goal,
7508 false,
7509 text_layout_details,
7510 );
7511 selection.collapse_to(cursor, goal);
7512 });
7513 })
7514 }
7515
7516 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7517 if self.take_rename(true, cx).is_some() {
7518 return;
7519 }
7520
7521 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7522 cx.propagate();
7523 return;
7524 }
7525
7526 let text_layout_details = &self.text_layout_details(cx);
7527
7528 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7529 let line_mode = s.line_mode;
7530 s.move_with(|map, selection| {
7531 if !selection.is_empty() && !line_mode {
7532 selection.goal = SelectionGoal::None;
7533 }
7534 let (cursor, goal) = movement::down_by_rows(
7535 map,
7536 selection.start,
7537 action.lines,
7538 selection.goal,
7539 false,
7540 text_layout_details,
7541 );
7542 selection.collapse_to(cursor, goal);
7543 });
7544 })
7545 }
7546
7547 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7548 let text_layout_details = &self.text_layout_details(cx);
7549 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7550 s.move_heads_with(|map, head, goal| {
7551 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7552 })
7553 })
7554 }
7555
7556 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7557 let text_layout_details = &self.text_layout_details(cx);
7558 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7559 s.move_heads_with(|map, head, goal| {
7560 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7561 })
7562 })
7563 }
7564
7565 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7566 let Some(row_count) = self.visible_row_count() else {
7567 return;
7568 };
7569
7570 let text_layout_details = &self.text_layout_details(cx);
7571
7572 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7573 s.move_heads_with(|map, head, goal| {
7574 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7575 })
7576 })
7577 }
7578
7579 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7580 if self.take_rename(true, cx).is_some() {
7581 return;
7582 }
7583
7584 if self
7585 .context_menu
7586 .write()
7587 .as_mut()
7588 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7589 .unwrap_or(false)
7590 {
7591 return;
7592 }
7593
7594 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7595 cx.propagate();
7596 return;
7597 }
7598
7599 let Some(row_count) = self.visible_row_count() else {
7600 return;
7601 };
7602
7603 let autoscroll = if action.center_cursor {
7604 Autoscroll::center()
7605 } else {
7606 Autoscroll::fit()
7607 };
7608
7609 let text_layout_details = &self.text_layout_details(cx);
7610
7611 self.change_selections(Some(autoscroll), cx, |s| {
7612 let line_mode = s.line_mode;
7613 s.move_with(|map, selection| {
7614 if !selection.is_empty() && !line_mode {
7615 selection.goal = SelectionGoal::None;
7616 }
7617 let (cursor, goal) = movement::up_by_rows(
7618 map,
7619 selection.end,
7620 row_count,
7621 selection.goal,
7622 false,
7623 text_layout_details,
7624 );
7625 selection.collapse_to(cursor, goal);
7626 });
7627 });
7628 }
7629
7630 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7631 let text_layout_details = &self.text_layout_details(cx);
7632 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7633 s.move_heads_with(|map, head, goal| {
7634 movement::up(map, head, goal, false, text_layout_details)
7635 })
7636 })
7637 }
7638
7639 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7640 self.take_rename(true, cx);
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 let selection_count = self.selections.count();
7649 let first_selection = self.selections.first_anchor();
7650
7651 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7652 let line_mode = s.line_mode;
7653 s.move_with(|map, selection| {
7654 if !selection.is_empty() && !line_mode {
7655 selection.goal = SelectionGoal::None;
7656 }
7657 let (cursor, goal) = movement::down(
7658 map,
7659 selection.end,
7660 selection.goal,
7661 false,
7662 text_layout_details,
7663 );
7664 selection.collapse_to(cursor, goal);
7665 });
7666 });
7667
7668 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7669 {
7670 cx.propagate();
7671 }
7672 }
7673
7674 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7675 let Some(row_count) = self.visible_row_count() else {
7676 return;
7677 };
7678
7679 let text_layout_details = &self.text_layout_details(cx);
7680
7681 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7682 s.move_heads_with(|map, head, goal| {
7683 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7684 })
7685 })
7686 }
7687
7688 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7689 if self.take_rename(true, cx).is_some() {
7690 return;
7691 }
7692
7693 if self
7694 .context_menu
7695 .write()
7696 .as_mut()
7697 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7698 .unwrap_or(false)
7699 {
7700 return;
7701 }
7702
7703 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7704 cx.propagate();
7705 return;
7706 }
7707
7708 let Some(row_count) = self.visible_row_count() else {
7709 return;
7710 };
7711
7712 let autoscroll = if action.center_cursor {
7713 Autoscroll::center()
7714 } else {
7715 Autoscroll::fit()
7716 };
7717
7718 let text_layout_details = &self.text_layout_details(cx);
7719 self.change_selections(Some(autoscroll), cx, |s| {
7720 let line_mode = s.line_mode;
7721 s.move_with(|map, selection| {
7722 if !selection.is_empty() && !line_mode {
7723 selection.goal = SelectionGoal::None;
7724 }
7725 let (cursor, goal) = movement::down_by_rows(
7726 map,
7727 selection.end,
7728 row_count,
7729 selection.goal,
7730 false,
7731 text_layout_details,
7732 );
7733 selection.collapse_to(cursor, goal);
7734 });
7735 });
7736 }
7737
7738 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7739 let text_layout_details = &self.text_layout_details(cx);
7740 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7741 s.move_heads_with(|map, head, goal| {
7742 movement::down(map, head, goal, false, text_layout_details)
7743 })
7744 });
7745 }
7746
7747 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7748 if let Some(context_menu) = self.context_menu.write().as_mut() {
7749 context_menu.select_first(self.completion_provider.as_deref(), cx);
7750 }
7751 }
7752
7753 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7754 if let Some(context_menu) = self.context_menu.write().as_mut() {
7755 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7756 }
7757 }
7758
7759 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7760 if let Some(context_menu) = self.context_menu.write().as_mut() {
7761 context_menu.select_next(self.completion_provider.as_deref(), cx);
7762 }
7763 }
7764
7765 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7766 if let Some(context_menu) = self.context_menu.write().as_mut() {
7767 context_menu.select_last(self.completion_provider.as_deref(), cx);
7768 }
7769 }
7770
7771 pub fn move_to_previous_word_start(
7772 &mut self,
7773 _: &MoveToPreviousWordStart,
7774 cx: &mut ViewContext<Self>,
7775 ) {
7776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7777 s.move_cursors_with(|map, head, _| {
7778 (
7779 movement::previous_word_start(map, head),
7780 SelectionGoal::None,
7781 )
7782 });
7783 })
7784 }
7785
7786 pub fn move_to_previous_subword_start(
7787 &mut self,
7788 _: &MoveToPreviousSubwordStart,
7789 cx: &mut ViewContext<Self>,
7790 ) {
7791 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7792 s.move_cursors_with(|map, head, _| {
7793 (
7794 movement::previous_subword_start(map, head),
7795 SelectionGoal::None,
7796 )
7797 });
7798 })
7799 }
7800
7801 pub fn select_to_previous_word_start(
7802 &mut self,
7803 _: &SelectToPreviousWordStart,
7804 cx: &mut ViewContext<Self>,
7805 ) {
7806 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7807 s.move_heads_with(|map, head, _| {
7808 (
7809 movement::previous_word_start(map, head),
7810 SelectionGoal::None,
7811 )
7812 });
7813 })
7814 }
7815
7816 pub fn select_to_previous_subword_start(
7817 &mut self,
7818 _: &SelectToPreviousSubwordStart,
7819 cx: &mut ViewContext<Self>,
7820 ) {
7821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7822 s.move_heads_with(|map, head, _| {
7823 (
7824 movement::previous_subword_start(map, head),
7825 SelectionGoal::None,
7826 )
7827 });
7828 })
7829 }
7830
7831 pub fn delete_to_previous_word_start(
7832 &mut self,
7833 action: &DeleteToPreviousWordStart,
7834 cx: &mut ViewContext<Self>,
7835 ) {
7836 self.transact(cx, |this, cx| {
7837 this.select_autoclose_pair(cx);
7838 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7839 let line_mode = s.line_mode;
7840 s.move_with(|map, selection| {
7841 if selection.is_empty() && !line_mode {
7842 let cursor = if action.ignore_newlines {
7843 movement::previous_word_start(map, selection.head())
7844 } else {
7845 movement::previous_word_start_or_newline(map, selection.head())
7846 };
7847 selection.set_head(cursor, SelectionGoal::None);
7848 }
7849 });
7850 });
7851 this.insert("", cx);
7852 });
7853 }
7854
7855 pub fn delete_to_previous_subword_start(
7856 &mut self,
7857 _: &DeleteToPreviousSubwordStart,
7858 cx: &mut ViewContext<Self>,
7859 ) {
7860 self.transact(cx, |this, cx| {
7861 this.select_autoclose_pair(cx);
7862 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7863 let line_mode = s.line_mode;
7864 s.move_with(|map, selection| {
7865 if selection.is_empty() && !line_mode {
7866 let cursor = movement::previous_subword_start(map, selection.head());
7867 selection.set_head(cursor, SelectionGoal::None);
7868 }
7869 });
7870 });
7871 this.insert("", cx);
7872 });
7873 }
7874
7875 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7876 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7877 s.move_cursors_with(|map, head, _| {
7878 (movement::next_word_end(map, head), SelectionGoal::None)
7879 });
7880 })
7881 }
7882
7883 pub fn move_to_next_subword_end(
7884 &mut self,
7885 _: &MoveToNextSubwordEnd,
7886 cx: &mut ViewContext<Self>,
7887 ) {
7888 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7889 s.move_cursors_with(|map, head, _| {
7890 (movement::next_subword_end(map, head), SelectionGoal::None)
7891 });
7892 })
7893 }
7894
7895 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7896 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7897 s.move_heads_with(|map, head, _| {
7898 (movement::next_word_end(map, head), SelectionGoal::None)
7899 });
7900 })
7901 }
7902
7903 pub fn select_to_next_subword_end(
7904 &mut self,
7905 _: &SelectToNextSubwordEnd,
7906 cx: &mut ViewContext<Self>,
7907 ) {
7908 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7909 s.move_heads_with(|map, head, _| {
7910 (movement::next_subword_end(map, head), SelectionGoal::None)
7911 });
7912 })
7913 }
7914
7915 pub fn delete_to_next_word_end(
7916 &mut self,
7917 action: &DeleteToNextWordEnd,
7918 cx: &mut ViewContext<Self>,
7919 ) {
7920 self.transact(cx, |this, cx| {
7921 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7922 let line_mode = s.line_mode;
7923 s.move_with(|map, selection| {
7924 if selection.is_empty() && !line_mode {
7925 let cursor = if action.ignore_newlines {
7926 movement::next_word_end(map, selection.head())
7927 } else {
7928 movement::next_word_end_or_newline(map, selection.head())
7929 };
7930 selection.set_head(cursor, SelectionGoal::None);
7931 }
7932 });
7933 });
7934 this.insert("", cx);
7935 });
7936 }
7937
7938 pub fn delete_to_next_subword_end(
7939 &mut self,
7940 _: &DeleteToNextSubwordEnd,
7941 cx: &mut ViewContext<Self>,
7942 ) {
7943 self.transact(cx, |this, cx| {
7944 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7945 s.move_with(|map, selection| {
7946 if selection.is_empty() {
7947 let cursor = movement::next_subword_end(map, selection.head());
7948 selection.set_head(cursor, SelectionGoal::None);
7949 }
7950 });
7951 });
7952 this.insert("", cx);
7953 });
7954 }
7955
7956 pub fn move_to_beginning_of_line(
7957 &mut self,
7958 action: &MoveToBeginningOfLine,
7959 cx: &mut ViewContext<Self>,
7960 ) {
7961 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7962 s.move_cursors_with(|map, head, _| {
7963 (
7964 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7965 SelectionGoal::None,
7966 )
7967 });
7968 })
7969 }
7970
7971 pub fn select_to_beginning_of_line(
7972 &mut self,
7973 action: &SelectToBeginningOfLine,
7974 cx: &mut ViewContext<Self>,
7975 ) {
7976 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7977 s.move_heads_with(|map, head, _| {
7978 (
7979 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7980 SelectionGoal::None,
7981 )
7982 });
7983 });
7984 }
7985
7986 pub fn delete_to_beginning_of_line(
7987 &mut self,
7988 _: &DeleteToBeginningOfLine,
7989 cx: &mut ViewContext<Self>,
7990 ) {
7991 self.transact(cx, |this, cx| {
7992 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7993 s.move_with(|_, selection| {
7994 selection.reversed = true;
7995 });
7996 });
7997
7998 this.select_to_beginning_of_line(
7999 &SelectToBeginningOfLine {
8000 stop_at_soft_wraps: false,
8001 },
8002 cx,
8003 );
8004 this.backspace(&Backspace, cx);
8005 });
8006 }
8007
8008 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8009 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8010 s.move_cursors_with(|map, head, _| {
8011 (
8012 movement::line_end(map, head, action.stop_at_soft_wraps),
8013 SelectionGoal::None,
8014 )
8015 });
8016 })
8017 }
8018
8019 pub fn select_to_end_of_line(
8020 &mut self,
8021 action: &SelectToEndOfLine,
8022 cx: &mut ViewContext<Self>,
8023 ) {
8024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8025 s.move_heads_with(|map, head, _| {
8026 (
8027 movement::line_end(map, head, action.stop_at_soft_wraps),
8028 SelectionGoal::None,
8029 )
8030 });
8031 })
8032 }
8033
8034 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8035 self.transact(cx, |this, cx| {
8036 this.select_to_end_of_line(
8037 &SelectToEndOfLine {
8038 stop_at_soft_wraps: false,
8039 },
8040 cx,
8041 );
8042 this.delete(&Delete, cx);
8043 });
8044 }
8045
8046 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8047 self.transact(cx, |this, cx| {
8048 this.select_to_end_of_line(
8049 &SelectToEndOfLine {
8050 stop_at_soft_wraps: false,
8051 },
8052 cx,
8053 );
8054 this.cut(&Cut, cx);
8055 });
8056 }
8057
8058 pub fn move_to_start_of_paragraph(
8059 &mut self,
8060 _: &MoveToStartOfParagraph,
8061 cx: &mut ViewContext<Self>,
8062 ) {
8063 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8064 cx.propagate();
8065 return;
8066 }
8067
8068 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8069 s.move_with(|map, selection| {
8070 selection.collapse_to(
8071 movement::start_of_paragraph(map, selection.head(), 1),
8072 SelectionGoal::None,
8073 )
8074 });
8075 })
8076 }
8077
8078 pub fn move_to_end_of_paragraph(
8079 &mut self,
8080 _: &MoveToEndOfParagraph,
8081 cx: &mut ViewContext<Self>,
8082 ) {
8083 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8084 cx.propagate();
8085 return;
8086 }
8087
8088 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8089 s.move_with(|map, selection| {
8090 selection.collapse_to(
8091 movement::end_of_paragraph(map, selection.head(), 1),
8092 SelectionGoal::None,
8093 )
8094 });
8095 })
8096 }
8097
8098 pub fn select_to_start_of_paragraph(
8099 &mut self,
8100 _: &SelectToStartOfParagraph,
8101 cx: &mut ViewContext<Self>,
8102 ) {
8103 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8104 cx.propagate();
8105 return;
8106 }
8107
8108 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8109 s.move_heads_with(|map, head, _| {
8110 (
8111 movement::start_of_paragraph(map, head, 1),
8112 SelectionGoal::None,
8113 )
8114 });
8115 })
8116 }
8117
8118 pub fn select_to_end_of_paragraph(
8119 &mut self,
8120 _: &SelectToEndOfParagraph,
8121 cx: &mut ViewContext<Self>,
8122 ) {
8123 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8124 cx.propagate();
8125 return;
8126 }
8127
8128 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8129 s.move_heads_with(|map, head, _| {
8130 (
8131 movement::end_of_paragraph(map, head, 1),
8132 SelectionGoal::None,
8133 )
8134 });
8135 })
8136 }
8137
8138 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8139 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8140 cx.propagate();
8141 return;
8142 }
8143
8144 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8145 s.select_ranges(vec![0..0]);
8146 });
8147 }
8148
8149 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8150 let mut selection = self.selections.last::<Point>(cx);
8151 selection.set_head(Point::zero(), SelectionGoal::None);
8152
8153 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8154 s.select(vec![selection]);
8155 });
8156 }
8157
8158 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8159 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8160 cx.propagate();
8161 return;
8162 }
8163
8164 let cursor = self.buffer.read(cx).read(cx).len();
8165 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8166 s.select_ranges(vec![cursor..cursor])
8167 });
8168 }
8169
8170 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8171 self.nav_history = nav_history;
8172 }
8173
8174 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8175 self.nav_history.as_ref()
8176 }
8177
8178 fn push_to_nav_history(
8179 &mut self,
8180 cursor_anchor: Anchor,
8181 new_position: Option<Point>,
8182 cx: &mut ViewContext<Self>,
8183 ) {
8184 if let Some(nav_history) = self.nav_history.as_mut() {
8185 let buffer = self.buffer.read(cx).read(cx);
8186 let cursor_position = cursor_anchor.to_point(&buffer);
8187 let scroll_state = self.scroll_manager.anchor();
8188 let scroll_top_row = scroll_state.top_row(&buffer);
8189 drop(buffer);
8190
8191 if let Some(new_position) = new_position {
8192 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8193 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8194 return;
8195 }
8196 }
8197
8198 nav_history.push(
8199 Some(NavigationData {
8200 cursor_anchor,
8201 cursor_position,
8202 scroll_anchor: scroll_state,
8203 scroll_top_row,
8204 }),
8205 cx,
8206 );
8207 }
8208 }
8209
8210 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8211 let buffer = self.buffer.read(cx).snapshot(cx);
8212 let mut selection = self.selections.first::<usize>(cx);
8213 selection.set_head(buffer.len(), SelectionGoal::None);
8214 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8215 s.select(vec![selection]);
8216 });
8217 }
8218
8219 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8220 let end = self.buffer.read(cx).read(cx).len();
8221 self.change_selections(None, cx, |s| {
8222 s.select_ranges(vec![0..end]);
8223 });
8224 }
8225
8226 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8227 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8228 let mut selections = self.selections.all::<Point>(cx);
8229 let max_point = display_map.buffer_snapshot.max_point();
8230 for selection in &mut selections {
8231 let rows = selection.spanned_rows(true, &display_map);
8232 selection.start = Point::new(rows.start.0, 0);
8233 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8234 selection.reversed = false;
8235 }
8236 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8237 s.select(selections);
8238 });
8239 }
8240
8241 pub fn split_selection_into_lines(
8242 &mut self,
8243 _: &SplitSelectionIntoLines,
8244 cx: &mut ViewContext<Self>,
8245 ) {
8246 let mut to_unfold = Vec::new();
8247 let mut new_selection_ranges = Vec::new();
8248 {
8249 let selections = self.selections.all::<Point>(cx);
8250 let buffer = self.buffer.read(cx).read(cx);
8251 for selection in selections {
8252 for row in selection.start.row..selection.end.row {
8253 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8254 new_selection_ranges.push(cursor..cursor);
8255 }
8256 new_selection_ranges.push(selection.end..selection.end);
8257 to_unfold.push(selection.start..selection.end);
8258 }
8259 }
8260 self.unfold_ranges(&to_unfold, true, true, cx);
8261 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8262 s.select_ranges(new_selection_ranges);
8263 });
8264 }
8265
8266 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8267 self.add_selection(true, cx);
8268 }
8269
8270 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8271 self.add_selection(false, cx);
8272 }
8273
8274 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8276 let mut selections = self.selections.all::<Point>(cx);
8277 let text_layout_details = self.text_layout_details(cx);
8278 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8279 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8280 let range = oldest_selection.display_range(&display_map).sorted();
8281
8282 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8283 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8284 let positions = start_x.min(end_x)..start_x.max(end_x);
8285
8286 selections.clear();
8287 let mut stack = Vec::new();
8288 for row in range.start.row().0..=range.end.row().0 {
8289 if let Some(selection) = self.selections.build_columnar_selection(
8290 &display_map,
8291 DisplayRow(row),
8292 &positions,
8293 oldest_selection.reversed,
8294 &text_layout_details,
8295 ) {
8296 stack.push(selection.id);
8297 selections.push(selection);
8298 }
8299 }
8300
8301 if above {
8302 stack.reverse();
8303 }
8304
8305 AddSelectionsState { above, stack }
8306 });
8307
8308 let last_added_selection = *state.stack.last().unwrap();
8309 let mut new_selections = Vec::new();
8310 if above == state.above {
8311 let end_row = if above {
8312 DisplayRow(0)
8313 } else {
8314 display_map.max_point().row()
8315 };
8316
8317 'outer: for selection in selections {
8318 if selection.id == last_added_selection {
8319 let range = selection.display_range(&display_map).sorted();
8320 debug_assert_eq!(range.start.row(), range.end.row());
8321 let mut row = range.start.row();
8322 let positions =
8323 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8324 px(start)..px(end)
8325 } else {
8326 let start_x =
8327 display_map.x_for_display_point(range.start, &text_layout_details);
8328 let end_x =
8329 display_map.x_for_display_point(range.end, &text_layout_details);
8330 start_x.min(end_x)..start_x.max(end_x)
8331 };
8332
8333 while row != end_row {
8334 if above {
8335 row.0 -= 1;
8336 } else {
8337 row.0 += 1;
8338 }
8339
8340 if let Some(new_selection) = self.selections.build_columnar_selection(
8341 &display_map,
8342 row,
8343 &positions,
8344 selection.reversed,
8345 &text_layout_details,
8346 ) {
8347 state.stack.push(new_selection.id);
8348 if above {
8349 new_selections.push(new_selection);
8350 new_selections.push(selection);
8351 } else {
8352 new_selections.push(selection);
8353 new_selections.push(new_selection);
8354 }
8355
8356 continue 'outer;
8357 }
8358 }
8359 }
8360
8361 new_selections.push(selection);
8362 }
8363 } else {
8364 new_selections = selections;
8365 new_selections.retain(|s| s.id != last_added_selection);
8366 state.stack.pop();
8367 }
8368
8369 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8370 s.select(new_selections);
8371 });
8372 if state.stack.len() > 1 {
8373 self.add_selections_state = Some(state);
8374 }
8375 }
8376
8377 pub fn select_next_match_internal(
8378 &mut self,
8379 display_map: &DisplaySnapshot,
8380 replace_newest: bool,
8381 autoscroll: Option<Autoscroll>,
8382 cx: &mut ViewContext<Self>,
8383 ) -> Result<()> {
8384 fn select_next_match_ranges(
8385 this: &mut Editor,
8386 range: Range<usize>,
8387 replace_newest: bool,
8388 auto_scroll: Option<Autoscroll>,
8389 cx: &mut ViewContext<Editor>,
8390 ) {
8391 this.unfold_ranges(&[range.clone()], false, true, cx);
8392 this.change_selections(auto_scroll, cx, |s| {
8393 if replace_newest {
8394 s.delete(s.newest_anchor().id);
8395 }
8396 s.insert_range(range.clone());
8397 });
8398 }
8399
8400 let buffer = &display_map.buffer_snapshot;
8401 let mut selections = self.selections.all::<usize>(cx);
8402 if let Some(mut select_next_state) = self.select_next_state.take() {
8403 let query = &select_next_state.query;
8404 if !select_next_state.done {
8405 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8406 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8407 let mut next_selected_range = None;
8408
8409 let bytes_after_last_selection =
8410 buffer.bytes_in_range(last_selection.end..buffer.len());
8411 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8412 let query_matches = query
8413 .stream_find_iter(bytes_after_last_selection)
8414 .map(|result| (last_selection.end, result))
8415 .chain(
8416 query
8417 .stream_find_iter(bytes_before_first_selection)
8418 .map(|result| (0, result)),
8419 );
8420
8421 for (start_offset, query_match) in query_matches {
8422 let query_match = query_match.unwrap(); // can only fail due to I/O
8423 let offset_range =
8424 start_offset + query_match.start()..start_offset + query_match.end();
8425 let display_range = offset_range.start.to_display_point(display_map)
8426 ..offset_range.end.to_display_point(display_map);
8427
8428 if !select_next_state.wordwise
8429 || (!movement::is_inside_word(display_map, display_range.start)
8430 && !movement::is_inside_word(display_map, display_range.end))
8431 {
8432 // TODO: This is n^2, because we might check all the selections
8433 if !selections
8434 .iter()
8435 .any(|selection| selection.range().overlaps(&offset_range))
8436 {
8437 next_selected_range = Some(offset_range);
8438 break;
8439 }
8440 }
8441 }
8442
8443 if let Some(next_selected_range) = next_selected_range {
8444 select_next_match_ranges(
8445 self,
8446 next_selected_range,
8447 replace_newest,
8448 autoscroll,
8449 cx,
8450 );
8451 } else {
8452 select_next_state.done = true;
8453 }
8454 }
8455
8456 self.select_next_state = Some(select_next_state);
8457 } else {
8458 let mut only_carets = true;
8459 let mut same_text_selected = true;
8460 let mut selected_text = None;
8461
8462 let mut selections_iter = selections.iter().peekable();
8463 while let Some(selection) = selections_iter.next() {
8464 if selection.start != selection.end {
8465 only_carets = false;
8466 }
8467
8468 if same_text_selected {
8469 if selected_text.is_none() {
8470 selected_text =
8471 Some(buffer.text_for_range(selection.range()).collect::<String>());
8472 }
8473
8474 if let Some(next_selection) = selections_iter.peek() {
8475 if next_selection.range().len() == selection.range().len() {
8476 let next_selected_text = buffer
8477 .text_for_range(next_selection.range())
8478 .collect::<String>();
8479 if Some(next_selected_text) != selected_text {
8480 same_text_selected = false;
8481 selected_text = None;
8482 }
8483 } else {
8484 same_text_selected = false;
8485 selected_text = None;
8486 }
8487 }
8488 }
8489 }
8490
8491 if only_carets {
8492 for selection in &mut selections {
8493 let word_range = movement::surrounding_word(
8494 display_map,
8495 selection.start.to_display_point(display_map),
8496 );
8497 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8498 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8499 selection.goal = SelectionGoal::None;
8500 selection.reversed = false;
8501 select_next_match_ranges(
8502 self,
8503 selection.start..selection.end,
8504 replace_newest,
8505 autoscroll,
8506 cx,
8507 );
8508 }
8509
8510 if selections.len() == 1 {
8511 let selection = selections
8512 .last()
8513 .expect("ensured that there's only one selection");
8514 let query = buffer
8515 .text_for_range(selection.start..selection.end)
8516 .collect::<String>();
8517 let is_empty = query.is_empty();
8518 let select_state = SelectNextState {
8519 query: AhoCorasick::new(&[query])?,
8520 wordwise: true,
8521 done: is_empty,
8522 };
8523 self.select_next_state = Some(select_state);
8524 } else {
8525 self.select_next_state = None;
8526 }
8527 } else if let Some(selected_text) = selected_text {
8528 self.select_next_state = Some(SelectNextState {
8529 query: AhoCorasick::new(&[selected_text])?,
8530 wordwise: false,
8531 done: false,
8532 });
8533 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8534 }
8535 }
8536 Ok(())
8537 }
8538
8539 pub fn select_all_matches(
8540 &mut self,
8541 _action: &SelectAllMatches,
8542 cx: &mut ViewContext<Self>,
8543 ) -> Result<()> {
8544 self.push_to_selection_history();
8545 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8546
8547 self.select_next_match_internal(&display_map, false, None, cx)?;
8548 let Some(select_next_state) = self.select_next_state.as_mut() else {
8549 return Ok(());
8550 };
8551 if select_next_state.done {
8552 return Ok(());
8553 }
8554
8555 let mut new_selections = self.selections.all::<usize>(cx);
8556
8557 let buffer = &display_map.buffer_snapshot;
8558 let query_matches = select_next_state
8559 .query
8560 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8561
8562 for query_match in query_matches {
8563 let query_match = query_match.unwrap(); // can only fail due to I/O
8564 let offset_range = query_match.start()..query_match.end();
8565 let display_range = offset_range.start.to_display_point(&display_map)
8566 ..offset_range.end.to_display_point(&display_map);
8567
8568 if !select_next_state.wordwise
8569 || (!movement::is_inside_word(&display_map, display_range.start)
8570 && !movement::is_inside_word(&display_map, display_range.end))
8571 {
8572 self.selections.change_with(cx, |selections| {
8573 new_selections.push(Selection {
8574 id: selections.new_selection_id(),
8575 start: offset_range.start,
8576 end: offset_range.end,
8577 reversed: false,
8578 goal: SelectionGoal::None,
8579 });
8580 });
8581 }
8582 }
8583
8584 new_selections.sort_by_key(|selection| selection.start);
8585 let mut ix = 0;
8586 while ix + 1 < new_selections.len() {
8587 let current_selection = &new_selections[ix];
8588 let next_selection = &new_selections[ix + 1];
8589 if current_selection.range().overlaps(&next_selection.range()) {
8590 if current_selection.id < next_selection.id {
8591 new_selections.remove(ix + 1);
8592 } else {
8593 new_selections.remove(ix);
8594 }
8595 } else {
8596 ix += 1;
8597 }
8598 }
8599
8600 select_next_state.done = true;
8601 self.unfold_ranges(
8602 &new_selections
8603 .iter()
8604 .map(|selection| selection.range())
8605 .collect::<Vec<_>>(),
8606 false,
8607 false,
8608 cx,
8609 );
8610 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8611 selections.select(new_selections)
8612 });
8613
8614 Ok(())
8615 }
8616
8617 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8618 self.push_to_selection_history();
8619 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8620 self.select_next_match_internal(
8621 &display_map,
8622 action.replace_newest,
8623 Some(Autoscroll::newest()),
8624 cx,
8625 )?;
8626 Ok(())
8627 }
8628
8629 pub fn select_previous(
8630 &mut self,
8631 action: &SelectPrevious,
8632 cx: &mut ViewContext<Self>,
8633 ) -> Result<()> {
8634 self.push_to_selection_history();
8635 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8636 let buffer = &display_map.buffer_snapshot;
8637 let mut selections = self.selections.all::<usize>(cx);
8638 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8639 let query = &select_prev_state.query;
8640 if !select_prev_state.done {
8641 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8642 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8643 let mut next_selected_range = None;
8644 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8645 let bytes_before_last_selection =
8646 buffer.reversed_bytes_in_range(0..last_selection.start);
8647 let bytes_after_first_selection =
8648 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8649 let query_matches = query
8650 .stream_find_iter(bytes_before_last_selection)
8651 .map(|result| (last_selection.start, result))
8652 .chain(
8653 query
8654 .stream_find_iter(bytes_after_first_selection)
8655 .map(|result| (buffer.len(), result)),
8656 );
8657 for (end_offset, query_match) in query_matches {
8658 let query_match = query_match.unwrap(); // can only fail due to I/O
8659 let offset_range =
8660 end_offset - query_match.end()..end_offset - query_match.start();
8661 let display_range = offset_range.start.to_display_point(&display_map)
8662 ..offset_range.end.to_display_point(&display_map);
8663
8664 if !select_prev_state.wordwise
8665 || (!movement::is_inside_word(&display_map, display_range.start)
8666 && !movement::is_inside_word(&display_map, display_range.end))
8667 {
8668 next_selected_range = Some(offset_range);
8669 break;
8670 }
8671 }
8672
8673 if let Some(next_selected_range) = next_selected_range {
8674 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8675 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8676 if action.replace_newest {
8677 s.delete(s.newest_anchor().id);
8678 }
8679 s.insert_range(next_selected_range);
8680 });
8681 } else {
8682 select_prev_state.done = true;
8683 }
8684 }
8685
8686 self.select_prev_state = Some(select_prev_state);
8687 } else {
8688 let mut only_carets = true;
8689 let mut same_text_selected = true;
8690 let mut selected_text = None;
8691
8692 let mut selections_iter = selections.iter().peekable();
8693 while let Some(selection) = selections_iter.next() {
8694 if selection.start != selection.end {
8695 only_carets = false;
8696 }
8697
8698 if same_text_selected {
8699 if selected_text.is_none() {
8700 selected_text =
8701 Some(buffer.text_for_range(selection.range()).collect::<String>());
8702 }
8703
8704 if let Some(next_selection) = selections_iter.peek() {
8705 if next_selection.range().len() == selection.range().len() {
8706 let next_selected_text = buffer
8707 .text_for_range(next_selection.range())
8708 .collect::<String>();
8709 if Some(next_selected_text) != selected_text {
8710 same_text_selected = false;
8711 selected_text = None;
8712 }
8713 } else {
8714 same_text_selected = false;
8715 selected_text = None;
8716 }
8717 }
8718 }
8719 }
8720
8721 if only_carets {
8722 for selection in &mut selections {
8723 let word_range = movement::surrounding_word(
8724 &display_map,
8725 selection.start.to_display_point(&display_map),
8726 );
8727 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8728 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8729 selection.goal = SelectionGoal::None;
8730 selection.reversed = false;
8731 }
8732 if selections.len() == 1 {
8733 let selection = selections
8734 .last()
8735 .expect("ensured that there's only one selection");
8736 let query = buffer
8737 .text_for_range(selection.start..selection.end)
8738 .collect::<String>();
8739 let is_empty = query.is_empty();
8740 let select_state = SelectNextState {
8741 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8742 wordwise: true,
8743 done: is_empty,
8744 };
8745 self.select_prev_state = Some(select_state);
8746 } else {
8747 self.select_prev_state = None;
8748 }
8749
8750 self.unfold_ranges(
8751 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8752 false,
8753 true,
8754 cx,
8755 );
8756 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8757 s.select(selections);
8758 });
8759 } else if let Some(selected_text) = selected_text {
8760 self.select_prev_state = Some(SelectNextState {
8761 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8762 wordwise: false,
8763 done: false,
8764 });
8765 self.select_previous(action, cx)?;
8766 }
8767 }
8768 Ok(())
8769 }
8770
8771 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8772 let text_layout_details = &self.text_layout_details(cx);
8773 self.transact(cx, |this, cx| {
8774 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8775 let mut edits = Vec::new();
8776 let mut selection_edit_ranges = Vec::new();
8777 let mut last_toggled_row = None;
8778 let snapshot = this.buffer.read(cx).read(cx);
8779 let empty_str: Arc<str> = Arc::default();
8780 let mut suffixes_inserted = Vec::new();
8781 let ignore_indent = action.ignore_indent;
8782
8783 fn comment_prefix_range(
8784 snapshot: &MultiBufferSnapshot,
8785 row: MultiBufferRow,
8786 comment_prefix: &str,
8787 comment_prefix_whitespace: &str,
8788 ignore_indent: bool,
8789 ) -> Range<Point> {
8790 let indent_size = if ignore_indent {
8791 0
8792 } else {
8793 snapshot.indent_size_for_line(row).len
8794 };
8795
8796 let start = Point::new(row.0, indent_size);
8797
8798 let mut line_bytes = snapshot
8799 .bytes_in_range(start..snapshot.max_point())
8800 .flatten()
8801 .copied();
8802
8803 // If this line currently begins with the line comment prefix, then record
8804 // the range containing the prefix.
8805 if line_bytes
8806 .by_ref()
8807 .take(comment_prefix.len())
8808 .eq(comment_prefix.bytes())
8809 {
8810 // Include any whitespace that matches the comment prefix.
8811 let matching_whitespace_len = line_bytes
8812 .zip(comment_prefix_whitespace.bytes())
8813 .take_while(|(a, b)| a == b)
8814 .count() as u32;
8815 let end = Point::new(
8816 start.row,
8817 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8818 );
8819 start..end
8820 } else {
8821 start..start
8822 }
8823 }
8824
8825 fn comment_suffix_range(
8826 snapshot: &MultiBufferSnapshot,
8827 row: MultiBufferRow,
8828 comment_suffix: &str,
8829 comment_suffix_has_leading_space: bool,
8830 ) -> Range<Point> {
8831 let end = Point::new(row.0, snapshot.line_len(row));
8832 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8833
8834 let mut line_end_bytes = snapshot
8835 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8836 .flatten()
8837 .copied();
8838
8839 let leading_space_len = if suffix_start_column > 0
8840 && line_end_bytes.next() == Some(b' ')
8841 && comment_suffix_has_leading_space
8842 {
8843 1
8844 } else {
8845 0
8846 };
8847
8848 // If this line currently begins with the line comment prefix, then record
8849 // the range containing the prefix.
8850 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8851 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8852 start..end
8853 } else {
8854 end..end
8855 }
8856 }
8857
8858 // TODO: Handle selections that cross excerpts
8859 for selection in &mut selections {
8860 let start_column = snapshot
8861 .indent_size_for_line(MultiBufferRow(selection.start.row))
8862 .len;
8863 let language = if let Some(language) =
8864 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8865 {
8866 language
8867 } else {
8868 continue;
8869 };
8870
8871 selection_edit_ranges.clear();
8872
8873 // If multiple selections contain a given row, avoid processing that
8874 // row more than once.
8875 let mut start_row = MultiBufferRow(selection.start.row);
8876 if last_toggled_row == Some(start_row) {
8877 start_row = start_row.next_row();
8878 }
8879 let end_row =
8880 if selection.end.row > selection.start.row && selection.end.column == 0 {
8881 MultiBufferRow(selection.end.row - 1)
8882 } else {
8883 MultiBufferRow(selection.end.row)
8884 };
8885 last_toggled_row = Some(end_row);
8886
8887 if start_row > end_row {
8888 continue;
8889 }
8890
8891 // If the language has line comments, toggle those.
8892 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8893
8894 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8895 if ignore_indent {
8896 full_comment_prefixes = full_comment_prefixes
8897 .into_iter()
8898 .map(|s| Arc::from(s.trim_end()))
8899 .collect();
8900 }
8901
8902 if !full_comment_prefixes.is_empty() {
8903 let first_prefix = full_comment_prefixes
8904 .first()
8905 .expect("prefixes is non-empty");
8906 let prefix_trimmed_lengths = full_comment_prefixes
8907 .iter()
8908 .map(|p| p.trim_end_matches(' ').len())
8909 .collect::<SmallVec<[usize; 4]>>();
8910
8911 let mut all_selection_lines_are_comments = true;
8912
8913 for row in start_row.0..=end_row.0 {
8914 let row = MultiBufferRow(row);
8915 if start_row < end_row && snapshot.is_line_blank(row) {
8916 continue;
8917 }
8918
8919 let prefix_range = full_comment_prefixes
8920 .iter()
8921 .zip(prefix_trimmed_lengths.iter().copied())
8922 .map(|(prefix, trimmed_prefix_len)| {
8923 comment_prefix_range(
8924 snapshot.deref(),
8925 row,
8926 &prefix[..trimmed_prefix_len],
8927 &prefix[trimmed_prefix_len..],
8928 ignore_indent,
8929 )
8930 })
8931 .max_by_key(|range| range.end.column - range.start.column)
8932 .expect("prefixes is non-empty");
8933
8934 if prefix_range.is_empty() {
8935 all_selection_lines_are_comments = false;
8936 }
8937
8938 selection_edit_ranges.push(prefix_range);
8939 }
8940
8941 if all_selection_lines_are_comments {
8942 edits.extend(
8943 selection_edit_ranges
8944 .iter()
8945 .cloned()
8946 .map(|range| (range, empty_str.clone())),
8947 );
8948 } else {
8949 let min_column = selection_edit_ranges
8950 .iter()
8951 .map(|range| range.start.column)
8952 .min()
8953 .unwrap_or(0);
8954 edits.extend(selection_edit_ranges.iter().map(|range| {
8955 let position = Point::new(range.start.row, min_column);
8956 (position..position, first_prefix.clone())
8957 }));
8958 }
8959 } else if let Some((full_comment_prefix, comment_suffix)) =
8960 language.block_comment_delimiters()
8961 {
8962 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8963 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8964 let prefix_range = comment_prefix_range(
8965 snapshot.deref(),
8966 start_row,
8967 comment_prefix,
8968 comment_prefix_whitespace,
8969 ignore_indent,
8970 );
8971 let suffix_range = comment_suffix_range(
8972 snapshot.deref(),
8973 end_row,
8974 comment_suffix.trim_start_matches(' '),
8975 comment_suffix.starts_with(' '),
8976 );
8977
8978 if prefix_range.is_empty() || suffix_range.is_empty() {
8979 edits.push((
8980 prefix_range.start..prefix_range.start,
8981 full_comment_prefix.clone(),
8982 ));
8983 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8984 suffixes_inserted.push((end_row, comment_suffix.len()));
8985 } else {
8986 edits.push((prefix_range, empty_str.clone()));
8987 edits.push((suffix_range, empty_str.clone()));
8988 }
8989 } else {
8990 continue;
8991 }
8992 }
8993
8994 drop(snapshot);
8995 this.buffer.update(cx, |buffer, cx| {
8996 buffer.edit(edits, None, cx);
8997 });
8998
8999 // Adjust selections so that they end before any comment suffixes that
9000 // were inserted.
9001 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9002 let mut selections = this.selections.all::<Point>(cx);
9003 let snapshot = this.buffer.read(cx).read(cx);
9004 for selection in &mut selections {
9005 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9006 match row.cmp(&MultiBufferRow(selection.end.row)) {
9007 Ordering::Less => {
9008 suffixes_inserted.next();
9009 continue;
9010 }
9011 Ordering::Greater => break,
9012 Ordering::Equal => {
9013 if selection.end.column == snapshot.line_len(row) {
9014 if selection.is_empty() {
9015 selection.start.column -= suffix_len as u32;
9016 }
9017 selection.end.column -= suffix_len as u32;
9018 }
9019 break;
9020 }
9021 }
9022 }
9023 }
9024
9025 drop(snapshot);
9026 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9027
9028 let selections = this.selections.all::<Point>(cx);
9029 let selections_on_single_row = selections.windows(2).all(|selections| {
9030 selections[0].start.row == selections[1].start.row
9031 && selections[0].end.row == selections[1].end.row
9032 && selections[0].start.row == selections[0].end.row
9033 });
9034 let selections_selecting = selections
9035 .iter()
9036 .any(|selection| selection.start != selection.end);
9037 let advance_downwards = action.advance_downwards
9038 && selections_on_single_row
9039 && !selections_selecting
9040 && !matches!(this.mode, EditorMode::SingleLine { .. });
9041
9042 if advance_downwards {
9043 let snapshot = this.buffer.read(cx).snapshot(cx);
9044
9045 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9046 s.move_cursors_with(|display_snapshot, display_point, _| {
9047 let mut point = display_point.to_point(display_snapshot);
9048 point.row += 1;
9049 point = snapshot.clip_point(point, Bias::Left);
9050 let display_point = point.to_display_point(display_snapshot);
9051 let goal = SelectionGoal::HorizontalPosition(
9052 display_snapshot
9053 .x_for_display_point(display_point, text_layout_details)
9054 .into(),
9055 );
9056 (display_point, goal)
9057 })
9058 });
9059 }
9060 });
9061 }
9062
9063 pub fn select_enclosing_symbol(
9064 &mut self,
9065 _: &SelectEnclosingSymbol,
9066 cx: &mut ViewContext<Self>,
9067 ) {
9068 let buffer = self.buffer.read(cx).snapshot(cx);
9069 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9070
9071 fn update_selection(
9072 selection: &Selection<usize>,
9073 buffer_snap: &MultiBufferSnapshot,
9074 ) -> Option<Selection<usize>> {
9075 let cursor = selection.head();
9076 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9077 for symbol in symbols.iter().rev() {
9078 let start = symbol.range.start.to_offset(buffer_snap);
9079 let end = symbol.range.end.to_offset(buffer_snap);
9080 let new_range = start..end;
9081 if start < selection.start || end > selection.end {
9082 return Some(Selection {
9083 id: selection.id,
9084 start: new_range.start,
9085 end: new_range.end,
9086 goal: SelectionGoal::None,
9087 reversed: selection.reversed,
9088 });
9089 }
9090 }
9091 None
9092 }
9093
9094 let mut selected_larger_symbol = false;
9095 let new_selections = old_selections
9096 .iter()
9097 .map(|selection| match update_selection(selection, &buffer) {
9098 Some(new_selection) => {
9099 if new_selection.range() != selection.range() {
9100 selected_larger_symbol = true;
9101 }
9102 new_selection
9103 }
9104 None => selection.clone(),
9105 })
9106 .collect::<Vec<_>>();
9107
9108 if selected_larger_symbol {
9109 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9110 s.select(new_selections);
9111 });
9112 }
9113 }
9114
9115 pub fn select_larger_syntax_node(
9116 &mut self,
9117 _: &SelectLargerSyntaxNode,
9118 cx: &mut ViewContext<Self>,
9119 ) {
9120 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9121 let buffer = self.buffer.read(cx).snapshot(cx);
9122 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9123
9124 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9125 let mut selected_larger_node = false;
9126 let new_selections = old_selections
9127 .iter()
9128 .map(|selection| {
9129 let old_range = selection.start..selection.end;
9130 let mut new_range = old_range.clone();
9131 while let Some(containing_range) =
9132 buffer.range_for_syntax_ancestor(new_range.clone())
9133 {
9134 new_range = containing_range;
9135 if !display_map.intersects_fold(new_range.start)
9136 && !display_map.intersects_fold(new_range.end)
9137 {
9138 break;
9139 }
9140 }
9141
9142 selected_larger_node |= new_range != old_range;
9143 Selection {
9144 id: selection.id,
9145 start: new_range.start,
9146 end: new_range.end,
9147 goal: SelectionGoal::None,
9148 reversed: selection.reversed,
9149 }
9150 })
9151 .collect::<Vec<_>>();
9152
9153 if selected_larger_node {
9154 stack.push(old_selections);
9155 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9156 s.select(new_selections);
9157 });
9158 }
9159 self.select_larger_syntax_node_stack = stack;
9160 }
9161
9162 pub fn select_smaller_syntax_node(
9163 &mut self,
9164 _: &SelectSmallerSyntaxNode,
9165 cx: &mut ViewContext<Self>,
9166 ) {
9167 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9168 if let Some(selections) = stack.pop() {
9169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9170 s.select(selections.to_vec());
9171 });
9172 }
9173 self.select_larger_syntax_node_stack = stack;
9174 }
9175
9176 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9177 if !EditorSettings::get_global(cx).gutter.runnables {
9178 self.clear_tasks();
9179 return Task::ready(());
9180 }
9181 let project = self.project.clone();
9182 cx.spawn(|this, mut cx| async move {
9183 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9184 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9185 }) else {
9186 return;
9187 };
9188
9189 let Some(project) = project else {
9190 return;
9191 };
9192
9193 let hide_runnables = project
9194 .update(&mut cx, |project, cx| {
9195 // Do not display any test indicators in non-dev server remote projects.
9196 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9197 })
9198 .unwrap_or(true);
9199 if hide_runnables {
9200 return;
9201 }
9202 let new_rows =
9203 cx.background_executor()
9204 .spawn({
9205 let snapshot = display_snapshot.clone();
9206 async move {
9207 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9208 }
9209 })
9210 .await;
9211 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9212
9213 this.update(&mut cx, |this, _| {
9214 this.clear_tasks();
9215 for (key, value) in rows {
9216 this.insert_tasks(key, value);
9217 }
9218 })
9219 .ok();
9220 })
9221 }
9222 fn fetch_runnable_ranges(
9223 snapshot: &DisplaySnapshot,
9224 range: Range<Anchor>,
9225 ) -> Vec<language::RunnableRange> {
9226 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9227 }
9228
9229 fn runnable_rows(
9230 project: Model<Project>,
9231 snapshot: DisplaySnapshot,
9232 runnable_ranges: Vec<RunnableRange>,
9233 mut cx: AsyncWindowContext,
9234 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9235 runnable_ranges
9236 .into_iter()
9237 .filter_map(|mut runnable| {
9238 let tasks = cx
9239 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9240 .ok()?;
9241 if tasks.is_empty() {
9242 return None;
9243 }
9244
9245 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9246
9247 let row = snapshot
9248 .buffer_snapshot
9249 .buffer_line_for_row(MultiBufferRow(point.row))?
9250 .1
9251 .start
9252 .row;
9253
9254 let context_range =
9255 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9256 Some((
9257 (runnable.buffer_id, row),
9258 RunnableTasks {
9259 templates: tasks,
9260 offset: MultiBufferOffset(runnable.run_range.start),
9261 context_range,
9262 column: point.column,
9263 extra_variables: runnable.extra_captures,
9264 },
9265 ))
9266 })
9267 .collect()
9268 }
9269
9270 fn templates_with_tags(
9271 project: &Model<Project>,
9272 runnable: &mut Runnable,
9273 cx: &WindowContext<'_>,
9274 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9275 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9276 let (worktree_id, file) = project
9277 .buffer_for_id(runnable.buffer, cx)
9278 .and_then(|buffer| buffer.read(cx).file())
9279 .map(|file| (file.worktree_id(cx), file.clone()))
9280 .unzip();
9281
9282 (
9283 project.task_store().read(cx).task_inventory().cloned(),
9284 worktree_id,
9285 file,
9286 )
9287 });
9288
9289 let tags = mem::take(&mut runnable.tags);
9290 let mut tags: Vec<_> = tags
9291 .into_iter()
9292 .flat_map(|tag| {
9293 let tag = tag.0.clone();
9294 inventory
9295 .as_ref()
9296 .into_iter()
9297 .flat_map(|inventory| {
9298 inventory.read(cx).list_tasks(
9299 file.clone(),
9300 Some(runnable.language.clone()),
9301 worktree_id,
9302 cx,
9303 )
9304 })
9305 .filter(move |(_, template)| {
9306 template.tags.iter().any(|source_tag| source_tag == &tag)
9307 })
9308 })
9309 .sorted_by_key(|(kind, _)| kind.to_owned())
9310 .collect();
9311 if let Some((leading_tag_source, _)) = tags.first() {
9312 // Strongest source wins; if we have worktree tag binding, prefer that to
9313 // global and language bindings;
9314 // if we have a global binding, prefer that to language binding.
9315 let first_mismatch = tags
9316 .iter()
9317 .position(|(tag_source, _)| tag_source != leading_tag_source);
9318 if let Some(index) = first_mismatch {
9319 tags.truncate(index);
9320 }
9321 }
9322
9323 tags
9324 }
9325
9326 pub fn move_to_enclosing_bracket(
9327 &mut self,
9328 _: &MoveToEnclosingBracket,
9329 cx: &mut ViewContext<Self>,
9330 ) {
9331 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9332 s.move_offsets_with(|snapshot, selection| {
9333 let Some(enclosing_bracket_ranges) =
9334 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9335 else {
9336 return;
9337 };
9338
9339 let mut best_length = usize::MAX;
9340 let mut best_inside = false;
9341 let mut best_in_bracket_range = false;
9342 let mut best_destination = None;
9343 for (open, close) in enclosing_bracket_ranges {
9344 let close = close.to_inclusive();
9345 let length = close.end() - open.start;
9346 let inside = selection.start >= open.end && selection.end <= *close.start();
9347 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9348 || close.contains(&selection.head());
9349
9350 // If best is next to a bracket and current isn't, skip
9351 if !in_bracket_range && best_in_bracket_range {
9352 continue;
9353 }
9354
9355 // Prefer smaller lengths unless best is inside and current isn't
9356 if length > best_length && (best_inside || !inside) {
9357 continue;
9358 }
9359
9360 best_length = length;
9361 best_inside = inside;
9362 best_in_bracket_range = in_bracket_range;
9363 best_destination = Some(
9364 if close.contains(&selection.start) && close.contains(&selection.end) {
9365 if inside {
9366 open.end
9367 } else {
9368 open.start
9369 }
9370 } else if inside {
9371 *close.start()
9372 } else {
9373 *close.end()
9374 },
9375 );
9376 }
9377
9378 if let Some(destination) = best_destination {
9379 selection.collapse_to(destination, SelectionGoal::None);
9380 }
9381 })
9382 });
9383 }
9384
9385 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9386 self.end_selection(cx);
9387 self.selection_history.mode = SelectionHistoryMode::Undoing;
9388 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9389 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9390 self.select_next_state = entry.select_next_state;
9391 self.select_prev_state = entry.select_prev_state;
9392 self.add_selections_state = entry.add_selections_state;
9393 self.request_autoscroll(Autoscroll::newest(), cx);
9394 }
9395 self.selection_history.mode = SelectionHistoryMode::Normal;
9396 }
9397
9398 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9399 self.end_selection(cx);
9400 self.selection_history.mode = SelectionHistoryMode::Redoing;
9401 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9402 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9403 self.select_next_state = entry.select_next_state;
9404 self.select_prev_state = entry.select_prev_state;
9405 self.add_selections_state = entry.add_selections_state;
9406 self.request_autoscroll(Autoscroll::newest(), cx);
9407 }
9408 self.selection_history.mode = SelectionHistoryMode::Normal;
9409 }
9410
9411 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9412 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9413 }
9414
9415 pub fn expand_excerpts_down(
9416 &mut self,
9417 action: &ExpandExcerptsDown,
9418 cx: &mut ViewContext<Self>,
9419 ) {
9420 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9421 }
9422
9423 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9424 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9425 }
9426
9427 pub fn expand_excerpts_for_direction(
9428 &mut self,
9429 lines: u32,
9430 direction: ExpandExcerptDirection,
9431 cx: &mut ViewContext<Self>,
9432 ) {
9433 let selections = self.selections.disjoint_anchors();
9434
9435 let lines = if lines == 0 {
9436 EditorSettings::get_global(cx).expand_excerpt_lines
9437 } else {
9438 lines
9439 };
9440
9441 self.buffer.update(cx, |buffer, cx| {
9442 buffer.expand_excerpts(
9443 selections
9444 .iter()
9445 .map(|selection| selection.head().excerpt_id)
9446 .dedup(),
9447 lines,
9448 direction,
9449 cx,
9450 )
9451 })
9452 }
9453
9454 pub fn expand_excerpt(
9455 &mut self,
9456 excerpt: ExcerptId,
9457 direction: ExpandExcerptDirection,
9458 cx: &mut ViewContext<Self>,
9459 ) {
9460 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9461 self.buffer.update(cx, |buffer, cx| {
9462 buffer.expand_excerpts([excerpt], lines, direction, cx)
9463 })
9464 }
9465
9466 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9467 self.go_to_diagnostic_impl(Direction::Next, cx)
9468 }
9469
9470 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9471 self.go_to_diagnostic_impl(Direction::Prev, cx)
9472 }
9473
9474 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9475 let buffer = self.buffer.read(cx).snapshot(cx);
9476 let selection = self.selections.newest::<usize>(cx);
9477
9478 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9479 if direction == Direction::Next {
9480 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9481 let (group_id, jump_to) = popover.activation_info();
9482 if self.activate_diagnostics(group_id, cx) {
9483 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9484 let mut new_selection = s.newest_anchor().clone();
9485 new_selection.collapse_to(jump_to, SelectionGoal::None);
9486 s.select_anchors(vec![new_selection.clone()]);
9487 });
9488 }
9489 return;
9490 }
9491 }
9492
9493 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9494 active_diagnostics
9495 .primary_range
9496 .to_offset(&buffer)
9497 .to_inclusive()
9498 });
9499 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9500 if active_primary_range.contains(&selection.head()) {
9501 *active_primary_range.start()
9502 } else {
9503 selection.head()
9504 }
9505 } else {
9506 selection.head()
9507 };
9508 let snapshot = self.snapshot(cx);
9509 loop {
9510 let diagnostics = if direction == Direction::Prev {
9511 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9512 } else {
9513 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9514 }
9515 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9516 let group = diagnostics
9517 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9518 // be sorted in a stable way
9519 // skip until we are at current active diagnostic, if it exists
9520 .skip_while(|entry| {
9521 (match direction {
9522 Direction::Prev => entry.range.start >= search_start,
9523 Direction::Next => entry.range.start <= search_start,
9524 }) && self
9525 .active_diagnostics
9526 .as_ref()
9527 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9528 })
9529 .find_map(|entry| {
9530 if entry.diagnostic.is_primary
9531 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9532 && !entry.range.is_empty()
9533 // if we match with the active diagnostic, skip it
9534 && Some(entry.diagnostic.group_id)
9535 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9536 {
9537 Some((entry.range, entry.diagnostic.group_id))
9538 } else {
9539 None
9540 }
9541 });
9542
9543 if let Some((primary_range, group_id)) = group {
9544 if self.activate_diagnostics(group_id, cx) {
9545 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9546 s.select(vec![Selection {
9547 id: selection.id,
9548 start: primary_range.start,
9549 end: primary_range.start,
9550 reversed: false,
9551 goal: SelectionGoal::None,
9552 }]);
9553 });
9554 }
9555 break;
9556 } else {
9557 // Cycle around to the start of the buffer, potentially moving back to the start of
9558 // the currently active diagnostic.
9559 active_primary_range.take();
9560 if direction == Direction::Prev {
9561 if search_start == buffer.len() {
9562 break;
9563 } else {
9564 search_start = buffer.len();
9565 }
9566 } else if search_start == 0 {
9567 break;
9568 } else {
9569 search_start = 0;
9570 }
9571 }
9572 }
9573 }
9574
9575 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9576 let snapshot = self
9577 .display_map
9578 .update(cx, |display_map, cx| display_map.snapshot(cx));
9579 let selection = self.selections.newest::<Point>(cx);
9580 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9581 }
9582
9583 fn go_to_hunk_after_position(
9584 &mut self,
9585 snapshot: &DisplaySnapshot,
9586 position: Point,
9587 cx: &mut ViewContext<'_, Editor>,
9588 ) -> Option<MultiBufferDiffHunk> {
9589 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9590 snapshot,
9591 position,
9592 false,
9593 snapshot
9594 .buffer_snapshot
9595 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9596 cx,
9597 ) {
9598 return Some(hunk);
9599 }
9600
9601 let wrapped_point = Point::zero();
9602 self.go_to_next_hunk_in_direction(
9603 snapshot,
9604 wrapped_point,
9605 true,
9606 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9607 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9608 ),
9609 cx,
9610 )
9611 }
9612
9613 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9614 let snapshot = self
9615 .display_map
9616 .update(cx, |display_map, cx| display_map.snapshot(cx));
9617 let selection = self.selections.newest::<Point>(cx);
9618
9619 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9620 }
9621
9622 fn go_to_hunk_before_position(
9623 &mut self,
9624 snapshot: &DisplaySnapshot,
9625 position: Point,
9626 cx: &mut ViewContext<'_, Editor>,
9627 ) -> Option<MultiBufferDiffHunk> {
9628 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9629 snapshot,
9630 position,
9631 false,
9632 snapshot
9633 .buffer_snapshot
9634 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9635 cx,
9636 ) {
9637 return Some(hunk);
9638 }
9639
9640 let wrapped_point = snapshot.buffer_snapshot.max_point();
9641 self.go_to_next_hunk_in_direction(
9642 snapshot,
9643 wrapped_point,
9644 true,
9645 snapshot
9646 .buffer_snapshot
9647 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9648 cx,
9649 )
9650 }
9651
9652 fn go_to_next_hunk_in_direction(
9653 &mut self,
9654 snapshot: &DisplaySnapshot,
9655 initial_point: Point,
9656 is_wrapped: bool,
9657 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9658 cx: &mut ViewContext<Editor>,
9659 ) -> Option<MultiBufferDiffHunk> {
9660 let display_point = initial_point.to_display_point(snapshot);
9661 let mut hunks = hunks
9662 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9663 .filter(|(display_hunk, _)| {
9664 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9665 })
9666 .dedup();
9667
9668 if let Some((display_hunk, hunk)) = hunks.next() {
9669 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9670 let row = display_hunk.start_display_row();
9671 let point = DisplayPoint::new(row, 0);
9672 s.select_display_ranges([point..point]);
9673 });
9674
9675 Some(hunk)
9676 } else {
9677 None
9678 }
9679 }
9680
9681 pub fn go_to_definition(
9682 &mut self,
9683 _: &GoToDefinition,
9684 cx: &mut ViewContext<Self>,
9685 ) -> Task<Result<Navigated>> {
9686 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9687 cx.spawn(|editor, mut cx| async move {
9688 if definition.await? == Navigated::Yes {
9689 return Ok(Navigated::Yes);
9690 }
9691 match editor.update(&mut cx, |editor, cx| {
9692 editor.find_all_references(&FindAllReferences, cx)
9693 })? {
9694 Some(references) => references.await,
9695 None => Ok(Navigated::No),
9696 }
9697 })
9698 }
9699
9700 pub fn go_to_declaration(
9701 &mut self,
9702 _: &GoToDeclaration,
9703 cx: &mut ViewContext<Self>,
9704 ) -> Task<Result<Navigated>> {
9705 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9706 }
9707
9708 pub fn go_to_declaration_split(
9709 &mut self,
9710 _: &GoToDeclaration,
9711 cx: &mut ViewContext<Self>,
9712 ) -> Task<Result<Navigated>> {
9713 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9714 }
9715
9716 pub fn go_to_implementation(
9717 &mut self,
9718 _: &GoToImplementation,
9719 cx: &mut ViewContext<Self>,
9720 ) -> Task<Result<Navigated>> {
9721 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9722 }
9723
9724 pub fn go_to_implementation_split(
9725 &mut self,
9726 _: &GoToImplementationSplit,
9727 cx: &mut ViewContext<Self>,
9728 ) -> Task<Result<Navigated>> {
9729 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9730 }
9731
9732 pub fn go_to_type_definition(
9733 &mut self,
9734 _: &GoToTypeDefinition,
9735 cx: &mut ViewContext<Self>,
9736 ) -> Task<Result<Navigated>> {
9737 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9738 }
9739
9740 pub fn go_to_definition_split(
9741 &mut self,
9742 _: &GoToDefinitionSplit,
9743 cx: &mut ViewContext<Self>,
9744 ) -> Task<Result<Navigated>> {
9745 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9746 }
9747
9748 pub fn go_to_type_definition_split(
9749 &mut self,
9750 _: &GoToTypeDefinitionSplit,
9751 cx: &mut ViewContext<Self>,
9752 ) -> Task<Result<Navigated>> {
9753 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9754 }
9755
9756 fn go_to_definition_of_kind(
9757 &mut self,
9758 kind: GotoDefinitionKind,
9759 split: bool,
9760 cx: &mut ViewContext<Self>,
9761 ) -> Task<Result<Navigated>> {
9762 let Some(provider) = self.semantics_provider.clone() else {
9763 return Task::ready(Ok(Navigated::No));
9764 };
9765 let head = self.selections.newest::<usize>(cx).head();
9766 let buffer = self.buffer.read(cx);
9767 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9768 text_anchor
9769 } else {
9770 return Task::ready(Ok(Navigated::No));
9771 };
9772
9773 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9774 return Task::ready(Ok(Navigated::No));
9775 };
9776
9777 cx.spawn(|editor, mut cx| async move {
9778 let definitions = definitions.await?;
9779 let navigated = editor
9780 .update(&mut cx, |editor, cx| {
9781 editor.navigate_to_hover_links(
9782 Some(kind),
9783 definitions
9784 .into_iter()
9785 .filter(|location| {
9786 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9787 })
9788 .map(HoverLink::Text)
9789 .collect::<Vec<_>>(),
9790 split,
9791 cx,
9792 )
9793 })?
9794 .await?;
9795 anyhow::Ok(navigated)
9796 })
9797 }
9798
9799 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9800 let position = self.selections.newest_anchor().head();
9801 let Some((buffer, buffer_position)) =
9802 self.buffer.read(cx).text_anchor_for_position(position, cx)
9803 else {
9804 return;
9805 };
9806
9807 cx.spawn(|editor, mut cx| async move {
9808 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9809 editor.update(&mut cx, |_, cx| {
9810 cx.open_url(&url);
9811 })
9812 } else {
9813 Ok(())
9814 }
9815 })
9816 .detach();
9817 }
9818
9819 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9820 let Some(workspace) = self.workspace() else {
9821 return;
9822 };
9823
9824 let position = self.selections.newest_anchor().head();
9825
9826 let Some((buffer, buffer_position)) =
9827 self.buffer.read(cx).text_anchor_for_position(position, cx)
9828 else {
9829 return;
9830 };
9831
9832 let project = self.project.clone();
9833
9834 cx.spawn(|_, mut cx| async move {
9835 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9836
9837 if let Some((_, path)) = result {
9838 workspace
9839 .update(&mut cx, |workspace, cx| {
9840 workspace.open_resolved_path(path, cx)
9841 })?
9842 .await?;
9843 }
9844 anyhow::Ok(())
9845 })
9846 .detach();
9847 }
9848
9849 pub(crate) fn navigate_to_hover_links(
9850 &mut self,
9851 kind: Option<GotoDefinitionKind>,
9852 mut definitions: Vec<HoverLink>,
9853 split: bool,
9854 cx: &mut ViewContext<Editor>,
9855 ) -> Task<Result<Navigated>> {
9856 // If there is one definition, just open it directly
9857 if definitions.len() == 1 {
9858 let definition = definitions.pop().unwrap();
9859
9860 enum TargetTaskResult {
9861 Location(Option<Location>),
9862 AlreadyNavigated,
9863 }
9864
9865 let target_task = match definition {
9866 HoverLink::Text(link) => {
9867 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9868 }
9869 HoverLink::InlayHint(lsp_location, server_id) => {
9870 let computation = self.compute_target_location(lsp_location, server_id, cx);
9871 cx.background_executor().spawn(async move {
9872 let location = computation.await?;
9873 Ok(TargetTaskResult::Location(location))
9874 })
9875 }
9876 HoverLink::Url(url) => {
9877 cx.open_url(&url);
9878 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9879 }
9880 HoverLink::File(path) => {
9881 if let Some(workspace) = self.workspace() {
9882 cx.spawn(|_, mut cx| async move {
9883 workspace
9884 .update(&mut cx, |workspace, cx| {
9885 workspace.open_resolved_path(path, cx)
9886 })?
9887 .await
9888 .map(|_| TargetTaskResult::AlreadyNavigated)
9889 })
9890 } else {
9891 Task::ready(Ok(TargetTaskResult::Location(None)))
9892 }
9893 }
9894 };
9895 cx.spawn(|editor, mut cx| async move {
9896 let target = match target_task.await.context("target resolution task")? {
9897 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9898 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9899 TargetTaskResult::Location(Some(target)) => target,
9900 };
9901
9902 editor.update(&mut cx, |editor, cx| {
9903 let Some(workspace) = editor.workspace() else {
9904 return Navigated::No;
9905 };
9906 let pane = workspace.read(cx).active_pane().clone();
9907
9908 let range = target.range.to_offset(target.buffer.read(cx));
9909 let range = editor.range_for_match(&range);
9910
9911 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9912 let buffer = target.buffer.read(cx);
9913 let range = check_multiline_range(buffer, range);
9914 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9915 s.select_ranges([range]);
9916 });
9917 } else {
9918 cx.window_context().defer(move |cx| {
9919 let target_editor: View<Self> =
9920 workspace.update(cx, |workspace, cx| {
9921 let pane = if split {
9922 workspace.adjacent_pane(cx)
9923 } else {
9924 workspace.active_pane().clone()
9925 };
9926
9927 workspace.open_project_item(
9928 pane,
9929 target.buffer.clone(),
9930 true,
9931 true,
9932 cx,
9933 )
9934 });
9935 target_editor.update(cx, |target_editor, cx| {
9936 // When selecting a definition in a different buffer, disable the nav history
9937 // to avoid creating a history entry at the previous cursor location.
9938 pane.update(cx, |pane, _| pane.disable_history());
9939 let buffer = target.buffer.read(cx);
9940 let range = check_multiline_range(buffer, range);
9941 target_editor.change_selections(
9942 Some(Autoscroll::focused()),
9943 cx,
9944 |s| {
9945 s.select_ranges([range]);
9946 },
9947 );
9948 pane.update(cx, |pane, _| pane.enable_history());
9949 });
9950 });
9951 }
9952 Navigated::Yes
9953 })
9954 })
9955 } else if !definitions.is_empty() {
9956 cx.spawn(|editor, mut cx| async move {
9957 let (title, location_tasks, workspace) = editor
9958 .update(&mut cx, |editor, cx| {
9959 let tab_kind = match kind {
9960 Some(GotoDefinitionKind::Implementation) => "Implementations",
9961 _ => "Definitions",
9962 };
9963 let title = definitions
9964 .iter()
9965 .find_map(|definition| match definition {
9966 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9967 let buffer = origin.buffer.read(cx);
9968 format!(
9969 "{} for {}",
9970 tab_kind,
9971 buffer
9972 .text_for_range(origin.range.clone())
9973 .collect::<String>()
9974 )
9975 }),
9976 HoverLink::InlayHint(_, _) => None,
9977 HoverLink::Url(_) => None,
9978 HoverLink::File(_) => None,
9979 })
9980 .unwrap_or(tab_kind.to_string());
9981 let location_tasks = definitions
9982 .into_iter()
9983 .map(|definition| match definition {
9984 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9985 HoverLink::InlayHint(lsp_location, server_id) => {
9986 editor.compute_target_location(lsp_location, server_id, cx)
9987 }
9988 HoverLink::Url(_) => Task::ready(Ok(None)),
9989 HoverLink::File(_) => Task::ready(Ok(None)),
9990 })
9991 .collect::<Vec<_>>();
9992 (title, location_tasks, editor.workspace().clone())
9993 })
9994 .context("location tasks preparation")?;
9995
9996 let locations = future::join_all(location_tasks)
9997 .await
9998 .into_iter()
9999 .filter_map(|location| location.transpose())
10000 .collect::<Result<_>>()
10001 .context("location tasks")?;
10002
10003 let Some(workspace) = workspace else {
10004 return Ok(Navigated::No);
10005 };
10006 let opened = workspace
10007 .update(&mut cx, |workspace, cx| {
10008 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10009 })
10010 .ok();
10011
10012 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10013 })
10014 } else {
10015 Task::ready(Ok(Navigated::No))
10016 }
10017 }
10018
10019 fn compute_target_location(
10020 &self,
10021 lsp_location: lsp::Location,
10022 server_id: LanguageServerId,
10023 cx: &mut ViewContext<Self>,
10024 ) -> Task<anyhow::Result<Option<Location>>> {
10025 let Some(project) = self.project.clone() else {
10026 return Task::Ready(Some(Ok(None)));
10027 };
10028
10029 cx.spawn(move |editor, mut cx| async move {
10030 let location_task = editor.update(&mut cx, |_, cx| {
10031 project.update(cx, |project, cx| {
10032 let language_server_name = project
10033 .language_server_statuses(cx)
10034 .find(|(id, _)| server_id == *id)
10035 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10036 language_server_name.map(|language_server_name| {
10037 project.open_local_buffer_via_lsp(
10038 lsp_location.uri.clone(),
10039 server_id,
10040 language_server_name,
10041 cx,
10042 )
10043 })
10044 })
10045 })?;
10046 let location = match location_task {
10047 Some(task) => Some({
10048 let target_buffer_handle = task.await.context("open local buffer")?;
10049 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10050 let target_start = target_buffer
10051 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10052 let target_end = target_buffer
10053 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10054 target_buffer.anchor_after(target_start)
10055 ..target_buffer.anchor_before(target_end)
10056 })?;
10057 Location {
10058 buffer: target_buffer_handle,
10059 range,
10060 }
10061 }),
10062 None => None,
10063 };
10064 Ok(location)
10065 })
10066 }
10067
10068 pub fn find_all_references(
10069 &mut self,
10070 _: &FindAllReferences,
10071 cx: &mut ViewContext<Self>,
10072 ) -> Option<Task<Result<Navigated>>> {
10073 let selection = self.selections.newest::<usize>(cx);
10074 let multi_buffer = self.buffer.read(cx);
10075 let head = selection.head();
10076
10077 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10078 let head_anchor = multi_buffer_snapshot.anchor_at(
10079 head,
10080 if head < selection.tail() {
10081 Bias::Right
10082 } else {
10083 Bias::Left
10084 },
10085 );
10086
10087 match self
10088 .find_all_references_task_sources
10089 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10090 {
10091 Ok(_) => {
10092 log::info!(
10093 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10094 );
10095 return None;
10096 }
10097 Err(i) => {
10098 self.find_all_references_task_sources.insert(i, head_anchor);
10099 }
10100 }
10101
10102 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10103 let workspace = self.workspace()?;
10104 let project = workspace.read(cx).project().clone();
10105 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10106 Some(cx.spawn(|editor, mut cx| async move {
10107 let _cleanup = defer({
10108 let mut cx = cx.clone();
10109 move || {
10110 let _ = editor.update(&mut cx, |editor, _| {
10111 if let Ok(i) =
10112 editor
10113 .find_all_references_task_sources
10114 .binary_search_by(|anchor| {
10115 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10116 })
10117 {
10118 editor.find_all_references_task_sources.remove(i);
10119 }
10120 });
10121 }
10122 });
10123
10124 let locations = references.await?;
10125 if locations.is_empty() {
10126 return anyhow::Ok(Navigated::No);
10127 }
10128
10129 workspace.update(&mut cx, |workspace, cx| {
10130 let title = locations
10131 .first()
10132 .as_ref()
10133 .map(|location| {
10134 let buffer = location.buffer.read(cx);
10135 format!(
10136 "References to `{}`",
10137 buffer
10138 .text_for_range(location.range.clone())
10139 .collect::<String>()
10140 )
10141 })
10142 .unwrap();
10143 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10144 Navigated::Yes
10145 })
10146 }))
10147 }
10148
10149 /// Opens a multibuffer with the given project locations in it
10150 pub fn open_locations_in_multibuffer(
10151 workspace: &mut Workspace,
10152 mut locations: Vec<Location>,
10153 title: String,
10154 split: bool,
10155 cx: &mut ViewContext<Workspace>,
10156 ) {
10157 // If there are multiple definitions, open them in a multibuffer
10158 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10159 let mut locations = locations.into_iter().peekable();
10160 let mut ranges_to_highlight = Vec::new();
10161 let capability = workspace.project().read(cx).capability();
10162
10163 let excerpt_buffer = cx.new_model(|cx| {
10164 let mut multibuffer = MultiBuffer::new(capability);
10165 while let Some(location) = locations.next() {
10166 let buffer = location.buffer.read(cx);
10167 let mut ranges_for_buffer = Vec::new();
10168 let range = location.range.to_offset(buffer);
10169 ranges_for_buffer.push(range.clone());
10170
10171 while let Some(next_location) = locations.peek() {
10172 if next_location.buffer == location.buffer {
10173 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10174 locations.next();
10175 } else {
10176 break;
10177 }
10178 }
10179
10180 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10181 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10182 location.buffer.clone(),
10183 ranges_for_buffer,
10184 DEFAULT_MULTIBUFFER_CONTEXT,
10185 cx,
10186 ))
10187 }
10188
10189 multibuffer.with_title(title)
10190 });
10191
10192 let editor = cx.new_view(|cx| {
10193 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10194 });
10195 editor.update(cx, |editor, cx| {
10196 if let Some(first_range) = ranges_to_highlight.first() {
10197 editor.change_selections(None, cx, |selections| {
10198 selections.clear_disjoint();
10199 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10200 });
10201 }
10202 editor.highlight_background::<Self>(
10203 &ranges_to_highlight,
10204 |theme| theme.editor_highlighted_line_background,
10205 cx,
10206 );
10207 });
10208
10209 let item = Box::new(editor);
10210 let item_id = item.item_id();
10211
10212 if split {
10213 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10214 } else {
10215 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10216 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10217 pane.close_current_preview_item(cx)
10218 } else {
10219 None
10220 }
10221 });
10222 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10223 }
10224 workspace.active_pane().update(cx, |pane, cx| {
10225 pane.set_preview_item_id(Some(item_id), cx);
10226 });
10227 }
10228
10229 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10230 use language::ToOffset as _;
10231
10232 let provider = self.semantics_provider.clone()?;
10233 let selection = self.selections.newest_anchor().clone();
10234 let (cursor_buffer, cursor_buffer_position) = self
10235 .buffer
10236 .read(cx)
10237 .text_anchor_for_position(selection.head(), cx)?;
10238 let (tail_buffer, cursor_buffer_position_end) = self
10239 .buffer
10240 .read(cx)
10241 .text_anchor_for_position(selection.tail(), cx)?;
10242 if tail_buffer != cursor_buffer {
10243 return None;
10244 }
10245
10246 let snapshot = cursor_buffer.read(cx).snapshot();
10247 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10248 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10249 let prepare_rename = provider
10250 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10251 .unwrap_or_else(|| Task::ready(Ok(None)));
10252 drop(snapshot);
10253
10254 Some(cx.spawn(|this, mut cx| async move {
10255 let rename_range = if let Some(range) = prepare_rename.await? {
10256 Some(range)
10257 } else {
10258 this.update(&mut cx, |this, cx| {
10259 let buffer = this.buffer.read(cx).snapshot(cx);
10260 let mut buffer_highlights = this
10261 .document_highlights_for_position(selection.head(), &buffer)
10262 .filter(|highlight| {
10263 highlight.start.excerpt_id == selection.head().excerpt_id
10264 && highlight.end.excerpt_id == selection.head().excerpt_id
10265 });
10266 buffer_highlights
10267 .next()
10268 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10269 })?
10270 };
10271 if let Some(rename_range) = rename_range {
10272 this.update(&mut cx, |this, cx| {
10273 let snapshot = cursor_buffer.read(cx).snapshot();
10274 let rename_buffer_range = rename_range.to_offset(&snapshot);
10275 let cursor_offset_in_rename_range =
10276 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10277 let cursor_offset_in_rename_range_end =
10278 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10279
10280 this.take_rename(false, cx);
10281 let buffer = this.buffer.read(cx).read(cx);
10282 let cursor_offset = selection.head().to_offset(&buffer);
10283 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10284 let rename_end = rename_start + rename_buffer_range.len();
10285 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10286 let mut old_highlight_id = None;
10287 let old_name: Arc<str> = buffer
10288 .chunks(rename_start..rename_end, true)
10289 .map(|chunk| {
10290 if old_highlight_id.is_none() {
10291 old_highlight_id = chunk.syntax_highlight_id;
10292 }
10293 chunk.text
10294 })
10295 .collect::<String>()
10296 .into();
10297
10298 drop(buffer);
10299
10300 // Position the selection in the rename editor so that it matches the current selection.
10301 this.show_local_selections = false;
10302 let rename_editor = cx.new_view(|cx| {
10303 let mut editor = Editor::single_line(cx);
10304 editor.buffer.update(cx, |buffer, cx| {
10305 buffer.edit([(0..0, old_name.clone())], None, cx)
10306 });
10307 let rename_selection_range = match cursor_offset_in_rename_range
10308 .cmp(&cursor_offset_in_rename_range_end)
10309 {
10310 Ordering::Equal => {
10311 editor.select_all(&SelectAll, cx);
10312 return editor;
10313 }
10314 Ordering::Less => {
10315 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10316 }
10317 Ordering::Greater => {
10318 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10319 }
10320 };
10321 if rename_selection_range.end > old_name.len() {
10322 editor.select_all(&SelectAll, cx);
10323 } else {
10324 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10325 s.select_ranges([rename_selection_range]);
10326 });
10327 }
10328 editor
10329 });
10330 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10331 if e == &EditorEvent::Focused {
10332 cx.emit(EditorEvent::FocusedIn)
10333 }
10334 })
10335 .detach();
10336
10337 let write_highlights =
10338 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10339 let read_highlights =
10340 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10341 let ranges = write_highlights
10342 .iter()
10343 .flat_map(|(_, ranges)| ranges.iter())
10344 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10345 .cloned()
10346 .collect();
10347
10348 this.highlight_text::<Rename>(
10349 ranges,
10350 HighlightStyle {
10351 fade_out: Some(0.6),
10352 ..Default::default()
10353 },
10354 cx,
10355 );
10356 let rename_focus_handle = rename_editor.focus_handle(cx);
10357 cx.focus(&rename_focus_handle);
10358 let block_id = this.insert_blocks(
10359 [BlockProperties {
10360 style: BlockStyle::Flex,
10361 placement: BlockPlacement::Below(range.start),
10362 height: 1,
10363 render: Box::new({
10364 let rename_editor = rename_editor.clone();
10365 move |cx: &mut BlockContext| {
10366 let mut text_style = cx.editor_style.text.clone();
10367 if let Some(highlight_style) = old_highlight_id
10368 .and_then(|h| h.style(&cx.editor_style.syntax))
10369 {
10370 text_style = text_style.highlight(highlight_style);
10371 }
10372 div()
10373 .pl(cx.anchor_x)
10374 .child(EditorElement::new(
10375 &rename_editor,
10376 EditorStyle {
10377 background: cx.theme().system().transparent,
10378 local_player: cx.editor_style.local_player,
10379 text: text_style,
10380 scrollbar_width: cx.editor_style.scrollbar_width,
10381 syntax: cx.editor_style.syntax.clone(),
10382 status: cx.editor_style.status.clone(),
10383 inlay_hints_style: HighlightStyle {
10384 font_weight: Some(FontWeight::BOLD),
10385 ..make_inlay_hints_style(cx)
10386 },
10387 suggestions_style: HighlightStyle {
10388 color: Some(cx.theme().status().predictive),
10389 ..HighlightStyle::default()
10390 },
10391 ..EditorStyle::default()
10392 },
10393 ))
10394 .into_any_element()
10395 }
10396 }),
10397 priority: 0,
10398 }],
10399 Some(Autoscroll::fit()),
10400 cx,
10401 )[0];
10402 this.pending_rename = Some(RenameState {
10403 range,
10404 old_name,
10405 editor: rename_editor,
10406 block_id,
10407 });
10408 })?;
10409 }
10410
10411 Ok(())
10412 }))
10413 }
10414
10415 pub fn confirm_rename(
10416 &mut self,
10417 _: &ConfirmRename,
10418 cx: &mut ViewContext<Self>,
10419 ) -> Option<Task<Result<()>>> {
10420 let rename = self.take_rename(false, cx)?;
10421 let workspace = self.workspace()?.downgrade();
10422 let (buffer, start) = self
10423 .buffer
10424 .read(cx)
10425 .text_anchor_for_position(rename.range.start, cx)?;
10426 let (end_buffer, _) = self
10427 .buffer
10428 .read(cx)
10429 .text_anchor_for_position(rename.range.end, cx)?;
10430 if buffer != end_buffer {
10431 return None;
10432 }
10433
10434 let old_name = rename.old_name;
10435 let new_name = rename.editor.read(cx).text(cx);
10436
10437 let rename = self.semantics_provider.as_ref()?.perform_rename(
10438 &buffer,
10439 start,
10440 new_name.clone(),
10441 cx,
10442 )?;
10443
10444 Some(cx.spawn(|editor, mut cx| async move {
10445 let project_transaction = rename.await?;
10446 Self::open_project_transaction(
10447 &editor,
10448 workspace,
10449 project_transaction,
10450 format!("Rename: {} → {}", old_name, new_name),
10451 cx.clone(),
10452 )
10453 .await?;
10454
10455 editor.update(&mut cx, |editor, cx| {
10456 editor.refresh_document_highlights(cx);
10457 })?;
10458 Ok(())
10459 }))
10460 }
10461
10462 fn take_rename(
10463 &mut self,
10464 moving_cursor: bool,
10465 cx: &mut ViewContext<Self>,
10466 ) -> Option<RenameState> {
10467 let rename = self.pending_rename.take()?;
10468 if rename.editor.focus_handle(cx).is_focused(cx) {
10469 cx.focus(&self.focus_handle);
10470 }
10471
10472 self.remove_blocks(
10473 [rename.block_id].into_iter().collect(),
10474 Some(Autoscroll::fit()),
10475 cx,
10476 );
10477 self.clear_highlights::<Rename>(cx);
10478 self.show_local_selections = true;
10479
10480 if moving_cursor {
10481 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10482 editor.selections.newest::<usize>(cx).head()
10483 });
10484
10485 // Update the selection to match the position of the selection inside
10486 // the rename editor.
10487 let snapshot = self.buffer.read(cx).read(cx);
10488 let rename_range = rename.range.to_offset(&snapshot);
10489 let cursor_in_editor = snapshot
10490 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10491 .min(rename_range.end);
10492 drop(snapshot);
10493
10494 self.change_selections(None, cx, |s| {
10495 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10496 });
10497 } else {
10498 self.refresh_document_highlights(cx);
10499 }
10500
10501 Some(rename)
10502 }
10503
10504 pub fn pending_rename(&self) -> Option<&RenameState> {
10505 self.pending_rename.as_ref()
10506 }
10507
10508 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10509 let project = match &self.project {
10510 Some(project) => project.clone(),
10511 None => return None,
10512 };
10513
10514 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10515 }
10516
10517 fn format_selections(
10518 &mut self,
10519 _: &FormatSelections,
10520 cx: &mut ViewContext<Self>,
10521 ) -> Option<Task<Result<()>>> {
10522 let project = match &self.project {
10523 Some(project) => project.clone(),
10524 None => return None,
10525 };
10526
10527 let selections = self
10528 .selections
10529 .all_adjusted(cx)
10530 .into_iter()
10531 .filter(|s| !s.is_empty())
10532 .collect_vec();
10533
10534 Some(self.perform_format(
10535 project,
10536 FormatTrigger::Manual,
10537 FormatTarget::Ranges(selections),
10538 cx,
10539 ))
10540 }
10541
10542 fn perform_format(
10543 &mut self,
10544 project: Model<Project>,
10545 trigger: FormatTrigger,
10546 target: FormatTarget,
10547 cx: &mut ViewContext<Self>,
10548 ) -> Task<Result<()>> {
10549 let buffer = self.buffer().clone();
10550 let mut buffers = buffer.read(cx).all_buffers();
10551 if trigger == FormatTrigger::Save {
10552 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10553 }
10554
10555 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10556 let format = project.update(cx, |project, cx| {
10557 project.format(buffers, true, trigger, target, cx)
10558 });
10559
10560 cx.spawn(|_, mut cx| async move {
10561 let transaction = futures::select_biased! {
10562 () = timeout => {
10563 log::warn!("timed out waiting for formatting");
10564 None
10565 }
10566 transaction = format.log_err().fuse() => transaction,
10567 };
10568
10569 buffer
10570 .update(&mut cx, |buffer, cx| {
10571 if let Some(transaction) = transaction {
10572 if !buffer.is_singleton() {
10573 buffer.push_transaction(&transaction.0, cx);
10574 }
10575 }
10576
10577 cx.notify();
10578 })
10579 .ok();
10580
10581 Ok(())
10582 })
10583 }
10584
10585 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10586 if let Some(project) = self.project.clone() {
10587 self.buffer.update(cx, |multi_buffer, cx| {
10588 project.update(cx, |project, cx| {
10589 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10590 });
10591 })
10592 }
10593 }
10594
10595 fn cancel_language_server_work(
10596 &mut self,
10597 _: &actions::CancelLanguageServerWork,
10598 cx: &mut ViewContext<Self>,
10599 ) {
10600 if let Some(project) = self.project.clone() {
10601 self.buffer.update(cx, |multi_buffer, cx| {
10602 project.update(cx, |project, cx| {
10603 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10604 });
10605 })
10606 }
10607 }
10608
10609 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10610 cx.show_character_palette();
10611 }
10612
10613 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10614 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10615 let buffer = self.buffer.read(cx).snapshot(cx);
10616 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10617 let is_valid = buffer
10618 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10619 .any(|entry| {
10620 entry.diagnostic.is_primary
10621 && !entry.range.is_empty()
10622 && entry.range.start == primary_range_start
10623 && entry.diagnostic.message == active_diagnostics.primary_message
10624 });
10625
10626 if is_valid != active_diagnostics.is_valid {
10627 active_diagnostics.is_valid = is_valid;
10628 let mut new_styles = HashMap::default();
10629 for (block_id, diagnostic) in &active_diagnostics.blocks {
10630 new_styles.insert(
10631 *block_id,
10632 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10633 );
10634 }
10635 self.display_map.update(cx, |display_map, _cx| {
10636 display_map.replace_blocks(new_styles)
10637 });
10638 }
10639 }
10640 }
10641
10642 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10643 self.dismiss_diagnostics(cx);
10644 let snapshot = self.snapshot(cx);
10645 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10646 let buffer = self.buffer.read(cx).snapshot(cx);
10647
10648 let mut primary_range = None;
10649 let mut primary_message = None;
10650 let mut group_end = Point::zero();
10651 let diagnostic_group = buffer
10652 .diagnostic_group::<MultiBufferPoint>(group_id)
10653 .filter_map(|entry| {
10654 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10655 && (entry.range.start.row == entry.range.end.row
10656 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10657 {
10658 return None;
10659 }
10660 if entry.range.end > group_end {
10661 group_end = entry.range.end;
10662 }
10663 if entry.diagnostic.is_primary {
10664 primary_range = Some(entry.range.clone());
10665 primary_message = Some(entry.diagnostic.message.clone());
10666 }
10667 Some(entry)
10668 })
10669 .collect::<Vec<_>>();
10670 let primary_range = primary_range?;
10671 let primary_message = primary_message?;
10672 let primary_range =
10673 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10674
10675 let blocks = display_map
10676 .insert_blocks(
10677 diagnostic_group.iter().map(|entry| {
10678 let diagnostic = entry.diagnostic.clone();
10679 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10680 BlockProperties {
10681 style: BlockStyle::Fixed,
10682 placement: BlockPlacement::Below(
10683 buffer.anchor_after(entry.range.start),
10684 ),
10685 height: message_height,
10686 render: diagnostic_block_renderer(diagnostic, None, true, true),
10687 priority: 0,
10688 }
10689 }),
10690 cx,
10691 )
10692 .into_iter()
10693 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10694 .collect();
10695
10696 Some(ActiveDiagnosticGroup {
10697 primary_range,
10698 primary_message,
10699 group_id,
10700 blocks,
10701 is_valid: true,
10702 })
10703 });
10704 self.active_diagnostics.is_some()
10705 }
10706
10707 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10708 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10709 self.display_map.update(cx, |display_map, cx| {
10710 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10711 });
10712 cx.notify();
10713 }
10714 }
10715
10716 pub fn set_selections_from_remote(
10717 &mut self,
10718 selections: Vec<Selection<Anchor>>,
10719 pending_selection: Option<Selection<Anchor>>,
10720 cx: &mut ViewContext<Self>,
10721 ) {
10722 let old_cursor_position = self.selections.newest_anchor().head();
10723 self.selections.change_with(cx, |s| {
10724 s.select_anchors(selections);
10725 if let Some(pending_selection) = pending_selection {
10726 s.set_pending(pending_selection, SelectMode::Character);
10727 } else {
10728 s.clear_pending();
10729 }
10730 });
10731 self.selections_did_change(false, &old_cursor_position, true, cx);
10732 }
10733
10734 fn push_to_selection_history(&mut self) {
10735 self.selection_history.push(SelectionHistoryEntry {
10736 selections: self.selections.disjoint_anchors(),
10737 select_next_state: self.select_next_state.clone(),
10738 select_prev_state: self.select_prev_state.clone(),
10739 add_selections_state: self.add_selections_state.clone(),
10740 });
10741 }
10742
10743 pub fn transact(
10744 &mut self,
10745 cx: &mut ViewContext<Self>,
10746 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10747 ) -> Option<TransactionId> {
10748 self.start_transaction_at(Instant::now(), cx);
10749 update(self, cx);
10750 self.end_transaction_at(Instant::now(), cx)
10751 }
10752
10753 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10754 self.end_selection(cx);
10755 if let Some(tx_id) = self
10756 .buffer
10757 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10758 {
10759 self.selection_history
10760 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10761 cx.emit(EditorEvent::TransactionBegun {
10762 transaction_id: tx_id,
10763 })
10764 }
10765 }
10766
10767 fn end_transaction_at(
10768 &mut self,
10769 now: Instant,
10770 cx: &mut ViewContext<Self>,
10771 ) -> Option<TransactionId> {
10772 if let Some(transaction_id) = self
10773 .buffer
10774 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10775 {
10776 if let Some((_, end_selections)) =
10777 self.selection_history.transaction_mut(transaction_id)
10778 {
10779 *end_selections = Some(self.selections.disjoint_anchors());
10780 } else {
10781 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10782 }
10783
10784 cx.emit(EditorEvent::Edited { transaction_id });
10785 Some(transaction_id)
10786 } else {
10787 None
10788 }
10789 }
10790
10791 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10792 let selection = self.selections.newest::<Point>(cx);
10793
10794 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10795 let range = if selection.is_empty() {
10796 let point = selection.head().to_display_point(&display_map);
10797 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10798 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10799 .to_point(&display_map);
10800 start..end
10801 } else {
10802 selection.range()
10803 };
10804 if display_map.folds_in_range(range).next().is_some() {
10805 self.unfold_lines(&Default::default(), cx)
10806 } else {
10807 self.fold(&Default::default(), cx)
10808 }
10809 }
10810
10811 pub fn toggle_fold_recursive(
10812 &mut self,
10813 _: &actions::ToggleFoldRecursive,
10814 cx: &mut ViewContext<Self>,
10815 ) {
10816 let selection = self.selections.newest::<Point>(cx);
10817
10818 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10819 let range = if selection.is_empty() {
10820 let point = selection.head().to_display_point(&display_map);
10821 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10822 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10823 .to_point(&display_map);
10824 start..end
10825 } else {
10826 selection.range()
10827 };
10828 if display_map.folds_in_range(range).next().is_some() {
10829 self.unfold_recursive(&Default::default(), cx)
10830 } else {
10831 self.fold_recursive(&Default::default(), cx)
10832 }
10833 }
10834
10835 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10836 let mut fold_ranges = Vec::new();
10837 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10838 let selections = self.selections.all_adjusted(cx);
10839
10840 for selection in selections {
10841 let range = selection.range().sorted();
10842 let buffer_start_row = range.start.row;
10843
10844 if range.start.row != range.end.row {
10845 let mut found = false;
10846 let mut row = range.start.row;
10847 while row <= range.end.row {
10848 if let Some((foldable_range, fold_text)) =
10849 { display_map.foldable_range(MultiBufferRow(row)) }
10850 {
10851 found = true;
10852 row = foldable_range.end.row + 1;
10853 fold_ranges.push((foldable_range, fold_text));
10854 } else {
10855 row += 1
10856 }
10857 }
10858 if found {
10859 continue;
10860 }
10861 }
10862
10863 for row in (0..=range.start.row).rev() {
10864 if let Some((foldable_range, fold_text)) =
10865 display_map.foldable_range(MultiBufferRow(row))
10866 {
10867 if foldable_range.end.row >= buffer_start_row {
10868 fold_ranges.push((foldable_range, fold_text));
10869 if row <= range.start.row {
10870 break;
10871 }
10872 }
10873 }
10874 }
10875 }
10876
10877 self.fold_ranges(fold_ranges, true, cx);
10878 }
10879
10880 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10881 let fold_at_level = fold_at.level;
10882 let snapshot = self.buffer.read(cx).snapshot(cx);
10883 let mut fold_ranges = Vec::new();
10884 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10885
10886 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10887 while start_row < end_row {
10888 match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10889 Some(foldable_range) => {
10890 let nested_start_row = foldable_range.0.start.row + 1;
10891 let nested_end_row = foldable_range.0.end.row;
10892
10893 if current_level < fold_at_level {
10894 stack.push((nested_start_row, nested_end_row, current_level + 1));
10895 } else if current_level == fold_at_level {
10896 fold_ranges.push(foldable_range);
10897 }
10898
10899 start_row = nested_end_row + 1;
10900 }
10901 None => start_row += 1,
10902 }
10903 }
10904 }
10905
10906 self.fold_ranges(fold_ranges, true, cx);
10907 }
10908
10909 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10910 let mut fold_ranges = Vec::new();
10911 let snapshot = self.buffer.read(cx).snapshot(cx);
10912
10913 for row in 0..snapshot.max_buffer_row().0 {
10914 if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10915 fold_ranges.push(foldable_range);
10916 }
10917 }
10918
10919 self.fold_ranges(fold_ranges, true, cx);
10920 }
10921
10922 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10923 let mut fold_ranges = Vec::new();
10924 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10925 let selections = self.selections.all_adjusted(cx);
10926
10927 for selection in selections {
10928 let range = selection.range().sorted();
10929 let buffer_start_row = range.start.row;
10930
10931 if range.start.row != range.end.row {
10932 let mut found = false;
10933 for row in range.start.row..=range.end.row {
10934 if let Some((foldable_range, fold_text)) =
10935 { display_map.foldable_range(MultiBufferRow(row)) }
10936 {
10937 found = true;
10938 fold_ranges.push((foldable_range, fold_text));
10939 }
10940 }
10941 if found {
10942 continue;
10943 }
10944 }
10945
10946 for row in (0..=range.start.row).rev() {
10947 if let Some((foldable_range, fold_text)) =
10948 display_map.foldable_range(MultiBufferRow(row))
10949 {
10950 if foldable_range.end.row >= buffer_start_row {
10951 fold_ranges.push((foldable_range, fold_text));
10952 } else {
10953 break;
10954 }
10955 }
10956 }
10957 }
10958
10959 self.fold_ranges(fold_ranges, true, cx);
10960 }
10961
10962 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10963 let buffer_row = fold_at.buffer_row;
10964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10965
10966 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10967 let autoscroll = self
10968 .selections
10969 .all::<Point>(cx)
10970 .iter()
10971 .any(|selection| fold_range.overlaps(&selection.range()));
10972
10973 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10974 }
10975 }
10976
10977 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10978 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10979 let buffer = &display_map.buffer_snapshot;
10980 let selections = self.selections.all::<Point>(cx);
10981 let ranges = selections
10982 .iter()
10983 .map(|s| {
10984 let range = s.display_range(&display_map).sorted();
10985 let mut start = range.start.to_point(&display_map);
10986 let mut end = range.end.to_point(&display_map);
10987 start.column = 0;
10988 end.column = buffer.line_len(MultiBufferRow(end.row));
10989 start..end
10990 })
10991 .collect::<Vec<_>>();
10992
10993 self.unfold_ranges(&ranges, true, true, cx);
10994 }
10995
10996 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10998 let selections = self.selections.all::<Point>(cx);
10999 let ranges = selections
11000 .iter()
11001 .map(|s| {
11002 let mut range = s.display_range(&display_map).sorted();
11003 *range.start.column_mut() = 0;
11004 *range.end.column_mut() = display_map.line_len(range.end.row());
11005 let start = range.start.to_point(&display_map);
11006 let end = range.end.to_point(&display_map);
11007 start..end
11008 })
11009 .collect::<Vec<_>>();
11010
11011 self.unfold_ranges(&ranges, true, true, cx);
11012 }
11013
11014 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11016
11017 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11018 ..Point::new(
11019 unfold_at.buffer_row.0,
11020 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11021 );
11022
11023 let autoscroll = self
11024 .selections
11025 .all::<Point>(cx)
11026 .iter()
11027 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11028
11029 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11030 }
11031
11032 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11033 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11034 self.unfold_ranges(
11035 &[Point::zero()..display_map.max_point().to_point(&display_map)],
11036 true,
11037 true,
11038 cx,
11039 );
11040 }
11041
11042 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11043 let selections = self.selections.all::<Point>(cx);
11044 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11045 let line_mode = self.selections.line_mode;
11046 let ranges = selections.into_iter().map(|s| {
11047 if line_mode {
11048 let start = Point::new(s.start.row, 0);
11049 let end = Point::new(
11050 s.end.row,
11051 display_map
11052 .buffer_snapshot
11053 .line_len(MultiBufferRow(s.end.row)),
11054 );
11055 (start..end, display_map.fold_placeholder.clone())
11056 } else {
11057 (s.start..s.end, display_map.fold_placeholder.clone())
11058 }
11059 });
11060 self.fold_ranges(ranges, true, cx);
11061 }
11062
11063 pub fn fold_ranges<T: ToOffset + Clone>(
11064 &mut self,
11065 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11066 auto_scroll: bool,
11067 cx: &mut ViewContext<Self>,
11068 ) {
11069 let mut fold_ranges = Vec::new();
11070 let mut buffers_affected = HashMap::default();
11071 let multi_buffer = self.buffer().read(cx);
11072 for (fold_range, fold_text) in ranges {
11073 if let Some((_, buffer, _)) =
11074 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11075 {
11076 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11077 };
11078 fold_ranges.push((fold_range, fold_text));
11079 }
11080
11081 let mut ranges = fold_ranges.into_iter().peekable();
11082 if ranges.peek().is_some() {
11083 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11084
11085 if auto_scroll {
11086 self.request_autoscroll(Autoscroll::fit(), cx);
11087 }
11088
11089 for buffer in buffers_affected.into_values() {
11090 self.sync_expanded_diff_hunks(buffer, cx);
11091 }
11092
11093 cx.notify();
11094
11095 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11096 // Clear diagnostics block when folding a range that contains it.
11097 let snapshot = self.snapshot(cx);
11098 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11099 drop(snapshot);
11100 self.active_diagnostics = Some(active_diagnostics);
11101 self.dismiss_diagnostics(cx);
11102 } else {
11103 self.active_diagnostics = Some(active_diagnostics);
11104 }
11105 }
11106
11107 self.scrollbar_marker_state.dirty = true;
11108 }
11109 }
11110
11111 /// Removes any folds whose ranges intersect any of the given ranges.
11112 pub fn unfold_ranges<T: ToOffset + Clone>(
11113 &mut self,
11114 ranges: &[Range<T>],
11115 inclusive: bool,
11116 auto_scroll: bool,
11117 cx: &mut ViewContext<Self>,
11118 ) {
11119 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11120 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11121 });
11122 }
11123
11124 /// Removes any folds with the given ranges.
11125 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11126 &mut self,
11127 ranges: &[Range<T>],
11128 type_id: TypeId,
11129 auto_scroll: bool,
11130 cx: &mut ViewContext<Self>,
11131 ) {
11132 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11133 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11134 });
11135 }
11136
11137 fn remove_folds_with<T: ToOffset + Clone>(
11138 &mut self,
11139 ranges: &[Range<T>],
11140 auto_scroll: bool,
11141 cx: &mut ViewContext<Self>,
11142 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11143 ) {
11144 if ranges.is_empty() {
11145 return;
11146 }
11147
11148 let mut buffers_affected = HashMap::default();
11149 let multi_buffer = self.buffer().read(cx);
11150 for range in ranges {
11151 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11152 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11153 };
11154 }
11155
11156 self.display_map.update(cx, update);
11157 if auto_scroll {
11158 self.request_autoscroll(Autoscroll::fit(), cx);
11159 }
11160
11161 for buffer in buffers_affected.into_values() {
11162 self.sync_expanded_diff_hunks(buffer, cx);
11163 }
11164
11165 cx.notify();
11166 self.scrollbar_marker_state.dirty = true;
11167 self.active_indent_guides_state.dirty = true;
11168 }
11169
11170 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11171 self.display_map.read(cx).fold_placeholder.clone()
11172 }
11173
11174 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11175 if hovered != self.gutter_hovered {
11176 self.gutter_hovered = hovered;
11177 cx.notify();
11178 }
11179 }
11180
11181 pub fn insert_blocks(
11182 &mut self,
11183 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11184 autoscroll: Option<Autoscroll>,
11185 cx: &mut ViewContext<Self>,
11186 ) -> Vec<CustomBlockId> {
11187 let blocks = self
11188 .display_map
11189 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11190 if let Some(autoscroll) = autoscroll {
11191 self.request_autoscroll(autoscroll, cx);
11192 }
11193 cx.notify();
11194 blocks
11195 }
11196
11197 pub fn resize_blocks(
11198 &mut self,
11199 heights: HashMap<CustomBlockId, u32>,
11200 autoscroll: Option<Autoscroll>,
11201 cx: &mut ViewContext<Self>,
11202 ) {
11203 self.display_map
11204 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11205 if let Some(autoscroll) = autoscroll {
11206 self.request_autoscroll(autoscroll, cx);
11207 }
11208 cx.notify();
11209 }
11210
11211 pub fn replace_blocks(
11212 &mut self,
11213 renderers: HashMap<CustomBlockId, RenderBlock>,
11214 autoscroll: Option<Autoscroll>,
11215 cx: &mut ViewContext<Self>,
11216 ) {
11217 self.display_map
11218 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11219 if let Some(autoscroll) = autoscroll {
11220 self.request_autoscroll(autoscroll, cx);
11221 }
11222 cx.notify();
11223 }
11224
11225 pub fn remove_blocks(
11226 &mut self,
11227 block_ids: HashSet<CustomBlockId>,
11228 autoscroll: Option<Autoscroll>,
11229 cx: &mut ViewContext<Self>,
11230 ) {
11231 self.display_map.update(cx, |display_map, cx| {
11232 display_map.remove_blocks(block_ids, cx)
11233 });
11234 if let Some(autoscroll) = autoscroll {
11235 self.request_autoscroll(autoscroll, cx);
11236 }
11237 cx.notify();
11238 }
11239
11240 pub fn row_for_block(
11241 &self,
11242 block_id: CustomBlockId,
11243 cx: &mut ViewContext<Self>,
11244 ) -> Option<DisplayRow> {
11245 self.display_map
11246 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11247 }
11248
11249 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11250 self.focused_block = Some(focused_block);
11251 }
11252
11253 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11254 self.focused_block.take()
11255 }
11256
11257 pub fn insert_creases(
11258 &mut self,
11259 creases: impl IntoIterator<Item = Crease>,
11260 cx: &mut ViewContext<Self>,
11261 ) -> Vec<CreaseId> {
11262 self.display_map
11263 .update(cx, |map, cx| map.insert_creases(creases, cx))
11264 }
11265
11266 pub fn remove_creases(
11267 &mut self,
11268 ids: impl IntoIterator<Item = CreaseId>,
11269 cx: &mut ViewContext<Self>,
11270 ) {
11271 self.display_map
11272 .update(cx, |map, cx| map.remove_creases(ids, cx));
11273 }
11274
11275 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11276 self.display_map
11277 .update(cx, |map, cx| map.snapshot(cx))
11278 .longest_row()
11279 }
11280
11281 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11282 self.display_map
11283 .update(cx, |map, cx| map.snapshot(cx))
11284 .max_point()
11285 }
11286
11287 pub fn text(&self, cx: &AppContext) -> String {
11288 self.buffer.read(cx).read(cx).text()
11289 }
11290
11291 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11292 let text = self.text(cx);
11293 let text = text.trim();
11294
11295 if text.is_empty() {
11296 return None;
11297 }
11298
11299 Some(text.to_string())
11300 }
11301
11302 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11303 self.transact(cx, |this, cx| {
11304 this.buffer
11305 .read(cx)
11306 .as_singleton()
11307 .expect("you can only call set_text on editors for singleton buffers")
11308 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11309 });
11310 }
11311
11312 pub fn display_text(&self, cx: &mut AppContext) -> String {
11313 self.display_map
11314 .update(cx, |map, cx| map.snapshot(cx))
11315 .text()
11316 }
11317
11318 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11319 let mut wrap_guides = smallvec::smallvec![];
11320
11321 if self.show_wrap_guides == Some(false) {
11322 return wrap_guides;
11323 }
11324
11325 let settings = self.buffer.read(cx).settings_at(0, cx);
11326 if settings.show_wrap_guides {
11327 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11328 wrap_guides.push((soft_wrap as usize, true));
11329 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11330 wrap_guides.push((soft_wrap as usize, true));
11331 }
11332 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11333 }
11334
11335 wrap_guides
11336 }
11337
11338 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11339 let settings = self.buffer.read(cx).settings_at(0, cx);
11340 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11341 match mode {
11342 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11343 SoftWrap::None
11344 }
11345 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11346 language_settings::SoftWrap::PreferredLineLength => {
11347 SoftWrap::Column(settings.preferred_line_length)
11348 }
11349 language_settings::SoftWrap::Bounded => {
11350 SoftWrap::Bounded(settings.preferred_line_length)
11351 }
11352 }
11353 }
11354
11355 pub fn set_soft_wrap_mode(
11356 &mut self,
11357 mode: language_settings::SoftWrap,
11358 cx: &mut ViewContext<Self>,
11359 ) {
11360 self.soft_wrap_mode_override = Some(mode);
11361 cx.notify();
11362 }
11363
11364 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11365 self.text_style_refinement = Some(style);
11366 }
11367
11368 /// called by the Element so we know what style we were most recently rendered with.
11369 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11370 let rem_size = cx.rem_size();
11371 self.display_map.update(cx, |map, cx| {
11372 map.set_font(
11373 style.text.font(),
11374 style.text.font_size.to_pixels(rem_size),
11375 cx,
11376 )
11377 });
11378 self.style = Some(style);
11379 }
11380
11381 pub fn style(&self) -> Option<&EditorStyle> {
11382 self.style.as_ref()
11383 }
11384
11385 // Called by the element. This method is not designed to be called outside of the editor
11386 // element's layout code because it does not notify when rewrapping is computed synchronously.
11387 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11388 self.display_map
11389 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11390 }
11391
11392 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11393 if self.soft_wrap_mode_override.is_some() {
11394 self.soft_wrap_mode_override.take();
11395 } else {
11396 let soft_wrap = match self.soft_wrap_mode(cx) {
11397 SoftWrap::GitDiff => return,
11398 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11399 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11400 language_settings::SoftWrap::None
11401 }
11402 };
11403 self.soft_wrap_mode_override = Some(soft_wrap);
11404 }
11405 cx.notify();
11406 }
11407
11408 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11409 let Some(workspace) = self.workspace() else {
11410 return;
11411 };
11412 let fs = workspace.read(cx).app_state().fs.clone();
11413 let current_show = TabBarSettings::get_global(cx).show;
11414 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11415 setting.show = Some(!current_show);
11416 });
11417 }
11418
11419 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11420 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11421 self.buffer
11422 .read(cx)
11423 .settings_at(0, cx)
11424 .indent_guides
11425 .enabled
11426 });
11427 self.show_indent_guides = Some(!currently_enabled);
11428 cx.notify();
11429 }
11430
11431 fn should_show_indent_guides(&self) -> Option<bool> {
11432 self.show_indent_guides
11433 }
11434
11435 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11436 let mut editor_settings = EditorSettings::get_global(cx).clone();
11437 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11438 EditorSettings::override_global(editor_settings, cx);
11439 }
11440
11441 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11442 self.use_relative_line_numbers
11443 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11444 }
11445
11446 pub fn toggle_relative_line_numbers(
11447 &mut self,
11448 _: &ToggleRelativeLineNumbers,
11449 cx: &mut ViewContext<Self>,
11450 ) {
11451 let is_relative = self.should_use_relative_line_numbers(cx);
11452 self.set_relative_line_number(Some(!is_relative), cx)
11453 }
11454
11455 pub fn set_relative_line_number(
11456 &mut self,
11457 is_relative: Option<bool>,
11458 cx: &mut ViewContext<Self>,
11459 ) {
11460 self.use_relative_line_numbers = is_relative;
11461 cx.notify();
11462 }
11463
11464 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11465 self.show_gutter = show_gutter;
11466 cx.notify();
11467 }
11468
11469 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11470 self.show_line_numbers = Some(show_line_numbers);
11471 cx.notify();
11472 }
11473
11474 pub fn set_show_git_diff_gutter(
11475 &mut self,
11476 show_git_diff_gutter: bool,
11477 cx: &mut ViewContext<Self>,
11478 ) {
11479 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11480 cx.notify();
11481 }
11482
11483 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11484 self.show_code_actions = Some(show_code_actions);
11485 cx.notify();
11486 }
11487
11488 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11489 self.show_runnables = Some(show_runnables);
11490 cx.notify();
11491 }
11492
11493 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11494 if self.display_map.read(cx).masked != masked {
11495 self.display_map.update(cx, |map, _| map.masked = masked);
11496 }
11497 cx.notify()
11498 }
11499
11500 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11501 self.show_wrap_guides = Some(show_wrap_guides);
11502 cx.notify();
11503 }
11504
11505 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11506 self.show_indent_guides = Some(show_indent_guides);
11507 cx.notify();
11508 }
11509
11510 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11511 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11512 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11513 if let Some(dir) = file.abs_path(cx).parent() {
11514 return Some(dir.to_owned());
11515 }
11516 }
11517
11518 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11519 return Some(project_path.path.to_path_buf());
11520 }
11521 }
11522
11523 None
11524 }
11525
11526 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11527 self.active_excerpt(cx)?
11528 .1
11529 .read(cx)
11530 .file()
11531 .and_then(|f| f.as_local())
11532 }
11533
11534 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11535 if let Some(target) = self.target_file(cx) {
11536 cx.reveal_path(&target.abs_path(cx));
11537 }
11538 }
11539
11540 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11541 if let Some(file) = self.target_file(cx) {
11542 if let Some(path) = file.abs_path(cx).to_str() {
11543 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11544 }
11545 }
11546 }
11547
11548 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11549 if let Some(file) = self.target_file(cx) {
11550 if let Some(path) = file.path().to_str() {
11551 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11552 }
11553 }
11554 }
11555
11556 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11557 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11558
11559 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11560 self.start_git_blame(true, cx);
11561 }
11562
11563 cx.notify();
11564 }
11565
11566 pub fn toggle_git_blame_inline(
11567 &mut self,
11568 _: &ToggleGitBlameInline,
11569 cx: &mut ViewContext<Self>,
11570 ) {
11571 self.toggle_git_blame_inline_internal(true, cx);
11572 cx.notify();
11573 }
11574
11575 pub fn git_blame_inline_enabled(&self) -> bool {
11576 self.git_blame_inline_enabled
11577 }
11578
11579 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11580 self.show_selection_menu = self
11581 .show_selection_menu
11582 .map(|show_selections_menu| !show_selections_menu)
11583 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11584
11585 cx.notify();
11586 }
11587
11588 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11589 self.show_selection_menu
11590 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11591 }
11592
11593 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11594 if let Some(project) = self.project.as_ref() {
11595 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11596 return;
11597 };
11598
11599 if buffer.read(cx).file().is_none() {
11600 return;
11601 }
11602
11603 let focused = self.focus_handle(cx).contains_focused(cx);
11604
11605 let project = project.clone();
11606 let blame =
11607 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11608 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11609 self.blame = Some(blame);
11610 }
11611 }
11612
11613 fn toggle_git_blame_inline_internal(
11614 &mut self,
11615 user_triggered: bool,
11616 cx: &mut ViewContext<Self>,
11617 ) {
11618 if self.git_blame_inline_enabled {
11619 self.git_blame_inline_enabled = false;
11620 self.show_git_blame_inline = false;
11621 self.show_git_blame_inline_delay_task.take();
11622 } else {
11623 self.git_blame_inline_enabled = true;
11624 self.start_git_blame_inline(user_triggered, cx);
11625 }
11626
11627 cx.notify();
11628 }
11629
11630 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11631 self.start_git_blame(user_triggered, cx);
11632
11633 if ProjectSettings::get_global(cx)
11634 .git
11635 .inline_blame_delay()
11636 .is_some()
11637 {
11638 self.start_inline_blame_timer(cx);
11639 } else {
11640 self.show_git_blame_inline = true
11641 }
11642 }
11643
11644 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11645 self.blame.as_ref()
11646 }
11647
11648 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11649 self.show_git_blame_gutter && self.has_blame_entries(cx)
11650 }
11651
11652 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11653 self.show_git_blame_inline
11654 && self.focus_handle.is_focused(cx)
11655 && !self.newest_selection_head_on_empty_line(cx)
11656 && self.has_blame_entries(cx)
11657 }
11658
11659 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11660 self.blame()
11661 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11662 }
11663
11664 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11665 let cursor_anchor = self.selections.newest_anchor().head();
11666
11667 let snapshot = self.buffer.read(cx).snapshot(cx);
11668 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11669
11670 snapshot.line_len(buffer_row) == 0
11671 }
11672
11673 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11674 let buffer_and_selection = maybe!({
11675 let selection = self.selections.newest::<Point>(cx);
11676 let selection_range = selection.range();
11677
11678 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11679 (buffer, selection_range.start.row..selection_range.end.row)
11680 } else {
11681 let buffer_ranges = self
11682 .buffer()
11683 .read(cx)
11684 .range_to_buffer_ranges(selection_range, cx);
11685
11686 let (buffer, range, _) = if selection.reversed {
11687 buffer_ranges.first()
11688 } else {
11689 buffer_ranges.last()
11690 }?;
11691
11692 let snapshot = buffer.read(cx).snapshot();
11693 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11694 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11695 (buffer.clone(), selection)
11696 };
11697
11698 Some((buffer, selection))
11699 });
11700
11701 let Some((buffer, selection)) = buffer_and_selection else {
11702 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11703 };
11704
11705 let Some(project) = self.project.as_ref() else {
11706 return Task::ready(Err(anyhow!("editor does not have project")));
11707 };
11708
11709 project.update(cx, |project, cx| {
11710 project.get_permalink_to_line(&buffer, selection, cx)
11711 })
11712 }
11713
11714 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11715 let permalink_task = self.get_permalink_to_line(cx);
11716 let workspace = self.workspace();
11717
11718 cx.spawn(|_, mut cx| async move {
11719 match permalink_task.await {
11720 Ok(permalink) => {
11721 cx.update(|cx| {
11722 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11723 })
11724 .ok();
11725 }
11726 Err(err) => {
11727 let message = format!("Failed to copy permalink: {err}");
11728
11729 Err::<(), anyhow::Error>(err).log_err();
11730
11731 if let Some(workspace) = workspace {
11732 workspace
11733 .update(&mut cx, |workspace, cx| {
11734 struct CopyPermalinkToLine;
11735
11736 workspace.show_toast(
11737 Toast::new(
11738 NotificationId::unique::<CopyPermalinkToLine>(),
11739 message,
11740 ),
11741 cx,
11742 )
11743 })
11744 .ok();
11745 }
11746 }
11747 }
11748 })
11749 .detach();
11750 }
11751
11752 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11753 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11754 if let Some(file) = self.target_file(cx) {
11755 if let Some(path) = file.path().to_str() {
11756 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11757 }
11758 }
11759 }
11760
11761 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11762 let permalink_task = self.get_permalink_to_line(cx);
11763 let workspace = self.workspace();
11764
11765 cx.spawn(|_, mut cx| async move {
11766 match permalink_task.await {
11767 Ok(permalink) => {
11768 cx.update(|cx| {
11769 cx.open_url(permalink.as_ref());
11770 })
11771 .ok();
11772 }
11773 Err(err) => {
11774 let message = format!("Failed to open permalink: {err}");
11775
11776 Err::<(), anyhow::Error>(err).log_err();
11777
11778 if let Some(workspace) = workspace {
11779 workspace
11780 .update(&mut cx, |workspace, cx| {
11781 struct OpenPermalinkToLine;
11782
11783 workspace.show_toast(
11784 Toast::new(
11785 NotificationId::unique::<OpenPermalinkToLine>(),
11786 message,
11787 ),
11788 cx,
11789 )
11790 })
11791 .ok();
11792 }
11793 }
11794 }
11795 })
11796 .detach();
11797 }
11798
11799 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11800 /// last highlight added will be used.
11801 ///
11802 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11803 pub fn highlight_rows<T: 'static>(
11804 &mut self,
11805 range: Range<Anchor>,
11806 color: Hsla,
11807 should_autoscroll: bool,
11808 cx: &mut ViewContext<Self>,
11809 ) {
11810 let snapshot = self.buffer().read(cx).snapshot(cx);
11811 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11812 let ix = row_highlights.binary_search_by(|highlight| {
11813 Ordering::Equal
11814 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11815 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11816 });
11817
11818 if let Err(mut ix) = ix {
11819 let index = post_inc(&mut self.highlight_order);
11820
11821 // If this range intersects with the preceding highlight, then merge it with
11822 // the preceding highlight. Otherwise insert a new highlight.
11823 let mut merged = false;
11824 if ix > 0 {
11825 let prev_highlight = &mut row_highlights[ix - 1];
11826 if prev_highlight
11827 .range
11828 .end
11829 .cmp(&range.start, &snapshot)
11830 .is_ge()
11831 {
11832 ix -= 1;
11833 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11834 prev_highlight.range.end = range.end;
11835 }
11836 merged = true;
11837 prev_highlight.index = index;
11838 prev_highlight.color = color;
11839 prev_highlight.should_autoscroll = should_autoscroll;
11840 }
11841 }
11842
11843 if !merged {
11844 row_highlights.insert(
11845 ix,
11846 RowHighlight {
11847 range: range.clone(),
11848 index,
11849 color,
11850 should_autoscroll,
11851 },
11852 );
11853 }
11854
11855 // If any of the following highlights intersect with this one, merge them.
11856 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11857 let highlight = &row_highlights[ix];
11858 if next_highlight
11859 .range
11860 .start
11861 .cmp(&highlight.range.end, &snapshot)
11862 .is_le()
11863 {
11864 if next_highlight
11865 .range
11866 .end
11867 .cmp(&highlight.range.end, &snapshot)
11868 .is_gt()
11869 {
11870 row_highlights[ix].range.end = next_highlight.range.end;
11871 }
11872 row_highlights.remove(ix + 1);
11873 } else {
11874 break;
11875 }
11876 }
11877 }
11878 }
11879
11880 /// Remove any highlighted row ranges of the given type that intersect the
11881 /// given ranges.
11882 pub fn remove_highlighted_rows<T: 'static>(
11883 &mut self,
11884 ranges_to_remove: Vec<Range<Anchor>>,
11885 cx: &mut ViewContext<Self>,
11886 ) {
11887 let snapshot = self.buffer().read(cx).snapshot(cx);
11888 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11889 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11890 row_highlights.retain(|highlight| {
11891 while let Some(range_to_remove) = ranges_to_remove.peek() {
11892 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11893 Ordering::Less | Ordering::Equal => {
11894 ranges_to_remove.next();
11895 }
11896 Ordering::Greater => {
11897 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11898 Ordering::Less | Ordering::Equal => {
11899 return false;
11900 }
11901 Ordering::Greater => break,
11902 }
11903 }
11904 }
11905 }
11906
11907 true
11908 })
11909 }
11910
11911 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11912 pub fn clear_row_highlights<T: 'static>(&mut self) {
11913 self.highlighted_rows.remove(&TypeId::of::<T>());
11914 }
11915
11916 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11917 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11918 self.highlighted_rows
11919 .get(&TypeId::of::<T>())
11920 .map_or(&[] as &[_], |vec| vec.as_slice())
11921 .iter()
11922 .map(|highlight| (highlight.range.clone(), highlight.color))
11923 }
11924
11925 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11926 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11927 /// Allows to ignore certain kinds of highlights.
11928 pub fn highlighted_display_rows(
11929 &mut self,
11930 cx: &mut WindowContext,
11931 ) -> BTreeMap<DisplayRow, Hsla> {
11932 let snapshot = self.snapshot(cx);
11933 let mut used_highlight_orders = HashMap::default();
11934 self.highlighted_rows
11935 .iter()
11936 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11937 .fold(
11938 BTreeMap::<DisplayRow, Hsla>::new(),
11939 |mut unique_rows, highlight| {
11940 let start = highlight.range.start.to_display_point(&snapshot);
11941 let end = highlight.range.end.to_display_point(&snapshot);
11942 let start_row = start.row().0;
11943 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11944 && end.column() == 0
11945 {
11946 end.row().0.saturating_sub(1)
11947 } else {
11948 end.row().0
11949 };
11950 for row in start_row..=end_row {
11951 let used_index =
11952 used_highlight_orders.entry(row).or_insert(highlight.index);
11953 if highlight.index >= *used_index {
11954 *used_index = highlight.index;
11955 unique_rows.insert(DisplayRow(row), highlight.color);
11956 }
11957 }
11958 unique_rows
11959 },
11960 )
11961 }
11962
11963 pub fn highlighted_display_row_for_autoscroll(
11964 &self,
11965 snapshot: &DisplaySnapshot,
11966 ) -> Option<DisplayRow> {
11967 self.highlighted_rows
11968 .values()
11969 .flat_map(|highlighted_rows| highlighted_rows.iter())
11970 .filter_map(|highlight| {
11971 if highlight.should_autoscroll {
11972 Some(highlight.range.start.to_display_point(snapshot).row())
11973 } else {
11974 None
11975 }
11976 })
11977 .min()
11978 }
11979
11980 pub fn set_search_within_ranges(
11981 &mut self,
11982 ranges: &[Range<Anchor>],
11983 cx: &mut ViewContext<Self>,
11984 ) {
11985 self.highlight_background::<SearchWithinRange>(
11986 ranges,
11987 |colors| colors.editor_document_highlight_read_background,
11988 cx,
11989 )
11990 }
11991
11992 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11993 self.breadcrumb_header = Some(new_header);
11994 }
11995
11996 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11997 self.clear_background_highlights::<SearchWithinRange>(cx);
11998 }
11999
12000 pub fn highlight_background<T: 'static>(
12001 &mut self,
12002 ranges: &[Range<Anchor>],
12003 color_fetcher: fn(&ThemeColors) -> Hsla,
12004 cx: &mut ViewContext<Self>,
12005 ) {
12006 self.background_highlights
12007 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12008 self.scrollbar_marker_state.dirty = true;
12009 cx.notify();
12010 }
12011
12012 pub fn clear_background_highlights<T: 'static>(
12013 &mut self,
12014 cx: &mut ViewContext<Self>,
12015 ) -> Option<BackgroundHighlight> {
12016 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12017 if !text_highlights.1.is_empty() {
12018 self.scrollbar_marker_state.dirty = true;
12019 cx.notify();
12020 }
12021 Some(text_highlights)
12022 }
12023
12024 pub fn highlight_gutter<T: 'static>(
12025 &mut self,
12026 ranges: &[Range<Anchor>],
12027 color_fetcher: fn(&AppContext) -> Hsla,
12028 cx: &mut ViewContext<Self>,
12029 ) {
12030 self.gutter_highlights
12031 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12032 cx.notify();
12033 }
12034
12035 pub fn clear_gutter_highlights<T: 'static>(
12036 &mut self,
12037 cx: &mut ViewContext<Self>,
12038 ) -> Option<GutterHighlight> {
12039 cx.notify();
12040 self.gutter_highlights.remove(&TypeId::of::<T>())
12041 }
12042
12043 #[cfg(feature = "test-support")]
12044 pub fn all_text_background_highlights(
12045 &mut self,
12046 cx: &mut ViewContext<Self>,
12047 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12048 let snapshot = self.snapshot(cx);
12049 let buffer = &snapshot.buffer_snapshot;
12050 let start = buffer.anchor_before(0);
12051 let end = buffer.anchor_after(buffer.len());
12052 let theme = cx.theme().colors();
12053 self.background_highlights_in_range(start..end, &snapshot, theme)
12054 }
12055
12056 #[cfg(feature = "test-support")]
12057 pub fn search_background_highlights(
12058 &mut self,
12059 cx: &mut ViewContext<Self>,
12060 ) -> Vec<Range<Point>> {
12061 let snapshot = self.buffer().read(cx).snapshot(cx);
12062
12063 let highlights = self
12064 .background_highlights
12065 .get(&TypeId::of::<items::BufferSearchHighlights>());
12066
12067 if let Some((_color, ranges)) = highlights {
12068 ranges
12069 .iter()
12070 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12071 .collect_vec()
12072 } else {
12073 vec![]
12074 }
12075 }
12076
12077 fn document_highlights_for_position<'a>(
12078 &'a self,
12079 position: Anchor,
12080 buffer: &'a MultiBufferSnapshot,
12081 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12082 let read_highlights = self
12083 .background_highlights
12084 .get(&TypeId::of::<DocumentHighlightRead>())
12085 .map(|h| &h.1);
12086 let write_highlights = self
12087 .background_highlights
12088 .get(&TypeId::of::<DocumentHighlightWrite>())
12089 .map(|h| &h.1);
12090 let left_position = position.bias_left(buffer);
12091 let right_position = position.bias_right(buffer);
12092 read_highlights
12093 .into_iter()
12094 .chain(write_highlights)
12095 .flat_map(move |ranges| {
12096 let start_ix = match ranges.binary_search_by(|probe| {
12097 let cmp = probe.end.cmp(&left_position, buffer);
12098 if cmp.is_ge() {
12099 Ordering::Greater
12100 } else {
12101 Ordering::Less
12102 }
12103 }) {
12104 Ok(i) | Err(i) => i,
12105 };
12106
12107 ranges[start_ix..]
12108 .iter()
12109 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12110 })
12111 }
12112
12113 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12114 self.background_highlights
12115 .get(&TypeId::of::<T>())
12116 .map_or(false, |(_, highlights)| !highlights.is_empty())
12117 }
12118
12119 pub fn background_highlights_in_range(
12120 &self,
12121 search_range: Range<Anchor>,
12122 display_snapshot: &DisplaySnapshot,
12123 theme: &ThemeColors,
12124 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12125 let mut results = Vec::new();
12126 for (color_fetcher, ranges) in self.background_highlights.values() {
12127 let color = color_fetcher(theme);
12128 let start_ix = match ranges.binary_search_by(|probe| {
12129 let cmp = probe
12130 .end
12131 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12132 if cmp.is_gt() {
12133 Ordering::Greater
12134 } else {
12135 Ordering::Less
12136 }
12137 }) {
12138 Ok(i) | Err(i) => i,
12139 };
12140 for range in &ranges[start_ix..] {
12141 if range
12142 .start
12143 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12144 .is_ge()
12145 {
12146 break;
12147 }
12148
12149 let start = range.start.to_display_point(display_snapshot);
12150 let end = range.end.to_display_point(display_snapshot);
12151 results.push((start..end, color))
12152 }
12153 }
12154 results
12155 }
12156
12157 pub fn background_highlight_row_ranges<T: 'static>(
12158 &self,
12159 search_range: Range<Anchor>,
12160 display_snapshot: &DisplaySnapshot,
12161 count: usize,
12162 ) -> Vec<RangeInclusive<DisplayPoint>> {
12163 let mut results = Vec::new();
12164 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12165 return vec![];
12166 };
12167
12168 let start_ix = match ranges.binary_search_by(|probe| {
12169 let cmp = probe
12170 .end
12171 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12172 if cmp.is_gt() {
12173 Ordering::Greater
12174 } else {
12175 Ordering::Less
12176 }
12177 }) {
12178 Ok(i) | Err(i) => i,
12179 };
12180 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12181 if let (Some(start_display), Some(end_display)) = (start, end) {
12182 results.push(
12183 start_display.to_display_point(display_snapshot)
12184 ..=end_display.to_display_point(display_snapshot),
12185 );
12186 }
12187 };
12188 let mut start_row: Option<Point> = None;
12189 let mut end_row: Option<Point> = None;
12190 if ranges.len() > count {
12191 return Vec::new();
12192 }
12193 for range in &ranges[start_ix..] {
12194 if range
12195 .start
12196 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12197 .is_ge()
12198 {
12199 break;
12200 }
12201 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12202 if let Some(current_row) = &end_row {
12203 if end.row == current_row.row {
12204 continue;
12205 }
12206 }
12207 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12208 if start_row.is_none() {
12209 assert_eq!(end_row, None);
12210 start_row = Some(start);
12211 end_row = Some(end);
12212 continue;
12213 }
12214 if let Some(current_end) = end_row.as_mut() {
12215 if start.row > current_end.row + 1 {
12216 push_region(start_row, end_row);
12217 start_row = Some(start);
12218 end_row = Some(end);
12219 } else {
12220 // Merge two hunks.
12221 *current_end = end;
12222 }
12223 } else {
12224 unreachable!();
12225 }
12226 }
12227 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12228 push_region(start_row, end_row);
12229 results
12230 }
12231
12232 pub fn gutter_highlights_in_range(
12233 &self,
12234 search_range: Range<Anchor>,
12235 display_snapshot: &DisplaySnapshot,
12236 cx: &AppContext,
12237 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12238 let mut results = Vec::new();
12239 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12240 let color = color_fetcher(cx);
12241 let start_ix = match ranges.binary_search_by(|probe| {
12242 let cmp = probe
12243 .end
12244 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12245 if cmp.is_gt() {
12246 Ordering::Greater
12247 } else {
12248 Ordering::Less
12249 }
12250 }) {
12251 Ok(i) | Err(i) => i,
12252 };
12253 for range in &ranges[start_ix..] {
12254 if range
12255 .start
12256 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12257 .is_ge()
12258 {
12259 break;
12260 }
12261
12262 let start = range.start.to_display_point(display_snapshot);
12263 let end = range.end.to_display_point(display_snapshot);
12264 results.push((start..end, color))
12265 }
12266 }
12267 results
12268 }
12269
12270 /// Get the text ranges corresponding to the redaction query
12271 pub fn redacted_ranges(
12272 &self,
12273 search_range: Range<Anchor>,
12274 display_snapshot: &DisplaySnapshot,
12275 cx: &WindowContext,
12276 ) -> Vec<Range<DisplayPoint>> {
12277 display_snapshot
12278 .buffer_snapshot
12279 .redacted_ranges(search_range, |file| {
12280 if let Some(file) = file {
12281 file.is_private()
12282 && EditorSettings::get(
12283 Some(SettingsLocation {
12284 worktree_id: file.worktree_id(cx),
12285 path: file.path().as_ref(),
12286 }),
12287 cx,
12288 )
12289 .redact_private_values
12290 } else {
12291 false
12292 }
12293 })
12294 .map(|range| {
12295 range.start.to_display_point(display_snapshot)
12296 ..range.end.to_display_point(display_snapshot)
12297 })
12298 .collect()
12299 }
12300
12301 pub fn highlight_text<T: 'static>(
12302 &mut self,
12303 ranges: Vec<Range<Anchor>>,
12304 style: HighlightStyle,
12305 cx: &mut ViewContext<Self>,
12306 ) {
12307 self.display_map.update(cx, |map, _| {
12308 map.highlight_text(TypeId::of::<T>(), ranges, style)
12309 });
12310 cx.notify();
12311 }
12312
12313 pub(crate) fn highlight_inlays<T: 'static>(
12314 &mut self,
12315 highlights: Vec<InlayHighlight>,
12316 style: HighlightStyle,
12317 cx: &mut ViewContext<Self>,
12318 ) {
12319 self.display_map.update(cx, |map, _| {
12320 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12321 });
12322 cx.notify();
12323 }
12324
12325 pub fn text_highlights<'a, T: 'static>(
12326 &'a self,
12327 cx: &'a AppContext,
12328 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12329 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12330 }
12331
12332 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12333 let cleared = self
12334 .display_map
12335 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12336 if cleared {
12337 cx.notify();
12338 }
12339 }
12340
12341 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12342 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12343 && self.focus_handle.is_focused(cx)
12344 }
12345
12346 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12347 self.show_cursor_when_unfocused = is_enabled;
12348 cx.notify();
12349 }
12350
12351 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12352 cx.notify();
12353 }
12354
12355 fn on_buffer_event(
12356 &mut self,
12357 multibuffer: Model<MultiBuffer>,
12358 event: &multi_buffer::Event,
12359 cx: &mut ViewContext<Self>,
12360 ) {
12361 match event {
12362 multi_buffer::Event::Edited {
12363 singleton_buffer_edited,
12364 } => {
12365 self.scrollbar_marker_state.dirty = true;
12366 self.active_indent_guides_state.dirty = true;
12367 self.refresh_active_diagnostics(cx);
12368 self.refresh_code_actions(cx);
12369 if self.has_active_inline_completion(cx) {
12370 self.update_visible_inline_completion(cx);
12371 }
12372 cx.emit(EditorEvent::BufferEdited);
12373 cx.emit(SearchEvent::MatchesInvalidated);
12374 if *singleton_buffer_edited {
12375 if let Some(project) = &self.project {
12376 let project = project.read(cx);
12377 #[allow(clippy::mutable_key_type)]
12378 let languages_affected = multibuffer
12379 .read(cx)
12380 .all_buffers()
12381 .into_iter()
12382 .filter_map(|buffer| {
12383 let buffer = buffer.read(cx);
12384 let language = buffer.language()?;
12385 if project.is_local()
12386 && project.language_servers_for_buffer(buffer, cx).count() == 0
12387 {
12388 None
12389 } else {
12390 Some(language)
12391 }
12392 })
12393 .cloned()
12394 .collect::<HashSet<_>>();
12395 if !languages_affected.is_empty() {
12396 self.refresh_inlay_hints(
12397 InlayHintRefreshReason::BufferEdited(languages_affected),
12398 cx,
12399 );
12400 }
12401 }
12402 }
12403
12404 let Some(project) = &self.project else { return };
12405 let (telemetry, is_via_ssh) = {
12406 let project = project.read(cx);
12407 let telemetry = project.client().telemetry().clone();
12408 let is_via_ssh = project.is_via_ssh();
12409 (telemetry, is_via_ssh)
12410 };
12411 refresh_linked_ranges(self, cx);
12412 telemetry.log_edit_event("editor", is_via_ssh);
12413 }
12414 multi_buffer::Event::ExcerptsAdded {
12415 buffer,
12416 predecessor,
12417 excerpts,
12418 } => {
12419 self.tasks_update_task = Some(self.refresh_runnables(cx));
12420 cx.emit(EditorEvent::ExcerptsAdded {
12421 buffer: buffer.clone(),
12422 predecessor: *predecessor,
12423 excerpts: excerpts.clone(),
12424 });
12425 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12426 }
12427 multi_buffer::Event::ExcerptsRemoved { ids } => {
12428 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12429 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12430 }
12431 multi_buffer::Event::ExcerptsEdited { ids } => {
12432 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12433 }
12434 multi_buffer::Event::ExcerptsExpanded { ids } => {
12435 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12436 }
12437 multi_buffer::Event::Reparsed(buffer_id) => {
12438 self.tasks_update_task = Some(self.refresh_runnables(cx));
12439
12440 cx.emit(EditorEvent::Reparsed(*buffer_id));
12441 }
12442 multi_buffer::Event::LanguageChanged(buffer_id) => {
12443 linked_editing_ranges::refresh_linked_ranges(self, cx);
12444 cx.emit(EditorEvent::Reparsed(*buffer_id));
12445 cx.notify();
12446 }
12447 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12448 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12449 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12450 cx.emit(EditorEvent::TitleChanged)
12451 }
12452 multi_buffer::Event::DiffBaseChanged => {
12453 self.scrollbar_marker_state.dirty = true;
12454 cx.emit(EditorEvent::DiffBaseChanged);
12455 cx.notify();
12456 }
12457 multi_buffer::Event::DiffUpdated { buffer } => {
12458 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12459 cx.notify();
12460 }
12461 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12462 multi_buffer::Event::DiagnosticsUpdated => {
12463 self.refresh_active_diagnostics(cx);
12464 self.scrollbar_marker_state.dirty = true;
12465 cx.notify();
12466 }
12467 _ => {}
12468 };
12469 }
12470
12471 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12472 cx.notify();
12473 }
12474
12475 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12476 self.tasks_update_task = Some(self.refresh_runnables(cx));
12477 self.refresh_inline_completion(true, false, cx);
12478 self.refresh_inlay_hints(
12479 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12480 self.selections.newest_anchor().head(),
12481 &self.buffer.read(cx).snapshot(cx),
12482 cx,
12483 )),
12484 cx,
12485 );
12486
12487 let old_cursor_shape = self.cursor_shape;
12488
12489 {
12490 let editor_settings = EditorSettings::get_global(cx);
12491 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12492 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12493 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12494 }
12495
12496 if old_cursor_shape != self.cursor_shape {
12497 cx.emit(EditorEvent::CursorShapeChanged);
12498 }
12499
12500 let project_settings = ProjectSettings::get_global(cx);
12501 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12502
12503 if self.mode == EditorMode::Full {
12504 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12505 if self.git_blame_inline_enabled != inline_blame_enabled {
12506 self.toggle_git_blame_inline_internal(false, cx);
12507 }
12508 }
12509
12510 cx.notify();
12511 }
12512
12513 pub fn set_searchable(&mut self, searchable: bool) {
12514 self.searchable = searchable;
12515 }
12516
12517 pub fn searchable(&self) -> bool {
12518 self.searchable
12519 }
12520
12521 fn open_proposed_changes_editor(
12522 &mut self,
12523 _: &OpenProposedChangesEditor,
12524 cx: &mut ViewContext<Self>,
12525 ) {
12526 let Some(workspace) = self.workspace() else {
12527 cx.propagate();
12528 return;
12529 };
12530
12531 let selections = self.selections.all::<usize>(cx);
12532 let buffer = self.buffer.read(cx);
12533 let mut new_selections_by_buffer = HashMap::default();
12534 for selection in selections {
12535 for (buffer, range, _) in
12536 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12537 {
12538 let mut range = range.to_point(buffer.read(cx));
12539 range.start.column = 0;
12540 range.end.column = buffer.read(cx).line_len(range.end.row);
12541 new_selections_by_buffer
12542 .entry(buffer)
12543 .or_insert(Vec::new())
12544 .push(range)
12545 }
12546 }
12547
12548 let proposed_changes_buffers = new_selections_by_buffer
12549 .into_iter()
12550 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12551 .collect::<Vec<_>>();
12552 let proposed_changes_editor = cx.new_view(|cx| {
12553 ProposedChangesEditor::new(
12554 "Proposed changes",
12555 proposed_changes_buffers,
12556 self.project.clone(),
12557 cx,
12558 )
12559 });
12560
12561 cx.window_context().defer(move |cx| {
12562 workspace.update(cx, |workspace, cx| {
12563 workspace.active_pane().update(cx, |pane, cx| {
12564 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12565 });
12566 });
12567 });
12568 }
12569
12570 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12571 self.open_excerpts_common(true, cx)
12572 }
12573
12574 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12575 self.open_excerpts_common(false, cx)
12576 }
12577
12578 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12579 let selections = self.selections.all::<usize>(cx);
12580 let buffer = self.buffer.read(cx);
12581 if buffer.is_singleton() {
12582 cx.propagate();
12583 return;
12584 }
12585
12586 let Some(workspace) = self.workspace() else {
12587 cx.propagate();
12588 return;
12589 };
12590
12591 let mut new_selections_by_buffer = HashMap::default();
12592 for selection in selections {
12593 for (mut buffer_handle, mut range, _) in
12594 buffer.range_to_buffer_ranges(selection.range(), cx)
12595 {
12596 // When editing branch buffers, jump to the corresponding location
12597 // in their base buffer.
12598 let buffer = buffer_handle.read(cx);
12599 if let Some(base_buffer) = buffer.diff_base_buffer() {
12600 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12601 buffer_handle = base_buffer;
12602 }
12603
12604 if selection.reversed {
12605 mem::swap(&mut range.start, &mut range.end);
12606 }
12607 new_selections_by_buffer
12608 .entry(buffer_handle)
12609 .or_insert(Vec::new())
12610 .push(range)
12611 }
12612 }
12613
12614 // We defer the pane interaction because we ourselves are a workspace item
12615 // and activating a new item causes the pane to call a method on us reentrantly,
12616 // which panics if we're on the stack.
12617 cx.window_context().defer(move |cx| {
12618 workspace.update(cx, |workspace, cx| {
12619 let pane = if split {
12620 workspace.adjacent_pane(cx)
12621 } else {
12622 workspace.active_pane().clone()
12623 };
12624
12625 for (buffer, ranges) in new_selections_by_buffer {
12626 let editor =
12627 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12628 editor.update(cx, |editor, cx| {
12629 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12630 s.select_ranges(ranges);
12631 });
12632 });
12633 }
12634 })
12635 });
12636 }
12637
12638 fn jump(
12639 &mut self,
12640 path: ProjectPath,
12641 position: Point,
12642 anchor: language::Anchor,
12643 offset_from_top: u32,
12644 cx: &mut ViewContext<Self>,
12645 ) {
12646 let workspace = self.workspace();
12647 cx.spawn(|_, mut cx| async move {
12648 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12649 let editor = workspace.update(&mut cx, |workspace, cx| {
12650 // Reset the preview item id before opening the new item
12651 workspace.active_pane().update(cx, |pane, cx| {
12652 pane.set_preview_item_id(None, cx);
12653 });
12654 workspace.open_path_preview(path, None, true, true, cx)
12655 })?;
12656 let editor = editor
12657 .await?
12658 .downcast::<Editor>()
12659 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12660 .downgrade();
12661 editor.update(&mut cx, |editor, cx| {
12662 let buffer = editor
12663 .buffer()
12664 .read(cx)
12665 .as_singleton()
12666 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12667 let buffer = buffer.read(cx);
12668 let cursor = if buffer.can_resolve(&anchor) {
12669 language::ToPoint::to_point(&anchor, buffer)
12670 } else {
12671 buffer.clip_point(position, Bias::Left)
12672 };
12673
12674 let nav_history = editor.nav_history.take();
12675 editor.change_selections(
12676 Some(Autoscroll::top_relative(offset_from_top as usize)),
12677 cx,
12678 |s| {
12679 s.select_ranges([cursor..cursor]);
12680 },
12681 );
12682 editor.nav_history = nav_history;
12683
12684 anyhow::Ok(())
12685 })??;
12686
12687 anyhow::Ok(())
12688 })
12689 .detach_and_log_err(cx);
12690 }
12691
12692 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12693 let snapshot = self.buffer.read(cx).read(cx);
12694 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12695 Some(
12696 ranges
12697 .iter()
12698 .map(move |range| {
12699 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12700 })
12701 .collect(),
12702 )
12703 }
12704
12705 fn selection_replacement_ranges(
12706 &self,
12707 range: Range<OffsetUtf16>,
12708 cx: &mut AppContext,
12709 ) -> Vec<Range<OffsetUtf16>> {
12710 let selections = self.selections.all::<OffsetUtf16>(cx);
12711 let newest_selection = selections
12712 .iter()
12713 .max_by_key(|selection| selection.id)
12714 .unwrap();
12715 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12716 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12717 let snapshot = self.buffer.read(cx).read(cx);
12718 selections
12719 .into_iter()
12720 .map(|mut selection| {
12721 selection.start.0 =
12722 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12723 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12724 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12725 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12726 })
12727 .collect()
12728 }
12729
12730 fn report_editor_event(
12731 &self,
12732 operation: &'static str,
12733 file_extension: Option<String>,
12734 cx: &AppContext,
12735 ) {
12736 if cfg!(any(test, feature = "test-support")) {
12737 return;
12738 }
12739
12740 let Some(project) = &self.project else { return };
12741
12742 // If None, we are in a file without an extension
12743 let file = self
12744 .buffer
12745 .read(cx)
12746 .as_singleton()
12747 .and_then(|b| b.read(cx).file());
12748 let file_extension = file_extension.or(file
12749 .as_ref()
12750 .and_then(|file| Path::new(file.file_name(cx)).extension())
12751 .and_then(|e| e.to_str())
12752 .map(|a| a.to_string()));
12753
12754 let vim_mode = cx
12755 .global::<SettingsStore>()
12756 .raw_user_settings()
12757 .get("vim_mode")
12758 == Some(&serde_json::Value::Bool(true));
12759
12760 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12761 == language::language_settings::InlineCompletionProvider::Copilot;
12762 let copilot_enabled_for_language = self
12763 .buffer
12764 .read(cx)
12765 .settings_at(0, cx)
12766 .show_inline_completions;
12767
12768 let project = project.read(cx);
12769 let telemetry = project.client().telemetry().clone();
12770 telemetry.report_editor_event(
12771 file_extension,
12772 vim_mode,
12773 operation,
12774 copilot_enabled,
12775 copilot_enabled_for_language,
12776 project.is_via_ssh(),
12777 )
12778 }
12779
12780 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12781 /// with each line being an array of {text, highlight} objects.
12782 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12783 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12784 return;
12785 };
12786
12787 #[derive(Serialize)]
12788 struct Chunk<'a> {
12789 text: String,
12790 highlight: Option<&'a str>,
12791 }
12792
12793 let snapshot = buffer.read(cx).snapshot();
12794 let range = self
12795 .selected_text_range(false, cx)
12796 .and_then(|selection| {
12797 if selection.range.is_empty() {
12798 None
12799 } else {
12800 Some(selection.range)
12801 }
12802 })
12803 .unwrap_or_else(|| 0..snapshot.len());
12804
12805 let chunks = snapshot.chunks(range, true);
12806 let mut lines = Vec::new();
12807 let mut line: VecDeque<Chunk> = VecDeque::new();
12808
12809 let Some(style) = self.style.as_ref() else {
12810 return;
12811 };
12812
12813 for chunk in chunks {
12814 let highlight = chunk
12815 .syntax_highlight_id
12816 .and_then(|id| id.name(&style.syntax));
12817 let mut chunk_lines = chunk.text.split('\n').peekable();
12818 while let Some(text) = chunk_lines.next() {
12819 let mut merged_with_last_token = false;
12820 if let Some(last_token) = line.back_mut() {
12821 if last_token.highlight == highlight {
12822 last_token.text.push_str(text);
12823 merged_with_last_token = true;
12824 }
12825 }
12826
12827 if !merged_with_last_token {
12828 line.push_back(Chunk {
12829 text: text.into(),
12830 highlight,
12831 });
12832 }
12833
12834 if chunk_lines.peek().is_some() {
12835 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12836 line.pop_front();
12837 }
12838 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12839 line.pop_back();
12840 }
12841
12842 lines.push(mem::take(&mut line));
12843 }
12844 }
12845 }
12846
12847 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12848 return;
12849 };
12850 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12851 }
12852
12853 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12854 &self.inlay_hint_cache
12855 }
12856
12857 pub fn replay_insert_event(
12858 &mut self,
12859 text: &str,
12860 relative_utf16_range: Option<Range<isize>>,
12861 cx: &mut ViewContext<Self>,
12862 ) {
12863 if !self.input_enabled {
12864 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12865 return;
12866 }
12867 if let Some(relative_utf16_range) = relative_utf16_range {
12868 let selections = self.selections.all::<OffsetUtf16>(cx);
12869 self.change_selections(None, cx, |s| {
12870 let new_ranges = selections.into_iter().map(|range| {
12871 let start = OffsetUtf16(
12872 range
12873 .head()
12874 .0
12875 .saturating_add_signed(relative_utf16_range.start),
12876 );
12877 let end = OffsetUtf16(
12878 range
12879 .head()
12880 .0
12881 .saturating_add_signed(relative_utf16_range.end),
12882 );
12883 start..end
12884 });
12885 s.select_ranges(new_ranges);
12886 });
12887 }
12888
12889 self.handle_input(text, cx);
12890 }
12891
12892 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12893 let Some(provider) = self.semantics_provider.as_ref() else {
12894 return false;
12895 };
12896
12897 let mut supports = false;
12898 self.buffer().read(cx).for_each_buffer(|buffer| {
12899 supports |= provider.supports_inlay_hints(buffer, cx);
12900 });
12901 supports
12902 }
12903
12904 pub fn focus(&self, cx: &mut WindowContext) {
12905 cx.focus(&self.focus_handle)
12906 }
12907
12908 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12909 self.focus_handle.is_focused(cx)
12910 }
12911
12912 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12913 cx.emit(EditorEvent::Focused);
12914
12915 if let Some(descendant) = self
12916 .last_focused_descendant
12917 .take()
12918 .and_then(|descendant| descendant.upgrade())
12919 {
12920 cx.focus(&descendant);
12921 } else {
12922 if let Some(blame) = self.blame.as_ref() {
12923 blame.update(cx, GitBlame::focus)
12924 }
12925
12926 self.blink_manager.update(cx, BlinkManager::enable);
12927 self.show_cursor_names(cx);
12928 self.buffer.update(cx, |buffer, cx| {
12929 buffer.finalize_last_transaction(cx);
12930 if self.leader_peer_id.is_none() {
12931 buffer.set_active_selections(
12932 &self.selections.disjoint_anchors(),
12933 self.selections.line_mode,
12934 self.cursor_shape,
12935 cx,
12936 );
12937 }
12938 });
12939 }
12940 }
12941
12942 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12943 cx.emit(EditorEvent::FocusedIn)
12944 }
12945
12946 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12947 if event.blurred != self.focus_handle {
12948 self.last_focused_descendant = Some(event.blurred);
12949 }
12950 }
12951
12952 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12953 self.blink_manager.update(cx, BlinkManager::disable);
12954 self.buffer
12955 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12956
12957 if let Some(blame) = self.blame.as_ref() {
12958 blame.update(cx, GitBlame::blur)
12959 }
12960 if !self.hover_state.focused(cx) {
12961 hide_hover(self, cx);
12962 }
12963
12964 self.hide_context_menu(cx);
12965 cx.emit(EditorEvent::Blurred);
12966 cx.notify();
12967 }
12968
12969 pub fn register_action<A: Action>(
12970 &mut self,
12971 listener: impl Fn(&A, &mut WindowContext) + 'static,
12972 ) -> Subscription {
12973 let id = self.next_editor_action_id.post_inc();
12974 let listener = Arc::new(listener);
12975 self.editor_actions.borrow_mut().insert(
12976 id,
12977 Box::new(move |cx| {
12978 let cx = cx.window_context();
12979 let listener = listener.clone();
12980 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12981 let action = action.downcast_ref().unwrap();
12982 if phase == DispatchPhase::Bubble {
12983 listener(action, cx)
12984 }
12985 })
12986 }),
12987 );
12988
12989 let editor_actions = self.editor_actions.clone();
12990 Subscription::new(move || {
12991 editor_actions.borrow_mut().remove(&id);
12992 })
12993 }
12994
12995 pub fn file_header_size(&self) -> u32 {
12996 FILE_HEADER_HEIGHT
12997 }
12998
12999 pub fn revert(
13000 &mut self,
13001 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13002 cx: &mut ViewContext<Self>,
13003 ) {
13004 self.buffer().update(cx, |multi_buffer, cx| {
13005 for (buffer_id, changes) in revert_changes {
13006 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13007 buffer.update(cx, |buffer, cx| {
13008 buffer.edit(
13009 changes.into_iter().map(|(range, text)| {
13010 (range, text.to_string().map(Arc::<str>::from))
13011 }),
13012 None,
13013 cx,
13014 );
13015 });
13016 }
13017 }
13018 });
13019 self.change_selections(None, cx, |selections| selections.refresh());
13020 }
13021
13022 pub fn to_pixel_point(
13023 &mut self,
13024 source: multi_buffer::Anchor,
13025 editor_snapshot: &EditorSnapshot,
13026 cx: &mut ViewContext<Self>,
13027 ) -> Option<gpui::Point<Pixels>> {
13028 let source_point = source.to_display_point(editor_snapshot);
13029 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13030 }
13031
13032 pub fn display_to_pixel_point(
13033 &mut self,
13034 source: DisplayPoint,
13035 editor_snapshot: &EditorSnapshot,
13036 cx: &mut ViewContext<Self>,
13037 ) -> Option<gpui::Point<Pixels>> {
13038 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13039 let text_layout_details = self.text_layout_details(cx);
13040 let scroll_top = text_layout_details
13041 .scroll_anchor
13042 .scroll_position(editor_snapshot)
13043 .y;
13044
13045 if source.row().as_f32() < scroll_top.floor() {
13046 return None;
13047 }
13048 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13049 let source_y = line_height * (source.row().as_f32() - scroll_top);
13050 Some(gpui::Point::new(source_x, source_y))
13051 }
13052
13053 pub fn has_active_completions_menu(&self) -> bool {
13054 self.context_menu.read().as_ref().map_or(false, |menu| {
13055 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13056 })
13057 }
13058
13059 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13060 self.addons
13061 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13062 }
13063
13064 pub fn unregister_addon<T: Addon>(&mut self) {
13065 self.addons.remove(&std::any::TypeId::of::<T>());
13066 }
13067
13068 pub fn addon<T: Addon>(&self) -> Option<&T> {
13069 let type_id = std::any::TypeId::of::<T>();
13070 self.addons
13071 .get(&type_id)
13072 .and_then(|item| item.to_any().downcast_ref::<T>())
13073 }
13074}
13075
13076fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13077 let tab_size = tab_size.get() as usize;
13078 let mut width = offset;
13079
13080 for ch in text.chars() {
13081 width += if ch == '\t' {
13082 tab_size - (width % tab_size)
13083 } else {
13084 1
13085 };
13086 }
13087
13088 width - offset
13089}
13090
13091#[cfg(test)]
13092mod tests {
13093 use super::*;
13094
13095 #[test]
13096 fn test_string_size_with_expanded_tabs() {
13097 let nz = |val| NonZeroU32::new(val).unwrap();
13098 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13099 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13100 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13101 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13102 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13103 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13104 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13105 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13106 }
13107}
13108
13109/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13110struct WordBreakingTokenizer<'a> {
13111 input: &'a str,
13112}
13113
13114impl<'a> WordBreakingTokenizer<'a> {
13115 fn new(input: &'a str) -> Self {
13116 Self { input }
13117 }
13118}
13119
13120fn is_char_ideographic(ch: char) -> bool {
13121 use unicode_script::Script::*;
13122 use unicode_script::UnicodeScript;
13123 matches!(ch.script(), Han | Tangut | Yi)
13124}
13125
13126fn is_grapheme_ideographic(text: &str) -> bool {
13127 text.chars().any(is_char_ideographic)
13128}
13129
13130fn is_grapheme_whitespace(text: &str) -> bool {
13131 text.chars().any(|x| x.is_whitespace())
13132}
13133
13134fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13135 text.chars().next().map_or(false, |ch| {
13136 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13137 })
13138}
13139
13140#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13141struct WordBreakToken<'a> {
13142 token: &'a str,
13143 grapheme_len: usize,
13144 is_whitespace: bool,
13145}
13146
13147impl<'a> Iterator for WordBreakingTokenizer<'a> {
13148 /// Yields a span, the count of graphemes in the token, and whether it was
13149 /// whitespace. Note that it also breaks at word boundaries.
13150 type Item = WordBreakToken<'a>;
13151
13152 fn next(&mut self) -> Option<Self::Item> {
13153 use unicode_segmentation::UnicodeSegmentation;
13154 if self.input.is_empty() {
13155 return None;
13156 }
13157
13158 let mut iter = self.input.graphemes(true).peekable();
13159 let mut offset = 0;
13160 let mut graphemes = 0;
13161 if let Some(first_grapheme) = iter.next() {
13162 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13163 offset += first_grapheme.len();
13164 graphemes += 1;
13165 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13166 if let Some(grapheme) = iter.peek().copied() {
13167 if should_stay_with_preceding_ideograph(grapheme) {
13168 offset += grapheme.len();
13169 graphemes += 1;
13170 }
13171 }
13172 } else {
13173 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13174 let mut next_word_bound = words.peek().copied();
13175 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13176 next_word_bound = words.next();
13177 }
13178 while let Some(grapheme) = iter.peek().copied() {
13179 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13180 break;
13181 };
13182 if is_grapheme_whitespace(grapheme) != is_whitespace {
13183 break;
13184 };
13185 offset += grapheme.len();
13186 graphemes += 1;
13187 iter.next();
13188 }
13189 }
13190 let token = &self.input[..offset];
13191 self.input = &self.input[offset..];
13192 if is_whitespace {
13193 Some(WordBreakToken {
13194 token: " ",
13195 grapheme_len: 1,
13196 is_whitespace: true,
13197 })
13198 } else {
13199 Some(WordBreakToken {
13200 token,
13201 grapheme_len: graphemes,
13202 is_whitespace: false,
13203 })
13204 }
13205 } else {
13206 None
13207 }
13208 }
13209}
13210
13211#[test]
13212fn test_word_breaking_tokenizer() {
13213 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13214 ("", &[]),
13215 (" ", &[(" ", 1, true)]),
13216 ("Ʒ", &[("Ʒ", 1, false)]),
13217 ("Ǽ", &[("Ǽ", 1, false)]),
13218 ("⋑", &[("⋑", 1, false)]),
13219 ("⋑⋑", &[("⋑⋑", 2, false)]),
13220 (
13221 "原理,进而",
13222 &[
13223 ("原", 1, false),
13224 ("理,", 2, false),
13225 ("进", 1, false),
13226 ("而", 1, false),
13227 ],
13228 ),
13229 (
13230 "hello world",
13231 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13232 ),
13233 (
13234 "hello, world",
13235 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13236 ),
13237 (
13238 " hello world",
13239 &[
13240 (" ", 1, true),
13241 ("hello", 5, false),
13242 (" ", 1, true),
13243 ("world", 5, false),
13244 ],
13245 ),
13246 (
13247 "这是什么 \n 钢笔",
13248 &[
13249 ("这", 1, false),
13250 ("是", 1, false),
13251 ("什", 1, false),
13252 ("么", 1, false),
13253 (" ", 1, true),
13254 ("钢", 1, false),
13255 ("笔", 1, false),
13256 ],
13257 ),
13258 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13259 ];
13260
13261 for (input, result) in tests {
13262 assert_eq!(
13263 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13264 result
13265 .iter()
13266 .copied()
13267 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13268 token,
13269 grapheme_len,
13270 is_whitespace,
13271 })
13272 .collect::<Vec<_>>()
13273 );
13274 }
13275}
13276
13277fn wrap_with_prefix(
13278 line_prefix: String,
13279 unwrapped_text: String,
13280 wrap_column: usize,
13281 tab_size: NonZeroU32,
13282) -> String {
13283 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13284 let mut wrapped_text = String::new();
13285 let mut current_line = line_prefix.clone();
13286
13287 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13288 let mut current_line_len = line_prefix_len;
13289 for WordBreakToken {
13290 token,
13291 grapheme_len,
13292 is_whitespace,
13293 } in tokenizer
13294 {
13295 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13296 wrapped_text.push_str(current_line.trim_end());
13297 wrapped_text.push('\n');
13298 current_line.truncate(line_prefix.len());
13299 current_line_len = line_prefix_len;
13300 if !is_whitespace {
13301 current_line.push_str(token);
13302 current_line_len += grapheme_len;
13303 }
13304 } else if !is_whitespace {
13305 current_line.push_str(token);
13306 current_line_len += grapheme_len;
13307 } else if current_line_len != line_prefix_len {
13308 current_line.push(' ');
13309 current_line_len += 1;
13310 }
13311 }
13312
13313 if !current_line.is_empty() {
13314 wrapped_text.push_str(¤t_line);
13315 }
13316 wrapped_text
13317}
13318
13319#[test]
13320fn test_wrap_with_prefix() {
13321 assert_eq!(
13322 wrap_with_prefix(
13323 "# ".to_string(),
13324 "abcdefg".to_string(),
13325 4,
13326 NonZeroU32::new(4).unwrap()
13327 ),
13328 "# abcdefg"
13329 );
13330 assert_eq!(
13331 wrap_with_prefix(
13332 "".to_string(),
13333 "\thello world".to_string(),
13334 8,
13335 NonZeroU32::new(4).unwrap()
13336 ),
13337 "hello\nworld"
13338 );
13339 assert_eq!(
13340 wrap_with_prefix(
13341 "// ".to_string(),
13342 "xx \nyy zz aa bb cc".to_string(),
13343 12,
13344 NonZeroU32::new(4).unwrap()
13345 ),
13346 "// xx yy zz\n// aa bb cc"
13347 );
13348 assert_eq!(
13349 wrap_with_prefix(
13350 String::new(),
13351 "这是什么 \n 钢笔".to_string(),
13352 3,
13353 NonZeroU32::new(4).unwrap()
13354 ),
13355 "这是什\n么 钢\n笔"
13356 );
13357}
13358
13359fn hunks_for_selections(
13360 multi_buffer_snapshot: &MultiBufferSnapshot,
13361 selections: &[Selection<Anchor>],
13362) -> Vec<MultiBufferDiffHunk> {
13363 let buffer_rows_for_selections = selections.iter().map(|selection| {
13364 let head = selection.head();
13365 let tail = selection.tail();
13366 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13367 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13368 if start > end {
13369 end..start
13370 } else {
13371 start..end
13372 }
13373 });
13374
13375 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13376}
13377
13378pub fn hunks_for_rows(
13379 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13380 multi_buffer_snapshot: &MultiBufferSnapshot,
13381) -> Vec<MultiBufferDiffHunk> {
13382 let mut hunks = Vec::new();
13383 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13384 HashMap::default();
13385 for selected_multi_buffer_rows in rows {
13386 let query_rows =
13387 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13388 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13389 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13390 // when the caret is just above or just below the deleted hunk.
13391 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13392 let related_to_selection = if allow_adjacent {
13393 hunk.row_range.overlaps(&query_rows)
13394 || hunk.row_range.start == query_rows.end
13395 || hunk.row_range.end == query_rows.start
13396 } else {
13397 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13398 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13399 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13400 || selected_multi_buffer_rows.end == hunk.row_range.start
13401 };
13402 if related_to_selection {
13403 if !processed_buffer_rows
13404 .entry(hunk.buffer_id)
13405 .or_default()
13406 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13407 {
13408 continue;
13409 }
13410 hunks.push(hunk);
13411 }
13412 }
13413 }
13414
13415 hunks
13416}
13417
13418pub trait CollaborationHub {
13419 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13420 fn user_participant_indices<'a>(
13421 &self,
13422 cx: &'a AppContext,
13423 ) -> &'a HashMap<u64, ParticipantIndex>;
13424 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13425}
13426
13427impl CollaborationHub for Model<Project> {
13428 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13429 self.read(cx).collaborators()
13430 }
13431
13432 fn user_participant_indices<'a>(
13433 &self,
13434 cx: &'a AppContext,
13435 ) -> &'a HashMap<u64, ParticipantIndex> {
13436 self.read(cx).user_store().read(cx).participant_indices()
13437 }
13438
13439 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13440 let this = self.read(cx);
13441 let user_ids = this.collaborators().values().map(|c| c.user_id);
13442 this.user_store().read_with(cx, |user_store, cx| {
13443 user_store.participant_names(user_ids, cx)
13444 })
13445 }
13446}
13447
13448pub trait SemanticsProvider {
13449 fn hover(
13450 &self,
13451 buffer: &Model<Buffer>,
13452 position: text::Anchor,
13453 cx: &mut AppContext,
13454 ) -> Option<Task<Vec<project::Hover>>>;
13455
13456 fn inlay_hints(
13457 &self,
13458 buffer_handle: Model<Buffer>,
13459 range: Range<text::Anchor>,
13460 cx: &mut AppContext,
13461 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13462
13463 fn resolve_inlay_hint(
13464 &self,
13465 hint: InlayHint,
13466 buffer_handle: Model<Buffer>,
13467 server_id: LanguageServerId,
13468 cx: &mut AppContext,
13469 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13470
13471 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13472
13473 fn document_highlights(
13474 &self,
13475 buffer: &Model<Buffer>,
13476 position: text::Anchor,
13477 cx: &mut AppContext,
13478 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13479
13480 fn definitions(
13481 &self,
13482 buffer: &Model<Buffer>,
13483 position: text::Anchor,
13484 kind: GotoDefinitionKind,
13485 cx: &mut AppContext,
13486 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13487
13488 fn range_for_rename(
13489 &self,
13490 buffer: &Model<Buffer>,
13491 position: text::Anchor,
13492 cx: &mut AppContext,
13493 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13494
13495 fn perform_rename(
13496 &self,
13497 buffer: &Model<Buffer>,
13498 position: text::Anchor,
13499 new_name: String,
13500 cx: &mut AppContext,
13501 ) -> Option<Task<Result<ProjectTransaction>>>;
13502}
13503
13504pub trait CompletionProvider {
13505 fn completions(
13506 &self,
13507 buffer: &Model<Buffer>,
13508 buffer_position: text::Anchor,
13509 trigger: CompletionContext,
13510 cx: &mut ViewContext<Editor>,
13511 ) -> Task<Result<Vec<Completion>>>;
13512
13513 fn resolve_completions(
13514 &self,
13515 buffer: Model<Buffer>,
13516 completion_indices: Vec<usize>,
13517 completions: Arc<RwLock<Box<[Completion]>>>,
13518 cx: &mut ViewContext<Editor>,
13519 ) -> Task<Result<bool>>;
13520
13521 fn apply_additional_edits_for_completion(
13522 &self,
13523 buffer: Model<Buffer>,
13524 completion: Completion,
13525 push_to_history: bool,
13526 cx: &mut ViewContext<Editor>,
13527 ) -> Task<Result<Option<language::Transaction>>>;
13528
13529 fn is_completion_trigger(
13530 &self,
13531 buffer: &Model<Buffer>,
13532 position: language::Anchor,
13533 text: &str,
13534 trigger_in_words: bool,
13535 cx: &mut ViewContext<Editor>,
13536 ) -> bool;
13537
13538 fn sort_completions(&self) -> bool {
13539 true
13540 }
13541}
13542
13543pub trait CodeActionProvider {
13544 fn code_actions(
13545 &self,
13546 buffer: &Model<Buffer>,
13547 range: Range<text::Anchor>,
13548 cx: &mut WindowContext,
13549 ) -> Task<Result<Vec<CodeAction>>>;
13550
13551 fn apply_code_action(
13552 &self,
13553 buffer_handle: Model<Buffer>,
13554 action: CodeAction,
13555 excerpt_id: ExcerptId,
13556 push_to_history: bool,
13557 cx: &mut WindowContext,
13558 ) -> Task<Result<ProjectTransaction>>;
13559}
13560
13561impl CodeActionProvider for Model<Project> {
13562 fn code_actions(
13563 &self,
13564 buffer: &Model<Buffer>,
13565 range: Range<text::Anchor>,
13566 cx: &mut WindowContext,
13567 ) -> Task<Result<Vec<CodeAction>>> {
13568 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13569 }
13570
13571 fn apply_code_action(
13572 &self,
13573 buffer_handle: Model<Buffer>,
13574 action: CodeAction,
13575 _excerpt_id: ExcerptId,
13576 push_to_history: bool,
13577 cx: &mut WindowContext,
13578 ) -> Task<Result<ProjectTransaction>> {
13579 self.update(cx, |project, cx| {
13580 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13581 })
13582 }
13583}
13584
13585fn snippet_completions(
13586 project: &Project,
13587 buffer: &Model<Buffer>,
13588 buffer_position: text::Anchor,
13589 cx: &mut AppContext,
13590) -> Vec<Completion> {
13591 let language = buffer.read(cx).language_at(buffer_position);
13592 let language_name = language.as_ref().map(|language| language.lsp_id());
13593 let snippet_store = project.snippets().read(cx);
13594 let snippets = snippet_store.snippets_for(language_name, cx);
13595
13596 if snippets.is_empty() {
13597 return vec![];
13598 }
13599 let snapshot = buffer.read(cx).text_snapshot();
13600 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13601
13602 let scope = language.map(|language| language.default_scope());
13603 let classifier = CharClassifier::new(scope).for_completion(true);
13604 let mut last_word = chars
13605 .take_while(|c| classifier.is_word(*c))
13606 .collect::<String>();
13607 last_word = last_word.chars().rev().collect();
13608 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13609 let to_lsp = |point: &text::Anchor| {
13610 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13611 point_to_lsp(end)
13612 };
13613 let lsp_end = to_lsp(&buffer_position);
13614 snippets
13615 .into_iter()
13616 .filter_map(|snippet| {
13617 let matching_prefix = snippet
13618 .prefix
13619 .iter()
13620 .find(|prefix| prefix.starts_with(&last_word))?;
13621 let start = as_offset - last_word.len();
13622 let start = snapshot.anchor_before(start);
13623 let range = start..buffer_position;
13624 let lsp_start = to_lsp(&start);
13625 let lsp_range = lsp::Range {
13626 start: lsp_start,
13627 end: lsp_end,
13628 };
13629 Some(Completion {
13630 old_range: range,
13631 new_text: snippet.body.clone(),
13632 label: CodeLabel {
13633 text: matching_prefix.clone(),
13634 runs: vec![],
13635 filter_range: 0..matching_prefix.len(),
13636 },
13637 server_id: LanguageServerId(usize::MAX),
13638 documentation: snippet.description.clone().map(Documentation::SingleLine),
13639 lsp_completion: lsp::CompletionItem {
13640 label: snippet.prefix.first().unwrap().clone(),
13641 kind: Some(CompletionItemKind::SNIPPET),
13642 label_details: snippet.description.as_ref().map(|description| {
13643 lsp::CompletionItemLabelDetails {
13644 detail: Some(description.clone()),
13645 description: None,
13646 }
13647 }),
13648 insert_text_format: Some(InsertTextFormat::SNIPPET),
13649 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13650 lsp::InsertReplaceEdit {
13651 new_text: snippet.body.clone(),
13652 insert: lsp_range,
13653 replace: lsp_range,
13654 },
13655 )),
13656 filter_text: Some(snippet.body.clone()),
13657 sort_text: Some(char::MAX.to_string()),
13658 ..Default::default()
13659 },
13660 confirm: None,
13661 })
13662 })
13663 .collect()
13664}
13665
13666impl CompletionProvider for Model<Project> {
13667 fn completions(
13668 &self,
13669 buffer: &Model<Buffer>,
13670 buffer_position: text::Anchor,
13671 options: CompletionContext,
13672 cx: &mut ViewContext<Editor>,
13673 ) -> Task<Result<Vec<Completion>>> {
13674 self.update(cx, |project, cx| {
13675 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13676 let project_completions = project.completions(buffer, buffer_position, options, cx);
13677 cx.background_executor().spawn(async move {
13678 let mut completions = project_completions.await?;
13679 //let snippets = snippets.into_iter().;
13680 completions.extend(snippets);
13681 Ok(completions)
13682 })
13683 })
13684 }
13685
13686 fn resolve_completions(
13687 &self,
13688 buffer: Model<Buffer>,
13689 completion_indices: Vec<usize>,
13690 completions: Arc<RwLock<Box<[Completion]>>>,
13691 cx: &mut ViewContext<Editor>,
13692 ) -> Task<Result<bool>> {
13693 self.update(cx, |project, cx| {
13694 project.resolve_completions(buffer, completion_indices, completions, cx)
13695 })
13696 }
13697
13698 fn apply_additional_edits_for_completion(
13699 &self,
13700 buffer: Model<Buffer>,
13701 completion: Completion,
13702 push_to_history: bool,
13703 cx: &mut ViewContext<Editor>,
13704 ) -> Task<Result<Option<language::Transaction>>> {
13705 self.update(cx, |project, cx| {
13706 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13707 })
13708 }
13709
13710 fn is_completion_trigger(
13711 &self,
13712 buffer: &Model<Buffer>,
13713 position: language::Anchor,
13714 text: &str,
13715 trigger_in_words: bool,
13716 cx: &mut ViewContext<Editor>,
13717 ) -> bool {
13718 if !EditorSettings::get_global(cx).show_completions_on_input {
13719 return false;
13720 }
13721
13722 let mut chars = text.chars();
13723 let char = if let Some(char) = chars.next() {
13724 char
13725 } else {
13726 return false;
13727 };
13728 if chars.next().is_some() {
13729 return false;
13730 }
13731
13732 let buffer = buffer.read(cx);
13733 let classifier = buffer
13734 .snapshot()
13735 .char_classifier_at(position)
13736 .for_completion(true);
13737 if trigger_in_words && classifier.is_word(char) {
13738 return true;
13739 }
13740
13741 buffer
13742 .completion_triggers()
13743 .iter()
13744 .any(|string| string == text)
13745 }
13746}
13747
13748impl SemanticsProvider for Model<Project> {
13749 fn hover(
13750 &self,
13751 buffer: &Model<Buffer>,
13752 position: text::Anchor,
13753 cx: &mut AppContext,
13754 ) -> Option<Task<Vec<project::Hover>>> {
13755 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13756 }
13757
13758 fn document_highlights(
13759 &self,
13760 buffer: &Model<Buffer>,
13761 position: text::Anchor,
13762 cx: &mut AppContext,
13763 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13764 Some(self.update(cx, |project, cx| {
13765 project.document_highlights(buffer, position, cx)
13766 }))
13767 }
13768
13769 fn definitions(
13770 &self,
13771 buffer: &Model<Buffer>,
13772 position: text::Anchor,
13773 kind: GotoDefinitionKind,
13774 cx: &mut AppContext,
13775 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13776 Some(self.update(cx, |project, cx| match kind {
13777 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13778 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13779 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13780 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13781 }))
13782 }
13783
13784 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13785 // TODO: make this work for remote projects
13786 self.read(cx)
13787 .language_servers_for_buffer(buffer.read(cx), cx)
13788 .any(
13789 |(_, server)| match server.capabilities().inlay_hint_provider {
13790 Some(lsp::OneOf::Left(enabled)) => enabled,
13791 Some(lsp::OneOf::Right(_)) => true,
13792 None => false,
13793 },
13794 )
13795 }
13796
13797 fn inlay_hints(
13798 &self,
13799 buffer_handle: Model<Buffer>,
13800 range: Range<text::Anchor>,
13801 cx: &mut AppContext,
13802 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13803 Some(self.update(cx, |project, cx| {
13804 project.inlay_hints(buffer_handle, range, cx)
13805 }))
13806 }
13807
13808 fn resolve_inlay_hint(
13809 &self,
13810 hint: InlayHint,
13811 buffer_handle: Model<Buffer>,
13812 server_id: LanguageServerId,
13813 cx: &mut AppContext,
13814 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13815 Some(self.update(cx, |project, cx| {
13816 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13817 }))
13818 }
13819
13820 fn range_for_rename(
13821 &self,
13822 buffer: &Model<Buffer>,
13823 position: text::Anchor,
13824 cx: &mut AppContext,
13825 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13826 Some(self.update(cx, |project, cx| {
13827 project.prepare_rename(buffer.clone(), position, cx)
13828 }))
13829 }
13830
13831 fn perform_rename(
13832 &self,
13833 buffer: &Model<Buffer>,
13834 position: text::Anchor,
13835 new_name: String,
13836 cx: &mut AppContext,
13837 ) -> Option<Task<Result<ProjectTransaction>>> {
13838 Some(self.update(cx, |project, cx| {
13839 project.perform_rename(buffer.clone(), position, new_name, cx)
13840 }))
13841 }
13842}
13843
13844fn inlay_hint_settings(
13845 location: Anchor,
13846 snapshot: &MultiBufferSnapshot,
13847 cx: &mut ViewContext<'_, Editor>,
13848) -> InlayHintSettings {
13849 let file = snapshot.file_at(location);
13850 let language = snapshot.language_at(location).map(|l| l.name());
13851 language_settings(language, file, cx).inlay_hints
13852}
13853
13854fn consume_contiguous_rows(
13855 contiguous_row_selections: &mut Vec<Selection<Point>>,
13856 selection: &Selection<Point>,
13857 display_map: &DisplaySnapshot,
13858 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13859) -> (MultiBufferRow, MultiBufferRow) {
13860 contiguous_row_selections.push(selection.clone());
13861 let start_row = MultiBufferRow(selection.start.row);
13862 let mut end_row = ending_row(selection, display_map);
13863
13864 while let Some(next_selection) = selections.peek() {
13865 if next_selection.start.row <= end_row.0 {
13866 end_row = ending_row(next_selection, display_map);
13867 contiguous_row_selections.push(selections.next().unwrap().clone());
13868 } else {
13869 break;
13870 }
13871 }
13872 (start_row, end_row)
13873}
13874
13875fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13876 if next_selection.end.column > 0 || next_selection.is_empty() {
13877 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13878 } else {
13879 MultiBufferRow(next_selection.end.row)
13880 }
13881}
13882
13883impl EditorSnapshot {
13884 pub fn remote_selections_in_range<'a>(
13885 &'a self,
13886 range: &'a Range<Anchor>,
13887 collaboration_hub: &dyn CollaborationHub,
13888 cx: &'a AppContext,
13889 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13890 let participant_names = collaboration_hub.user_names(cx);
13891 let participant_indices = collaboration_hub.user_participant_indices(cx);
13892 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13893 let collaborators_by_replica_id = collaborators_by_peer_id
13894 .iter()
13895 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13896 .collect::<HashMap<_, _>>();
13897 self.buffer_snapshot
13898 .selections_in_range(range, false)
13899 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13900 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13901 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13902 let user_name = participant_names.get(&collaborator.user_id).cloned();
13903 Some(RemoteSelection {
13904 replica_id,
13905 selection,
13906 cursor_shape,
13907 line_mode,
13908 participant_index,
13909 peer_id: collaborator.peer_id,
13910 user_name,
13911 })
13912 })
13913 }
13914
13915 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13916 self.display_snapshot.buffer_snapshot.language_at(position)
13917 }
13918
13919 pub fn is_focused(&self) -> bool {
13920 self.is_focused
13921 }
13922
13923 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13924 self.placeholder_text.as_ref()
13925 }
13926
13927 pub fn scroll_position(&self) -> gpui::Point<f32> {
13928 self.scroll_anchor.scroll_position(&self.display_snapshot)
13929 }
13930
13931 fn gutter_dimensions(
13932 &self,
13933 font_id: FontId,
13934 font_size: Pixels,
13935 em_width: Pixels,
13936 em_advance: Pixels,
13937 max_line_number_width: Pixels,
13938 cx: &AppContext,
13939 ) -> GutterDimensions {
13940 if !self.show_gutter {
13941 return GutterDimensions::default();
13942 }
13943 let descent = cx.text_system().descent(font_id, font_size);
13944
13945 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13946 matches!(
13947 ProjectSettings::get_global(cx).git.git_gutter,
13948 Some(GitGutterSetting::TrackedFiles)
13949 )
13950 });
13951 let gutter_settings = EditorSettings::get_global(cx).gutter;
13952 let show_line_numbers = self
13953 .show_line_numbers
13954 .unwrap_or(gutter_settings.line_numbers);
13955 let line_gutter_width = if show_line_numbers {
13956 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13957 let min_width_for_number_on_gutter = em_advance * 4.0;
13958 max_line_number_width.max(min_width_for_number_on_gutter)
13959 } else {
13960 0.0.into()
13961 };
13962
13963 let show_code_actions = self
13964 .show_code_actions
13965 .unwrap_or(gutter_settings.code_actions);
13966
13967 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13968
13969 let git_blame_entries_width =
13970 self.git_blame_gutter_max_author_length
13971 .map(|max_author_length| {
13972 // Length of the author name, but also space for the commit hash,
13973 // the spacing and the timestamp.
13974 let max_char_count = max_author_length
13975 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13976 + 7 // length of commit sha
13977 + 14 // length of max relative timestamp ("60 minutes ago")
13978 + 4; // gaps and margins
13979
13980 em_advance * max_char_count
13981 });
13982
13983 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13984 left_padding += if show_code_actions || show_runnables {
13985 em_width * 3.0
13986 } else if show_git_gutter && show_line_numbers {
13987 em_width * 2.0
13988 } else if show_git_gutter || show_line_numbers {
13989 em_width
13990 } else {
13991 px(0.)
13992 };
13993
13994 let right_padding = if gutter_settings.folds && show_line_numbers {
13995 em_width * 4.0
13996 } else if gutter_settings.folds {
13997 em_width * 3.0
13998 } else if show_line_numbers {
13999 em_width
14000 } else {
14001 px(0.)
14002 };
14003
14004 GutterDimensions {
14005 left_padding,
14006 right_padding,
14007 width: line_gutter_width + left_padding + right_padding,
14008 margin: -descent,
14009 git_blame_entries_width,
14010 }
14011 }
14012
14013 pub fn render_fold_toggle(
14014 &self,
14015 buffer_row: MultiBufferRow,
14016 row_contains_cursor: bool,
14017 editor: View<Editor>,
14018 cx: &mut WindowContext,
14019 ) -> Option<AnyElement> {
14020 let folded = self.is_line_folded(buffer_row);
14021
14022 if let Some(crease) = self
14023 .crease_snapshot
14024 .query_row(buffer_row, &self.buffer_snapshot)
14025 {
14026 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14027 if folded {
14028 editor.update(cx, |editor, cx| {
14029 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14030 });
14031 } else {
14032 editor.update(cx, |editor, cx| {
14033 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14034 });
14035 }
14036 });
14037
14038 Some((crease.render_toggle)(
14039 buffer_row,
14040 folded,
14041 toggle_callback,
14042 cx,
14043 ))
14044 } else if folded
14045 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14046 {
14047 Some(
14048 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14049 .selected(folded)
14050 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14051 if folded {
14052 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14053 } else {
14054 this.fold_at(&FoldAt { buffer_row }, cx);
14055 }
14056 }))
14057 .into_any_element(),
14058 )
14059 } else {
14060 None
14061 }
14062 }
14063
14064 pub fn render_crease_trailer(
14065 &self,
14066 buffer_row: MultiBufferRow,
14067 cx: &mut WindowContext,
14068 ) -> Option<AnyElement> {
14069 let folded = self.is_line_folded(buffer_row);
14070 let crease = self
14071 .crease_snapshot
14072 .query_row(buffer_row, &self.buffer_snapshot)?;
14073 Some((crease.render_trailer)(buffer_row, folded, cx))
14074 }
14075}
14076
14077impl Deref for EditorSnapshot {
14078 type Target = DisplaySnapshot;
14079
14080 fn deref(&self) -> &Self::Target {
14081 &self.display_snapshot
14082 }
14083}
14084
14085#[derive(Clone, Debug, PartialEq, Eq)]
14086pub enum EditorEvent {
14087 InputIgnored {
14088 text: Arc<str>,
14089 },
14090 InputHandled {
14091 utf16_range_to_replace: Option<Range<isize>>,
14092 text: Arc<str>,
14093 },
14094 ExcerptsAdded {
14095 buffer: Model<Buffer>,
14096 predecessor: ExcerptId,
14097 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14098 },
14099 ExcerptsRemoved {
14100 ids: Vec<ExcerptId>,
14101 },
14102 ExcerptsEdited {
14103 ids: Vec<ExcerptId>,
14104 },
14105 ExcerptsExpanded {
14106 ids: Vec<ExcerptId>,
14107 },
14108 BufferEdited,
14109 Edited {
14110 transaction_id: clock::Lamport,
14111 },
14112 Reparsed(BufferId),
14113 Focused,
14114 FocusedIn,
14115 Blurred,
14116 DirtyChanged,
14117 Saved,
14118 TitleChanged,
14119 DiffBaseChanged,
14120 SelectionsChanged {
14121 local: bool,
14122 },
14123 ScrollPositionChanged {
14124 local: bool,
14125 autoscroll: bool,
14126 },
14127 Closed,
14128 TransactionUndone {
14129 transaction_id: clock::Lamport,
14130 },
14131 TransactionBegun {
14132 transaction_id: clock::Lamport,
14133 },
14134 Reloaded,
14135 CursorShapeChanged,
14136}
14137
14138impl EventEmitter<EditorEvent> for Editor {}
14139
14140impl FocusableView for Editor {
14141 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14142 self.focus_handle.clone()
14143 }
14144}
14145
14146impl Render for Editor {
14147 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14148 let settings = ThemeSettings::get_global(cx);
14149
14150 let mut text_style = match self.mode {
14151 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14152 color: cx.theme().colors().editor_foreground,
14153 font_family: settings.ui_font.family.clone(),
14154 font_features: settings.ui_font.features.clone(),
14155 font_fallbacks: settings.ui_font.fallbacks.clone(),
14156 font_size: rems(0.875).into(),
14157 font_weight: settings.ui_font.weight,
14158 line_height: relative(settings.buffer_line_height.value()),
14159 ..Default::default()
14160 },
14161 EditorMode::Full => TextStyle {
14162 color: cx.theme().colors().editor_foreground,
14163 font_family: settings.buffer_font.family.clone(),
14164 font_features: settings.buffer_font.features.clone(),
14165 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14166 font_size: settings.buffer_font_size(cx).into(),
14167 font_weight: settings.buffer_font.weight,
14168 line_height: relative(settings.buffer_line_height.value()),
14169 ..Default::default()
14170 },
14171 };
14172 if let Some(text_style_refinement) = &self.text_style_refinement {
14173 text_style.refine(text_style_refinement)
14174 }
14175
14176 let background = match self.mode {
14177 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14178 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14179 EditorMode::Full => cx.theme().colors().editor_background,
14180 };
14181
14182 EditorElement::new(
14183 cx.view(),
14184 EditorStyle {
14185 background,
14186 local_player: cx.theme().players().local(),
14187 text: text_style,
14188 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14189 syntax: cx.theme().syntax().clone(),
14190 status: cx.theme().status().clone(),
14191 inlay_hints_style: make_inlay_hints_style(cx),
14192 suggestions_style: HighlightStyle {
14193 color: Some(cx.theme().status().predictive),
14194 ..HighlightStyle::default()
14195 },
14196 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14197 },
14198 )
14199 }
14200}
14201
14202impl ViewInputHandler for Editor {
14203 fn text_for_range(
14204 &mut self,
14205 range_utf16: Range<usize>,
14206 cx: &mut ViewContext<Self>,
14207 ) -> Option<String> {
14208 Some(
14209 self.buffer
14210 .read(cx)
14211 .read(cx)
14212 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14213 .collect(),
14214 )
14215 }
14216
14217 fn selected_text_range(
14218 &mut self,
14219 ignore_disabled_input: bool,
14220 cx: &mut ViewContext<Self>,
14221 ) -> Option<UTF16Selection> {
14222 // Prevent the IME menu from appearing when holding down an alphabetic key
14223 // while input is disabled.
14224 if !ignore_disabled_input && !self.input_enabled {
14225 return None;
14226 }
14227
14228 let selection = self.selections.newest::<OffsetUtf16>(cx);
14229 let range = selection.range();
14230
14231 Some(UTF16Selection {
14232 range: range.start.0..range.end.0,
14233 reversed: selection.reversed,
14234 })
14235 }
14236
14237 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14238 let snapshot = self.buffer.read(cx).read(cx);
14239 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14240 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14241 }
14242
14243 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14244 self.clear_highlights::<InputComposition>(cx);
14245 self.ime_transaction.take();
14246 }
14247
14248 fn replace_text_in_range(
14249 &mut self,
14250 range_utf16: Option<Range<usize>>,
14251 text: &str,
14252 cx: &mut ViewContext<Self>,
14253 ) {
14254 if !self.input_enabled {
14255 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14256 return;
14257 }
14258
14259 self.transact(cx, |this, cx| {
14260 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14261 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14262 Some(this.selection_replacement_ranges(range_utf16, cx))
14263 } else {
14264 this.marked_text_ranges(cx)
14265 };
14266
14267 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14268 let newest_selection_id = this.selections.newest_anchor().id;
14269 this.selections
14270 .all::<OffsetUtf16>(cx)
14271 .iter()
14272 .zip(ranges_to_replace.iter())
14273 .find_map(|(selection, range)| {
14274 if selection.id == newest_selection_id {
14275 Some(
14276 (range.start.0 as isize - selection.head().0 as isize)
14277 ..(range.end.0 as isize - selection.head().0 as isize),
14278 )
14279 } else {
14280 None
14281 }
14282 })
14283 });
14284
14285 cx.emit(EditorEvent::InputHandled {
14286 utf16_range_to_replace: range_to_replace,
14287 text: text.into(),
14288 });
14289
14290 if let Some(new_selected_ranges) = new_selected_ranges {
14291 this.change_selections(None, cx, |selections| {
14292 selections.select_ranges(new_selected_ranges)
14293 });
14294 this.backspace(&Default::default(), cx);
14295 }
14296
14297 this.handle_input(text, cx);
14298 });
14299
14300 if let Some(transaction) = self.ime_transaction {
14301 self.buffer.update(cx, |buffer, cx| {
14302 buffer.group_until_transaction(transaction, cx);
14303 });
14304 }
14305
14306 self.unmark_text(cx);
14307 }
14308
14309 fn replace_and_mark_text_in_range(
14310 &mut self,
14311 range_utf16: Option<Range<usize>>,
14312 text: &str,
14313 new_selected_range_utf16: Option<Range<usize>>,
14314 cx: &mut ViewContext<Self>,
14315 ) {
14316 if !self.input_enabled {
14317 return;
14318 }
14319
14320 let transaction = self.transact(cx, |this, cx| {
14321 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14322 let snapshot = this.buffer.read(cx).read(cx);
14323 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14324 for marked_range in &mut marked_ranges {
14325 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14326 marked_range.start.0 += relative_range_utf16.start;
14327 marked_range.start =
14328 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14329 marked_range.end =
14330 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14331 }
14332 }
14333 Some(marked_ranges)
14334 } else if let Some(range_utf16) = range_utf16 {
14335 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14336 Some(this.selection_replacement_ranges(range_utf16, cx))
14337 } else {
14338 None
14339 };
14340
14341 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14342 let newest_selection_id = this.selections.newest_anchor().id;
14343 this.selections
14344 .all::<OffsetUtf16>(cx)
14345 .iter()
14346 .zip(ranges_to_replace.iter())
14347 .find_map(|(selection, range)| {
14348 if selection.id == newest_selection_id {
14349 Some(
14350 (range.start.0 as isize - selection.head().0 as isize)
14351 ..(range.end.0 as isize - selection.head().0 as isize),
14352 )
14353 } else {
14354 None
14355 }
14356 })
14357 });
14358
14359 cx.emit(EditorEvent::InputHandled {
14360 utf16_range_to_replace: range_to_replace,
14361 text: text.into(),
14362 });
14363
14364 if let Some(ranges) = ranges_to_replace {
14365 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14366 }
14367
14368 let marked_ranges = {
14369 let snapshot = this.buffer.read(cx).read(cx);
14370 this.selections
14371 .disjoint_anchors()
14372 .iter()
14373 .map(|selection| {
14374 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14375 })
14376 .collect::<Vec<_>>()
14377 };
14378
14379 if text.is_empty() {
14380 this.unmark_text(cx);
14381 } else {
14382 this.highlight_text::<InputComposition>(
14383 marked_ranges.clone(),
14384 HighlightStyle {
14385 underline: Some(UnderlineStyle {
14386 thickness: px(1.),
14387 color: None,
14388 wavy: false,
14389 }),
14390 ..Default::default()
14391 },
14392 cx,
14393 );
14394 }
14395
14396 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14397 let use_autoclose = this.use_autoclose;
14398 let use_auto_surround = this.use_auto_surround;
14399 this.set_use_autoclose(false);
14400 this.set_use_auto_surround(false);
14401 this.handle_input(text, cx);
14402 this.set_use_autoclose(use_autoclose);
14403 this.set_use_auto_surround(use_auto_surround);
14404
14405 if let Some(new_selected_range) = new_selected_range_utf16 {
14406 let snapshot = this.buffer.read(cx).read(cx);
14407 let new_selected_ranges = marked_ranges
14408 .into_iter()
14409 .map(|marked_range| {
14410 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14411 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14412 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14413 snapshot.clip_offset_utf16(new_start, Bias::Left)
14414 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14415 })
14416 .collect::<Vec<_>>();
14417
14418 drop(snapshot);
14419 this.change_selections(None, cx, |selections| {
14420 selections.select_ranges(new_selected_ranges)
14421 });
14422 }
14423 });
14424
14425 self.ime_transaction = self.ime_transaction.or(transaction);
14426 if let Some(transaction) = self.ime_transaction {
14427 self.buffer.update(cx, |buffer, cx| {
14428 buffer.group_until_transaction(transaction, cx);
14429 });
14430 }
14431
14432 if self.text_highlights::<InputComposition>(cx).is_none() {
14433 self.ime_transaction.take();
14434 }
14435 }
14436
14437 fn bounds_for_range(
14438 &mut self,
14439 range_utf16: Range<usize>,
14440 element_bounds: gpui::Bounds<Pixels>,
14441 cx: &mut ViewContext<Self>,
14442 ) -> Option<gpui::Bounds<Pixels>> {
14443 let text_layout_details = self.text_layout_details(cx);
14444 let style = &text_layout_details.editor_style;
14445 let font_id = cx.text_system().resolve_font(&style.text.font());
14446 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14447 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14448
14449 let em_width = cx
14450 .text_system()
14451 .typographic_bounds(font_id, font_size, 'm')
14452 .unwrap()
14453 .size
14454 .width;
14455
14456 let snapshot = self.snapshot(cx);
14457 let scroll_position = snapshot.scroll_position();
14458 let scroll_left = scroll_position.x * em_width;
14459
14460 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14461 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14462 + self.gutter_dimensions.width;
14463 let y = line_height * (start.row().as_f32() - scroll_position.y);
14464
14465 Some(Bounds {
14466 origin: element_bounds.origin + point(x, y),
14467 size: size(em_width, line_height),
14468 })
14469 }
14470}
14471
14472trait SelectionExt {
14473 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14474 fn spanned_rows(
14475 &self,
14476 include_end_if_at_line_start: bool,
14477 map: &DisplaySnapshot,
14478 ) -> Range<MultiBufferRow>;
14479}
14480
14481impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14482 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14483 let start = self
14484 .start
14485 .to_point(&map.buffer_snapshot)
14486 .to_display_point(map);
14487 let end = self
14488 .end
14489 .to_point(&map.buffer_snapshot)
14490 .to_display_point(map);
14491 if self.reversed {
14492 end..start
14493 } else {
14494 start..end
14495 }
14496 }
14497
14498 fn spanned_rows(
14499 &self,
14500 include_end_if_at_line_start: bool,
14501 map: &DisplaySnapshot,
14502 ) -> Range<MultiBufferRow> {
14503 let start = self.start.to_point(&map.buffer_snapshot);
14504 let mut end = self.end.to_point(&map.buffer_snapshot);
14505 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14506 end.row -= 1;
14507 }
14508
14509 let buffer_start = map.prev_line_boundary(start).0;
14510 let buffer_end = map.next_line_boundary(end).0;
14511 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14512 }
14513}
14514
14515impl<T: InvalidationRegion> InvalidationStack<T> {
14516 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14517 where
14518 S: Clone + ToOffset,
14519 {
14520 while let Some(region) = self.last() {
14521 let all_selections_inside_invalidation_ranges =
14522 if selections.len() == region.ranges().len() {
14523 selections
14524 .iter()
14525 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14526 .all(|(selection, invalidation_range)| {
14527 let head = selection.head().to_offset(buffer);
14528 invalidation_range.start <= head && invalidation_range.end >= head
14529 })
14530 } else {
14531 false
14532 };
14533
14534 if all_selections_inside_invalidation_ranges {
14535 break;
14536 } else {
14537 self.pop();
14538 }
14539 }
14540 }
14541}
14542
14543impl<T> Default for InvalidationStack<T> {
14544 fn default() -> Self {
14545 Self(Default::default())
14546 }
14547}
14548
14549impl<T> Deref for InvalidationStack<T> {
14550 type Target = Vec<T>;
14551
14552 fn deref(&self) -> &Self::Target {
14553 &self.0
14554 }
14555}
14556
14557impl<T> DerefMut for InvalidationStack<T> {
14558 fn deref_mut(&mut self) -> &mut Self::Target {
14559 &mut self.0
14560 }
14561}
14562
14563impl InvalidationRegion for SnippetState {
14564 fn ranges(&self) -> &[Range<Anchor>] {
14565 &self.ranges[self.active_index]
14566 }
14567}
14568
14569pub fn diagnostic_block_renderer(
14570 diagnostic: Diagnostic,
14571 max_message_rows: Option<u8>,
14572 allow_closing: bool,
14573 _is_valid: bool,
14574) -> RenderBlock {
14575 let (text_without_backticks, code_ranges) =
14576 highlight_diagnostic_message(&diagnostic, max_message_rows);
14577
14578 Box::new(move |cx: &mut BlockContext| {
14579 let group_id: SharedString = cx.block_id.to_string().into();
14580
14581 let mut text_style = cx.text_style().clone();
14582 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14583 let theme_settings = ThemeSettings::get_global(cx);
14584 text_style.font_family = theme_settings.buffer_font.family.clone();
14585 text_style.font_style = theme_settings.buffer_font.style;
14586 text_style.font_features = theme_settings.buffer_font.features.clone();
14587 text_style.font_weight = theme_settings.buffer_font.weight;
14588
14589 let multi_line_diagnostic = diagnostic.message.contains('\n');
14590
14591 let buttons = |diagnostic: &Diagnostic| {
14592 if multi_line_diagnostic {
14593 v_flex()
14594 } else {
14595 h_flex()
14596 }
14597 .when(allow_closing, |div| {
14598 div.children(diagnostic.is_primary.then(|| {
14599 IconButton::new("close-block", IconName::XCircle)
14600 .icon_color(Color::Muted)
14601 .size(ButtonSize::Compact)
14602 .style(ButtonStyle::Transparent)
14603 .visible_on_hover(group_id.clone())
14604 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14605 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14606 }))
14607 })
14608 .child(
14609 IconButton::new("copy-block", IconName::Copy)
14610 .icon_color(Color::Muted)
14611 .size(ButtonSize::Compact)
14612 .style(ButtonStyle::Transparent)
14613 .visible_on_hover(group_id.clone())
14614 .on_click({
14615 let message = diagnostic.message.clone();
14616 move |_click, cx| {
14617 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14618 }
14619 })
14620 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14621 )
14622 };
14623
14624 let icon_size = buttons(&diagnostic)
14625 .into_any_element()
14626 .layout_as_root(AvailableSpace::min_size(), cx);
14627
14628 h_flex()
14629 .id(cx.block_id)
14630 .group(group_id.clone())
14631 .relative()
14632 .size_full()
14633 .pl(cx.gutter_dimensions.width)
14634 .w(cx.max_width - cx.gutter_dimensions.full_width())
14635 .child(
14636 div()
14637 .flex()
14638 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14639 .flex_shrink(),
14640 )
14641 .child(buttons(&diagnostic))
14642 .child(div().flex().flex_shrink_0().child(
14643 StyledText::new(text_without_backticks.clone()).with_highlights(
14644 &text_style,
14645 code_ranges.iter().map(|range| {
14646 (
14647 range.clone(),
14648 HighlightStyle {
14649 font_weight: Some(FontWeight::BOLD),
14650 ..Default::default()
14651 },
14652 )
14653 }),
14654 ),
14655 ))
14656 .into_any_element()
14657 })
14658}
14659
14660pub fn highlight_diagnostic_message(
14661 diagnostic: &Diagnostic,
14662 mut max_message_rows: Option<u8>,
14663) -> (SharedString, Vec<Range<usize>>) {
14664 let mut text_without_backticks = String::new();
14665 let mut code_ranges = Vec::new();
14666
14667 if let Some(source) = &diagnostic.source {
14668 text_without_backticks.push_str(source);
14669 code_ranges.push(0..source.len());
14670 text_without_backticks.push_str(": ");
14671 }
14672
14673 let mut prev_offset = 0;
14674 let mut in_code_block = false;
14675 let has_row_limit = max_message_rows.is_some();
14676 let mut newline_indices = diagnostic
14677 .message
14678 .match_indices('\n')
14679 .filter(|_| has_row_limit)
14680 .map(|(ix, _)| ix)
14681 .fuse()
14682 .peekable();
14683
14684 for (quote_ix, _) in diagnostic
14685 .message
14686 .match_indices('`')
14687 .chain([(diagnostic.message.len(), "")])
14688 {
14689 let mut first_newline_ix = None;
14690 let mut last_newline_ix = None;
14691 while let Some(newline_ix) = newline_indices.peek() {
14692 if *newline_ix < quote_ix {
14693 if first_newline_ix.is_none() {
14694 first_newline_ix = Some(*newline_ix);
14695 }
14696 last_newline_ix = Some(*newline_ix);
14697
14698 if let Some(rows_left) = &mut max_message_rows {
14699 if *rows_left == 0 {
14700 break;
14701 } else {
14702 *rows_left -= 1;
14703 }
14704 }
14705 let _ = newline_indices.next();
14706 } else {
14707 break;
14708 }
14709 }
14710 let prev_len = text_without_backticks.len();
14711 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14712 text_without_backticks.push_str(new_text);
14713 if in_code_block {
14714 code_ranges.push(prev_len..text_without_backticks.len());
14715 }
14716 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14717 in_code_block = !in_code_block;
14718 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14719 text_without_backticks.push_str("...");
14720 break;
14721 }
14722 }
14723
14724 (text_without_backticks.into(), code_ranges)
14725}
14726
14727fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14728 match severity {
14729 DiagnosticSeverity::ERROR => colors.error,
14730 DiagnosticSeverity::WARNING => colors.warning,
14731 DiagnosticSeverity::INFORMATION => colors.info,
14732 DiagnosticSeverity::HINT => colors.info,
14733 _ => colors.ignored,
14734 }
14735}
14736
14737pub fn styled_runs_for_code_label<'a>(
14738 label: &'a CodeLabel,
14739 syntax_theme: &'a theme::SyntaxTheme,
14740) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14741 let fade_out = HighlightStyle {
14742 fade_out: Some(0.35),
14743 ..Default::default()
14744 };
14745
14746 let mut prev_end = label.filter_range.end;
14747 label
14748 .runs
14749 .iter()
14750 .enumerate()
14751 .flat_map(move |(ix, (range, highlight_id))| {
14752 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14753 style
14754 } else {
14755 return Default::default();
14756 };
14757 let mut muted_style = style;
14758 muted_style.highlight(fade_out);
14759
14760 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14761 if range.start >= label.filter_range.end {
14762 if range.start > prev_end {
14763 runs.push((prev_end..range.start, fade_out));
14764 }
14765 runs.push((range.clone(), muted_style));
14766 } else if range.end <= label.filter_range.end {
14767 runs.push((range.clone(), style));
14768 } else {
14769 runs.push((range.start..label.filter_range.end, style));
14770 runs.push((label.filter_range.end..range.end, muted_style));
14771 }
14772 prev_end = cmp::max(prev_end, range.end);
14773
14774 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14775 runs.push((prev_end..label.text.len(), fade_out));
14776 }
14777
14778 runs
14779 })
14780}
14781
14782pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14783 let mut prev_index = 0;
14784 let mut prev_codepoint: Option<char> = None;
14785 text.char_indices()
14786 .chain([(text.len(), '\0')])
14787 .filter_map(move |(index, codepoint)| {
14788 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14789 let is_boundary = index == text.len()
14790 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14791 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14792 if is_boundary {
14793 let chunk = &text[prev_index..index];
14794 prev_index = index;
14795 Some(chunk)
14796 } else {
14797 None
14798 }
14799 })
14800}
14801
14802pub trait RangeToAnchorExt: Sized {
14803 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14804
14805 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14806 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14807 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14808 }
14809}
14810
14811impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14812 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14813 let start_offset = self.start.to_offset(snapshot);
14814 let end_offset = self.end.to_offset(snapshot);
14815 if start_offset == end_offset {
14816 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14817 } else {
14818 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14819 }
14820 }
14821}
14822
14823pub trait RowExt {
14824 fn as_f32(&self) -> f32;
14825
14826 fn next_row(&self) -> Self;
14827
14828 fn previous_row(&self) -> Self;
14829
14830 fn minus(&self, other: Self) -> u32;
14831}
14832
14833impl RowExt for DisplayRow {
14834 fn as_f32(&self) -> f32 {
14835 self.0 as f32
14836 }
14837
14838 fn next_row(&self) -> Self {
14839 Self(self.0 + 1)
14840 }
14841
14842 fn previous_row(&self) -> Self {
14843 Self(self.0.saturating_sub(1))
14844 }
14845
14846 fn minus(&self, other: Self) -> u32 {
14847 self.0 - other.0
14848 }
14849}
14850
14851impl RowExt for MultiBufferRow {
14852 fn as_f32(&self) -> f32 {
14853 self.0 as f32
14854 }
14855
14856 fn next_row(&self) -> Self {
14857 Self(self.0 + 1)
14858 }
14859
14860 fn previous_row(&self) -> Self {
14861 Self(self.0.saturating_sub(1))
14862 }
14863
14864 fn minus(&self, other: Self) -> u32 {
14865 self.0 - other.0
14866 }
14867}
14868
14869trait RowRangeExt {
14870 type Row;
14871
14872 fn len(&self) -> usize;
14873
14874 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14875}
14876
14877impl RowRangeExt for Range<MultiBufferRow> {
14878 type Row = MultiBufferRow;
14879
14880 fn len(&self) -> usize {
14881 (self.end.0 - self.start.0) as usize
14882 }
14883
14884 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14885 (self.start.0..self.end.0).map(MultiBufferRow)
14886 }
14887}
14888
14889impl RowRangeExt for Range<DisplayRow> {
14890 type Row = DisplayRow;
14891
14892 fn len(&self) -> usize {
14893 (self.end.0 - self.start.0) as usize
14894 }
14895
14896 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14897 (self.start.0..self.end.0).map(DisplayRow)
14898 }
14899}
14900
14901fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14902 if hunk.diff_base_byte_range.is_empty() {
14903 DiffHunkStatus::Added
14904 } else if hunk.row_range.is_empty() {
14905 DiffHunkStatus::Removed
14906 } else {
14907 DiffHunkStatus::Modified
14908 }
14909}
14910
14911/// If select range has more than one line, we
14912/// just point the cursor to range.start.
14913fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14914 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14915 range
14916 } else {
14917 range.start..range.start
14918 }
14919}