1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
78 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
79 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
81 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
82 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{
100 point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
101};
102use linked_editing_ranges::refresh_linked_ranges;
103pub use proposed_changes_editor::{
104 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
105};
106use similar::{ChangeTag, TextDiff};
107use std::iter::Peekable;
108use task::{ResolvedTask, TaskTemplate, TaskVariables};
109
110use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
111pub use lsp::CompletionContext;
112use lsp::{
113 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
114 LanguageServerId,
115};
116use mouse_context_menu::MouseContextMenu;
117use movement::TextLayoutDetails;
118pub use multi_buffer::{
119 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
120 ToPoint,
121};
122use multi_buffer::{
123 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
124};
125use ordered_float::OrderedFloat;
126use parking_lot::{Mutex, RwLock};
127use project::{
128 lsp_store::{FormatTarget, FormatTrigger},
129 project_settings::{GitGutterSetting, ProjectSettings},
130 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
131 LocationLink, Project, ProjectTransaction, TaskSourceKind,
132};
133use rand::prelude::*;
134use rpc::{proto::*, ErrorExt};
135use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
136use selections_collection::{
137 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
138};
139use serde::{Deserialize, Serialize};
140use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
141use smallvec::SmallVec;
142use snippet::Snippet;
143use std::{
144 any::TypeId,
145 borrow::Cow,
146 cell::RefCell,
147 cmp::{self, Ordering, Reverse},
148 mem,
149 num::NonZeroU32,
150 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
151 path::{Path, PathBuf},
152 rc::Rc,
153 sync::Arc,
154 time::{Duration, Instant},
155};
156pub use sum_tree::Bias;
157use sum_tree::TreeMap;
158use text::{BufferId, OffsetUtf16, Rope};
159use theme::{
160 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
161 ThemeColors, ThemeSettings,
162};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 ListItem, Popover, PopoverMenuHandle, Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::find_url;
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189#[doc(hidden)]
190pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
191
192pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
193pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
194
195pub fn render_parsed_markdown(
196 element_id: impl Into<ElementId>,
197 parsed: &language::ParsedMarkdown,
198 editor_style: &EditorStyle,
199 workspace: Option<WeakView<Workspace>>,
200 cx: &mut WindowContext,
201) -> InteractiveText {
202 let code_span_background_color = cx
203 .theme()
204 .colors()
205 .editor_document_highlight_read_background;
206
207 let highlights = gpui::combine_highlights(
208 parsed.highlights.iter().filter_map(|(range, highlight)| {
209 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
210 Some((range.clone(), highlight))
211 }),
212 parsed
213 .regions
214 .iter()
215 .zip(&parsed.region_ranges)
216 .filter_map(|(region, range)| {
217 if region.code {
218 Some((
219 range.clone(),
220 HighlightStyle {
221 background_color: Some(code_span_background_color),
222 ..Default::default()
223 },
224 ))
225 } else {
226 None
227 }
228 }),
229 );
230
231 let mut links = Vec::new();
232 let mut link_ranges = Vec::new();
233 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
234 if let Some(link) = region.link.clone() {
235 links.push(link);
236 link_ranges.push(range.clone());
237 }
238 }
239
240 InteractiveText::new(
241 element_id,
242 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
243 )
244 .on_click(link_ranges, move |clicked_range_ix, cx| {
245 match &links[clicked_range_ix] {
246 markdown::Link::Web { url } => cx.open_url(url),
247 markdown::Link::Path { path } => {
248 if let Some(workspace) = &workspace {
249 _ = workspace.update(cx, |workspace, cx| {
250 workspace.open_abs_path(path.clone(), false, cx).detach();
251 });
252 }
253 }
254 }
255 })
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub(crate) enum InlayId {
260 Suggestion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::Suggestion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DiffRowHighlight {}
274enum DocumentHighlightRead {}
275enum DocumentHighlightWrite {}
276enum InputComposition {}
277
278#[derive(Copy, Clone, PartialEq, Eq)]
279pub enum Direction {
280 Prev,
281 Next,
282}
283
284#[derive(Debug, Copy, Clone, PartialEq, Eq)]
285pub enum Navigated {
286 Yes,
287 No,
288}
289
290impl Navigated {
291 pub fn from_bool(yes: bool) -> Navigated {
292 if yes {
293 Navigated::Yes
294 } else {
295 Navigated::No
296 }
297 }
298}
299
300pub fn init_settings(cx: &mut AppContext) {
301 EditorSettings::register(cx);
302}
303
304pub fn init(cx: &mut AppContext) {
305 init_settings(cx);
306
307 workspace::register_project_item::<Editor>(cx);
308 workspace::FollowableViewRegistry::register::<Editor>(cx);
309 workspace::register_serializable_item::<Editor>(cx);
310
311 cx.observe_new_views(
312 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
313 workspace.register_action(Editor::new_file);
314 workspace.register_action(Editor::new_file_vertical);
315 workspace.register_action(Editor::new_file_horizontal);
316 },
317 )
318 .detach();
319
320 cx.on_action(move |_: &workspace::NewFile, cx| {
321 let app_state = workspace::AppState::global(cx);
322 if let Some(app_state) = app_state.upgrade() {
323 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
324 Editor::new_file(workspace, &Default::default(), cx)
325 })
326 .detach();
327 }
328 });
329 cx.on_action(move |_: &workspace::NewWindow, cx| {
330 let app_state = workspace::AppState::global(cx);
331 if let Some(app_state) = app_state.upgrade() {
332 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
333 Editor::new_file(workspace, &Default::default(), cx)
334 })
335 .detach();
336 }
337 });
338}
339
340pub struct SearchWithinRange;
341
342trait InvalidationRegion {
343 fn ranges(&self) -> &[Range<Anchor>];
344}
345
346#[derive(Clone, Debug, PartialEq)]
347pub enum SelectPhase {
348 Begin {
349 position: DisplayPoint,
350 add: bool,
351 click_count: usize,
352 },
353 BeginColumnar {
354 position: DisplayPoint,
355 reset: bool,
356 goal_column: u32,
357 },
358 Extend {
359 position: DisplayPoint,
360 click_count: usize,
361 },
362 Update {
363 position: DisplayPoint,
364 goal_column: u32,
365 scroll_delta: gpui::Point<f32>,
366 },
367 End,
368}
369
370#[derive(Clone, Debug)]
371pub enum SelectMode {
372 Character,
373 Word(Range<Anchor>),
374 Line(Range<Anchor>),
375 All,
376}
377
378#[derive(Copy, Clone, PartialEq, Eq, Debug)]
379pub enum EditorMode {
380 SingleLine { auto_width: bool },
381 AutoHeight { max_lines: usize },
382 Full,
383}
384
385#[derive(Copy, Clone, Debug)]
386pub enum SoftWrap {
387 /// Prefer not to wrap at all.
388 ///
389 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
390 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
391 GitDiff,
392 /// Prefer a single line generally, unless an overly long line is encountered.
393 None,
394 /// Soft wrap lines that exceed the editor width.
395 EditorWidth,
396 /// Soft wrap lines at the preferred line length.
397 Column(u32),
398 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
399 Bounded(u32),
400}
401
402#[derive(Clone)]
403pub struct EditorStyle {
404 pub background: Hsla,
405 pub local_player: PlayerColor,
406 pub text: TextStyle,
407 pub scrollbar_width: Pixels,
408 pub syntax: Arc<SyntaxTheme>,
409 pub status: StatusColors,
410 pub inlay_hints_style: HighlightStyle,
411 pub suggestions_style: HighlightStyle,
412 pub unnecessary_code_fade: f32,
413}
414
415impl Default for EditorStyle {
416 fn default() -> Self {
417 Self {
418 background: Hsla::default(),
419 local_player: PlayerColor::default(),
420 text: TextStyle::default(),
421 scrollbar_width: Pixels::default(),
422 syntax: Default::default(),
423 // HACK: Status colors don't have a real default.
424 // We should look into removing the status colors from the editor
425 // style and retrieve them directly from the theme.
426 status: StatusColors::dark(),
427 inlay_hints_style: HighlightStyle::default(),
428 suggestions_style: HighlightStyle::default(),
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446type CompletionId = usize;
447
448#[derive(Clone, Debug)]
449struct CompletionState {
450 // render_inlay_ids represents the inlay hints that are inserted
451 // for rendering the inline completions. They may be discontinuous
452 // in the event that the completion provider returns some intersection
453 // with the existing content.
454 render_inlay_ids: Vec<InlayId>,
455 // text is the resulting rope that is inserted when the user accepts a completion.
456 text: Rope,
457 // position is the position of the cursor when the completion was triggered.
458 position: multi_buffer::Anchor,
459 // delete_range is the range of text that this completion state covers.
460 // if the completion is accepted, this range should be deleted.
461 delete_range: Option<Range<multi_buffer::Anchor>>,
462}
463
464#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
465struct EditorActionId(usize);
466
467impl EditorActionId {
468 pub fn post_inc(&mut self) -> Self {
469 let answer = self.0;
470
471 *self = Self(answer + 1);
472
473 Self(answer)
474 }
475}
476
477// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
478// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
479
480type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
481type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
482
483#[derive(Default)]
484struct ScrollbarMarkerState {
485 scrollbar_size: Size<Pixels>,
486 dirty: bool,
487 markers: Arc<[PaintQuad]>,
488 pending_refresh: Option<Task<Result<()>>>,
489}
490
491impl ScrollbarMarkerState {
492 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
493 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
494 }
495}
496
497#[derive(Clone, Debug)]
498struct RunnableTasks {
499 templates: Vec<(TaskSourceKind, TaskTemplate)>,
500 offset: MultiBufferOffset,
501 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
502 column: u32,
503 // Values of all named captures, including those starting with '_'
504 extra_variables: HashMap<String, String>,
505 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
506 context_range: Range<BufferOffset>,
507}
508
509impl RunnableTasks {
510 fn resolve<'a>(
511 &'a self,
512 cx: &'a task::TaskContext,
513 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
514 self.templates.iter().filter_map(|(kind, template)| {
515 template
516 .resolve_task(&kind.to_id_base(), cx)
517 .map(|task| (kind.clone(), task))
518 })
519 }
520}
521
522#[derive(Clone)]
523struct ResolvedTasks {
524 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
525 position: Anchor,
526}
527#[derive(Copy, Clone, Debug)]
528struct MultiBufferOffset(usize);
529#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
530struct BufferOffset(usize);
531
532// Addons allow storing per-editor state in other crates (e.g. Vim)
533pub trait Addon: 'static {
534 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
535
536 fn to_any(&self) -> &dyn std::any::Any;
537}
538
539/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
540///
541/// See the [module level documentation](self) for more information.
542pub struct Editor {
543 focus_handle: FocusHandle,
544 last_focused_descendant: Option<WeakFocusHandle>,
545 /// The text buffer being edited
546 buffer: Model<MultiBuffer>,
547 /// Map of how text in the buffer should be displayed.
548 /// Handles soft wraps, folds, fake inlay text insertions, etc.
549 pub display_map: Model<DisplayMap>,
550 pub selections: SelectionsCollection,
551 pub scroll_manager: ScrollManager,
552 /// When inline assist editors are linked, they all render cursors because
553 /// typing enters text into each of them, even the ones that aren't focused.
554 pub(crate) show_cursor_when_unfocused: bool,
555 columnar_selection_tail: Option<Anchor>,
556 add_selections_state: Option<AddSelectionsState>,
557 select_next_state: Option<SelectNextState>,
558 select_prev_state: Option<SelectNextState>,
559 selection_history: SelectionHistory,
560 autoclose_regions: Vec<AutocloseRegion>,
561 snippet_stack: InvalidationStack<SnippetState>,
562 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
563 ime_transaction: Option<TransactionId>,
564 active_diagnostics: Option<ActiveDiagnosticGroup>,
565 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
566
567 project: Option<Model<Project>>,
568 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
569 completion_provider: Option<Box<dyn CompletionProvider>>,
570 collaboration_hub: Option<Box<dyn CollaborationHub>>,
571 blink_manager: Model<BlinkManager>,
572 show_cursor_names: bool,
573 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
574 pub show_local_selections: bool,
575 mode: EditorMode,
576 show_breadcrumbs: bool,
577 show_gutter: bool,
578 show_line_numbers: Option<bool>,
579 use_relative_line_numbers: Option<bool>,
580 show_git_diff_gutter: Option<bool>,
581 show_code_actions: Option<bool>,
582 show_runnables: Option<bool>,
583 show_wrap_guides: Option<bool>,
584 show_indent_guides: Option<bool>,
585 placeholder_text: Option<Arc<str>>,
586 highlight_order: usize,
587 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
588 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
589 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
590 scrollbar_marker_state: ScrollbarMarkerState,
591 active_indent_guides_state: ActiveIndentGuidesState,
592 nav_history: Option<ItemNavHistory>,
593 context_menu: RwLock<Option<ContextMenu>>,
594 mouse_context_menu: Option<MouseContextMenu>,
595 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
596 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
597 signature_help_state: SignatureHelpState,
598 auto_signature_help: Option<bool>,
599 find_all_references_task_sources: Vec<Anchor>,
600 next_completion_id: CompletionId,
601 completion_documentation_pre_resolve_debounce: DebouncedDelay,
602 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
603 code_actions_task: Option<Task<Result<()>>>,
604 document_highlights_task: Option<Task<()>>,
605 linked_editing_range_task: Option<Task<Option<()>>>,
606 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
607 pending_rename: Option<RenameState>,
608 searchable: bool,
609 cursor_shape: CursorShape,
610 current_line_highlight: Option<CurrentLineHighlight>,
611 collapse_matches: bool,
612 autoindent_mode: Option<AutoindentMode>,
613 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
614 input_enabled: bool,
615 use_modal_editing: bool,
616 read_only: bool,
617 leader_peer_id: Option<PeerId>,
618 remote_id: Option<ViewId>,
619 hover_state: HoverState,
620 gutter_hovered: bool,
621 hovered_link_state: Option<HoveredLinkState>,
622 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
623 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
624 active_inline_completion: Option<CompletionState>,
625 // enable_inline_completions is a switch that Vim can use to disable
626 // inline completions based on its mode.
627 enable_inline_completions: bool,
628 show_inline_completions_override: Option<bool>,
629 inlay_hint_cache: InlayHintCache,
630 expanded_hunks: ExpandedHunks,
631 next_inlay_id: usize,
632 _subscriptions: Vec<Subscription>,
633 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
634 gutter_dimensions: GutterDimensions,
635 style: Option<EditorStyle>,
636 text_style_refinement: Option<TextStyleRefinement>,
637 next_editor_action_id: EditorActionId,
638 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
639 use_autoclose: bool,
640 use_auto_surround: bool,
641 auto_replace_emoji_shortcode: bool,
642 show_git_blame_gutter: bool,
643 show_git_blame_inline: bool,
644 show_git_blame_inline_delay_task: Option<Task<()>>,
645 git_blame_inline_enabled: bool,
646 serialize_dirty_buffers: bool,
647 show_selection_menu: Option<bool>,
648 blame: Option<Model<GitBlame>>,
649 blame_subscription: Option<Subscription>,
650 custom_context_menu: Option<
651 Box<
652 dyn 'static
653 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
654 >,
655 >,
656 last_bounds: Option<Bounds<Pixels>>,
657 expect_bounds_change: Option<Bounds<Pixels>>,
658 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
659 tasks_update_task: Option<Task<()>>,
660 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
661 breadcrumb_header: Option<String>,
662 focused_block: Option<FocusedBlock>,
663 next_scroll_position: NextScrollCursorCenterTopBottom,
664 addons: HashMap<TypeId, Box<dyn Addon>>,
665 _scroll_cursor_center_top_bottom_task: Task<()>,
666}
667
668#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
669enum NextScrollCursorCenterTopBottom {
670 #[default]
671 Center,
672 Top,
673 Bottom,
674}
675
676impl NextScrollCursorCenterTopBottom {
677 fn next(&self) -> Self {
678 match self {
679 Self::Center => Self::Top,
680 Self::Top => Self::Bottom,
681 Self::Bottom => Self::Center,
682 }
683 }
684}
685
686#[derive(Clone)]
687pub struct EditorSnapshot {
688 pub mode: EditorMode,
689 show_gutter: bool,
690 show_line_numbers: Option<bool>,
691 show_git_diff_gutter: Option<bool>,
692 show_code_actions: Option<bool>,
693 show_runnables: Option<bool>,
694 git_blame_gutter_max_author_length: Option<usize>,
695 pub display_snapshot: DisplaySnapshot,
696 pub placeholder_text: Option<Arc<str>>,
697 is_focused: bool,
698 scroll_anchor: ScrollAnchor,
699 ongoing_scroll: OngoingScroll,
700 current_line_highlight: CurrentLineHighlight,
701 gutter_hovered: bool,
702}
703
704const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
705
706#[derive(Default, Debug, Clone, Copy)]
707pub struct GutterDimensions {
708 pub left_padding: Pixels,
709 pub right_padding: Pixels,
710 pub width: Pixels,
711 pub margin: Pixels,
712 pub git_blame_entries_width: Option<Pixels>,
713}
714
715impl GutterDimensions {
716 /// The full width of the space taken up by the gutter.
717 pub fn full_width(&self) -> Pixels {
718 self.margin + self.width
719 }
720
721 /// The width of the space reserved for the fold indicators,
722 /// use alongside 'justify_end' and `gutter_width` to
723 /// right align content with the line numbers
724 pub fn fold_area_width(&self) -> Pixels {
725 self.margin + self.right_padding
726 }
727}
728
729#[derive(Debug)]
730pub struct RemoteSelection {
731 pub replica_id: ReplicaId,
732 pub selection: Selection<Anchor>,
733 pub cursor_shape: CursorShape,
734 pub peer_id: PeerId,
735 pub line_mode: bool,
736 pub participant_index: Option<ParticipantIndex>,
737 pub user_name: Option<SharedString>,
738}
739
740#[derive(Clone, Debug)]
741struct SelectionHistoryEntry {
742 selections: Arc<[Selection<Anchor>]>,
743 select_next_state: Option<SelectNextState>,
744 select_prev_state: Option<SelectNextState>,
745 add_selections_state: Option<AddSelectionsState>,
746}
747
748enum SelectionHistoryMode {
749 Normal,
750 Undoing,
751 Redoing,
752}
753
754#[derive(Clone, PartialEq, Eq, Hash)]
755struct HoveredCursor {
756 replica_id: u16,
757 selection_id: usize,
758}
759
760impl Default for SelectionHistoryMode {
761 fn default() -> Self {
762 Self::Normal
763 }
764}
765
766#[derive(Default)]
767struct SelectionHistory {
768 #[allow(clippy::type_complexity)]
769 selections_by_transaction:
770 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
771 mode: SelectionHistoryMode,
772 undo_stack: VecDeque<SelectionHistoryEntry>,
773 redo_stack: VecDeque<SelectionHistoryEntry>,
774}
775
776impl SelectionHistory {
777 fn insert_transaction(
778 &mut self,
779 transaction_id: TransactionId,
780 selections: Arc<[Selection<Anchor>]>,
781 ) {
782 self.selections_by_transaction
783 .insert(transaction_id, (selections, None));
784 }
785
786 #[allow(clippy::type_complexity)]
787 fn transaction(
788 &self,
789 transaction_id: TransactionId,
790 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
791 self.selections_by_transaction.get(&transaction_id)
792 }
793
794 #[allow(clippy::type_complexity)]
795 fn transaction_mut(
796 &mut self,
797 transaction_id: TransactionId,
798 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
799 self.selections_by_transaction.get_mut(&transaction_id)
800 }
801
802 fn push(&mut self, entry: SelectionHistoryEntry) {
803 if !entry.selections.is_empty() {
804 match self.mode {
805 SelectionHistoryMode::Normal => {
806 self.push_undo(entry);
807 self.redo_stack.clear();
808 }
809 SelectionHistoryMode::Undoing => self.push_redo(entry),
810 SelectionHistoryMode::Redoing => self.push_undo(entry),
811 }
812 }
813 }
814
815 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
816 if self
817 .undo_stack
818 .back()
819 .map_or(true, |e| e.selections != entry.selections)
820 {
821 self.undo_stack.push_back(entry);
822 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
823 self.undo_stack.pop_front();
824 }
825 }
826 }
827
828 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
829 if self
830 .redo_stack
831 .back()
832 .map_or(true, |e| e.selections != entry.selections)
833 {
834 self.redo_stack.push_back(entry);
835 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
836 self.redo_stack.pop_front();
837 }
838 }
839 }
840}
841
842struct RowHighlight {
843 index: usize,
844 range: Range<Anchor>,
845 color: Hsla,
846 should_autoscroll: bool,
847}
848
849#[derive(Clone, Debug)]
850struct AddSelectionsState {
851 above: bool,
852 stack: Vec<usize>,
853}
854
855#[derive(Clone)]
856struct SelectNextState {
857 query: AhoCorasick,
858 wordwise: bool,
859 done: bool,
860}
861
862impl std::fmt::Debug for SelectNextState {
863 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
864 f.debug_struct(std::any::type_name::<Self>())
865 .field("wordwise", &self.wordwise)
866 .field("done", &self.done)
867 .finish()
868 }
869}
870
871#[derive(Debug)]
872struct AutocloseRegion {
873 selection_id: usize,
874 range: Range<Anchor>,
875 pair: BracketPair,
876}
877
878#[derive(Debug)]
879struct SnippetState {
880 ranges: Vec<Vec<Range<Anchor>>>,
881 active_index: usize,
882}
883
884#[doc(hidden)]
885pub struct RenameState {
886 pub range: Range<Anchor>,
887 pub old_name: Arc<str>,
888 pub editor: View<Editor>,
889 block_id: CustomBlockId,
890}
891
892struct InvalidationStack<T>(Vec<T>);
893
894struct RegisteredInlineCompletionProvider {
895 provider: Arc<dyn InlineCompletionProviderHandle>,
896 _subscription: Subscription,
897}
898
899enum ContextMenu {
900 Completions(CompletionsMenu),
901 CodeActions(CodeActionsMenu),
902}
903
904impl ContextMenu {
905 fn select_first(
906 &mut self,
907 provider: Option<&dyn CompletionProvider>,
908 cx: &mut ViewContext<Editor>,
909 ) -> bool {
910 if self.visible() {
911 match self {
912 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
913 ContextMenu::CodeActions(menu) => menu.select_first(cx),
914 }
915 true
916 } else {
917 false
918 }
919 }
920
921 fn select_prev(
922 &mut self,
923 provider: Option<&dyn CompletionProvider>,
924 cx: &mut ViewContext<Editor>,
925 ) -> bool {
926 if self.visible() {
927 match self {
928 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
929 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
930 }
931 true
932 } else {
933 false
934 }
935 }
936
937 fn select_next(
938 &mut self,
939 provider: Option<&dyn CompletionProvider>,
940 cx: &mut ViewContext<Editor>,
941 ) -> bool {
942 if self.visible() {
943 match self {
944 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
945 ContextMenu::CodeActions(menu) => menu.select_next(cx),
946 }
947 true
948 } else {
949 false
950 }
951 }
952
953 fn select_last(
954 &mut self,
955 provider: Option<&dyn CompletionProvider>,
956 cx: &mut ViewContext<Editor>,
957 ) -> bool {
958 if self.visible() {
959 match self {
960 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
961 ContextMenu::CodeActions(menu) => menu.select_last(cx),
962 }
963 true
964 } else {
965 false
966 }
967 }
968
969 fn visible(&self) -> bool {
970 match self {
971 ContextMenu::Completions(menu) => menu.visible(),
972 ContextMenu::CodeActions(menu) => menu.visible(),
973 }
974 }
975
976 fn render(
977 &self,
978 cursor_position: DisplayPoint,
979 style: &EditorStyle,
980 max_height: Pixels,
981 workspace: Option<WeakView<Workspace>>,
982 cx: &mut ViewContext<Editor>,
983 ) -> (ContextMenuOrigin, AnyElement) {
984 match self {
985 ContextMenu::Completions(menu) => (
986 ContextMenuOrigin::EditorPoint(cursor_position),
987 menu.render(style, max_height, workspace, cx),
988 ),
989 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
990 }
991 }
992}
993
994enum ContextMenuOrigin {
995 EditorPoint(DisplayPoint),
996 GutterIndicator(DisplayRow),
997}
998
999#[derive(Clone)]
1000struct CompletionsMenu {
1001 id: CompletionId,
1002 sort_completions: bool,
1003 initial_position: Anchor,
1004 buffer: Model<Buffer>,
1005 completions: Arc<RwLock<Box<[Completion]>>>,
1006 match_candidates: Arc<[StringMatchCandidate]>,
1007 matches: Arc<[StringMatch]>,
1008 selected_item: usize,
1009 scroll_handle: UniformListScrollHandle,
1010 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
1011}
1012
1013impl CompletionsMenu {
1014 fn select_first(
1015 &mut self,
1016 provider: Option<&dyn CompletionProvider>,
1017 cx: &mut ViewContext<Editor>,
1018 ) {
1019 self.selected_item = 0;
1020 self.scroll_handle
1021 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1022 self.attempt_resolve_selected_completion_documentation(provider, cx);
1023 cx.notify();
1024 }
1025
1026 fn select_prev(
1027 &mut self,
1028 provider: Option<&dyn CompletionProvider>,
1029 cx: &mut ViewContext<Editor>,
1030 ) {
1031 if self.selected_item > 0 {
1032 self.selected_item -= 1;
1033 } else {
1034 self.selected_item = self.matches.len() - 1;
1035 }
1036 self.scroll_handle
1037 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1038 self.attempt_resolve_selected_completion_documentation(provider, cx);
1039 cx.notify();
1040 }
1041
1042 fn select_next(
1043 &mut self,
1044 provider: Option<&dyn CompletionProvider>,
1045 cx: &mut ViewContext<Editor>,
1046 ) {
1047 if self.selected_item + 1 < self.matches.len() {
1048 self.selected_item += 1;
1049 } else {
1050 self.selected_item = 0;
1051 }
1052 self.scroll_handle
1053 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1054 self.attempt_resolve_selected_completion_documentation(provider, cx);
1055 cx.notify();
1056 }
1057
1058 fn select_last(
1059 &mut self,
1060 provider: Option<&dyn CompletionProvider>,
1061 cx: &mut ViewContext<Editor>,
1062 ) {
1063 self.selected_item = self.matches.len() - 1;
1064 self.scroll_handle
1065 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1066 self.attempt_resolve_selected_completion_documentation(provider, cx);
1067 cx.notify();
1068 }
1069
1070 fn pre_resolve_completion_documentation(
1071 buffer: Model<Buffer>,
1072 completions: Arc<RwLock<Box<[Completion]>>>,
1073 matches: Arc<[StringMatch]>,
1074 editor: &Editor,
1075 cx: &mut ViewContext<Editor>,
1076 ) -> Task<()> {
1077 let settings = EditorSettings::get_global(cx);
1078 if !settings.show_completion_documentation {
1079 return Task::ready(());
1080 }
1081
1082 let Some(provider) = editor.completion_provider.as_ref() else {
1083 return Task::ready(());
1084 };
1085
1086 let resolve_task = provider.resolve_completions(
1087 buffer,
1088 matches.iter().map(|m| m.candidate_id).collect(),
1089 completions.clone(),
1090 cx,
1091 );
1092
1093 cx.spawn(move |this, mut cx| async move {
1094 if let Some(true) = resolve_task.await.log_err() {
1095 this.update(&mut cx, |_, cx| cx.notify()).ok();
1096 }
1097 })
1098 }
1099
1100 fn attempt_resolve_selected_completion_documentation(
1101 &mut self,
1102 provider: Option<&dyn CompletionProvider>,
1103 cx: &mut ViewContext<Editor>,
1104 ) {
1105 let settings = EditorSettings::get_global(cx);
1106 if !settings.show_completion_documentation {
1107 return;
1108 }
1109
1110 let completion_index = self.matches[self.selected_item].candidate_id;
1111 let Some(provider) = provider else {
1112 return;
1113 };
1114
1115 let resolve_task = provider.resolve_completions(
1116 self.buffer.clone(),
1117 vec![completion_index],
1118 self.completions.clone(),
1119 cx,
1120 );
1121
1122 let delay_ms =
1123 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1124 let delay = Duration::from_millis(delay_ms);
1125
1126 self.selected_completion_documentation_resolve_debounce
1127 .lock()
1128 .fire_new(delay, cx, |_, cx| {
1129 cx.spawn(move |this, mut cx| async move {
1130 if let Some(true) = resolve_task.await.log_err() {
1131 this.update(&mut cx, |_, cx| cx.notify()).ok();
1132 }
1133 })
1134 });
1135 }
1136
1137 fn visible(&self) -> bool {
1138 !self.matches.is_empty()
1139 }
1140
1141 fn render(
1142 &self,
1143 style: &EditorStyle,
1144 max_height: Pixels,
1145 workspace: Option<WeakView<Workspace>>,
1146 cx: &mut ViewContext<Editor>,
1147 ) -> AnyElement {
1148 let settings = EditorSettings::get_global(cx);
1149 let show_completion_documentation = settings.show_completion_documentation;
1150
1151 let widest_completion_ix = self
1152 .matches
1153 .iter()
1154 .enumerate()
1155 .max_by_key(|(_, mat)| {
1156 let completions = self.completions.read();
1157 let completion = &completions[mat.candidate_id];
1158 let documentation = &completion.documentation;
1159
1160 let mut len = completion.label.text.chars().count();
1161 if let Some(Documentation::SingleLine(text)) = documentation {
1162 if show_completion_documentation {
1163 len += text.chars().count();
1164 }
1165 }
1166
1167 len
1168 })
1169 .map(|(ix, _)| ix);
1170
1171 let completions = self.completions.clone();
1172 let matches = self.matches.clone();
1173 let selected_item = self.selected_item;
1174 let style = style.clone();
1175
1176 let multiline_docs = if show_completion_documentation {
1177 let mat = &self.matches[selected_item];
1178 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1179 Some(Documentation::MultiLinePlainText(text)) => {
1180 Some(div().child(SharedString::from(text.clone())))
1181 }
1182 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1183 Some(div().child(render_parsed_markdown(
1184 "completions_markdown",
1185 parsed,
1186 &style,
1187 workspace,
1188 cx,
1189 )))
1190 }
1191 _ => None,
1192 };
1193 multiline_docs.map(|div| {
1194 div.id("multiline_docs")
1195 .max_h(max_height)
1196 .flex_1()
1197 .px_1p5()
1198 .py_1()
1199 .min_w(px(260.))
1200 .max_w(px(640.))
1201 .w(px(500.))
1202 .overflow_y_scroll()
1203 .occlude()
1204 })
1205 } else {
1206 None
1207 };
1208
1209 let list = uniform_list(
1210 cx.view().clone(),
1211 "completions",
1212 matches.len(),
1213 move |_editor, range, cx| {
1214 let start_ix = range.start;
1215 let completions_guard = completions.read();
1216
1217 matches[range]
1218 .iter()
1219 .enumerate()
1220 .map(|(ix, mat)| {
1221 let item_ix = start_ix + ix;
1222 let candidate_id = mat.candidate_id;
1223 let completion = &completions_guard[candidate_id];
1224
1225 let documentation = if show_completion_documentation {
1226 &completion.documentation
1227 } else {
1228 &None
1229 };
1230
1231 let highlights = gpui::combine_highlights(
1232 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1233 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1234 |(range, mut highlight)| {
1235 // Ignore font weight for syntax highlighting, as we'll use it
1236 // for fuzzy matches.
1237 highlight.font_weight = None;
1238
1239 if completion.lsp_completion.deprecated.unwrap_or(false) {
1240 highlight.strikethrough = Some(StrikethroughStyle {
1241 thickness: 1.0.into(),
1242 ..Default::default()
1243 });
1244 highlight.color = Some(cx.theme().colors().text_muted);
1245 }
1246
1247 (range, highlight)
1248 },
1249 ),
1250 );
1251 let completion_label = StyledText::new(completion.label.text.clone())
1252 .with_highlights(&style.text, highlights);
1253 let documentation_label =
1254 if let Some(Documentation::SingleLine(text)) = documentation {
1255 if text.trim().is_empty() {
1256 None
1257 } else {
1258 Some(
1259 Label::new(text.clone())
1260 .ml_4()
1261 .size(LabelSize::Small)
1262 .color(Color::Muted),
1263 )
1264 }
1265 } else {
1266 None
1267 };
1268
1269 let color_swatch = completion
1270 .color()
1271 .map(|color| div().size_4().bg(color).rounded_sm());
1272
1273 div().min_w(px(220.)).max_w(px(540.)).child(
1274 ListItem::new(mat.candidate_id)
1275 .inset(true)
1276 .selected(item_ix == selected_item)
1277 .on_click(cx.listener(move |editor, _event, cx| {
1278 cx.stop_propagation();
1279 if let Some(task) = editor.confirm_completion(
1280 &ConfirmCompletion {
1281 item_ix: Some(item_ix),
1282 },
1283 cx,
1284 ) {
1285 task.detach_and_log_err(cx)
1286 }
1287 }))
1288 .start_slot::<Div>(color_swatch)
1289 .child(h_flex().overflow_hidden().child(completion_label))
1290 .end_slot::<Label>(documentation_label),
1291 )
1292 })
1293 .collect()
1294 },
1295 )
1296 .occlude()
1297 .max_h(max_height)
1298 .track_scroll(self.scroll_handle.clone())
1299 .with_width_from_item(widest_completion_ix)
1300 .with_sizing_behavior(ListSizingBehavior::Infer);
1301
1302 Popover::new()
1303 .child(list)
1304 .when_some(multiline_docs, |popover, multiline_docs| {
1305 popover.aside(multiline_docs)
1306 })
1307 .into_any_element()
1308 }
1309
1310 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1311 let mut matches = if let Some(query) = query {
1312 fuzzy::match_strings(
1313 &self.match_candidates,
1314 query,
1315 query.chars().any(|c| c.is_uppercase()),
1316 100,
1317 &Default::default(),
1318 executor,
1319 )
1320 .await
1321 } else {
1322 self.match_candidates
1323 .iter()
1324 .enumerate()
1325 .map(|(candidate_id, candidate)| StringMatch {
1326 candidate_id,
1327 score: Default::default(),
1328 positions: Default::default(),
1329 string: candidate.string.clone(),
1330 })
1331 .collect()
1332 };
1333
1334 // Remove all candidates where the query's start does not match the start of any word in the candidate
1335 if let Some(query) = query {
1336 if let Some(query_start) = query.chars().next() {
1337 matches.retain(|string_match| {
1338 split_words(&string_match.string).any(|word| {
1339 // Check that the first codepoint of the word as lowercase matches the first
1340 // codepoint of the query as lowercase
1341 word.chars()
1342 .flat_map(|codepoint| codepoint.to_lowercase())
1343 .zip(query_start.to_lowercase())
1344 .all(|(word_cp, query_cp)| word_cp == query_cp)
1345 })
1346 });
1347 }
1348 }
1349
1350 let completions = self.completions.read();
1351 if self.sort_completions {
1352 matches.sort_unstable_by_key(|mat| {
1353 // We do want to strike a balance here between what the language server tells us
1354 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1355 // `Creat` and there is a local variable called `CreateComponent`).
1356 // So what we do is: we bucket all matches into two buckets
1357 // - Strong matches
1358 // - Weak matches
1359 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1360 // and the Weak matches are the rest.
1361 //
1362 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1363 // matches, we prefer language-server sort_text first.
1364 //
1365 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1366 // Rest of the matches(weak) can be sorted as language-server expects.
1367
1368 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1369 enum MatchScore<'a> {
1370 Strong {
1371 score: Reverse<OrderedFloat<f64>>,
1372 sort_text: Option<&'a str>,
1373 sort_key: (usize, &'a str),
1374 },
1375 Weak {
1376 sort_text: Option<&'a str>,
1377 score: Reverse<OrderedFloat<f64>>,
1378 sort_key: (usize, &'a str),
1379 },
1380 }
1381
1382 let completion = &completions[mat.candidate_id];
1383 let sort_key = completion.sort_key();
1384 let sort_text = completion.lsp_completion.sort_text.as_deref();
1385 let score = Reverse(OrderedFloat(mat.score));
1386
1387 if mat.score >= 0.2 {
1388 MatchScore::Strong {
1389 score,
1390 sort_text,
1391 sort_key,
1392 }
1393 } else {
1394 MatchScore::Weak {
1395 sort_text,
1396 score,
1397 sort_key,
1398 }
1399 }
1400 });
1401 }
1402
1403 for mat in &mut matches {
1404 let completion = &completions[mat.candidate_id];
1405 mat.string.clone_from(&completion.label.text);
1406 for position in &mut mat.positions {
1407 *position += completion.label.filter_range.start;
1408 }
1409 }
1410 drop(completions);
1411
1412 self.matches = matches.into();
1413 self.selected_item = 0;
1414 }
1415}
1416
1417struct AvailableCodeAction {
1418 excerpt_id: ExcerptId,
1419 action: CodeAction,
1420 provider: Arc<dyn CodeActionProvider>,
1421}
1422
1423#[derive(Clone)]
1424struct CodeActionContents {
1425 tasks: Option<Arc<ResolvedTasks>>,
1426 actions: Option<Arc<[AvailableCodeAction]>>,
1427}
1428
1429impl CodeActionContents {
1430 fn len(&self) -> usize {
1431 match (&self.tasks, &self.actions) {
1432 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1433 (Some(tasks), None) => tasks.templates.len(),
1434 (None, Some(actions)) => actions.len(),
1435 (None, None) => 0,
1436 }
1437 }
1438
1439 fn is_empty(&self) -> bool {
1440 match (&self.tasks, &self.actions) {
1441 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1442 (Some(tasks), None) => tasks.templates.is_empty(),
1443 (None, Some(actions)) => actions.is_empty(),
1444 (None, None) => true,
1445 }
1446 }
1447
1448 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1449 self.tasks
1450 .iter()
1451 .flat_map(|tasks| {
1452 tasks
1453 .templates
1454 .iter()
1455 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1456 })
1457 .chain(self.actions.iter().flat_map(|actions| {
1458 actions.iter().map(|available| CodeActionsItem::CodeAction {
1459 excerpt_id: available.excerpt_id,
1460 action: available.action.clone(),
1461 provider: available.provider.clone(),
1462 })
1463 }))
1464 }
1465 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1466 match (&self.tasks, &self.actions) {
1467 (Some(tasks), Some(actions)) => {
1468 if index < tasks.templates.len() {
1469 tasks
1470 .templates
1471 .get(index)
1472 .cloned()
1473 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1474 } else {
1475 actions.get(index - tasks.templates.len()).map(|available| {
1476 CodeActionsItem::CodeAction {
1477 excerpt_id: available.excerpt_id,
1478 action: available.action.clone(),
1479 provider: available.provider.clone(),
1480 }
1481 })
1482 }
1483 }
1484 (Some(tasks), None) => tasks
1485 .templates
1486 .get(index)
1487 .cloned()
1488 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1489 (None, Some(actions)) => {
1490 actions
1491 .get(index)
1492 .map(|available| CodeActionsItem::CodeAction {
1493 excerpt_id: available.excerpt_id,
1494 action: available.action.clone(),
1495 provider: available.provider.clone(),
1496 })
1497 }
1498 (None, None) => None,
1499 }
1500 }
1501}
1502
1503#[allow(clippy::large_enum_variant)]
1504#[derive(Clone)]
1505enum CodeActionsItem {
1506 Task(TaskSourceKind, ResolvedTask),
1507 CodeAction {
1508 excerpt_id: ExcerptId,
1509 action: CodeAction,
1510 provider: Arc<dyn CodeActionProvider>,
1511 },
1512}
1513
1514impl CodeActionsItem {
1515 fn as_task(&self) -> Option<&ResolvedTask> {
1516 let Self::Task(_, task) = self else {
1517 return None;
1518 };
1519 Some(task)
1520 }
1521 fn as_code_action(&self) -> Option<&CodeAction> {
1522 let Self::CodeAction { action, .. } = self else {
1523 return None;
1524 };
1525 Some(action)
1526 }
1527 fn label(&self) -> String {
1528 match self {
1529 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1530 Self::Task(_, task) => task.resolved_label.clone(),
1531 }
1532 }
1533}
1534
1535struct CodeActionsMenu {
1536 actions: CodeActionContents,
1537 buffer: Model<Buffer>,
1538 selected_item: usize,
1539 scroll_handle: UniformListScrollHandle,
1540 deployed_from_indicator: Option<DisplayRow>,
1541}
1542
1543impl CodeActionsMenu {
1544 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1545 self.selected_item = 0;
1546 self.scroll_handle
1547 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1548 cx.notify()
1549 }
1550
1551 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1552 if self.selected_item > 0 {
1553 self.selected_item -= 1;
1554 } else {
1555 self.selected_item = self.actions.len() - 1;
1556 }
1557 self.scroll_handle
1558 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1559 cx.notify();
1560 }
1561
1562 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1563 if self.selected_item + 1 < self.actions.len() {
1564 self.selected_item += 1;
1565 } else {
1566 self.selected_item = 0;
1567 }
1568 self.scroll_handle
1569 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1570 cx.notify();
1571 }
1572
1573 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1574 self.selected_item = self.actions.len() - 1;
1575 self.scroll_handle
1576 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1577 cx.notify()
1578 }
1579
1580 fn visible(&self) -> bool {
1581 !self.actions.is_empty()
1582 }
1583
1584 fn render(
1585 &self,
1586 cursor_position: DisplayPoint,
1587 _style: &EditorStyle,
1588 max_height: Pixels,
1589 cx: &mut ViewContext<Editor>,
1590 ) -> (ContextMenuOrigin, AnyElement) {
1591 let actions = self.actions.clone();
1592 let selected_item = self.selected_item;
1593 let element = uniform_list(
1594 cx.view().clone(),
1595 "code_actions_menu",
1596 self.actions.len(),
1597 move |_this, range, cx| {
1598 actions
1599 .iter()
1600 .skip(range.start)
1601 .take(range.end - range.start)
1602 .enumerate()
1603 .map(|(ix, action)| {
1604 let item_ix = range.start + ix;
1605 let selected = selected_item == item_ix;
1606 let colors = cx.theme().colors();
1607 div()
1608 .px_1()
1609 .rounded_md()
1610 .text_color(colors.text)
1611 .when(selected, |style| {
1612 style
1613 .bg(colors.element_active)
1614 .text_color(colors.text_accent)
1615 })
1616 .hover(|style| {
1617 style
1618 .bg(colors.element_hover)
1619 .text_color(colors.text_accent)
1620 })
1621 .whitespace_nowrap()
1622 .when_some(action.as_code_action(), |this, action| {
1623 this.on_mouse_down(
1624 MouseButton::Left,
1625 cx.listener(move |editor, _, cx| {
1626 cx.stop_propagation();
1627 if let Some(task) = editor.confirm_code_action(
1628 &ConfirmCodeAction {
1629 item_ix: Some(item_ix),
1630 },
1631 cx,
1632 ) {
1633 task.detach_and_log_err(cx)
1634 }
1635 }),
1636 )
1637 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1638 .child(SharedString::from(action.lsp_action.title.clone()))
1639 })
1640 .when_some(action.as_task(), |this, task| {
1641 this.on_mouse_down(
1642 MouseButton::Left,
1643 cx.listener(move |editor, _, cx| {
1644 cx.stop_propagation();
1645 if let Some(task) = editor.confirm_code_action(
1646 &ConfirmCodeAction {
1647 item_ix: Some(item_ix),
1648 },
1649 cx,
1650 ) {
1651 task.detach_and_log_err(cx)
1652 }
1653 }),
1654 )
1655 .child(SharedString::from(task.resolved_label.clone()))
1656 })
1657 })
1658 .collect()
1659 },
1660 )
1661 .elevation_1(cx)
1662 .p_1()
1663 .max_h(max_height)
1664 .occlude()
1665 .track_scroll(self.scroll_handle.clone())
1666 .with_width_from_item(
1667 self.actions
1668 .iter()
1669 .enumerate()
1670 .max_by_key(|(_, action)| match action {
1671 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1672 CodeActionsItem::CodeAction { action, .. } => {
1673 action.lsp_action.title.chars().count()
1674 }
1675 })
1676 .map(|(ix, _)| ix),
1677 )
1678 .with_sizing_behavior(ListSizingBehavior::Infer)
1679 .into_any_element();
1680
1681 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1682 ContextMenuOrigin::GutterIndicator(row)
1683 } else {
1684 ContextMenuOrigin::EditorPoint(cursor_position)
1685 };
1686
1687 (cursor_position, element)
1688 }
1689}
1690
1691#[derive(Debug)]
1692struct ActiveDiagnosticGroup {
1693 primary_range: Range<Anchor>,
1694 primary_message: String,
1695 group_id: usize,
1696 blocks: HashMap<CustomBlockId, Diagnostic>,
1697 is_valid: bool,
1698}
1699
1700#[derive(Serialize, Deserialize, Clone, Debug)]
1701pub struct ClipboardSelection {
1702 pub len: usize,
1703 pub is_entire_line: bool,
1704 pub first_line_indent: u32,
1705}
1706
1707#[derive(Debug)]
1708pub(crate) struct NavigationData {
1709 cursor_anchor: Anchor,
1710 cursor_position: Point,
1711 scroll_anchor: ScrollAnchor,
1712 scroll_top_row: u32,
1713}
1714
1715#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1716pub enum GotoDefinitionKind {
1717 Symbol,
1718 Declaration,
1719 Type,
1720 Implementation,
1721}
1722
1723#[derive(Debug, Clone)]
1724enum InlayHintRefreshReason {
1725 Toggle(bool),
1726 SettingsChange(InlayHintSettings),
1727 NewLinesShown,
1728 BufferEdited(HashSet<Arc<Language>>),
1729 RefreshRequested,
1730 ExcerptsRemoved(Vec<ExcerptId>),
1731}
1732
1733impl InlayHintRefreshReason {
1734 fn description(&self) -> &'static str {
1735 match self {
1736 Self::Toggle(_) => "toggle",
1737 Self::SettingsChange(_) => "settings change",
1738 Self::NewLinesShown => "new lines shown",
1739 Self::BufferEdited(_) => "buffer edited",
1740 Self::RefreshRequested => "refresh requested",
1741 Self::ExcerptsRemoved(_) => "excerpts removed",
1742 }
1743 }
1744}
1745
1746pub(crate) struct FocusedBlock {
1747 id: BlockId,
1748 focus_handle: WeakFocusHandle,
1749}
1750
1751#[derive(Clone)]
1752struct JumpData {
1753 excerpt_id: ExcerptId,
1754 position: Point,
1755 anchor: text::Anchor,
1756 path: Option<project::ProjectPath>,
1757 line_offset_from_top: u32,
1758}
1759
1760impl Editor {
1761 pub fn single_line(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: false },
1766 buffer,
1767 None,
1768 false,
1769 cx,
1770 )
1771 }
1772
1773 pub fn multi_line(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(EditorMode::Full, buffer, None, false, cx)
1777 }
1778
1779 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1780 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1781 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1782 Self::new(
1783 EditorMode::SingleLine { auto_width: true },
1784 buffer,
1785 None,
1786 false,
1787 cx,
1788 )
1789 }
1790
1791 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1792 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1793 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1794 Self::new(
1795 EditorMode::AutoHeight { max_lines },
1796 buffer,
1797 None,
1798 false,
1799 cx,
1800 )
1801 }
1802
1803 pub fn for_buffer(
1804 buffer: Model<Buffer>,
1805 project: Option<Model<Project>>,
1806 cx: &mut ViewContext<Self>,
1807 ) -> Self {
1808 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1809 Self::new(EditorMode::Full, buffer, project, false, cx)
1810 }
1811
1812 pub fn for_multibuffer(
1813 buffer: Model<MultiBuffer>,
1814 project: Option<Model<Project>>,
1815 show_excerpt_controls: bool,
1816 cx: &mut ViewContext<Self>,
1817 ) -> Self {
1818 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1819 }
1820
1821 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1822 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1823 let mut clone = Self::new(
1824 self.mode,
1825 self.buffer.clone(),
1826 self.project.clone(),
1827 show_excerpt_controls,
1828 cx,
1829 );
1830 self.display_map.update(cx, |display_map, cx| {
1831 let snapshot = display_map.snapshot(cx);
1832 clone.display_map.update(cx, |display_map, cx| {
1833 display_map.set_state(&snapshot, cx);
1834 });
1835 });
1836 clone.selections.clone_state(&self.selections);
1837 clone.scroll_manager.clone_state(&self.scroll_manager);
1838 clone.searchable = self.searchable;
1839 clone
1840 }
1841
1842 pub fn new(
1843 mode: EditorMode,
1844 buffer: Model<MultiBuffer>,
1845 project: Option<Model<Project>>,
1846 show_excerpt_controls: bool,
1847 cx: &mut ViewContext<Self>,
1848 ) -> Self {
1849 let style = cx.text_style();
1850 let font_size = style.font_size.to_pixels(cx.rem_size());
1851 let editor = cx.view().downgrade();
1852 let fold_placeholder = FoldPlaceholder {
1853 constrain_width: true,
1854 render: Arc::new(move |fold_id, fold_range, cx| {
1855 let editor = editor.clone();
1856 div()
1857 .id(fold_id)
1858 .bg(cx.theme().colors().ghost_element_background)
1859 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1860 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1861 .rounded_sm()
1862 .size_full()
1863 .cursor_pointer()
1864 .child("⋯")
1865 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1866 .on_click(move |_, cx| {
1867 editor
1868 .update(cx, |editor, cx| {
1869 editor.unfold_ranges(
1870 &[fold_range.start..fold_range.end],
1871 true,
1872 false,
1873 cx,
1874 );
1875 cx.stop_propagation();
1876 })
1877 .ok();
1878 })
1879 .into_any()
1880 }),
1881 merge_adjacent: true,
1882 ..Default::default()
1883 };
1884 let display_map = cx.new_model(|cx| {
1885 DisplayMap::new(
1886 buffer.clone(),
1887 style.font(),
1888 font_size,
1889 None,
1890 show_excerpt_controls,
1891 FILE_HEADER_HEIGHT,
1892 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1893 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1894 fold_placeholder,
1895 cx,
1896 )
1897 });
1898
1899 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1900
1901 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1902
1903 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1904 .then(|| language_settings::SoftWrap::None);
1905
1906 let mut project_subscriptions = Vec::new();
1907 if mode == EditorMode::Full {
1908 if let Some(project) = project.as_ref() {
1909 if buffer.read(cx).is_singleton() {
1910 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1911 cx.emit(EditorEvent::TitleChanged);
1912 }));
1913 }
1914 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1915 if let project::Event::RefreshInlayHints = event {
1916 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1917 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1918 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1919 let focus_handle = editor.focus_handle(cx);
1920 if focus_handle.is_focused(cx) {
1921 let snapshot = buffer.read(cx).snapshot();
1922 for (range, snippet) in snippet_edits {
1923 let editor_range =
1924 language::range_from_lsp(*range).to_offset(&snapshot);
1925 editor
1926 .insert_snippet(&[editor_range], snippet.clone(), cx)
1927 .ok();
1928 }
1929 }
1930 }
1931 }
1932 }));
1933 if let Some(task_inventory) = project
1934 .read(cx)
1935 .task_store()
1936 .read(cx)
1937 .task_inventory()
1938 .cloned()
1939 {
1940 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1941 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1942 }));
1943 }
1944 }
1945 }
1946
1947 let inlay_hint_settings = inlay_hint_settings(
1948 selections.newest_anchor().head(),
1949 &buffer.read(cx).snapshot(cx),
1950 cx,
1951 );
1952 let focus_handle = cx.focus_handle();
1953 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1954 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1955 .detach();
1956 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1957 .detach();
1958 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1959
1960 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1961 Some(false)
1962 } else {
1963 None
1964 };
1965
1966 let mut code_action_providers = Vec::new();
1967 if let Some(project) = project.clone() {
1968 code_action_providers.push(Arc::new(project) as Arc<_>);
1969 }
1970
1971 let mut this = Self {
1972 focus_handle,
1973 show_cursor_when_unfocused: false,
1974 last_focused_descendant: None,
1975 buffer: buffer.clone(),
1976 display_map: display_map.clone(),
1977 selections,
1978 scroll_manager: ScrollManager::new(cx),
1979 columnar_selection_tail: None,
1980 add_selections_state: None,
1981 select_next_state: None,
1982 select_prev_state: None,
1983 selection_history: Default::default(),
1984 autoclose_regions: Default::default(),
1985 snippet_stack: Default::default(),
1986 select_larger_syntax_node_stack: Vec::new(),
1987 ime_transaction: Default::default(),
1988 active_diagnostics: None,
1989 soft_wrap_mode_override,
1990 completion_provider: project.clone().map(|project| Box::new(project) as _),
1991 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1992 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1993 project,
1994 blink_manager: blink_manager.clone(),
1995 show_local_selections: true,
1996 mode,
1997 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1998 show_gutter: mode == EditorMode::Full,
1999 show_line_numbers: None,
2000 use_relative_line_numbers: None,
2001 show_git_diff_gutter: None,
2002 show_code_actions: None,
2003 show_runnables: None,
2004 show_wrap_guides: None,
2005 show_indent_guides,
2006 placeholder_text: None,
2007 highlight_order: 0,
2008 highlighted_rows: HashMap::default(),
2009 background_highlights: Default::default(),
2010 gutter_highlights: TreeMap::default(),
2011 scrollbar_marker_state: ScrollbarMarkerState::default(),
2012 active_indent_guides_state: ActiveIndentGuidesState::default(),
2013 nav_history: None,
2014 context_menu: RwLock::new(None),
2015 mouse_context_menu: None,
2016 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2017 completion_tasks: Default::default(),
2018 signature_help_state: SignatureHelpState::default(),
2019 auto_signature_help: None,
2020 find_all_references_task_sources: Vec::new(),
2021 next_completion_id: 0,
2022 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2023 next_inlay_id: 0,
2024 code_action_providers,
2025 available_code_actions: Default::default(),
2026 code_actions_task: Default::default(),
2027 document_highlights_task: Default::default(),
2028 linked_editing_range_task: Default::default(),
2029 pending_rename: Default::default(),
2030 searchable: true,
2031 cursor_shape: EditorSettings::get_global(cx)
2032 .cursor_shape
2033 .unwrap_or_default(),
2034 current_line_highlight: None,
2035 autoindent_mode: Some(AutoindentMode::EachLine),
2036 collapse_matches: false,
2037 workspace: None,
2038 input_enabled: true,
2039 use_modal_editing: mode == EditorMode::Full,
2040 read_only: false,
2041 use_autoclose: true,
2042 use_auto_surround: true,
2043 auto_replace_emoji_shortcode: false,
2044 leader_peer_id: None,
2045 remote_id: None,
2046 hover_state: Default::default(),
2047 hovered_link_state: Default::default(),
2048 inline_completion_provider: None,
2049 active_inline_completion: None,
2050 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2051 expanded_hunks: ExpandedHunks::default(),
2052 gutter_hovered: false,
2053 pixel_position_of_newest_cursor: None,
2054 last_bounds: None,
2055 expect_bounds_change: None,
2056 gutter_dimensions: GutterDimensions::default(),
2057 style: None,
2058 show_cursor_names: false,
2059 hovered_cursors: Default::default(),
2060 next_editor_action_id: EditorActionId::default(),
2061 editor_actions: Rc::default(),
2062 show_inline_completions_override: None,
2063 enable_inline_completions: true,
2064 custom_context_menu: None,
2065 show_git_blame_gutter: false,
2066 show_git_blame_inline: false,
2067 show_selection_menu: None,
2068 show_git_blame_inline_delay_task: None,
2069 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2070 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2071 .session
2072 .restore_unsaved_buffers,
2073 blame: None,
2074 blame_subscription: None,
2075 tasks: Default::default(),
2076 _subscriptions: vec![
2077 cx.observe(&buffer, Self::on_buffer_changed),
2078 cx.subscribe(&buffer, Self::on_buffer_event),
2079 cx.observe(&display_map, Self::on_display_map_changed),
2080 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2081 cx.observe_global::<SettingsStore>(Self::settings_changed),
2082 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2083 cx.observe_window_activation(|editor, cx| {
2084 let active = cx.is_window_active();
2085 editor.blink_manager.update(cx, |blink_manager, cx| {
2086 if active {
2087 blink_manager.enable(cx);
2088 } else {
2089 blink_manager.disable(cx);
2090 }
2091 });
2092 }),
2093 ],
2094 tasks_update_task: None,
2095 linked_edit_ranges: Default::default(),
2096 previous_search_ranges: None,
2097 breadcrumb_header: None,
2098 focused_block: None,
2099 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2100 addons: HashMap::default(),
2101 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2102 text_style_refinement: None,
2103 };
2104 this.tasks_update_task = Some(this.refresh_runnables(cx));
2105 this._subscriptions.extend(project_subscriptions);
2106
2107 this.end_selection(cx);
2108 this.scroll_manager.show_scrollbar(cx);
2109
2110 if mode == EditorMode::Full {
2111 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2112 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2113
2114 if this.git_blame_inline_enabled {
2115 this.git_blame_inline_enabled = true;
2116 this.start_git_blame_inline(false, cx);
2117 }
2118 }
2119
2120 this.report_editor_event("open", None, cx);
2121 this
2122 }
2123
2124 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2125 self.mouse_context_menu
2126 .as_ref()
2127 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2128 }
2129
2130 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2131 let mut key_context = KeyContext::new_with_defaults();
2132 key_context.add("Editor");
2133 let mode = match self.mode {
2134 EditorMode::SingleLine { .. } => "single_line",
2135 EditorMode::AutoHeight { .. } => "auto_height",
2136 EditorMode::Full => "full",
2137 };
2138
2139 if EditorSettings::jupyter_enabled(cx) {
2140 key_context.add("jupyter");
2141 }
2142
2143 key_context.set("mode", mode);
2144 if self.pending_rename.is_some() {
2145 key_context.add("renaming");
2146 }
2147 if self.context_menu_visible() {
2148 match self.context_menu.read().as_ref() {
2149 Some(ContextMenu::Completions(_)) => {
2150 key_context.add("menu");
2151 key_context.add("showing_completions")
2152 }
2153 Some(ContextMenu::CodeActions(_)) => {
2154 key_context.add("menu");
2155 key_context.add("showing_code_actions")
2156 }
2157 None => {}
2158 }
2159 }
2160
2161 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2162 if !self.focus_handle(cx).contains_focused(cx)
2163 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2164 {
2165 for addon in self.addons.values() {
2166 addon.extend_key_context(&mut key_context, cx)
2167 }
2168 }
2169
2170 if let Some(extension) = self
2171 .buffer
2172 .read(cx)
2173 .as_singleton()
2174 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2175 {
2176 key_context.set("extension", extension.to_string());
2177 }
2178
2179 if self.has_active_inline_completion(cx) {
2180 key_context.add("copilot_suggestion");
2181 key_context.add("inline_completion");
2182 }
2183
2184 key_context
2185 }
2186
2187 pub fn new_file(
2188 workspace: &mut Workspace,
2189 _: &workspace::NewFile,
2190 cx: &mut ViewContext<Workspace>,
2191 ) {
2192 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2193 "Failed to create buffer",
2194 cx,
2195 |e, _| match e.error_code() {
2196 ErrorCode::RemoteUpgradeRequired => Some(format!(
2197 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2198 e.error_tag("required").unwrap_or("the latest version")
2199 )),
2200 _ => None,
2201 },
2202 );
2203 }
2204
2205 pub fn new_in_workspace(
2206 workspace: &mut Workspace,
2207 cx: &mut ViewContext<Workspace>,
2208 ) -> Task<Result<View<Editor>>> {
2209 let project = workspace.project().clone();
2210 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2211
2212 cx.spawn(|workspace, mut cx| async move {
2213 let buffer = create.await?;
2214 workspace.update(&mut cx, |workspace, cx| {
2215 let editor =
2216 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2217 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2218 editor
2219 })
2220 })
2221 }
2222
2223 fn new_file_vertical(
2224 workspace: &mut Workspace,
2225 _: &workspace::NewFileSplitVertical,
2226 cx: &mut ViewContext<Workspace>,
2227 ) {
2228 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2229 }
2230
2231 fn new_file_horizontal(
2232 workspace: &mut Workspace,
2233 _: &workspace::NewFileSplitHorizontal,
2234 cx: &mut ViewContext<Workspace>,
2235 ) {
2236 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2237 }
2238
2239 fn new_file_in_direction(
2240 workspace: &mut Workspace,
2241 direction: SplitDirection,
2242 cx: &mut ViewContext<Workspace>,
2243 ) {
2244 let project = workspace.project().clone();
2245 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2246
2247 cx.spawn(|workspace, mut cx| async move {
2248 let buffer = create.await?;
2249 workspace.update(&mut cx, move |workspace, cx| {
2250 workspace.split_item(
2251 direction,
2252 Box::new(
2253 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2254 ),
2255 cx,
2256 )
2257 })?;
2258 anyhow::Ok(())
2259 })
2260 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2261 ErrorCode::RemoteUpgradeRequired => Some(format!(
2262 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2263 e.error_tag("required").unwrap_or("the latest version")
2264 )),
2265 _ => None,
2266 });
2267 }
2268
2269 pub fn leader_peer_id(&self) -> Option<PeerId> {
2270 self.leader_peer_id
2271 }
2272
2273 pub fn buffer(&self) -> &Model<MultiBuffer> {
2274 &self.buffer
2275 }
2276
2277 pub fn workspace(&self) -> Option<View<Workspace>> {
2278 self.workspace.as_ref()?.0.upgrade()
2279 }
2280
2281 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2282 self.buffer().read(cx).title(cx)
2283 }
2284
2285 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2286 let git_blame_gutter_max_author_length = self
2287 .render_git_blame_gutter(cx)
2288 .then(|| {
2289 if let Some(blame) = self.blame.as_ref() {
2290 let max_author_length =
2291 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2292 Some(max_author_length)
2293 } else {
2294 None
2295 }
2296 })
2297 .flatten();
2298
2299 EditorSnapshot {
2300 mode: self.mode,
2301 show_gutter: self.show_gutter,
2302 show_line_numbers: self.show_line_numbers,
2303 show_git_diff_gutter: self.show_git_diff_gutter,
2304 show_code_actions: self.show_code_actions,
2305 show_runnables: self.show_runnables,
2306 git_blame_gutter_max_author_length,
2307 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2308 scroll_anchor: self.scroll_manager.anchor(),
2309 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2310 placeholder_text: self.placeholder_text.clone(),
2311 is_focused: self.focus_handle.is_focused(cx),
2312 current_line_highlight: self
2313 .current_line_highlight
2314 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2315 gutter_hovered: self.gutter_hovered,
2316 }
2317 }
2318
2319 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2320 self.buffer.read(cx).language_at(point, cx)
2321 }
2322
2323 pub fn file_at<T: ToOffset>(
2324 &self,
2325 point: T,
2326 cx: &AppContext,
2327 ) -> Option<Arc<dyn language::File>> {
2328 self.buffer.read(cx).read(cx).file_at(point).cloned()
2329 }
2330
2331 pub fn active_excerpt(
2332 &self,
2333 cx: &AppContext,
2334 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2335 self.buffer
2336 .read(cx)
2337 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2338 }
2339
2340 pub fn mode(&self) -> EditorMode {
2341 self.mode
2342 }
2343
2344 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2345 self.collaboration_hub.as_deref()
2346 }
2347
2348 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2349 self.collaboration_hub = Some(hub);
2350 }
2351
2352 pub fn set_custom_context_menu(
2353 &mut self,
2354 f: impl 'static
2355 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2356 ) {
2357 self.custom_context_menu = Some(Box::new(f))
2358 }
2359
2360 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2361 self.completion_provider = provider;
2362 }
2363
2364 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2365 self.semantics_provider.clone()
2366 }
2367
2368 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2369 self.semantics_provider = provider;
2370 }
2371
2372 pub fn set_inline_completion_provider<T>(
2373 &mut self,
2374 provider: Option<Model<T>>,
2375 cx: &mut ViewContext<Self>,
2376 ) where
2377 T: InlineCompletionProvider,
2378 {
2379 self.inline_completion_provider =
2380 provider.map(|provider| RegisteredInlineCompletionProvider {
2381 _subscription: cx.observe(&provider, |this, _, cx| {
2382 if this.focus_handle.is_focused(cx) {
2383 this.update_visible_inline_completion(cx);
2384 }
2385 }),
2386 provider: Arc::new(provider),
2387 });
2388 self.refresh_inline_completion(false, false, cx);
2389 }
2390
2391 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2392 self.placeholder_text.as_deref()
2393 }
2394
2395 pub fn set_placeholder_text(
2396 &mut self,
2397 placeholder_text: impl Into<Arc<str>>,
2398 cx: &mut ViewContext<Self>,
2399 ) {
2400 let placeholder_text = Some(placeholder_text.into());
2401 if self.placeholder_text != placeholder_text {
2402 self.placeholder_text = placeholder_text;
2403 cx.notify();
2404 }
2405 }
2406
2407 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2408 self.cursor_shape = cursor_shape;
2409
2410 // Disrupt blink for immediate user feedback that the cursor shape has changed
2411 self.blink_manager.update(cx, BlinkManager::show_cursor);
2412
2413 cx.notify();
2414 }
2415
2416 pub fn set_current_line_highlight(
2417 &mut self,
2418 current_line_highlight: Option<CurrentLineHighlight>,
2419 ) {
2420 self.current_line_highlight = current_line_highlight;
2421 }
2422
2423 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2424 self.collapse_matches = collapse_matches;
2425 }
2426
2427 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2428 if self.collapse_matches {
2429 return range.start..range.start;
2430 }
2431 range.clone()
2432 }
2433
2434 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2435 if self.display_map.read(cx).clip_at_line_ends != clip {
2436 self.display_map
2437 .update(cx, |map, _| map.clip_at_line_ends = clip);
2438 }
2439 }
2440
2441 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2442 self.input_enabled = input_enabled;
2443 }
2444
2445 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2446 self.enable_inline_completions = enabled;
2447 }
2448
2449 pub fn set_autoindent(&mut self, autoindent: bool) {
2450 if autoindent {
2451 self.autoindent_mode = Some(AutoindentMode::EachLine);
2452 } else {
2453 self.autoindent_mode = None;
2454 }
2455 }
2456
2457 pub fn read_only(&self, cx: &AppContext) -> bool {
2458 self.read_only || self.buffer.read(cx).read_only()
2459 }
2460
2461 pub fn set_read_only(&mut self, read_only: bool) {
2462 self.read_only = read_only;
2463 }
2464
2465 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2466 self.use_autoclose = autoclose;
2467 }
2468
2469 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2470 self.use_auto_surround = auto_surround;
2471 }
2472
2473 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2474 self.auto_replace_emoji_shortcode = auto_replace;
2475 }
2476
2477 pub fn toggle_inline_completions(
2478 &mut self,
2479 _: &ToggleInlineCompletions,
2480 cx: &mut ViewContext<Self>,
2481 ) {
2482 if self.show_inline_completions_override.is_some() {
2483 self.set_show_inline_completions(None, cx);
2484 } else {
2485 let cursor = self.selections.newest_anchor().head();
2486 if let Some((buffer, cursor_buffer_position)) =
2487 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2488 {
2489 let show_inline_completions =
2490 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2491 self.set_show_inline_completions(Some(show_inline_completions), cx);
2492 }
2493 }
2494 }
2495
2496 pub fn set_show_inline_completions(
2497 &mut self,
2498 show_inline_completions: Option<bool>,
2499 cx: &mut ViewContext<Self>,
2500 ) {
2501 self.show_inline_completions_override = show_inline_completions;
2502 self.refresh_inline_completion(false, true, cx);
2503 }
2504
2505 fn should_show_inline_completions(
2506 &self,
2507 buffer: &Model<Buffer>,
2508 buffer_position: language::Anchor,
2509 cx: &AppContext,
2510 ) -> bool {
2511 if !self.snippet_stack.is_empty() {
2512 return false;
2513 }
2514
2515 if let Some(provider) = self.inline_completion_provider() {
2516 if let Some(show_inline_completions) = self.show_inline_completions_override {
2517 show_inline_completions
2518 } else {
2519 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2520 }
2521 } else {
2522 false
2523 }
2524 }
2525
2526 pub fn set_use_modal_editing(&mut self, to: bool) {
2527 self.use_modal_editing = to;
2528 }
2529
2530 pub fn use_modal_editing(&self) -> bool {
2531 self.use_modal_editing
2532 }
2533
2534 fn selections_did_change(
2535 &mut self,
2536 local: bool,
2537 old_cursor_position: &Anchor,
2538 show_completions: bool,
2539 cx: &mut ViewContext<Self>,
2540 ) {
2541 cx.invalidate_character_coordinates();
2542
2543 // Copy selections to primary selection buffer
2544 #[cfg(target_os = "linux")]
2545 if local {
2546 let selections = self.selections.all::<usize>(cx);
2547 let buffer_handle = self.buffer.read(cx).read(cx);
2548
2549 let mut text = String::new();
2550 for (index, selection) in selections.iter().enumerate() {
2551 let text_for_selection = buffer_handle
2552 .text_for_range(selection.start..selection.end)
2553 .collect::<String>();
2554
2555 text.push_str(&text_for_selection);
2556 if index != selections.len() - 1 {
2557 text.push('\n');
2558 }
2559 }
2560
2561 if !text.is_empty() {
2562 cx.write_to_primary(ClipboardItem::new_string(text));
2563 }
2564 }
2565
2566 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2567 self.buffer.update(cx, |buffer, cx| {
2568 buffer.set_active_selections(
2569 &self.selections.disjoint_anchors(),
2570 self.selections.line_mode,
2571 self.cursor_shape,
2572 cx,
2573 )
2574 });
2575 }
2576 let display_map = self
2577 .display_map
2578 .update(cx, |display_map, cx| display_map.snapshot(cx));
2579 let buffer = &display_map.buffer_snapshot;
2580 self.add_selections_state = None;
2581 self.select_next_state = None;
2582 self.select_prev_state = None;
2583 self.select_larger_syntax_node_stack.clear();
2584 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2585 self.snippet_stack
2586 .invalidate(&self.selections.disjoint_anchors(), buffer);
2587 self.take_rename(false, cx);
2588
2589 let new_cursor_position = self.selections.newest_anchor().head();
2590
2591 self.push_to_nav_history(
2592 *old_cursor_position,
2593 Some(new_cursor_position.to_point(buffer)),
2594 cx,
2595 );
2596
2597 if local {
2598 let new_cursor_position = self.selections.newest_anchor().head();
2599 let mut context_menu = self.context_menu.write();
2600 let completion_menu = match context_menu.as_ref() {
2601 Some(ContextMenu::Completions(menu)) => Some(menu),
2602
2603 _ => {
2604 *context_menu = None;
2605 None
2606 }
2607 };
2608
2609 if let Some(completion_menu) = completion_menu {
2610 let cursor_position = new_cursor_position.to_offset(buffer);
2611 let (word_range, kind) =
2612 buffer.surrounding_word(completion_menu.initial_position, true);
2613 if kind == Some(CharKind::Word)
2614 && word_range.to_inclusive().contains(&cursor_position)
2615 {
2616 let mut completion_menu = completion_menu.clone();
2617 drop(context_menu);
2618
2619 let query = Self::completion_query(buffer, cursor_position);
2620 cx.spawn(move |this, mut cx| async move {
2621 completion_menu
2622 .filter(query.as_deref(), cx.background_executor().clone())
2623 .await;
2624
2625 this.update(&mut cx, |this, cx| {
2626 let mut context_menu = this.context_menu.write();
2627 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2628 return;
2629 };
2630
2631 if menu.id > completion_menu.id {
2632 return;
2633 }
2634
2635 *context_menu = Some(ContextMenu::Completions(completion_menu));
2636 drop(context_menu);
2637 cx.notify();
2638 })
2639 })
2640 .detach();
2641
2642 if show_completions {
2643 self.show_completions(&ShowCompletions { trigger: None }, cx);
2644 }
2645 } else {
2646 drop(context_menu);
2647 self.hide_context_menu(cx);
2648 }
2649 } else {
2650 drop(context_menu);
2651 }
2652
2653 hide_hover(self, cx);
2654
2655 if old_cursor_position.to_display_point(&display_map).row()
2656 != new_cursor_position.to_display_point(&display_map).row()
2657 {
2658 self.available_code_actions.take();
2659 }
2660 self.refresh_code_actions(cx);
2661 self.refresh_document_highlights(cx);
2662 refresh_matching_bracket_highlights(self, cx);
2663 self.discard_inline_completion(false, cx);
2664 linked_editing_ranges::refresh_linked_ranges(self, cx);
2665 if self.git_blame_inline_enabled {
2666 self.start_inline_blame_timer(cx);
2667 }
2668 }
2669
2670 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2671 cx.emit(EditorEvent::SelectionsChanged { local });
2672
2673 if self.selections.disjoint_anchors().len() == 1 {
2674 cx.emit(SearchEvent::ActiveMatchChanged)
2675 }
2676 cx.notify();
2677 }
2678
2679 pub fn change_selections<R>(
2680 &mut self,
2681 autoscroll: Option<Autoscroll>,
2682 cx: &mut ViewContext<Self>,
2683 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2684 ) -> R {
2685 self.change_selections_inner(autoscroll, true, cx, change)
2686 }
2687
2688 pub fn change_selections_inner<R>(
2689 &mut self,
2690 autoscroll: Option<Autoscroll>,
2691 request_completions: bool,
2692 cx: &mut ViewContext<Self>,
2693 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2694 ) -> R {
2695 let old_cursor_position = self.selections.newest_anchor().head();
2696 self.push_to_selection_history();
2697
2698 let (changed, result) = self.selections.change_with(cx, change);
2699
2700 if changed {
2701 if let Some(autoscroll) = autoscroll {
2702 self.request_autoscroll(autoscroll, cx);
2703 }
2704 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2705
2706 if self.should_open_signature_help_automatically(
2707 &old_cursor_position,
2708 self.signature_help_state.backspace_pressed(),
2709 cx,
2710 ) {
2711 self.show_signature_help(&ShowSignatureHelp, cx);
2712 }
2713 self.signature_help_state.set_backspace_pressed(false);
2714 }
2715
2716 result
2717 }
2718
2719 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2720 where
2721 I: IntoIterator<Item = (Range<S>, T)>,
2722 S: ToOffset,
2723 T: Into<Arc<str>>,
2724 {
2725 if self.read_only(cx) {
2726 return;
2727 }
2728
2729 self.buffer
2730 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2731 }
2732
2733 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2734 where
2735 I: IntoIterator<Item = (Range<S>, T)>,
2736 S: ToOffset,
2737 T: Into<Arc<str>>,
2738 {
2739 if self.read_only(cx) {
2740 return;
2741 }
2742
2743 self.buffer.update(cx, |buffer, cx| {
2744 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2745 });
2746 }
2747
2748 pub fn edit_with_block_indent<I, S, T>(
2749 &mut self,
2750 edits: I,
2751 original_indent_columns: Vec<u32>,
2752 cx: &mut ViewContext<Self>,
2753 ) where
2754 I: IntoIterator<Item = (Range<S>, T)>,
2755 S: ToOffset,
2756 T: Into<Arc<str>>,
2757 {
2758 if self.read_only(cx) {
2759 return;
2760 }
2761
2762 self.buffer.update(cx, |buffer, cx| {
2763 buffer.edit(
2764 edits,
2765 Some(AutoindentMode::Block {
2766 original_indent_columns,
2767 }),
2768 cx,
2769 )
2770 });
2771 }
2772
2773 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2774 self.hide_context_menu(cx);
2775
2776 match phase {
2777 SelectPhase::Begin {
2778 position,
2779 add,
2780 click_count,
2781 } => self.begin_selection(position, add, click_count, cx),
2782 SelectPhase::BeginColumnar {
2783 position,
2784 goal_column,
2785 reset,
2786 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2787 SelectPhase::Extend {
2788 position,
2789 click_count,
2790 } => self.extend_selection(position, click_count, cx),
2791 SelectPhase::Update {
2792 position,
2793 goal_column,
2794 scroll_delta,
2795 } => self.update_selection(position, goal_column, scroll_delta, cx),
2796 SelectPhase::End => self.end_selection(cx),
2797 }
2798 }
2799
2800 fn extend_selection(
2801 &mut self,
2802 position: DisplayPoint,
2803 click_count: usize,
2804 cx: &mut ViewContext<Self>,
2805 ) {
2806 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2807 let tail = self.selections.newest::<usize>(cx).tail();
2808 self.begin_selection(position, false, click_count, cx);
2809
2810 let position = position.to_offset(&display_map, Bias::Left);
2811 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2812
2813 let mut pending_selection = self
2814 .selections
2815 .pending_anchor()
2816 .expect("extend_selection not called with pending selection");
2817 if position >= tail {
2818 pending_selection.start = tail_anchor;
2819 } else {
2820 pending_selection.end = tail_anchor;
2821 pending_selection.reversed = true;
2822 }
2823
2824 let mut pending_mode = self.selections.pending_mode().unwrap();
2825 match &mut pending_mode {
2826 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2827 _ => {}
2828 }
2829
2830 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2831 s.set_pending(pending_selection, pending_mode)
2832 });
2833 }
2834
2835 fn begin_selection(
2836 &mut self,
2837 position: DisplayPoint,
2838 add: bool,
2839 click_count: usize,
2840 cx: &mut ViewContext<Self>,
2841 ) {
2842 if !self.focus_handle.is_focused(cx) {
2843 self.last_focused_descendant = None;
2844 cx.focus(&self.focus_handle);
2845 }
2846
2847 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2848 let buffer = &display_map.buffer_snapshot;
2849 let newest_selection = self.selections.newest_anchor().clone();
2850 let position = display_map.clip_point(position, Bias::Left);
2851
2852 let start;
2853 let end;
2854 let mode;
2855 let auto_scroll;
2856 match click_count {
2857 1 => {
2858 start = buffer.anchor_before(position.to_point(&display_map));
2859 end = start;
2860 mode = SelectMode::Character;
2861 auto_scroll = true;
2862 }
2863 2 => {
2864 let range = movement::surrounding_word(&display_map, position);
2865 start = buffer.anchor_before(range.start.to_point(&display_map));
2866 end = buffer.anchor_before(range.end.to_point(&display_map));
2867 mode = SelectMode::Word(start..end);
2868 auto_scroll = true;
2869 }
2870 3 => {
2871 let position = display_map
2872 .clip_point(position, Bias::Left)
2873 .to_point(&display_map);
2874 let line_start = display_map.prev_line_boundary(position).0;
2875 let next_line_start = buffer.clip_point(
2876 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2877 Bias::Left,
2878 );
2879 start = buffer.anchor_before(line_start);
2880 end = buffer.anchor_before(next_line_start);
2881 mode = SelectMode::Line(start..end);
2882 auto_scroll = true;
2883 }
2884 _ => {
2885 start = buffer.anchor_before(0);
2886 end = buffer.anchor_before(buffer.len());
2887 mode = SelectMode::All;
2888 auto_scroll = false;
2889 }
2890 }
2891
2892 let point_to_delete: Option<usize> = {
2893 let selected_points: Vec<Selection<Point>> =
2894 self.selections.disjoint_in_range(start..end, cx);
2895
2896 if !add || click_count > 1 {
2897 None
2898 } else if !selected_points.is_empty() {
2899 Some(selected_points[0].id)
2900 } else {
2901 let clicked_point_already_selected =
2902 self.selections.disjoint.iter().find(|selection| {
2903 selection.start.to_point(buffer) == start.to_point(buffer)
2904 || selection.end.to_point(buffer) == end.to_point(buffer)
2905 });
2906
2907 clicked_point_already_selected.map(|selection| selection.id)
2908 }
2909 };
2910
2911 let selections_count = self.selections.count();
2912
2913 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2914 if let Some(point_to_delete) = point_to_delete {
2915 s.delete(point_to_delete);
2916
2917 if selections_count == 1 {
2918 s.set_pending_anchor_range(start..end, mode);
2919 }
2920 } else {
2921 if !add {
2922 s.clear_disjoint();
2923 } else if click_count > 1 {
2924 s.delete(newest_selection.id)
2925 }
2926
2927 s.set_pending_anchor_range(start..end, mode);
2928 }
2929 });
2930 }
2931
2932 fn begin_columnar_selection(
2933 &mut self,
2934 position: DisplayPoint,
2935 goal_column: u32,
2936 reset: bool,
2937 cx: &mut ViewContext<Self>,
2938 ) {
2939 if !self.focus_handle.is_focused(cx) {
2940 self.last_focused_descendant = None;
2941 cx.focus(&self.focus_handle);
2942 }
2943
2944 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2945
2946 if reset {
2947 let pointer_position = display_map
2948 .buffer_snapshot
2949 .anchor_before(position.to_point(&display_map));
2950
2951 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2952 s.clear_disjoint();
2953 s.set_pending_anchor_range(
2954 pointer_position..pointer_position,
2955 SelectMode::Character,
2956 );
2957 });
2958 }
2959
2960 let tail = self.selections.newest::<Point>(cx).tail();
2961 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2962
2963 if !reset {
2964 self.select_columns(
2965 tail.to_display_point(&display_map),
2966 position,
2967 goal_column,
2968 &display_map,
2969 cx,
2970 );
2971 }
2972 }
2973
2974 fn update_selection(
2975 &mut self,
2976 position: DisplayPoint,
2977 goal_column: u32,
2978 scroll_delta: gpui::Point<f32>,
2979 cx: &mut ViewContext<Self>,
2980 ) {
2981 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2982
2983 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2984 let tail = tail.to_display_point(&display_map);
2985 self.select_columns(tail, position, goal_column, &display_map, cx);
2986 } else if let Some(mut pending) = self.selections.pending_anchor() {
2987 let buffer = self.buffer.read(cx).snapshot(cx);
2988 let head;
2989 let tail;
2990 let mode = self.selections.pending_mode().unwrap();
2991 match &mode {
2992 SelectMode::Character => {
2993 head = position.to_point(&display_map);
2994 tail = pending.tail().to_point(&buffer);
2995 }
2996 SelectMode::Word(original_range) => {
2997 let original_display_range = original_range.start.to_display_point(&display_map)
2998 ..original_range.end.to_display_point(&display_map);
2999 let original_buffer_range = original_display_range.start.to_point(&display_map)
3000 ..original_display_range.end.to_point(&display_map);
3001 if movement::is_inside_word(&display_map, position)
3002 || original_display_range.contains(&position)
3003 {
3004 let word_range = movement::surrounding_word(&display_map, position);
3005 if word_range.start < original_display_range.start {
3006 head = word_range.start.to_point(&display_map);
3007 } else {
3008 head = word_range.end.to_point(&display_map);
3009 }
3010 } else {
3011 head = position.to_point(&display_map);
3012 }
3013
3014 if head <= original_buffer_range.start {
3015 tail = original_buffer_range.end;
3016 } else {
3017 tail = original_buffer_range.start;
3018 }
3019 }
3020 SelectMode::Line(original_range) => {
3021 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3022
3023 let position = display_map
3024 .clip_point(position, Bias::Left)
3025 .to_point(&display_map);
3026 let line_start = display_map.prev_line_boundary(position).0;
3027 let next_line_start = buffer.clip_point(
3028 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3029 Bias::Left,
3030 );
3031
3032 if line_start < original_range.start {
3033 head = line_start
3034 } else {
3035 head = next_line_start
3036 }
3037
3038 if head <= original_range.start {
3039 tail = original_range.end;
3040 } else {
3041 tail = original_range.start;
3042 }
3043 }
3044 SelectMode::All => {
3045 return;
3046 }
3047 };
3048
3049 if head < tail {
3050 pending.start = buffer.anchor_before(head);
3051 pending.end = buffer.anchor_before(tail);
3052 pending.reversed = true;
3053 } else {
3054 pending.start = buffer.anchor_before(tail);
3055 pending.end = buffer.anchor_before(head);
3056 pending.reversed = false;
3057 }
3058
3059 self.change_selections(None, cx, |s| {
3060 s.set_pending(pending, mode);
3061 });
3062 } else {
3063 log::error!("update_selection dispatched with no pending selection");
3064 return;
3065 }
3066
3067 self.apply_scroll_delta(scroll_delta, cx);
3068 cx.notify();
3069 }
3070
3071 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3072 self.columnar_selection_tail.take();
3073 if self.selections.pending_anchor().is_some() {
3074 let selections = self.selections.all::<usize>(cx);
3075 self.change_selections(None, cx, |s| {
3076 s.select(selections);
3077 s.clear_pending();
3078 });
3079 }
3080 }
3081
3082 fn select_columns(
3083 &mut self,
3084 tail: DisplayPoint,
3085 head: DisplayPoint,
3086 goal_column: u32,
3087 display_map: &DisplaySnapshot,
3088 cx: &mut ViewContext<Self>,
3089 ) {
3090 let start_row = cmp::min(tail.row(), head.row());
3091 let end_row = cmp::max(tail.row(), head.row());
3092 let start_column = cmp::min(tail.column(), goal_column);
3093 let end_column = cmp::max(tail.column(), goal_column);
3094 let reversed = start_column < tail.column();
3095
3096 let selection_ranges = (start_row.0..=end_row.0)
3097 .map(DisplayRow)
3098 .filter_map(|row| {
3099 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3100 let start = display_map
3101 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3102 .to_point(display_map);
3103 let end = display_map
3104 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3105 .to_point(display_map);
3106 if reversed {
3107 Some(end..start)
3108 } else {
3109 Some(start..end)
3110 }
3111 } else {
3112 None
3113 }
3114 })
3115 .collect::<Vec<_>>();
3116
3117 self.change_selections(None, cx, |s| {
3118 s.select_ranges(selection_ranges);
3119 });
3120 cx.notify();
3121 }
3122
3123 pub fn has_pending_nonempty_selection(&self) -> bool {
3124 let pending_nonempty_selection = match self.selections.pending_anchor() {
3125 Some(Selection { start, end, .. }) => start != end,
3126 None => false,
3127 };
3128
3129 pending_nonempty_selection
3130 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3131 }
3132
3133 pub fn has_pending_selection(&self) -> bool {
3134 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3135 }
3136
3137 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3138 if self.clear_expanded_diff_hunks(cx) {
3139 cx.notify();
3140 return;
3141 }
3142 if self.dismiss_menus_and_popups(true, cx) {
3143 return;
3144 }
3145
3146 if self.mode == EditorMode::Full
3147 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3148 {
3149 return;
3150 }
3151
3152 cx.propagate();
3153 }
3154
3155 pub fn dismiss_menus_and_popups(
3156 &mut self,
3157 should_report_inline_completion_event: bool,
3158 cx: &mut ViewContext<Self>,
3159 ) -> bool {
3160 if self.take_rename(false, cx).is_some() {
3161 return true;
3162 }
3163
3164 if hide_hover(self, cx) {
3165 return true;
3166 }
3167
3168 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3169 return true;
3170 }
3171
3172 if self.hide_context_menu(cx).is_some() {
3173 return true;
3174 }
3175
3176 if self.mouse_context_menu.take().is_some() {
3177 return true;
3178 }
3179
3180 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3181 return true;
3182 }
3183
3184 if self.snippet_stack.pop().is_some() {
3185 return true;
3186 }
3187
3188 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3189 self.dismiss_diagnostics(cx);
3190 return true;
3191 }
3192
3193 false
3194 }
3195
3196 fn linked_editing_ranges_for(
3197 &self,
3198 selection: Range<text::Anchor>,
3199 cx: &AppContext,
3200 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3201 if self.linked_edit_ranges.is_empty() {
3202 return None;
3203 }
3204 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3205 selection.end.buffer_id.and_then(|end_buffer_id| {
3206 if selection.start.buffer_id != Some(end_buffer_id) {
3207 return None;
3208 }
3209 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3210 let snapshot = buffer.read(cx).snapshot();
3211 self.linked_edit_ranges
3212 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3213 .map(|ranges| (ranges, snapshot, buffer))
3214 })?;
3215 use text::ToOffset as TO;
3216 // find offset from the start of current range to current cursor position
3217 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3218
3219 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3220 let start_difference = start_offset - start_byte_offset;
3221 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3222 let end_difference = end_offset - start_byte_offset;
3223 // Current range has associated linked ranges.
3224 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3225 for range in linked_ranges.iter() {
3226 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3227 let end_offset = start_offset + end_difference;
3228 let start_offset = start_offset + start_difference;
3229 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3230 continue;
3231 }
3232 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3233 if s.start.buffer_id != selection.start.buffer_id
3234 || s.end.buffer_id != selection.end.buffer_id
3235 {
3236 return false;
3237 }
3238 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3239 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3240 }) {
3241 continue;
3242 }
3243 let start = buffer_snapshot.anchor_after(start_offset);
3244 let end = buffer_snapshot.anchor_after(end_offset);
3245 linked_edits
3246 .entry(buffer.clone())
3247 .or_default()
3248 .push(start..end);
3249 }
3250 Some(linked_edits)
3251 }
3252
3253 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3254 let text: Arc<str> = text.into();
3255
3256 if self.read_only(cx) {
3257 return;
3258 }
3259
3260 let selections = self.selections.all_adjusted(cx);
3261 let mut bracket_inserted = false;
3262 let mut edits = Vec::new();
3263 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3264 let mut new_selections = Vec::with_capacity(selections.len());
3265 let mut new_autoclose_regions = Vec::new();
3266 let snapshot = self.buffer.read(cx).read(cx);
3267
3268 for (selection, autoclose_region) in
3269 self.selections_with_autoclose_regions(selections, &snapshot)
3270 {
3271 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3272 // Determine if the inserted text matches the opening or closing
3273 // bracket of any of this language's bracket pairs.
3274 let mut bracket_pair = None;
3275 let mut is_bracket_pair_start = false;
3276 let mut is_bracket_pair_end = false;
3277 if !text.is_empty() {
3278 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3279 // and they are removing the character that triggered IME popup.
3280 for (pair, enabled) in scope.brackets() {
3281 if !pair.close && !pair.surround {
3282 continue;
3283 }
3284
3285 if enabled && pair.start.ends_with(text.as_ref()) {
3286 let prefix_len = pair.start.len() - text.len();
3287 let preceding_text_matches_prefix = prefix_len == 0
3288 || (selection.start.column >= (prefix_len as u32)
3289 && snapshot.contains_str_at(
3290 Point::new(
3291 selection.start.row,
3292 selection.start.column - (prefix_len as u32),
3293 ),
3294 &pair.start[..prefix_len],
3295 ));
3296 if preceding_text_matches_prefix {
3297 bracket_pair = Some(pair.clone());
3298 is_bracket_pair_start = true;
3299 break;
3300 }
3301 }
3302 if pair.end.as_str() == text.as_ref() {
3303 bracket_pair = Some(pair.clone());
3304 is_bracket_pair_end = true;
3305 break;
3306 }
3307 }
3308 }
3309
3310 if let Some(bracket_pair) = bracket_pair {
3311 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3312 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3313 let auto_surround =
3314 self.use_auto_surround && snapshot_settings.use_auto_surround;
3315 if selection.is_empty() {
3316 if is_bracket_pair_start {
3317 // If the inserted text is a suffix of an opening bracket and the
3318 // selection is preceded by the rest of the opening bracket, then
3319 // insert the closing bracket.
3320 let following_text_allows_autoclose = snapshot
3321 .chars_at(selection.start)
3322 .next()
3323 .map_or(true, |c| scope.should_autoclose_before(c));
3324
3325 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3326 && bracket_pair.start.len() == 1
3327 {
3328 let target = bracket_pair.start.chars().next().unwrap();
3329 let current_line_count = snapshot
3330 .reversed_chars_at(selection.start)
3331 .take_while(|&c| c != '\n')
3332 .filter(|&c| c == target)
3333 .count();
3334 current_line_count % 2 == 1
3335 } else {
3336 false
3337 };
3338
3339 if autoclose
3340 && bracket_pair.close
3341 && following_text_allows_autoclose
3342 && !is_closing_quote
3343 {
3344 let anchor = snapshot.anchor_before(selection.end);
3345 new_selections.push((selection.map(|_| anchor), text.len()));
3346 new_autoclose_regions.push((
3347 anchor,
3348 text.len(),
3349 selection.id,
3350 bracket_pair.clone(),
3351 ));
3352 edits.push((
3353 selection.range(),
3354 format!("{}{}", text, bracket_pair.end).into(),
3355 ));
3356 bracket_inserted = true;
3357 continue;
3358 }
3359 }
3360
3361 if let Some(region) = autoclose_region {
3362 // If the selection is followed by an auto-inserted closing bracket,
3363 // then don't insert that closing bracket again; just move the selection
3364 // past the closing bracket.
3365 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3366 && text.as_ref() == region.pair.end.as_str();
3367 if should_skip {
3368 let anchor = snapshot.anchor_after(selection.end);
3369 new_selections
3370 .push((selection.map(|_| anchor), region.pair.end.len()));
3371 continue;
3372 }
3373 }
3374
3375 let always_treat_brackets_as_autoclosed = snapshot
3376 .settings_at(selection.start, cx)
3377 .always_treat_brackets_as_autoclosed;
3378 if always_treat_brackets_as_autoclosed
3379 && is_bracket_pair_end
3380 && snapshot.contains_str_at(selection.end, text.as_ref())
3381 {
3382 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3383 // and the inserted text is a closing bracket and the selection is followed
3384 // by the closing bracket then move the selection past the closing bracket.
3385 let anchor = snapshot.anchor_after(selection.end);
3386 new_selections.push((selection.map(|_| anchor), text.len()));
3387 continue;
3388 }
3389 }
3390 // If an opening bracket is 1 character long and is typed while
3391 // text is selected, then surround that text with the bracket pair.
3392 else if auto_surround
3393 && bracket_pair.surround
3394 && is_bracket_pair_start
3395 && bracket_pair.start.chars().count() == 1
3396 {
3397 edits.push((selection.start..selection.start, text.clone()));
3398 edits.push((
3399 selection.end..selection.end,
3400 bracket_pair.end.as_str().into(),
3401 ));
3402 bracket_inserted = true;
3403 new_selections.push((
3404 Selection {
3405 id: selection.id,
3406 start: snapshot.anchor_after(selection.start),
3407 end: snapshot.anchor_before(selection.end),
3408 reversed: selection.reversed,
3409 goal: selection.goal,
3410 },
3411 0,
3412 ));
3413 continue;
3414 }
3415 }
3416 }
3417
3418 if self.auto_replace_emoji_shortcode
3419 && selection.is_empty()
3420 && text.as_ref().ends_with(':')
3421 {
3422 if let Some(possible_emoji_short_code) =
3423 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3424 {
3425 if !possible_emoji_short_code.is_empty() {
3426 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3427 let emoji_shortcode_start = Point::new(
3428 selection.start.row,
3429 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3430 );
3431
3432 // Remove shortcode from buffer
3433 edits.push((
3434 emoji_shortcode_start..selection.start,
3435 "".to_string().into(),
3436 ));
3437 new_selections.push((
3438 Selection {
3439 id: selection.id,
3440 start: snapshot.anchor_after(emoji_shortcode_start),
3441 end: snapshot.anchor_before(selection.start),
3442 reversed: selection.reversed,
3443 goal: selection.goal,
3444 },
3445 0,
3446 ));
3447
3448 // Insert emoji
3449 let selection_start_anchor = snapshot.anchor_after(selection.start);
3450 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3451 edits.push((selection.start..selection.end, emoji.to_string().into()));
3452
3453 continue;
3454 }
3455 }
3456 }
3457 }
3458
3459 // If not handling any auto-close operation, then just replace the selected
3460 // text with the given input and move the selection to the end of the
3461 // newly inserted text.
3462 let anchor = snapshot.anchor_after(selection.end);
3463 if !self.linked_edit_ranges.is_empty() {
3464 let start_anchor = snapshot.anchor_before(selection.start);
3465
3466 let is_word_char = text.chars().next().map_or(true, |char| {
3467 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3468 classifier.is_word(char)
3469 });
3470
3471 if is_word_char {
3472 if let Some(ranges) = self
3473 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3474 {
3475 for (buffer, edits) in ranges {
3476 linked_edits
3477 .entry(buffer.clone())
3478 .or_default()
3479 .extend(edits.into_iter().map(|range| (range, text.clone())));
3480 }
3481 }
3482 }
3483 }
3484
3485 new_selections.push((selection.map(|_| anchor), 0));
3486 edits.push((selection.start..selection.end, text.clone()));
3487 }
3488
3489 drop(snapshot);
3490
3491 self.transact(cx, |this, cx| {
3492 this.buffer.update(cx, |buffer, cx| {
3493 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3494 });
3495 for (buffer, edits) in linked_edits {
3496 buffer.update(cx, |buffer, cx| {
3497 let snapshot = buffer.snapshot();
3498 let edits = edits
3499 .into_iter()
3500 .map(|(range, text)| {
3501 use text::ToPoint as TP;
3502 let end_point = TP::to_point(&range.end, &snapshot);
3503 let start_point = TP::to_point(&range.start, &snapshot);
3504 (start_point..end_point, text)
3505 })
3506 .sorted_by_key(|(range, _)| range.start)
3507 .collect::<Vec<_>>();
3508 buffer.edit(edits, None, cx);
3509 })
3510 }
3511 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3512 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3513 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3514 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3515 .zip(new_selection_deltas)
3516 .map(|(selection, delta)| Selection {
3517 id: selection.id,
3518 start: selection.start + delta,
3519 end: selection.end + delta,
3520 reversed: selection.reversed,
3521 goal: SelectionGoal::None,
3522 })
3523 .collect::<Vec<_>>();
3524
3525 let mut i = 0;
3526 for (position, delta, selection_id, pair) in new_autoclose_regions {
3527 let position = position.to_offset(&map.buffer_snapshot) + delta;
3528 let start = map.buffer_snapshot.anchor_before(position);
3529 let end = map.buffer_snapshot.anchor_after(position);
3530 while let Some(existing_state) = this.autoclose_regions.get(i) {
3531 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3532 Ordering::Less => i += 1,
3533 Ordering::Greater => break,
3534 Ordering::Equal => {
3535 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3536 Ordering::Less => i += 1,
3537 Ordering::Equal => break,
3538 Ordering::Greater => break,
3539 }
3540 }
3541 }
3542 }
3543 this.autoclose_regions.insert(
3544 i,
3545 AutocloseRegion {
3546 selection_id,
3547 range: start..end,
3548 pair,
3549 },
3550 );
3551 }
3552
3553 let had_active_inline_completion = this.has_active_inline_completion(cx);
3554 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3555 s.select(new_selections)
3556 });
3557
3558 if !bracket_inserted {
3559 if let Some(on_type_format_task) =
3560 this.trigger_on_type_formatting(text.to_string(), cx)
3561 {
3562 on_type_format_task.detach_and_log_err(cx);
3563 }
3564 }
3565
3566 let editor_settings = EditorSettings::get_global(cx);
3567 if bracket_inserted
3568 && (editor_settings.auto_signature_help
3569 || editor_settings.show_signature_help_after_edits)
3570 {
3571 this.show_signature_help(&ShowSignatureHelp, cx);
3572 }
3573
3574 let trigger_in_words = !had_active_inline_completion;
3575 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3576 linked_editing_ranges::refresh_linked_ranges(this, cx);
3577 this.refresh_inline_completion(true, false, cx);
3578 });
3579 }
3580
3581 fn find_possible_emoji_shortcode_at_position(
3582 snapshot: &MultiBufferSnapshot,
3583 position: Point,
3584 ) -> Option<String> {
3585 let mut chars = Vec::new();
3586 let mut found_colon = false;
3587 for char in snapshot.reversed_chars_at(position).take(100) {
3588 // Found a possible emoji shortcode in the middle of the buffer
3589 if found_colon {
3590 if char.is_whitespace() {
3591 chars.reverse();
3592 return Some(chars.iter().collect());
3593 }
3594 // If the previous character is not a whitespace, we are in the middle of a word
3595 // and we only want to complete the shortcode if the word is made up of other emojis
3596 let mut containing_word = String::new();
3597 for ch in snapshot
3598 .reversed_chars_at(position)
3599 .skip(chars.len() + 1)
3600 .take(100)
3601 {
3602 if ch.is_whitespace() {
3603 break;
3604 }
3605 containing_word.push(ch);
3606 }
3607 let containing_word = containing_word.chars().rev().collect::<String>();
3608 if util::word_consists_of_emojis(containing_word.as_str()) {
3609 chars.reverse();
3610 return Some(chars.iter().collect());
3611 }
3612 }
3613
3614 if char.is_whitespace() || !char.is_ascii() {
3615 return None;
3616 }
3617 if char == ':' {
3618 found_colon = true;
3619 } else {
3620 chars.push(char);
3621 }
3622 }
3623 // Found a possible emoji shortcode at the beginning of the buffer
3624 chars.reverse();
3625 Some(chars.iter().collect())
3626 }
3627
3628 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3629 self.transact(cx, |this, cx| {
3630 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3631 let selections = this.selections.all::<usize>(cx);
3632 let multi_buffer = this.buffer.read(cx);
3633 let buffer = multi_buffer.snapshot(cx);
3634 selections
3635 .iter()
3636 .map(|selection| {
3637 let start_point = selection.start.to_point(&buffer);
3638 let mut indent =
3639 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3640 indent.len = cmp::min(indent.len, start_point.column);
3641 let start = selection.start;
3642 let end = selection.end;
3643 let selection_is_empty = start == end;
3644 let language_scope = buffer.language_scope_at(start);
3645 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3646 &language_scope
3647 {
3648 let leading_whitespace_len = buffer
3649 .reversed_chars_at(start)
3650 .take_while(|c| c.is_whitespace() && *c != '\n')
3651 .map(|c| c.len_utf8())
3652 .sum::<usize>();
3653
3654 let trailing_whitespace_len = buffer
3655 .chars_at(end)
3656 .take_while(|c| c.is_whitespace() && *c != '\n')
3657 .map(|c| c.len_utf8())
3658 .sum::<usize>();
3659
3660 let insert_extra_newline =
3661 language.brackets().any(|(pair, enabled)| {
3662 let pair_start = pair.start.trim_end();
3663 let pair_end = pair.end.trim_start();
3664
3665 enabled
3666 && pair.newline
3667 && buffer.contains_str_at(
3668 end + trailing_whitespace_len,
3669 pair_end,
3670 )
3671 && buffer.contains_str_at(
3672 (start - leading_whitespace_len)
3673 .saturating_sub(pair_start.len()),
3674 pair_start,
3675 )
3676 });
3677
3678 // Comment extension on newline is allowed only for cursor selections
3679 let comment_delimiter = maybe!({
3680 if !selection_is_empty {
3681 return None;
3682 }
3683
3684 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3685 return None;
3686 }
3687
3688 let delimiters = language.line_comment_prefixes();
3689 let max_len_of_delimiter =
3690 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3691 let (snapshot, range) =
3692 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3693
3694 let mut index_of_first_non_whitespace = 0;
3695 let comment_candidate = snapshot
3696 .chars_for_range(range)
3697 .skip_while(|c| {
3698 let should_skip = c.is_whitespace();
3699 if should_skip {
3700 index_of_first_non_whitespace += 1;
3701 }
3702 should_skip
3703 })
3704 .take(max_len_of_delimiter)
3705 .collect::<String>();
3706 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3707 comment_candidate.starts_with(comment_prefix.as_ref())
3708 })?;
3709 let cursor_is_placed_after_comment_marker =
3710 index_of_first_non_whitespace + comment_prefix.len()
3711 <= start_point.column as usize;
3712 if cursor_is_placed_after_comment_marker {
3713 Some(comment_prefix.clone())
3714 } else {
3715 None
3716 }
3717 });
3718 (comment_delimiter, insert_extra_newline)
3719 } else {
3720 (None, false)
3721 };
3722
3723 let capacity_for_delimiter = comment_delimiter
3724 .as_deref()
3725 .map(str::len)
3726 .unwrap_or_default();
3727 let mut new_text =
3728 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3729 new_text.push('\n');
3730 new_text.extend(indent.chars());
3731 if let Some(delimiter) = &comment_delimiter {
3732 new_text.push_str(delimiter);
3733 }
3734 if insert_extra_newline {
3735 new_text = new_text.repeat(2);
3736 }
3737
3738 let anchor = buffer.anchor_after(end);
3739 let new_selection = selection.map(|_| anchor);
3740 (
3741 (start..end, new_text),
3742 (insert_extra_newline, new_selection),
3743 )
3744 })
3745 .unzip()
3746 };
3747
3748 this.edit_with_autoindent(edits, cx);
3749 let buffer = this.buffer.read(cx).snapshot(cx);
3750 let new_selections = selection_fixup_info
3751 .into_iter()
3752 .map(|(extra_newline_inserted, new_selection)| {
3753 let mut cursor = new_selection.end.to_point(&buffer);
3754 if extra_newline_inserted {
3755 cursor.row -= 1;
3756 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3757 }
3758 new_selection.map(|_| cursor)
3759 })
3760 .collect();
3761
3762 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3763 this.refresh_inline_completion(true, false, cx);
3764 });
3765 }
3766
3767 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3768 let buffer = self.buffer.read(cx);
3769 let snapshot = buffer.snapshot(cx);
3770
3771 let mut edits = Vec::new();
3772 let mut rows = Vec::new();
3773
3774 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3775 let cursor = selection.head();
3776 let row = cursor.row;
3777
3778 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3779
3780 let newline = "\n".to_string();
3781 edits.push((start_of_line..start_of_line, newline));
3782
3783 rows.push(row + rows_inserted as u32);
3784 }
3785
3786 self.transact(cx, |editor, cx| {
3787 editor.edit(edits, cx);
3788
3789 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3790 let mut index = 0;
3791 s.move_cursors_with(|map, _, _| {
3792 let row = rows[index];
3793 index += 1;
3794
3795 let point = Point::new(row, 0);
3796 let boundary = map.next_line_boundary(point).1;
3797 let clipped = map.clip_point(boundary, Bias::Left);
3798
3799 (clipped, SelectionGoal::None)
3800 });
3801 });
3802
3803 let mut indent_edits = Vec::new();
3804 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3805 for row in rows {
3806 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3807 for (row, indent) in indents {
3808 if indent.len == 0 {
3809 continue;
3810 }
3811
3812 let text = match indent.kind {
3813 IndentKind::Space => " ".repeat(indent.len as usize),
3814 IndentKind::Tab => "\t".repeat(indent.len as usize),
3815 };
3816 let point = Point::new(row.0, 0);
3817 indent_edits.push((point..point, text));
3818 }
3819 }
3820 editor.edit(indent_edits, cx);
3821 });
3822 }
3823
3824 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3825 let buffer = self.buffer.read(cx);
3826 let snapshot = buffer.snapshot(cx);
3827
3828 let mut edits = Vec::new();
3829 let mut rows = Vec::new();
3830 let mut rows_inserted = 0;
3831
3832 for selection in self.selections.all_adjusted(cx) {
3833 let cursor = selection.head();
3834 let row = cursor.row;
3835
3836 let point = Point::new(row + 1, 0);
3837 let start_of_line = snapshot.clip_point(point, Bias::Left);
3838
3839 let newline = "\n".to_string();
3840 edits.push((start_of_line..start_of_line, newline));
3841
3842 rows_inserted += 1;
3843 rows.push(row + rows_inserted);
3844 }
3845
3846 self.transact(cx, |editor, cx| {
3847 editor.edit(edits, cx);
3848
3849 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3850 let mut index = 0;
3851 s.move_cursors_with(|map, _, _| {
3852 let row = rows[index];
3853 index += 1;
3854
3855 let point = Point::new(row, 0);
3856 let boundary = map.next_line_boundary(point).1;
3857 let clipped = map.clip_point(boundary, Bias::Left);
3858
3859 (clipped, SelectionGoal::None)
3860 });
3861 });
3862
3863 let mut indent_edits = Vec::new();
3864 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3865 for row in rows {
3866 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3867 for (row, indent) in indents {
3868 if indent.len == 0 {
3869 continue;
3870 }
3871
3872 let text = match indent.kind {
3873 IndentKind::Space => " ".repeat(indent.len as usize),
3874 IndentKind::Tab => "\t".repeat(indent.len as usize),
3875 };
3876 let point = Point::new(row.0, 0);
3877 indent_edits.push((point..point, text));
3878 }
3879 }
3880 editor.edit(indent_edits, cx);
3881 });
3882 }
3883
3884 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3885 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3886 original_indent_columns: Vec::new(),
3887 });
3888 self.insert_with_autoindent_mode(text, autoindent, cx);
3889 }
3890
3891 fn insert_with_autoindent_mode(
3892 &mut self,
3893 text: &str,
3894 autoindent_mode: Option<AutoindentMode>,
3895 cx: &mut ViewContext<Self>,
3896 ) {
3897 if self.read_only(cx) {
3898 return;
3899 }
3900
3901 let text: Arc<str> = text.into();
3902 self.transact(cx, |this, cx| {
3903 let old_selections = this.selections.all_adjusted(cx);
3904 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3905 let anchors = {
3906 let snapshot = buffer.read(cx);
3907 old_selections
3908 .iter()
3909 .map(|s| {
3910 let anchor = snapshot.anchor_after(s.head());
3911 s.map(|_| anchor)
3912 })
3913 .collect::<Vec<_>>()
3914 };
3915 buffer.edit(
3916 old_selections
3917 .iter()
3918 .map(|s| (s.start..s.end, text.clone())),
3919 autoindent_mode,
3920 cx,
3921 );
3922 anchors
3923 });
3924
3925 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3926 s.select_anchors(selection_anchors);
3927 })
3928 });
3929 }
3930
3931 fn trigger_completion_on_input(
3932 &mut self,
3933 text: &str,
3934 trigger_in_words: bool,
3935 cx: &mut ViewContext<Self>,
3936 ) {
3937 if self.is_completion_trigger(text, trigger_in_words, cx) {
3938 self.show_completions(
3939 &ShowCompletions {
3940 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3941 },
3942 cx,
3943 );
3944 } else {
3945 self.hide_context_menu(cx);
3946 }
3947 }
3948
3949 fn is_completion_trigger(
3950 &self,
3951 text: &str,
3952 trigger_in_words: bool,
3953 cx: &mut ViewContext<Self>,
3954 ) -> bool {
3955 let position = self.selections.newest_anchor().head();
3956 let multibuffer = self.buffer.read(cx);
3957 let Some(buffer) = position
3958 .buffer_id
3959 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3960 else {
3961 return false;
3962 };
3963
3964 if let Some(completion_provider) = &self.completion_provider {
3965 completion_provider.is_completion_trigger(
3966 &buffer,
3967 position.text_anchor,
3968 text,
3969 trigger_in_words,
3970 cx,
3971 )
3972 } else {
3973 false
3974 }
3975 }
3976
3977 /// If any empty selections is touching the start of its innermost containing autoclose
3978 /// region, expand it to select the brackets.
3979 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3980 let selections = self.selections.all::<usize>(cx);
3981 let buffer = self.buffer.read(cx).read(cx);
3982 let new_selections = self
3983 .selections_with_autoclose_regions(selections, &buffer)
3984 .map(|(mut selection, region)| {
3985 if !selection.is_empty() {
3986 return selection;
3987 }
3988
3989 if let Some(region) = region {
3990 let mut range = region.range.to_offset(&buffer);
3991 if selection.start == range.start && range.start >= region.pair.start.len() {
3992 range.start -= region.pair.start.len();
3993 if buffer.contains_str_at(range.start, ®ion.pair.start)
3994 && buffer.contains_str_at(range.end, ®ion.pair.end)
3995 {
3996 range.end += region.pair.end.len();
3997 selection.start = range.start;
3998 selection.end = range.end;
3999
4000 return selection;
4001 }
4002 }
4003 }
4004
4005 let always_treat_brackets_as_autoclosed = buffer
4006 .settings_at(selection.start, cx)
4007 .always_treat_brackets_as_autoclosed;
4008
4009 if !always_treat_brackets_as_autoclosed {
4010 return selection;
4011 }
4012
4013 if let Some(scope) = buffer.language_scope_at(selection.start) {
4014 for (pair, enabled) in scope.brackets() {
4015 if !enabled || !pair.close {
4016 continue;
4017 }
4018
4019 if buffer.contains_str_at(selection.start, &pair.end) {
4020 let pair_start_len = pair.start.len();
4021 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4022 {
4023 selection.start -= pair_start_len;
4024 selection.end += pair.end.len();
4025
4026 return selection;
4027 }
4028 }
4029 }
4030 }
4031
4032 selection
4033 })
4034 .collect();
4035
4036 drop(buffer);
4037 self.change_selections(None, cx, |selections| selections.select(new_selections));
4038 }
4039
4040 /// Iterate the given selections, and for each one, find the smallest surrounding
4041 /// autoclose region. This uses the ordering of the selections and the autoclose
4042 /// regions to avoid repeated comparisons.
4043 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4044 &'a self,
4045 selections: impl IntoIterator<Item = Selection<D>>,
4046 buffer: &'a MultiBufferSnapshot,
4047 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4048 let mut i = 0;
4049 let mut regions = self.autoclose_regions.as_slice();
4050 selections.into_iter().map(move |selection| {
4051 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4052
4053 let mut enclosing = None;
4054 while let Some(pair_state) = regions.get(i) {
4055 if pair_state.range.end.to_offset(buffer) < range.start {
4056 regions = ®ions[i + 1..];
4057 i = 0;
4058 } else if pair_state.range.start.to_offset(buffer) > range.end {
4059 break;
4060 } else {
4061 if pair_state.selection_id == selection.id {
4062 enclosing = Some(pair_state);
4063 }
4064 i += 1;
4065 }
4066 }
4067
4068 (selection, enclosing)
4069 })
4070 }
4071
4072 /// Remove any autoclose regions that no longer contain their selection.
4073 fn invalidate_autoclose_regions(
4074 &mut self,
4075 mut selections: &[Selection<Anchor>],
4076 buffer: &MultiBufferSnapshot,
4077 ) {
4078 self.autoclose_regions.retain(|state| {
4079 let mut i = 0;
4080 while let Some(selection) = selections.get(i) {
4081 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4082 selections = &selections[1..];
4083 continue;
4084 }
4085 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4086 break;
4087 }
4088 if selection.id == state.selection_id {
4089 return true;
4090 } else {
4091 i += 1;
4092 }
4093 }
4094 false
4095 });
4096 }
4097
4098 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4099 let offset = position.to_offset(buffer);
4100 let (word_range, kind) = buffer.surrounding_word(offset, true);
4101 if offset > word_range.start && kind == Some(CharKind::Word) {
4102 Some(
4103 buffer
4104 .text_for_range(word_range.start..offset)
4105 .collect::<String>(),
4106 )
4107 } else {
4108 None
4109 }
4110 }
4111
4112 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4113 self.refresh_inlay_hints(
4114 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4115 cx,
4116 );
4117 }
4118
4119 pub fn inlay_hints_enabled(&self) -> bool {
4120 self.inlay_hint_cache.enabled
4121 }
4122
4123 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4124 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4125 return;
4126 }
4127
4128 let reason_description = reason.description();
4129 let ignore_debounce = matches!(
4130 reason,
4131 InlayHintRefreshReason::SettingsChange(_)
4132 | InlayHintRefreshReason::Toggle(_)
4133 | InlayHintRefreshReason::ExcerptsRemoved(_)
4134 );
4135 let (invalidate_cache, required_languages) = match reason {
4136 InlayHintRefreshReason::Toggle(enabled) => {
4137 self.inlay_hint_cache.enabled = enabled;
4138 if enabled {
4139 (InvalidationStrategy::RefreshRequested, None)
4140 } else {
4141 self.inlay_hint_cache.clear();
4142 self.splice_inlays(
4143 self.visible_inlay_hints(cx)
4144 .iter()
4145 .map(|inlay| inlay.id)
4146 .collect(),
4147 Vec::new(),
4148 cx,
4149 );
4150 return;
4151 }
4152 }
4153 InlayHintRefreshReason::SettingsChange(new_settings) => {
4154 match self.inlay_hint_cache.update_settings(
4155 &self.buffer,
4156 new_settings,
4157 self.visible_inlay_hints(cx),
4158 cx,
4159 ) {
4160 ControlFlow::Break(Some(InlaySplice {
4161 to_remove,
4162 to_insert,
4163 })) => {
4164 self.splice_inlays(to_remove, to_insert, cx);
4165 return;
4166 }
4167 ControlFlow::Break(None) => return,
4168 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4169 }
4170 }
4171 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4172 if let Some(InlaySplice {
4173 to_remove,
4174 to_insert,
4175 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4176 {
4177 self.splice_inlays(to_remove, to_insert, cx);
4178 }
4179 return;
4180 }
4181 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4182 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4183 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4184 }
4185 InlayHintRefreshReason::RefreshRequested => {
4186 (InvalidationStrategy::RefreshRequested, None)
4187 }
4188 };
4189
4190 if let Some(InlaySplice {
4191 to_remove,
4192 to_insert,
4193 }) = self.inlay_hint_cache.spawn_hint_refresh(
4194 reason_description,
4195 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4196 invalidate_cache,
4197 ignore_debounce,
4198 cx,
4199 ) {
4200 self.splice_inlays(to_remove, to_insert, cx);
4201 }
4202 }
4203
4204 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4205 self.display_map
4206 .read(cx)
4207 .current_inlays()
4208 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4209 .cloned()
4210 .collect()
4211 }
4212
4213 pub fn excerpts_for_inlay_hints_query(
4214 &self,
4215 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4216 cx: &mut ViewContext<Editor>,
4217 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4218 let Some(project) = self.project.as_ref() else {
4219 return HashMap::default();
4220 };
4221 let project = project.read(cx);
4222 let multi_buffer = self.buffer().read(cx);
4223 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4224 let multi_buffer_visible_start = self
4225 .scroll_manager
4226 .anchor()
4227 .anchor
4228 .to_point(&multi_buffer_snapshot);
4229 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4230 multi_buffer_visible_start
4231 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4232 Bias::Left,
4233 );
4234 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4235 multi_buffer
4236 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4237 .into_iter()
4238 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4239 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4240 let buffer = buffer_handle.read(cx);
4241 let buffer_file = project::File::from_dyn(buffer.file())?;
4242 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4243 let worktree_entry = buffer_worktree
4244 .read(cx)
4245 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4246 if worktree_entry.is_ignored {
4247 return None;
4248 }
4249
4250 let language = buffer.language()?;
4251 if let Some(restrict_to_languages) = restrict_to_languages {
4252 if !restrict_to_languages.contains(language) {
4253 return None;
4254 }
4255 }
4256 Some((
4257 excerpt_id,
4258 (
4259 buffer_handle,
4260 buffer.version().clone(),
4261 excerpt_visible_range,
4262 ),
4263 ))
4264 })
4265 .collect()
4266 }
4267
4268 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4269 TextLayoutDetails {
4270 text_system: cx.text_system().clone(),
4271 editor_style: self.style.clone().unwrap(),
4272 rem_size: cx.rem_size(),
4273 scroll_anchor: self.scroll_manager.anchor(),
4274 visible_rows: self.visible_line_count(),
4275 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4276 }
4277 }
4278
4279 fn splice_inlays(
4280 &self,
4281 to_remove: Vec<InlayId>,
4282 to_insert: Vec<Inlay>,
4283 cx: &mut ViewContext<Self>,
4284 ) {
4285 self.display_map.update(cx, |display_map, cx| {
4286 display_map.splice_inlays(to_remove, to_insert, cx);
4287 });
4288 cx.notify();
4289 }
4290
4291 fn trigger_on_type_formatting(
4292 &self,
4293 input: String,
4294 cx: &mut ViewContext<Self>,
4295 ) -> Option<Task<Result<()>>> {
4296 if input.len() != 1 {
4297 return None;
4298 }
4299
4300 let project = self.project.as_ref()?;
4301 let position = self.selections.newest_anchor().head();
4302 let (buffer, buffer_position) = self
4303 .buffer
4304 .read(cx)
4305 .text_anchor_for_position(position, cx)?;
4306
4307 let settings = language_settings::language_settings(
4308 buffer
4309 .read(cx)
4310 .language_at(buffer_position)
4311 .map(|l| l.name()),
4312 buffer.read(cx).file(),
4313 cx,
4314 );
4315 if !settings.use_on_type_format {
4316 return None;
4317 }
4318
4319 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4320 // hence we do LSP request & edit on host side only — add formats to host's history.
4321 let push_to_lsp_host_history = true;
4322 // If this is not the host, append its history with new edits.
4323 let push_to_client_history = project.read(cx).is_via_collab();
4324
4325 let on_type_formatting = project.update(cx, |project, cx| {
4326 project.on_type_format(
4327 buffer.clone(),
4328 buffer_position,
4329 input,
4330 push_to_lsp_host_history,
4331 cx,
4332 )
4333 });
4334 Some(cx.spawn(|editor, mut cx| async move {
4335 if let Some(transaction) = on_type_formatting.await? {
4336 if push_to_client_history {
4337 buffer
4338 .update(&mut cx, |buffer, _| {
4339 buffer.push_transaction(transaction, Instant::now());
4340 })
4341 .ok();
4342 }
4343 editor.update(&mut cx, |editor, cx| {
4344 editor.refresh_document_highlights(cx);
4345 })?;
4346 }
4347 Ok(())
4348 }))
4349 }
4350
4351 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4352 if self.pending_rename.is_some() {
4353 return;
4354 }
4355
4356 let Some(provider) = self.completion_provider.as_ref() else {
4357 return;
4358 };
4359
4360 let position = self.selections.newest_anchor().head();
4361 let (buffer, buffer_position) =
4362 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4363 output
4364 } else {
4365 return;
4366 };
4367
4368 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4369 let is_followup_invoke = {
4370 let context_menu_state = self.context_menu.read();
4371 matches!(
4372 context_menu_state.deref(),
4373 Some(ContextMenu::Completions(_))
4374 )
4375 };
4376 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4377 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4378 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4379 CompletionTriggerKind::TRIGGER_CHARACTER
4380 }
4381
4382 _ => CompletionTriggerKind::INVOKED,
4383 };
4384 let completion_context = CompletionContext {
4385 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4386 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4387 Some(String::from(trigger))
4388 } else {
4389 None
4390 }
4391 }),
4392 trigger_kind,
4393 };
4394 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4395 let sort_completions = provider.sort_completions();
4396
4397 let id = post_inc(&mut self.next_completion_id);
4398 let task = cx.spawn(|this, mut cx| {
4399 async move {
4400 this.update(&mut cx, |this, _| {
4401 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4402 })?;
4403 let completions = completions.await.log_err();
4404 let menu = if let Some(completions) = completions {
4405 let mut menu = CompletionsMenu {
4406 id,
4407 sort_completions,
4408 initial_position: position,
4409 match_candidates: completions
4410 .iter()
4411 .enumerate()
4412 .map(|(id, completion)| {
4413 StringMatchCandidate::new(
4414 id,
4415 completion.label.text[completion.label.filter_range.clone()]
4416 .into(),
4417 )
4418 })
4419 .collect(),
4420 buffer: buffer.clone(),
4421 completions: Arc::new(RwLock::new(completions.into())),
4422 matches: Vec::new().into(),
4423 selected_item: 0,
4424 scroll_handle: UniformListScrollHandle::new(),
4425 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4426 DebouncedDelay::new(),
4427 )),
4428 };
4429 menu.filter(query.as_deref(), cx.background_executor().clone())
4430 .await;
4431
4432 if menu.matches.is_empty() {
4433 None
4434 } else {
4435 this.update(&mut cx, |editor, cx| {
4436 let completions = menu.completions.clone();
4437 let matches = menu.matches.clone();
4438
4439 let delay_ms = EditorSettings::get_global(cx)
4440 .completion_documentation_secondary_query_debounce;
4441 let delay = Duration::from_millis(delay_ms);
4442 editor
4443 .completion_documentation_pre_resolve_debounce
4444 .fire_new(delay, cx, |editor, cx| {
4445 CompletionsMenu::pre_resolve_completion_documentation(
4446 buffer,
4447 completions,
4448 matches,
4449 editor,
4450 cx,
4451 )
4452 });
4453 })
4454 .ok();
4455 Some(menu)
4456 }
4457 } else {
4458 None
4459 };
4460
4461 this.update(&mut cx, |this, cx| {
4462 let mut context_menu = this.context_menu.write();
4463 match context_menu.as_ref() {
4464 None => {}
4465
4466 Some(ContextMenu::Completions(prev_menu)) => {
4467 if prev_menu.id > id {
4468 return;
4469 }
4470 }
4471
4472 _ => return,
4473 }
4474
4475 if this.focus_handle.is_focused(cx) && menu.is_some() {
4476 let menu = menu.unwrap();
4477 *context_menu = Some(ContextMenu::Completions(menu));
4478 drop(context_menu);
4479 this.discard_inline_completion(false, cx);
4480 cx.notify();
4481 } else if this.completion_tasks.len() <= 1 {
4482 // If there are no more completion tasks and the last menu was
4483 // empty, we should hide it. If it was already hidden, we should
4484 // also show the copilot completion when available.
4485 drop(context_menu);
4486 if this.hide_context_menu(cx).is_none() {
4487 this.update_visible_inline_completion(cx);
4488 }
4489 }
4490 })?;
4491
4492 Ok::<_, anyhow::Error>(())
4493 }
4494 .log_err()
4495 });
4496
4497 self.completion_tasks.push((id, task));
4498 }
4499
4500 pub fn confirm_completion(
4501 &mut self,
4502 action: &ConfirmCompletion,
4503 cx: &mut ViewContext<Self>,
4504 ) -> Option<Task<Result<()>>> {
4505 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4506 }
4507
4508 pub fn compose_completion(
4509 &mut self,
4510 action: &ComposeCompletion,
4511 cx: &mut ViewContext<Self>,
4512 ) -> Option<Task<Result<()>>> {
4513 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4514 }
4515
4516 fn do_completion(
4517 &mut self,
4518 item_ix: Option<usize>,
4519 intent: CompletionIntent,
4520 cx: &mut ViewContext<Editor>,
4521 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4522 use language::ToOffset as _;
4523
4524 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4525 menu
4526 } else {
4527 return None;
4528 };
4529
4530 let mat = completions_menu
4531 .matches
4532 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4533 let buffer_handle = completions_menu.buffer;
4534 let completions = completions_menu.completions.read();
4535 let completion = completions.get(mat.candidate_id)?;
4536 cx.stop_propagation();
4537
4538 let snippet;
4539 let text;
4540
4541 if completion.is_snippet() {
4542 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4543 text = snippet.as_ref().unwrap().text.clone();
4544 } else {
4545 snippet = None;
4546 text = completion.new_text.clone();
4547 };
4548 let selections = self.selections.all::<usize>(cx);
4549 let buffer = buffer_handle.read(cx);
4550 let old_range = completion.old_range.to_offset(buffer);
4551 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4552
4553 let newest_selection = self.selections.newest_anchor();
4554 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4555 return None;
4556 }
4557
4558 let lookbehind = newest_selection
4559 .start
4560 .text_anchor
4561 .to_offset(buffer)
4562 .saturating_sub(old_range.start);
4563 let lookahead = old_range
4564 .end
4565 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4566 let mut common_prefix_len = old_text
4567 .bytes()
4568 .zip(text.bytes())
4569 .take_while(|(a, b)| a == b)
4570 .count();
4571
4572 let snapshot = self.buffer.read(cx).snapshot(cx);
4573 let mut range_to_replace: Option<Range<isize>> = None;
4574 let mut ranges = Vec::new();
4575 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4576 for selection in &selections {
4577 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4578 let start = selection.start.saturating_sub(lookbehind);
4579 let end = selection.end + lookahead;
4580 if selection.id == newest_selection.id {
4581 range_to_replace = Some(
4582 ((start + common_prefix_len) as isize - selection.start as isize)
4583 ..(end as isize - selection.start as isize),
4584 );
4585 }
4586 ranges.push(start + common_prefix_len..end);
4587 } else {
4588 common_prefix_len = 0;
4589 ranges.clear();
4590 ranges.extend(selections.iter().map(|s| {
4591 if s.id == newest_selection.id {
4592 range_to_replace = Some(
4593 old_range.start.to_offset_utf16(&snapshot).0 as isize
4594 - selection.start as isize
4595 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4596 - selection.start as isize,
4597 );
4598 old_range.clone()
4599 } else {
4600 s.start..s.end
4601 }
4602 }));
4603 break;
4604 }
4605 if !self.linked_edit_ranges.is_empty() {
4606 let start_anchor = snapshot.anchor_before(selection.head());
4607 let end_anchor = snapshot.anchor_after(selection.tail());
4608 if let Some(ranges) = self
4609 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4610 {
4611 for (buffer, edits) in ranges {
4612 linked_edits.entry(buffer.clone()).or_default().extend(
4613 edits
4614 .into_iter()
4615 .map(|range| (range, text[common_prefix_len..].to_owned())),
4616 );
4617 }
4618 }
4619 }
4620 }
4621 let text = &text[common_prefix_len..];
4622
4623 cx.emit(EditorEvent::InputHandled {
4624 utf16_range_to_replace: range_to_replace,
4625 text: text.into(),
4626 });
4627
4628 self.transact(cx, |this, cx| {
4629 if let Some(mut snippet) = snippet {
4630 snippet.text = text.to_string();
4631 for tabstop in snippet.tabstops.iter_mut().flatten() {
4632 tabstop.start -= common_prefix_len as isize;
4633 tabstop.end -= common_prefix_len as isize;
4634 }
4635
4636 this.insert_snippet(&ranges, snippet, cx).log_err();
4637 } else {
4638 this.buffer.update(cx, |buffer, cx| {
4639 buffer.edit(
4640 ranges.iter().map(|range| (range.clone(), text)),
4641 this.autoindent_mode.clone(),
4642 cx,
4643 );
4644 });
4645 }
4646 for (buffer, edits) in linked_edits {
4647 buffer.update(cx, |buffer, cx| {
4648 let snapshot = buffer.snapshot();
4649 let edits = edits
4650 .into_iter()
4651 .map(|(range, text)| {
4652 use text::ToPoint as TP;
4653 let end_point = TP::to_point(&range.end, &snapshot);
4654 let start_point = TP::to_point(&range.start, &snapshot);
4655 (start_point..end_point, text)
4656 })
4657 .sorted_by_key(|(range, _)| range.start)
4658 .collect::<Vec<_>>();
4659 buffer.edit(edits, None, cx);
4660 })
4661 }
4662
4663 this.refresh_inline_completion(true, false, cx);
4664 });
4665
4666 let show_new_completions_on_confirm = completion
4667 .confirm
4668 .as_ref()
4669 .map_or(false, |confirm| confirm(intent, cx));
4670 if show_new_completions_on_confirm {
4671 self.show_completions(&ShowCompletions { trigger: None }, cx);
4672 }
4673
4674 let provider = self.completion_provider.as_ref()?;
4675 let apply_edits = provider.apply_additional_edits_for_completion(
4676 buffer_handle,
4677 completion.clone(),
4678 true,
4679 cx,
4680 );
4681
4682 let editor_settings = EditorSettings::get_global(cx);
4683 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4684 // After the code completion is finished, users often want to know what signatures are needed.
4685 // so we should automatically call signature_help
4686 self.show_signature_help(&ShowSignatureHelp, cx);
4687 }
4688
4689 Some(cx.foreground_executor().spawn(async move {
4690 apply_edits.await?;
4691 Ok(())
4692 }))
4693 }
4694
4695 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4696 let mut context_menu = self.context_menu.write();
4697 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4698 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4699 // Toggle if we're selecting the same one
4700 *context_menu = None;
4701 cx.notify();
4702 return;
4703 } else {
4704 // Otherwise, clear it and start a new one
4705 *context_menu = None;
4706 cx.notify();
4707 }
4708 }
4709 drop(context_menu);
4710 let snapshot = self.snapshot(cx);
4711 let deployed_from_indicator = action.deployed_from_indicator;
4712 let mut task = self.code_actions_task.take();
4713 let action = action.clone();
4714 cx.spawn(|editor, mut cx| async move {
4715 while let Some(prev_task) = task {
4716 prev_task.await.log_err();
4717 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4718 }
4719
4720 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4721 if editor.focus_handle.is_focused(cx) {
4722 let multibuffer_point = action
4723 .deployed_from_indicator
4724 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4725 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4726 let (buffer, buffer_row) = snapshot
4727 .buffer_snapshot
4728 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4729 .and_then(|(buffer_snapshot, range)| {
4730 editor
4731 .buffer
4732 .read(cx)
4733 .buffer(buffer_snapshot.remote_id())
4734 .map(|buffer| (buffer, range.start.row))
4735 })?;
4736 let (_, code_actions) = editor
4737 .available_code_actions
4738 .clone()
4739 .and_then(|(location, code_actions)| {
4740 let snapshot = location.buffer.read(cx).snapshot();
4741 let point_range = location.range.to_point(&snapshot);
4742 let point_range = point_range.start.row..=point_range.end.row;
4743 if point_range.contains(&buffer_row) {
4744 Some((location, code_actions))
4745 } else {
4746 None
4747 }
4748 })
4749 .unzip();
4750 let buffer_id = buffer.read(cx).remote_id();
4751 let tasks = editor
4752 .tasks
4753 .get(&(buffer_id, buffer_row))
4754 .map(|t| Arc::new(t.to_owned()));
4755 if tasks.is_none() && code_actions.is_none() {
4756 return None;
4757 }
4758
4759 editor.completion_tasks.clear();
4760 editor.discard_inline_completion(false, cx);
4761 let task_context =
4762 tasks
4763 .as_ref()
4764 .zip(editor.project.clone())
4765 .map(|(tasks, project)| {
4766 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4767 });
4768
4769 Some(cx.spawn(|editor, mut cx| async move {
4770 let task_context = match task_context {
4771 Some(task_context) => task_context.await,
4772 None => None,
4773 };
4774 let resolved_tasks =
4775 tasks.zip(task_context).map(|(tasks, task_context)| {
4776 Arc::new(ResolvedTasks {
4777 templates: tasks.resolve(&task_context).collect(),
4778 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4779 multibuffer_point.row,
4780 tasks.column,
4781 )),
4782 })
4783 });
4784 let spawn_straight_away = resolved_tasks
4785 .as_ref()
4786 .map_or(false, |tasks| tasks.templates.len() == 1)
4787 && code_actions
4788 .as_ref()
4789 .map_or(true, |actions| actions.is_empty());
4790 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4791 *editor.context_menu.write() =
4792 Some(ContextMenu::CodeActions(CodeActionsMenu {
4793 buffer,
4794 actions: CodeActionContents {
4795 tasks: resolved_tasks,
4796 actions: code_actions,
4797 },
4798 selected_item: Default::default(),
4799 scroll_handle: UniformListScrollHandle::default(),
4800 deployed_from_indicator,
4801 }));
4802 if spawn_straight_away {
4803 if let Some(task) = editor.confirm_code_action(
4804 &ConfirmCodeAction { item_ix: Some(0) },
4805 cx,
4806 ) {
4807 cx.notify();
4808 return task;
4809 }
4810 }
4811 cx.notify();
4812 Task::ready(Ok(()))
4813 }) {
4814 task.await
4815 } else {
4816 Ok(())
4817 }
4818 }))
4819 } else {
4820 Some(Task::ready(Ok(())))
4821 }
4822 })?;
4823 if let Some(task) = spawned_test_task {
4824 task.await?;
4825 }
4826
4827 Ok::<_, anyhow::Error>(())
4828 })
4829 .detach_and_log_err(cx);
4830 }
4831
4832 pub fn confirm_code_action(
4833 &mut self,
4834 action: &ConfirmCodeAction,
4835 cx: &mut ViewContext<Self>,
4836 ) -> Option<Task<Result<()>>> {
4837 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4838 menu
4839 } else {
4840 return None;
4841 };
4842 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4843 let action = actions_menu.actions.get(action_ix)?;
4844 let title = action.label();
4845 let buffer = actions_menu.buffer;
4846 let workspace = self.workspace()?;
4847
4848 match action {
4849 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4850 workspace.update(cx, |workspace, cx| {
4851 workspace::tasks::schedule_resolved_task(
4852 workspace,
4853 task_source_kind,
4854 resolved_task,
4855 false,
4856 cx,
4857 );
4858
4859 Some(Task::ready(Ok(())))
4860 })
4861 }
4862 CodeActionsItem::CodeAction {
4863 excerpt_id,
4864 action,
4865 provider,
4866 } => {
4867 let apply_code_action =
4868 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4869 let workspace = workspace.downgrade();
4870 Some(cx.spawn(|editor, cx| async move {
4871 let project_transaction = apply_code_action.await?;
4872 Self::open_project_transaction(
4873 &editor,
4874 workspace,
4875 project_transaction,
4876 title,
4877 cx,
4878 )
4879 .await
4880 }))
4881 }
4882 }
4883 }
4884
4885 pub async fn open_project_transaction(
4886 this: &WeakView<Editor>,
4887 workspace: WeakView<Workspace>,
4888 transaction: ProjectTransaction,
4889 title: String,
4890 mut cx: AsyncWindowContext,
4891 ) -> Result<()> {
4892 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4893 cx.update(|cx| {
4894 entries.sort_unstable_by_key(|(buffer, _)| {
4895 buffer.read(cx).file().map(|f| f.path().clone())
4896 });
4897 })?;
4898
4899 // If the project transaction's edits are all contained within this editor, then
4900 // avoid opening a new editor to display them.
4901
4902 if let Some((buffer, transaction)) = entries.first() {
4903 if entries.len() == 1 {
4904 let excerpt = this.update(&mut cx, |editor, cx| {
4905 editor
4906 .buffer()
4907 .read(cx)
4908 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4909 })?;
4910 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4911 if excerpted_buffer == *buffer {
4912 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4913 let excerpt_range = excerpt_range.to_offset(buffer);
4914 buffer
4915 .edited_ranges_for_transaction::<usize>(transaction)
4916 .all(|range| {
4917 excerpt_range.start <= range.start
4918 && excerpt_range.end >= range.end
4919 })
4920 })?;
4921
4922 if all_edits_within_excerpt {
4923 return Ok(());
4924 }
4925 }
4926 }
4927 }
4928 } else {
4929 return Ok(());
4930 }
4931
4932 let mut ranges_to_highlight = Vec::new();
4933 let excerpt_buffer = cx.new_model(|cx| {
4934 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4935 for (buffer_handle, transaction) in &entries {
4936 let buffer = buffer_handle.read(cx);
4937 ranges_to_highlight.extend(
4938 multibuffer.push_excerpts_with_context_lines(
4939 buffer_handle.clone(),
4940 buffer
4941 .edited_ranges_for_transaction::<usize>(transaction)
4942 .collect(),
4943 DEFAULT_MULTIBUFFER_CONTEXT,
4944 cx,
4945 ),
4946 );
4947 }
4948 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4949 multibuffer
4950 })?;
4951
4952 workspace.update(&mut cx, |workspace, cx| {
4953 let project = workspace.project().clone();
4954 let editor =
4955 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4956 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4957 editor.update(cx, |editor, cx| {
4958 editor.highlight_background::<Self>(
4959 &ranges_to_highlight,
4960 |theme| theme.editor_highlighted_line_background,
4961 cx,
4962 );
4963 });
4964 })?;
4965
4966 Ok(())
4967 }
4968
4969 pub fn clear_code_action_providers(&mut self) {
4970 self.code_action_providers.clear();
4971 self.available_code_actions.take();
4972 }
4973
4974 pub fn push_code_action_provider(
4975 &mut self,
4976 provider: Arc<dyn CodeActionProvider>,
4977 cx: &mut ViewContext<Self>,
4978 ) {
4979 self.code_action_providers.push(provider);
4980 self.refresh_code_actions(cx);
4981 }
4982
4983 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4984 let buffer = self.buffer.read(cx);
4985 let newest_selection = self.selections.newest_anchor().clone();
4986 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4987 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4988 if start_buffer != end_buffer {
4989 return None;
4990 }
4991
4992 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4993 cx.background_executor()
4994 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4995 .await;
4996
4997 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4998 let providers = this.code_action_providers.clone();
4999 let tasks = this
5000 .code_action_providers
5001 .iter()
5002 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5003 .collect::<Vec<_>>();
5004 (providers, tasks)
5005 })?;
5006
5007 let mut actions = Vec::new();
5008 for (provider, provider_actions) in
5009 providers.into_iter().zip(future::join_all(tasks).await)
5010 {
5011 if let Some(provider_actions) = provider_actions.log_err() {
5012 actions.extend(provider_actions.into_iter().map(|action| {
5013 AvailableCodeAction {
5014 excerpt_id: newest_selection.start.excerpt_id,
5015 action,
5016 provider: provider.clone(),
5017 }
5018 }));
5019 }
5020 }
5021
5022 this.update(&mut cx, |this, cx| {
5023 this.available_code_actions = if actions.is_empty() {
5024 None
5025 } else {
5026 Some((
5027 Location {
5028 buffer: start_buffer,
5029 range: start..end,
5030 },
5031 actions.into(),
5032 ))
5033 };
5034 cx.notify();
5035 })
5036 }));
5037 None
5038 }
5039
5040 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5041 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5042 self.show_git_blame_inline = false;
5043
5044 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5045 cx.background_executor().timer(delay).await;
5046
5047 this.update(&mut cx, |this, cx| {
5048 this.show_git_blame_inline = true;
5049 cx.notify();
5050 })
5051 .log_err();
5052 }));
5053 }
5054 }
5055
5056 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5057 if self.pending_rename.is_some() {
5058 return None;
5059 }
5060
5061 let provider = self.semantics_provider.clone()?;
5062 let buffer = self.buffer.read(cx);
5063 let newest_selection = self.selections.newest_anchor().clone();
5064 let cursor_position = newest_selection.head();
5065 let (cursor_buffer, cursor_buffer_position) =
5066 buffer.text_anchor_for_position(cursor_position, cx)?;
5067 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5068 if cursor_buffer != tail_buffer {
5069 return None;
5070 }
5071
5072 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5073 cx.background_executor()
5074 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5075 .await;
5076
5077 let highlights = if let Some(highlights) = cx
5078 .update(|cx| {
5079 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5080 })
5081 .ok()
5082 .flatten()
5083 {
5084 highlights.await.log_err()
5085 } else {
5086 None
5087 };
5088
5089 if let Some(highlights) = highlights {
5090 this.update(&mut cx, |this, cx| {
5091 if this.pending_rename.is_some() {
5092 return;
5093 }
5094
5095 let buffer_id = cursor_position.buffer_id;
5096 let buffer = this.buffer.read(cx);
5097 if !buffer
5098 .text_anchor_for_position(cursor_position, cx)
5099 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5100 {
5101 return;
5102 }
5103
5104 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5105 let mut write_ranges = Vec::new();
5106 let mut read_ranges = Vec::new();
5107 for highlight in highlights {
5108 for (excerpt_id, excerpt_range) in
5109 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5110 {
5111 let start = highlight
5112 .range
5113 .start
5114 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5115 let end = highlight
5116 .range
5117 .end
5118 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5119 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5120 continue;
5121 }
5122
5123 let range = Anchor {
5124 buffer_id,
5125 excerpt_id,
5126 text_anchor: start,
5127 }..Anchor {
5128 buffer_id,
5129 excerpt_id,
5130 text_anchor: end,
5131 };
5132 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5133 write_ranges.push(range);
5134 } else {
5135 read_ranges.push(range);
5136 }
5137 }
5138 }
5139
5140 this.highlight_background::<DocumentHighlightRead>(
5141 &read_ranges,
5142 |theme| theme.editor_document_highlight_read_background,
5143 cx,
5144 );
5145 this.highlight_background::<DocumentHighlightWrite>(
5146 &write_ranges,
5147 |theme| theme.editor_document_highlight_write_background,
5148 cx,
5149 );
5150 cx.notify();
5151 })
5152 .log_err();
5153 }
5154 }));
5155 None
5156 }
5157
5158 pub fn refresh_inline_completion(
5159 &mut self,
5160 debounce: bool,
5161 user_requested: bool,
5162 cx: &mut ViewContext<Self>,
5163 ) -> Option<()> {
5164 let provider = self.inline_completion_provider()?;
5165 let cursor = self.selections.newest_anchor().head();
5166 let (buffer, cursor_buffer_position) =
5167 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5168
5169 if !user_requested
5170 && (!self.enable_inline_completions
5171 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5172 {
5173 self.discard_inline_completion(false, cx);
5174 return None;
5175 }
5176
5177 self.update_visible_inline_completion(cx);
5178 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5179 Some(())
5180 }
5181
5182 fn cycle_inline_completion(
5183 &mut self,
5184 direction: Direction,
5185 cx: &mut ViewContext<Self>,
5186 ) -> Option<()> {
5187 let provider = self.inline_completion_provider()?;
5188 let cursor = self.selections.newest_anchor().head();
5189 let (buffer, cursor_buffer_position) =
5190 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5191 if !self.enable_inline_completions
5192 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5193 {
5194 return None;
5195 }
5196
5197 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5198 self.update_visible_inline_completion(cx);
5199
5200 Some(())
5201 }
5202
5203 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5204 if !self.has_active_inline_completion(cx) {
5205 self.refresh_inline_completion(false, true, cx);
5206 return;
5207 }
5208
5209 self.update_visible_inline_completion(cx);
5210 }
5211
5212 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5213 self.show_cursor_names(cx);
5214 }
5215
5216 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5217 self.show_cursor_names = true;
5218 cx.notify();
5219 cx.spawn(|this, mut cx| async move {
5220 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5221 this.update(&mut cx, |this, cx| {
5222 this.show_cursor_names = false;
5223 cx.notify()
5224 })
5225 .ok()
5226 })
5227 .detach();
5228 }
5229
5230 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5231 if self.has_active_inline_completion(cx) {
5232 self.cycle_inline_completion(Direction::Next, cx);
5233 } else {
5234 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5235 if is_copilot_disabled {
5236 cx.propagate();
5237 }
5238 }
5239 }
5240
5241 pub fn previous_inline_completion(
5242 &mut self,
5243 _: &PreviousInlineCompletion,
5244 cx: &mut ViewContext<Self>,
5245 ) {
5246 if self.has_active_inline_completion(cx) {
5247 self.cycle_inline_completion(Direction::Prev, cx);
5248 } else {
5249 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5250 if is_copilot_disabled {
5251 cx.propagate();
5252 }
5253 }
5254 }
5255
5256 pub fn accept_inline_completion(
5257 &mut self,
5258 _: &AcceptInlineCompletion,
5259 cx: &mut ViewContext<Self>,
5260 ) {
5261 let Some(completion) = self.take_active_inline_completion(cx) else {
5262 return;
5263 };
5264 if let Some(provider) = self.inline_completion_provider() {
5265 provider.accept(cx);
5266 }
5267
5268 cx.emit(EditorEvent::InputHandled {
5269 utf16_range_to_replace: None,
5270 text: completion.text.to_string().into(),
5271 });
5272
5273 if let Some(range) = completion.delete_range {
5274 self.change_selections(None, cx, |s| s.select_ranges([range]))
5275 }
5276 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5277 self.refresh_inline_completion(true, true, cx);
5278 cx.notify();
5279 }
5280
5281 pub fn accept_partial_inline_completion(
5282 &mut self,
5283 _: &AcceptPartialInlineCompletion,
5284 cx: &mut ViewContext<Self>,
5285 ) {
5286 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5287 if let Some(completion) = self.take_active_inline_completion(cx) {
5288 let mut partial_completion = completion
5289 .text
5290 .chars()
5291 .by_ref()
5292 .take_while(|c| c.is_alphabetic())
5293 .collect::<String>();
5294 if partial_completion.is_empty() {
5295 partial_completion = completion
5296 .text
5297 .chars()
5298 .by_ref()
5299 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5300 .collect::<String>();
5301 }
5302
5303 cx.emit(EditorEvent::InputHandled {
5304 utf16_range_to_replace: None,
5305 text: partial_completion.clone().into(),
5306 });
5307
5308 if let Some(range) = completion.delete_range {
5309 self.change_selections(None, cx, |s| s.select_ranges([range]))
5310 }
5311 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5312
5313 self.refresh_inline_completion(true, true, cx);
5314 cx.notify();
5315 }
5316 }
5317 }
5318
5319 fn discard_inline_completion(
5320 &mut self,
5321 should_report_inline_completion_event: bool,
5322 cx: &mut ViewContext<Self>,
5323 ) -> bool {
5324 if let Some(provider) = self.inline_completion_provider() {
5325 provider.discard(should_report_inline_completion_event, cx);
5326 }
5327
5328 self.take_active_inline_completion(cx).is_some()
5329 }
5330
5331 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5332 if let Some(completion) = self.active_inline_completion.as_ref() {
5333 let buffer = self.buffer.read(cx).read(cx);
5334 completion.position.is_valid(&buffer)
5335 } else {
5336 false
5337 }
5338 }
5339
5340 fn take_active_inline_completion(
5341 &mut self,
5342 cx: &mut ViewContext<Self>,
5343 ) -> Option<CompletionState> {
5344 let completion = self.active_inline_completion.take()?;
5345 let render_inlay_ids = completion.render_inlay_ids.clone();
5346 self.display_map.update(cx, |map, cx| {
5347 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5348 });
5349 let buffer = self.buffer.read(cx).read(cx);
5350
5351 if completion.position.is_valid(&buffer) {
5352 Some(completion)
5353 } else {
5354 None
5355 }
5356 }
5357
5358 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5359 let selection = self.selections.newest_anchor();
5360 let cursor = selection.head();
5361
5362 let excerpt_id = cursor.excerpt_id;
5363
5364 if self.context_menu.read().is_none()
5365 && self.completion_tasks.is_empty()
5366 && selection.start == selection.end
5367 {
5368 if let Some(provider) = self.inline_completion_provider() {
5369 if let Some((buffer, cursor_buffer_position)) =
5370 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5371 {
5372 if let Some(proposal) =
5373 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5374 {
5375 let mut to_remove = Vec::new();
5376 if let Some(completion) = self.active_inline_completion.take() {
5377 to_remove.extend(completion.render_inlay_ids.iter());
5378 }
5379
5380 let to_add = proposal
5381 .inlays
5382 .iter()
5383 .filter_map(|inlay| {
5384 let snapshot = self.buffer.read(cx).snapshot(cx);
5385 let id = post_inc(&mut self.next_inlay_id);
5386 match inlay {
5387 InlayProposal::Hint(position, hint) => {
5388 let position =
5389 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5390 Some(Inlay::hint(id, position, hint))
5391 }
5392 InlayProposal::Suggestion(position, text) => {
5393 let position =
5394 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5395 Some(Inlay::suggestion(id, position, text.clone()))
5396 }
5397 }
5398 })
5399 .collect_vec();
5400
5401 self.active_inline_completion = Some(CompletionState {
5402 position: cursor,
5403 text: proposal.text,
5404 delete_range: proposal.delete_range.and_then(|range| {
5405 let snapshot = self.buffer.read(cx).snapshot(cx);
5406 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5407 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5408 Some(start?..end?)
5409 }),
5410 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5411 });
5412
5413 self.display_map
5414 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5415
5416 cx.notify();
5417 return;
5418 }
5419 }
5420 }
5421 }
5422
5423 self.discard_inline_completion(false, cx);
5424 }
5425
5426 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5427 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5428 }
5429
5430 fn render_code_actions_indicator(
5431 &self,
5432 _style: &EditorStyle,
5433 row: DisplayRow,
5434 is_active: bool,
5435 cx: &mut ViewContext<Self>,
5436 ) -> Option<IconButton> {
5437 if self.available_code_actions.is_some() {
5438 Some(
5439 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5440 .shape(ui::IconButtonShape::Square)
5441 .icon_size(IconSize::XSmall)
5442 .icon_color(Color::Muted)
5443 .selected(is_active)
5444 .tooltip({
5445 let focus_handle = self.focus_handle.clone();
5446 move |cx| {
5447 Tooltip::for_action_in(
5448 "Toggle Code Actions",
5449 &ToggleCodeActions {
5450 deployed_from_indicator: None,
5451 },
5452 &focus_handle,
5453 cx,
5454 )
5455 }
5456 })
5457 .on_click(cx.listener(move |editor, _e, cx| {
5458 editor.focus(cx);
5459 editor.toggle_code_actions(
5460 &ToggleCodeActions {
5461 deployed_from_indicator: Some(row),
5462 },
5463 cx,
5464 );
5465 })),
5466 )
5467 } else {
5468 None
5469 }
5470 }
5471
5472 fn clear_tasks(&mut self) {
5473 self.tasks.clear()
5474 }
5475
5476 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5477 if self.tasks.insert(key, value).is_some() {
5478 // This case should hopefully be rare, but just in case...
5479 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5480 }
5481 }
5482
5483 fn build_tasks_context(
5484 project: &Model<Project>,
5485 buffer: &Model<Buffer>,
5486 buffer_row: u32,
5487 tasks: &Arc<RunnableTasks>,
5488 cx: &mut ViewContext<Self>,
5489 ) -> Task<Option<task::TaskContext>> {
5490 let position = Point::new(buffer_row, tasks.column);
5491 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5492 let location = Location {
5493 buffer: buffer.clone(),
5494 range: range_start..range_start,
5495 };
5496 // Fill in the environmental variables from the tree-sitter captures
5497 let mut captured_task_variables = TaskVariables::default();
5498 for (capture_name, value) in tasks.extra_variables.clone() {
5499 captured_task_variables.insert(
5500 task::VariableName::Custom(capture_name.into()),
5501 value.clone(),
5502 );
5503 }
5504 project.update(cx, |project, cx| {
5505 project.task_store().update(cx, |task_store, cx| {
5506 task_store.task_context_for_location(captured_task_variables, location, cx)
5507 })
5508 })
5509 }
5510
5511 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5512 let Some((workspace, _)) = self.workspace.clone() else {
5513 return;
5514 };
5515 let Some(project) = self.project.clone() else {
5516 return;
5517 };
5518
5519 // Try to find a closest, enclosing node using tree-sitter that has a
5520 // task
5521 let Some((buffer, buffer_row, tasks)) = self
5522 .find_enclosing_node_task(cx)
5523 // Or find the task that's closest in row-distance.
5524 .or_else(|| self.find_closest_task(cx))
5525 else {
5526 return;
5527 };
5528
5529 let reveal_strategy = action.reveal;
5530 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5531 cx.spawn(|_, mut cx| async move {
5532 let context = task_context.await?;
5533 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5534
5535 let resolved = resolved_task.resolved.as_mut()?;
5536 resolved.reveal = reveal_strategy;
5537
5538 workspace
5539 .update(&mut cx, |workspace, cx| {
5540 workspace::tasks::schedule_resolved_task(
5541 workspace,
5542 task_source_kind,
5543 resolved_task,
5544 false,
5545 cx,
5546 );
5547 })
5548 .ok()
5549 })
5550 .detach();
5551 }
5552
5553 fn find_closest_task(
5554 &mut self,
5555 cx: &mut ViewContext<Self>,
5556 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5557 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5558
5559 let ((buffer_id, row), tasks) = self
5560 .tasks
5561 .iter()
5562 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5563
5564 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5565 let tasks = Arc::new(tasks.to_owned());
5566 Some((buffer, *row, tasks))
5567 }
5568
5569 fn find_enclosing_node_task(
5570 &mut self,
5571 cx: &mut ViewContext<Self>,
5572 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5573 let snapshot = self.buffer.read(cx).snapshot(cx);
5574 let offset = self.selections.newest::<usize>(cx).head();
5575 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5576 let buffer_id = excerpt.buffer().remote_id();
5577
5578 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5579 let mut cursor = layer.node().walk();
5580
5581 while cursor.goto_first_child_for_byte(offset).is_some() {
5582 if cursor.node().end_byte() == offset {
5583 cursor.goto_next_sibling();
5584 }
5585 }
5586
5587 // Ascend to the smallest ancestor that contains the range and has a task.
5588 loop {
5589 let node = cursor.node();
5590 let node_range = node.byte_range();
5591 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5592
5593 // Check if this node contains our offset
5594 if node_range.start <= offset && node_range.end >= offset {
5595 // If it contains offset, check for task
5596 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5597 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5598 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5599 }
5600 }
5601
5602 if !cursor.goto_parent() {
5603 break;
5604 }
5605 }
5606 None
5607 }
5608
5609 fn render_run_indicator(
5610 &self,
5611 _style: &EditorStyle,
5612 is_active: bool,
5613 row: DisplayRow,
5614 cx: &mut ViewContext<Self>,
5615 ) -> IconButton {
5616 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5617 .shape(ui::IconButtonShape::Square)
5618 .icon_size(IconSize::XSmall)
5619 .icon_color(Color::Muted)
5620 .selected(is_active)
5621 .on_click(cx.listener(move |editor, _e, cx| {
5622 editor.focus(cx);
5623 editor.toggle_code_actions(
5624 &ToggleCodeActions {
5625 deployed_from_indicator: Some(row),
5626 },
5627 cx,
5628 );
5629 }))
5630 }
5631
5632 pub fn context_menu_visible(&self) -> bool {
5633 self.context_menu
5634 .read()
5635 .as_ref()
5636 .map_or(false, |menu| menu.visible())
5637 }
5638
5639 fn render_context_menu(
5640 &self,
5641 cursor_position: DisplayPoint,
5642 style: &EditorStyle,
5643 max_height: Pixels,
5644 cx: &mut ViewContext<Editor>,
5645 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5646 self.context_menu.read().as_ref().map(|menu| {
5647 menu.render(
5648 cursor_position,
5649 style,
5650 max_height,
5651 self.workspace.as_ref().map(|(w, _)| w.clone()),
5652 cx,
5653 )
5654 })
5655 }
5656
5657 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5658 cx.notify();
5659 self.completion_tasks.clear();
5660 let context_menu = self.context_menu.write().take();
5661 if context_menu.is_some() {
5662 self.update_visible_inline_completion(cx);
5663 }
5664 context_menu
5665 }
5666
5667 pub fn insert_snippet(
5668 &mut self,
5669 insertion_ranges: &[Range<usize>],
5670 snippet: Snippet,
5671 cx: &mut ViewContext<Self>,
5672 ) -> Result<()> {
5673 struct Tabstop<T> {
5674 is_end_tabstop: bool,
5675 ranges: Vec<Range<T>>,
5676 }
5677
5678 let tabstops = self.buffer.update(cx, |buffer, cx| {
5679 let snippet_text: Arc<str> = snippet.text.clone().into();
5680 buffer.edit(
5681 insertion_ranges
5682 .iter()
5683 .cloned()
5684 .map(|range| (range, snippet_text.clone())),
5685 Some(AutoindentMode::EachLine),
5686 cx,
5687 );
5688
5689 let snapshot = &*buffer.read(cx);
5690 let snippet = &snippet;
5691 snippet
5692 .tabstops
5693 .iter()
5694 .map(|tabstop| {
5695 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5696 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5697 });
5698 let mut tabstop_ranges = tabstop
5699 .iter()
5700 .flat_map(|tabstop_range| {
5701 let mut delta = 0_isize;
5702 insertion_ranges.iter().map(move |insertion_range| {
5703 let insertion_start = insertion_range.start as isize + delta;
5704 delta +=
5705 snippet.text.len() as isize - insertion_range.len() as isize;
5706
5707 let start = ((insertion_start + tabstop_range.start) as usize)
5708 .min(snapshot.len());
5709 let end = ((insertion_start + tabstop_range.end) as usize)
5710 .min(snapshot.len());
5711 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5712 })
5713 })
5714 .collect::<Vec<_>>();
5715 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5716
5717 Tabstop {
5718 is_end_tabstop,
5719 ranges: tabstop_ranges,
5720 }
5721 })
5722 .collect::<Vec<_>>()
5723 });
5724 if let Some(tabstop) = tabstops.first() {
5725 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5726 s.select_ranges(tabstop.ranges.iter().cloned());
5727 });
5728
5729 // If we're already at the last tabstop and it's at the end of the snippet,
5730 // we're done, we don't need to keep the state around.
5731 if !tabstop.is_end_tabstop {
5732 let ranges = tabstops
5733 .into_iter()
5734 .map(|tabstop| tabstop.ranges)
5735 .collect::<Vec<_>>();
5736 self.snippet_stack.push(SnippetState {
5737 active_index: 0,
5738 ranges,
5739 });
5740 }
5741
5742 // Check whether the just-entered snippet ends with an auto-closable bracket.
5743 if self.autoclose_regions.is_empty() {
5744 let snapshot = self.buffer.read(cx).snapshot(cx);
5745 for selection in &mut self.selections.all::<Point>(cx) {
5746 let selection_head = selection.head();
5747 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5748 continue;
5749 };
5750
5751 let mut bracket_pair = None;
5752 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5753 let prev_chars = snapshot
5754 .reversed_chars_at(selection_head)
5755 .collect::<String>();
5756 for (pair, enabled) in scope.brackets() {
5757 if enabled
5758 && pair.close
5759 && prev_chars.starts_with(pair.start.as_str())
5760 && next_chars.starts_with(pair.end.as_str())
5761 {
5762 bracket_pair = Some(pair.clone());
5763 break;
5764 }
5765 }
5766 if let Some(pair) = bracket_pair {
5767 let start = snapshot.anchor_after(selection_head);
5768 let end = snapshot.anchor_after(selection_head);
5769 self.autoclose_regions.push(AutocloseRegion {
5770 selection_id: selection.id,
5771 range: start..end,
5772 pair,
5773 });
5774 }
5775 }
5776 }
5777 }
5778 Ok(())
5779 }
5780
5781 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5782 self.move_to_snippet_tabstop(Bias::Right, cx)
5783 }
5784
5785 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5786 self.move_to_snippet_tabstop(Bias::Left, cx)
5787 }
5788
5789 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5790 if let Some(mut snippet) = self.snippet_stack.pop() {
5791 match bias {
5792 Bias::Left => {
5793 if snippet.active_index > 0 {
5794 snippet.active_index -= 1;
5795 } else {
5796 self.snippet_stack.push(snippet);
5797 return false;
5798 }
5799 }
5800 Bias::Right => {
5801 if snippet.active_index + 1 < snippet.ranges.len() {
5802 snippet.active_index += 1;
5803 } else {
5804 self.snippet_stack.push(snippet);
5805 return false;
5806 }
5807 }
5808 }
5809 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5810 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5811 s.select_anchor_ranges(current_ranges.iter().cloned())
5812 });
5813 // If snippet state is not at the last tabstop, push it back on the stack
5814 if snippet.active_index + 1 < snippet.ranges.len() {
5815 self.snippet_stack.push(snippet);
5816 }
5817 return true;
5818 }
5819 }
5820
5821 false
5822 }
5823
5824 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5825 self.transact(cx, |this, cx| {
5826 this.select_all(&SelectAll, cx);
5827 this.insert("", cx);
5828 });
5829 }
5830
5831 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5832 self.transact(cx, |this, cx| {
5833 this.select_autoclose_pair(cx);
5834 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5835 if !this.linked_edit_ranges.is_empty() {
5836 let selections = this.selections.all::<MultiBufferPoint>(cx);
5837 let snapshot = this.buffer.read(cx).snapshot(cx);
5838
5839 for selection in selections.iter() {
5840 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5841 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5842 if selection_start.buffer_id != selection_end.buffer_id {
5843 continue;
5844 }
5845 if let Some(ranges) =
5846 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5847 {
5848 for (buffer, entries) in ranges {
5849 linked_ranges.entry(buffer).or_default().extend(entries);
5850 }
5851 }
5852 }
5853 }
5854
5855 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5856 if !this.selections.line_mode {
5857 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5858 for selection in &mut selections {
5859 if selection.is_empty() {
5860 let old_head = selection.head();
5861 let mut new_head =
5862 movement::left(&display_map, old_head.to_display_point(&display_map))
5863 .to_point(&display_map);
5864 if let Some((buffer, line_buffer_range)) = display_map
5865 .buffer_snapshot
5866 .buffer_line_for_row(MultiBufferRow(old_head.row))
5867 {
5868 let indent_size =
5869 buffer.indent_size_for_line(line_buffer_range.start.row);
5870 let indent_len = match indent_size.kind {
5871 IndentKind::Space => {
5872 buffer.settings_at(line_buffer_range.start, cx).tab_size
5873 }
5874 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5875 };
5876 if old_head.column <= indent_size.len && old_head.column > 0 {
5877 let indent_len = indent_len.get();
5878 new_head = cmp::min(
5879 new_head,
5880 MultiBufferPoint::new(
5881 old_head.row,
5882 ((old_head.column - 1) / indent_len) * indent_len,
5883 ),
5884 );
5885 }
5886 }
5887
5888 selection.set_head(new_head, SelectionGoal::None);
5889 }
5890 }
5891 }
5892
5893 this.signature_help_state.set_backspace_pressed(true);
5894 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5895 this.insert("", cx);
5896 let empty_str: Arc<str> = Arc::from("");
5897 for (buffer, edits) in linked_ranges {
5898 let snapshot = buffer.read(cx).snapshot();
5899 use text::ToPoint as TP;
5900
5901 let edits = edits
5902 .into_iter()
5903 .map(|range| {
5904 let end_point = TP::to_point(&range.end, &snapshot);
5905 let mut start_point = TP::to_point(&range.start, &snapshot);
5906
5907 if end_point == start_point {
5908 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5909 .saturating_sub(1);
5910 start_point = TP::to_point(&offset, &snapshot);
5911 };
5912
5913 (start_point..end_point, empty_str.clone())
5914 })
5915 .sorted_by_key(|(range, _)| range.start)
5916 .collect::<Vec<_>>();
5917 buffer.update(cx, |this, cx| {
5918 this.edit(edits, None, cx);
5919 })
5920 }
5921 this.refresh_inline_completion(true, false, cx);
5922 linked_editing_ranges::refresh_linked_ranges(this, cx);
5923 });
5924 }
5925
5926 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5927 self.transact(cx, |this, cx| {
5928 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5929 let line_mode = s.line_mode;
5930 s.move_with(|map, selection| {
5931 if selection.is_empty() && !line_mode {
5932 let cursor = movement::right(map, selection.head());
5933 selection.end = cursor;
5934 selection.reversed = true;
5935 selection.goal = SelectionGoal::None;
5936 }
5937 })
5938 });
5939 this.insert("", cx);
5940 this.refresh_inline_completion(true, false, cx);
5941 });
5942 }
5943
5944 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5945 if self.move_to_prev_snippet_tabstop(cx) {
5946 return;
5947 }
5948
5949 self.outdent(&Outdent, cx);
5950 }
5951
5952 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5953 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5954 return;
5955 }
5956
5957 let mut selections = self.selections.all_adjusted(cx);
5958 let buffer = self.buffer.read(cx);
5959 let snapshot = buffer.snapshot(cx);
5960 let rows_iter = selections.iter().map(|s| s.head().row);
5961 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5962
5963 let mut edits = Vec::new();
5964 let mut prev_edited_row = 0;
5965 let mut row_delta = 0;
5966 for selection in &mut selections {
5967 if selection.start.row != prev_edited_row {
5968 row_delta = 0;
5969 }
5970 prev_edited_row = selection.end.row;
5971
5972 // If the selection is non-empty, then increase the indentation of the selected lines.
5973 if !selection.is_empty() {
5974 row_delta =
5975 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5976 continue;
5977 }
5978
5979 // If the selection is empty and the cursor is in the leading whitespace before the
5980 // suggested indentation, then auto-indent the line.
5981 let cursor = selection.head();
5982 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5983 if let Some(suggested_indent) =
5984 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5985 {
5986 if cursor.column < suggested_indent.len
5987 && cursor.column <= current_indent.len
5988 && current_indent.len <= suggested_indent.len
5989 {
5990 selection.start = Point::new(cursor.row, suggested_indent.len);
5991 selection.end = selection.start;
5992 if row_delta == 0 {
5993 edits.extend(Buffer::edit_for_indent_size_adjustment(
5994 cursor.row,
5995 current_indent,
5996 suggested_indent,
5997 ));
5998 row_delta = suggested_indent.len - current_indent.len;
5999 }
6000 continue;
6001 }
6002 }
6003
6004 // Otherwise, insert a hard or soft tab.
6005 let settings = buffer.settings_at(cursor, cx);
6006 let tab_size = if settings.hard_tabs {
6007 IndentSize::tab()
6008 } else {
6009 let tab_size = settings.tab_size.get();
6010 let char_column = snapshot
6011 .text_for_range(Point::new(cursor.row, 0)..cursor)
6012 .flat_map(str::chars)
6013 .count()
6014 + row_delta as usize;
6015 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6016 IndentSize::spaces(chars_to_next_tab_stop)
6017 };
6018 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6019 selection.end = selection.start;
6020 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6021 row_delta += tab_size.len;
6022 }
6023
6024 self.transact(cx, |this, cx| {
6025 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6026 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6027 this.refresh_inline_completion(true, false, cx);
6028 });
6029 }
6030
6031 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6032 if self.read_only(cx) {
6033 return;
6034 }
6035 let mut selections = self.selections.all::<Point>(cx);
6036 let mut prev_edited_row = 0;
6037 let mut row_delta = 0;
6038 let mut edits = Vec::new();
6039 let buffer = self.buffer.read(cx);
6040 let snapshot = buffer.snapshot(cx);
6041 for selection in &mut selections {
6042 if selection.start.row != prev_edited_row {
6043 row_delta = 0;
6044 }
6045 prev_edited_row = selection.end.row;
6046
6047 row_delta =
6048 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6049 }
6050
6051 self.transact(cx, |this, cx| {
6052 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6053 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6054 });
6055 }
6056
6057 fn indent_selection(
6058 buffer: &MultiBuffer,
6059 snapshot: &MultiBufferSnapshot,
6060 selection: &mut Selection<Point>,
6061 edits: &mut Vec<(Range<Point>, String)>,
6062 delta_for_start_row: u32,
6063 cx: &AppContext,
6064 ) -> u32 {
6065 let settings = buffer.settings_at(selection.start, cx);
6066 let tab_size = settings.tab_size.get();
6067 let indent_kind = if settings.hard_tabs {
6068 IndentKind::Tab
6069 } else {
6070 IndentKind::Space
6071 };
6072 let mut start_row = selection.start.row;
6073 let mut end_row = selection.end.row + 1;
6074
6075 // If a selection ends at the beginning of a line, don't indent
6076 // that last line.
6077 if selection.end.column == 0 && selection.end.row > selection.start.row {
6078 end_row -= 1;
6079 }
6080
6081 // Avoid re-indenting a row that has already been indented by a
6082 // previous selection, but still update this selection's column
6083 // to reflect that indentation.
6084 if delta_for_start_row > 0 {
6085 start_row += 1;
6086 selection.start.column += delta_for_start_row;
6087 if selection.end.row == selection.start.row {
6088 selection.end.column += delta_for_start_row;
6089 }
6090 }
6091
6092 let mut delta_for_end_row = 0;
6093 let has_multiple_rows = start_row + 1 != end_row;
6094 for row in start_row..end_row {
6095 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6096 let indent_delta = match (current_indent.kind, indent_kind) {
6097 (IndentKind::Space, IndentKind::Space) => {
6098 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6099 IndentSize::spaces(columns_to_next_tab_stop)
6100 }
6101 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6102 (_, IndentKind::Tab) => IndentSize::tab(),
6103 };
6104
6105 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6106 0
6107 } else {
6108 selection.start.column
6109 };
6110 let row_start = Point::new(row, start);
6111 edits.push((
6112 row_start..row_start,
6113 indent_delta.chars().collect::<String>(),
6114 ));
6115
6116 // Update this selection's endpoints to reflect the indentation.
6117 if row == selection.start.row {
6118 selection.start.column += indent_delta.len;
6119 }
6120 if row == selection.end.row {
6121 selection.end.column += indent_delta.len;
6122 delta_for_end_row = indent_delta.len;
6123 }
6124 }
6125
6126 if selection.start.row == selection.end.row {
6127 delta_for_start_row + delta_for_end_row
6128 } else {
6129 delta_for_end_row
6130 }
6131 }
6132
6133 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6134 if self.read_only(cx) {
6135 return;
6136 }
6137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6138 let selections = self.selections.all::<Point>(cx);
6139 let mut deletion_ranges = Vec::new();
6140 let mut last_outdent = None;
6141 {
6142 let buffer = self.buffer.read(cx);
6143 let snapshot = buffer.snapshot(cx);
6144 for selection in &selections {
6145 let settings = buffer.settings_at(selection.start, cx);
6146 let tab_size = settings.tab_size.get();
6147 let mut rows = selection.spanned_rows(false, &display_map);
6148
6149 // Avoid re-outdenting a row that has already been outdented by a
6150 // previous selection.
6151 if let Some(last_row) = last_outdent {
6152 if last_row == rows.start {
6153 rows.start = rows.start.next_row();
6154 }
6155 }
6156 let has_multiple_rows = rows.len() > 1;
6157 for row in rows.iter_rows() {
6158 let indent_size = snapshot.indent_size_for_line(row);
6159 if indent_size.len > 0 {
6160 let deletion_len = match indent_size.kind {
6161 IndentKind::Space => {
6162 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6163 if columns_to_prev_tab_stop == 0 {
6164 tab_size
6165 } else {
6166 columns_to_prev_tab_stop
6167 }
6168 }
6169 IndentKind::Tab => 1,
6170 };
6171 let start = if has_multiple_rows
6172 || deletion_len > selection.start.column
6173 || indent_size.len < selection.start.column
6174 {
6175 0
6176 } else {
6177 selection.start.column - deletion_len
6178 };
6179 deletion_ranges.push(
6180 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6181 );
6182 last_outdent = Some(row);
6183 }
6184 }
6185 }
6186 }
6187
6188 self.transact(cx, |this, cx| {
6189 this.buffer.update(cx, |buffer, cx| {
6190 let empty_str: Arc<str> = Arc::default();
6191 buffer.edit(
6192 deletion_ranges
6193 .into_iter()
6194 .map(|range| (range, empty_str.clone())),
6195 None,
6196 cx,
6197 );
6198 });
6199 let selections = this.selections.all::<usize>(cx);
6200 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6201 });
6202 }
6203
6204 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6205 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6206 let selections = self.selections.all::<Point>(cx);
6207
6208 let mut new_cursors = Vec::new();
6209 let mut edit_ranges = Vec::new();
6210 let mut selections = selections.iter().peekable();
6211 while let Some(selection) = selections.next() {
6212 let mut rows = selection.spanned_rows(false, &display_map);
6213 let goal_display_column = selection.head().to_display_point(&display_map).column();
6214
6215 // Accumulate contiguous regions of rows that we want to delete.
6216 while let Some(next_selection) = selections.peek() {
6217 let next_rows = next_selection.spanned_rows(false, &display_map);
6218 if next_rows.start <= rows.end {
6219 rows.end = next_rows.end;
6220 selections.next().unwrap();
6221 } else {
6222 break;
6223 }
6224 }
6225
6226 let buffer = &display_map.buffer_snapshot;
6227 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6228 let edit_end;
6229 let cursor_buffer_row;
6230 if buffer.max_point().row >= rows.end.0 {
6231 // If there's a line after the range, delete the \n from the end of the row range
6232 // and position the cursor on the next line.
6233 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6234 cursor_buffer_row = rows.end;
6235 } else {
6236 // If there isn't a line after the range, delete the \n from the line before the
6237 // start of the row range and position the cursor there.
6238 edit_start = edit_start.saturating_sub(1);
6239 edit_end = buffer.len();
6240 cursor_buffer_row = rows.start.previous_row();
6241 }
6242
6243 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6244 *cursor.column_mut() =
6245 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6246
6247 new_cursors.push((
6248 selection.id,
6249 buffer.anchor_after(cursor.to_point(&display_map)),
6250 ));
6251 edit_ranges.push(edit_start..edit_end);
6252 }
6253
6254 self.transact(cx, |this, cx| {
6255 let buffer = this.buffer.update(cx, |buffer, cx| {
6256 let empty_str: Arc<str> = Arc::default();
6257 buffer.edit(
6258 edit_ranges
6259 .into_iter()
6260 .map(|range| (range, empty_str.clone())),
6261 None,
6262 cx,
6263 );
6264 buffer.snapshot(cx)
6265 });
6266 let new_selections = new_cursors
6267 .into_iter()
6268 .map(|(id, cursor)| {
6269 let cursor = cursor.to_point(&buffer);
6270 Selection {
6271 id,
6272 start: cursor,
6273 end: cursor,
6274 reversed: false,
6275 goal: SelectionGoal::None,
6276 }
6277 })
6278 .collect();
6279
6280 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6281 s.select(new_selections);
6282 });
6283 });
6284 }
6285
6286 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6287 if self.read_only(cx) {
6288 return;
6289 }
6290 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6291 for selection in self.selections.all::<Point>(cx) {
6292 let start = MultiBufferRow(selection.start.row);
6293 let end = if selection.start.row == selection.end.row {
6294 MultiBufferRow(selection.start.row + 1)
6295 } else {
6296 MultiBufferRow(selection.end.row)
6297 };
6298
6299 if let Some(last_row_range) = row_ranges.last_mut() {
6300 if start <= last_row_range.end {
6301 last_row_range.end = end;
6302 continue;
6303 }
6304 }
6305 row_ranges.push(start..end);
6306 }
6307
6308 let snapshot = self.buffer.read(cx).snapshot(cx);
6309 let mut cursor_positions = Vec::new();
6310 for row_range in &row_ranges {
6311 let anchor = snapshot.anchor_before(Point::new(
6312 row_range.end.previous_row().0,
6313 snapshot.line_len(row_range.end.previous_row()),
6314 ));
6315 cursor_positions.push(anchor..anchor);
6316 }
6317
6318 self.transact(cx, |this, cx| {
6319 for row_range in row_ranges.into_iter().rev() {
6320 for row in row_range.iter_rows().rev() {
6321 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6322 let next_line_row = row.next_row();
6323 let indent = snapshot.indent_size_for_line(next_line_row);
6324 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6325
6326 let replace = if snapshot.line_len(next_line_row) > indent.len {
6327 " "
6328 } else {
6329 ""
6330 };
6331
6332 this.buffer.update(cx, |buffer, cx| {
6333 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6334 });
6335 }
6336 }
6337
6338 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6339 s.select_anchor_ranges(cursor_positions)
6340 });
6341 });
6342 }
6343
6344 pub fn sort_lines_case_sensitive(
6345 &mut self,
6346 _: &SortLinesCaseSensitive,
6347 cx: &mut ViewContext<Self>,
6348 ) {
6349 self.manipulate_lines(cx, |lines| lines.sort())
6350 }
6351
6352 pub fn sort_lines_case_insensitive(
6353 &mut self,
6354 _: &SortLinesCaseInsensitive,
6355 cx: &mut ViewContext<Self>,
6356 ) {
6357 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6358 }
6359
6360 pub fn unique_lines_case_insensitive(
6361 &mut self,
6362 _: &UniqueLinesCaseInsensitive,
6363 cx: &mut ViewContext<Self>,
6364 ) {
6365 self.manipulate_lines(cx, |lines| {
6366 let mut seen = HashSet::default();
6367 lines.retain(|line| seen.insert(line.to_lowercase()));
6368 })
6369 }
6370
6371 pub fn unique_lines_case_sensitive(
6372 &mut self,
6373 _: &UniqueLinesCaseSensitive,
6374 cx: &mut ViewContext<Self>,
6375 ) {
6376 self.manipulate_lines(cx, |lines| {
6377 let mut seen = HashSet::default();
6378 lines.retain(|line| seen.insert(*line));
6379 })
6380 }
6381
6382 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6383 let mut revert_changes = HashMap::default();
6384 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6385 for hunk in hunks_for_rows(
6386 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6387 &multi_buffer_snapshot,
6388 ) {
6389 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6390 }
6391 if !revert_changes.is_empty() {
6392 self.transact(cx, |editor, cx| {
6393 editor.revert(revert_changes, cx);
6394 });
6395 }
6396 }
6397
6398 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6399 let Some(project) = self.project.clone() else {
6400 return;
6401 };
6402 self.reload(project, cx).detach_and_notify_err(cx);
6403 }
6404
6405 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6406 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6407 if !revert_changes.is_empty() {
6408 self.transact(cx, |editor, cx| {
6409 editor.revert(revert_changes, cx);
6410 });
6411 }
6412 }
6413
6414 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6415 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6416 let project_path = buffer.read(cx).project_path(cx)?;
6417 let project = self.project.as_ref()?.read(cx);
6418 let entry = project.entry_for_path(&project_path, cx)?;
6419 let parent = match &entry.canonical_path {
6420 Some(canonical_path) => canonical_path.to_path_buf(),
6421 None => project.absolute_path(&project_path, cx)?,
6422 }
6423 .parent()?
6424 .to_path_buf();
6425 Some(parent)
6426 }) {
6427 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6428 }
6429 }
6430
6431 fn gather_revert_changes(
6432 &mut self,
6433 selections: &[Selection<Anchor>],
6434 cx: &mut ViewContext<'_, Editor>,
6435 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6436 let mut revert_changes = HashMap::default();
6437 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6438 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6439 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6440 }
6441 revert_changes
6442 }
6443
6444 pub fn prepare_revert_change(
6445 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6446 multi_buffer: &Model<MultiBuffer>,
6447 hunk: &MultiBufferDiffHunk,
6448 cx: &AppContext,
6449 ) -> Option<()> {
6450 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6451 let buffer = buffer.read(cx);
6452 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6453 let buffer_snapshot = buffer.snapshot();
6454 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6455 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6456 probe
6457 .0
6458 .start
6459 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6460 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6461 }) {
6462 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6463 Some(())
6464 } else {
6465 None
6466 }
6467 }
6468
6469 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6470 self.manipulate_lines(cx, |lines| lines.reverse())
6471 }
6472
6473 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6474 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6475 }
6476
6477 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6478 where
6479 Fn: FnMut(&mut Vec<&str>),
6480 {
6481 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6482 let buffer = self.buffer.read(cx).snapshot(cx);
6483
6484 let mut edits = Vec::new();
6485
6486 let selections = self.selections.all::<Point>(cx);
6487 let mut selections = selections.iter().peekable();
6488 let mut contiguous_row_selections = Vec::new();
6489 let mut new_selections = Vec::new();
6490 let mut added_lines = 0;
6491 let mut removed_lines = 0;
6492
6493 while let Some(selection) = selections.next() {
6494 let (start_row, end_row) = consume_contiguous_rows(
6495 &mut contiguous_row_selections,
6496 selection,
6497 &display_map,
6498 &mut selections,
6499 );
6500
6501 let start_point = Point::new(start_row.0, 0);
6502 let end_point = Point::new(
6503 end_row.previous_row().0,
6504 buffer.line_len(end_row.previous_row()),
6505 );
6506 let text = buffer
6507 .text_for_range(start_point..end_point)
6508 .collect::<String>();
6509
6510 let mut lines = text.split('\n').collect_vec();
6511
6512 let lines_before = lines.len();
6513 callback(&mut lines);
6514 let lines_after = lines.len();
6515
6516 edits.push((start_point..end_point, lines.join("\n")));
6517
6518 // Selections must change based on added and removed line count
6519 let start_row =
6520 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6521 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6522 new_selections.push(Selection {
6523 id: selection.id,
6524 start: start_row,
6525 end: end_row,
6526 goal: SelectionGoal::None,
6527 reversed: selection.reversed,
6528 });
6529
6530 if lines_after > lines_before {
6531 added_lines += lines_after - lines_before;
6532 } else if lines_before > lines_after {
6533 removed_lines += lines_before - lines_after;
6534 }
6535 }
6536
6537 self.transact(cx, |this, cx| {
6538 let buffer = this.buffer.update(cx, |buffer, cx| {
6539 buffer.edit(edits, None, cx);
6540 buffer.snapshot(cx)
6541 });
6542
6543 // Recalculate offsets on newly edited buffer
6544 let new_selections = new_selections
6545 .iter()
6546 .map(|s| {
6547 let start_point = Point::new(s.start.0, 0);
6548 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6549 Selection {
6550 id: s.id,
6551 start: buffer.point_to_offset(start_point),
6552 end: buffer.point_to_offset(end_point),
6553 goal: s.goal,
6554 reversed: s.reversed,
6555 }
6556 })
6557 .collect();
6558
6559 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6560 s.select(new_selections);
6561 });
6562
6563 this.request_autoscroll(Autoscroll::fit(), cx);
6564 });
6565 }
6566
6567 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6568 self.manipulate_text(cx, |text| text.to_uppercase())
6569 }
6570
6571 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6572 self.manipulate_text(cx, |text| text.to_lowercase())
6573 }
6574
6575 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
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::Title))
6581 .join("\n")
6582 })
6583 }
6584
6585 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6586 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6587 }
6588
6589 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6590 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6591 }
6592
6593 pub fn convert_to_upper_camel_case(
6594 &mut self,
6595 _: &ConvertToUpperCamelCase,
6596 cx: &mut ViewContext<Self>,
6597 ) {
6598 self.manipulate_text(cx, |text| {
6599 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6600 // https://github.com/rutrum/convert-case/issues/16
6601 text.split('\n')
6602 .map(|line| line.to_case(Case::UpperCamel))
6603 .join("\n")
6604 })
6605 }
6606
6607 pub fn convert_to_lower_camel_case(
6608 &mut self,
6609 _: &ConvertToLowerCamelCase,
6610 cx: &mut ViewContext<Self>,
6611 ) {
6612 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6613 }
6614
6615 pub fn convert_to_opposite_case(
6616 &mut self,
6617 _: &ConvertToOppositeCase,
6618 cx: &mut ViewContext<Self>,
6619 ) {
6620 self.manipulate_text(cx, |text| {
6621 text.chars()
6622 .fold(String::with_capacity(text.len()), |mut t, c| {
6623 if c.is_uppercase() {
6624 t.extend(c.to_lowercase());
6625 } else {
6626 t.extend(c.to_uppercase());
6627 }
6628 t
6629 })
6630 })
6631 }
6632
6633 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6634 where
6635 Fn: FnMut(&str) -> String,
6636 {
6637 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6638 let buffer = self.buffer.read(cx).snapshot(cx);
6639
6640 let mut new_selections = Vec::new();
6641 let mut edits = Vec::new();
6642 let mut selection_adjustment = 0i32;
6643
6644 for selection in self.selections.all::<usize>(cx) {
6645 let selection_is_empty = selection.is_empty();
6646
6647 let (start, end) = if selection_is_empty {
6648 let word_range = movement::surrounding_word(
6649 &display_map,
6650 selection.start.to_display_point(&display_map),
6651 );
6652 let start = word_range.start.to_offset(&display_map, Bias::Left);
6653 let end = word_range.end.to_offset(&display_map, Bias::Left);
6654 (start, end)
6655 } else {
6656 (selection.start, selection.end)
6657 };
6658
6659 let text = buffer.text_for_range(start..end).collect::<String>();
6660 let old_length = text.len() as i32;
6661 let text = callback(&text);
6662
6663 new_selections.push(Selection {
6664 start: (start as i32 - selection_adjustment) as usize,
6665 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6666 goal: SelectionGoal::None,
6667 ..selection
6668 });
6669
6670 selection_adjustment += old_length - text.len() as i32;
6671
6672 edits.push((start..end, text));
6673 }
6674
6675 self.transact(cx, |this, cx| {
6676 this.buffer.update(cx, |buffer, cx| {
6677 buffer.edit(edits, None, cx);
6678 });
6679
6680 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6681 s.select(new_selections);
6682 });
6683
6684 this.request_autoscroll(Autoscroll::fit(), cx);
6685 });
6686 }
6687
6688 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6689 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6690 let buffer = &display_map.buffer_snapshot;
6691 let selections = self.selections.all::<Point>(cx);
6692
6693 let mut edits = Vec::new();
6694 let mut selections_iter = selections.iter().peekable();
6695 while let Some(selection) = selections_iter.next() {
6696 // Avoid duplicating the same lines twice.
6697 let mut rows = selection.spanned_rows(false, &display_map);
6698
6699 while let Some(next_selection) = selections_iter.peek() {
6700 let next_rows = next_selection.spanned_rows(false, &display_map);
6701 if next_rows.start < rows.end {
6702 rows.end = next_rows.end;
6703 selections_iter.next().unwrap();
6704 } else {
6705 break;
6706 }
6707 }
6708
6709 // Copy the text from the selected row region and splice it either at the start
6710 // or end of the region.
6711 let start = Point::new(rows.start.0, 0);
6712 let end = Point::new(
6713 rows.end.previous_row().0,
6714 buffer.line_len(rows.end.previous_row()),
6715 );
6716 let text = buffer
6717 .text_for_range(start..end)
6718 .chain(Some("\n"))
6719 .collect::<String>();
6720 let insert_location = if upwards {
6721 Point::new(rows.end.0, 0)
6722 } else {
6723 start
6724 };
6725 edits.push((insert_location..insert_location, text));
6726 }
6727
6728 self.transact(cx, |this, cx| {
6729 this.buffer.update(cx, |buffer, cx| {
6730 buffer.edit(edits, None, cx);
6731 });
6732
6733 this.request_autoscroll(Autoscroll::fit(), cx);
6734 });
6735 }
6736
6737 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6738 self.duplicate_line(true, cx);
6739 }
6740
6741 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6742 self.duplicate_line(false, cx);
6743 }
6744
6745 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6747 let buffer = self.buffer.read(cx).snapshot(cx);
6748
6749 let mut edits = Vec::new();
6750 let mut unfold_ranges = Vec::new();
6751 let mut refold_ranges = Vec::new();
6752
6753 let selections = self.selections.all::<Point>(cx);
6754 let mut selections = selections.iter().peekable();
6755 let mut contiguous_row_selections = Vec::new();
6756 let mut new_selections = Vec::new();
6757
6758 while let Some(selection) = selections.next() {
6759 // Find all the selections that span a contiguous row range
6760 let (start_row, end_row) = consume_contiguous_rows(
6761 &mut contiguous_row_selections,
6762 selection,
6763 &display_map,
6764 &mut selections,
6765 );
6766
6767 // Move the text spanned by the row range to be before the line preceding the row range
6768 if start_row.0 > 0 {
6769 let range_to_move = Point::new(
6770 start_row.previous_row().0,
6771 buffer.line_len(start_row.previous_row()),
6772 )
6773 ..Point::new(
6774 end_row.previous_row().0,
6775 buffer.line_len(end_row.previous_row()),
6776 );
6777 let insertion_point = display_map
6778 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6779 .0;
6780
6781 // Don't move lines across excerpts
6782 if buffer
6783 .excerpt_boundaries_in_range((
6784 Bound::Excluded(insertion_point),
6785 Bound::Included(range_to_move.end),
6786 ))
6787 .next()
6788 .is_none()
6789 {
6790 let text = buffer
6791 .text_for_range(range_to_move.clone())
6792 .flat_map(|s| s.chars())
6793 .skip(1)
6794 .chain(['\n'])
6795 .collect::<String>();
6796
6797 edits.push((
6798 buffer.anchor_after(range_to_move.start)
6799 ..buffer.anchor_before(range_to_move.end),
6800 String::new(),
6801 ));
6802 let insertion_anchor = buffer.anchor_after(insertion_point);
6803 edits.push((insertion_anchor..insertion_anchor, text));
6804
6805 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6806
6807 // Move selections up
6808 new_selections.extend(contiguous_row_selections.drain(..).map(
6809 |mut selection| {
6810 selection.start.row -= row_delta;
6811 selection.end.row -= row_delta;
6812 selection
6813 },
6814 ));
6815
6816 // Move folds up
6817 unfold_ranges.push(range_to_move.clone());
6818 for fold in display_map.folds_in_range(
6819 buffer.anchor_before(range_to_move.start)
6820 ..buffer.anchor_after(range_to_move.end),
6821 ) {
6822 let mut start = fold.range.start.to_point(&buffer);
6823 let mut end = fold.range.end.to_point(&buffer);
6824 start.row -= row_delta;
6825 end.row -= row_delta;
6826 refold_ranges.push((start..end, fold.placeholder.clone()));
6827 }
6828 }
6829 }
6830
6831 // If we didn't move line(s), preserve the existing selections
6832 new_selections.append(&mut contiguous_row_selections);
6833 }
6834
6835 self.transact(cx, |this, cx| {
6836 this.unfold_ranges(&unfold_ranges, true, true, cx);
6837 this.buffer.update(cx, |buffer, cx| {
6838 for (range, text) in edits {
6839 buffer.edit([(range, text)], None, cx);
6840 }
6841 });
6842 this.fold_ranges(refold_ranges, true, cx);
6843 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6844 s.select(new_selections);
6845 })
6846 });
6847 }
6848
6849 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6851 let buffer = self.buffer.read(cx).snapshot(cx);
6852
6853 let mut edits = Vec::new();
6854 let mut unfold_ranges = Vec::new();
6855 let mut refold_ranges = Vec::new();
6856
6857 let selections = self.selections.all::<Point>(cx);
6858 let mut selections = selections.iter().peekable();
6859 let mut contiguous_row_selections = Vec::new();
6860 let mut new_selections = Vec::new();
6861
6862 while let Some(selection) = selections.next() {
6863 // Find all the selections that span a contiguous row range
6864 let (start_row, end_row) = consume_contiguous_rows(
6865 &mut contiguous_row_selections,
6866 selection,
6867 &display_map,
6868 &mut selections,
6869 );
6870
6871 // Move the text spanned by the row range to be after the last line of the row range
6872 if end_row.0 <= buffer.max_point().row {
6873 let range_to_move =
6874 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6875 let insertion_point = display_map
6876 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6877 .0;
6878
6879 // Don't move lines across excerpt boundaries
6880 if buffer
6881 .excerpt_boundaries_in_range((
6882 Bound::Excluded(range_to_move.start),
6883 Bound::Included(insertion_point),
6884 ))
6885 .next()
6886 .is_none()
6887 {
6888 let mut text = String::from("\n");
6889 text.extend(buffer.text_for_range(range_to_move.clone()));
6890 text.pop(); // Drop trailing newline
6891 edits.push((
6892 buffer.anchor_after(range_to_move.start)
6893 ..buffer.anchor_before(range_to_move.end),
6894 String::new(),
6895 ));
6896 let insertion_anchor = buffer.anchor_after(insertion_point);
6897 edits.push((insertion_anchor..insertion_anchor, text));
6898
6899 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6900
6901 // Move selections down
6902 new_selections.extend(contiguous_row_selections.drain(..).map(
6903 |mut selection| {
6904 selection.start.row += row_delta;
6905 selection.end.row += row_delta;
6906 selection
6907 },
6908 ));
6909
6910 // Move folds down
6911 unfold_ranges.push(range_to_move.clone());
6912 for fold in display_map.folds_in_range(
6913 buffer.anchor_before(range_to_move.start)
6914 ..buffer.anchor_after(range_to_move.end),
6915 ) {
6916 let mut start = fold.range.start.to_point(&buffer);
6917 let mut end = fold.range.end.to_point(&buffer);
6918 start.row += row_delta;
6919 end.row += row_delta;
6920 refold_ranges.push((start..end, fold.placeholder.clone()));
6921 }
6922 }
6923 }
6924
6925 // If we didn't move line(s), preserve the existing selections
6926 new_selections.append(&mut contiguous_row_selections);
6927 }
6928
6929 self.transact(cx, |this, cx| {
6930 this.unfold_ranges(&unfold_ranges, true, true, cx);
6931 this.buffer.update(cx, |buffer, cx| {
6932 for (range, text) in edits {
6933 buffer.edit([(range, text)], None, cx);
6934 }
6935 });
6936 this.fold_ranges(refold_ranges, true, cx);
6937 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6938 });
6939 }
6940
6941 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6942 let text_layout_details = &self.text_layout_details(cx);
6943 self.transact(cx, |this, cx| {
6944 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6945 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6946 let line_mode = s.line_mode;
6947 s.move_with(|display_map, selection| {
6948 if !selection.is_empty() || line_mode {
6949 return;
6950 }
6951
6952 let mut head = selection.head();
6953 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6954 if head.column() == display_map.line_len(head.row()) {
6955 transpose_offset = display_map
6956 .buffer_snapshot
6957 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6958 }
6959
6960 if transpose_offset == 0 {
6961 return;
6962 }
6963
6964 *head.column_mut() += 1;
6965 head = display_map.clip_point(head, Bias::Right);
6966 let goal = SelectionGoal::HorizontalPosition(
6967 display_map
6968 .x_for_display_point(head, text_layout_details)
6969 .into(),
6970 );
6971 selection.collapse_to(head, goal);
6972
6973 let transpose_start = display_map
6974 .buffer_snapshot
6975 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6976 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6977 let transpose_end = display_map
6978 .buffer_snapshot
6979 .clip_offset(transpose_offset + 1, Bias::Right);
6980 if let Some(ch) =
6981 display_map.buffer_snapshot.chars_at(transpose_start).next()
6982 {
6983 edits.push((transpose_start..transpose_offset, String::new()));
6984 edits.push((transpose_end..transpose_end, ch.to_string()));
6985 }
6986 }
6987 });
6988 edits
6989 });
6990 this.buffer
6991 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6992 let selections = this.selections.all::<usize>(cx);
6993 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6994 s.select(selections);
6995 });
6996 });
6997 }
6998
6999 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7000 self.rewrap_impl(true, cx)
7001 }
7002
7003 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
7004 let buffer = self.buffer.read(cx).snapshot(cx);
7005 let selections = self.selections.all::<Point>(cx);
7006 let mut selections = selections.iter().peekable();
7007
7008 let mut edits = Vec::new();
7009 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7010
7011 while let Some(selection) = selections.next() {
7012 let mut start_row = selection.start.row;
7013 let mut end_row = selection.end.row;
7014
7015 // Skip selections that overlap with a range that has already been rewrapped.
7016 let selection_range = start_row..end_row;
7017 if rewrapped_row_ranges
7018 .iter()
7019 .any(|range| range.overlaps(&selection_range))
7020 {
7021 continue;
7022 }
7023
7024 let mut should_rewrap = !only_text;
7025
7026 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7027 match language_scope.language_name().0.as_ref() {
7028 "Markdown" | "Plain Text" => {
7029 should_rewrap = true;
7030 }
7031 _ => {}
7032 }
7033 }
7034
7035 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7036
7037 // Since not all lines in the selection may be at the same indent
7038 // level, choose the indent size that is the most common between all
7039 // of the lines.
7040 //
7041 // If there is a tie, we use the deepest indent.
7042 let (indent_size, indent_end) = {
7043 let mut indent_size_occurrences = HashMap::default();
7044 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7045
7046 for row in start_row..=end_row {
7047 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7048 rows_by_indent_size.entry(indent).or_default().push(row);
7049 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7050 }
7051
7052 let indent_size = indent_size_occurrences
7053 .into_iter()
7054 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7055 .map(|(indent, _)| indent)
7056 .unwrap_or_default();
7057 let row = rows_by_indent_size[&indent_size][0];
7058 let indent_end = Point::new(row, indent_size.len);
7059
7060 (indent_size, indent_end)
7061 };
7062
7063 let mut line_prefix = indent_size.chars().collect::<String>();
7064
7065 if let Some(comment_prefix) =
7066 buffer
7067 .language_scope_at(selection.head())
7068 .and_then(|language| {
7069 language
7070 .line_comment_prefixes()
7071 .iter()
7072 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7073 .cloned()
7074 })
7075 {
7076 line_prefix.push_str(&comment_prefix);
7077 should_rewrap = true;
7078 }
7079
7080 if !should_rewrap {
7081 continue;
7082 }
7083
7084 if selection.is_empty() {
7085 'expand_upwards: while start_row > 0 {
7086 let prev_row = start_row - 1;
7087 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7088 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7089 {
7090 start_row = prev_row;
7091 } else {
7092 break 'expand_upwards;
7093 }
7094 }
7095
7096 'expand_downwards: while end_row < buffer.max_point().row {
7097 let next_row = end_row + 1;
7098 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7099 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7100 {
7101 end_row = next_row;
7102 } else {
7103 break 'expand_downwards;
7104 }
7105 }
7106 }
7107
7108 let start = Point::new(start_row, 0);
7109 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7110 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7111 let Some(lines_without_prefixes) = selection_text
7112 .lines()
7113 .map(|line| {
7114 line.strip_prefix(&line_prefix)
7115 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7116 .ok_or_else(|| {
7117 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7118 })
7119 })
7120 .collect::<Result<Vec<_>, _>>()
7121 .log_err()
7122 else {
7123 continue;
7124 };
7125
7126 let wrap_column = buffer
7127 .settings_at(Point::new(start_row, 0), cx)
7128 .preferred_line_length as usize;
7129 let wrapped_text = wrap_with_prefix(
7130 line_prefix,
7131 lines_without_prefixes.join(" "),
7132 wrap_column,
7133 tab_size,
7134 );
7135
7136 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7137 let mut offset = start.to_offset(&buffer);
7138 let mut moved_since_edit = true;
7139
7140 for change in diff.iter_all_changes() {
7141 let value = change.value();
7142 match change.tag() {
7143 ChangeTag::Equal => {
7144 offset += value.len();
7145 moved_since_edit = true;
7146 }
7147 ChangeTag::Delete => {
7148 let start = buffer.anchor_after(offset);
7149 let end = buffer.anchor_before(offset + value.len());
7150
7151 if moved_since_edit {
7152 edits.push((start..end, String::new()));
7153 } else {
7154 edits.last_mut().unwrap().0.end = end;
7155 }
7156
7157 offset += value.len();
7158 moved_since_edit = false;
7159 }
7160 ChangeTag::Insert => {
7161 if moved_since_edit {
7162 let anchor = buffer.anchor_after(offset);
7163 edits.push((anchor..anchor, value.to_string()));
7164 } else {
7165 edits.last_mut().unwrap().1.push_str(value);
7166 }
7167
7168 moved_since_edit = false;
7169 }
7170 }
7171 }
7172
7173 rewrapped_row_ranges.push(start_row..=end_row);
7174 }
7175
7176 self.buffer
7177 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7178 }
7179
7180 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7181 let mut text = String::new();
7182 let buffer = self.buffer.read(cx).snapshot(cx);
7183 let mut selections = self.selections.all::<Point>(cx);
7184 let mut clipboard_selections = Vec::with_capacity(selections.len());
7185 {
7186 let max_point = buffer.max_point();
7187 let mut is_first = true;
7188 for selection in &mut selections {
7189 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7190 if is_entire_line {
7191 selection.start = Point::new(selection.start.row, 0);
7192 if !selection.is_empty() && selection.end.column == 0 {
7193 selection.end = cmp::min(max_point, selection.end);
7194 } else {
7195 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7196 }
7197 selection.goal = SelectionGoal::None;
7198 }
7199 if is_first {
7200 is_first = false;
7201 } else {
7202 text += "\n";
7203 }
7204 let mut len = 0;
7205 for chunk in buffer.text_for_range(selection.start..selection.end) {
7206 text.push_str(chunk);
7207 len += chunk.len();
7208 }
7209 clipboard_selections.push(ClipboardSelection {
7210 len,
7211 is_entire_line,
7212 first_line_indent: buffer
7213 .indent_size_for_line(MultiBufferRow(selection.start.row))
7214 .len,
7215 });
7216 }
7217 }
7218
7219 self.transact(cx, |this, cx| {
7220 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7221 s.select(selections);
7222 });
7223 this.insert("", cx);
7224 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7225 text,
7226 clipboard_selections,
7227 ));
7228 });
7229 }
7230
7231 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7232 let selections = self.selections.all::<Point>(cx);
7233 let buffer = self.buffer.read(cx).read(cx);
7234 let mut text = String::new();
7235
7236 let mut clipboard_selections = Vec::with_capacity(selections.len());
7237 {
7238 let max_point = buffer.max_point();
7239 let mut is_first = true;
7240 for selection in selections.iter() {
7241 let mut start = selection.start;
7242 let mut end = selection.end;
7243 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7244 if is_entire_line {
7245 start = Point::new(start.row, 0);
7246 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7247 }
7248 if is_first {
7249 is_first = false;
7250 } else {
7251 text += "\n";
7252 }
7253 let mut len = 0;
7254 for chunk in buffer.text_for_range(start..end) {
7255 text.push_str(chunk);
7256 len += chunk.len();
7257 }
7258 clipboard_selections.push(ClipboardSelection {
7259 len,
7260 is_entire_line,
7261 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7262 });
7263 }
7264 }
7265
7266 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7267 text,
7268 clipboard_selections,
7269 ));
7270 }
7271
7272 pub fn do_paste(
7273 &mut self,
7274 text: &String,
7275 clipboard_selections: Option<Vec<ClipboardSelection>>,
7276 handle_entire_lines: bool,
7277 cx: &mut ViewContext<Self>,
7278 ) {
7279 if self.read_only(cx) {
7280 return;
7281 }
7282
7283 let clipboard_text = Cow::Borrowed(text);
7284
7285 self.transact(cx, |this, cx| {
7286 if let Some(mut clipboard_selections) = clipboard_selections {
7287 let old_selections = this.selections.all::<usize>(cx);
7288 let all_selections_were_entire_line =
7289 clipboard_selections.iter().all(|s| s.is_entire_line);
7290 let first_selection_indent_column =
7291 clipboard_selections.first().map(|s| s.first_line_indent);
7292 if clipboard_selections.len() != old_selections.len() {
7293 clipboard_selections.drain(..);
7294 }
7295 let cursor_offset = this.selections.last::<usize>(cx).head();
7296 let mut auto_indent_on_paste = true;
7297
7298 this.buffer.update(cx, |buffer, cx| {
7299 let snapshot = buffer.read(cx);
7300 auto_indent_on_paste =
7301 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7302
7303 let mut start_offset = 0;
7304 let mut edits = Vec::new();
7305 let mut original_indent_columns = Vec::new();
7306 for (ix, selection) in old_selections.iter().enumerate() {
7307 let to_insert;
7308 let entire_line;
7309 let original_indent_column;
7310 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7311 let end_offset = start_offset + clipboard_selection.len;
7312 to_insert = &clipboard_text[start_offset..end_offset];
7313 entire_line = clipboard_selection.is_entire_line;
7314 start_offset = end_offset + 1;
7315 original_indent_column = Some(clipboard_selection.first_line_indent);
7316 } else {
7317 to_insert = clipboard_text.as_str();
7318 entire_line = all_selections_were_entire_line;
7319 original_indent_column = first_selection_indent_column
7320 }
7321
7322 // If the corresponding selection was empty when this slice of the
7323 // clipboard text was written, then the entire line containing the
7324 // selection was copied. If this selection is also currently empty,
7325 // then paste the line before the current line of the buffer.
7326 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7327 let column = selection.start.to_point(&snapshot).column as usize;
7328 let line_start = selection.start - column;
7329 line_start..line_start
7330 } else {
7331 selection.range()
7332 };
7333
7334 edits.push((range, to_insert));
7335 original_indent_columns.extend(original_indent_column);
7336 }
7337 drop(snapshot);
7338
7339 buffer.edit(
7340 edits,
7341 if auto_indent_on_paste {
7342 Some(AutoindentMode::Block {
7343 original_indent_columns,
7344 })
7345 } else {
7346 None
7347 },
7348 cx,
7349 );
7350 });
7351
7352 let selections = this.selections.all::<usize>(cx);
7353 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7354 } else {
7355 this.insert(&clipboard_text, cx);
7356 }
7357 });
7358 }
7359
7360 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7361 if let Some(item) = cx.read_from_clipboard() {
7362 let entries = item.entries();
7363
7364 match entries.first() {
7365 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7366 // of all the pasted entries.
7367 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7368 .do_paste(
7369 clipboard_string.text(),
7370 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7371 true,
7372 cx,
7373 ),
7374 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7375 }
7376 }
7377 }
7378
7379 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7380 if self.read_only(cx) {
7381 return;
7382 }
7383
7384 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7385 if let Some((selections, _)) =
7386 self.selection_history.transaction(transaction_id).cloned()
7387 {
7388 self.change_selections(None, cx, |s| {
7389 s.select_anchors(selections.to_vec());
7390 });
7391 }
7392 self.request_autoscroll(Autoscroll::fit(), cx);
7393 self.unmark_text(cx);
7394 self.refresh_inline_completion(true, false, cx);
7395 cx.emit(EditorEvent::Edited { transaction_id });
7396 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7397 }
7398 }
7399
7400 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7401 if self.read_only(cx) {
7402 return;
7403 }
7404
7405 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7406 if let Some((_, Some(selections))) =
7407 self.selection_history.transaction(transaction_id).cloned()
7408 {
7409 self.change_selections(None, cx, |s| {
7410 s.select_anchors(selections.to_vec());
7411 });
7412 }
7413 self.request_autoscroll(Autoscroll::fit(), cx);
7414 self.unmark_text(cx);
7415 self.refresh_inline_completion(true, false, cx);
7416 cx.emit(EditorEvent::Edited { transaction_id });
7417 }
7418 }
7419
7420 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7421 self.buffer
7422 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7423 }
7424
7425 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7426 self.buffer
7427 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7428 }
7429
7430 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7431 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7432 let line_mode = s.line_mode;
7433 s.move_with(|map, selection| {
7434 let cursor = if selection.is_empty() && !line_mode {
7435 movement::left(map, selection.start)
7436 } else {
7437 selection.start
7438 };
7439 selection.collapse_to(cursor, SelectionGoal::None);
7440 });
7441 })
7442 }
7443
7444 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7446 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7447 })
7448 }
7449
7450 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7451 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7452 let line_mode = s.line_mode;
7453 s.move_with(|map, selection| {
7454 let cursor = if selection.is_empty() && !line_mode {
7455 movement::right(map, selection.end)
7456 } else {
7457 selection.end
7458 };
7459 selection.collapse_to(cursor, SelectionGoal::None)
7460 });
7461 })
7462 }
7463
7464 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7465 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7466 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7467 })
7468 }
7469
7470 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7471 if self.take_rename(true, cx).is_some() {
7472 return;
7473 }
7474
7475 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7476 cx.propagate();
7477 return;
7478 }
7479
7480 let text_layout_details = &self.text_layout_details(cx);
7481 let selection_count = self.selections.count();
7482 let first_selection = self.selections.first_anchor();
7483
7484 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7485 let line_mode = s.line_mode;
7486 s.move_with(|map, selection| {
7487 if !selection.is_empty() && !line_mode {
7488 selection.goal = SelectionGoal::None;
7489 }
7490 let (cursor, goal) = movement::up(
7491 map,
7492 selection.start,
7493 selection.goal,
7494 false,
7495 text_layout_details,
7496 );
7497 selection.collapse_to(cursor, goal);
7498 });
7499 });
7500
7501 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7502 {
7503 cx.propagate();
7504 }
7505 }
7506
7507 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7508 if self.take_rename(true, cx).is_some() {
7509 return;
7510 }
7511
7512 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7513 cx.propagate();
7514 return;
7515 }
7516
7517 let text_layout_details = &self.text_layout_details(cx);
7518
7519 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7520 let line_mode = s.line_mode;
7521 s.move_with(|map, selection| {
7522 if !selection.is_empty() && !line_mode {
7523 selection.goal = SelectionGoal::None;
7524 }
7525 let (cursor, goal) = movement::up_by_rows(
7526 map,
7527 selection.start,
7528 action.lines,
7529 selection.goal,
7530 false,
7531 text_layout_details,
7532 );
7533 selection.collapse_to(cursor, goal);
7534 });
7535 })
7536 }
7537
7538 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7539 if self.take_rename(true, cx).is_some() {
7540 return;
7541 }
7542
7543 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7544 cx.propagate();
7545 return;
7546 }
7547
7548 let text_layout_details = &self.text_layout_details(cx);
7549
7550 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7551 let line_mode = s.line_mode;
7552 s.move_with(|map, selection| {
7553 if !selection.is_empty() && !line_mode {
7554 selection.goal = SelectionGoal::None;
7555 }
7556 let (cursor, goal) = movement::down_by_rows(
7557 map,
7558 selection.start,
7559 action.lines,
7560 selection.goal,
7561 false,
7562 text_layout_details,
7563 );
7564 selection.collapse_to(cursor, goal);
7565 });
7566 })
7567 }
7568
7569 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7570 let text_layout_details = &self.text_layout_details(cx);
7571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7572 s.move_heads_with(|map, head, goal| {
7573 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7574 })
7575 })
7576 }
7577
7578 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7579 let text_layout_details = &self.text_layout_details(cx);
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 s.move_heads_with(|map, head, goal| {
7582 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7583 })
7584 })
7585 }
7586
7587 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7588 let Some(row_count) = self.visible_row_count() else {
7589 return;
7590 };
7591
7592 let text_layout_details = &self.text_layout_details(cx);
7593
7594 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7595 s.move_heads_with(|map, head, goal| {
7596 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7597 })
7598 })
7599 }
7600
7601 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7602 if self.take_rename(true, cx).is_some() {
7603 return;
7604 }
7605
7606 if self
7607 .context_menu
7608 .write()
7609 .as_mut()
7610 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7611 .unwrap_or(false)
7612 {
7613 return;
7614 }
7615
7616 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7617 cx.propagate();
7618 return;
7619 }
7620
7621 let Some(row_count) = self.visible_row_count() else {
7622 return;
7623 };
7624
7625 let autoscroll = if action.center_cursor {
7626 Autoscroll::center()
7627 } else {
7628 Autoscroll::fit()
7629 };
7630
7631 let text_layout_details = &self.text_layout_details(cx);
7632
7633 self.change_selections(Some(autoscroll), cx, |s| {
7634 let line_mode = s.line_mode;
7635 s.move_with(|map, selection| {
7636 if !selection.is_empty() && !line_mode {
7637 selection.goal = SelectionGoal::None;
7638 }
7639 let (cursor, goal) = movement::up_by_rows(
7640 map,
7641 selection.end,
7642 row_count,
7643 selection.goal,
7644 false,
7645 text_layout_details,
7646 );
7647 selection.collapse_to(cursor, goal);
7648 });
7649 });
7650 }
7651
7652 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7653 let text_layout_details = &self.text_layout_details(cx);
7654 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7655 s.move_heads_with(|map, head, goal| {
7656 movement::up(map, head, goal, false, text_layout_details)
7657 })
7658 })
7659 }
7660
7661 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7662 self.take_rename(true, cx);
7663
7664 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7665 cx.propagate();
7666 return;
7667 }
7668
7669 let text_layout_details = &self.text_layout_details(cx);
7670 let selection_count = self.selections.count();
7671 let first_selection = self.selections.first_anchor();
7672
7673 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7674 let line_mode = s.line_mode;
7675 s.move_with(|map, selection| {
7676 if !selection.is_empty() && !line_mode {
7677 selection.goal = SelectionGoal::None;
7678 }
7679 let (cursor, goal) = movement::down(
7680 map,
7681 selection.end,
7682 selection.goal,
7683 false,
7684 text_layout_details,
7685 );
7686 selection.collapse_to(cursor, goal);
7687 });
7688 });
7689
7690 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7691 {
7692 cx.propagate();
7693 }
7694 }
7695
7696 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7697 let Some(row_count) = self.visible_row_count() else {
7698 return;
7699 };
7700
7701 let text_layout_details = &self.text_layout_details(cx);
7702
7703 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7704 s.move_heads_with(|map, head, goal| {
7705 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7706 })
7707 })
7708 }
7709
7710 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7711 if self.take_rename(true, cx).is_some() {
7712 return;
7713 }
7714
7715 if self
7716 .context_menu
7717 .write()
7718 .as_mut()
7719 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7720 .unwrap_or(false)
7721 {
7722 return;
7723 }
7724
7725 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7726 cx.propagate();
7727 return;
7728 }
7729
7730 let Some(row_count) = self.visible_row_count() else {
7731 return;
7732 };
7733
7734 let autoscroll = if action.center_cursor {
7735 Autoscroll::center()
7736 } else {
7737 Autoscroll::fit()
7738 };
7739
7740 let text_layout_details = &self.text_layout_details(cx);
7741 self.change_selections(Some(autoscroll), cx, |s| {
7742 let line_mode = s.line_mode;
7743 s.move_with(|map, selection| {
7744 if !selection.is_empty() && !line_mode {
7745 selection.goal = SelectionGoal::None;
7746 }
7747 let (cursor, goal) = movement::down_by_rows(
7748 map,
7749 selection.end,
7750 row_count,
7751 selection.goal,
7752 false,
7753 text_layout_details,
7754 );
7755 selection.collapse_to(cursor, goal);
7756 });
7757 });
7758 }
7759
7760 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7761 let text_layout_details = &self.text_layout_details(cx);
7762 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7763 s.move_heads_with(|map, head, goal| {
7764 movement::down(map, head, goal, false, text_layout_details)
7765 })
7766 });
7767 }
7768
7769 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7770 if let Some(context_menu) = self.context_menu.write().as_mut() {
7771 context_menu.select_first(self.completion_provider.as_deref(), cx);
7772 }
7773 }
7774
7775 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7776 if let Some(context_menu) = self.context_menu.write().as_mut() {
7777 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7778 }
7779 }
7780
7781 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7782 if let Some(context_menu) = self.context_menu.write().as_mut() {
7783 context_menu.select_next(self.completion_provider.as_deref(), cx);
7784 }
7785 }
7786
7787 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7788 if let Some(context_menu) = self.context_menu.write().as_mut() {
7789 context_menu.select_last(self.completion_provider.as_deref(), cx);
7790 }
7791 }
7792
7793 pub fn move_to_previous_word_start(
7794 &mut self,
7795 _: &MoveToPreviousWordStart,
7796 cx: &mut ViewContext<Self>,
7797 ) {
7798 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7799 s.move_cursors_with(|map, head, _| {
7800 (
7801 movement::previous_word_start(map, head),
7802 SelectionGoal::None,
7803 )
7804 });
7805 })
7806 }
7807
7808 pub fn move_to_previous_subword_start(
7809 &mut self,
7810 _: &MoveToPreviousSubwordStart,
7811 cx: &mut ViewContext<Self>,
7812 ) {
7813 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7814 s.move_cursors_with(|map, head, _| {
7815 (
7816 movement::previous_subword_start(map, head),
7817 SelectionGoal::None,
7818 )
7819 });
7820 })
7821 }
7822
7823 pub fn select_to_previous_word_start(
7824 &mut self,
7825 _: &SelectToPreviousWordStart,
7826 cx: &mut ViewContext<Self>,
7827 ) {
7828 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7829 s.move_heads_with(|map, head, _| {
7830 (
7831 movement::previous_word_start(map, head),
7832 SelectionGoal::None,
7833 )
7834 });
7835 })
7836 }
7837
7838 pub fn select_to_previous_subword_start(
7839 &mut self,
7840 _: &SelectToPreviousSubwordStart,
7841 cx: &mut ViewContext<Self>,
7842 ) {
7843 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7844 s.move_heads_with(|map, head, _| {
7845 (
7846 movement::previous_subword_start(map, head),
7847 SelectionGoal::None,
7848 )
7849 });
7850 })
7851 }
7852
7853 pub fn delete_to_previous_word_start(
7854 &mut self,
7855 action: &DeleteToPreviousWordStart,
7856 cx: &mut ViewContext<Self>,
7857 ) {
7858 self.transact(cx, |this, cx| {
7859 this.select_autoclose_pair(cx);
7860 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7861 let line_mode = s.line_mode;
7862 s.move_with(|map, selection| {
7863 if selection.is_empty() && !line_mode {
7864 let cursor = if action.ignore_newlines {
7865 movement::previous_word_start(map, selection.head())
7866 } else {
7867 movement::previous_word_start_or_newline(map, selection.head())
7868 };
7869 selection.set_head(cursor, SelectionGoal::None);
7870 }
7871 });
7872 });
7873 this.insert("", cx);
7874 });
7875 }
7876
7877 pub fn delete_to_previous_subword_start(
7878 &mut self,
7879 _: &DeleteToPreviousSubwordStart,
7880 cx: &mut ViewContext<Self>,
7881 ) {
7882 self.transact(cx, |this, cx| {
7883 this.select_autoclose_pair(cx);
7884 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7885 let line_mode = s.line_mode;
7886 s.move_with(|map, selection| {
7887 if selection.is_empty() && !line_mode {
7888 let cursor = movement::previous_subword_start(map, selection.head());
7889 selection.set_head(cursor, SelectionGoal::None);
7890 }
7891 });
7892 });
7893 this.insert("", cx);
7894 });
7895 }
7896
7897 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7899 s.move_cursors_with(|map, head, _| {
7900 (movement::next_word_end(map, head), SelectionGoal::None)
7901 });
7902 })
7903 }
7904
7905 pub fn move_to_next_subword_end(
7906 &mut self,
7907 _: &MoveToNextSubwordEnd,
7908 cx: &mut ViewContext<Self>,
7909 ) {
7910 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7911 s.move_cursors_with(|map, head, _| {
7912 (movement::next_subword_end(map, head), SelectionGoal::None)
7913 });
7914 })
7915 }
7916
7917 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7918 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7919 s.move_heads_with(|map, head, _| {
7920 (movement::next_word_end(map, head), SelectionGoal::None)
7921 });
7922 })
7923 }
7924
7925 pub fn select_to_next_subword_end(
7926 &mut self,
7927 _: &SelectToNextSubwordEnd,
7928 cx: &mut ViewContext<Self>,
7929 ) {
7930 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7931 s.move_heads_with(|map, head, _| {
7932 (movement::next_subword_end(map, head), SelectionGoal::None)
7933 });
7934 })
7935 }
7936
7937 pub fn delete_to_next_word_end(
7938 &mut self,
7939 action: &DeleteToNextWordEnd,
7940 cx: &mut ViewContext<Self>,
7941 ) {
7942 self.transact(cx, |this, cx| {
7943 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 let line_mode = s.line_mode;
7945 s.move_with(|map, selection| {
7946 if selection.is_empty() && !line_mode {
7947 let cursor = if action.ignore_newlines {
7948 movement::next_word_end(map, selection.head())
7949 } else {
7950 movement::next_word_end_or_newline(map, selection.head())
7951 };
7952 selection.set_head(cursor, SelectionGoal::None);
7953 }
7954 });
7955 });
7956 this.insert("", cx);
7957 });
7958 }
7959
7960 pub fn delete_to_next_subword_end(
7961 &mut self,
7962 _: &DeleteToNextSubwordEnd,
7963 cx: &mut ViewContext<Self>,
7964 ) {
7965 self.transact(cx, |this, cx| {
7966 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7967 s.move_with(|map, selection| {
7968 if selection.is_empty() {
7969 let cursor = movement::next_subword_end(map, selection.head());
7970 selection.set_head(cursor, SelectionGoal::None);
7971 }
7972 });
7973 });
7974 this.insert("", cx);
7975 });
7976 }
7977
7978 pub fn move_to_beginning_of_line(
7979 &mut self,
7980 action: &MoveToBeginningOfLine,
7981 cx: &mut ViewContext<Self>,
7982 ) {
7983 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7984 s.move_cursors_with(|map, head, _| {
7985 (
7986 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7987 SelectionGoal::None,
7988 )
7989 });
7990 })
7991 }
7992
7993 pub fn select_to_beginning_of_line(
7994 &mut self,
7995 action: &SelectToBeginningOfLine,
7996 cx: &mut ViewContext<Self>,
7997 ) {
7998 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7999 s.move_heads_with(|map, head, _| {
8000 (
8001 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8002 SelectionGoal::None,
8003 )
8004 });
8005 });
8006 }
8007
8008 pub fn delete_to_beginning_of_line(
8009 &mut self,
8010 _: &DeleteToBeginningOfLine,
8011 cx: &mut ViewContext<Self>,
8012 ) {
8013 self.transact(cx, |this, cx| {
8014 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8015 s.move_with(|_, selection| {
8016 selection.reversed = true;
8017 });
8018 });
8019
8020 this.select_to_beginning_of_line(
8021 &SelectToBeginningOfLine {
8022 stop_at_soft_wraps: false,
8023 },
8024 cx,
8025 );
8026 this.backspace(&Backspace, cx);
8027 });
8028 }
8029
8030 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8031 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8032 s.move_cursors_with(|map, head, _| {
8033 (
8034 movement::line_end(map, head, action.stop_at_soft_wraps),
8035 SelectionGoal::None,
8036 )
8037 });
8038 })
8039 }
8040
8041 pub fn select_to_end_of_line(
8042 &mut self,
8043 action: &SelectToEndOfLine,
8044 cx: &mut ViewContext<Self>,
8045 ) {
8046 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8047 s.move_heads_with(|map, head, _| {
8048 (
8049 movement::line_end(map, head, action.stop_at_soft_wraps),
8050 SelectionGoal::None,
8051 )
8052 });
8053 })
8054 }
8055
8056 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8057 self.transact(cx, |this, cx| {
8058 this.select_to_end_of_line(
8059 &SelectToEndOfLine {
8060 stop_at_soft_wraps: false,
8061 },
8062 cx,
8063 );
8064 this.delete(&Delete, cx);
8065 });
8066 }
8067
8068 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8069 self.transact(cx, |this, cx| {
8070 this.select_to_end_of_line(
8071 &SelectToEndOfLine {
8072 stop_at_soft_wraps: false,
8073 },
8074 cx,
8075 );
8076 this.cut(&Cut, cx);
8077 });
8078 }
8079
8080 pub fn move_to_start_of_paragraph(
8081 &mut self,
8082 _: &MoveToStartOfParagraph,
8083 cx: &mut ViewContext<Self>,
8084 ) {
8085 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8086 cx.propagate();
8087 return;
8088 }
8089
8090 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8091 s.move_with(|map, selection| {
8092 selection.collapse_to(
8093 movement::start_of_paragraph(map, selection.head(), 1),
8094 SelectionGoal::None,
8095 )
8096 });
8097 })
8098 }
8099
8100 pub fn move_to_end_of_paragraph(
8101 &mut self,
8102 _: &MoveToEndOfParagraph,
8103 cx: &mut ViewContext<Self>,
8104 ) {
8105 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8106 cx.propagate();
8107 return;
8108 }
8109
8110 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8111 s.move_with(|map, selection| {
8112 selection.collapse_to(
8113 movement::end_of_paragraph(map, selection.head(), 1),
8114 SelectionGoal::None,
8115 )
8116 });
8117 })
8118 }
8119
8120 pub fn select_to_start_of_paragraph(
8121 &mut self,
8122 _: &SelectToStartOfParagraph,
8123 cx: &mut ViewContext<Self>,
8124 ) {
8125 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8126 cx.propagate();
8127 return;
8128 }
8129
8130 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8131 s.move_heads_with(|map, head, _| {
8132 (
8133 movement::start_of_paragraph(map, head, 1),
8134 SelectionGoal::None,
8135 )
8136 });
8137 })
8138 }
8139
8140 pub fn select_to_end_of_paragraph(
8141 &mut self,
8142 _: &SelectToEndOfParagraph,
8143 cx: &mut ViewContext<Self>,
8144 ) {
8145 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8146 cx.propagate();
8147 return;
8148 }
8149
8150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8151 s.move_heads_with(|map, head, _| {
8152 (
8153 movement::end_of_paragraph(map, head, 1),
8154 SelectionGoal::None,
8155 )
8156 });
8157 })
8158 }
8159
8160 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8161 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8162 cx.propagate();
8163 return;
8164 }
8165
8166 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8167 s.select_ranges(vec![0..0]);
8168 });
8169 }
8170
8171 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8172 let mut selection = self.selections.last::<Point>(cx);
8173 selection.set_head(Point::zero(), SelectionGoal::None);
8174
8175 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8176 s.select(vec![selection]);
8177 });
8178 }
8179
8180 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8181 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8182 cx.propagate();
8183 return;
8184 }
8185
8186 let cursor = self.buffer.read(cx).read(cx).len();
8187 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8188 s.select_ranges(vec![cursor..cursor])
8189 });
8190 }
8191
8192 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8193 self.nav_history = nav_history;
8194 }
8195
8196 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8197 self.nav_history.as_ref()
8198 }
8199
8200 fn push_to_nav_history(
8201 &mut self,
8202 cursor_anchor: Anchor,
8203 new_position: Option<Point>,
8204 cx: &mut ViewContext<Self>,
8205 ) {
8206 if let Some(nav_history) = self.nav_history.as_mut() {
8207 let buffer = self.buffer.read(cx).read(cx);
8208 let cursor_position = cursor_anchor.to_point(&buffer);
8209 let scroll_state = self.scroll_manager.anchor();
8210 let scroll_top_row = scroll_state.top_row(&buffer);
8211 drop(buffer);
8212
8213 if let Some(new_position) = new_position {
8214 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8215 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8216 return;
8217 }
8218 }
8219
8220 nav_history.push(
8221 Some(NavigationData {
8222 cursor_anchor,
8223 cursor_position,
8224 scroll_anchor: scroll_state,
8225 scroll_top_row,
8226 }),
8227 cx,
8228 );
8229 }
8230 }
8231
8232 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8233 let buffer = self.buffer.read(cx).snapshot(cx);
8234 let mut selection = self.selections.first::<usize>(cx);
8235 selection.set_head(buffer.len(), SelectionGoal::None);
8236 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8237 s.select(vec![selection]);
8238 });
8239 }
8240
8241 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8242 let end = self.buffer.read(cx).read(cx).len();
8243 self.change_selections(None, cx, |s| {
8244 s.select_ranges(vec![0..end]);
8245 });
8246 }
8247
8248 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8249 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8250 let mut selections = self.selections.all::<Point>(cx);
8251 let max_point = display_map.buffer_snapshot.max_point();
8252 for selection in &mut selections {
8253 let rows = selection.spanned_rows(true, &display_map);
8254 selection.start = Point::new(rows.start.0, 0);
8255 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8256 selection.reversed = false;
8257 }
8258 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8259 s.select(selections);
8260 });
8261 }
8262
8263 pub fn split_selection_into_lines(
8264 &mut self,
8265 _: &SplitSelectionIntoLines,
8266 cx: &mut ViewContext<Self>,
8267 ) {
8268 let mut to_unfold = Vec::new();
8269 let mut new_selection_ranges = Vec::new();
8270 {
8271 let selections = self.selections.all::<Point>(cx);
8272 let buffer = self.buffer.read(cx).read(cx);
8273 for selection in selections {
8274 for row in selection.start.row..selection.end.row {
8275 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8276 new_selection_ranges.push(cursor..cursor);
8277 }
8278 new_selection_ranges.push(selection.end..selection.end);
8279 to_unfold.push(selection.start..selection.end);
8280 }
8281 }
8282 self.unfold_ranges(&to_unfold, true, true, cx);
8283 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8284 s.select_ranges(new_selection_ranges);
8285 });
8286 }
8287
8288 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8289 self.add_selection(true, cx);
8290 }
8291
8292 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8293 self.add_selection(false, cx);
8294 }
8295
8296 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8298 let mut selections = self.selections.all::<Point>(cx);
8299 let text_layout_details = self.text_layout_details(cx);
8300 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8301 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8302 let range = oldest_selection.display_range(&display_map).sorted();
8303
8304 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8305 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8306 let positions = start_x.min(end_x)..start_x.max(end_x);
8307
8308 selections.clear();
8309 let mut stack = Vec::new();
8310 for row in range.start.row().0..=range.end.row().0 {
8311 if let Some(selection) = self.selections.build_columnar_selection(
8312 &display_map,
8313 DisplayRow(row),
8314 &positions,
8315 oldest_selection.reversed,
8316 &text_layout_details,
8317 ) {
8318 stack.push(selection.id);
8319 selections.push(selection);
8320 }
8321 }
8322
8323 if above {
8324 stack.reverse();
8325 }
8326
8327 AddSelectionsState { above, stack }
8328 });
8329
8330 let last_added_selection = *state.stack.last().unwrap();
8331 let mut new_selections = Vec::new();
8332 if above == state.above {
8333 let end_row = if above {
8334 DisplayRow(0)
8335 } else {
8336 display_map.max_point().row()
8337 };
8338
8339 'outer: for selection in selections {
8340 if selection.id == last_added_selection {
8341 let range = selection.display_range(&display_map).sorted();
8342 debug_assert_eq!(range.start.row(), range.end.row());
8343 let mut row = range.start.row();
8344 let positions =
8345 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8346 px(start)..px(end)
8347 } else {
8348 let start_x =
8349 display_map.x_for_display_point(range.start, &text_layout_details);
8350 let end_x =
8351 display_map.x_for_display_point(range.end, &text_layout_details);
8352 start_x.min(end_x)..start_x.max(end_x)
8353 };
8354
8355 while row != end_row {
8356 if above {
8357 row.0 -= 1;
8358 } else {
8359 row.0 += 1;
8360 }
8361
8362 if let Some(new_selection) = self.selections.build_columnar_selection(
8363 &display_map,
8364 row,
8365 &positions,
8366 selection.reversed,
8367 &text_layout_details,
8368 ) {
8369 state.stack.push(new_selection.id);
8370 if above {
8371 new_selections.push(new_selection);
8372 new_selections.push(selection);
8373 } else {
8374 new_selections.push(selection);
8375 new_selections.push(new_selection);
8376 }
8377
8378 continue 'outer;
8379 }
8380 }
8381 }
8382
8383 new_selections.push(selection);
8384 }
8385 } else {
8386 new_selections = selections;
8387 new_selections.retain(|s| s.id != last_added_selection);
8388 state.stack.pop();
8389 }
8390
8391 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8392 s.select(new_selections);
8393 });
8394 if state.stack.len() > 1 {
8395 self.add_selections_state = Some(state);
8396 }
8397 }
8398
8399 pub fn select_next_match_internal(
8400 &mut self,
8401 display_map: &DisplaySnapshot,
8402 replace_newest: bool,
8403 autoscroll: Option<Autoscroll>,
8404 cx: &mut ViewContext<Self>,
8405 ) -> Result<()> {
8406 fn select_next_match_ranges(
8407 this: &mut Editor,
8408 range: Range<usize>,
8409 replace_newest: bool,
8410 auto_scroll: Option<Autoscroll>,
8411 cx: &mut ViewContext<Editor>,
8412 ) {
8413 this.unfold_ranges(&[range.clone()], false, true, cx);
8414 this.change_selections(auto_scroll, cx, |s| {
8415 if replace_newest {
8416 s.delete(s.newest_anchor().id);
8417 }
8418 s.insert_range(range.clone());
8419 });
8420 }
8421
8422 let buffer = &display_map.buffer_snapshot;
8423 let mut selections = self.selections.all::<usize>(cx);
8424 if let Some(mut select_next_state) = self.select_next_state.take() {
8425 let query = &select_next_state.query;
8426 if !select_next_state.done {
8427 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8428 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8429 let mut next_selected_range = None;
8430
8431 let bytes_after_last_selection =
8432 buffer.bytes_in_range(last_selection.end..buffer.len());
8433 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8434 let query_matches = query
8435 .stream_find_iter(bytes_after_last_selection)
8436 .map(|result| (last_selection.end, result))
8437 .chain(
8438 query
8439 .stream_find_iter(bytes_before_first_selection)
8440 .map(|result| (0, result)),
8441 );
8442
8443 for (start_offset, query_match) in query_matches {
8444 let query_match = query_match.unwrap(); // can only fail due to I/O
8445 let offset_range =
8446 start_offset + query_match.start()..start_offset + query_match.end();
8447 let display_range = offset_range.start.to_display_point(display_map)
8448 ..offset_range.end.to_display_point(display_map);
8449
8450 if !select_next_state.wordwise
8451 || (!movement::is_inside_word(display_map, display_range.start)
8452 && !movement::is_inside_word(display_map, display_range.end))
8453 {
8454 // TODO: This is n^2, because we might check all the selections
8455 if !selections
8456 .iter()
8457 .any(|selection| selection.range().overlaps(&offset_range))
8458 {
8459 next_selected_range = Some(offset_range);
8460 break;
8461 }
8462 }
8463 }
8464
8465 if let Some(next_selected_range) = next_selected_range {
8466 select_next_match_ranges(
8467 self,
8468 next_selected_range,
8469 replace_newest,
8470 autoscroll,
8471 cx,
8472 );
8473 } else {
8474 select_next_state.done = true;
8475 }
8476 }
8477
8478 self.select_next_state = Some(select_next_state);
8479 } else {
8480 let mut only_carets = true;
8481 let mut same_text_selected = true;
8482 let mut selected_text = None;
8483
8484 let mut selections_iter = selections.iter().peekable();
8485 while let Some(selection) = selections_iter.next() {
8486 if selection.start != selection.end {
8487 only_carets = false;
8488 }
8489
8490 if same_text_selected {
8491 if selected_text.is_none() {
8492 selected_text =
8493 Some(buffer.text_for_range(selection.range()).collect::<String>());
8494 }
8495
8496 if let Some(next_selection) = selections_iter.peek() {
8497 if next_selection.range().len() == selection.range().len() {
8498 let next_selected_text = buffer
8499 .text_for_range(next_selection.range())
8500 .collect::<String>();
8501 if Some(next_selected_text) != selected_text {
8502 same_text_selected = false;
8503 selected_text = None;
8504 }
8505 } else {
8506 same_text_selected = false;
8507 selected_text = None;
8508 }
8509 }
8510 }
8511 }
8512
8513 if only_carets {
8514 for selection in &mut selections {
8515 let word_range = movement::surrounding_word(
8516 display_map,
8517 selection.start.to_display_point(display_map),
8518 );
8519 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8520 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8521 selection.goal = SelectionGoal::None;
8522 selection.reversed = false;
8523 select_next_match_ranges(
8524 self,
8525 selection.start..selection.end,
8526 replace_newest,
8527 autoscroll,
8528 cx,
8529 );
8530 }
8531
8532 if selections.len() == 1 {
8533 let selection = selections
8534 .last()
8535 .expect("ensured that there's only one selection");
8536 let query = buffer
8537 .text_for_range(selection.start..selection.end)
8538 .collect::<String>();
8539 let is_empty = query.is_empty();
8540 let select_state = SelectNextState {
8541 query: AhoCorasick::new(&[query])?,
8542 wordwise: true,
8543 done: is_empty,
8544 };
8545 self.select_next_state = Some(select_state);
8546 } else {
8547 self.select_next_state = None;
8548 }
8549 } else if let Some(selected_text) = selected_text {
8550 self.select_next_state = Some(SelectNextState {
8551 query: AhoCorasick::new(&[selected_text])?,
8552 wordwise: false,
8553 done: false,
8554 });
8555 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8556 }
8557 }
8558 Ok(())
8559 }
8560
8561 pub fn select_all_matches(
8562 &mut self,
8563 _action: &SelectAllMatches,
8564 cx: &mut ViewContext<Self>,
8565 ) -> Result<()> {
8566 self.push_to_selection_history();
8567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8568
8569 self.select_next_match_internal(&display_map, false, None, cx)?;
8570 let Some(select_next_state) = self.select_next_state.as_mut() else {
8571 return Ok(());
8572 };
8573 if select_next_state.done {
8574 return Ok(());
8575 }
8576
8577 let mut new_selections = self.selections.all::<usize>(cx);
8578
8579 let buffer = &display_map.buffer_snapshot;
8580 let query_matches = select_next_state
8581 .query
8582 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8583
8584 for query_match in query_matches {
8585 let query_match = query_match.unwrap(); // can only fail due to I/O
8586 let offset_range = query_match.start()..query_match.end();
8587 let display_range = offset_range.start.to_display_point(&display_map)
8588 ..offset_range.end.to_display_point(&display_map);
8589
8590 if !select_next_state.wordwise
8591 || (!movement::is_inside_word(&display_map, display_range.start)
8592 && !movement::is_inside_word(&display_map, display_range.end))
8593 {
8594 self.selections.change_with(cx, |selections| {
8595 new_selections.push(Selection {
8596 id: selections.new_selection_id(),
8597 start: offset_range.start,
8598 end: offset_range.end,
8599 reversed: false,
8600 goal: SelectionGoal::None,
8601 });
8602 });
8603 }
8604 }
8605
8606 new_selections.sort_by_key(|selection| selection.start);
8607 let mut ix = 0;
8608 while ix + 1 < new_selections.len() {
8609 let current_selection = &new_selections[ix];
8610 let next_selection = &new_selections[ix + 1];
8611 if current_selection.range().overlaps(&next_selection.range()) {
8612 if current_selection.id < next_selection.id {
8613 new_selections.remove(ix + 1);
8614 } else {
8615 new_selections.remove(ix);
8616 }
8617 } else {
8618 ix += 1;
8619 }
8620 }
8621
8622 select_next_state.done = true;
8623 self.unfold_ranges(
8624 &new_selections
8625 .iter()
8626 .map(|selection| selection.range())
8627 .collect::<Vec<_>>(),
8628 false,
8629 false,
8630 cx,
8631 );
8632 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8633 selections.select(new_selections)
8634 });
8635
8636 Ok(())
8637 }
8638
8639 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8640 self.push_to_selection_history();
8641 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8642 self.select_next_match_internal(
8643 &display_map,
8644 action.replace_newest,
8645 Some(Autoscroll::newest()),
8646 cx,
8647 )?;
8648 Ok(())
8649 }
8650
8651 pub fn select_previous(
8652 &mut self,
8653 action: &SelectPrevious,
8654 cx: &mut ViewContext<Self>,
8655 ) -> Result<()> {
8656 self.push_to_selection_history();
8657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8658 let buffer = &display_map.buffer_snapshot;
8659 let mut selections = self.selections.all::<usize>(cx);
8660 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8661 let query = &select_prev_state.query;
8662 if !select_prev_state.done {
8663 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8664 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8665 let mut next_selected_range = None;
8666 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8667 let bytes_before_last_selection =
8668 buffer.reversed_bytes_in_range(0..last_selection.start);
8669 let bytes_after_first_selection =
8670 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8671 let query_matches = query
8672 .stream_find_iter(bytes_before_last_selection)
8673 .map(|result| (last_selection.start, result))
8674 .chain(
8675 query
8676 .stream_find_iter(bytes_after_first_selection)
8677 .map(|result| (buffer.len(), result)),
8678 );
8679 for (end_offset, query_match) in query_matches {
8680 let query_match = query_match.unwrap(); // can only fail due to I/O
8681 let offset_range =
8682 end_offset - query_match.end()..end_offset - query_match.start();
8683 let display_range = offset_range.start.to_display_point(&display_map)
8684 ..offset_range.end.to_display_point(&display_map);
8685
8686 if !select_prev_state.wordwise
8687 || (!movement::is_inside_word(&display_map, display_range.start)
8688 && !movement::is_inside_word(&display_map, display_range.end))
8689 {
8690 next_selected_range = Some(offset_range);
8691 break;
8692 }
8693 }
8694
8695 if let Some(next_selected_range) = next_selected_range {
8696 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8697 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8698 if action.replace_newest {
8699 s.delete(s.newest_anchor().id);
8700 }
8701 s.insert_range(next_selected_range);
8702 });
8703 } else {
8704 select_prev_state.done = true;
8705 }
8706 }
8707
8708 self.select_prev_state = Some(select_prev_state);
8709 } else {
8710 let mut only_carets = true;
8711 let mut same_text_selected = true;
8712 let mut selected_text = None;
8713
8714 let mut selections_iter = selections.iter().peekable();
8715 while let Some(selection) = selections_iter.next() {
8716 if selection.start != selection.end {
8717 only_carets = false;
8718 }
8719
8720 if same_text_selected {
8721 if selected_text.is_none() {
8722 selected_text =
8723 Some(buffer.text_for_range(selection.range()).collect::<String>());
8724 }
8725
8726 if let Some(next_selection) = selections_iter.peek() {
8727 if next_selection.range().len() == selection.range().len() {
8728 let next_selected_text = buffer
8729 .text_for_range(next_selection.range())
8730 .collect::<String>();
8731 if Some(next_selected_text) != selected_text {
8732 same_text_selected = false;
8733 selected_text = None;
8734 }
8735 } else {
8736 same_text_selected = false;
8737 selected_text = None;
8738 }
8739 }
8740 }
8741 }
8742
8743 if only_carets {
8744 for selection in &mut selections {
8745 let word_range = movement::surrounding_word(
8746 &display_map,
8747 selection.start.to_display_point(&display_map),
8748 );
8749 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8750 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8751 selection.goal = SelectionGoal::None;
8752 selection.reversed = false;
8753 }
8754 if selections.len() == 1 {
8755 let selection = selections
8756 .last()
8757 .expect("ensured that there's only one selection");
8758 let query = buffer
8759 .text_for_range(selection.start..selection.end)
8760 .collect::<String>();
8761 let is_empty = query.is_empty();
8762 let select_state = SelectNextState {
8763 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8764 wordwise: true,
8765 done: is_empty,
8766 };
8767 self.select_prev_state = Some(select_state);
8768 } else {
8769 self.select_prev_state = None;
8770 }
8771
8772 self.unfold_ranges(
8773 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8774 false,
8775 true,
8776 cx,
8777 );
8778 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8779 s.select(selections);
8780 });
8781 } else if let Some(selected_text) = selected_text {
8782 self.select_prev_state = Some(SelectNextState {
8783 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8784 wordwise: false,
8785 done: false,
8786 });
8787 self.select_previous(action, cx)?;
8788 }
8789 }
8790 Ok(())
8791 }
8792
8793 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8794 if self.read_only(cx) {
8795 return;
8796 }
8797 let text_layout_details = &self.text_layout_details(cx);
8798 self.transact(cx, |this, cx| {
8799 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8800 let mut edits = Vec::new();
8801 let mut selection_edit_ranges = Vec::new();
8802 let mut last_toggled_row = None;
8803 let snapshot = this.buffer.read(cx).read(cx);
8804 let empty_str: Arc<str> = Arc::default();
8805 let mut suffixes_inserted = Vec::new();
8806 let ignore_indent = action.ignore_indent;
8807
8808 fn comment_prefix_range(
8809 snapshot: &MultiBufferSnapshot,
8810 row: MultiBufferRow,
8811 comment_prefix: &str,
8812 comment_prefix_whitespace: &str,
8813 ignore_indent: bool,
8814 ) -> Range<Point> {
8815 let indent_size = if ignore_indent {
8816 0
8817 } else {
8818 snapshot.indent_size_for_line(row).len
8819 };
8820
8821 let start = Point::new(row.0, indent_size);
8822
8823 let mut line_bytes = snapshot
8824 .bytes_in_range(start..snapshot.max_point())
8825 .flatten()
8826 .copied();
8827
8828 // If this line currently begins with the line comment prefix, then record
8829 // the range containing the prefix.
8830 if line_bytes
8831 .by_ref()
8832 .take(comment_prefix.len())
8833 .eq(comment_prefix.bytes())
8834 {
8835 // Include any whitespace that matches the comment prefix.
8836 let matching_whitespace_len = line_bytes
8837 .zip(comment_prefix_whitespace.bytes())
8838 .take_while(|(a, b)| a == b)
8839 .count() as u32;
8840 let end = Point::new(
8841 start.row,
8842 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8843 );
8844 start..end
8845 } else {
8846 start..start
8847 }
8848 }
8849
8850 fn comment_suffix_range(
8851 snapshot: &MultiBufferSnapshot,
8852 row: MultiBufferRow,
8853 comment_suffix: &str,
8854 comment_suffix_has_leading_space: bool,
8855 ) -> Range<Point> {
8856 let end = Point::new(row.0, snapshot.line_len(row));
8857 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8858
8859 let mut line_end_bytes = snapshot
8860 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8861 .flatten()
8862 .copied();
8863
8864 let leading_space_len = if suffix_start_column > 0
8865 && line_end_bytes.next() == Some(b' ')
8866 && comment_suffix_has_leading_space
8867 {
8868 1
8869 } else {
8870 0
8871 };
8872
8873 // If this line currently begins with the line comment prefix, then record
8874 // the range containing the prefix.
8875 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8876 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8877 start..end
8878 } else {
8879 end..end
8880 }
8881 }
8882
8883 // TODO: Handle selections that cross excerpts
8884 for selection in &mut selections {
8885 let start_column = snapshot
8886 .indent_size_for_line(MultiBufferRow(selection.start.row))
8887 .len;
8888 let language = if let Some(language) =
8889 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8890 {
8891 language
8892 } else {
8893 continue;
8894 };
8895
8896 selection_edit_ranges.clear();
8897
8898 // If multiple selections contain a given row, avoid processing that
8899 // row more than once.
8900 let mut start_row = MultiBufferRow(selection.start.row);
8901 if last_toggled_row == Some(start_row) {
8902 start_row = start_row.next_row();
8903 }
8904 let end_row =
8905 if selection.end.row > selection.start.row && selection.end.column == 0 {
8906 MultiBufferRow(selection.end.row - 1)
8907 } else {
8908 MultiBufferRow(selection.end.row)
8909 };
8910 last_toggled_row = Some(end_row);
8911
8912 if start_row > end_row {
8913 continue;
8914 }
8915
8916 // If the language has line comments, toggle those.
8917 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8918
8919 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8920 if ignore_indent {
8921 full_comment_prefixes = full_comment_prefixes
8922 .into_iter()
8923 .map(|s| Arc::from(s.trim_end()))
8924 .collect();
8925 }
8926
8927 if !full_comment_prefixes.is_empty() {
8928 let first_prefix = full_comment_prefixes
8929 .first()
8930 .expect("prefixes is non-empty");
8931 let prefix_trimmed_lengths = full_comment_prefixes
8932 .iter()
8933 .map(|p| p.trim_end_matches(' ').len())
8934 .collect::<SmallVec<[usize; 4]>>();
8935
8936 let mut all_selection_lines_are_comments = true;
8937
8938 for row in start_row.0..=end_row.0 {
8939 let row = MultiBufferRow(row);
8940 if start_row < end_row && snapshot.is_line_blank(row) {
8941 continue;
8942 }
8943
8944 let prefix_range = full_comment_prefixes
8945 .iter()
8946 .zip(prefix_trimmed_lengths.iter().copied())
8947 .map(|(prefix, trimmed_prefix_len)| {
8948 comment_prefix_range(
8949 snapshot.deref(),
8950 row,
8951 &prefix[..trimmed_prefix_len],
8952 &prefix[trimmed_prefix_len..],
8953 ignore_indent,
8954 )
8955 })
8956 .max_by_key(|range| range.end.column - range.start.column)
8957 .expect("prefixes is non-empty");
8958
8959 if prefix_range.is_empty() {
8960 all_selection_lines_are_comments = false;
8961 }
8962
8963 selection_edit_ranges.push(prefix_range);
8964 }
8965
8966 if all_selection_lines_are_comments {
8967 edits.extend(
8968 selection_edit_ranges
8969 .iter()
8970 .cloned()
8971 .map(|range| (range, empty_str.clone())),
8972 );
8973 } else {
8974 let min_column = selection_edit_ranges
8975 .iter()
8976 .map(|range| range.start.column)
8977 .min()
8978 .unwrap_or(0);
8979 edits.extend(selection_edit_ranges.iter().map(|range| {
8980 let position = Point::new(range.start.row, min_column);
8981 (position..position, first_prefix.clone())
8982 }));
8983 }
8984 } else if let Some((full_comment_prefix, comment_suffix)) =
8985 language.block_comment_delimiters()
8986 {
8987 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8988 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8989 let prefix_range = comment_prefix_range(
8990 snapshot.deref(),
8991 start_row,
8992 comment_prefix,
8993 comment_prefix_whitespace,
8994 ignore_indent,
8995 );
8996 let suffix_range = comment_suffix_range(
8997 snapshot.deref(),
8998 end_row,
8999 comment_suffix.trim_start_matches(' '),
9000 comment_suffix.starts_with(' '),
9001 );
9002
9003 if prefix_range.is_empty() || suffix_range.is_empty() {
9004 edits.push((
9005 prefix_range.start..prefix_range.start,
9006 full_comment_prefix.clone(),
9007 ));
9008 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9009 suffixes_inserted.push((end_row, comment_suffix.len()));
9010 } else {
9011 edits.push((prefix_range, empty_str.clone()));
9012 edits.push((suffix_range, empty_str.clone()));
9013 }
9014 } else {
9015 continue;
9016 }
9017 }
9018
9019 drop(snapshot);
9020 this.buffer.update(cx, |buffer, cx| {
9021 buffer.edit(edits, None, cx);
9022 });
9023
9024 // Adjust selections so that they end before any comment suffixes that
9025 // were inserted.
9026 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9027 let mut selections = this.selections.all::<Point>(cx);
9028 let snapshot = this.buffer.read(cx).read(cx);
9029 for selection in &mut selections {
9030 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9031 match row.cmp(&MultiBufferRow(selection.end.row)) {
9032 Ordering::Less => {
9033 suffixes_inserted.next();
9034 continue;
9035 }
9036 Ordering::Greater => break,
9037 Ordering::Equal => {
9038 if selection.end.column == snapshot.line_len(row) {
9039 if selection.is_empty() {
9040 selection.start.column -= suffix_len as u32;
9041 }
9042 selection.end.column -= suffix_len as u32;
9043 }
9044 break;
9045 }
9046 }
9047 }
9048 }
9049
9050 drop(snapshot);
9051 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9052
9053 let selections = this.selections.all::<Point>(cx);
9054 let selections_on_single_row = selections.windows(2).all(|selections| {
9055 selections[0].start.row == selections[1].start.row
9056 && selections[0].end.row == selections[1].end.row
9057 && selections[0].start.row == selections[0].end.row
9058 });
9059 let selections_selecting = selections
9060 .iter()
9061 .any(|selection| selection.start != selection.end);
9062 let advance_downwards = action.advance_downwards
9063 && selections_on_single_row
9064 && !selections_selecting
9065 && !matches!(this.mode, EditorMode::SingleLine { .. });
9066
9067 if advance_downwards {
9068 let snapshot = this.buffer.read(cx).snapshot(cx);
9069
9070 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9071 s.move_cursors_with(|display_snapshot, display_point, _| {
9072 let mut point = display_point.to_point(display_snapshot);
9073 point.row += 1;
9074 point = snapshot.clip_point(point, Bias::Left);
9075 let display_point = point.to_display_point(display_snapshot);
9076 let goal = SelectionGoal::HorizontalPosition(
9077 display_snapshot
9078 .x_for_display_point(display_point, text_layout_details)
9079 .into(),
9080 );
9081 (display_point, goal)
9082 })
9083 });
9084 }
9085 });
9086 }
9087
9088 pub fn select_enclosing_symbol(
9089 &mut self,
9090 _: &SelectEnclosingSymbol,
9091 cx: &mut ViewContext<Self>,
9092 ) {
9093 let buffer = self.buffer.read(cx).snapshot(cx);
9094 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9095
9096 fn update_selection(
9097 selection: &Selection<usize>,
9098 buffer_snap: &MultiBufferSnapshot,
9099 ) -> Option<Selection<usize>> {
9100 let cursor = selection.head();
9101 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9102 for symbol in symbols.iter().rev() {
9103 let start = symbol.range.start.to_offset(buffer_snap);
9104 let end = symbol.range.end.to_offset(buffer_snap);
9105 let new_range = start..end;
9106 if start < selection.start || end > selection.end {
9107 return Some(Selection {
9108 id: selection.id,
9109 start: new_range.start,
9110 end: new_range.end,
9111 goal: SelectionGoal::None,
9112 reversed: selection.reversed,
9113 });
9114 }
9115 }
9116 None
9117 }
9118
9119 let mut selected_larger_symbol = false;
9120 let new_selections = old_selections
9121 .iter()
9122 .map(|selection| match update_selection(selection, &buffer) {
9123 Some(new_selection) => {
9124 if new_selection.range() != selection.range() {
9125 selected_larger_symbol = true;
9126 }
9127 new_selection
9128 }
9129 None => selection.clone(),
9130 })
9131 .collect::<Vec<_>>();
9132
9133 if selected_larger_symbol {
9134 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9135 s.select(new_selections);
9136 });
9137 }
9138 }
9139
9140 pub fn select_larger_syntax_node(
9141 &mut self,
9142 _: &SelectLargerSyntaxNode,
9143 cx: &mut ViewContext<Self>,
9144 ) {
9145 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9146 let buffer = self.buffer.read(cx).snapshot(cx);
9147 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9148
9149 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9150 let mut selected_larger_node = false;
9151 let new_selections = old_selections
9152 .iter()
9153 .map(|selection| {
9154 let old_range = selection.start..selection.end;
9155 let mut new_range = old_range.clone();
9156 while let Some(containing_range) =
9157 buffer.range_for_syntax_ancestor(new_range.clone())
9158 {
9159 new_range = containing_range;
9160 if !display_map.intersects_fold(new_range.start)
9161 && !display_map.intersects_fold(new_range.end)
9162 {
9163 break;
9164 }
9165 }
9166
9167 selected_larger_node |= new_range != old_range;
9168 Selection {
9169 id: selection.id,
9170 start: new_range.start,
9171 end: new_range.end,
9172 goal: SelectionGoal::None,
9173 reversed: selection.reversed,
9174 }
9175 })
9176 .collect::<Vec<_>>();
9177
9178 if selected_larger_node {
9179 stack.push(old_selections);
9180 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9181 s.select(new_selections);
9182 });
9183 }
9184 self.select_larger_syntax_node_stack = stack;
9185 }
9186
9187 pub fn select_smaller_syntax_node(
9188 &mut self,
9189 _: &SelectSmallerSyntaxNode,
9190 cx: &mut ViewContext<Self>,
9191 ) {
9192 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9193 if let Some(selections) = stack.pop() {
9194 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9195 s.select(selections.to_vec());
9196 });
9197 }
9198 self.select_larger_syntax_node_stack = stack;
9199 }
9200
9201 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9202 if !EditorSettings::get_global(cx).gutter.runnables {
9203 self.clear_tasks();
9204 return Task::ready(());
9205 }
9206 let project = self.project.as_ref().map(Model::downgrade);
9207 cx.spawn(|this, mut cx| async move {
9208 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9209 let Some(project) = project.and_then(|p| p.upgrade()) else {
9210 return;
9211 };
9212 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9213 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9214 }) else {
9215 return;
9216 };
9217
9218 let hide_runnables = project
9219 .update(&mut cx, |project, cx| {
9220 // Do not display any test indicators in non-dev server remote projects.
9221 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9222 })
9223 .unwrap_or(true);
9224 if hide_runnables {
9225 return;
9226 }
9227 let new_rows =
9228 cx.background_executor()
9229 .spawn({
9230 let snapshot = display_snapshot.clone();
9231 async move {
9232 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9233 }
9234 })
9235 .await;
9236 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9237
9238 this.update(&mut cx, |this, _| {
9239 this.clear_tasks();
9240 for (key, value) in rows {
9241 this.insert_tasks(key, value);
9242 }
9243 })
9244 .ok();
9245 })
9246 }
9247 fn fetch_runnable_ranges(
9248 snapshot: &DisplaySnapshot,
9249 range: Range<Anchor>,
9250 ) -> Vec<language::RunnableRange> {
9251 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9252 }
9253
9254 fn runnable_rows(
9255 project: Model<Project>,
9256 snapshot: DisplaySnapshot,
9257 runnable_ranges: Vec<RunnableRange>,
9258 mut cx: AsyncWindowContext,
9259 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9260 runnable_ranges
9261 .into_iter()
9262 .filter_map(|mut runnable| {
9263 let tasks = cx
9264 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9265 .ok()?;
9266 if tasks.is_empty() {
9267 return None;
9268 }
9269
9270 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9271
9272 let row = snapshot
9273 .buffer_snapshot
9274 .buffer_line_for_row(MultiBufferRow(point.row))?
9275 .1
9276 .start
9277 .row;
9278
9279 let context_range =
9280 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9281 Some((
9282 (runnable.buffer_id, row),
9283 RunnableTasks {
9284 templates: tasks,
9285 offset: MultiBufferOffset(runnable.run_range.start),
9286 context_range,
9287 column: point.column,
9288 extra_variables: runnable.extra_captures,
9289 },
9290 ))
9291 })
9292 .collect()
9293 }
9294
9295 fn templates_with_tags(
9296 project: &Model<Project>,
9297 runnable: &mut Runnable,
9298 cx: &WindowContext<'_>,
9299 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9300 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9301 let (worktree_id, file) = project
9302 .buffer_for_id(runnable.buffer, cx)
9303 .and_then(|buffer| buffer.read(cx).file())
9304 .map(|file| (file.worktree_id(cx), file.clone()))
9305 .unzip();
9306
9307 (
9308 project.task_store().read(cx).task_inventory().cloned(),
9309 worktree_id,
9310 file,
9311 )
9312 });
9313
9314 let tags = mem::take(&mut runnable.tags);
9315 let mut tags: Vec<_> = tags
9316 .into_iter()
9317 .flat_map(|tag| {
9318 let tag = tag.0.clone();
9319 inventory
9320 .as_ref()
9321 .into_iter()
9322 .flat_map(|inventory| {
9323 inventory.read(cx).list_tasks(
9324 file.clone(),
9325 Some(runnable.language.clone()),
9326 worktree_id,
9327 cx,
9328 )
9329 })
9330 .filter(move |(_, template)| {
9331 template.tags.iter().any(|source_tag| source_tag == &tag)
9332 })
9333 })
9334 .sorted_by_key(|(kind, _)| kind.to_owned())
9335 .collect();
9336 if let Some((leading_tag_source, _)) = tags.first() {
9337 // Strongest source wins; if we have worktree tag binding, prefer that to
9338 // global and language bindings;
9339 // if we have a global binding, prefer that to language binding.
9340 let first_mismatch = tags
9341 .iter()
9342 .position(|(tag_source, _)| tag_source != leading_tag_source);
9343 if let Some(index) = first_mismatch {
9344 tags.truncate(index);
9345 }
9346 }
9347
9348 tags
9349 }
9350
9351 pub fn move_to_enclosing_bracket(
9352 &mut self,
9353 _: &MoveToEnclosingBracket,
9354 cx: &mut ViewContext<Self>,
9355 ) {
9356 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9357 s.move_offsets_with(|snapshot, selection| {
9358 let Some(enclosing_bracket_ranges) =
9359 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9360 else {
9361 return;
9362 };
9363
9364 let mut best_length = usize::MAX;
9365 let mut best_inside = false;
9366 let mut best_in_bracket_range = false;
9367 let mut best_destination = None;
9368 for (open, close) in enclosing_bracket_ranges {
9369 let close = close.to_inclusive();
9370 let length = close.end() - open.start;
9371 let inside = selection.start >= open.end && selection.end <= *close.start();
9372 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9373 || close.contains(&selection.head());
9374
9375 // If best is next to a bracket and current isn't, skip
9376 if !in_bracket_range && best_in_bracket_range {
9377 continue;
9378 }
9379
9380 // Prefer smaller lengths unless best is inside and current isn't
9381 if length > best_length && (best_inside || !inside) {
9382 continue;
9383 }
9384
9385 best_length = length;
9386 best_inside = inside;
9387 best_in_bracket_range = in_bracket_range;
9388 best_destination = Some(
9389 if close.contains(&selection.start) && close.contains(&selection.end) {
9390 if inside {
9391 open.end
9392 } else {
9393 open.start
9394 }
9395 } else if inside {
9396 *close.start()
9397 } else {
9398 *close.end()
9399 },
9400 );
9401 }
9402
9403 if let Some(destination) = best_destination {
9404 selection.collapse_to(destination, SelectionGoal::None);
9405 }
9406 })
9407 });
9408 }
9409
9410 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9411 self.end_selection(cx);
9412 self.selection_history.mode = SelectionHistoryMode::Undoing;
9413 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9414 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9415 self.select_next_state = entry.select_next_state;
9416 self.select_prev_state = entry.select_prev_state;
9417 self.add_selections_state = entry.add_selections_state;
9418 self.request_autoscroll(Autoscroll::newest(), cx);
9419 }
9420 self.selection_history.mode = SelectionHistoryMode::Normal;
9421 }
9422
9423 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9424 self.end_selection(cx);
9425 self.selection_history.mode = SelectionHistoryMode::Redoing;
9426 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9427 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9428 self.select_next_state = entry.select_next_state;
9429 self.select_prev_state = entry.select_prev_state;
9430 self.add_selections_state = entry.add_selections_state;
9431 self.request_autoscroll(Autoscroll::newest(), cx);
9432 }
9433 self.selection_history.mode = SelectionHistoryMode::Normal;
9434 }
9435
9436 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9437 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9438 }
9439
9440 pub fn expand_excerpts_down(
9441 &mut self,
9442 action: &ExpandExcerptsDown,
9443 cx: &mut ViewContext<Self>,
9444 ) {
9445 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9446 }
9447
9448 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9449 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9450 }
9451
9452 pub fn expand_excerpts_for_direction(
9453 &mut self,
9454 lines: u32,
9455 direction: ExpandExcerptDirection,
9456 cx: &mut ViewContext<Self>,
9457 ) {
9458 let selections = self.selections.disjoint_anchors();
9459
9460 let lines = if lines == 0 {
9461 EditorSettings::get_global(cx).expand_excerpt_lines
9462 } else {
9463 lines
9464 };
9465
9466 self.buffer.update(cx, |buffer, cx| {
9467 buffer.expand_excerpts(
9468 selections
9469 .iter()
9470 .map(|selection| selection.head().excerpt_id)
9471 .dedup(),
9472 lines,
9473 direction,
9474 cx,
9475 )
9476 })
9477 }
9478
9479 pub fn expand_excerpt(
9480 &mut self,
9481 excerpt: ExcerptId,
9482 direction: ExpandExcerptDirection,
9483 cx: &mut ViewContext<Self>,
9484 ) {
9485 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9486 self.buffer.update(cx, |buffer, cx| {
9487 buffer.expand_excerpts([excerpt], lines, direction, cx)
9488 })
9489 }
9490
9491 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9492 self.go_to_diagnostic_impl(Direction::Next, cx)
9493 }
9494
9495 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9496 self.go_to_diagnostic_impl(Direction::Prev, cx)
9497 }
9498
9499 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9500 let buffer = self.buffer.read(cx).snapshot(cx);
9501 let selection = self.selections.newest::<usize>(cx);
9502
9503 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9504 if direction == Direction::Next {
9505 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9506 let (group_id, jump_to) = popover.activation_info();
9507 if self.activate_diagnostics(group_id, cx) {
9508 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9509 let mut new_selection = s.newest_anchor().clone();
9510 new_selection.collapse_to(jump_to, SelectionGoal::None);
9511 s.select_anchors(vec![new_selection.clone()]);
9512 });
9513 }
9514 return;
9515 }
9516 }
9517
9518 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9519 active_diagnostics
9520 .primary_range
9521 .to_offset(&buffer)
9522 .to_inclusive()
9523 });
9524 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9525 if active_primary_range.contains(&selection.head()) {
9526 *active_primary_range.start()
9527 } else {
9528 selection.head()
9529 }
9530 } else {
9531 selection.head()
9532 };
9533 let snapshot = self.snapshot(cx);
9534 loop {
9535 let diagnostics = if direction == Direction::Prev {
9536 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9537 } else {
9538 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9539 }
9540 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9541 let group = diagnostics
9542 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9543 // be sorted in a stable way
9544 // skip until we are at current active diagnostic, if it exists
9545 .skip_while(|entry| {
9546 (match direction {
9547 Direction::Prev => entry.range.start >= search_start,
9548 Direction::Next => entry.range.start <= search_start,
9549 }) && self
9550 .active_diagnostics
9551 .as_ref()
9552 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9553 })
9554 .find_map(|entry| {
9555 if entry.diagnostic.is_primary
9556 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9557 && !entry.range.is_empty()
9558 // if we match with the active diagnostic, skip it
9559 && Some(entry.diagnostic.group_id)
9560 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9561 {
9562 Some((entry.range, entry.diagnostic.group_id))
9563 } else {
9564 None
9565 }
9566 });
9567
9568 if let Some((primary_range, group_id)) = group {
9569 if self.activate_diagnostics(group_id, cx) {
9570 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9571 s.select(vec![Selection {
9572 id: selection.id,
9573 start: primary_range.start,
9574 end: primary_range.start,
9575 reversed: false,
9576 goal: SelectionGoal::None,
9577 }]);
9578 });
9579 }
9580 break;
9581 } else {
9582 // Cycle around to the start of the buffer, potentially moving back to the start of
9583 // the currently active diagnostic.
9584 active_primary_range.take();
9585 if direction == Direction::Prev {
9586 if search_start == buffer.len() {
9587 break;
9588 } else {
9589 search_start = buffer.len();
9590 }
9591 } else if search_start == 0 {
9592 break;
9593 } else {
9594 search_start = 0;
9595 }
9596 }
9597 }
9598 }
9599
9600 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9601 let snapshot = self
9602 .display_map
9603 .update(cx, |display_map, cx| display_map.snapshot(cx));
9604 let selection = self.selections.newest::<Point>(cx);
9605 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9606 }
9607
9608 fn go_to_hunk_after_position(
9609 &mut self,
9610 snapshot: &DisplaySnapshot,
9611 position: Point,
9612 cx: &mut ViewContext<'_, Editor>,
9613 ) -> Option<MultiBufferDiffHunk> {
9614 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9615 snapshot,
9616 position,
9617 false,
9618 snapshot
9619 .buffer_snapshot
9620 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9621 cx,
9622 ) {
9623 return Some(hunk);
9624 }
9625
9626 let wrapped_point = Point::zero();
9627 self.go_to_next_hunk_in_direction(
9628 snapshot,
9629 wrapped_point,
9630 true,
9631 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9632 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9633 ),
9634 cx,
9635 )
9636 }
9637
9638 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9639 let snapshot = self
9640 .display_map
9641 .update(cx, |display_map, cx| display_map.snapshot(cx));
9642 let selection = self.selections.newest::<Point>(cx);
9643
9644 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9645 }
9646
9647 fn go_to_hunk_before_position(
9648 &mut self,
9649 snapshot: &DisplaySnapshot,
9650 position: Point,
9651 cx: &mut ViewContext<'_, Editor>,
9652 ) -> Option<MultiBufferDiffHunk> {
9653 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9654 snapshot,
9655 position,
9656 false,
9657 snapshot
9658 .buffer_snapshot
9659 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9660 cx,
9661 ) {
9662 return Some(hunk);
9663 }
9664
9665 let wrapped_point = snapshot.buffer_snapshot.max_point();
9666 self.go_to_next_hunk_in_direction(
9667 snapshot,
9668 wrapped_point,
9669 true,
9670 snapshot
9671 .buffer_snapshot
9672 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9673 cx,
9674 )
9675 }
9676
9677 fn go_to_next_hunk_in_direction(
9678 &mut self,
9679 snapshot: &DisplaySnapshot,
9680 initial_point: Point,
9681 is_wrapped: bool,
9682 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9683 cx: &mut ViewContext<Editor>,
9684 ) -> Option<MultiBufferDiffHunk> {
9685 let display_point = initial_point.to_display_point(snapshot);
9686 let mut hunks = hunks
9687 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9688 .filter(|(display_hunk, _)| {
9689 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9690 })
9691 .dedup();
9692
9693 if let Some((display_hunk, hunk)) = hunks.next() {
9694 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9695 let row = display_hunk.start_display_row();
9696 let point = DisplayPoint::new(row, 0);
9697 s.select_display_ranges([point..point]);
9698 });
9699
9700 Some(hunk)
9701 } else {
9702 None
9703 }
9704 }
9705
9706 pub fn go_to_definition(
9707 &mut self,
9708 _: &GoToDefinition,
9709 cx: &mut ViewContext<Self>,
9710 ) -> Task<Result<Navigated>> {
9711 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9712 cx.spawn(|editor, mut cx| async move {
9713 if definition.await? == Navigated::Yes {
9714 return Ok(Navigated::Yes);
9715 }
9716 match editor.update(&mut cx, |editor, cx| {
9717 editor.find_all_references(&FindAllReferences, cx)
9718 })? {
9719 Some(references) => references.await,
9720 None => Ok(Navigated::No),
9721 }
9722 })
9723 }
9724
9725 pub fn go_to_declaration(
9726 &mut self,
9727 _: &GoToDeclaration,
9728 cx: &mut ViewContext<Self>,
9729 ) -> Task<Result<Navigated>> {
9730 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9731 }
9732
9733 pub fn go_to_declaration_split(
9734 &mut self,
9735 _: &GoToDeclaration,
9736 cx: &mut ViewContext<Self>,
9737 ) -> Task<Result<Navigated>> {
9738 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9739 }
9740
9741 pub fn go_to_implementation(
9742 &mut self,
9743 _: &GoToImplementation,
9744 cx: &mut ViewContext<Self>,
9745 ) -> Task<Result<Navigated>> {
9746 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9747 }
9748
9749 pub fn go_to_implementation_split(
9750 &mut self,
9751 _: &GoToImplementationSplit,
9752 cx: &mut ViewContext<Self>,
9753 ) -> Task<Result<Navigated>> {
9754 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9755 }
9756
9757 pub fn go_to_type_definition(
9758 &mut self,
9759 _: &GoToTypeDefinition,
9760 cx: &mut ViewContext<Self>,
9761 ) -> Task<Result<Navigated>> {
9762 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9763 }
9764
9765 pub fn go_to_definition_split(
9766 &mut self,
9767 _: &GoToDefinitionSplit,
9768 cx: &mut ViewContext<Self>,
9769 ) -> Task<Result<Navigated>> {
9770 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9771 }
9772
9773 pub fn go_to_type_definition_split(
9774 &mut self,
9775 _: &GoToTypeDefinitionSplit,
9776 cx: &mut ViewContext<Self>,
9777 ) -> Task<Result<Navigated>> {
9778 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9779 }
9780
9781 fn go_to_definition_of_kind(
9782 &mut self,
9783 kind: GotoDefinitionKind,
9784 split: bool,
9785 cx: &mut ViewContext<Self>,
9786 ) -> Task<Result<Navigated>> {
9787 let Some(provider) = self.semantics_provider.clone() else {
9788 return Task::ready(Ok(Navigated::No));
9789 };
9790 let head = self.selections.newest::<usize>(cx).head();
9791 let buffer = self.buffer.read(cx);
9792 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9793 text_anchor
9794 } else {
9795 return Task::ready(Ok(Navigated::No));
9796 };
9797
9798 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9799 return Task::ready(Ok(Navigated::No));
9800 };
9801
9802 cx.spawn(|editor, mut cx| async move {
9803 let definitions = definitions.await?;
9804 let navigated = editor
9805 .update(&mut cx, |editor, cx| {
9806 editor.navigate_to_hover_links(
9807 Some(kind),
9808 definitions
9809 .into_iter()
9810 .filter(|location| {
9811 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9812 })
9813 .map(HoverLink::Text)
9814 .collect::<Vec<_>>(),
9815 split,
9816 cx,
9817 )
9818 })?
9819 .await?;
9820 anyhow::Ok(navigated)
9821 })
9822 }
9823
9824 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9825 let position = self.selections.newest_anchor().head();
9826 let Some((buffer, buffer_position)) =
9827 self.buffer.read(cx).text_anchor_for_position(position, cx)
9828 else {
9829 return;
9830 };
9831
9832 cx.spawn(|editor, mut cx| async move {
9833 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9834 editor.update(&mut cx, |_, cx| {
9835 cx.open_url(&url);
9836 })
9837 } else {
9838 Ok(())
9839 }
9840 })
9841 .detach();
9842 }
9843
9844 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9845 let Some(workspace) = self.workspace() else {
9846 return;
9847 };
9848
9849 let position = self.selections.newest_anchor().head();
9850
9851 let Some((buffer, buffer_position)) =
9852 self.buffer.read(cx).text_anchor_for_position(position, cx)
9853 else {
9854 return;
9855 };
9856
9857 let project = self.project.clone();
9858
9859 cx.spawn(|_, mut cx| async move {
9860 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9861
9862 if let Some((_, path)) = result {
9863 workspace
9864 .update(&mut cx, |workspace, cx| {
9865 workspace.open_resolved_path(path, cx)
9866 })?
9867 .await?;
9868 }
9869 anyhow::Ok(())
9870 })
9871 .detach();
9872 }
9873
9874 pub(crate) fn navigate_to_hover_links(
9875 &mut self,
9876 kind: Option<GotoDefinitionKind>,
9877 mut definitions: Vec<HoverLink>,
9878 split: bool,
9879 cx: &mut ViewContext<Editor>,
9880 ) -> Task<Result<Navigated>> {
9881 // If there is one definition, just open it directly
9882 if definitions.len() == 1 {
9883 let definition = definitions.pop().unwrap();
9884
9885 enum TargetTaskResult {
9886 Location(Option<Location>),
9887 AlreadyNavigated,
9888 }
9889
9890 let target_task = match definition {
9891 HoverLink::Text(link) => {
9892 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9893 }
9894 HoverLink::InlayHint(lsp_location, server_id) => {
9895 let computation = self.compute_target_location(lsp_location, server_id, cx);
9896 cx.background_executor().spawn(async move {
9897 let location = computation.await?;
9898 Ok(TargetTaskResult::Location(location))
9899 })
9900 }
9901 HoverLink::Url(url) => {
9902 cx.open_url(&url);
9903 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9904 }
9905 HoverLink::File(path) => {
9906 if let Some(workspace) = self.workspace() {
9907 cx.spawn(|_, mut cx| async move {
9908 workspace
9909 .update(&mut cx, |workspace, cx| {
9910 workspace.open_resolved_path(path, cx)
9911 })?
9912 .await
9913 .map(|_| TargetTaskResult::AlreadyNavigated)
9914 })
9915 } else {
9916 Task::ready(Ok(TargetTaskResult::Location(None)))
9917 }
9918 }
9919 };
9920 cx.spawn(|editor, mut cx| async move {
9921 let target = match target_task.await.context("target resolution task")? {
9922 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9923 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9924 TargetTaskResult::Location(Some(target)) => target,
9925 };
9926
9927 editor.update(&mut cx, |editor, cx| {
9928 let Some(workspace) = editor.workspace() else {
9929 return Navigated::No;
9930 };
9931 let pane = workspace.read(cx).active_pane().clone();
9932
9933 let range = target.range.to_offset(target.buffer.read(cx));
9934 let range = editor.range_for_match(&range);
9935
9936 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9937 let buffer = target.buffer.read(cx);
9938 let range = check_multiline_range(buffer, range);
9939 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9940 s.select_ranges([range]);
9941 });
9942 } else {
9943 cx.window_context().defer(move |cx| {
9944 let target_editor: View<Self> =
9945 workspace.update(cx, |workspace, cx| {
9946 let pane = if split {
9947 workspace.adjacent_pane(cx)
9948 } else {
9949 workspace.active_pane().clone()
9950 };
9951
9952 workspace.open_project_item(
9953 pane,
9954 target.buffer.clone(),
9955 true,
9956 true,
9957 cx,
9958 )
9959 });
9960 target_editor.update(cx, |target_editor, cx| {
9961 // When selecting a definition in a different buffer, disable the nav history
9962 // to avoid creating a history entry at the previous cursor location.
9963 pane.update(cx, |pane, _| pane.disable_history());
9964 let buffer = target.buffer.read(cx);
9965 let range = check_multiline_range(buffer, range);
9966 target_editor.change_selections(
9967 Some(Autoscroll::focused()),
9968 cx,
9969 |s| {
9970 s.select_ranges([range]);
9971 },
9972 );
9973 pane.update(cx, |pane, _| pane.enable_history());
9974 });
9975 });
9976 }
9977 Navigated::Yes
9978 })
9979 })
9980 } else if !definitions.is_empty() {
9981 cx.spawn(|editor, mut cx| async move {
9982 let (title, location_tasks, workspace) = editor
9983 .update(&mut cx, |editor, cx| {
9984 let tab_kind = match kind {
9985 Some(GotoDefinitionKind::Implementation) => "Implementations",
9986 _ => "Definitions",
9987 };
9988 let title = definitions
9989 .iter()
9990 .find_map(|definition| match definition {
9991 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9992 let buffer = origin.buffer.read(cx);
9993 format!(
9994 "{} for {}",
9995 tab_kind,
9996 buffer
9997 .text_for_range(origin.range.clone())
9998 .collect::<String>()
9999 )
10000 }),
10001 HoverLink::InlayHint(_, _) => None,
10002 HoverLink::Url(_) => None,
10003 HoverLink::File(_) => None,
10004 })
10005 .unwrap_or(tab_kind.to_string());
10006 let location_tasks = definitions
10007 .into_iter()
10008 .map(|definition| match definition {
10009 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10010 HoverLink::InlayHint(lsp_location, server_id) => {
10011 editor.compute_target_location(lsp_location, server_id, cx)
10012 }
10013 HoverLink::Url(_) => Task::ready(Ok(None)),
10014 HoverLink::File(_) => Task::ready(Ok(None)),
10015 })
10016 .collect::<Vec<_>>();
10017 (title, location_tasks, editor.workspace().clone())
10018 })
10019 .context("location tasks preparation")?;
10020
10021 let locations = future::join_all(location_tasks)
10022 .await
10023 .into_iter()
10024 .filter_map(|location| location.transpose())
10025 .collect::<Result<_>>()
10026 .context("location tasks")?;
10027
10028 let Some(workspace) = workspace else {
10029 return Ok(Navigated::No);
10030 };
10031 let opened = workspace
10032 .update(&mut cx, |workspace, cx| {
10033 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10034 })
10035 .ok();
10036
10037 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10038 })
10039 } else {
10040 Task::ready(Ok(Navigated::No))
10041 }
10042 }
10043
10044 fn compute_target_location(
10045 &self,
10046 lsp_location: lsp::Location,
10047 server_id: LanguageServerId,
10048 cx: &mut ViewContext<Self>,
10049 ) -> Task<anyhow::Result<Option<Location>>> {
10050 let Some(project) = self.project.clone() else {
10051 return Task::Ready(Some(Ok(None)));
10052 };
10053
10054 cx.spawn(move |editor, mut cx| async move {
10055 let location_task = editor.update(&mut cx, |_, cx| {
10056 project.update(cx, |project, cx| {
10057 let language_server_name = project
10058 .language_server_statuses(cx)
10059 .find(|(id, _)| server_id == *id)
10060 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10061 language_server_name.map(|language_server_name| {
10062 project.open_local_buffer_via_lsp(
10063 lsp_location.uri.clone(),
10064 server_id,
10065 language_server_name,
10066 cx,
10067 )
10068 })
10069 })
10070 })?;
10071 let location = match location_task {
10072 Some(task) => Some({
10073 let target_buffer_handle = task.await.context("open local buffer")?;
10074 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10075 let target_start = target_buffer
10076 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10077 let target_end = target_buffer
10078 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10079 target_buffer.anchor_after(target_start)
10080 ..target_buffer.anchor_before(target_end)
10081 })?;
10082 Location {
10083 buffer: target_buffer_handle,
10084 range,
10085 }
10086 }),
10087 None => None,
10088 };
10089 Ok(location)
10090 })
10091 }
10092
10093 pub fn find_all_references(
10094 &mut self,
10095 _: &FindAllReferences,
10096 cx: &mut ViewContext<Self>,
10097 ) -> Option<Task<Result<Navigated>>> {
10098 let selection = self.selections.newest::<usize>(cx);
10099 let multi_buffer = self.buffer.read(cx);
10100 let head = selection.head();
10101
10102 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10103 let head_anchor = multi_buffer_snapshot.anchor_at(
10104 head,
10105 if head < selection.tail() {
10106 Bias::Right
10107 } else {
10108 Bias::Left
10109 },
10110 );
10111
10112 match self
10113 .find_all_references_task_sources
10114 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10115 {
10116 Ok(_) => {
10117 log::info!(
10118 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10119 );
10120 return None;
10121 }
10122 Err(i) => {
10123 self.find_all_references_task_sources.insert(i, head_anchor);
10124 }
10125 }
10126
10127 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10128 let workspace = self.workspace()?;
10129 let project = workspace.read(cx).project().clone();
10130 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10131 Some(cx.spawn(|editor, mut cx| async move {
10132 let _cleanup = defer({
10133 let mut cx = cx.clone();
10134 move || {
10135 let _ = editor.update(&mut cx, |editor, _| {
10136 if let Ok(i) =
10137 editor
10138 .find_all_references_task_sources
10139 .binary_search_by(|anchor| {
10140 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10141 })
10142 {
10143 editor.find_all_references_task_sources.remove(i);
10144 }
10145 });
10146 }
10147 });
10148
10149 let locations = references.await?;
10150 if locations.is_empty() {
10151 return anyhow::Ok(Navigated::No);
10152 }
10153
10154 workspace.update(&mut cx, |workspace, cx| {
10155 let title = locations
10156 .first()
10157 .as_ref()
10158 .map(|location| {
10159 let buffer = location.buffer.read(cx);
10160 format!(
10161 "References to `{}`",
10162 buffer
10163 .text_for_range(location.range.clone())
10164 .collect::<String>()
10165 )
10166 })
10167 .unwrap();
10168 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10169 Navigated::Yes
10170 })
10171 }))
10172 }
10173
10174 /// Opens a multibuffer with the given project locations in it
10175 pub fn open_locations_in_multibuffer(
10176 workspace: &mut Workspace,
10177 mut locations: Vec<Location>,
10178 title: String,
10179 split: bool,
10180 cx: &mut ViewContext<Workspace>,
10181 ) {
10182 // If there are multiple definitions, open them in a multibuffer
10183 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10184 let mut locations = locations.into_iter().peekable();
10185 let mut ranges_to_highlight = Vec::new();
10186 let capability = workspace.project().read(cx).capability();
10187
10188 let excerpt_buffer = cx.new_model(|cx| {
10189 let mut multibuffer = MultiBuffer::new(capability);
10190 while let Some(location) = locations.next() {
10191 let buffer = location.buffer.read(cx);
10192 let mut ranges_for_buffer = Vec::new();
10193 let range = location.range.to_offset(buffer);
10194 ranges_for_buffer.push(range.clone());
10195
10196 while let Some(next_location) = locations.peek() {
10197 if next_location.buffer == location.buffer {
10198 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10199 locations.next();
10200 } else {
10201 break;
10202 }
10203 }
10204
10205 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10206 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10207 location.buffer.clone(),
10208 ranges_for_buffer,
10209 DEFAULT_MULTIBUFFER_CONTEXT,
10210 cx,
10211 ))
10212 }
10213
10214 multibuffer.with_title(title)
10215 });
10216
10217 let editor = cx.new_view(|cx| {
10218 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10219 });
10220 editor.update(cx, |editor, cx| {
10221 if let Some(first_range) = ranges_to_highlight.first() {
10222 editor.change_selections(None, cx, |selections| {
10223 selections.clear_disjoint();
10224 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10225 });
10226 }
10227 editor.highlight_background::<Self>(
10228 &ranges_to_highlight,
10229 |theme| theme.editor_highlighted_line_background,
10230 cx,
10231 );
10232 });
10233
10234 let item = Box::new(editor);
10235 let item_id = item.item_id();
10236
10237 if split {
10238 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10239 } else {
10240 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10241 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10242 pane.close_current_preview_item(cx)
10243 } else {
10244 None
10245 }
10246 });
10247 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10248 }
10249 workspace.active_pane().update(cx, |pane, cx| {
10250 pane.set_preview_item_id(Some(item_id), cx);
10251 });
10252 }
10253
10254 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10255 use language::ToOffset as _;
10256
10257 let provider = self.semantics_provider.clone()?;
10258 let selection = self.selections.newest_anchor().clone();
10259 let (cursor_buffer, cursor_buffer_position) = self
10260 .buffer
10261 .read(cx)
10262 .text_anchor_for_position(selection.head(), cx)?;
10263 let (tail_buffer, cursor_buffer_position_end) = self
10264 .buffer
10265 .read(cx)
10266 .text_anchor_for_position(selection.tail(), cx)?;
10267 if tail_buffer != cursor_buffer {
10268 return None;
10269 }
10270
10271 let snapshot = cursor_buffer.read(cx).snapshot();
10272 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10273 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10274 let prepare_rename = provider
10275 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10276 .unwrap_or_else(|| Task::ready(Ok(None)));
10277 drop(snapshot);
10278
10279 Some(cx.spawn(|this, mut cx| async move {
10280 let rename_range = if let Some(range) = prepare_rename.await? {
10281 Some(range)
10282 } else {
10283 this.update(&mut cx, |this, cx| {
10284 let buffer = this.buffer.read(cx).snapshot(cx);
10285 let mut buffer_highlights = this
10286 .document_highlights_for_position(selection.head(), &buffer)
10287 .filter(|highlight| {
10288 highlight.start.excerpt_id == selection.head().excerpt_id
10289 && highlight.end.excerpt_id == selection.head().excerpt_id
10290 });
10291 buffer_highlights
10292 .next()
10293 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10294 })?
10295 };
10296 if let Some(rename_range) = rename_range {
10297 this.update(&mut cx, |this, cx| {
10298 let snapshot = cursor_buffer.read(cx).snapshot();
10299 let rename_buffer_range = rename_range.to_offset(&snapshot);
10300 let cursor_offset_in_rename_range =
10301 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10302 let cursor_offset_in_rename_range_end =
10303 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10304
10305 this.take_rename(false, cx);
10306 let buffer = this.buffer.read(cx).read(cx);
10307 let cursor_offset = selection.head().to_offset(&buffer);
10308 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10309 let rename_end = rename_start + rename_buffer_range.len();
10310 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10311 let mut old_highlight_id = None;
10312 let old_name: Arc<str> = buffer
10313 .chunks(rename_start..rename_end, true)
10314 .map(|chunk| {
10315 if old_highlight_id.is_none() {
10316 old_highlight_id = chunk.syntax_highlight_id;
10317 }
10318 chunk.text
10319 })
10320 .collect::<String>()
10321 .into();
10322
10323 drop(buffer);
10324
10325 // Position the selection in the rename editor so that it matches the current selection.
10326 this.show_local_selections = false;
10327 let rename_editor = cx.new_view(|cx| {
10328 let mut editor = Editor::single_line(cx);
10329 editor.buffer.update(cx, |buffer, cx| {
10330 buffer.edit([(0..0, old_name.clone())], None, cx)
10331 });
10332 let rename_selection_range = match cursor_offset_in_rename_range
10333 .cmp(&cursor_offset_in_rename_range_end)
10334 {
10335 Ordering::Equal => {
10336 editor.select_all(&SelectAll, cx);
10337 return editor;
10338 }
10339 Ordering::Less => {
10340 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10341 }
10342 Ordering::Greater => {
10343 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10344 }
10345 };
10346 if rename_selection_range.end > old_name.len() {
10347 editor.select_all(&SelectAll, cx);
10348 } else {
10349 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10350 s.select_ranges([rename_selection_range]);
10351 });
10352 }
10353 editor
10354 });
10355 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10356 if e == &EditorEvent::Focused {
10357 cx.emit(EditorEvent::FocusedIn)
10358 }
10359 })
10360 .detach();
10361
10362 let write_highlights =
10363 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10364 let read_highlights =
10365 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10366 let ranges = write_highlights
10367 .iter()
10368 .flat_map(|(_, ranges)| ranges.iter())
10369 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10370 .cloned()
10371 .collect();
10372
10373 this.highlight_text::<Rename>(
10374 ranges,
10375 HighlightStyle {
10376 fade_out: Some(0.6),
10377 ..Default::default()
10378 },
10379 cx,
10380 );
10381 let rename_focus_handle = rename_editor.focus_handle(cx);
10382 cx.focus(&rename_focus_handle);
10383 let block_id = this.insert_blocks(
10384 [BlockProperties {
10385 style: BlockStyle::Flex,
10386 placement: BlockPlacement::Below(range.start),
10387 height: 1,
10388 render: Box::new({
10389 let rename_editor = rename_editor.clone();
10390 move |cx: &mut BlockContext| {
10391 let mut text_style = cx.editor_style.text.clone();
10392 if let Some(highlight_style) = old_highlight_id
10393 .and_then(|h| h.style(&cx.editor_style.syntax))
10394 {
10395 text_style = text_style.highlight(highlight_style);
10396 }
10397 div()
10398 .pl(cx.anchor_x)
10399 .child(EditorElement::new(
10400 &rename_editor,
10401 EditorStyle {
10402 background: cx.theme().system().transparent,
10403 local_player: cx.editor_style.local_player,
10404 text: text_style,
10405 scrollbar_width: cx.editor_style.scrollbar_width,
10406 syntax: cx.editor_style.syntax.clone(),
10407 status: cx.editor_style.status.clone(),
10408 inlay_hints_style: HighlightStyle {
10409 font_weight: Some(FontWeight::BOLD),
10410 ..make_inlay_hints_style(cx)
10411 },
10412 suggestions_style: HighlightStyle {
10413 color: Some(cx.theme().status().predictive),
10414 ..HighlightStyle::default()
10415 },
10416 ..EditorStyle::default()
10417 },
10418 ))
10419 .into_any_element()
10420 }
10421 }),
10422 priority: 0,
10423 }],
10424 Some(Autoscroll::fit()),
10425 cx,
10426 )[0];
10427 this.pending_rename = Some(RenameState {
10428 range,
10429 old_name,
10430 editor: rename_editor,
10431 block_id,
10432 });
10433 })?;
10434 }
10435
10436 Ok(())
10437 }))
10438 }
10439
10440 pub fn confirm_rename(
10441 &mut self,
10442 _: &ConfirmRename,
10443 cx: &mut ViewContext<Self>,
10444 ) -> Option<Task<Result<()>>> {
10445 let rename = self.take_rename(false, cx)?;
10446 let workspace = self.workspace()?.downgrade();
10447 let (buffer, start) = self
10448 .buffer
10449 .read(cx)
10450 .text_anchor_for_position(rename.range.start, cx)?;
10451 let (end_buffer, _) = self
10452 .buffer
10453 .read(cx)
10454 .text_anchor_for_position(rename.range.end, cx)?;
10455 if buffer != end_buffer {
10456 return None;
10457 }
10458
10459 let old_name = rename.old_name;
10460 let new_name = rename.editor.read(cx).text(cx);
10461
10462 let rename = self.semantics_provider.as_ref()?.perform_rename(
10463 &buffer,
10464 start,
10465 new_name.clone(),
10466 cx,
10467 )?;
10468
10469 Some(cx.spawn(|editor, mut cx| async move {
10470 let project_transaction = rename.await?;
10471 Self::open_project_transaction(
10472 &editor,
10473 workspace,
10474 project_transaction,
10475 format!("Rename: {} → {}", old_name, new_name),
10476 cx.clone(),
10477 )
10478 .await?;
10479
10480 editor.update(&mut cx, |editor, cx| {
10481 editor.refresh_document_highlights(cx);
10482 })?;
10483 Ok(())
10484 }))
10485 }
10486
10487 fn take_rename(
10488 &mut self,
10489 moving_cursor: bool,
10490 cx: &mut ViewContext<Self>,
10491 ) -> Option<RenameState> {
10492 let rename = self.pending_rename.take()?;
10493 if rename.editor.focus_handle(cx).is_focused(cx) {
10494 cx.focus(&self.focus_handle);
10495 }
10496
10497 self.remove_blocks(
10498 [rename.block_id].into_iter().collect(),
10499 Some(Autoscroll::fit()),
10500 cx,
10501 );
10502 self.clear_highlights::<Rename>(cx);
10503 self.show_local_selections = true;
10504
10505 if moving_cursor {
10506 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10507 editor.selections.newest::<usize>(cx).head()
10508 });
10509
10510 // Update the selection to match the position of the selection inside
10511 // the rename editor.
10512 let snapshot = self.buffer.read(cx).read(cx);
10513 let rename_range = rename.range.to_offset(&snapshot);
10514 let cursor_in_editor = snapshot
10515 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10516 .min(rename_range.end);
10517 drop(snapshot);
10518
10519 self.change_selections(None, cx, |s| {
10520 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10521 });
10522 } else {
10523 self.refresh_document_highlights(cx);
10524 }
10525
10526 Some(rename)
10527 }
10528
10529 pub fn pending_rename(&self) -> Option<&RenameState> {
10530 self.pending_rename.as_ref()
10531 }
10532
10533 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10534 let project = match &self.project {
10535 Some(project) => project.clone(),
10536 None => return None,
10537 };
10538
10539 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10540 }
10541
10542 fn format_selections(
10543 &mut self,
10544 _: &FormatSelections,
10545 cx: &mut ViewContext<Self>,
10546 ) -> Option<Task<Result<()>>> {
10547 let project = match &self.project {
10548 Some(project) => project.clone(),
10549 None => return None,
10550 };
10551
10552 let selections = self
10553 .selections
10554 .all_adjusted(cx)
10555 .into_iter()
10556 .filter(|s| !s.is_empty())
10557 .collect_vec();
10558
10559 Some(self.perform_format(
10560 project,
10561 FormatTrigger::Manual,
10562 FormatTarget::Ranges(selections),
10563 cx,
10564 ))
10565 }
10566
10567 fn perform_format(
10568 &mut self,
10569 project: Model<Project>,
10570 trigger: FormatTrigger,
10571 target: FormatTarget,
10572 cx: &mut ViewContext<Self>,
10573 ) -> Task<Result<()>> {
10574 let buffer = self.buffer().clone();
10575 let mut buffers = buffer.read(cx).all_buffers();
10576 if trigger == FormatTrigger::Save {
10577 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10578 }
10579
10580 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10581 let format = project.update(cx, |project, cx| {
10582 project.format(buffers, true, trigger, target, cx)
10583 });
10584
10585 cx.spawn(|_, mut cx| async move {
10586 let transaction = futures::select_biased! {
10587 () = timeout => {
10588 log::warn!("timed out waiting for formatting");
10589 None
10590 }
10591 transaction = format.log_err().fuse() => transaction,
10592 };
10593
10594 buffer
10595 .update(&mut cx, |buffer, cx| {
10596 if let Some(transaction) = transaction {
10597 if !buffer.is_singleton() {
10598 buffer.push_transaction(&transaction.0, cx);
10599 }
10600 }
10601
10602 cx.notify();
10603 })
10604 .ok();
10605
10606 Ok(())
10607 })
10608 }
10609
10610 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10611 if let Some(project) = self.project.clone() {
10612 self.buffer.update(cx, |multi_buffer, cx| {
10613 project.update(cx, |project, cx| {
10614 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10615 });
10616 })
10617 }
10618 }
10619
10620 fn cancel_language_server_work(
10621 &mut self,
10622 _: &actions::CancelLanguageServerWork,
10623 cx: &mut ViewContext<Self>,
10624 ) {
10625 if let Some(project) = self.project.clone() {
10626 self.buffer.update(cx, |multi_buffer, cx| {
10627 project.update(cx, |project, cx| {
10628 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10629 });
10630 })
10631 }
10632 }
10633
10634 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10635 cx.show_character_palette();
10636 }
10637
10638 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10639 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10640 let buffer = self.buffer.read(cx).snapshot(cx);
10641 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10642 let is_valid = buffer
10643 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10644 .any(|entry| {
10645 entry.diagnostic.is_primary
10646 && !entry.range.is_empty()
10647 && entry.range.start == primary_range_start
10648 && entry.diagnostic.message == active_diagnostics.primary_message
10649 });
10650
10651 if is_valid != active_diagnostics.is_valid {
10652 active_diagnostics.is_valid = is_valid;
10653 let mut new_styles = HashMap::default();
10654 for (block_id, diagnostic) in &active_diagnostics.blocks {
10655 new_styles.insert(
10656 *block_id,
10657 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10658 );
10659 }
10660 self.display_map.update(cx, |display_map, _cx| {
10661 display_map.replace_blocks(new_styles)
10662 });
10663 }
10664 }
10665 }
10666
10667 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10668 self.dismiss_diagnostics(cx);
10669 let snapshot = self.snapshot(cx);
10670 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10671 let buffer = self.buffer.read(cx).snapshot(cx);
10672
10673 let mut primary_range = None;
10674 let mut primary_message = None;
10675 let mut group_end = Point::zero();
10676 let diagnostic_group = buffer
10677 .diagnostic_group::<MultiBufferPoint>(group_id)
10678 .filter_map(|entry| {
10679 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10680 && (entry.range.start.row == entry.range.end.row
10681 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10682 {
10683 return None;
10684 }
10685 if entry.range.end > group_end {
10686 group_end = entry.range.end;
10687 }
10688 if entry.diagnostic.is_primary {
10689 primary_range = Some(entry.range.clone());
10690 primary_message = Some(entry.diagnostic.message.clone());
10691 }
10692 Some(entry)
10693 })
10694 .collect::<Vec<_>>();
10695 let primary_range = primary_range?;
10696 let primary_message = primary_message?;
10697 let primary_range =
10698 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10699
10700 let blocks = display_map
10701 .insert_blocks(
10702 diagnostic_group.iter().map(|entry| {
10703 let diagnostic = entry.diagnostic.clone();
10704 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10705 BlockProperties {
10706 style: BlockStyle::Fixed,
10707 placement: BlockPlacement::Below(
10708 buffer.anchor_after(entry.range.start),
10709 ),
10710 height: message_height,
10711 render: diagnostic_block_renderer(diagnostic, None, true, true),
10712 priority: 0,
10713 }
10714 }),
10715 cx,
10716 )
10717 .into_iter()
10718 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10719 .collect();
10720
10721 Some(ActiveDiagnosticGroup {
10722 primary_range,
10723 primary_message,
10724 group_id,
10725 blocks,
10726 is_valid: true,
10727 })
10728 });
10729 self.active_diagnostics.is_some()
10730 }
10731
10732 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10733 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10734 self.display_map.update(cx, |display_map, cx| {
10735 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10736 });
10737 cx.notify();
10738 }
10739 }
10740
10741 pub fn set_selections_from_remote(
10742 &mut self,
10743 selections: Vec<Selection<Anchor>>,
10744 pending_selection: Option<Selection<Anchor>>,
10745 cx: &mut ViewContext<Self>,
10746 ) {
10747 let old_cursor_position = self.selections.newest_anchor().head();
10748 self.selections.change_with(cx, |s| {
10749 s.select_anchors(selections);
10750 if let Some(pending_selection) = pending_selection {
10751 s.set_pending(pending_selection, SelectMode::Character);
10752 } else {
10753 s.clear_pending();
10754 }
10755 });
10756 self.selections_did_change(false, &old_cursor_position, true, cx);
10757 }
10758
10759 fn push_to_selection_history(&mut self) {
10760 self.selection_history.push(SelectionHistoryEntry {
10761 selections: self.selections.disjoint_anchors(),
10762 select_next_state: self.select_next_state.clone(),
10763 select_prev_state: self.select_prev_state.clone(),
10764 add_selections_state: self.add_selections_state.clone(),
10765 });
10766 }
10767
10768 pub fn transact(
10769 &mut self,
10770 cx: &mut ViewContext<Self>,
10771 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10772 ) -> Option<TransactionId> {
10773 self.start_transaction_at(Instant::now(), cx);
10774 update(self, cx);
10775 self.end_transaction_at(Instant::now(), cx)
10776 }
10777
10778 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10779 self.end_selection(cx);
10780 if let Some(tx_id) = self
10781 .buffer
10782 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10783 {
10784 self.selection_history
10785 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10786 cx.emit(EditorEvent::TransactionBegun {
10787 transaction_id: tx_id,
10788 })
10789 }
10790 }
10791
10792 fn end_transaction_at(
10793 &mut self,
10794 now: Instant,
10795 cx: &mut ViewContext<Self>,
10796 ) -> Option<TransactionId> {
10797 if let Some(transaction_id) = self
10798 .buffer
10799 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10800 {
10801 if let Some((_, end_selections)) =
10802 self.selection_history.transaction_mut(transaction_id)
10803 {
10804 *end_selections = Some(self.selections.disjoint_anchors());
10805 } else {
10806 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10807 }
10808
10809 cx.emit(EditorEvent::Edited { transaction_id });
10810 Some(transaction_id)
10811 } else {
10812 None
10813 }
10814 }
10815
10816 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10817 let selection = self.selections.newest::<Point>(cx);
10818
10819 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10820 let range = if selection.is_empty() {
10821 let point = selection.head().to_display_point(&display_map);
10822 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10823 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10824 .to_point(&display_map);
10825 start..end
10826 } else {
10827 selection.range()
10828 };
10829 if display_map.folds_in_range(range).next().is_some() {
10830 self.unfold_lines(&Default::default(), cx)
10831 } else {
10832 self.fold(&Default::default(), cx)
10833 }
10834 }
10835
10836 pub fn toggle_fold_recursive(
10837 &mut self,
10838 _: &actions::ToggleFoldRecursive,
10839 cx: &mut ViewContext<Self>,
10840 ) {
10841 let selection = self.selections.newest::<Point>(cx);
10842
10843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10844 let range = if selection.is_empty() {
10845 let point = selection.head().to_display_point(&display_map);
10846 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10847 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10848 .to_point(&display_map);
10849 start..end
10850 } else {
10851 selection.range()
10852 };
10853 if display_map.folds_in_range(range).next().is_some() {
10854 self.unfold_recursive(&Default::default(), cx)
10855 } else {
10856 self.fold_recursive(&Default::default(), cx)
10857 }
10858 }
10859
10860 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10861 let mut fold_ranges = Vec::new();
10862 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10863 let selections = self.selections.all_adjusted(cx);
10864
10865 for selection in selections {
10866 let range = selection.range().sorted();
10867 let buffer_start_row = range.start.row;
10868
10869 if range.start.row != range.end.row {
10870 let mut found = false;
10871 let mut row = range.start.row;
10872 while row <= range.end.row {
10873 if let Some((foldable_range, fold_text)) =
10874 { display_map.foldable_range(MultiBufferRow(row)) }
10875 {
10876 found = true;
10877 row = foldable_range.end.row + 1;
10878 fold_ranges.push((foldable_range, fold_text));
10879 } else {
10880 row += 1
10881 }
10882 }
10883 if found {
10884 continue;
10885 }
10886 }
10887
10888 for row in (0..=range.start.row).rev() {
10889 if let Some((foldable_range, fold_text)) =
10890 display_map.foldable_range(MultiBufferRow(row))
10891 {
10892 if foldable_range.end.row >= buffer_start_row {
10893 fold_ranges.push((foldable_range, fold_text));
10894 if row <= range.start.row {
10895 break;
10896 }
10897 }
10898 }
10899 }
10900 }
10901
10902 self.fold_ranges(fold_ranges, true, cx);
10903 }
10904
10905 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10906 let fold_at_level = fold_at.level;
10907 let snapshot = self.buffer.read(cx).snapshot(cx);
10908 let mut fold_ranges = Vec::new();
10909 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10910
10911 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10912 while start_row < end_row {
10913 match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10914 Some(foldable_range) => {
10915 let nested_start_row = foldable_range.0.start.row + 1;
10916 let nested_end_row = foldable_range.0.end.row;
10917
10918 if current_level < fold_at_level {
10919 stack.push((nested_start_row, nested_end_row, current_level + 1));
10920 } else if current_level == fold_at_level {
10921 fold_ranges.push(foldable_range);
10922 }
10923
10924 start_row = nested_end_row + 1;
10925 }
10926 None => start_row += 1,
10927 }
10928 }
10929 }
10930
10931 self.fold_ranges(fold_ranges, true, cx);
10932 }
10933
10934 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10935 let mut fold_ranges = Vec::new();
10936 let snapshot = self.buffer.read(cx).snapshot(cx);
10937
10938 for row in 0..snapshot.max_buffer_row().0 {
10939 if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10940 fold_ranges.push(foldable_range);
10941 }
10942 }
10943
10944 self.fold_ranges(fold_ranges, true, cx);
10945 }
10946
10947 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10948 let mut fold_ranges = Vec::new();
10949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10950 let selections = self.selections.all_adjusted(cx);
10951
10952 for selection in selections {
10953 let range = selection.range().sorted();
10954 let buffer_start_row = range.start.row;
10955
10956 if range.start.row != range.end.row {
10957 let mut found = false;
10958 for row in range.start.row..=range.end.row {
10959 if let Some((foldable_range, fold_text)) =
10960 { display_map.foldable_range(MultiBufferRow(row)) }
10961 {
10962 found = true;
10963 fold_ranges.push((foldable_range, fold_text));
10964 }
10965 }
10966 if found {
10967 continue;
10968 }
10969 }
10970
10971 for row in (0..=range.start.row).rev() {
10972 if let Some((foldable_range, fold_text)) =
10973 display_map.foldable_range(MultiBufferRow(row))
10974 {
10975 if foldable_range.end.row >= buffer_start_row {
10976 fold_ranges.push((foldable_range, fold_text));
10977 } else {
10978 break;
10979 }
10980 }
10981 }
10982 }
10983
10984 self.fold_ranges(fold_ranges, true, cx);
10985 }
10986
10987 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10988 let buffer_row = fold_at.buffer_row;
10989 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10990
10991 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10992 let autoscroll = self
10993 .selections
10994 .all::<Point>(cx)
10995 .iter()
10996 .any(|selection| fold_range.overlaps(&selection.range()));
10997
10998 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10999 }
11000 }
11001
11002 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11003 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11004 let buffer = &display_map.buffer_snapshot;
11005 let selections = self.selections.all::<Point>(cx);
11006 let ranges = selections
11007 .iter()
11008 .map(|s| {
11009 let range = s.display_range(&display_map).sorted();
11010 let mut start = range.start.to_point(&display_map);
11011 let mut end = range.end.to_point(&display_map);
11012 start.column = 0;
11013 end.column = buffer.line_len(MultiBufferRow(end.row));
11014 start..end
11015 })
11016 .collect::<Vec<_>>();
11017
11018 self.unfold_ranges(&ranges, true, true, cx);
11019 }
11020
11021 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11022 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11023 let selections = self.selections.all::<Point>(cx);
11024 let ranges = selections
11025 .iter()
11026 .map(|s| {
11027 let mut range = s.display_range(&display_map).sorted();
11028 *range.start.column_mut() = 0;
11029 *range.end.column_mut() = display_map.line_len(range.end.row());
11030 let start = range.start.to_point(&display_map);
11031 let end = range.end.to_point(&display_map);
11032 start..end
11033 })
11034 .collect::<Vec<_>>();
11035
11036 self.unfold_ranges(&ranges, true, true, cx);
11037 }
11038
11039 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11040 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11041
11042 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11043 ..Point::new(
11044 unfold_at.buffer_row.0,
11045 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11046 );
11047
11048 let autoscroll = self
11049 .selections
11050 .all::<Point>(cx)
11051 .iter()
11052 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11053
11054 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11055 }
11056
11057 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11058 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11059 self.unfold_ranges(
11060 &[Point::zero()..display_map.max_point().to_point(&display_map)],
11061 true,
11062 true,
11063 cx,
11064 );
11065 }
11066
11067 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11068 let selections = self.selections.all::<Point>(cx);
11069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11070 let line_mode = self.selections.line_mode;
11071 let ranges = selections.into_iter().map(|s| {
11072 if line_mode {
11073 let start = Point::new(s.start.row, 0);
11074 let end = Point::new(
11075 s.end.row,
11076 display_map
11077 .buffer_snapshot
11078 .line_len(MultiBufferRow(s.end.row)),
11079 );
11080 (start..end, display_map.fold_placeholder.clone())
11081 } else {
11082 (s.start..s.end, display_map.fold_placeholder.clone())
11083 }
11084 });
11085 self.fold_ranges(ranges, true, cx);
11086 }
11087
11088 pub fn fold_ranges<T: ToOffset + Clone>(
11089 &mut self,
11090 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11091 auto_scroll: bool,
11092 cx: &mut ViewContext<Self>,
11093 ) {
11094 let mut fold_ranges = Vec::new();
11095 let mut buffers_affected = HashMap::default();
11096 let multi_buffer = self.buffer().read(cx);
11097 for (fold_range, fold_text) in ranges {
11098 if let Some((_, buffer, _)) =
11099 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11100 {
11101 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11102 };
11103 fold_ranges.push((fold_range, fold_text));
11104 }
11105
11106 let mut ranges = fold_ranges.into_iter().peekable();
11107 if ranges.peek().is_some() {
11108 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11109
11110 if auto_scroll {
11111 self.request_autoscroll(Autoscroll::fit(), cx);
11112 }
11113
11114 for buffer in buffers_affected.into_values() {
11115 self.sync_expanded_diff_hunks(buffer, cx);
11116 }
11117
11118 cx.notify();
11119
11120 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11121 // Clear diagnostics block when folding a range that contains it.
11122 let snapshot = self.snapshot(cx);
11123 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11124 drop(snapshot);
11125 self.active_diagnostics = Some(active_diagnostics);
11126 self.dismiss_diagnostics(cx);
11127 } else {
11128 self.active_diagnostics = Some(active_diagnostics);
11129 }
11130 }
11131
11132 self.scrollbar_marker_state.dirty = true;
11133 }
11134 }
11135
11136 /// Removes any folds whose ranges intersect any of the given ranges.
11137 pub fn unfold_ranges<T: ToOffset + Clone>(
11138 &mut self,
11139 ranges: &[Range<T>],
11140 inclusive: bool,
11141 auto_scroll: bool,
11142 cx: &mut ViewContext<Self>,
11143 ) {
11144 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11145 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11146 });
11147 }
11148
11149 /// Removes any folds with the given ranges.
11150 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11151 &mut self,
11152 ranges: &[Range<T>],
11153 type_id: TypeId,
11154 auto_scroll: bool,
11155 cx: &mut ViewContext<Self>,
11156 ) {
11157 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11158 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11159 });
11160 }
11161
11162 fn remove_folds_with<T: ToOffset + Clone>(
11163 &mut self,
11164 ranges: &[Range<T>],
11165 auto_scroll: bool,
11166 cx: &mut ViewContext<Self>,
11167 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11168 ) {
11169 if ranges.is_empty() {
11170 return;
11171 }
11172
11173 let mut buffers_affected = HashMap::default();
11174 let multi_buffer = self.buffer().read(cx);
11175 for range in ranges {
11176 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11177 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11178 };
11179 }
11180
11181 self.display_map.update(cx, update);
11182 if auto_scroll {
11183 self.request_autoscroll(Autoscroll::fit(), cx);
11184 }
11185
11186 for buffer in buffers_affected.into_values() {
11187 self.sync_expanded_diff_hunks(buffer, cx);
11188 }
11189
11190 cx.notify();
11191 self.scrollbar_marker_state.dirty = true;
11192 self.active_indent_guides_state.dirty = true;
11193 }
11194
11195 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11196 self.display_map.read(cx).fold_placeholder.clone()
11197 }
11198
11199 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11200 if hovered != self.gutter_hovered {
11201 self.gutter_hovered = hovered;
11202 cx.notify();
11203 }
11204 }
11205
11206 pub fn insert_blocks(
11207 &mut self,
11208 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11209 autoscroll: Option<Autoscroll>,
11210 cx: &mut ViewContext<Self>,
11211 ) -> Vec<CustomBlockId> {
11212 let blocks = self
11213 .display_map
11214 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11215 if let Some(autoscroll) = autoscroll {
11216 self.request_autoscroll(autoscroll, cx);
11217 }
11218 cx.notify();
11219 blocks
11220 }
11221
11222 pub fn resize_blocks(
11223 &mut self,
11224 heights: HashMap<CustomBlockId, u32>,
11225 autoscroll: Option<Autoscroll>,
11226 cx: &mut ViewContext<Self>,
11227 ) {
11228 self.display_map
11229 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11230 if let Some(autoscroll) = autoscroll {
11231 self.request_autoscroll(autoscroll, cx);
11232 }
11233 cx.notify();
11234 }
11235
11236 pub fn replace_blocks(
11237 &mut self,
11238 renderers: HashMap<CustomBlockId, RenderBlock>,
11239 autoscroll: Option<Autoscroll>,
11240 cx: &mut ViewContext<Self>,
11241 ) {
11242 self.display_map
11243 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11244 if let Some(autoscroll) = autoscroll {
11245 self.request_autoscroll(autoscroll, cx);
11246 }
11247 cx.notify();
11248 }
11249
11250 pub fn remove_blocks(
11251 &mut self,
11252 block_ids: HashSet<CustomBlockId>,
11253 autoscroll: Option<Autoscroll>,
11254 cx: &mut ViewContext<Self>,
11255 ) {
11256 self.display_map.update(cx, |display_map, cx| {
11257 display_map.remove_blocks(block_ids, cx)
11258 });
11259 if let Some(autoscroll) = autoscroll {
11260 self.request_autoscroll(autoscroll, cx);
11261 }
11262 cx.notify();
11263 }
11264
11265 pub fn row_for_block(
11266 &self,
11267 block_id: CustomBlockId,
11268 cx: &mut ViewContext<Self>,
11269 ) -> Option<DisplayRow> {
11270 self.display_map
11271 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11272 }
11273
11274 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11275 self.focused_block = Some(focused_block);
11276 }
11277
11278 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11279 self.focused_block.take()
11280 }
11281
11282 pub fn insert_creases(
11283 &mut self,
11284 creases: impl IntoIterator<Item = Crease>,
11285 cx: &mut ViewContext<Self>,
11286 ) -> Vec<CreaseId> {
11287 self.display_map
11288 .update(cx, |map, cx| map.insert_creases(creases, cx))
11289 }
11290
11291 pub fn remove_creases(
11292 &mut self,
11293 ids: impl IntoIterator<Item = CreaseId>,
11294 cx: &mut ViewContext<Self>,
11295 ) {
11296 self.display_map
11297 .update(cx, |map, cx| map.remove_creases(ids, cx));
11298 }
11299
11300 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11301 self.display_map
11302 .update(cx, |map, cx| map.snapshot(cx))
11303 .longest_row()
11304 }
11305
11306 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11307 self.display_map
11308 .update(cx, |map, cx| map.snapshot(cx))
11309 .max_point()
11310 }
11311
11312 pub fn text(&self, cx: &AppContext) -> String {
11313 self.buffer.read(cx).read(cx).text()
11314 }
11315
11316 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11317 let text = self.text(cx);
11318 let text = text.trim();
11319
11320 if text.is_empty() {
11321 return None;
11322 }
11323
11324 Some(text.to_string())
11325 }
11326
11327 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11328 self.transact(cx, |this, cx| {
11329 this.buffer
11330 .read(cx)
11331 .as_singleton()
11332 .expect("you can only call set_text on editors for singleton buffers")
11333 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11334 });
11335 }
11336
11337 pub fn display_text(&self, cx: &mut AppContext) -> String {
11338 self.display_map
11339 .update(cx, |map, cx| map.snapshot(cx))
11340 .text()
11341 }
11342
11343 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11344 let mut wrap_guides = smallvec::smallvec![];
11345
11346 if self.show_wrap_guides == Some(false) {
11347 return wrap_guides;
11348 }
11349
11350 let settings = self.buffer.read(cx).settings_at(0, cx);
11351 if settings.show_wrap_guides {
11352 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11353 wrap_guides.push((soft_wrap as usize, true));
11354 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11355 wrap_guides.push((soft_wrap as usize, true));
11356 }
11357 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11358 }
11359
11360 wrap_guides
11361 }
11362
11363 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11364 let settings = self.buffer.read(cx).settings_at(0, cx);
11365 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11366 match mode {
11367 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11368 SoftWrap::None
11369 }
11370 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11371 language_settings::SoftWrap::PreferredLineLength => {
11372 SoftWrap::Column(settings.preferred_line_length)
11373 }
11374 language_settings::SoftWrap::Bounded => {
11375 SoftWrap::Bounded(settings.preferred_line_length)
11376 }
11377 }
11378 }
11379
11380 pub fn set_soft_wrap_mode(
11381 &mut self,
11382 mode: language_settings::SoftWrap,
11383 cx: &mut ViewContext<Self>,
11384 ) {
11385 self.soft_wrap_mode_override = Some(mode);
11386 cx.notify();
11387 }
11388
11389 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11390 self.text_style_refinement = Some(style);
11391 }
11392
11393 /// called by the Element so we know what style we were most recently rendered with.
11394 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11395 let rem_size = cx.rem_size();
11396 self.display_map.update(cx, |map, cx| {
11397 map.set_font(
11398 style.text.font(),
11399 style.text.font_size.to_pixels(rem_size),
11400 cx,
11401 )
11402 });
11403 self.style = Some(style);
11404 }
11405
11406 pub fn style(&self) -> Option<&EditorStyle> {
11407 self.style.as_ref()
11408 }
11409
11410 // Called by the element. This method is not designed to be called outside of the editor
11411 // element's layout code because it does not notify when rewrapping is computed synchronously.
11412 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11413 self.display_map
11414 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11415 }
11416
11417 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11418 if self.soft_wrap_mode_override.is_some() {
11419 self.soft_wrap_mode_override.take();
11420 } else {
11421 let soft_wrap = match self.soft_wrap_mode(cx) {
11422 SoftWrap::GitDiff => return,
11423 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11424 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11425 language_settings::SoftWrap::None
11426 }
11427 };
11428 self.soft_wrap_mode_override = Some(soft_wrap);
11429 }
11430 cx.notify();
11431 }
11432
11433 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11434 let Some(workspace) = self.workspace() else {
11435 return;
11436 };
11437 let fs = workspace.read(cx).app_state().fs.clone();
11438 let current_show = TabBarSettings::get_global(cx).show;
11439 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11440 setting.show = Some(!current_show);
11441 });
11442 }
11443
11444 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11445 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11446 self.buffer
11447 .read(cx)
11448 .settings_at(0, cx)
11449 .indent_guides
11450 .enabled
11451 });
11452 self.show_indent_guides = Some(!currently_enabled);
11453 cx.notify();
11454 }
11455
11456 fn should_show_indent_guides(&self) -> Option<bool> {
11457 self.show_indent_guides
11458 }
11459
11460 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11461 let mut editor_settings = EditorSettings::get_global(cx).clone();
11462 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11463 EditorSettings::override_global(editor_settings, cx);
11464 }
11465
11466 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11467 self.use_relative_line_numbers
11468 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11469 }
11470
11471 pub fn toggle_relative_line_numbers(
11472 &mut self,
11473 _: &ToggleRelativeLineNumbers,
11474 cx: &mut ViewContext<Self>,
11475 ) {
11476 let is_relative = self.should_use_relative_line_numbers(cx);
11477 self.set_relative_line_number(Some(!is_relative), cx)
11478 }
11479
11480 pub fn set_relative_line_number(
11481 &mut self,
11482 is_relative: Option<bool>,
11483 cx: &mut ViewContext<Self>,
11484 ) {
11485 self.use_relative_line_numbers = is_relative;
11486 cx.notify();
11487 }
11488
11489 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11490 self.show_gutter = show_gutter;
11491 cx.notify();
11492 }
11493
11494 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11495 self.show_line_numbers = Some(show_line_numbers);
11496 cx.notify();
11497 }
11498
11499 pub fn set_show_git_diff_gutter(
11500 &mut self,
11501 show_git_diff_gutter: bool,
11502 cx: &mut ViewContext<Self>,
11503 ) {
11504 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11505 cx.notify();
11506 }
11507
11508 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11509 self.show_code_actions = Some(show_code_actions);
11510 cx.notify();
11511 }
11512
11513 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11514 self.show_runnables = Some(show_runnables);
11515 cx.notify();
11516 }
11517
11518 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11519 if self.display_map.read(cx).masked != masked {
11520 self.display_map.update(cx, |map, _| map.masked = masked);
11521 }
11522 cx.notify()
11523 }
11524
11525 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11526 self.show_wrap_guides = Some(show_wrap_guides);
11527 cx.notify();
11528 }
11529
11530 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11531 self.show_indent_guides = Some(show_indent_guides);
11532 cx.notify();
11533 }
11534
11535 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11536 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11537 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11538 if let Some(dir) = file.abs_path(cx).parent() {
11539 return Some(dir.to_owned());
11540 }
11541 }
11542
11543 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11544 return Some(project_path.path.to_path_buf());
11545 }
11546 }
11547
11548 None
11549 }
11550
11551 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11552 self.active_excerpt(cx)?
11553 .1
11554 .read(cx)
11555 .file()
11556 .and_then(|f| f.as_local())
11557 }
11558
11559 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11560 if let Some(target) = self.target_file(cx) {
11561 cx.reveal_path(&target.abs_path(cx));
11562 }
11563 }
11564
11565 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11566 if let Some(file) = self.target_file(cx) {
11567 if let Some(path) = file.abs_path(cx).to_str() {
11568 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11569 }
11570 }
11571 }
11572
11573 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11574 if let Some(file) = self.target_file(cx) {
11575 if let Some(path) = file.path().to_str() {
11576 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11577 }
11578 }
11579 }
11580
11581 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11582 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11583
11584 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11585 self.start_git_blame(true, cx);
11586 }
11587
11588 cx.notify();
11589 }
11590
11591 pub fn toggle_git_blame_inline(
11592 &mut self,
11593 _: &ToggleGitBlameInline,
11594 cx: &mut ViewContext<Self>,
11595 ) {
11596 self.toggle_git_blame_inline_internal(true, cx);
11597 cx.notify();
11598 }
11599
11600 pub fn git_blame_inline_enabled(&self) -> bool {
11601 self.git_blame_inline_enabled
11602 }
11603
11604 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11605 self.show_selection_menu = self
11606 .show_selection_menu
11607 .map(|show_selections_menu| !show_selections_menu)
11608 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11609
11610 cx.notify();
11611 }
11612
11613 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11614 self.show_selection_menu
11615 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11616 }
11617
11618 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11619 if let Some(project) = self.project.as_ref() {
11620 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11621 return;
11622 };
11623
11624 if buffer.read(cx).file().is_none() {
11625 return;
11626 }
11627
11628 let focused = self.focus_handle(cx).contains_focused(cx);
11629
11630 let project = project.clone();
11631 let blame =
11632 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11633 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11634 self.blame = Some(blame);
11635 }
11636 }
11637
11638 fn toggle_git_blame_inline_internal(
11639 &mut self,
11640 user_triggered: bool,
11641 cx: &mut ViewContext<Self>,
11642 ) {
11643 if self.git_blame_inline_enabled {
11644 self.git_blame_inline_enabled = false;
11645 self.show_git_blame_inline = false;
11646 self.show_git_blame_inline_delay_task.take();
11647 } else {
11648 self.git_blame_inline_enabled = true;
11649 self.start_git_blame_inline(user_triggered, cx);
11650 }
11651
11652 cx.notify();
11653 }
11654
11655 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11656 self.start_git_blame(user_triggered, cx);
11657
11658 if ProjectSettings::get_global(cx)
11659 .git
11660 .inline_blame_delay()
11661 .is_some()
11662 {
11663 self.start_inline_blame_timer(cx);
11664 } else {
11665 self.show_git_blame_inline = true
11666 }
11667 }
11668
11669 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11670 self.blame.as_ref()
11671 }
11672
11673 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11674 self.show_git_blame_gutter && self.has_blame_entries(cx)
11675 }
11676
11677 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11678 self.show_git_blame_inline
11679 && self.focus_handle.is_focused(cx)
11680 && !self.newest_selection_head_on_empty_line(cx)
11681 && self.has_blame_entries(cx)
11682 }
11683
11684 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11685 self.blame()
11686 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11687 }
11688
11689 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11690 let cursor_anchor = self.selections.newest_anchor().head();
11691
11692 let snapshot = self.buffer.read(cx).snapshot(cx);
11693 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11694
11695 snapshot.line_len(buffer_row) == 0
11696 }
11697
11698 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11699 let buffer_and_selection = maybe!({
11700 let selection = self.selections.newest::<Point>(cx);
11701 let selection_range = selection.range();
11702
11703 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11704 (buffer, selection_range.start.row..selection_range.end.row)
11705 } else {
11706 let buffer_ranges = self
11707 .buffer()
11708 .read(cx)
11709 .range_to_buffer_ranges(selection_range, cx);
11710
11711 let (buffer, range, _) = if selection.reversed {
11712 buffer_ranges.first()
11713 } else {
11714 buffer_ranges.last()
11715 }?;
11716
11717 let snapshot = buffer.read(cx).snapshot();
11718 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11719 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11720 (buffer.clone(), selection)
11721 };
11722
11723 Some((buffer, selection))
11724 });
11725
11726 let Some((buffer, selection)) = buffer_and_selection else {
11727 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11728 };
11729
11730 let Some(project) = self.project.as_ref() else {
11731 return Task::ready(Err(anyhow!("editor does not have project")));
11732 };
11733
11734 project.update(cx, |project, cx| {
11735 project.get_permalink_to_line(&buffer, selection, cx)
11736 })
11737 }
11738
11739 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11740 let permalink_task = self.get_permalink_to_line(cx);
11741 let workspace = self.workspace();
11742
11743 cx.spawn(|_, mut cx| async move {
11744 match permalink_task.await {
11745 Ok(permalink) => {
11746 cx.update(|cx| {
11747 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11748 })
11749 .ok();
11750 }
11751 Err(err) => {
11752 let message = format!("Failed to copy permalink: {err}");
11753
11754 Err::<(), anyhow::Error>(err).log_err();
11755
11756 if let Some(workspace) = workspace {
11757 workspace
11758 .update(&mut cx, |workspace, cx| {
11759 struct CopyPermalinkToLine;
11760
11761 workspace.show_toast(
11762 Toast::new(
11763 NotificationId::unique::<CopyPermalinkToLine>(),
11764 message,
11765 ),
11766 cx,
11767 )
11768 })
11769 .ok();
11770 }
11771 }
11772 }
11773 })
11774 .detach();
11775 }
11776
11777 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11778 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11779 if let Some(file) = self.target_file(cx) {
11780 if let Some(path) = file.path().to_str() {
11781 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11782 }
11783 }
11784 }
11785
11786 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11787 let permalink_task = self.get_permalink_to_line(cx);
11788 let workspace = self.workspace();
11789
11790 cx.spawn(|_, mut cx| async move {
11791 match permalink_task.await {
11792 Ok(permalink) => {
11793 cx.update(|cx| {
11794 cx.open_url(permalink.as_ref());
11795 })
11796 .ok();
11797 }
11798 Err(err) => {
11799 let message = format!("Failed to open permalink: {err}");
11800
11801 Err::<(), anyhow::Error>(err).log_err();
11802
11803 if let Some(workspace) = workspace {
11804 workspace
11805 .update(&mut cx, |workspace, cx| {
11806 struct OpenPermalinkToLine;
11807
11808 workspace.show_toast(
11809 Toast::new(
11810 NotificationId::unique::<OpenPermalinkToLine>(),
11811 message,
11812 ),
11813 cx,
11814 )
11815 })
11816 .ok();
11817 }
11818 }
11819 }
11820 })
11821 .detach();
11822 }
11823
11824 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11825 /// last highlight added will be used.
11826 ///
11827 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11828 pub fn highlight_rows<T: 'static>(
11829 &mut self,
11830 range: Range<Anchor>,
11831 color: Hsla,
11832 should_autoscroll: bool,
11833 cx: &mut ViewContext<Self>,
11834 ) {
11835 let snapshot = self.buffer().read(cx).snapshot(cx);
11836 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11837 let ix = row_highlights.binary_search_by(|highlight| {
11838 Ordering::Equal
11839 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11840 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11841 });
11842
11843 if let Err(mut ix) = ix {
11844 let index = post_inc(&mut self.highlight_order);
11845
11846 // If this range intersects with the preceding highlight, then merge it with
11847 // the preceding highlight. Otherwise insert a new highlight.
11848 let mut merged = false;
11849 if ix > 0 {
11850 let prev_highlight = &mut row_highlights[ix - 1];
11851 if prev_highlight
11852 .range
11853 .end
11854 .cmp(&range.start, &snapshot)
11855 .is_ge()
11856 {
11857 ix -= 1;
11858 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11859 prev_highlight.range.end = range.end;
11860 }
11861 merged = true;
11862 prev_highlight.index = index;
11863 prev_highlight.color = color;
11864 prev_highlight.should_autoscroll = should_autoscroll;
11865 }
11866 }
11867
11868 if !merged {
11869 row_highlights.insert(
11870 ix,
11871 RowHighlight {
11872 range: range.clone(),
11873 index,
11874 color,
11875 should_autoscroll,
11876 },
11877 );
11878 }
11879
11880 // If any of the following highlights intersect with this one, merge them.
11881 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11882 let highlight = &row_highlights[ix];
11883 if next_highlight
11884 .range
11885 .start
11886 .cmp(&highlight.range.end, &snapshot)
11887 .is_le()
11888 {
11889 if next_highlight
11890 .range
11891 .end
11892 .cmp(&highlight.range.end, &snapshot)
11893 .is_gt()
11894 {
11895 row_highlights[ix].range.end = next_highlight.range.end;
11896 }
11897 row_highlights.remove(ix + 1);
11898 } else {
11899 break;
11900 }
11901 }
11902 }
11903 }
11904
11905 /// Remove any highlighted row ranges of the given type that intersect the
11906 /// given ranges.
11907 pub fn remove_highlighted_rows<T: 'static>(
11908 &mut self,
11909 ranges_to_remove: Vec<Range<Anchor>>,
11910 cx: &mut ViewContext<Self>,
11911 ) {
11912 let snapshot = self.buffer().read(cx).snapshot(cx);
11913 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11914 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11915 row_highlights.retain(|highlight| {
11916 while let Some(range_to_remove) = ranges_to_remove.peek() {
11917 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11918 Ordering::Less | Ordering::Equal => {
11919 ranges_to_remove.next();
11920 }
11921 Ordering::Greater => {
11922 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11923 Ordering::Less | Ordering::Equal => {
11924 return false;
11925 }
11926 Ordering::Greater => break,
11927 }
11928 }
11929 }
11930 }
11931
11932 true
11933 })
11934 }
11935
11936 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11937 pub fn clear_row_highlights<T: 'static>(&mut self) {
11938 self.highlighted_rows.remove(&TypeId::of::<T>());
11939 }
11940
11941 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11942 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11943 self.highlighted_rows
11944 .get(&TypeId::of::<T>())
11945 .map_or(&[] as &[_], |vec| vec.as_slice())
11946 .iter()
11947 .map(|highlight| (highlight.range.clone(), highlight.color))
11948 }
11949
11950 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11951 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11952 /// Allows to ignore certain kinds of highlights.
11953 pub fn highlighted_display_rows(
11954 &mut self,
11955 cx: &mut WindowContext,
11956 ) -> BTreeMap<DisplayRow, Hsla> {
11957 let snapshot = self.snapshot(cx);
11958 let mut used_highlight_orders = HashMap::default();
11959 self.highlighted_rows
11960 .iter()
11961 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11962 .fold(
11963 BTreeMap::<DisplayRow, Hsla>::new(),
11964 |mut unique_rows, highlight| {
11965 let start = highlight.range.start.to_display_point(&snapshot);
11966 let end = highlight.range.end.to_display_point(&snapshot);
11967 let start_row = start.row().0;
11968 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11969 && end.column() == 0
11970 {
11971 end.row().0.saturating_sub(1)
11972 } else {
11973 end.row().0
11974 };
11975 for row in start_row..=end_row {
11976 let used_index =
11977 used_highlight_orders.entry(row).or_insert(highlight.index);
11978 if highlight.index >= *used_index {
11979 *used_index = highlight.index;
11980 unique_rows.insert(DisplayRow(row), highlight.color);
11981 }
11982 }
11983 unique_rows
11984 },
11985 )
11986 }
11987
11988 pub fn highlighted_display_row_for_autoscroll(
11989 &self,
11990 snapshot: &DisplaySnapshot,
11991 ) -> Option<DisplayRow> {
11992 self.highlighted_rows
11993 .values()
11994 .flat_map(|highlighted_rows| highlighted_rows.iter())
11995 .filter_map(|highlight| {
11996 if highlight.should_autoscroll {
11997 Some(highlight.range.start.to_display_point(snapshot).row())
11998 } else {
11999 None
12000 }
12001 })
12002 .min()
12003 }
12004
12005 pub fn set_search_within_ranges(
12006 &mut self,
12007 ranges: &[Range<Anchor>],
12008 cx: &mut ViewContext<Self>,
12009 ) {
12010 self.highlight_background::<SearchWithinRange>(
12011 ranges,
12012 |colors| colors.editor_document_highlight_read_background,
12013 cx,
12014 )
12015 }
12016
12017 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12018 self.breadcrumb_header = Some(new_header);
12019 }
12020
12021 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12022 self.clear_background_highlights::<SearchWithinRange>(cx);
12023 }
12024
12025 pub fn highlight_background<T: 'static>(
12026 &mut self,
12027 ranges: &[Range<Anchor>],
12028 color_fetcher: fn(&ThemeColors) -> Hsla,
12029 cx: &mut ViewContext<Self>,
12030 ) {
12031 self.background_highlights
12032 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12033 self.scrollbar_marker_state.dirty = true;
12034 cx.notify();
12035 }
12036
12037 pub fn clear_background_highlights<T: 'static>(
12038 &mut self,
12039 cx: &mut ViewContext<Self>,
12040 ) -> Option<BackgroundHighlight> {
12041 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12042 if !text_highlights.1.is_empty() {
12043 self.scrollbar_marker_state.dirty = true;
12044 cx.notify();
12045 }
12046 Some(text_highlights)
12047 }
12048
12049 pub fn highlight_gutter<T: 'static>(
12050 &mut self,
12051 ranges: &[Range<Anchor>],
12052 color_fetcher: fn(&AppContext) -> Hsla,
12053 cx: &mut ViewContext<Self>,
12054 ) {
12055 self.gutter_highlights
12056 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12057 cx.notify();
12058 }
12059
12060 pub fn clear_gutter_highlights<T: 'static>(
12061 &mut self,
12062 cx: &mut ViewContext<Self>,
12063 ) -> Option<GutterHighlight> {
12064 cx.notify();
12065 self.gutter_highlights.remove(&TypeId::of::<T>())
12066 }
12067
12068 #[cfg(feature = "test-support")]
12069 pub fn all_text_background_highlights(
12070 &mut self,
12071 cx: &mut ViewContext<Self>,
12072 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12073 let snapshot = self.snapshot(cx);
12074 let buffer = &snapshot.buffer_snapshot;
12075 let start = buffer.anchor_before(0);
12076 let end = buffer.anchor_after(buffer.len());
12077 let theme = cx.theme().colors();
12078 self.background_highlights_in_range(start..end, &snapshot, theme)
12079 }
12080
12081 #[cfg(feature = "test-support")]
12082 pub fn search_background_highlights(
12083 &mut self,
12084 cx: &mut ViewContext<Self>,
12085 ) -> Vec<Range<Point>> {
12086 let snapshot = self.buffer().read(cx).snapshot(cx);
12087
12088 let highlights = self
12089 .background_highlights
12090 .get(&TypeId::of::<items::BufferSearchHighlights>());
12091
12092 if let Some((_color, ranges)) = highlights {
12093 ranges
12094 .iter()
12095 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12096 .collect_vec()
12097 } else {
12098 vec![]
12099 }
12100 }
12101
12102 fn document_highlights_for_position<'a>(
12103 &'a self,
12104 position: Anchor,
12105 buffer: &'a MultiBufferSnapshot,
12106 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12107 let read_highlights = self
12108 .background_highlights
12109 .get(&TypeId::of::<DocumentHighlightRead>())
12110 .map(|h| &h.1);
12111 let write_highlights = self
12112 .background_highlights
12113 .get(&TypeId::of::<DocumentHighlightWrite>())
12114 .map(|h| &h.1);
12115 let left_position = position.bias_left(buffer);
12116 let right_position = position.bias_right(buffer);
12117 read_highlights
12118 .into_iter()
12119 .chain(write_highlights)
12120 .flat_map(move |ranges| {
12121 let start_ix = match ranges.binary_search_by(|probe| {
12122 let cmp = probe.end.cmp(&left_position, buffer);
12123 if cmp.is_ge() {
12124 Ordering::Greater
12125 } else {
12126 Ordering::Less
12127 }
12128 }) {
12129 Ok(i) | Err(i) => i,
12130 };
12131
12132 ranges[start_ix..]
12133 .iter()
12134 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12135 })
12136 }
12137
12138 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12139 self.background_highlights
12140 .get(&TypeId::of::<T>())
12141 .map_or(false, |(_, highlights)| !highlights.is_empty())
12142 }
12143
12144 pub fn background_highlights_in_range(
12145 &self,
12146 search_range: Range<Anchor>,
12147 display_snapshot: &DisplaySnapshot,
12148 theme: &ThemeColors,
12149 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12150 let mut results = Vec::new();
12151 for (color_fetcher, ranges) in self.background_highlights.values() {
12152 let color = color_fetcher(theme);
12153 let start_ix = match ranges.binary_search_by(|probe| {
12154 let cmp = probe
12155 .end
12156 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12157 if cmp.is_gt() {
12158 Ordering::Greater
12159 } else {
12160 Ordering::Less
12161 }
12162 }) {
12163 Ok(i) | Err(i) => i,
12164 };
12165 for range in &ranges[start_ix..] {
12166 if range
12167 .start
12168 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12169 .is_ge()
12170 {
12171 break;
12172 }
12173
12174 let start = range.start.to_display_point(display_snapshot);
12175 let end = range.end.to_display_point(display_snapshot);
12176 results.push((start..end, color))
12177 }
12178 }
12179 results
12180 }
12181
12182 pub fn background_highlight_row_ranges<T: 'static>(
12183 &self,
12184 search_range: Range<Anchor>,
12185 display_snapshot: &DisplaySnapshot,
12186 count: usize,
12187 ) -> Vec<RangeInclusive<DisplayPoint>> {
12188 let mut results = Vec::new();
12189 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12190 return vec![];
12191 };
12192
12193 let start_ix = match ranges.binary_search_by(|probe| {
12194 let cmp = probe
12195 .end
12196 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12197 if cmp.is_gt() {
12198 Ordering::Greater
12199 } else {
12200 Ordering::Less
12201 }
12202 }) {
12203 Ok(i) | Err(i) => i,
12204 };
12205 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12206 if let (Some(start_display), Some(end_display)) = (start, end) {
12207 results.push(
12208 start_display.to_display_point(display_snapshot)
12209 ..=end_display.to_display_point(display_snapshot),
12210 );
12211 }
12212 };
12213 let mut start_row: Option<Point> = None;
12214 let mut end_row: Option<Point> = None;
12215 if ranges.len() > count {
12216 return Vec::new();
12217 }
12218 for range in &ranges[start_ix..] {
12219 if range
12220 .start
12221 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12222 .is_ge()
12223 {
12224 break;
12225 }
12226 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12227 if let Some(current_row) = &end_row {
12228 if end.row == current_row.row {
12229 continue;
12230 }
12231 }
12232 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12233 if start_row.is_none() {
12234 assert_eq!(end_row, None);
12235 start_row = Some(start);
12236 end_row = Some(end);
12237 continue;
12238 }
12239 if let Some(current_end) = end_row.as_mut() {
12240 if start.row > current_end.row + 1 {
12241 push_region(start_row, end_row);
12242 start_row = Some(start);
12243 end_row = Some(end);
12244 } else {
12245 // Merge two hunks.
12246 *current_end = end;
12247 }
12248 } else {
12249 unreachable!();
12250 }
12251 }
12252 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12253 push_region(start_row, end_row);
12254 results
12255 }
12256
12257 pub fn gutter_highlights_in_range(
12258 &self,
12259 search_range: Range<Anchor>,
12260 display_snapshot: &DisplaySnapshot,
12261 cx: &AppContext,
12262 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12263 let mut results = Vec::new();
12264 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12265 let color = color_fetcher(cx);
12266 let start_ix = match ranges.binary_search_by(|probe| {
12267 let cmp = probe
12268 .end
12269 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12270 if cmp.is_gt() {
12271 Ordering::Greater
12272 } else {
12273 Ordering::Less
12274 }
12275 }) {
12276 Ok(i) | Err(i) => i,
12277 };
12278 for range in &ranges[start_ix..] {
12279 if range
12280 .start
12281 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12282 .is_ge()
12283 {
12284 break;
12285 }
12286
12287 let start = range.start.to_display_point(display_snapshot);
12288 let end = range.end.to_display_point(display_snapshot);
12289 results.push((start..end, color))
12290 }
12291 }
12292 results
12293 }
12294
12295 /// Get the text ranges corresponding to the redaction query
12296 pub fn redacted_ranges(
12297 &self,
12298 search_range: Range<Anchor>,
12299 display_snapshot: &DisplaySnapshot,
12300 cx: &WindowContext,
12301 ) -> Vec<Range<DisplayPoint>> {
12302 display_snapshot
12303 .buffer_snapshot
12304 .redacted_ranges(search_range, |file| {
12305 if let Some(file) = file {
12306 file.is_private()
12307 && EditorSettings::get(
12308 Some(SettingsLocation {
12309 worktree_id: file.worktree_id(cx),
12310 path: file.path().as_ref(),
12311 }),
12312 cx,
12313 )
12314 .redact_private_values
12315 } else {
12316 false
12317 }
12318 })
12319 .map(|range| {
12320 range.start.to_display_point(display_snapshot)
12321 ..range.end.to_display_point(display_snapshot)
12322 })
12323 .collect()
12324 }
12325
12326 pub fn highlight_text<T: 'static>(
12327 &mut self,
12328 ranges: Vec<Range<Anchor>>,
12329 style: HighlightStyle,
12330 cx: &mut ViewContext<Self>,
12331 ) {
12332 self.display_map.update(cx, |map, _| {
12333 map.highlight_text(TypeId::of::<T>(), ranges, style)
12334 });
12335 cx.notify();
12336 }
12337
12338 pub(crate) fn highlight_inlays<T: 'static>(
12339 &mut self,
12340 highlights: Vec<InlayHighlight>,
12341 style: HighlightStyle,
12342 cx: &mut ViewContext<Self>,
12343 ) {
12344 self.display_map.update(cx, |map, _| {
12345 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12346 });
12347 cx.notify();
12348 }
12349
12350 pub fn text_highlights<'a, T: 'static>(
12351 &'a self,
12352 cx: &'a AppContext,
12353 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12354 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12355 }
12356
12357 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12358 let cleared = self
12359 .display_map
12360 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12361 if cleared {
12362 cx.notify();
12363 }
12364 }
12365
12366 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12367 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12368 && self.focus_handle.is_focused(cx)
12369 }
12370
12371 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12372 self.show_cursor_when_unfocused = is_enabled;
12373 cx.notify();
12374 }
12375
12376 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12377 cx.notify();
12378 }
12379
12380 fn on_buffer_event(
12381 &mut self,
12382 multibuffer: Model<MultiBuffer>,
12383 event: &multi_buffer::Event,
12384 cx: &mut ViewContext<Self>,
12385 ) {
12386 match event {
12387 multi_buffer::Event::Edited {
12388 singleton_buffer_edited,
12389 } => {
12390 self.scrollbar_marker_state.dirty = true;
12391 self.active_indent_guides_state.dirty = true;
12392 self.refresh_active_diagnostics(cx);
12393 self.refresh_code_actions(cx);
12394 if self.has_active_inline_completion(cx) {
12395 self.update_visible_inline_completion(cx);
12396 }
12397 cx.emit(EditorEvent::BufferEdited);
12398 cx.emit(SearchEvent::MatchesInvalidated);
12399 if *singleton_buffer_edited {
12400 if let Some(project) = &self.project {
12401 let project = project.read(cx);
12402 #[allow(clippy::mutable_key_type)]
12403 let languages_affected = multibuffer
12404 .read(cx)
12405 .all_buffers()
12406 .into_iter()
12407 .filter_map(|buffer| {
12408 let buffer = buffer.read(cx);
12409 let language = buffer.language()?;
12410 if project.is_local()
12411 && project.language_servers_for_buffer(buffer, cx).count() == 0
12412 {
12413 None
12414 } else {
12415 Some(language)
12416 }
12417 })
12418 .cloned()
12419 .collect::<HashSet<_>>();
12420 if !languages_affected.is_empty() {
12421 self.refresh_inlay_hints(
12422 InlayHintRefreshReason::BufferEdited(languages_affected),
12423 cx,
12424 );
12425 }
12426 }
12427 }
12428
12429 let Some(project) = &self.project else { return };
12430 let (telemetry, is_via_ssh) = {
12431 let project = project.read(cx);
12432 let telemetry = project.client().telemetry().clone();
12433 let is_via_ssh = project.is_via_ssh();
12434 (telemetry, is_via_ssh)
12435 };
12436 refresh_linked_ranges(self, cx);
12437 telemetry.log_edit_event("editor", is_via_ssh);
12438 }
12439 multi_buffer::Event::ExcerptsAdded {
12440 buffer,
12441 predecessor,
12442 excerpts,
12443 } => {
12444 self.tasks_update_task = Some(self.refresh_runnables(cx));
12445 cx.emit(EditorEvent::ExcerptsAdded {
12446 buffer: buffer.clone(),
12447 predecessor: *predecessor,
12448 excerpts: excerpts.clone(),
12449 });
12450 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12451 }
12452 multi_buffer::Event::ExcerptsRemoved { ids } => {
12453 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12454 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12455 }
12456 multi_buffer::Event::ExcerptsEdited { ids } => {
12457 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12458 }
12459 multi_buffer::Event::ExcerptsExpanded { ids } => {
12460 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12461 }
12462 multi_buffer::Event::Reparsed(buffer_id) => {
12463 self.tasks_update_task = Some(self.refresh_runnables(cx));
12464
12465 cx.emit(EditorEvent::Reparsed(*buffer_id));
12466 }
12467 multi_buffer::Event::LanguageChanged(buffer_id) => {
12468 linked_editing_ranges::refresh_linked_ranges(self, cx);
12469 cx.emit(EditorEvent::Reparsed(*buffer_id));
12470 cx.notify();
12471 }
12472 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12473 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12474 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12475 cx.emit(EditorEvent::TitleChanged)
12476 }
12477 multi_buffer::Event::DiffBaseChanged => {
12478 self.scrollbar_marker_state.dirty = true;
12479 cx.emit(EditorEvent::DiffBaseChanged);
12480 cx.notify();
12481 }
12482 multi_buffer::Event::DiffUpdated { buffer } => {
12483 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12484 cx.notify();
12485 }
12486 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12487 multi_buffer::Event::DiagnosticsUpdated => {
12488 self.refresh_active_diagnostics(cx);
12489 self.scrollbar_marker_state.dirty = true;
12490 cx.notify();
12491 }
12492 _ => {}
12493 };
12494 }
12495
12496 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12497 cx.notify();
12498 }
12499
12500 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12501 self.tasks_update_task = Some(self.refresh_runnables(cx));
12502 self.refresh_inline_completion(true, false, cx);
12503 self.refresh_inlay_hints(
12504 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12505 self.selections.newest_anchor().head(),
12506 &self.buffer.read(cx).snapshot(cx),
12507 cx,
12508 )),
12509 cx,
12510 );
12511
12512 let old_cursor_shape = self.cursor_shape;
12513
12514 {
12515 let editor_settings = EditorSettings::get_global(cx);
12516 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12517 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12518 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12519 }
12520
12521 if old_cursor_shape != self.cursor_shape {
12522 cx.emit(EditorEvent::CursorShapeChanged);
12523 }
12524
12525 let project_settings = ProjectSettings::get_global(cx);
12526 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12527
12528 if self.mode == EditorMode::Full {
12529 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12530 if self.git_blame_inline_enabled != inline_blame_enabled {
12531 self.toggle_git_blame_inline_internal(false, cx);
12532 }
12533 }
12534
12535 cx.notify();
12536 }
12537
12538 pub fn set_searchable(&mut self, searchable: bool) {
12539 self.searchable = searchable;
12540 }
12541
12542 pub fn searchable(&self) -> bool {
12543 self.searchable
12544 }
12545
12546 fn open_proposed_changes_editor(
12547 &mut self,
12548 _: &OpenProposedChangesEditor,
12549 cx: &mut ViewContext<Self>,
12550 ) {
12551 let Some(workspace) = self.workspace() else {
12552 cx.propagate();
12553 return;
12554 };
12555
12556 let selections = self.selections.all::<usize>(cx);
12557 let buffer = self.buffer.read(cx);
12558 let mut new_selections_by_buffer = HashMap::default();
12559 for selection in selections {
12560 for (buffer, range, _) in
12561 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12562 {
12563 let mut range = range.to_point(buffer.read(cx));
12564 range.start.column = 0;
12565 range.end.column = buffer.read(cx).line_len(range.end.row);
12566 new_selections_by_buffer
12567 .entry(buffer)
12568 .or_insert(Vec::new())
12569 .push(range)
12570 }
12571 }
12572
12573 let proposed_changes_buffers = new_selections_by_buffer
12574 .into_iter()
12575 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12576 .collect::<Vec<_>>();
12577 let proposed_changes_editor = cx.new_view(|cx| {
12578 ProposedChangesEditor::new(
12579 "Proposed changes",
12580 proposed_changes_buffers,
12581 self.project.clone(),
12582 cx,
12583 )
12584 });
12585
12586 cx.window_context().defer(move |cx| {
12587 workspace.update(cx, |workspace, cx| {
12588 workspace.active_pane().update(cx, |pane, cx| {
12589 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12590 });
12591 });
12592 });
12593 }
12594
12595 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12596 self.open_excerpts_common(None, true, cx)
12597 }
12598
12599 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12600 self.open_excerpts_common(None, false, cx)
12601 }
12602
12603 fn open_excerpts_common(
12604 &mut self,
12605 jump_data: Option<JumpData>,
12606 split: bool,
12607 cx: &mut ViewContext<Self>,
12608 ) {
12609 let Some(workspace) = self.workspace() else {
12610 cx.propagate();
12611 return;
12612 };
12613
12614 if self.buffer.read(cx).is_singleton() {
12615 cx.propagate();
12616 return;
12617 }
12618
12619 let mut new_selections_by_buffer = HashMap::default();
12620 match &jump_data {
12621 Some(jump_data) => {
12622 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12623 if let Some(buffer) = multi_buffer_snapshot
12624 .buffer_id_for_excerpt(jump_data.excerpt_id)
12625 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12626 {
12627 let buffer_snapshot = buffer.read(cx).snapshot();
12628 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12629 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12630 } else {
12631 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12632 };
12633 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12634 new_selections_by_buffer.insert(
12635 buffer,
12636 (
12637 vec![jump_to_offset..jump_to_offset],
12638 Some(jump_data.line_offset_from_top),
12639 ),
12640 );
12641 }
12642 }
12643 None => {
12644 let selections = self.selections.all::<usize>(cx);
12645 let buffer = self.buffer.read(cx);
12646 for selection in selections {
12647 for (mut buffer_handle, mut range, _) in
12648 buffer.range_to_buffer_ranges(selection.range(), cx)
12649 {
12650 // When editing branch buffers, jump to the corresponding location
12651 // in their base buffer.
12652 let buffer = buffer_handle.read(cx);
12653 if let Some(base_buffer) = buffer.diff_base_buffer() {
12654 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12655 buffer_handle = base_buffer;
12656 }
12657
12658 if selection.reversed {
12659 mem::swap(&mut range.start, &mut range.end);
12660 }
12661 new_selections_by_buffer
12662 .entry(buffer_handle)
12663 .or_insert((Vec::new(), None))
12664 .0
12665 .push(range)
12666 }
12667 }
12668 }
12669 }
12670
12671 if new_selections_by_buffer.is_empty() {
12672 return;
12673 }
12674
12675 // We defer the pane interaction because we ourselves are a workspace item
12676 // and activating a new item causes the pane to call a method on us reentrantly,
12677 // which panics if we're on the stack.
12678 cx.window_context().defer(move |cx| {
12679 workspace.update(cx, |workspace, cx| {
12680 let pane = if split {
12681 workspace.adjacent_pane(cx)
12682 } else {
12683 workspace.active_pane().clone()
12684 };
12685
12686 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12687 let editor =
12688 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12689 editor.update(cx, |editor, cx| {
12690 let autoscroll = match scroll_offset {
12691 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12692 None => Autoscroll::newest(),
12693 };
12694 let nav_history = editor.nav_history.take();
12695 editor.change_selections(Some(autoscroll), cx, |s| {
12696 s.select_ranges(ranges);
12697 });
12698 editor.nav_history = nav_history;
12699 });
12700 }
12701 })
12702 });
12703 }
12704
12705 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12706 let snapshot = self.buffer.read(cx).read(cx);
12707 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12708 Some(
12709 ranges
12710 .iter()
12711 .map(move |range| {
12712 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12713 })
12714 .collect(),
12715 )
12716 }
12717
12718 fn selection_replacement_ranges(
12719 &self,
12720 range: Range<OffsetUtf16>,
12721 cx: &mut AppContext,
12722 ) -> Vec<Range<OffsetUtf16>> {
12723 let selections = self.selections.all::<OffsetUtf16>(cx);
12724 let newest_selection = selections
12725 .iter()
12726 .max_by_key(|selection| selection.id)
12727 .unwrap();
12728 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12729 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12730 let snapshot = self.buffer.read(cx).read(cx);
12731 selections
12732 .into_iter()
12733 .map(|mut selection| {
12734 selection.start.0 =
12735 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12736 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12737 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12738 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12739 })
12740 .collect()
12741 }
12742
12743 fn report_editor_event(
12744 &self,
12745 operation: &'static str,
12746 file_extension: Option<String>,
12747 cx: &AppContext,
12748 ) {
12749 if cfg!(any(test, feature = "test-support")) {
12750 return;
12751 }
12752
12753 let Some(project) = &self.project else { return };
12754
12755 // If None, we are in a file without an extension
12756 let file = self
12757 .buffer
12758 .read(cx)
12759 .as_singleton()
12760 .and_then(|b| b.read(cx).file());
12761 let file_extension = file_extension.or(file
12762 .as_ref()
12763 .and_then(|file| Path::new(file.file_name(cx)).extension())
12764 .and_then(|e| e.to_str())
12765 .map(|a| a.to_string()));
12766
12767 let vim_mode = cx
12768 .global::<SettingsStore>()
12769 .raw_user_settings()
12770 .get("vim_mode")
12771 == Some(&serde_json::Value::Bool(true));
12772
12773 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12774 == language::language_settings::InlineCompletionProvider::Copilot;
12775 let copilot_enabled_for_language = self
12776 .buffer
12777 .read(cx)
12778 .settings_at(0, cx)
12779 .show_inline_completions;
12780
12781 let project = project.read(cx);
12782 let telemetry = project.client().telemetry().clone();
12783 telemetry.report_editor_event(
12784 file_extension,
12785 vim_mode,
12786 operation,
12787 copilot_enabled,
12788 copilot_enabled_for_language,
12789 project.is_via_ssh(),
12790 )
12791 }
12792
12793 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12794 /// with each line being an array of {text, highlight} objects.
12795 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12796 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12797 return;
12798 };
12799
12800 #[derive(Serialize)]
12801 struct Chunk<'a> {
12802 text: String,
12803 highlight: Option<&'a str>,
12804 }
12805
12806 let snapshot = buffer.read(cx).snapshot();
12807 let range = self
12808 .selected_text_range(false, cx)
12809 .and_then(|selection| {
12810 if selection.range.is_empty() {
12811 None
12812 } else {
12813 Some(selection.range)
12814 }
12815 })
12816 .unwrap_or_else(|| 0..snapshot.len());
12817
12818 let chunks = snapshot.chunks(range, true);
12819 let mut lines = Vec::new();
12820 let mut line: VecDeque<Chunk> = VecDeque::new();
12821
12822 let Some(style) = self.style.as_ref() else {
12823 return;
12824 };
12825
12826 for chunk in chunks {
12827 let highlight = chunk
12828 .syntax_highlight_id
12829 .and_then(|id| id.name(&style.syntax));
12830 let mut chunk_lines = chunk.text.split('\n').peekable();
12831 while let Some(text) = chunk_lines.next() {
12832 let mut merged_with_last_token = false;
12833 if let Some(last_token) = line.back_mut() {
12834 if last_token.highlight == highlight {
12835 last_token.text.push_str(text);
12836 merged_with_last_token = true;
12837 }
12838 }
12839
12840 if !merged_with_last_token {
12841 line.push_back(Chunk {
12842 text: text.into(),
12843 highlight,
12844 });
12845 }
12846
12847 if chunk_lines.peek().is_some() {
12848 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12849 line.pop_front();
12850 }
12851 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12852 line.pop_back();
12853 }
12854
12855 lines.push(mem::take(&mut line));
12856 }
12857 }
12858 }
12859
12860 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12861 return;
12862 };
12863 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12864 }
12865
12866 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12867 &self.inlay_hint_cache
12868 }
12869
12870 pub fn replay_insert_event(
12871 &mut self,
12872 text: &str,
12873 relative_utf16_range: Option<Range<isize>>,
12874 cx: &mut ViewContext<Self>,
12875 ) {
12876 if !self.input_enabled {
12877 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12878 return;
12879 }
12880 if let Some(relative_utf16_range) = relative_utf16_range {
12881 let selections = self.selections.all::<OffsetUtf16>(cx);
12882 self.change_selections(None, cx, |s| {
12883 let new_ranges = selections.into_iter().map(|range| {
12884 let start = OffsetUtf16(
12885 range
12886 .head()
12887 .0
12888 .saturating_add_signed(relative_utf16_range.start),
12889 );
12890 let end = OffsetUtf16(
12891 range
12892 .head()
12893 .0
12894 .saturating_add_signed(relative_utf16_range.end),
12895 );
12896 start..end
12897 });
12898 s.select_ranges(new_ranges);
12899 });
12900 }
12901
12902 self.handle_input(text, cx);
12903 }
12904
12905 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12906 let Some(provider) = self.semantics_provider.as_ref() else {
12907 return false;
12908 };
12909
12910 let mut supports = false;
12911 self.buffer().read(cx).for_each_buffer(|buffer| {
12912 supports |= provider.supports_inlay_hints(buffer, cx);
12913 });
12914 supports
12915 }
12916
12917 pub fn focus(&self, cx: &mut WindowContext) {
12918 cx.focus(&self.focus_handle)
12919 }
12920
12921 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12922 self.focus_handle.is_focused(cx)
12923 }
12924
12925 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12926 cx.emit(EditorEvent::Focused);
12927
12928 if let Some(descendant) = self
12929 .last_focused_descendant
12930 .take()
12931 .and_then(|descendant| descendant.upgrade())
12932 {
12933 cx.focus(&descendant);
12934 } else {
12935 if let Some(blame) = self.blame.as_ref() {
12936 blame.update(cx, GitBlame::focus)
12937 }
12938
12939 self.blink_manager.update(cx, BlinkManager::enable);
12940 self.show_cursor_names(cx);
12941 self.buffer.update(cx, |buffer, cx| {
12942 buffer.finalize_last_transaction(cx);
12943 if self.leader_peer_id.is_none() {
12944 buffer.set_active_selections(
12945 &self.selections.disjoint_anchors(),
12946 self.selections.line_mode,
12947 self.cursor_shape,
12948 cx,
12949 );
12950 }
12951 });
12952 }
12953 }
12954
12955 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12956 cx.emit(EditorEvent::FocusedIn)
12957 }
12958
12959 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12960 if event.blurred != self.focus_handle {
12961 self.last_focused_descendant = Some(event.blurred);
12962 }
12963 }
12964
12965 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12966 self.blink_manager.update(cx, BlinkManager::disable);
12967 self.buffer
12968 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12969
12970 if let Some(blame) = self.blame.as_ref() {
12971 blame.update(cx, GitBlame::blur)
12972 }
12973 if !self.hover_state.focused(cx) {
12974 hide_hover(self, cx);
12975 }
12976
12977 self.hide_context_menu(cx);
12978 cx.emit(EditorEvent::Blurred);
12979 cx.notify();
12980 }
12981
12982 pub fn register_action<A: Action>(
12983 &mut self,
12984 listener: impl Fn(&A, &mut WindowContext) + 'static,
12985 ) -> Subscription {
12986 let id = self.next_editor_action_id.post_inc();
12987 let listener = Arc::new(listener);
12988 self.editor_actions.borrow_mut().insert(
12989 id,
12990 Box::new(move |cx| {
12991 let cx = cx.window_context();
12992 let listener = listener.clone();
12993 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12994 let action = action.downcast_ref().unwrap();
12995 if phase == DispatchPhase::Bubble {
12996 listener(action, cx)
12997 }
12998 })
12999 }),
13000 );
13001
13002 let editor_actions = self.editor_actions.clone();
13003 Subscription::new(move || {
13004 editor_actions.borrow_mut().remove(&id);
13005 })
13006 }
13007
13008 pub fn file_header_size(&self) -> u32 {
13009 FILE_HEADER_HEIGHT
13010 }
13011
13012 pub fn revert(
13013 &mut self,
13014 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13015 cx: &mut ViewContext<Self>,
13016 ) {
13017 self.buffer().update(cx, |multi_buffer, cx| {
13018 for (buffer_id, changes) in revert_changes {
13019 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13020 buffer.update(cx, |buffer, cx| {
13021 buffer.edit(
13022 changes.into_iter().map(|(range, text)| {
13023 (range, text.to_string().map(Arc::<str>::from))
13024 }),
13025 None,
13026 cx,
13027 );
13028 });
13029 }
13030 }
13031 });
13032 self.change_selections(None, cx, |selections| selections.refresh());
13033 }
13034
13035 pub fn to_pixel_point(
13036 &mut self,
13037 source: multi_buffer::Anchor,
13038 editor_snapshot: &EditorSnapshot,
13039 cx: &mut ViewContext<Self>,
13040 ) -> Option<gpui::Point<Pixels>> {
13041 let source_point = source.to_display_point(editor_snapshot);
13042 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13043 }
13044
13045 pub fn display_to_pixel_point(
13046 &mut self,
13047 source: DisplayPoint,
13048 editor_snapshot: &EditorSnapshot,
13049 cx: &mut ViewContext<Self>,
13050 ) -> Option<gpui::Point<Pixels>> {
13051 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13052 let text_layout_details = self.text_layout_details(cx);
13053 let scroll_top = text_layout_details
13054 .scroll_anchor
13055 .scroll_position(editor_snapshot)
13056 .y;
13057
13058 if source.row().as_f32() < scroll_top.floor() {
13059 return None;
13060 }
13061 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13062 let source_y = line_height * (source.row().as_f32() - scroll_top);
13063 Some(gpui::Point::new(source_x, source_y))
13064 }
13065
13066 pub fn has_active_completions_menu(&self) -> bool {
13067 self.context_menu.read().as_ref().map_or(false, |menu| {
13068 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13069 })
13070 }
13071
13072 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13073 self.addons
13074 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13075 }
13076
13077 pub fn unregister_addon<T: Addon>(&mut self) {
13078 self.addons.remove(&std::any::TypeId::of::<T>());
13079 }
13080
13081 pub fn addon<T: Addon>(&self) -> Option<&T> {
13082 let type_id = std::any::TypeId::of::<T>();
13083 self.addons
13084 .get(&type_id)
13085 .and_then(|item| item.to_any().downcast_ref::<T>())
13086 }
13087}
13088
13089fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13090 let tab_size = tab_size.get() as usize;
13091 let mut width = offset;
13092
13093 for ch in text.chars() {
13094 width += if ch == '\t' {
13095 tab_size - (width % tab_size)
13096 } else {
13097 1
13098 };
13099 }
13100
13101 width - offset
13102}
13103
13104#[cfg(test)]
13105mod tests {
13106 use super::*;
13107
13108 #[test]
13109 fn test_string_size_with_expanded_tabs() {
13110 let nz = |val| NonZeroU32::new(val).unwrap();
13111 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13112 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13113 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13114 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13115 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13116 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13117 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13118 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13119 }
13120}
13121
13122/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13123struct WordBreakingTokenizer<'a> {
13124 input: &'a str,
13125}
13126
13127impl<'a> WordBreakingTokenizer<'a> {
13128 fn new(input: &'a str) -> Self {
13129 Self { input }
13130 }
13131}
13132
13133fn is_char_ideographic(ch: char) -> bool {
13134 use unicode_script::Script::*;
13135 use unicode_script::UnicodeScript;
13136 matches!(ch.script(), Han | Tangut | Yi)
13137}
13138
13139fn is_grapheme_ideographic(text: &str) -> bool {
13140 text.chars().any(is_char_ideographic)
13141}
13142
13143fn is_grapheme_whitespace(text: &str) -> bool {
13144 text.chars().any(|x| x.is_whitespace())
13145}
13146
13147fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13148 text.chars().next().map_or(false, |ch| {
13149 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13150 })
13151}
13152
13153#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13154struct WordBreakToken<'a> {
13155 token: &'a str,
13156 grapheme_len: usize,
13157 is_whitespace: bool,
13158}
13159
13160impl<'a> Iterator for WordBreakingTokenizer<'a> {
13161 /// Yields a span, the count of graphemes in the token, and whether it was
13162 /// whitespace. Note that it also breaks at word boundaries.
13163 type Item = WordBreakToken<'a>;
13164
13165 fn next(&mut self) -> Option<Self::Item> {
13166 use unicode_segmentation::UnicodeSegmentation;
13167 if self.input.is_empty() {
13168 return None;
13169 }
13170
13171 let mut iter = self.input.graphemes(true).peekable();
13172 let mut offset = 0;
13173 let mut graphemes = 0;
13174 if let Some(first_grapheme) = iter.next() {
13175 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13176 offset += first_grapheme.len();
13177 graphemes += 1;
13178 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13179 if let Some(grapheme) = iter.peek().copied() {
13180 if should_stay_with_preceding_ideograph(grapheme) {
13181 offset += grapheme.len();
13182 graphemes += 1;
13183 }
13184 }
13185 } else {
13186 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13187 let mut next_word_bound = words.peek().copied();
13188 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13189 next_word_bound = words.next();
13190 }
13191 while let Some(grapheme) = iter.peek().copied() {
13192 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13193 break;
13194 };
13195 if is_grapheme_whitespace(grapheme) != is_whitespace {
13196 break;
13197 };
13198 offset += grapheme.len();
13199 graphemes += 1;
13200 iter.next();
13201 }
13202 }
13203 let token = &self.input[..offset];
13204 self.input = &self.input[offset..];
13205 if is_whitespace {
13206 Some(WordBreakToken {
13207 token: " ",
13208 grapheme_len: 1,
13209 is_whitespace: true,
13210 })
13211 } else {
13212 Some(WordBreakToken {
13213 token,
13214 grapheme_len: graphemes,
13215 is_whitespace: false,
13216 })
13217 }
13218 } else {
13219 None
13220 }
13221 }
13222}
13223
13224#[test]
13225fn test_word_breaking_tokenizer() {
13226 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13227 ("", &[]),
13228 (" ", &[(" ", 1, true)]),
13229 ("Ʒ", &[("Ʒ", 1, false)]),
13230 ("Ǽ", &[("Ǽ", 1, false)]),
13231 ("⋑", &[("⋑", 1, false)]),
13232 ("⋑⋑", &[("⋑⋑", 2, false)]),
13233 (
13234 "原理,进而",
13235 &[
13236 ("原", 1, false),
13237 ("理,", 2, false),
13238 ("进", 1, false),
13239 ("而", 1, false),
13240 ],
13241 ),
13242 (
13243 "hello world",
13244 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13245 ),
13246 (
13247 "hello, world",
13248 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13249 ),
13250 (
13251 " hello world",
13252 &[
13253 (" ", 1, true),
13254 ("hello", 5, false),
13255 (" ", 1, true),
13256 ("world", 5, false),
13257 ],
13258 ),
13259 (
13260 "这是什么 \n 钢笔",
13261 &[
13262 ("这", 1, false),
13263 ("是", 1, false),
13264 ("什", 1, false),
13265 ("么", 1, false),
13266 (" ", 1, true),
13267 ("钢", 1, false),
13268 ("笔", 1, false),
13269 ],
13270 ),
13271 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13272 ];
13273
13274 for (input, result) in tests {
13275 assert_eq!(
13276 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13277 result
13278 .iter()
13279 .copied()
13280 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13281 token,
13282 grapheme_len,
13283 is_whitespace,
13284 })
13285 .collect::<Vec<_>>()
13286 );
13287 }
13288}
13289
13290fn wrap_with_prefix(
13291 line_prefix: String,
13292 unwrapped_text: String,
13293 wrap_column: usize,
13294 tab_size: NonZeroU32,
13295) -> String {
13296 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13297 let mut wrapped_text = String::new();
13298 let mut current_line = line_prefix.clone();
13299
13300 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13301 let mut current_line_len = line_prefix_len;
13302 for WordBreakToken {
13303 token,
13304 grapheme_len,
13305 is_whitespace,
13306 } in tokenizer
13307 {
13308 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13309 wrapped_text.push_str(current_line.trim_end());
13310 wrapped_text.push('\n');
13311 current_line.truncate(line_prefix.len());
13312 current_line_len = line_prefix_len;
13313 if !is_whitespace {
13314 current_line.push_str(token);
13315 current_line_len += grapheme_len;
13316 }
13317 } else if !is_whitespace {
13318 current_line.push_str(token);
13319 current_line_len += grapheme_len;
13320 } else if current_line_len != line_prefix_len {
13321 current_line.push(' ');
13322 current_line_len += 1;
13323 }
13324 }
13325
13326 if !current_line.is_empty() {
13327 wrapped_text.push_str(¤t_line);
13328 }
13329 wrapped_text
13330}
13331
13332#[test]
13333fn test_wrap_with_prefix() {
13334 assert_eq!(
13335 wrap_with_prefix(
13336 "# ".to_string(),
13337 "abcdefg".to_string(),
13338 4,
13339 NonZeroU32::new(4).unwrap()
13340 ),
13341 "# abcdefg"
13342 );
13343 assert_eq!(
13344 wrap_with_prefix(
13345 "".to_string(),
13346 "\thello world".to_string(),
13347 8,
13348 NonZeroU32::new(4).unwrap()
13349 ),
13350 "hello\nworld"
13351 );
13352 assert_eq!(
13353 wrap_with_prefix(
13354 "// ".to_string(),
13355 "xx \nyy zz aa bb cc".to_string(),
13356 12,
13357 NonZeroU32::new(4).unwrap()
13358 ),
13359 "// xx yy zz\n// aa bb cc"
13360 );
13361 assert_eq!(
13362 wrap_with_prefix(
13363 String::new(),
13364 "这是什么 \n 钢笔".to_string(),
13365 3,
13366 NonZeroU32::new(4).unwrap()
13367 ),
13368 "这是什\n么 钢\n笔"
13369 );
13370}
13371
13372fn hunks_for_selections(
13373 multi_buffer_snapshot: &MultiBufferSnapshot,
13374 selections: &[Selection<Anchor>],
13375) -> Vec<MultiBufferDiffHunk> {
13376 let buffer_rows_for_selections = selections.iter().map(|selection| {
13377 let head = selection.head();
13378 let tail = selection.tail();
13379 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13380 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13381 if start > end {
13382 end..start
13383 } else {
13384 start..end
13385 }
13386 });
13387
13388 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13389}
13390
13391pub fn hunks_for_rows(
13392 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13393 multi_buffer_snapshot: &MultiBufferSnapshot,
13394) -> Vec<MultiBufferDiffHunk> {
13395 let mut hunks = Vec::new();
13396 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13397 HashMap::default();
13398 for selected_multi_buffer_rows in rows {
13399 let query_rows =
13400 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13401 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13402 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13403 // when the caret is just above or just below the deleted hunk.
13404 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13405 let related_to_selection = if allow_adjacent {
13406 hunk.row_range.overlaps(&query_rows)
13407 || hunk.row_range.start == query_rows.end
13408 || hunk.row_range.end == query_rows.start
13409 } else {
13410 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13411 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13412 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13413 || selected_multi_buffer_rows.end == hunk.row_range.start
13414 };
13415 if related_to_selection {
13416 if !processed_buffer_rows
13417 .entry(hunk.buffer_id)
13418 .or_default()
13419 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13420 {
13421 continue;
13422 }
13423 hunks.push(hunk);
13424 }
13425 }
13426 }
13427
13428 hunks
13429}
13430
13431pub trait CollaborationHub {
13432 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13433 fn user_participant_indices<'a>(
13434 &self,
13435 cx: &'a AppContext,
13436 ) -> &'a HashMap<u64, ParticipantIndex>;
13437 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13438}
13439
13440impl CollaborationHub for Model<Project> {
13441 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13442 self.read(cx).collaborators()
13443 }
13444
13445 fn user_participant_indices<'a>(
13446 &self,
13447 cx: &'a AppContext,
13448 ) -> &'a HashMap<u64, ParticipantIndex> {
13449 self.read(cx).user_store().read(cx).participant_indices()
13450 }
13451
13452 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13453 let this = self.read(cx);
13454 let user_ids = this.collaborators().values().map(|c| c.user_id);
13455 this.user_store().read_with(cx, |user_store, cx| {
13456 user_store.participant_names(user_ids, cx)
13457 })
13458 }
13459}
13460
13461pub trait SemanticsProvider {
13462 fn hover(
13463 &self,
13464 buffer: &Model<Buffer>,
13465 position: text::Anchor,
13466 cx: &mut AppContext,
13467 ) -> Option<Task<Vec<project::Hover>>>;
13468
13469 fn inlay_hints(
13470 &self,
13471 buffer_handle: Model<Buffer>,
13472 range: Range<text::Anchor>,
13473 cx: &mut AppContext,
13474 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13475
13476 fn resolve_inlay_hint(
13477 &self,
13478 hint: InlayHint,
13479 buffer_handle: Model<Buffer>,
13480 server_id: LanguageServerId,
13481 cx: &mut AppContext,
13482 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13483
13484 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13485
13486 fn document_highlights(
13487 &self,
13488 buffer: &Model<Buffer>,
13489 position: text::Anchor,
13490 cx: &mut AppContext,
13491 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13492
13493 fn definitions(
13494 &self,
13495 buffer: &Model<Buffer>,
13496 position: text::Anchor,
13497 kind: GotoDefinitionKind,
13498 cx: &mut AppContext,
13499 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13500
13501 fn range_for_rename(
13502 &self,
13503 buffer: &Model<Buffer>,
13504 position: text::Anchor,
13505 cx: &mut AppContext,
13506 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13507
13508 fn perform_rename(
13509 &self,
13510 buffer: &Model<Buffer>,
13511 position: text::Anchor,
13512 new_name: String,
13513 cx: &mut AppContext,
13514 ) -> Option<Task<Result<ProjectTransaction>>>;
13515}
13516
13517pub trait CompletionProvider {
13518 fn completions(
13519 &self,
13520 buffer: &Model<Buffer>,
13521 buffer_position: text::Anchor,
13522 trigger: CompletionContext,
13523 cx: &mut ViewContext<Editor>,
13524 ) -> Task<Result<Vec<Completion>>>;
13525
13526 fn resolve_completions(
13527 &self,
13528 buffer: Model<Buffer>,
13529 completion_indices: Vec<usize>,
13530 completions: Arc<RwLock<Box<[Completion]>>>,
13531 cx: &mut ViewContext<Editor>,
13532 ) -> Task<Result<bool>>;
13533
13534 fn apply_additional_edits_for_completion(
13535 &self,
13536 buffer: Model<Buffer>,
13537 completion: Completion,
13538 push_to_history: bool,
13539 cx: &mut ViewContext<Editor>,
13540 ) -> Task<Result<Option<language::Transaction>>>;
13541
13542 fn is_completion_trigger(
13543 &self,
13544 buffer: &Model<Buffer>,
13545 position: language::Anchor,
13546 text: &str,
13547 trigger_in_words: bool,
13548 cx: &mut ViewContext<Editor>,
13549 ) -> bool;
13550
13551 fn sort_completions(&self) -> bool {
13552 true
13553 }
13554}
13555
13556pub trait CodeActionProvider {
13557 fn code_actions(
13558 &self,
13559 buffer: &Model<Buffer>,
13560 range: Range<text::Anchor>,
13561 cx: &mut WindowContext,
13562 ) -> Task<Result<Vec<CodeAction>>>;
13563
13564 fn apply_code_action(
13565 &self,
13566 buffer_handle: Model<Buffer>,
13567 action: CodeAction,
13568 excerpt_id: ExcerptId,
13569 push_to_history: bool,
13570 cx: &mut WindowContext,
13571 ) -> Task<Result<ProjectTransaction>>;
13572}
13573
13574impl CodeActionProvider for Model<Project> {
13575 fn code_actions(
13576 &self,
13577 buffer: &Model<Buffer>,
13578 range: Range<text::Anchor>,
13579 cx: &mut WindowContext,
13580 ) -> Task<Result<Vec<CodeAction>>> {
13581 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13582 }
13583
13584 fn apply_code_action(
13585 &self,
13586 buffer_handle: Model<Buffer>,
13587 action: CodeAction,
13588 _excerpt_id: ExcerptId,
13589 push_to_history: bool,
13590 cx: &mut WindowContext,
13591 ) -> Task<Result<ProjectTransaction>> {
13592 self.update(cx, |project, cx| {
13593 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13594 })
13595 }
13596}
13597
13598fn snippet_completions(
13599 project: &Project,
13600 buffer: &Model<Buffer>,
13601 buffer_position: text::Anchor,
13602 cx: &mut AppContext,
13603) -> Vec<Completion> {
13604 let language = buffer.read(cx).language_at(buffer_position);
13605 let language_name = language.as_ref().map(|language| language.lsp_id());
13606 let snippet_store = project.snippets().read(cx);
13607 let snippets = snippet_store.snippets_for(language_name, cx);
13608
13609 if snippets.is_empty() {
13610 return vec![];
13611 }
13612 let snapshot = buffer.read(cx).text_snapshot();
13613 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13614
13615 let scope = language.map(|language| language.default_scope());
13616 let classifier = CharClassifier::new(scope).for_completion(true);
13617 let mut last_word = chars
13618 .take_while(|c| classifier.is_word(*c))
13619 .collect::<String>();
13620 last_word = last_word.chars().rev().collect();
13621 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13622 let to_lsp = |point: &text::Anchor| {
13623 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13624 point_to_lsp(end)
13625 };
13626 let lsp_end = to_lsp(&buffer_position);
13627 snippets
13628 .into_iter()
13629 .filter_map(|snippet| {
13630 let matching_prefix = snippet
13631 .prefix
13632 .iter()
13633 .find(|prefix| prefix.starts_with(&last_word))?;
13634 let start = as_offset - last_word.len();
13635 let start = snapshot.anchor_before(start);
13636 let range = start..buffer_position;
13637 let lsp_start = to_lsp(&start);
13638 let lsp_range = lsp::Range {
13639 start: lsp_start,
13640 end: lsp_end,
13641 };
13642 Some(Completion {
13643 old_range: range,
13644 new_text: snippet.body.clone(),
13645 label: CodeLabel {
13646 text: matching_prefix.clone(),
13647 runs: vec![],
13648 filter_range: 0..matching_prefix.len(),
13649 },
13650 server_id: LanguageServerId(usize::MAX),
13651 documentation: snippet.description.clone().map(Documentation::SingleLine),
13652 lsp_completion: lsp::CompletionItem {
13653 label: snippet.prefix.first().unwrap().clone(),
13654 kind: Some(CompletionItemKind::SNIPPET),
13655 label_details: snippet.description.as_ref().map(|description| {
13656 lsp::CompletionItemLabelDetails {
13657 detail: Some(description.clone()),
13658 description: None,
13659 }
13660 }),
13661 insert_text_format: Some(InsertTextFormat::SNIPPET),
13662 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13663 lsp::InsertReplaceEdit {
13664 new_text: snippet.body.clone(),
13665 insert: lsp_range,
13666 replace: lsp_range,
13667 },
13668 )),
13669 filter_text: Some(snippet.body.clone()),
13670 sort_text: Some(char::MAX.to_string()),
13671 ..Default::default()
13672 },
13673 confirm: None,
13674 })
13675 })
13676 .collect()
13677}
13678
13679impl CompletionProvider for Model<Project> {
13680 fn completions(
13681 &self,
13682 buffer: &Model<Buffer>,
13683 buffer_position: text::Anchor,
13684 options: CompletionContext,
13685 cx: &mut ViewContext<Editor>,
13686 ) -> Task<Result<Vec<Completion>>> {
13687 self.update(cx, |project, cx| {
13688 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13689 let project_completions = project.completions(buffer, buffer_position, options, cx);
13690 cx.background_executor().spawn(async move {
13691 let mut completions = project_completions.await?;
13692 //let snippets = snippets.into_iter().;
13693 completions.extend(snippets);
13694 Ok(completions)
13695 })
13696 })
13697 }
13698
13699 fn resolve_completions(
13700 &self,
13701 buffer: Model<Buffer>,
13702 completion_indices: Vec<usize>,
13703 completions: Arc<RwLock<Box<[Completion]>>>,
13704 cx: &mut ViewContext<Editor>,
13705 ) -> Task<Result<bool>> {
13706 self.update(cx, |project, cx| {
13707 project.resolve_completions(buffer, completion_indices, completions, cx)
13708 })
13709 }
13710
13711 fn apply_additional_edits_for_completion(
13712 &self,
13713 buffer: Model<Buffer>,
13714 completion: Completion,
13715 push_to_history: bool,
13716 cx: &mut ViewContext<Editor>,
13717 ) -> Task<Result<Option<language::Transaction>>> {
13718 self.update(cx, |project, cx| {
13719 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13720 })
13721 }
13722
13723 fn is_completion_trigger(
13724 &self,
13725 buffer: &Model<Buffer>,
13726 position: language::Anchor,
13727 text: &str,
13728 trigger_in_words: bool,
13729 cx: &mut ViewContext<Editor>,
13730 ) -> bool {
13731 if !EditorSettings::get_global(cx).show_completions_on_input {
13732 return false;
13733 }
13734
13735 let mut chars = text.chars();
13736 let char = if let Some(char) = chars.next() {
13737 char
13738 } else {
13739 return false;
13740 };
13741 if chars.next().is_some() {
13742 return false;
13743 }
13744
13745 let buffer = buffer.read(cx);
13746 let classifier = buffer
13747 .snapshot()
13748 .char_classifier_at(position)
13749 .for_completion(true);
13750 if trigger_in_words && classifier.is_word(char) {
13751 return true;
13752 }
13753
13754 buffer.completion_triggers().contains(text)
13755 }
13756}
13757
13758impl SemanticsProvider for Model<Project> {
13759 fn hover(
13760 &self,
13761 buffer: &Model<Buffer>,
13762 position: text::Anchor,
13763 cx: &mut AppContext,
13764 ) -> Option<Task<Vec<project::Hover>>> {
13765 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13766 }
13767
13768 fn document_highlights(
13769 &self,
13770 buffer: &Model<Buffer>,
13771 position: text::Anchor,
13772 cx: &mut AppContext,
13773 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13774 Some(self.update(cx, |project, cx| {
13775 project.document_highlights(buffer, position, cx)
13776 }))
13777 }
13778
13779 fn definitions(
13780 &self,
13781 buffer: &Model<Buffer>,
13782 position: text::Anchor,
13783 kind: GotoDefinitionKind,
13784 cx: &mut AppContext,
13785 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13786 Some(self.update(cx, |project, cx| match kind {
13787 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13788 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13789 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13790 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13791 }))
13792 }
13793
13794 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13795 // TODO: make this work for remote projects
13796 self.read(cx)
13797 .language_servers_for_buffer(buffer.read(cx), cx)
13798 .any(
13799 |(_, server)| match server.capabilities().inlay_hint_provider {
13800 Some(lsp::OneOf::Left(enabled)) => enabled,
13801 Some(lsp::OneOf::Right(_)) => true,
13802 None => false,
13803 },
13804 )
13805 }
13806
13807 fn inlay_hints(
13808 &self,
13809 buffer_handle: Model<Buffer>,
13810 range: Range<text::Anchor>,
13811 cx: &mut AppContext,
13812 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13813 Some(self.update(cx, |project, cx| {
13814 project.inlay_hints(buffer_handle, range, cx)
13815 }))
13816 }
13817
13818 fn resolve_inlay_hint(
13819 &self,
13820 hint: InlayHint,
13821 buffer_handle: Model<Buffer>,
13822 server_id: LanguageServerId,
13823 cx: &mut AppContext,
13824 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13825 Some(self.update(cx, |project, cx| {
13826 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13827 }))
13828 }
13829
13830 fn range_for_rename(
13831 &self,
13832 buffer: &Model<Buffer>,
13833 position: text::Anchor,
13834 cx: &mut AppContext,
13835 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13836 Some(self.update(cx, |project, cx| {
13837 project.prepare_rename(buffer.clone(), position, cx)
13838 }))
13839 }
13840
13841 fn perform_rename(
13842 &self,
13843 buffer: &Model<Buffer>,
13844 position: text::Anchor,
13845 new_name: String,
13846 cx: &mut AppContext,
13847 ) -> Option<Task<Result<ProjectTransaction>>> {
13848 Some(self.update(cx, |project, cx| {
13849 project.perform_rename(buffer.clone(), position, new_name, cx)
13850 }))
13851 }
13852}
13853
13854fn inlay_hint_settings(
13855 location: Anchor,
13856 snapshot: &MultiBufferSnapshot,
13857 cx: &mut ViewContext<'_, Editor>,
13858) -> InlayHintSettings {
13859 let file = snapshot.file_at(location);
13860 let language = snapshot.language_at(location).map(|l| l.name());
13861 language_settings(language, file, cx).inlay_hints
13862}
13863
13864fn consume_contiguous_rows(
13865 contiguous_row_selections: &mut Vec<Selection<Point>>,
13866 selection: &Selection<Point>,
13867 display_map: &DisplaySnapshot,
13868 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13869) -> (MultiBufferRow, MultiBufferRow) {
13870 contiguous_row_selections.push(selection.clone());
13871 let start_row = MultiBufferRow(selection.start.row);
13872 let mut end_row = ending_row(selection, display_map);
13873
13874 while let Some(next_selection) = selections.peek() {
13875 if next_selection.start.row <= end_row.0 {
13876 end_row = ending_row(next_selection, display_map);
13877 contiguous_row_selections.push(selections.next().unwrap().clone());
13878 } else {
13879 break;
13880 }
13881 }
13882 (start_row, end_row)
13883}
13884
13885fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13886 if next_selection.end.column > 0 || next_selection.is_empty() {
13887 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13888 } else {
13889 MultiBufferRow(next_selection.end.row)
13890 }
13891}
13892
13893impl EditorSnapshot {
13894 pub fn remote_selections_in_range<'a>(
13895 &'a self,
13896 range: &'a Range<Anchor>,
13897 collaboration_hub: &dyn CollaborationHub,
13898 cx: &'a AppContext,
13899 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13900 let participant_names = collaboration_hub.user_names(cx);
13901 let participant_indices = collaboration_hub.user_participant_indices(cx);
13902 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13903 let collaborators_by_replica_id = collaborators_by_peer_id
13904 .iter()
13905 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13906 .collect::<HashMap<_, _>>();
13907 self.buffer_snapshot
13908 .selections_in_range(range, false)
13909 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13910 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13911 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13912 let user_name = participant_names.get(&collaborator.user_id).cloned();
13913 Some(RemoteSelection {
13914 replica_id,
13915 selection,
13916 cursor_shape,
13917 line_mode,
13918 participant_index,
13919 peer_id: collaborator.peer_id,
13920 user_name,
13921 })
13922 })
13923 }
13924
13925 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13926 self.display_snapshot.buffer_snapshot.language_at(position)
13927 }
13928
13929 pub fn is_focused(&self) -> bool {
13930 self.is_focused
13931 }
13932
13933 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13934 self.placeholder_text.as_ref()
13935 }
13936
13937 pub fn scroll_position(&self) -> gpui::Point<f32> {
13938 self.scroll_anchor.scroll_position(&self.display_snapshot)
13939 }
13940
13941 fn gutter_dimensions(
13942 &self,
13943 font_id: FontId,
13944 font_size: Pixels,
13945 em_width: Pixels,
13946 em_advance: Pixels,
13947 max_line_number_width: Pixels,
13948 cx: &AppContext,
13949 ) -> GutterDimensions {
13950 if !self.show_gutter {
13951 return GutterDimensions::default();
13952 }
13953 let descent = cx.text_system().descent(font_id, font_size);
13954
13955 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13956 matches!(
13957 ProjectSettings::get_global(cx).git.git_gutter,
13958 Some(GitGutterSetting::TrackedFiles)
13959 )
13960 });
13961 let gutter_settings = EditorSettings::get_global(cx).gutter;
13962 let show_line_numbers = self
13963 .show_line_numbers
13964 .unwrap_or(gutter_settings.line_numbers);
13965 let line_gutter_width = if show_line_numbers {
13966 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13967 let min_width_for_number_on_gutter = em_advance * 4.0;
13968 max_line_number_width.max(min_width_for_number_on_gutter)
13969 } else {
13970 0.0.into()
13971 };
13972
13973 let show_code_actions = self
13974 .show_code_actions
13975 .unwrap_or(gutter_settings.code_actions);
13976
13977 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13978
13979 let git_blame_entries_width =
13980 self.git_blame_gutter_max_author_length
13981 .map(|max_author_length| {
13982 // Length of the author name, but also space for the commit hash,
13983 // the spacing and the timestamp.
13984 let max_char_count = max_author_length
13985 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13986 + 7 // length of commit sha
13987 + 14 // length of max relative timestamp ("60 minutes ago")
13988 + 4; // gaps and margins
13989
13990 em_advance * max_char_count
13991 });
13992
13993 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13994 left_padding += if show_code_actions || show_runnables {
13995 em_width * 3.0
13996 } else if show_git_gutter && show_line_numbers {
13997 em_width * 2.0
13998 } else if show_git_gutter || show_line_numbers {
13999 em_width
14000 } else {
14001 px(0.)
14002 };
14003
14004 let right_padding = if gutter_settings.folds && show_line_numbers {
14005 em_width * 4.0
14006 } else if gutter_settings.folds {
14007 em_width * 3.0
14008 } else if show_line_numbers {
14009 em_width
14010 } else {
14011 px(0.)
14012 };
14013
14014 GutterDimensions {
14015 left_padding,
14016 right_padding,
14017 width: line_gutter_width + left_padding + right_padding,
14018 margin: -descent,
14019 git_blame_entries_width,
14020 }
14021 }
14022
14023 pub fn render_fold_toggle(
14024 &self,
14025 buffer_row: MultiBufferRow,
14026 row_contains_cursor: bool,
14027 editor: View<Editor>,
14028 cx: &mut WindowContext,
14029 ) -> Option<AnyElement> {
14030 let folded = self.is_line_folded(buffer_row);
14031
14032 if let Some(crease) = self
14033 .crease_snapshot
14034 .query_row(buffer_row, &self.buffer_snapshot)
14035 {
14036 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14037 if folded {
14038 editor.update(cx, |editor, cx| {
14039 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14040 });
14041 } else {
14042 editor.update(cx, |editor, cx| {
14043 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14044 });
14045 }
14046 });
14047
14048 Some((crease.render_toggle)(
14049 buffer_row,
14050 folded,
14051 toggle_callback,
14052 cx,
14053 ))
14054 } else if folded
14055 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14056 {
14057 Some(
14058 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14059 .selected(folded)
14060 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14061 if folded {
14062 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14063 } else {
14064 this.fold_at(&FoldAt { buffer_row }, cx);
14065 }
14066 }))
14067 .into_any_element(),
14068 )
14069 } else {
14070 None
14071 }
14072 }
14073
14074 pub fn render_crease_trailer(
14075 &self,
14076 buffer_row: MultiBufferRow,
14077 cx: &mut WindowContext,
14078 ) -> Option<AnyElement> {
14079 let folded = self.is_line_folded(buffer_row);
14080 let crease = self
14081 .crease_snapshot
14082 .query_row(buffer_row, &self.buffer_snapshot)?;
14083 Some((crease.render_trailer)(buffer_row, folded, cx))
14084 }
14085}
14086
14087impl Deref for EditorSnapshot {
14088 type Target = DisplaySnapshot;
14089
14090 fn deref(&self) -> &Self::Target {
14091 &self.display_snapshot
14092 }
14093}
14094
14095#[derive(Clone, Debug, PartialEq, Eq)]
14096pub enum EditorEvent {
14097 InputIgnored {
14098 text: Arc<str>,
14099 },
14100 InputHandled {
14101 utf16_range_to_replace: Option<Range<isize>>,
14102 text: Arc<str>,
14103 },
14104 ExcerptsAdded {
14105 buffer: Model<Buffer>,
14106 predecessor: ExcerptId,
14107 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14108 },
14109 ExcerptsRemoved {
14110 ids: Vec<ExcerptId>,
14111 },
14112 ExcerptsEdited {
14113 ids: Vec<ExcerptId>,
14114 },
14115 ExcerptsExpanded {
14116 ids: Vec<ExcerptId>,
14117 },
14118 BufferEdited,
14119 Edited {
14120 transaction_id: clock::Lamport,
14121 },
14122 Reparsed(BufferId),
14123 Focused,
14124 FocusedIn,
14125 Blurred,
14126 DirtyChanged,
14127 Saved,
14128 TitleChanged,
14129 DiffBaseChanged,
14130 SelectionsChanged {
14131 local: bool,
14132 },
14133 ScrollPositionChanged {
14134 local: bool,
14135 autoscroll: bool,
14136 },
14137 Closed,
14138 TransactionUndone {
14139 transaction_id: clock::Lamport,
14140 },
14141 TransactionBegun {
14142 transaction_id: clock::Lamport,
14143 },
14144 Reloaded,
14145 CursorShapeChanged,
14146}
14147
14148impl EventEmitter<EditorEvent> for Editor {}
14149
14150impl FocusableView for Editor {
14151 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14152 self.focus_handle.clone()
14153 }
14154}
14155
14156impl Render for Editor {
14157 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14158 let settings = ThemeSettings::get_global(cx);
14159
14160 let mut text_style = match self.mode {
14161 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14162 color: cx.theme().colors().editor_foreground,
14163 font_family: settings.ui_font.family.clone(),
14164 font_features: settings.ui_font.features.clone(),
14165 font_fallbacks: settings.ui_font.fallbacks.clone(),
14166 font_size: rems(0.875).into(),
14167 font_weight: settings.ui_font.weight,
14168 line_height: relative(settings.buffer_line_height.value()),
14169 ..Default::default()
14170 },
14171 EditorMode::Full => TextStyle {
14172 color: cx.theme().colors().editor_foreground,
14173 font_family: settings.buffer_font.family.clone(),
14174 font_features: settings.buffer_font.features.clone(),
14175 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14176 font_size: settings.buffer_font_size(cx).into(),
14177 font_weight: settings.buffer_font.weight,
14178 line_height: relative(settings.buffer_line_height.value()),
14179 ..Default::default()
14180 },
14181 };
14182 if let Some(text_style_refinement) = &self.text_style_refinement {
14183 text_style.refine(text_style_refinement)
14184 }
14185
14186 let background = match self.mode {
14187 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14188 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14189 EditorMode::Full => cx.theme().colors().editor_background,
14190 };
14191
14192 EditorElement::new(
14193 cx.view(),
14194 EditorStyle {
14195 background,
14196 local_player: cx.theme().players().local(),
14197 text: text_style,
14198 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14199 syntax: cx.theme().syntax().clone(),
14200 status: cx.theme().status().clone(),
14201 inlay_hints_style: make_inlay_hints_style(cx),
14202 suggestions_style: HighlightStyle {
14203 color: Some(cx.theme().status().predictive),
14204 ..HighlightStyle::default()
14205 },
14206 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14207 },
14208 )
14209 }
14210}
14211
14212impl ViewInputHandler for Editor {
14213 fn text_for_range(
14214 &mut self,
14215 range_utf16: Range<usize>,
14216 cx: &mut ViewContext<Self>,
14217 ) -> Option<String> {
14218 Some(
14219 self.buffer
14220 .read(cx)
14221 .read(cx)
14222 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14223 .collect(),
14224 )
14225 }
14226
14227 fn selected_text_range(
14228 &mut self,
14229 ignore_disabled_input: bool,
14230 cx: &mut ViewContext<Self>,
14231 ) -> Option<UTF16Selection> {
14232 // Prevent the IME menu from appearing when holding down an alphabetic key
14233 // while input is disabled.
14234 if !ignore_disabled_input && !self.input_enabled {
14235 return None;
14236 }
14237
14238 let selection = self.selections.newest::<OffsetUtf16>(cx);
14239 let range = selection.range();
14240
14241 Some(UTF16Selection {
14242 range: range.start.0..range.end.0,
14243 reversed: selection.reversed,
14244 })
14245 }
14246
14247 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14248 let snapshot = self.buffer.read(cx).read(cx);
14249 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14250 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14251 }
14252
14253 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14254 self.clear_highlights::<InputComposition>(cx);
14255 self.ime_transaction.take();
14256 }
14257
14258 fn replace_text_in_range(
14259 &mut self,
14260 range_utf16: Option<Range<usize>>,
14261 text: &str,
14262 cx: &mut ViewContext<Self>,
14263 ) {
14264 if !self.input_enabled {
14265 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14266 return;
14267 }
14268
14269 self.transact(cx, |this, cx| {
14270 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14271 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14272 Some(this.selection_replacement_ranges(range_utf16, cx))
14273 } else {
14274 this.marked_text_ranges(cx)
14275 };
14276
14277 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14278 let newest_selection_id = this.selections.newest_anchor().id;
14279 this.selections
14280 .all::<OffsetUtf16>(cx)
14281 .iter()
14282 .zip(ranges_to_replace.iter())
14283 .find_map(|(selection, range)| {
14284 if selection.id == newest_selection_id {
14285 Some(
14286 (range.start.0 as isize - selection.head().0 as isize)
14287 ..(range.end.0 as isize - selection.head().0 as isize),
14288 )
14289 } else {
14290 None
14291 }
14292 })
14293 });
14294
14295 cx.emit(EditorEvent::InputHandled {
14296 utf16_range_to_replace: range_to_replace,
14297 text: text.into(),
14298 });
14299
14300 if let Some(new_selected_ranges) = new_selected_ranges {
14301 this.change_selections(None, cx, |selections| {
14302 selections.select_ranges(new_selected_ranges)
14303 });
14304 this.backspace(&Default::default(), cx);
14305 }
14306
14307 this.handle_input(text, cx);
14308 });
14309
14310 if let Some(transaction) = self.ime_transaction {
14311 self.buffer.update(cx, |buffer, cx| {
14312 buffer.group_until_transaction(transaction, cx);
14313 });
14314 }
14315
14316 self.unmark_text(cx);
14317 }
14318
14319 fn replace_and_mark_text_in_range(
14320 &mut self,
14321 range_utf16: Option<Range<usize>>,
14322 text: &str,
14323 new_selected_range_utf16: Option<Range<usize>>,
14324 cx: &mut ViewContext<Self>,
14325 ) {
14326 if !self.input_enabled {
14327 return;
14328 }
14329
14330 let transaction = self.transact(cx, |this, cx| {
14331 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14332 let snapshot = this.buffer.read(cx).read(cx);
14333 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14334 for marked_range in &mut marked_ranges {
14335 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14336 marked_range.start.0 += relative_range_utf16.start;
14337 marked_range.start =
14338 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14339 marked_range.end =
14340 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14341 }
14342 }
14343 Some(marked_ranges)
14344 } else if let Some(range_utf16) = range_utf16 {
14345 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14346 Some(this.selection_replacement_ranges(range_utf16, cx))
14347 } else {
14348 None
14349 };
14350
14351 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14352 let newest_selection_id = this.selections.newest_anchor().id;
14353 this.selections
14354 .all::<OffsetUtf16>(cx)
14355 .iter()
14356 .zip(ranges_to_replace.iter())
14357 .find_map(|(selection, range)| {
14358 if selection.id == newest_selection_id {
14359 Some(
14360 (range.start.0 as isize - selection.head().0 as isize)
14361 ..(range.end.0 as isize - selection.head().0 as isize),
14362 )
14363 } else {
14364 None
14365 }
14366 })
14367 });
14368
14369 cx.emit(EditorEvent::InputHandled {
14370 utf16_range_to_replace: range_to_replace,
14371 text: text.into(),
14372 });
14373
14374 if let Some(ranges) = ranges_to_replace {
14375 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14376 }
14377
14378 let marked_ranges = {
14379 let snapshot = this.buffer.read(cx).read(cx);
14380 this.selections
14381 .disjoint_anchors()
14382 .iter()
14383 .map(|selection| {
14384 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14385 })
14386 .collect::<Vec<_>>()
14387 };
14388
14389 if text.is_empty() {
14390 this.unmark_text(cx);
14391 } else {
14392 this.highlight_text::<InputComposition>(
14393 marked_ranges.clone(),
14394 HighlightStyle {
14395 underline: Some(UnderlineStyle {
14396 thickness: px(1.),
14397 color: None,
14398 wavy: false,
14399 }),
14400 ..Default::default()
14401 },
14402 cx,
14403 );
14404 }
14405
14406 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14407 let use_autoclose = this.use_autoclose;
14408 let use_auto_surround = this.use_auto_surround;
14409 this.set_use_autoclose(false);
14410 this.set_use_auto_surround(false);
14411 this.handle_input(text, cx);
14412 this.set_use_autoclose(use_autoclose);
14413 this.set_use_auto_surround(use_auto_surround);
14414
14415 if let Some(new_selected_range) = new_selected_range_utf16 {
14416 let snapshot = this.buffer.read(cx).read(cx);
14417 let new_selected_ranges = marked_ranges
14418 .into_iter()
14419 .map(|marked_range| {
14420 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14421 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14422 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14423 snapshot.clip_offset_utf16(new_start, Bias::Left)
14424 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14425 })
14426 .collect::<Vec<_>>();
14427
14428 drop(snapshot);
14429 this.change_selections(None, cx, |selections| {
14430 selections.select_ranges(new_selected_ranges)
14431 });
14432 }
14433 });
14434
14435 self.ime_transaction = self.ime_transaction.or(transaction);
14436 if let Some(transaction) = self.ime_transaction {
14437 self.buffer.update(cx, |buffer, cx| {
14438 buffer.group_until_transaction(transaction, cx);
14439 });
14440 }
14441
14442 if self.text_highlights::<InputComposition>(cx).is_none() {
14443 self.ime_transaction.take();
14444 }
14445 }
14446
14447 fn bounds_for_range(
14448 &mut self,
14449 range_utf16: Range<usize>,
14450 element_bounds: gpui::Bounds<Pixels>,
14451 cx: &mut ViewContext<Self>,
14452 ) -> Option<gpui::Bounds<Pixels>> {
14453 let text_layout_details = self.text_layout_details(cx);
14454 let style = &text_layout_details.editor_style;
14455 let font_id = cx.text_system().resolve_font(&style.text.font());
14456 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14457 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14458
14459 let em_width = cx
14460 .text_system()
14461 .typographic_bounds(font_id, font_size, 'm')
14462 .unwrap()
14463 .size
14464 .width;
14465
14466 let snapshot = self.snapshot(cx);
14467 let scroll_position = snapshot.scroll_position();
14468 let scroll_left = scroll_position.x * em_width;
14469
14470 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14471 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14472 + self.gutter_dimensions.width;
14473 let y = line_height * (start.row().as_f32() - scroll_position.y);
14474
14475 Some(Bounds {
14476 origin: element_bounds.origin + point(x, y),
14477 size: size(em_width, line_height),
14478 })
14479 }
14480}
14481
14482trait SelectionExt {
14483 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14484 fn spanned_rows(
14485 &self,
14486 include_end_if_at_line_start: bool,
14487 map: &DisplaySnapshot,
14488 ) -> Range<MultiBufferRow>;
14489}
14490
14491impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14492 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14493 let start = self
14494 .start
14495 .to_point(&map.buffer_snapshot)
14496 .to_display_point(map);
14497 let end = self
14498 .end
14499 .to_point(&map.buffer_snapshot)
14500 .to_display_point(map);
14501 if self.reversed {
14502 end..start
14503 } else {
14504 start..end
14505 }
14506 }
14507
14508 fn spanned_rows(
14509 &self,
14510 include_end_if_at_line_start: bool,
14511 map: &DisplaySnapshot,
14512 ) -> Range<MultiBufferRow> {
14513 let start = self.start.to_point(&map.buffer_snapshot);
14514 let mut end = self.end.to_point(&map.buffer_snapshot);
14515 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14516 end.row -= 1;
14517 }
14518
14519 let buffer_start = map.prev_line_boundary(start).0;
14520 let buffer_end = map.next_line_boundary(end).0;
14521 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14522 }
14523}
14524
14525impl<T: InvalidationRegion> InvalidationStack<T> {
14526 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14527 where
14528 S: Clone + ToOffset,
14529 {
14530 while let Some(region) = self.last() {
14531 let all_selections_inside_invalidation_ranges =
14532 if selections.len() == region.ranges().len() {
14533 selections
14534 .iter()
14535 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14536 .all(|(selection, invalidation_range)| {
14537 let head = selection.head().to_offset(buffer);
14538 invalidation_range.start <= head && invalidation_range.end >= head
14539 })
14540 } else {
14541 false
14542 };
14543
14544 if all_selections_inside_invalidation_ranges {
14545 break;
14546 } else {
14547 self.pop();
14548 }
14549 }
14550 }
14551}
14552
14553impl<T> Default for InvalidationStack<T> {
14554 fn default() -> Self {
14555 Self(Default::default())
14556 }
14557}
14558
14559impl<T> Deref for InvalidationStack<T> {
14560 type Target = Vec<T>;
14561
14562 fn deref(&self) -> &Self::Target {
14563 &self.0
14564 }
14565}
14566
14567impl<T> DerefMut for InvalidationStack<T> {
14568 fn deref_mut(&mut self) -> &mut Self::Target {
14569 &mut self.0
14570 }
14571}
14572
14573impl InvalidationRegion for SnippetState {
14574 fn ranges(&self) -> &[Range<Anchor>] {
14575 &self.ranges[self.active_index]
14576 }
14577}
14578
14579pub fn diagnostic_block_renderer(
14580 diagnostic: Diagnostic,
14581 max_message_rows: Option<u8>,
14582 allow_closing: bool,
14583 _is_valid: bool,
14584) -> RenderBlock {
14585 let (text_without_backticks, code_ranges) =
14586 highlight_diagnostic_message(&diagnostic, max_message_rows);
14587
14588 Box::new(move |cx: &mut BlockContext| {
14589 let group_id: SharedString = cx.block_id.to_string().into();
14590
14591 let mut text_style = cx.text_style().clone();
14592 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14593 let theme_settings = ThemeSettings::get_global(cx);
14594 text_style.font_family = theme_settings.buffer_font.family.clone();
14595 text_style.font_style = theme_settings.buffer_font.style;
14596 text_style.font_features = theme_settings.buffer_font.features.clone();
14597 text_style.font_weight = theme_settings.buffer_font.weight;
14598
14599 let multi_line_diagnostic = diagnostic.message.contains('\n');
14600
14601 let buttons = |diagnostic: &Diagnostic| {
14602 if multi_line_diagnostic {
14603 v_flex()
14604 } else {
14605 h_flex()
14606 }
14607 .when(allow_closing, |div| {
14608 div.children(diagnostic.is_primary.then(|| {
14609 IconButton::new("close-block", IconName::XCircle)
14610 .icon_color(Color::Muted)
14611 .size(ButtonSize::Compact)
14612 .style(ButtonStyle::Transparent)
14613 .visible_on_hover(group_id.clone())
14614 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14615 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14616 }))
14617 })
14618 .child(
14619 IconButton::new("copy-block", IconName::Copy)
14620 .icon_color(Color::Muted)
14621 .size(ButtonSize::Compact)
14622 .style(ButtonStyle::Transparent)
14623 .visible_on_hover(group_id.clone())
14624 .on_click({
14625 let message = diagnostic.message.clone();
14626 move |_click, cx| {
14627 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14628 }
14629 })
14630 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14631 )
14632 };
14633
14634 let icon_size = buttons(&diagnostic)
14635 .into_any_element()
14636 .layout_as_root(AvailableSpace::min_size(), cx);
14637
14638 h_flex()
14639 .id(cx.block_id)
14640 .group(group_id.clone())
14641 .relative()
14642 .size_full()
14643 .pl(cx.gutter_dimensions.width)
14644 .w(cx.max_width - cx.gutter_dimensions.full_width())
14645 .child(
14646 div()
14647 .flex()
14648 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14649 .flex_shrink(),
14650 )
14651 .child(buttons(&diagnostic))
14652 .child(div().flex().flex_shrink_0().child(
14653 StyledText::new(text_without_backticks.clone()).with_highlights(
14654 &text_style,
14655 code_ranges.iter().map(|range| {
14656 (
14657 range.clone(),
14658 HighlightStyle {
14659 font_weight: Some(FontWeight::BOLD),
14660 ..Default::default()
14661 },
14662 )
14663 }),
14664 ),
14665 ))
14666 .into_any_element()
14667 })
14668}
14669
14670pub fn highlight_diagnostic_message(
14671 diagnostic: &Diagnostic,
14672 mut max_message_rows: Option<u8>,
14673) -> (SharedString, Vec<Range<usize>>) {
14674 let mut text_without_backticks = String::new();
14675 let mut code_ranges = Vec::new();
14676
14677 if let Some(source) = &diagnostic.source {
14678 text_without_backticks.push_str(source);
14679 code_ranges.push(0..source.len());
14680 text_without_backticks.push_str(": ");
14681 }
14682
14683 let mut prev_offset = 0;
14684 let mut in_code_block = false;
14685 let has_row_limit = max_message_rows.is_some();
14686 let mut newline_indices = diagnostic
14687 .message
14688 .match_indices('\n')
14689 .filter(|_| has_row_limit)
14690 .map(|(ix, _)| ix)
14691 .fuse()
14692 .peekable();
14693
14694 for (quote_ix, _) in diagnostic
14695 .message
14696 .match_indices('`')
14697 .chain([(diagnostic.message.len(), "")])
14698 {
14699 let mut first_newline_ix = None;
14700 let mut last_newline_ix = None;
14701 while let Some(newline_ix) = newline_indices.peek() {
14702 if *newline_ix < quote_ix {
14703 if first_newline_ix.is_none() {
14704 first_newline_ix = Some(*newline_ix);
14705 }
14706 last_newline_ix = Some(*newline_ix);
14707
14708 if let Some(rows_left) = &mut max_message_rows {
14709 if *rows_left == 0 {
14710 break;
14711 } else {
14712 *rows_left -= 1;
14713 }
14714 }
14715 let _ = newline_indices.next();
14716 } else {
14717 break;
14718 }
14719 }
14720 let prev_len = text_without_backticks.len();
14721 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14722 text_without_backticks.push_str(new_text);
14723 if in_code_block {
14724 code_ranges.push(prev_len..text_without_backticks.len());
14725 }
14726 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14727 in_code_block = !in_code_block;
14728 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14729 text_without_backticks.push_str("...");
14730 break;
14731 }
14732 }
14733
14734 (text_without_backticks.into(), code_ranges)
14735}
14736
14737fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14738 match severity {
14739 DiagnosticSeverity::ERROR => colors.error,
14740 DiagnosticSeverity::WARNING => colors.warning,
14741 DiagnosticSeverity::INFORMATION => colors.info,
14742 DiagnosticSeverity::HINT => colors.info,
14743 _ => colors.ignored,
14744 }
14745}
14746
14747pub fn styled_runs_for_code_label<'a>(
14748 label: &'a CodeLabel,
14749 syntax_theme: &'a theme::SyntaxTheme,
14750) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14751 let fade_out = HighlightStyle {
14752 fade_out: Some(0.35),
14753 ..Default::default()
14754 };
14755
14756 let mut prev_end = label.filter_range.end;
14757 label
14758 .runs
14759 .iter()
14760 .enumerate()
14761 .flat_map(move |(ix, (range, highlight_id))| {
14762 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14763 style
14764 } else {
14765 return Default::default();
14766 };
14767 let mut muted_style = style;
14768 muted_style.highlight(fade_out);
14769
14770 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14771 if range.start >= label.filter_range.end {
14772 if range.start > prev_end {
14773 runs.push((prev_end..range.start, fade_out));
14774 }
14775 runs.push((range.clone(), muted_style));
14776 } else if range.end <= label.filter_range.end {
14777 runs.push((range.clone(), style));
14778 } else {
14779 runs.push((range.start..label.filter_range.end, style));
14780 runs.push((label.filter_range.end..range.end, muted_style));
14781 }
14782 prev_end = cmp::max(prev_end, range.end);
14783
14784 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14785 runs.push((prev_end..label.text.len(), fade_out));
14786 }
14787
14788 runs
14789 })
14790}
14791
14792pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14793 let mut prev_index = 0;
14794 let mut prev_codepoint: Option<char> = None;
14795 text.char_indices()
14796 .chain([(text.len(), '\0')])
14797 .filter_map(move |(index, codepoint)| {
14798 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14799 let is_boundary = index == text.len()
14800 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14801 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14802 if is_boundary {
14803 let chunk = &text[prev_index..index];
14804 prev_index = index;
14805 Some(chunk)
14806 } else {
14807 None
14808 }
14809 })
14810}
14811
14812pub trait RangeToAnchorExt: Sized {
14813 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14814
14815 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14816 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14817 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14818 }
14819}
14820
14821impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14822 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14823 let start_offset = self.start.to_offset(snapshot);
14824 let end_offset = self.end.to_offset(snapshot);
14825 if start_offset == end_offset {
14826 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14827 } else {
14828 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14829 }
14830 }
14831}
14832
14833pub trait RowExt {
14834 fn as_f32(&self) -> f32;
14835
14836 fn next_row(&self) -> Self;
14837
14838 fn previous_row(&self) -> Self;
14839
14840 fn minus(&self, other: Self) -> u32;
14841}
14842
14843impl RowExt for DisplayRow {
14844 fn as_f32(&self) -> f32 {
14845 self.0 as f32
14846 }
14847
14848 fn next_row(&self) -> Self {
14849 Self(self.0 + 1)
14850 }
14851
14852 fn previous_row(&self) -> Self {
14853 Self(self.0.saturating_sub(1))
14854 }
14855
14856 fn minus(&self, other: Self) -> u32 {
14857 self.0 - other.0
14858 }
14859}
14860
14861impl RowExt for MultiBufferRow {
14862 fn as_f32(&self) -> f32 {
14863 self.0 as f32
14864 }
14865
14866 fn next_row(&self) -> Self {
14867 Self(self.0 + 1)
14868 }
14869
14870 fn previous_row(&self) -> Self {
14871 Self(self.0.saturating_sub(1))
14872 }
14873
14874 fn minus(&self, other: Self) -> u32 {
14875 self.0 - other.0
14876 }
14877}
14878
14879trait RowRangeExt {
14880 type Row;
14881
14882 fn len(&self) -> usize;
14883
14884 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14885}
14886
14887impl RowRangeExt for Range<MultiBufferRow> {
14888 type Row = MultiBufferRow;
14889
14890 fn len(&self) -> usize {
14891 (self.end.0 - self.start.0) as usize
14892 }
14893
14894 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14895 (self.start.0..self.end.0).map(MultiBufferRow)
14896 }
14897}
14898
14899impl RowRangeExt for Range<DisplayRow> {
14900 type Row = DisplayRow;
14901
14902 fn len(&self) -> usize {
14903 (self.end.0 - self.start.0) as usize
14904 }
14905
14906 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14907 (self.start.0..self.end.0).map(DisplayRow)
14908 }
14909}
14910
14911fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14912 if hunk.diff_base_byte_range.is_empty() {
14913 DiffHunkStatus::Added
14914 } else if hunk.row_range.is_empty() {
14915 DiffHunkStatus::Removed
14916 } else {
14917 DiffHunkStatus::Modified
14918 }
14919}
14920
14921/// If select range has more than one line, we
14922/// just point the cursor to range.start.
14923fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14924 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14925 range
14926 } else {
14927 range.start..range.start
14928 }
14929}
14930
14931const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);