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 rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
80 VisualContext, WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 language_settings::{self, all_language_settings, InlayHintSettings},
93 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
94 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
95 Point, Selection, SelectionGoal, TransactionId,
96};
97use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
98use linked_editing_ranges::refresh_linked_ranges;
99use task::{ResolvedTask, TaskTemplate, TaskVariables};
100
101use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
102pub use lsp::CompletionContext;
103use lsp::{
104 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
105 LanguageServerId,
106};
107use mouse_context_menu::MouseContextMenu;
108use movement::TextLayoutDetails;
109pub use multi_buffer::{
110 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
111 ToPoint,
112};
113use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
114use ordered_float::OrderedFloat;
115use parking_lot::{Mutex, RwLock};
116use project::project_settings::{GitGutterSetting, ProjectSettings};
117use project::{
118 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
119 ProjectTransaction, TaskSourceKind,
120};
121use rand::prelude::*;
122use rpc::{proto::*, ErrorExt};
123use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
124use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
125use serde::{Deserialize, Serialize};
126use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
127use smallvec::SmallVec;
128use snippet::Snippet;
129use std::{
130 any::TypeId,
131 borrow::Cow,
132 cell::RefCell,
133 cmp::{self, Ordering, Reverse},
134 mem,
135 num::NonZeroU32,
136 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
137 path::{Path, PathBuf},
138 rc::Rc,
139 sync::Arc,
140 time::{Duration, Instant},
141};
142pub use sum_tree::Bias;
143use sum_tree::TreeMap;
144use text::{BufferId, OffsetUtf16, Rope};
145use theme::{
146 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
147 ThemeColors, ThemeSettings,
148};
149use ui::{
150 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
151 ListItem, Popover, Tooltip,
152};
153use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
154use workspace::item::{ItemHandle, PreviewTabsSettings};
155use workspace::notifications::{DetachAndPromptErr, NotificationId};
156use workspace::{
157 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
158};
159use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
160
161use crate::hover_links::find_url;
162use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
163
164pub const FILE_HEADER_HEIGHT: u32 = 1;
165pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
167pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
168const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
169const MAX_LINE_LEN: usize = 1024;
170const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
171const MAX_SELECTION_HISTORY_LEN: usize = 1024;
172pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
173#[doc(hidden)]
174pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
175#[doc(hidden)]
176pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
177
178pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
179pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
180
181pub fn render_parsed_markdown(
182 element_id: impl Into<ElementId>,
183 parsed: &language::ParsedMarkdown,
184 editor_style: &EditorStyle,
185 workspace: Option<WeakView<Workspace>>,
186 cx: &mut WindowContext,
187) -> InteractiveText {
188 let code_span_background_color = cx
189 .theme()
190 .colors()
191 .editor_document_highlight_read_background;
192
193 let highlights = gpui::combine_highlights(
194 parsed.highlights.iter().filter_map(|(range, highlight)| {
195 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
196 Some((range.clone(), highlight))
197 }),
198 parsed
199 .regions
200 .iter()
201 .zip(&parsed.region_ranges)
202 .filter_map(|(region, range)| {
203 if region.code {
204 Some((
205 range.clone(),
206 HighlightStyle {
207 background_color: Some(code_span_background_color),
208 ..Default::default()
209 },
210 ))
211 } else {
212 None
213 }
214 }),
215 );
216
217 let mut links = Vec::new();
218 let mut link_ranges = Vec::new();
219 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
220 if let Some(link) = region.link.clone() {
221 links.push(link);
222 link_ranges.push(range.clone());
223 }
224 }
225
226 InteractiveText::new(
227 element_id,
228 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
229 )
230 .on_click(link_ranges, move |clicked_range_ix, cx| {
231 match &links[clicked_range_ix] {
232 markdown::Link::Web { url } => cx.open_url(url),
233 markdown::Link::Path { path } => {
234 if let Some(workspace) = &workspace {
235 _ = workspace.update(cx, |workspace, cx| {
236 workspace.open_abs_path(path.clone(), false, cx).detach();
237 });
238 }
239 }
240 }
241 })
242}
243
244#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
245pub(crate) enum InlayId {
246 Suggestion(usize),
247 Hint(usize),
248}
249
250impl InlayId {
251 fn id(&self) -> usize {
252 match self {
253 Self::Suggestion(id) => *id,
254 Self::Hint(id) => *id,
255 }
256 }
257}
258
259enum DiffRowHighlight {}
260enum DocumentHighlightRead {}
261enum DocumentHighlightWrite {}
262enum InputComposition {}
263
264#[derive(Copy, Clone, PartialEq, Eq)]
265pub enum Direction {
266 Prev,
267 Next,
268}
269
270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
271pub enum Navigated {
272 Yes,
273 No,
274}
275
276impl Navigated {
277 pub fn from_bool(yes: bool) -> Navigated {
278 if yes {
279 Navigated::Yes
280 } else {
281 Navigated::No
282 }
283 }
284}
285
286pub fn init_settings(cx: &mut AppContext) {
287 EditorSettings::register(cx);
288}
289
290pub fn init(cx: &mut AppContext) {
291 init_settings(cx);
292
293 workspace::register_project_item::<Editor>(cx);
294 workspace::FollowableViewRegistry::register::<Editor>(cx);
295 workspace::register_serializable_item::<Editor>(cx);
296
297 cx.observe_new_views(
298 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
299 workspace.register_action(Editor::new_file);
300 workspace.register_action(Editor::new_file_vertical);
301 workspace.register_action(Editor::new_file_horizontal);
302 },
303 )
304 .detach();
305
306 cx.on_action(move |_: &workspace::NewFile, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
310 Editor::new_file(workspace, &Default::default(), cx)
311 })
312 .detach();
313 }
314 });
315 cx.on_action(move |_: &workspace::NewWindow, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324}
325
326pub struct SearchWithinRange;
327
328trait InvalidationRegion {
329 fn ranges(&self) -> &[Range<Anchor>];
330}
331
332#[derive(Clone, Debug, PartialEq)]
333pub enum SelectPhase {
334 Begin {
335 position: DisplayPoint,
336 add: bool,
337 click_count: usize,
338 },
339 BeginColumnar {
340 position: DisplayPoint,
341 reset: bool,
342 goal_column: u32,
343 },
344 Extend {
345 position: DisplayPoint,
346 click_count: usize,
347 },
348 Update {
349 position: DisplayPoint,
350 goal_column: u32,
351 scroll_delta: gpui::Point<f32>,
352 },
353 End,
354}
355
356#[derive(Clone, Debug)]
357pub enum SelectMode {
358 Character,
359 Word(Range<Anchor>),
360 Line(Range<Anchor>),
361 All,
362}
363
364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
365pub enum EditorMode {
366 SingleLine { auto_width: bool },
367 AutoHeight { max_lines: usize },
368 Full,
369}
370
371#[derive(Clone, Debug)]
372pub enum SoftWrap {
373 None,
374 PreferLine,
375 EditorWidth,
376 Column(u32),
377 Bounded(u32),
378}
379
380#[derive(Clone)]
381pub struct EditorStyle {
382 pub background: Hsla,
383 pub local_player: PlayerColor,
384 pub text: TextStyle,
385 pub scrollbar_width: Pixels,
386 pub syntax: Arc<SyntaxTheme>,
387 pub status: StatusColors,
388 pub inlay_hints_style: HighlightStyle,
389 pub suggestions_style: HighlightStyle,
390 pub unnecessary_code_fade: f32,
391}
392
393impl Default for EditorStyle {
394 fn default() -> Self {
395 Self {
396 background: Hsla::default(),
397 local_player: PlayerColor::default(),
398 text: TextStyle::default(),
399 scrollbar_width: Pixels::default(),
400 syntax: Default::default(),
401 // HACK: Status colors don't have a real default.
402 // We should look into removing the status colors from the editor
403 // style and retrieve them directly from the theme.
404 status: StatusColors::dark(),
405 inlay_hints_style: HighlightStyle::default(),
406 suggestions_style: HighlightStyle::default(),
407 unnecessary_code_fade: Default::default(),
408 }
409 }
410}
411
412type CompletionId = usize;
413
414#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
415struct EditorActionId(usize);
416
417impl EditorActionId {
418 pub fn post_inc(&mut self) -> Self {
419 let answer = self.0;
420
421 *self = Self(answer + 1);
422
423 Self(answer)
424 }
425}
426
427// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
428// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
429
430type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
431type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
432
433#[derive(Default)]
434struct ScrollbarMarkerState {
435 scrollbar_size: Size<Pixels>,
436 dirty: bool,
437 markers: Arc<[PaintQuad]>,
438 pending_refresh: Option<Task<Result<()>>>,
439}
440
441impl ScrollbarMarkerState {
442 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
443 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
444 }
445}
446
447#[derive(Clone, Debug)]
448struct RunnableTasks {
449 templates: Vec<(TaskSourceKind, TaskTemplate)>,
450 offset: MultiBufferOffset,
451 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
452 column: u32,
453 // Values of all named captures, including those starting with '_'
454 extra_variables: HashMap<String, String>,
455 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
456 context_range: Range<BufferOffset>,
457}
458
459#[derive(Clone)]
460struct ResolvedTasks {
461 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
462 position: Anchor,
463}
464#[derive(Copy, Clone, Debug)]
465struct MultiBufferOffset(usize);
466#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
467struct BufferOffset(usize);
468
469// Addons allow storing per-editor state in other crates (e.g. Vim)
470pub trait Addon: 'static {
471 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
472
473 fn to_any(&self) -> &dyn std::any::Any;
474}
475
476/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
477///
478/// See the [module level documentation](self) for more information.
479pub struct Editor {
480 focus_handle: FocusHandle,
481 last_focused_descendant: Option<WeakFocusHandle>,
482 /// The text buffer being edited
483 buffer: Model<MultiBuffer>,
484 /// Map of how text in the buffer should be displayed.
485 /// Handles soft wraps, folds, fake inlay text insertions, etc.
486 pub display_map: Model<DisplayMap>,
487 pub selections: SelectionsCollection,
488 pub scroll_manager: ScrollManager,
489 /// When inline assist editors are linked, they all render cursors because
490 /// typing enters text into each of them, even the ones that aren't focused.
491 pub(crate) show_cursor_when_unfocused: bool,
492 columnar_selection_tail: Option<Anchor>,
493 add_selections_state: Option<AddSelectionsState>,
494 select_next_state: Option<SelectNextState>,
495 select_prev_state: Option<SelectNextState>,
496 selection_history: SelectionHistory,
497 autoclose_regions: Vec<AutocloseRegion>,
498 snippet_stack: InvalidationStack<SnippetState>,
499 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
500 ime_transaction: Option<TransactionId>,
501 active_diagnostics: Option<ActiveDiagnosticGroup>,
502 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
503 project: Option<Model<Project>>,
504 completion_provider: Option<Box<dyn CompletionProvider>>,
505 collaboration_hub: Option<Box<dyn CollaborationHub>>,
506 blink_manager: Model<BlinkManager>,
507 show_cursor_names: bool,
508 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
509 pub show_local_selections: bool,
510 mode: EditorMode,
511 show_breadcrumbs: bool,
512 show_gutter: bool,
513 show_line_numbers: Option<bool>,
514 use_relative_line_numbers: Option<bool>,
515 show_git_diff_gutter: Option<bool>,
516 show_code_actions: Option<bool>,
517 show_runnables: Option<bool>,
518 show_wrap_guides: Option<bool>,
519 show_indent_guides: Option<bool>,
520 placeholder_text: Option<Arc<str>>,
521 highlight_order: usize,
522 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
523 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
524 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
525 scrollbar_marker_state: ScrollbarMarkerState,
526 active_indent_guides_state: ActiveIndentGuidesState,
527 nav_history: Option<ItemNavHistory>,
528 context_menu: RwLock<Option<ContextMenu>>,
529 mouse_context_menu: Option<MouseContextMenu>,
530 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
531 signature_help_state: SignatureHelpState,
532 auto_signature_help: Option<bool>,
533 find_all_references_task_sources: Vec<Anchor>,
534 next_completion_id: CompletionId,
535 completion_documentation_pre_resolve_debounce: DebouncedDelay,
536 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
537 code_actions_task: Option<Task<()>>,
538 document_highlights_task: Option<Task<()>>,
539 linked_editing_range_task: Option<Task<Option<()>>>,
540 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
541 pending_rename: Option<RenameState>,
542 searchable: bool,
543 cursor_shape: CursorShape,
544 current_line_highlight: Option<CurrentLineHighlight>,
545 collapse_matches: bool,
546 autoindent_mode: Option<AutoindentMode>,
547 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
548 input_enabled: bool,
549 use_modal_editing: bool,
550 read_only: bool,
551 leader_peer_id: Option<PeerId>,
552 remote_id: Option<ViewId>,
553 hover_state: HoverState,
554 gutter_hovered: bool,
555 hovered_link_state: Option<HoveredLinkState>,
556 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
557 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
558 // enable_inline_completions is a switch that Vim can use to disable
559 // inline completions based on its mode.
560 enable_inline_completions: bool,
561 show_inline_completions_override: Option<bool>,
562 inlay_hint_cache: InlayHintCache,
563 expanded_hunks: ExpandedHunks,
564 next_inlay_id: usize,
565 _subscriptions: Vec<Subscription>,
566 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
567 gutter_dimensions: GutterDimensions,
568 style: Option<EditorStyle>,
569 next_editor_action_id: EditorActionId,
570 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
571 use_autoclose: bool,
572 use_auto_surround: bool,
573 auto_replace_emoji_shortcode: bool,
574 show_git_blame_gutter: bool,
575 show_git_blame_inline: bool,
576 show_git_blame_inline_delay_task: Option<Task<()>>,
577 git_blame_inline_enabled: bool,
578 serialize_dirty_buffers: bool,
579 show_selection_menu: Option<bool>,
580 blame: Option<Model<GitBlame>>,
581 blame_subscription: Option<Subscription>,
582 custom_context_menu: Option<
583 Box<
584 dyn 'static
585 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
586 >,
587 >,
588 last_bounds: Option<Bounds<Pixels>>,
589 expect_bounds_change: Option<Bounds<Pixels>>,
590 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
591 tasks_update_task: Option<Task<()>>,
592 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
593 file_header_size: u32,
594 breadcrumb_header: Option<String>,
595 focused_block: Option<FocusedBlock>,
596 next_scroll_position: NextScrollCursorCenterTopBottom,
597 addons: HashMap<TypeId, Box<dyn Addon>>,
598 _scroll_cursor_center_top_bottom_task: Task<()>,
599}
600
601#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
602enum NextScrollCursorCenterTopBottom {
603 #[default]
604 Center,
605 Top,
606 Bottom,
607}
608
609impl NextScrollCursorCenterTopBottom {
610 fn next(&self) -> Self {
611 match self {
612 Self::Center => Self::Top,
613 Self::Top => Self::Bottom,
614 Self::Bottom => Self::Center,
615 }
616 }
617}
618
619#[derive(Clone)]
620pub struct EditorSnapshot {
621 pub mode: EditorMode,
622 show_gutter: bool,
623 show_line_numbers: Option<bool>,
624 show_git_diff_gutter: Option<bool>,
625 show_code_actions: Option<bool>,
626 show_runnables: Option<bool>,
627 render_git_blame_gutter: bool,
628 pub display_snapshot: DisplaySnapshot,
629 pub placeholder_text: Option<Arc<str>>,
630 is_focused: bool,
631 scroll_anchor: ScrollAnchor,
632 ongoing_scroll: OngoingScroll,
633 current_line_highlight: CurrentLineHighlight,
634 gutter_hovered: bool,
635}
636
637const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
638
639#[derive(Default, Debug, Clone, Copy)]
640pub struct GutterDimensions {
641 pub left_padding: Pixels,
642 pub right_padding: Pixels,
643 pub width: Pixels,
644 pub margin: Pixels,
645 pub git_blame_entries_width: Option<Pixels>,
646}
647
648impl GutterDimensions {
649 /// The full width of the space taken up by the gutter.
650 pub fn full_width(&self) -> Pixels {
651 self.margin + self.width
652 }
653
654 /// The width of the space reserved for the fold indicators,
655 /// use alongside 'justify_end' and `gutter_width` to
656 /// right align content with the line numbers
657 pub fn fold_area_width(&self) -> Pixels {
658 self.margin + self.right_padding
659 }
660}
661
662#[derive(Debug)]
663pub struct RemoteSelection {
664 pub replica_id: ReplicaId,
665 pub selection: Selection<Anchor>,
666 pub cursor_shape: CursorShape,
667 pub peer_id: PeerId,
668 pub line_mode: bool,
669 pub participant_index: Option<ParticipantIndex>,
670 pub user_name: Option<SharedString>,
671}
672
673#[derive(Clone, Debug)]
674struct SelectionHistoryEntry {
675 selections: Arc<[Selection<Anchor>]>,
676 select_next_state: Option<SelectNextState>,
677 select_prev_state: Option<SelectNextState>,
678 add_selections_state: Option<AddSelectionsState>,
679}
680
681enum SelectionHistoryMode {
682 Normal,
683 Undoing,
684 Redoing,
685}
686
687#[derive(Clone, PartialEq, Eq, Hash)]
688struct HoveredCursor {
689 replica_id: u16,
690 selection_id: usize,
691}
692
693impl Default for SelectionHistoryMode {
694 fn default() -> Self {
695 Self::Normal
696 }
697}
698
699#[derive(Default)]
700struct SelectionHistory {
701 #[allow(clippy::type_complexity)]
702 selections_by_transaction:
703 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
704 mode: SelectionHistoryMode,
705 undo_stack: VecDeque<SelectionHistoryEntry>,
706 redo_stack: VecDeque<SelectionHistoryEntry>,
707}
708
709impl SelectionHistory {
710 fn insert_transaction(
711 &mut self,
712 transaction_id: TransactionId,
713 selections: Arc<[Selection<Anchor>]>,
714 ) {
715 self.selections_by_transaction
716 .insert(transaction_id, (selections, None));
717 }
718
719 #[allow(clippy::type_complexity)]
720 fn transaction(
721 &self,
722 transaction_id: TransactionId,
723 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
724 self.selections_by_transaction.get(&transaction_id)
725 }
726
727 #[allow(clippy::type_complexity)]
728 fn transaction_mut(
729 &mut self,
730 transaction_id: TransactionId,
731 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
732 self.selections_by_transaction.get_mut(&transaction_id)
733 }
734
735 fn push(&mut self, entry: SelectionHistoryEntry) {
736 if !entry.selections.is_empty() {
737 match self.mode {
738 SelectionHistoryMode::Normal => {
739 self.push_undo(entry);
740 self.redo_stack.clear();
741 }
742 SelectionHistoryMode::Undoing => self.push_redo(entry),
743 SelectionHistoryMode::Redoing => self.push_undo(entry),
744 }
745 }
746 }
747
748 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
749 if self
750 .undo_stack
751 .back()
752 .map_or(true, |e| e.selections != entry.selections)
753 {
754 self.undo_stack.push_back(entry);
755 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
756 self.undo_stack.pop_front();
757 }
758 }
759 }
760
761 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
762 if self
763 .redo_stack
764 .back()
765 .map_or(true, |e| e.selections != entry.selections)
766 {
767 self.redo_stack.push_back(entry);
768 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
769 self.redo_stack.pop_front();
770 }
771 }
772 }
773}
774
775struct RowHighlight {
776 index: usize,
777 range: RangeInclusive<Anchor>,
778 color: Option<Hsla>,
779 should_autoscroll: bool,
780}
781
782#[derive(Clone, Debug)]
783struct AddSelectionsState {
784 above: bool,
785 stack: Vec<usize>,
786}
787
788#[derive(Clone)]
789struct SelectNextState {
790 query: AhoCorasick,
791 wordwise: bool,
792 done: bool,
793}
794
795impl std::fmt::Debug for SelectNextState {
796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
797 f.debug_struct(std::any::type_name::<Self>())
798 .field("wordwise", &self.wordwise)
799 .field("done", &self.done)
800 .finish()
801 }
802}
803
804#[derive(Debug)]
805struct AutocloseRegion {
806 selection_id: usize,
807 range: Range<Anchor>,
808 pair: BracketPair,
809}
810
811#[derive(Debug)]
812struct SnippetState {
813 ranges: Vec<Vec<Range<Anchor>>>,
814 active_index: usize,
815}
816
817#[doc(hidden)]
818pub struct RenameState {
819 pub range: Range<Anchor>,
820 pub old_name: Arc<str>,
821 pub editor: View<Editor>,
822 block_id: CustomBlockId,
823}
824
825struct InvalidationStack<T>(Vec<T>);
826
827struct RegisteredInlineCompletionProvider {
828 provider: Arc<dyn InlineCompletionProviderHandle>,
829 _subscription: Subscription,
830}
831
832enum ContextMenu {
833 Completions(CompletionsMenu),
834 CodeActions(CodeActionsMenu),
835}
836
837impl ContextMenu {
838 fn select_first(
839 &mut self,
840 project: Option<&Model<Project>>,
841 cx: &mut ViewContext<Editor>,
842 ) -> bool {
843 if self.visible() {
844 match self {
845 ContextMenu::Completions(menu) => menu.select_first(project, cx),
846 ContextMenu::CodeActions(menu) => menu.select_first(cx),
847 }
848 true
849 } else {
850 false
851 }
852 }
853
854 fn select_prev(
855 &mut self,
856 project: Option<&Model<Project>>,
857 cx: &mut ViewContext<Editor>,
858 ) -> bool {
859 if self.visible() {
860 match self {
861 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
862 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
863 }
864 true
865 } else {
866 false
867 }
868 }
869
870 fn select_next(
871 &mut self,
872 project: Option<&Model<Project>>,
873 cx: &mut ViewContext<Editor>,
874 ) -> bool {
875 if self.visible() {
876 match self {
877 ContextMenu::Completions(menu) => menu.select_next(project, cx),
878 ContextMenu::CodeActions(menu) => menu.select_next(cx),
879 }
880 true
881 } else {
882 false
883 }
884 }
885
886 fn select_last(
887 &mut self,
888 project: Option<&Model<Project>>,
889 cx: &mut ViewContext<Editor>,
890 ) -> bool {
891 if self.visible() {
892 match self {
893 ContextMenu::Completions(menu) => menu.select_last(project, cx),
894 ContextMenu::CodeActions(menu) => menu.select_last(cx),
895 }
896 true
897 } else {
898 false
899 }
900 }
901
902 fn visible(&self) -> bool {
903 match self {
904 ContextMenu::Completions(menu) => menu.visible(),
905 ContextMenu::CodeActions(menu) => menu.visible(),
906 }
907 }
908
909 fn render(
910 &self,
911 cursor_position: DisplayPoint,
912 style: &EditorStyle,
913 max_height: Pixels,
914 workspace: Option<WeakView<Workspace>>,
915 cx: &mut ViewContext<Editor>,
916 ) -> (ContextMenuOrigin, AnyElement) {
917 match self {
918 ContextMenu::Completions(menu) => (
919 ContextMenuOrigin::EditorPoint(cursor_position),
920 menu.render(style, max_height, workspace, cx),
921 ),
922 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
923 }
924 }
925}
926
927enum ContextMenuOrigin {
928 EditorPoint(DisplayPoint),
929 GutterIndicator(DisplayRow),
930}
931
932#[derive(Clone)]
933struct CompletionsMenu {
934 id: CompletionId,
935 sort_completions: bool,
936 initial_position: Anchor,
937 buffer: Model<Buffer>,
938 completions: Arc<RwLock<Box<[Completion]>>>,
939 match_candidates: Arc<[StringMatchCandidate]>,
940 matches: Arc<[StringMatch]>,
941 selected_item: usize,
942 scroll_handle: UniformListScrollHandle,
943 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
944}
945
946impl CompletionsMenu {
947 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
948 self.selected_item = 0;
949 self.scroll_handle.scroll_to_item(self.selected_item);
950 self.attempt_resolve_selected_completion_documentation(project, cx);
951 cx.notify();
952 }
953
954 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
955 if self.selected_item > 0 {
956 self.selected_item -= 1;
957 } else {
958 self.selected_item = self.matches.len() - 1;
959 }
960 self.scroll_handle.scroll_to_item(self.selected_item);
961 self.attempt_resolve_selected_completion_documentation(project, cx);
962 cx.notify();
963 }
964
965 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
966 if self.selected_item + 1 < self.matches.len() {
967 self.selected_item += 1;
968 } else {
969 self.selected_item = 0;
970 }
971 self.scroll_handle.scroll_to_item(self.selected_item);
972 self.attempt_resolve_selected_completion_documentation(project, cx);
973 cx.notify();
974 }
975
976 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
977 self.selected_item = self.matches.len() - 1;
978 self.scroll_handle.scroll_to_item(self.selected_item);
979 self.attempt_resolve_selected_completion_documentation(project, cx);
980 cx.notify();
981 }
982
983 fn pre_resolve_completion_documentation(
984 buffer: Model<Buffer>,
985 completions: Arc<RwLock<Box<[Completion]>>>,
986 matches: Arc<[StringMatch]>,
987 editor: &Editor,
988 cx: &mut ViewContext<Editor>,
989 ) -> Task<()> {
990 let settings = EditorSettings::get_global(cx);
991 if !settings.show_completion_documentation {
992 return Task::ready(());
993 }
994
995 let Some(provider) = editor.completion_provider.as_ref() else {
996 return Task::ready(());
997 };
998
999 let resolve_task = provider.resolve_completions(
1000 buffer,
1001 matches.iter().map(|m| m.candidate_id).collect(),
1002 completions.clone(),
1003 cx,
1004 );
1005
1006 cx.spawn(move |this, mut cx| async move {
1007 if let Some(true) = resolve_task.await.log_err() {
1008 this.update(&mut cx, |_, cx| cx.notify()).ok();
1009 }
1010 })
1011 }
1012
1013 fn attempt_resolve_selected_completion_documentation(
1014 &mut self,
1015 project: Option<&Model<Project>>,
1016 cx: &mut ViewContext<Editor>,
1017 ) {
1018 let settings = EditorSettings::get_global(cx);
1019 if !settings.show_completion_documentation {
1020 return;
1021 }
1022
1023 let completion_index = self.matches[self.selected_item].candidate_id;
1024 let Some(project) = project else {
1025 return;
1026 };
1027
1028 let resolve_task = project.update(cx, |project, cx| {
1029 project.resolve_completions(
1030 self.buffer.clone(),
1031 vec![completion_index],
1032 self.completions.clone(),
1033 cx,
1034 )
1035 });
1036
1037 let delay_ms =
1038 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1039 let delay = Duration::from_millis(delay_ms);
1040
1041 self.selected_completion_documentation_resolve_debounce
1042 .lock()
1043 .fire_new(delay, cx, |_, cx| {
1044 cx.spawn(move |this, mut cx| async move {
1045 if let Some(true) = resolve_task.await.log_err() {
1046 this.update(&mut cx, |_, cx| cx.notify()).ok();
1047 }
1048 })
1049 });
1050 }
1051
1052 fn visible(&self) -> bool {
1053 !self.matches.is_empty()
1054 }
1055
1056 fn render(
1057 &self,
1058 style: &EditorStyle,
1059 max_height: Pixels,
1060 workspace: Option<WeakView<Workspace>>,
1061 cx: &mut ViewContext<Editor>,
1062 ) -> AnyElement {
1063 let settings = EditorSettings::get_global(cx);
1064 let show_completion_documentation = settings.show_completion_documentation;
1065
1066 let widest_completion_ix = self
1067 .matches
1068 .iter()
1069 .enumerate()
1070 .max_by_key(|(_, mat)| {
1071 let completions = self.completions.read();
1072 let completion = &completions[mat.candidate_id];
1073 let documentation = &completion.documentation;
1074
1075 let mut len = completion.label.text.chars().count();
1076 if let Some(Documentation::SingleLine(text)) = documentation {
1077 if show_completion_documentation {
1078 len += text.chars().count();
1079 }
1080 }
1081
1082 len
1083 })
1084 .map(|(ix, _)| ix);
1085
1086 let completions = self.completions.clone();
1087 let matches = self.matches.clone();
1088 let selected_item = self.selected_item;
1089 let style = style.clone();
1090
1091 let multiline_docs = if show_completion_documentation {
1092 let mat = &self.matches[selected_item];
1093 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1094 Some(Documentation::MultiLinePlainText(text)) => {
1095 Some(div().child(SharedString::from(text.clone())))
1096 }
1097 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1098 Some(div().child(render_parsed_markdown(
1099 "completions_markdown",
1100 parsed,
1101 &style,
1102 workspace,
1103 cx,
1104 )))
1105 }
1106 _ => None,
1107 };
1108 multiline_docs.map(|div| {
1109 div.id("multiline_docs")
1110 .max_h(max_height)
1111 .flex_1()
1112 .px_1p5()
1113 .py_1()
1114 .min_w(px(260.))
1115 .max_w(px(640.))
1116 .w(px(500.))
1117 .overflow_y_scroll()
1118 .occlude()
1119 })
1120 } else {
1121 None
1122 };
1123
1124 let list = uniform_list(
1125 cx.view().clone(),
1126 "completions",
1127 matches.len(),
1128 move |_editor, range, cx| {
1129 let start_ix = range.start;
1130 let completions_guard = completions.read();
1131
1132 matches[range]
1133 .iter()
1134 .enumerate()
1135 .map(|(ix, mat)| {
1136 let item_ix = start_ix + ix;
1137 let candidate_id = mat.candidate_id;
1138 let completion = &completions_guard[candidate_id];
1139
1140 let documentation = if show_completion_documentation {
1141 &completion.documentation
1142 } else {
1143 &None
1144 };
1145
1146 let highlights = gpui::combine_highlights(
1147 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1148 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1149 |(range, mut highlight)| {
1150 // Ignore font weight for syntax highlighting, as we'll use it
1151 // for fuzzy matches.
1152 highlight.font_weight = None;
1153
1154 if completion.lsp_completion.deprecated.unwrap_or(false) {
1155 highlight.strikethrough = Some(StrikethroughStyle {
1156 thickness: 1.0.into(),
1157 ..Default::default()
1158 });
1159 highlight.color = Some(cx.theme().colors().text_muted);
1160 }
1161
1162 (range, highlight)
1163 },
1164 ),
1165 );
1166 let completion_label = StyledText::new(completion.label.text.clone())
1167 .with_highlights(&style.text, highlights);
1168 let documentation_label =
1169 if let Some(Documentation::SingleLine(text)) = documentation {
1170 if text.trim().is_empty() {
1171 None
1172 } else {
1173 Some(
1174 Label::new(text.clone())
1175 .ml_4()
1176 .size(LabelSize::Small)
1177 .color(Color::Muted),
1178 )
1179 }
1180 } else {
1181 None
1182 };
1183
1184 div().min_w(px(220.)).max_w(px(540.)).child(
1185 ListItem::new(mat.candidate_id)
1186 .inset(true)
1187 .selected(item_ix == selected_item)
1188 .on_click(cx.listener(move |editor, _event, cx| {
1189 cx.stop_propagation();
1190 if let Some(task) = editor.confirm_completion(
1191 &ConfirmCompletion {
1192 item_ix: Some(item_ix),
1193 },
1194 cx,
1195 ) {
1196 task.detach_and_log_err(cx)
1197 }
1198 }))
1199 .child(h_flex().overflow_hidden().child(completion_label))
1200 .end_slot::<Label>(documentation_label),
1201 )
1202 })
1203 .collect()
1204 },
1205 )
1206 .occlude()
1207 .max_h(max_height)
1208 .track_scroll(self.scroll_handle.clone())
1209 .with_width_from_item(widest_completion_ix)
1210 .with_sizing_behavior(ListSizingBehavior::Infer);
1211
1212 Popover::new()
1213 .child(list)
1214 .when_some(multiline_docs, |popover, multiline_docs| {
1215 popover.aside(multiline_docs)
1216 })
1217 .into_any_element()
1218 }
1219
1220 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1221 let mut matches = if let Some(query) = query {
1222 fuzzy::match_strings(
1223 &self.match_candidates,
1224 query,
1225 query.chars().any(|c| c.is_uppercase()),
1226 100,
1227 &Default::default(),
1228 executor,
1229 )
1230 .await
1231 } else {
1232 self.match_candidates
1233 .iter()
1234 .enumerate()
1235 .map(|(candidate_id, candidate)| StringMatch {
1236 candidate_id,
1237 score: Default::default(),
1238 positions: Default::default(),
1239 string: candidate.string.clone(),
1240 })
1241 .collect()
1242 };
1243
1244 // Remove all candidates where the query's start does not match the start of any word in the candidate
1245 if let Some(query) = query {
1246 if let Some(query_start) = query.chars().next() {
1247 matches.retain(|string_match| {
1248 split_words(&string_match.string).any(|word| {
1249 // Check that the first codepoint of the word as lowercase matches the first
1250 // codepoint of the query as lowercase
1251 word.chars()
1252 .flat_map(|codepoint| codepoint.to_lowercase())
1253 .zip(query_start.to_lowercase())
1254 .all(|(word_cp, query_cp)| word_cp == query_cp)
1255 })
1256 });
1257 }
1258 }
1259
1260 let completions = self.completions.read();
1261 if self.sort_completions {
1262 matches.sort_unstable_by_key(|mat| {
1263 // We do want to strike a balance here between what the language server tells us
1264 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1265 // `Creat` and there is a local variable called `CreateComponent`).
1266 // So what we do is: we bucket all matches into two buckets
1267 // - Strong matches
1268 // - Weak matches
1269 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1270 // and the Weak matches are the rest.
1271 //
1272 // For the strong matches, we sort by the language-servers score first and for the weak
1273 // matches, we prefer our fuzzy finder first.
1274 //
1275 // The thinking behind that: it's useless to take the sort_text the language-server gives
1276 // us into account when it's obviously a bad match.
1277
1278 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1279 enum MatchScore<'a> {
1280 Strong {
1281 sort_text: Option<&'a str>,
1282 score: Reverse<OrderedFloat<f64>>,
1283 sort_key: (usize, &'a str),
1284 },
1285 Weak {
1286 score: Reverse<OrderedFloat<f64>>,
1287 sort_text: Option<&'a str>,
1288 sort_key: (usize, &'a str),
1289 },
1290 }
1291
1292 let completion = &completions[mat.candidate_id];
1293 let sort_key = completion.sort_key();
1294 let sort_text = completion.lsp_completion.sort_text.as_deref();
1295 let score = Reverse(OrderedFloat(mat.score));
1296
1297 if mat.score >= 0.2 {
1298 MatchScore::Strong {
1299 sort_text,
1300 score,
1301 sort_key,
1302 }
1303 } else {
1304 MatchScore::Weak {
1305 score,
1306 sort_text,
1307 sort_key,
1308 }
1309 }
1310 });
1311 }
1312
1313 for mat in &mut matches {
1314 let completion = &completions[mat.candidate_id];
1315 mat.string.clone_from(&completion.label.text);
1316 for position in &mut mat.positions {
1317 *position += completion.label.filter_range.start;
1318 }
1319 }
1320 drop(completions);
1321
1322 self.matches = matches.into();
1323 self.selected_item = 0;
1324 }
1325}
1326
1327#[derive(Clone)]
1328struct CodeActionContents {
1329 tasks: Option<Arc<ResolvedTasks>>,
1330 actions: Option<Arc<[CodeAction]>>,
1331}
1332
1333impl CodeActionContents {
1334 fn len(&self) -> usize {
1335 match (&self.tasks, &self.actions) {
1336 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1337 (Some(tasks), None) => tasks.templates.len(),
1338 (None, Some(actions)) => actions.len(),
1339 (None, None) => 0,
1340 }
1341 }
1342
1343 fn is_empty(&self) -> bool {
1344 match (&self.tasks, &self.actions) {
1345 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1346 (Some(tasks), None) => tasks.templates.is_empty(),
1347 (None, Some(actions)) => actions.is_empty(),
1348 (None, None) => true,
1349 }
1350 }
1351
1352 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1353 self.tasks
1354 .iter()
1355 .flat_map(|tasks| {
1356 tasks
1357 .templates
1358 .iter()
1359 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1360 })
1361 .chain(self.actions.iter().flat_map(|actions| {
1362 actions
1363 .iter()
1364 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1365 }))
1366 }
1367 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1368 match (&self.tasks, &self.actions) {
1369 (Some(tasks), Some(actions)) => {
1370 if index < tasks.templates.len() {
1371 tasks
1372 .templates
1373 .get(index)
1374 .cloned()
1375 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1376 } else {
1377 actions
1378 .get(index - tasks.templates.len())
1379 .cloned()
1380 .map(CodeActionsItem::CodeAction)
1381 }
1382 }
1383 (Some(tasks), None) => tasks
1384 .templates
1385 .get(index)
1386 .cloned()
1387 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1388 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1389 (None, None) => None,
1390 }
1391 }
1392}
1393
1394#[allow(clippy::large_enum_variant)]
1395#[derive(Clone)]
1396enum CodeActionsItem {
1397 Task(TaskSourceKind, ResolvedTask),
1398 CodeAction(CodeAction),
1399}
1400
1401impl CodeActionsItem {
1402 fn as_task(&self) -> Option<&ResolvedTask> {
1403 let Self::Task(_, task) = self else {
1404 return None;
1405 };
1406 Some(task)
1407 }
1408 fn as_code_action(&self) -> Option<&CodeAction> {
1409 let Self::CodeAction(action) = self else {
1410 return None;
1411 };
1412 Some(action)
1413 }
1414 fn label(&self) -> String {
1415 match self {
1416 Self::CodeAction(action) => action.lsp_action.title.clone(),
1417 Self::Task(_, task) => task.resolved_label.clone(),
1418 }
1419 }
1420}
1421
1422struct CodeActionsMenu {
1423 actions: CodeActionContents,
1424 buffer: Model<Buffer>,
1425 selected_item: usize,
1426 scroll_handle: UniformListScrollHandle,
1427 deployed_from_indicator: Option<DisplayRow>,
1428}
1429
1430impl CodeActionsMenu {
1431 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1432 self.selected_item = 0;
1433 self.scroll_handle.scroll_to_item(self.selected_item);
1434 cx.notify()
1435 }
1436
1437 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1438 if self.selected_item > 0 {
1439 self.selected_item -= 1;
1440 } else {
1441 self.selected_item = self.actions.len() - 1;
1442 }
1443 self.scroll_handle.scroll_to_item(self.selected_item);
1444 cx.notify();
1445 }
1446
1447 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1448 if self.selected_item + 1 < self.actions.len() {
1449 self.selected_item += 1;
1450 } else {
1451 self.selected_item = 0;
1452 }
1453 self.scroll_handle.scroll_to_item(self.selected_item);
1454 cx.notify();
1455 }
1456
1457 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1458 self.selected_item = self.actions.len() - 1;
1459 self.scroll_handle.scroll_to_item(self.selected_item);
1460 cx.notify()
1461 }
1462
1463 fn visible(&self) -> bool {
1464 !self.actions.is_empty()
1465 }
1466
1467 fn render(
1468 &self,
1469 cursor_position: DisplayPoint,
1470 _style: &EditorStyle,
1471 max_height: Pixels,
1472 cx: &mut ViewContext<Editor>,
1473 ) -> (ContextMenuOrigin, AnyElement) {
1474 let actions = self.actions.clone();
1475 let selected_item = self.selected_item;
1476 let element = uniform_list(
1477 cx.view().clone(),
1478 "code_actions_menu",
1479 self.actions.len(),
1480 move |_this, range, cx| {
1481 actions
1482 .iter()
1483 .skip(range.start)
1484 .take(range.end - range.start)
1485 .enumerate()
1486 .map(|(ix, action)| {
1487 let item_ix = range.start + ix;
1488 let selected = selected_item == item_ix;
1489 let colors = cx.theme().colors();
1490 div()
1491 .px_1()
1492 .rounded_md()
1493 .text_color(colors.text)
1494 .when(selected, |style| {
1495 style
1496 .bg(colors.element_active)
1497 .text_color(colors.text_accent)
1498 })
1499 .hover(|style| {
1500 style
1501 .bg(colors.element_hover)
1502 .text_color(colors.text_accent)
1503 })
1504 .whitespace_nowrap()
1505 .when_some(action.as_code_action(), |this, action| {
1506 this.on_mouse_down(
1507 MouseButton::Left,
1508 cx.listener(move |editor, _, cx| {
1509 cx.stop_propagation();
1510 if let Some(task) = editor.confirm_code_action(
1511 &ConfirmCodeAction {
1512 item_ix: Some(item_ix),
1513 },
1514 cx,
1515 ) {
1516 task.detach_and_log_err(cx)
1517 }
1518 }),
1519 )
1520 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1521 .child(SharedString::from(action.lsp_action.title.clone()))
1522 })
1523 .when_some(action.as_task(), |this, task| {
1524 this.on_mouse_down(
1525 MouseButton::Left,
1526 cx.listener(move |editor, _, cx| {
1527 cx.stop_propagation();
1528 if let Some(task) = editor.confirm_code_action(
1529 &ConfirmCodeAction {
1530 item_ix: Some(item_ix),
1531 },
1532 cx,
1533 ) {
1534 task.detach_and_log_err(cx)
1535 }
1536 }),
1537 )
1538 .child(SharedString::from(task.resolved_label.clone()))
1539 })
1540 })
1541 .collect()
1542 },
1543 )
1544 .elevation_1(cx)
1545 .p_1()
1546 .max_h(max_height)
1547 .occlude()
1548 .track_scroll(self.scroll_handle.clone())
1549 .with_width_from_item(
1550 self.actions
1551 .iter()
1552 .enumerate()
1553 .max_by_key(|(_, action)| match action {
1554 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1555 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1556 })
1557 .map(|(ix, _)| ix),
1558 )
1559 .with_sizing_behavior(ListSizingBehavior::Infer)
1560 .into_any_element();
1561
1562 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1563 ContextMenuOrigin::GutterIndicator(row)
1564 } else {
1565 ContextMenuOrigin::EditorPoint(cursor_position)
1566 };
1567
1568 (cursor_position, element)
1569 }
1570}
1571
1572#[derive(Debug)]
1573struct ActiveDiagnosticGroup {
1574 primary_range: Range<Anchor>,
1575 primary_message: String,
1576 group_id: usize,
1577 blocks: HashMap<CustomBlockId, Diagnostic>,
1578 is_valid: bool,
1579}
1580
1581#[derive(Serialize, Deserialize, Clone, Debug)]
1582pub struct ClipboardSelection {
1583 pub len: usize,
1584 pub is_entire_line: bool,
1585 pub first_line_indent: u32,
1586}
1587
1588#[derive(Debug)]
1589pub(crate) struct NavigationData {
1590 cursor_anchor: Anchor,
1591 cursor_position: Point,
1592 scroll_anchor: ScrollAnchor,
1593 scroll_top_row: u32,
1594}
1595
1596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1597enum GotoDefinitionKind {
1598 Symbol,
1599 Declaration,
1600 Type,
1601 Implementation,
1602}
1603
1604#[derive(Debug, Clone)]
1605enum InlayHintRefreshReason {
1606 Toggle(bool),
1607 SettingsChange(InlayHintSettings),
1608 NewLinesShown,
1609 BufferEdited(HashSet<Arc<Language>>),
1610 RefreshRequested,
1611 ExcerptsRemoved(Vec<ExcerptId>),
1612}
1613
1614impl InlayHintRefreshReason {
1615 fn description(&self) -> &'static str {
1616 match self {
1617 Self::Toggle(_) => "toggle",
1618 Self::SettingsChange(_) => "settings change",
1619 Self::NewLinesShown => "new lines shown",
1620 Self::BufferEdited(_) => "buffer edited",
1621 Self::RefreshRequested => "refresh requested",
1622 Self::ExcerptsRemoved(_) => "excerpts removed",
1623 }
1624 }
1625}
1626
1627pub(crate) struct FocusedBlock {
1628 id: BlockId,
1629 focus_handle: WeakFocusHandle,
1630}
1631
1632impl Editor {
1633 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1634 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1635 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1636 Self::new(
1637 EditorMode::SingleLine { auto_width: false },
1638 buffer,
1639 None,
1640 false,
1641 cx,
1642 )
1643 }
1644
1645 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1646 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1647 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1648 Self::new(EditorMode::Full, buffer, None, false, cx)
1649 }
1650
1651 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1652 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1653 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1654 Self::new(
1655 EditorMode::SingleLine { auto_width: true },
1656 buffer,
1657 None,
1658 false,
1659 cx,
1660 )
1661 }
1662
1663 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1664 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1665 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1666 Self::new(
1667 EditorMode::AutoHeight { max_lines },
1668 buffer,
1669 None,
1670 false,
1671 cx,
1672 )
1673 }
1674
1675 pub fn for_buffer(
1676 buffer: Model<Buffer>,
1677 project: Option<Model<Project>>,
1678 cx: &mut ViewContext<Self>,
1679 ) -> Self {
1680 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1681 Self::new(EditorMode::Full, buffer, project, false, cx)
1682 }
1683
1684 pub fn for_multibuffer(
1685 buffer: Model<MultiBuffer>,
1686 project: Option<Model<Project>>,
1687 show_excerpt_controls: bool,
1688 cx: &mut ViewContext<Self>,
1689 ) -> Self {
1690 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1691 }
1692
1693 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1694 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1695 let mut clone = Self::new(
1696 self.mode,
1697 self.buffer.clone(),
1698 self.project.clone(),
1699 show_excerpt_controls,
1700 cx,
1701 );
1702 self.display_map.update(cx, |display_map, cx| {
1703 let snapshot = display_map.snapshot(cx);
1704 clone.display_map.update(cx, |display_map, cx| {
1705 display_map.set_state(&snapshot, cx);
1706 });
1707 });
1708 clone.selections.clone_state(&self.selections);
1709 clone.scroll_manager.clone_state(&self.scroll_manager);
1710 clone.searchable = self.searchable;
1711 clone
1712 }
1713
1714 pub fn new(
1715 mode: EditorMode,
1716 buffer: Model<MultiBuffer>,
1717 project: Option<Model<Project>>,
1718 show_excerpt_controls: bool,
1719 cx: &mut ViewContext<Self>,
1720 ) -> Self {
1721 let style = cx.text_style();
1722 let font_size = style.font_size.to_pixels(cx.rem_size());
1723 let editor = cx.view().downgrade();
1724 let fold_placeholder = FoldPlaceholder {
1725 constrain_width: true,
1726 render: Arc::new(move |fold_id, fold_range, cx| {
1727 let editor = editor.clone();
1728 div()
1729 .id(fold_id)
1730 .bg(cx.theme().colors().ghost_element_background)
1731 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1732 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1733 .rounded_sm()
1734 .size_full()
1735 .cursor_pointer()
1736 .child("⋯")
1737 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1738 .on_click(move |_, cx| {
1739 editor
1740 .update(cx, |editor, cx| {
1741 editor.unfold_ranges(
1742 [fold_range.start..fold_range.end],
1743 true,
1744 false,
1745 cx,
1746 );
1747 cx.stop_propagation();
1748 })
1749 .ok();
1750 })
1751 .into_any()
1752 }),
1753 merge_adjacent: true,
1754 };
1755 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1756 let display_map = cx.new_model(|cx| {
1757 DisplayMap::new(
1758 buffer.clone(),
1759 style.font(),
1760 font_size,
1761 None,
1762 show_excerpt_controls,
1763 file_header_size,
1764 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1765 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1766 fold_placeholder,
1767 cx,
1768 )
1769 });
1770
1771 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1772
1773 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1774
1775 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1776 .then(|| language_settings::SoftWrap::PreferLine);
1777
1778 let mut project_subscriptions = Vec::new();
1779 if mode == EditorMode::Full {
1780 if let Some(project) = project.as_ref() {
1781 if buffer.read(cx).is_singleton() {
1782 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1783 cx.emit(EditorEvent::TitleChanged);
1784 }));
1785 }
1786 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1787 if let project::Event::RefreshInlayHints = event {
1788 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1789 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1790 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1791 let focus_handle = editor.focus_handle(cx);
1792 if focus_handle.is_focused(cx) {
1793 let snapshot = buffer.read(cx).snapshot();
1794 for (range, snippet) in snippet_edits {
1795 let editor_range =
1796 language::range_from_lsp(*range).to_offset(&snapshot);
1797 editor
1798 .insert_snippet(&[editor_range], snippet.clone(), cx)
1799 .ok();
1800 }
1801 }
1802 }
1803 }
1804 }));
1805 let task_inventory = project.read(cx).task_inventory().clone();
1806 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1807 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1808 }));
1809 }
1810 }
1811
1812 let inlay_hint_settings = inlay_hint_settings(
1813 selections.newest_anchor().head(),
1814 &buffer.read(cx).snapshot(cx),
1815 cx,
1816 );
1817 let focus_handle = cx.focus_handle();
1818 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1819 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1820 .detach();
1821 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1822 .detach();
1823 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1824
1825 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1826 Some(false)
1827 } else {
1828 None
1829 };
1830
1831 let mut this = Self {
1832 focus_handle,
1833 show_cursor_when_unfocused: false,
1834 last_focused_descendant: None,
1835 buffer: buffer.clone(),
1836 display_map: display_map.clone(),
1837 selections,
1838 scroll_manager: ScrollManager::new(cx),
1839 columnar_selection_tail: None,
1840 add_selections_state: None,
1841 select_next_state: None,
1842 select_prev_state: None,
1843 selection_history: Default::default(),
1844 autoclose_regions: Default::default(),
1845 snippet_stack: Default::default(),
1846 select_larger_syntax_node_stack: Vec::new(),
1847 ime_transaction: Default::default(),
1848 active_diagnostics: None,
1849 soft_wrap_mode_override,
1850 completion_provider: project.clone().map(|project| Box::new(project) as _),
1851 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1852 project,
1853 blink_manager: blink_manager.clone(),
1854 show_local_selections: true,
1855 mode,
1856 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1857 show_gutter: mode == EditorMode::Full,
1858 show_line_numbers: None,
1859 use_relative_line_numbers: None,
1860 show_git_diff_gutter: None,
1861 show_code_actions: None,
1862 show_runnables: None,
1863 show_wrap_guides: None,
1864 show_indent_guides,
1865 placeholder_text: None,
1866 highlight_order: 0,
1867 highlighted_rows: HashMap::default(),
1868 background_highlights: Default::default(),
1869 gutter_highlights: TreeMap::default(),
1870 scrollbar_marker_state: ScrollbarMarkerState::default(),
1871 active_indent_guides_state: ActiveIndentGuidesState::default(),
1872 nav_history: None,
1873 context_menu: RwLock::new(None),
1874 mouse_context_menu: None,
1875 completion_tasks: Default::default(),
1876 signature_help_state: SignatureHelpState::default(),
1877 auto_signature_help: None,
1878 find_all_references_task_sources: Vec::new(),
1879 next_completion_id: 0,
1880 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1881 next_inlay_id: 0,
1882 available_code_actions: Default::default(),
1883 code_actions_task: Default::default(),
1884 document_highlights_task: Default::default(),
1885 linked_editing_range_task: Default::default(),
1886 pending_rename: Default::default(),
1887 searchable: true,
1888 cursor_shape: Default::default(),
1889 current_line_highlight: None,
1890 autoindent_mode: Some(AutoindentMode::EachLine),
1891 collapse_matches: false,
1892 workspace: None,
1893 input_enabled: true,
1894 use_modal_editing: mode == EditorMode::Full,
1895 read_only: false,
1896 use_autoclose: true,
1897 use_auto_surround: true,
1898 auto_replace_emoji_shortcode: false,
1899 leader_peer_id: None,
1900 remote_id: None,
1901 hover_state: Default::default(),
1902 hovered_link_state: Default::default(),
1903 inline_completion_provider: None,
1904 active_inline_completion: None,
1905 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1906 expanded_hunks: ExpandedHunks::default(),
1907 gutter_hovered: false,
1908 pixel_position_of_newest_cursor: None,
1909 last_bounds: None,
1910 expect_bounds_change: None,
1911 gutter_dimensions: GutterDimensions::default(),
1912 style: None,
1913 show_cursor_names: false,
1914 hovered_cursors: Default::default(),
1915 next_editor_action_id: EditorActionId::default(),
1916 editor_actions: Rc::default(),
1917 show_inline_completions_override: None,
1918 enable_inline_completions: true,
1919 custom_context_menu: None,
1920 show_git_blame_gutter: false,
1921 show_git_blame_inline: false,
1922 show_selection_menu: None,
1923 show_git_blame_inline_delay_task: None,
1924 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1925 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1926 .session
1927 .restore_unsaved_buffers,
1928 blame: None,
1929 blame_subscription: None,
1930 file_header_size,
1931 tasks: Default::default(),
1932 _subscriptions: vec![
1933 cx.observe(&buffer, Self::on_buffer_changed),
1934 cx.subscribe(&buffer, Self::on_buffer_event),
1935 cx.observe(&display_map, Self::on_display_map_changed),
1936 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1937 cx.observe_global::<SettingsStore>(Self::settings_changed),
1938 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1939 cx.observe_window_activation(|editor, cx| {
1940 let active = cx.is_window_active();
1941 editor.blink_manager.update(cx, |blink_manager, cx| {
1942 if active {
1943 blink_manager.enable(cx);
1944 } else {
1945 blink_manager.disable(cx);
1946 }
1947 });
1948 }),
1949 ],
1950 tasks_update_task: None,
1951 linked_edit_ranges: Default::default(),
1952 previous_search_ranges: None,
1953 breadcrumb_header: None,
1954 focused_block: None,
1955 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1956 addons: HashMap::default(),
1957 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1958 };
1959 this.tasks_update_task = Some(this.refresh_runnables(cx));
1960 this._subscriptions.extend(project_subscriptions);
1961
1962 this.end_selection(cx);
1963 this.scroll_manager.show_scrollbar(cx);
1964
1965 if mode == EditorMode::Full {
1966 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1967 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1968
1969 if this.git_blame_inline_enabled {
1970 this.git_blame_inline_enabled = true;
1971 this.start_git_blame_inline(false, cx);
1972 }
1973 }
1974
1975 this.report_editor_event("open", None, cx);
1976 this
1977 }
1978
1979 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1980 self.mouse_context_menu
1981 .as_ref()
1982 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1983 }
1984
1985 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1986 let mut key_context = KeyContext::new_with_defaults();
1987 key_context.add("Editor");
1988 let mode = match self.mode {
1989 EditorMode::SingleLine { .. } => "single_line",
1990 EditorMode::AutoHeight { .. } => "auto_height",
1991 EditorMode::Full => "full",
1992 };
1993
1994 if EditorSettings::jupyter_enabled(cx) {
1995 key_context.add("jupyter");
1996 }
1997
1998 key_context.set("mode", mode);
1999 if self.pending_rename.is_some() {
2000 key_context.add("renaming");
2001 }
2002 if self.context_menu_visible() {
2003 match self.context_menu.read().as_ref() {
2004 Some(ContextMenu::Completions(_)) => {
2005 key_context.add("menu");
2006 key_context.add("showing_completions")
2007 }
2008 Some(ContextMenu::CodeActions(_)) => {
2009 key_context.add("menu");
2010 key_context.add("showing_code_actions")
2011 }
2012 None => {}
2013 }
2014 }
2015
2016 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2017 if !self.focus_handle(cx).contains_focused(cx)
2018 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2019 {
2020 for addon in self.addons.values() {
2021 addon.extend_key_context(&mut key_context, cx)
2022 }
2023 }
2024
2025 if let Some(extension) = self
2026 .buffer
2027 .read(cx)
2028 .as_singleton()
2029 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2030 {
2031 key_context.set("extension", extension.to_string());
2032 }
2033
2034 if self.has_active_inline_completion(cx) {
2035 key_context.add("copilot_suggestion");
2036 key_context.add("inline_completion");
2037 }
2038
2039 key_context
2040 }
2041
2042 pub fn new_file(
2043 workspace: &mut Workspace,
2044 _: &workspace::NewFile,
2045 cx: &mut ViewContext<Workspace>,
2046 ) {
2047 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2048 "Failed to create buffer",
2049 cx,
2050 |e, _| match e.error_code() {
2051 ErrorCode::RemoteUpgradeRequired => Some(format!(
2052 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2053 e.error_tag("required").unwrap_or("the latest version")
2054 )),
2055 _ => None,
2056 },
2057 );
2058 }
2059
2060 pub fn new_in_workspace(
2061 workspace: &mut Workspace,
2062 cx: &mut ViewContext<Workspace>,
2063 ) -> Task<Result<View<Editor>>> {
2064 let project = workspace.project().clone();
2065 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2066
2067 cx.spawn(|workspace, mut cx| async move {
2068 let buffer = create.await?;
2069 workspace.update(&mut cx, |workspace, cx| {
2070 let editor =
2071 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2072 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2073 editor
2074 })
2075 })
2076 }
2077
2078 fn new_file_vertical(
2079 workspace: &mut Workspace,
2080 _: &workspace::NewFileSplitVertical,
2081 cx: &mut ViewContext<Workspace>,
2082 ) {
2083 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2084 }
2085
2086 fn new_file_horizontal(
2087 workspace: &mut Workspace,
2088 _: &workspace::NewFileSplitHorizontal,
2089 cx: &mut ViewContext<Workspace>,
2090 ) {
2091 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2092 }
2093
2094 fn new_file_in_direction(
2095 workspace: &mut Workspace,
2096 direction: SplitDirection,
2097 cx: &mut ViewContext<Workspace>,
2098 ) {
2099 let project = workspace.project().clone();
2100 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2101
2102 cx.spawn(|workspace, mut cx| async move {
2103 let buffer = create.await?;
2104 workspace.update(&mut cx, move |workspace, cx| {
2105 workspace.split_item(
2106 direction,
2107 Box::new(
2108 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2109 ),
2110 cx,
2111 )
2112 })?;
2113 anyhow::Ok(())
2114 })
2115 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2116 ErrorCode::RemoteUpgradeRequired => Some(format!(
2117 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2118 e.error_tag("required").unwrap_or("the latest version")
2119 )),
2120 _ => None,
2121 });
2122 }
2123
2124 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2125 self.buffer.read(cx).replica_id()
2126 }
2127
2128 pub fn leader_peer_id(&self) -> Option<PeerId> {
2129 self.leader_peer_id
2130 }
2131
2132 pub fn buffer(&self) -> &Model<MultiBuffer> {
2133 &self.buffer
2134 }
2135
2136 pub fn workspace(&self) -> Option<View<Workspace>> {
2137 self.workspace.as_ref()?.0.upgrade()
2138 }
2139
2140 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2141 self.buffer().read(cx).title(cx)
2142 }
2143
2144 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2145 EditorSnapshot {
2146 mode: self.mode,
2147 show_gutter: self.show_gutter,
2148 show_line_numbers: self.show_line_numbers,
2149 show_git_diff_gutter: self.show_git_diff_gutter,
2150 show_code_actions: self.show_code_actions,
2151 show_runnables: self.show_runnables,
2152 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2153 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2154 scroll_anchor: self.scroll_manager.anchor(),
2155 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2156 placeholder_text: self.placeholder_text.clone(),
2157 is_focused: self.focus_handle.is_focused(cx),
2158 current_line_highlight: self
2159 .current_line_highlight
2160 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2161 gutter_hovered: self.gutter_hovered,
2162 }
2163 }
2164
2165 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2166 self.buffer.read(cx).language_at(point, cx)
2167 }
2168
2169 pub fn file_at<T: ToOffset>(
2170 &self,
2171 point: T,
2172 cx: &AppContext,
2173 ) -> Option<Arc<dyn language::File>> {
2174 self.buffer.read(cx).read(cx).file_at(point).cloned()
2175 }
2176
2177 pub fn active_excerpt(
2178 &self,
2179 cx: &AppContext,
2180 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2181 self.buffer
2182 .read(cx)
2183 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2184 }
2185
2186 pub fn mode(&self) -> EditorMode {
2187 self.mode
2188 }
2189
2190 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2191 self.collaboration_hub.as_deref()
2192 }
2193
2194 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2195 self.collaboration_hub = Some(hub);
2196 }
2197
2198 pub fn set_custom_context_menu(
2199 &mut self,
2200 f: impl 'static
2201 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2202 ) {
2203 self.custom_context_menu = Some(Box::new(f))
2204 }
2205
2206 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2207 self.completion_provider = Some(provider);
2208 }
2209
2210 pub fn set_inline_completion_provider<T>(
2211 &mut self,
2212 provider: Option<Model<T>>,
2213 cx: &mut ViewContext<Self>,
2214 ) where
2215 T: InlineCompletionProvider,
2216 {
2217 self.inline_completion_provider =
2218 provider.map(|provider| RegisteredInlineCompletionProvider {
2219 _subscription: cx.observe(&provider, |this, _, cx| {
2220 if this.focus_handle.is_focused(cx) {
2221 this.update_visible_inline_completion(cx);
2222 }
2223 }),
2224 provider: Arc::new(provider),
2225 });
2226 self.refresh_inline_completion(false, false, cx);
2227 }
2228
2229 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2230 self.placeholder_text.as_deref()
2231 }
2232
2233 pub fn set_placeholder_text(
2234 &mut self,
2235 placeholder_text: impl Into<Arc<str>>,
2236 cx: &mut ViewContext<Self>,
2237 ) {
2238 let placeholder_text = Some(placeholder_text.into());
2239 if self.placeholder_text != placeholder_text {
2240 self.placeholder_text = placeholder_text;
2241 cx.notify();
2242 }
2243 }
2244
2245 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2246 self.cursor_shape = cursor_shape;
2247
2248 // Disrupt blink for immediate user feedback that the cursor shape has changed
2249 self.blink_manager.update(cx, BlinkManager::show_cursor);
2250
2251 cx.notify();
2252 }
2253
2254 pub fn set_current_line_highlight(
2255 &mut self,
2256 current_line_highlight: Option<CurrentLineHighlight>,
2257 ) {
2258 self.current_line_highlight = current_line_highlight;
2259 }
2260
2261 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2262 self.collapse_matches = collapse_matches;
2263 }
2264
2265 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2266 if self.collapse_matches {
2267 return range.start..range.start;
2268 }
2269 range.clone()
2270 }
2271
2272 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2273 if self.display_map.read(cx).clip_at_line_ends != clip {
2274 self.display_map
2275 .update(cx, |map, _| map.clip_at_line_ends = clip);
2276 }
2277 }
2278
2279 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2280 self.input_enabled = input_enabled;
2281 }
2282
2283 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2284 self.enable_inline_completions = enabled;
2285 }
2286
2287 pub fn set_autoindent(&mut self, autoindent: bool) {
2288 if autoindent {
2289 self.autoindent_mode = Some(AutoindentMode::EachLine);
2290 } else {
2291 self.autoindent_mode = None;
2292 }
2293 }
2294
2295 pub fn read_only(&self, cx: &AppContext) -> bool {
2296 self.read_only || self.buffer.read(cx).read_only()
2297 }
2298
2299 pub fn set_read_only(&mut self, read_only: bool) {
2300 self.read_only = read_only;
2301 }
2302
2303 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2304 self.use_autoclose = autoclose;
2305 }
2306
2307 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2308 self.use_auto_surround = auto_surround;
2309 }
2310
2311 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2312 self.auto_replace_emoji_shortcode = auto_replace;
2313 }
2314
2315 pub fn toggle_inline_completions(
2316 &mut self,
2317 _: &ToggleInlineCompletions,
2318 cx: &mut ViewContext<Self>,
2319 ) {
2320 if self.show_inline_completions_override.is_some() {
2321 self.set_show_inline_completions(None, cx);
2322 } else {
2323 let cursor = self.selections.newest_anchor().head();
2324 if let Some((buffer, cursor_buffer_position)) =
2325 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2326 {
2327 let show_inline_completions =
2328 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2329 self.set_show_inline_completions(Some(show_inline_completions), cx);
2330 }
2331 }
2332 }
2333
2334 pub fn set_show_inline_completions(
2335 &mut self,
2336 show_inline_completions: Option<bool>,
2337 cx: &mut ViewContext<Self>,
2338 ) {
2339 self.show_inline_completions_override = show_inline_completions;
2340 self.refresh_inline_completion(false, true, cx);
2341 }
2342
2343 fn should_show_inline_completions(
2344 &self,
2345 buffer: &Model<Buffer>,
2346 buffer_position: language::Anchor,
2347 cx: &AppContext,
2348 ) -> bool {
2349 if let Some(provider) = self.inline_completion_provider() {
2350 if let Some(show_inline_completions) = self.show_inline_completions_override {
2351 show_inline_completions
2352 } else {
2353 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2354 }
2355 } else {
2356 false
2357 }
2358 }
2359
2360 pub fn set_use_modal_editing(&mut self, to: bool) {
2361 self.use_modal_editing = to;
2362 }
2363
2364 pub fn use_modal_editing(&self) -> bool {
2365 self.use_modal_editing
2366 }
2367
2368 fn selections_did_change(
2369 &mut self,
2370 local: bool,
2371 old_cursor_position: &Anchor,
2372 show_completions: bool,
2373 cx: &mut ViewContext<Self>,
2374 ) {
2375 cx.invalidate_character_coordinates();
2376
2377 // Copy selections to primary selection buffer
2378 #[cfg(target_os = "linux")]
2379 if local {
2380 let selections = self.selections.all::<usize>(cx);
2381 let buffer_handle = self.buffer.read(cx).read(cx);
2382
2383 let mut text = String::new();
2384 for (index, selection) in selections.iter().enumerate() {
2385 let text_for_selection = buffer_handle
2386 .text_for_range(selection.start..selection.end)
2387 .collect::<String>();
2388
2389 text.push_str(&text_for_selection);
2390 if index != selections.len() - 1 {
2391 text.push('\n');
2392 }
2393 }
2394
2395 if !text.is_empty() {
2396 cx.write_to_primary(ClipboardItem::new_string(text));
2397 }
2398 }
2399
2400 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2401 self.buffer.update(cx, |buffer, cx| {
2402 buffer.set_active_selections(
2403 &self.selections.disjoint_anchors(),
2404 self.selections.line_mode,
2405 self.cursor_shape,
2406 cx,
2407 )
2408 });
2409 }
2410 let display_map = self
2411 .display_map
2412 .update(cx, |display_map, cx| display_map.snapshot(cx));
2413 let buffer = &display_map.buffer_snapshot;
2414 self.add_selections_state = None;
2415 self.select_next_state = None;
2416 self.select_prev_state = None;
2417 self.select_larger_syntax_node_stack.clear();
2418 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2419 self.snippet_stack
2420 .invalidate(&self.selections.disjoint_anchors(), buffer);
2421 self.take_rename(false, cx);
2422
2423 let new_cursor_position = self.selections.newest_anchor().head();
2424
2425 self.push_to_nav_history(
2426 *old_cursor_position,
2427 Some(new_cursor_position.to_point(buffer)),
2428 cx,
2429 );
2430
2431 if local {
2432 let new_cursor_position = self.selections.newest_anchor().head();
2433 let mut context_menu = self.context_menu.write();
2434 let completion_menu = match context_menu.as_ref() {
2435 Some(ContextMenu::Completions(menu)) => Some(menu),
2436
2437 _ => {
2438 *context_menu = None;
2439 None
2440 }
2441 };
2442
2443 if let Some(completion_menu) = completion_menu {
2444 let cursor_position = new_cursor_position.to_offset(buffer);
2445 let (word_range, kind) =
2446 buffer.surrounding_word(completion_menu.initial_position, true);
2447 if kind == Some(CharKind::Word)
2448 && word_range.to_inclusive().contains(&cursor_position)
2449 {
2450 let mut completion_menu = completion_menu.clone();
2451 drop(context_menu);
2452
2453 let query = Self::completion_query(buffer, cursor_position);
2454 cx.spawn(move |this, mut cx| async move {
2455 completion_menu
2456 .filter(query.as_deref(), cx.background_executor().clone())
2457 .await;
2458
2459 this.update(&mut cx, |this, cx| {
2460 let mut context_menu = this.context_menu.write();
2461 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2462 return;
2463 };
2464
2465 if menu.id > completion_menu.id {
2466 return;
2467 }
2468
2469 *context_menu = Some(ContextMenu::Completions(completion_menu));
2470 drop(context_menu);
2471 cx.notify();
2472 })
2473 })
2474 .detach();
2475
2476 if show_completions {
2477 self.show_completions(&ShowCompletions { trigger: None }, cx);
2478 }
2479 } else {
2480 drop(context_menu);
2481 self.hide_context_menu(cx);
2482 }
2483 } else {
2484 drop(context_menu);
2485 }
2486
2487 hide_hover(self, cx);
2488
2489 if old_cursor_position.to_display_point(&display_map).row()
2490 != new_cursor_position.to_display_point(&display_map).row()
2491 {
2492 self.available_code_actions.take();
2493 }
2494 self.refresh_code_actions(cx);
2495 self.refresh_document_highlights(cx);
2496 refresh_matching_bracket_highlights(self, cx);
2497 self.discard_inline_completion(false, cx);
2498 linked_editing_ranges::refresh_linked_ranges(self, cx);
2499 if self.git_blame_inline_enabled {
2500 self.start_inline_blame_timer(cx);
2501 }
2502 }
2503
2504 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2505 cx.emit(EditorEvent::SelectionsChanged { local });
2506
2507 if self.selections.disjoint_anchors().len() == 1 {
2508 cx.emit(SearchEvent::ActiveMatchChanged)
2509 }
2510 cx.notify();
2511 }
2512
2513 pub fn change_selections<R>(
2514 &mut self,
2515 autoscroll: Option<Autoscroll>,
2516 cx: &mut ViewContext<Self>,
2517 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2518 ) -> R {
2519 self.change_selections_inner(autoscroll, true, cx, change)
2520 }
2521
2522 pub fn change_selections_inner<R>(
2523 &mut self,
2524 autoscroll: Option<Autoscroll>,
2525 request_completions: bool,
2526 cx: &mut ViewContext<Self>,
2527 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2528 ) -> R {
2529 let old_cursor_position = self.selections.newest_anchor().head();
2530 self.push_to_selection_history();
2531
2532 let (changed, result) = self.selections.change_with(cx, change);
2533
2534 if changed {
2535 if let Some(autoscroll) = autoscroll {
2536 self.request_autoscroll(autoscroll, cx);
2537 }
2538 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2539
2540 if self.should_open_signature_help_automatically(
2541 &old_cursor_position,
2542 self.signature_help_state.backspace_pressed(),
2543 cx,
2544 ) {
2545 self.show_signature_help(&ShowSignatureHelp, cx);
2546 }
2547 self.signature_help_state.set_backspace_pressed(false);
2548 }
2549
2550 result
2551 }
2552
2553 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2554 where
2555 I: IntoIterator<Item = (Range<S>, T)>,
2556 S: ToOffset,
2557 T: Into<Arc<str>>,
2558 {
2559 if self.read_only(cx) {
2560 return;
2561 }
2562
2563 self.buffer
2564 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2565 }
2566
2567 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2568 where
2569 I: IntoIterator<Item = (Range<S>, T)>,
2570 S: ToOffset,
2571 T: Into<Arc<str>>,
2572 {
2573 if self.read_only(cx) {
2574 return;
2575 }
2576
2577 self.buffer.update(cx, |buffer, cx| {
2578 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2579 });
2580 }
2581
2582 pub fn edit_with_block_indent<I, S, T>(
2583 &mut self,
2584 edits: I,
2585 original_indent_columns: Vec<u32>,
2586 cx: &mut ViewContext<Self>,
2587 ) where
2588 I: IntoIterator<Item = (Range<S>, T)>,
2589 S: ToOffset,
2590 T: Into<Arc<str>>,
2591 {
2592 if self.read_only(cx) {
2593 return;
2594 }
2595
2596 self.buffer.update(cx, |buffer, cx| {
2597 buffer.edit(
2598 edits,
2599 Some(AutoindentMode::Block {
2600 original_indent_columns,
2601 }),
2602 cx,
2603 )
2604 });
2605 }
2606
2607 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2608 self.hide_context_menu(cx);
2609
2610 match phase {
2611 SelectPhase::Begin {
2612 position,
2613 add,
2614 click_count,
2615 } => self.begin_selection(position, add, click_count, cx),
2616 SelectPhase::BeginColumnar {
2617 position,
2618 goal_column,
2619 reset,
2620 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2621 SelectPhase::Extend {
2622 position,
2623 click_count,
2624 } => self.extend_selection(position, click_count, cx),
2625 SelectPhase::Update {
2626 position,
2627 goal_column,
2628 scroll_delta,
2629 } => self.update_selection(position, goal_column, scroll_delta, cx),
2630 SelectPhase::End => self.end_selection(cx),
2631 }
2632 }
2633
2634 fn extend_selection(
2635 &mut self,
2636 position: DisplayPoint,
2637 click_count: usize,
2638 cx: &mut ViewContext<Self>,
2639 ) {
2640 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2641 let tail = self.selections.newest::<usize>(cx).tail();
2642 self.begin_selection(position, false, click_count, cx);
2643
2644 let position = position.to_offset(&display_map, Bias::Left);
2645 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2646
2647 let mut pending_selection = self
2648 .selections
2649 .pending_anchor()
2650 .expect("extend_selection not called with pending selection");
2651 if position >= tail {
2652 pending_selection.start = tail_anchor;
2653 } else {
2654 pending_selection.end = tail_anchor;
2655 pending_selection.reversed = true;
2656 }
2657
2658 let mut pending_mode = self.selections.pending_mode().unwrap();
2659 match &mut pending_mode {
2660 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2661 _ => {}
2662 }
2663
2664 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2665 s.set_pending(pending_selection, pending_mode)
2666 });
2667 }
2668
2669 fn begin_selection(
2670 &mut self,
2671 position: DisplayPoint,
2672 add: bool,
2673 click_count: usize,
2674 cx: &mut ViewContext<Self>,
2675 ) {
2676 if !self.focus_handle.is_focused(cx) {
2677 self.last_focused_descendant = None;
2678 cx.focus(&self.focus_handle);
2679 }
2680
2681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2682 let buffer = &display_map.buffer_snapshot;
2683 let newest_selection = self.selections.newest_anchor().clone();
2684 let position = display_map.clip_point(position, Bias::Left);
2685
2686 let start;
2687 let end;
2688 let mode;
2689 let auto_scroll;
2690 match click_count {
2691 1 => {
2692 start = buffer.anchor_before(position.to_point(&display_map));
2693 end = start;
2694 mode = SelectMode::Character;
2695 auto_scroll = true;
2696 }
2697 2 => {
2698 let range = movement::surrounding_word(&display_map, position);
2699 start = buffer.anchor_before(range.start.to_point(&display_map));
2700 end = buffer.anchor_before(range.end.to_point(&display_map));
2701 mode = SelectMode::Word(start..end);
2702 auto_scroll = true;
2703 }
2704 3 => {
2705 let position = display_map
2706 .clip_point(position, Bias::Left)
2707 .to_point(&display_map);
2708 let line_start = display_map.prev_line_boundary(position).0;
2709 let next_line_start = buffer.clip_point(
2710 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2711 Bias::Left,
2712 );
2713 start = buffer.anchor_before(line_start);
2714 end = buffer.anchor_before(next_line_start);
2715 mode = SelectMode::Line(start..end);
2716 auto_scroll = true;
2717 }
2718 _ => {
2719 start = buffer.anchor_before(0);
2720 end = buffer.anchor_before(buffer.len());
2721 mode = SelectMode::All;
2722 auto_scroll = false;
2723 }
2724 }
2725
2726 let point_to_delete: Option<usize> = {
2727 let selected_points: Vec<Selection<Point>> =
2728 self.selections.disjoint_in_range(start..end, cx);
2729
2730 if !add || click_count > 1 {
2731 None
2732 } else if !selected_points.is_empty() {
2733 Some(selected_points[0].id)
2734 } else {
2735 let clicked_point_already_selected =
2736 self.selections.disjoint.iter().find(|selection| {
2737 selection.start.to_point(buffer) == start.to_point(buffer)
2738 || selection.end.to_point(buffer) == end.to_point(buffer)
2739 });
2740
2741 clicked_point_already_selected.map(|selection| selection.id)
2742 }
2743 };
2744
2745 let selections_count = self.selections.count();
2746
2747 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2748 if let Some(point_to_delete) = point_to_delete {
2749 s.delete(point_to_delete);
2750
2751 if selections_count == 1 {
2752 s.set_pending_anchor_range(start..end, mode);
2753 }
2754 } else {
2755 if !add {
2756 s.clear_disjoint();
2757 } else if click_count > 1 {
2758 s.delete(newest_selection.id)
2759 }
2760
2761 s.set_pending_anchor_range(start..end, mode);
2762 }
2763 });
2764 }
2765
2766 fn begin_columnar_selection(
2767 &mut self,
2768 position: DisplayPoint,
2769 goal_column: u32,
2770 reset: bool,
2771 cx: &mut ViewContext<Self>,
2772 ) {
2773 if !self.focus_handle.is_focused(cx) {
2774 self.last_focused_descendant = None;
2775 cx.focus(&self.focus_handle);
2776 }
2777
2778 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2779
2780 if reset {
2781 let pointer_position = display_map
2782 .buffer_snapshot
2783 .anchor_before(position.to_point(&display_map));
2784
2785 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2786 s.clear_disjoint();
2787 s.set_pending_anchor_range(
2788 pointer_position..pointer_position,
2789 SelectMode::Character,
2790 );
2791 });
2792 }
2793
2794 let tail = self.selections.newest::<Point>(cx).tail();
2795 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2796
2797 if !reset {
2798 self.select_columns(
2799 tail.to_display_point(&display_map),
2800 position,
2801 goal_column,
2802 &display_map,
2803 cx,
2804 );
2805 }
2806 }
2807
2808 fn update_selection(
2809 &mut self,
2810 position: DisplayPoint,
2811 goal_column: u32,
2812 scroll_delta: gpui::Point<f32>,
2813 cx: &mut ViewContext<Self>,
2814 ) {
2815 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2816
2817 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2818 let tail = tail.to_display_point(&display_map);
2819 self.select_columns(tail, position, goal_column, &display_map, cx);
2820 } else if let Some(mut pending) = self.selections.pending_anchor() {
2821 let buffer = self.buffer.read(cx).snapshot(cx);
2822 let head;
2823 let tail;
2824 let mode = self.selections.pending_mode().unwrap();
2825 match &mode {
2826 SelectMode::Character => {
2827 head = position.to_point(&display_map);
2828 tail = pending.tail().to_point(&buffer);
2829 }
2830 SelectMode::Word(original_range) => {
2831 let original_display_range = original_range.start.to_display_point(&display_map)
2832 ..original_range.end.to_display_point(&display_map);
2833 let original_buffer_range = original_display_range.start.to_point(&display_map)
2834 ..original_display_range.end.to_point(&display_map);
2835 if movement::is_inside_word(&display_map, position)
2836 || original_display_range.contains(&position)
2837 {
2838 let word_range = movement::surrounding_word(&display_map, position);
2839 if word_range.start < original_display_range.start {
2840 head = word_range.start.to_point(&display_map);
2841 } else {
2842 head = word_range.end.to_point(&display_map);
2843 }
2844 } else {
2845 head = position.to_point(&display_map);
2846 }
2847
2848 if head <= original_buffer_range.start {
2849 tail = original_buffer_range.end;
2850 } else {
2851 tail = original_buffer_range.start;
2852 }
2853 }
2854 SelectMode::Line(original_range) => {
2855 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2856
2857 let position = display_map
2858 .clip_point(position, Bias::Left)
2859 .to_point(&display_map);
2860 let line_start = display_map.prev_line_boundary(position).0;
2861 let next_line_start = buffer.clip_point(
2862 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2863 Bias::Left,
2864 );
2865
2866 if line_start < original_range.start {
2867 head = line_start
2868 } else {
2869 head = next_line_start
2870 }
2871
2872 if head <= original_range.start {
2873 tail = original_range.end;
2874 } else {
2875 tail = original_range.start;
2876 }
2877 }
2878 SelectMode::All => {
2879 return;
2880 }
2881 };
2882
2883 if head < tail {
2884 pending.start = buffer.anchor_before(head);
2885 pending.end = buffer.anchor_before(tail);
2886 pending.reversed = true;
2887 } else {
2888 pending.start = buffer.anchor_before(tail);
2889 pending.end = buffer.anchor_before(head);
2890 pending.reversed = false;
2891 }
2892
2893 self.change_selections(None, cx, |s| {
2894 s.set_pending(pending, mode);
2895 });
2896 } else {
2897 log::error!("update_selection dispatched with no pending selection");
2898 return;
2899 }
2900
2901 self.apply_scroll_delta(scroll_delta, cx);
2902 cx.notify();
2903 }
2904
2905 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2906 self.columnar_selection_tail.take();
2907 if self.selections.pending_anchor().is_some() {
2908 let selections = self.selections.all::<usize>(cx);
2909 self.change_selections(None, cx, |s| {
2910 s.select(selections);
2911 s.clear_pending();
2912 });
2913 }
2914 }
2915
2916 fn select_columns(
2917 &mut self,
2918 tail: DisplayPoint,
2919 head: DisplayPoint,
2920 goal_column: u32,
2921 display_map: &DisplaySnapshot,
2922 cx: &mut ViewContext<Self>,
2923 ) {
2924 let start_row = cmp::min(tail.row(), head.row());
2925 let end_row = cmp::max(tail.row(), head.row());
2926 let start_column = cmp::min(tail.column(), goal_column);
2927 let end_column = cmp::max(tail.column(), goal_column);
2928 let reversed = start_column < tail.column();
2929
2930 let selection_ranges = (start_row.0..=end_row.0)
2931 .map(DisplayRow)
2932 .filter_map(|row| {
2933 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2934 let start = display_map
2935 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2936 .to_point(display_map);
2937 let end = display_map
2938 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2939 .to_point(display_map);
2940 if reversed {
2941 Some(end..start)
2942 } else {
2943 Some(start..end)
2944 }
2945 } else {
2946 None
2947 }
2948 })
2949 .collect::<Vec<_>>();
2950
2951 self.change_selections(None, cx, |s| {
2952 s.select_ranges(selection_ranges);
2953 });
2954 cx.notify();
2955 }
2956
2957 pub fn has_pending_nonempty_selection(&self) -> bool {
2958 let pending_nonempty_selection = match self.selections.pending_anchor() {
2959 Some(Selection { start, end, .. }) => start != end,
2960 None => false,
2961 };
2962
2963 pending_nonempty_selection
2964 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2965 }
2966
2967 pub fn has_pending_selection(&self) -> bool {
2968 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2969 }
2970
2971 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2972 if self.clear_clicked_diff_hunks(cx) {
2973 cx.notify();
2974 return;
2975 }
2976 if self.dismiss_menus_and_popups(true, cx) {
2977 return;
2978 }
2979
2980 if self.mode == EditorMode::Full
2981 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2982 {
2983 return;
2984 }
2985
2986 cx.propagate();
2987 }
2988
2989 pub fn dismiss_menus_and_popups(
2990 &mut self,
2991 should_report_inline_completion_event: bool,
2992 cx: &mut ViewContext<Self>,
2993 ) -> bool {
2994 if self.take_rename(false, cx).is_some() {
2995 return true;
2996 }
2997
2998 if hide_hover(self, cx) {
2999 return true;
3000 }
3001
3002 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3003 return true;
3004 }
3005
3006 if self.hide_context_menu(cx).is_some() {
3007 return true;
3008 }
3009
3010 if self.mouse_context_menu.take().is_some() {
3011 return true;
3012 }
3013
3014 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3015 return true;
3016 }
3017
3018 if self.snippet_stack.pop().is_some() {
3019 return true;
3020 }
3021
3022 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3023 self.dismiss_diagnostics(cx);
3024 return true;
3025 }
3026
3027 false
3028 }
3029
3030 fn linked_editing_ranges_for(
3031 &self,
3032 selection: Range<text::Anchor>,
3033 cx: &AppContext,
3034 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3035 if self.linked_edit_ranges.is_empty() {
3036 return None;
3037 }
3038 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3039 selection.end.buffer_id.and_then(|end_buffer_id| {
3040 if selection.start.buffer_id != Some(end_buffer_id) {
3041 return None;
3042 }
3043 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3044 let snapshot = buffer.read(cx).snapshot();
3045 self.linked_edit_ranges
3046 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3047 .map(|ranges| (ranges, snapshot, buffer))
3048 })?;
3049 use text::ToOffset as TO;
3050 // find offset from the start of current range to current cursor position
3051 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3052
3053 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3054 let start_difference = start_offset - start_byte_offset;
3055 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3056 let end_difference = end_offset - start_byte_offset;
3057 // Current range has associated linked ranges.
3058 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3059 for range in linked_ranges.iter() {
3060 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3061 let end_offset = start_offset + end_difference;
3062 let start_offset = start_offset + start_difference;
3063 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3064 continue;
3065 }
3066 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3067 if s.start.buffer_id != selection.start.buffer_id
3068 || s.end.buffer_id != selection.end.buffer_id
3069 {
3070 return false;
3071 }
3072 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3073 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3074 }) {
3075 continue;
3076 }
3077 let start = buffer_snapshot.anchor_after(start_offset);
3078 let end = buffer_snapshot.anchor_after(end_offset);
3079 linked_edits
3080 .entry(buffer.clone())
3081 .or_default()
3082 .push(start..end);
3083 }
3084 Some(linked_edits)
3085 }
3086
3087 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3088 let text: Arc<str> = text.into();
3089
3090 if self.read_only(cx) {
3091 return;
3092 }
3093
3094 let selections = self.selections.all_adjusted(cx);
3095 let mut bracket_inserted = false;
3096 let mut edits = Vec::new();
3097 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3098 let mut new_selections = Vec::with_capacity(selections.len());
3099 let mut new_autoclose_regions = Vec::new();
3100 let snapshot = self.buffer.read(cx).read(cx);
3101
3102 for (selection, autoclose_region) in
3103 self.selections_with_autoclose_regions(selections, &snapshot)
3104 {
3105 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3106 // Determine if the inserted text matches the opening or closing
3107 // bracket of any of this language's bracket pairs.
3108 let mut bracket_pair = None;
3109 let mut is_bracket_pair_start = false;
3110 let mut is_bracket_pair_end = false;
3111 if !text.is_empty() {
3112 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3113 // and they are removing the character that triggered IME popup.
3114 for (pair, enabled) in scope.brackets() {
3115 if !pair.close && !pair.surround {
3116 continue;
3117 }
3118
3119 if enabled && pair.start.ends_with(text.as_ref()) {
3120 bracket_pair = Some(pair.clone());
3121 is_bracket_pair_start = true;
3122 break;
3123 }
3124 if pair.end.as_str() == text.as_ref() {
3125 bracket_pair = Some(pair.clone());
3126 is_bracket_pair_end = true;
3127 break;
3128 }
3129 }
3130 }
3131
3132 if let Some(bracket_pair) = bracket_pair {
3133 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3134 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3135 let auto_surround =
3136 self.use_auto_surround && snapshot_settings.use_auto_surround;
3137 if selection.is_empty() {
3138 if is_bracket_pair_start {
3139 let prefix_len = bracket_pair.start.len() - text.len();
3140
3141 // If the inserted text is a suffix of an opening bracket and the
3142 // selection is preceded by the rest of the opening bracket, then
3143 // insert the closing bracket.
3144 let following_text_allows_autoclose = snapshot
3145 .chars_at(selection.start)
3146 .next()
3147 .map_or(true, |c| scope.should_autoclose_before(c));
3148 let preceding_text_matches_prefix = prefix_len == 0
3149 || (selection.start.column >= (prefix_len as u32)
3150 && snapshot.contains_str_at(
3151 Point::new(
3152 selection.start.row,
3153 selection.start.column - (prefix_len as u32),
3154 ),
3155 &bracket_pair.start[..prefix_len],
3156 ));
3157
3158 if autoclose
3159 && bracket_pair.close
3160 && following_text_allows_autoclose
3161 && preceding_text_matches_prefix
3162 {
3163 let anchor = snapshot.anchor_before(selection.end);
3164 new_selections.push((selection.map(|_| anchor), text.len()));
3165 new_autoclose_regions.push((
3166 anchor,
3167 text.len(),
3168 selection.id,
3169 bracket_pair.clone(),
3170 ));
3171 edits.push((
3172 selection.range(),
3173 format!("{}{}", text, bracket_pair.end).into(),
3174 ));
3175 bracket_inserted = true;
3176 continue;
3177 }
3178 }
3179
3180 if let Some(region) = autoclose_region {
3181 // If the selection is followed by an auto-inserted closing bracket,
3182 // then don't insert that closing bracket again; just move the selection
3183 // past the closing bracket.
3184 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3185 && text.as_ref() == region.pair.end.as_str();
3186 if should_skip {
3187 let anchor = snapshot.anchor_after(selection.end);
3188 new_selections
3189 .push((selection.map(|_| anchor), region.pair.end.len()));
3190 continue;
3191 }
3192 }
3193
3194 let always_treat_brackets_as_autoclosed = snapshot
3195 .settings_at(selection.start, cx)
3196 .always_treat_brackets_as_autoclosed;
3197 if always_treat_brackets_as_autoclosed
3198 && is_bracket_pair_end
3199 && snapshot.contains_str_at(selection.end, text.as_ref())
3200 {
3201 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3202 // and the inserted text is a closing bracket and the selection is followed
3203 // by the closing bracket then move the selection past the closing bracket.
3204 let anchor = snapshot.anchor_after(selection.end);
3205 new_selections.push((selection.map(|_| anchor), text.len()));
3206 continue;
3207 }
3208 }
3209 // If an opening bracket is 1 character long and is typed while
3210 // text is selected, then surround that text with the bracket pair.
3211 else if auto_surround
3212 && bracket_pair.surround
3213 && is_bracket_pair_start
3214 && bracket_pair.start.chars().count() == 1
3215 {
3216 edits.push((selection.start..selection.start, text.clone()));
3217 edits.push((
3218 selection.end..selection.end,
3219 bracket_pair.end.as_str().into(),
3220 ));
3221 bracket_inserted = true;
3222 new_selections.push((
3223 Selection {
3224 id: selection.id,
3225 start: snapshot.anchor_after(selection.start),
3226 end: snapshot.anchor_before(selection.end),
3227 reversed: selection.reversed,
3228 goal: selection.goal,
3229 },
3230 0,
3231 ));
3232 continue;
3233 }
3234 }
3235 }
3236
3237 if self.auto_replace_emoji_shortcode
3238 && selection.is_empty()
3239 && text.as_ref().ends_with(':')
3240 {
3241 if let Some(possible_emoji_short_code) =
3242 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3243 {
3244 if !possible_emoji_short_code.is_empty() {
3245 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3246 let emoji_shortcode_start = Point::new(
3247 selection.start.row,
3248 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3249 );
3250
3251 // Remove shortcode from buffer
3252 edits.push((
3253 emoji_shortcode_start..selection.start,
3254 "".to_string().into(),
3255 ));
3256 new_selections.push((
3257 Selection {
3258 id: selection.id,
3259 start: snapshot.anchor_after(emoji_shortcode_start),
3260 end: snapshot.anchor_before(selection.start),
3261 reversed: selection.reversed,
3262 goal: selection.goal,
3263 },
3264 0,
3265 ));
3266
3267 // Insert emoji
3268 let selection_start_anchor = snapshot.anchor_after(selection.start);
3269 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3270 edits.push((selection.start..selection.end, emoji.to_string().into()));
3271
3272 continue;
3273 }
3274 }
3275 }
3276 }
3277
3278 // If not handling any auto-close operation, then just replace the selected
3279 // text with the given input and move the selection to the end of the
3280 // newly inserted text.
3281 let anchor = snapshot.anchor_after(selection.end);
3282 if !self.linked_edit_ranges.is_empty() {
3283 let start_anchor = snapshot.anchor_before(selection.start);
3284
3285 let is_word_char = text.chars().next().map_or(true, |char| {
3286 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3287 classifier.is_word(char)
3288 });
3289
3290 if is_word_char {
3291 if let Some(ranges) = self
3292 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3293 {
3294 for (buffer, edits) in ranges {
3295 linked_edits
3296 .entry(buffer.clone())
3297 .or_default()
3298 .extend(edits.into_iter().map(|range| (range, text.clone())));
3299 }
3300 }
3301 }
3302 }
3303
3304 new_selections.push((selection.map(|_| anchor), 0));
3305 edits.push((selection.start..selection.end, text.clone()));
3306 }
3307
3308 drop(snapshot);
3309
3310 self.transact(cx, |this, cx| {
3311 this.buffer.update(cx, |buffer, cx| {
3312 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3313 });
3314 for (buffer, edits) in linked_edits {
3315 buffer.update(cx, |buffer, cx| {
3316 let snapshot = buffer.snapshot();
3317 let edits = edits
3318 .into_iter()
3319 .map(|(range, text)| {
3320 use text::ToPoint as TP;
3321 let end_point = TP::to_point(&range.end, &snapshot);
3322 let start_point = TP::to_point(&range.start, &snapshot);
3323 (start_point..end_point, text)
3324 })
3325 .sorted_by_key(|(range, _)| range.start)
3326 .collect::<Vec<_>>();
3327 buffer.edit(edits, None, cx);
3328 })
3329 }
3330 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3331 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3332 let snapshot = this.buffer.read(cx).read(cx);
3333 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3334 .zip(new_selection_deltas)
3335 .map(|(selection, delta)| Selection {
3336 id: selection.id,
3337 start: selection.start + delta,
3338 end: selection.end + delta,
3339 reversed: selection.reversed,
3340 goal: SelectionGoal::None,
3341 })
3342 .collect::<Vec<_>>();
3343
3344 let mut i = 0;
3345 for (position, delta, selection_id, pair) in new_autoclose_regions {
3346 let position = position.to_offset(&snapshot) + delta;
3347 let start = snapshot.anchor_before(position);
3348 let end = snapshot.anchor_after(position);
3349 while let Some(existing_state) = this.autoclose_regions.get(i) {
3350 match existing_state.range.start.cmp(&start, &snapshot) {
3351 Ordering::Less => i += 1,
3352 Ordering::Greater => break,
3353 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3354 Ordering::Less => i += 1,
3355 Ordering::Equal => break,
3356 Ordering::Greater => break,
3357 },
3358 }
3359 }
3360 this.autoclose_regions.insert(
3361 i,
3362 AutocloseRegion {
3363 selection_id,
3364 range: start..end,
3365 pair,
3366 },
3367 );
3368 }
3369
3370 drop(snapshot);
3371 let had_active_inline_completion = this.has_active_inline_completion(cx);
3372 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3373 s.select(new_selections)
3374 });
3375
3376 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3377 if let Some(on_type_format_task) =
3378 this.trigger_on_type_formatting(text.to_string(), cx)
3379 {
3380 on_type_format_task.detach_and_log_err(cx);
3381 }
3382 }
3383
3384 let editor_settings = EditorSettings::get_global(cx);
3385 if bracket_inserted
3386 && (editor_settings.auto_signature_help
3387 || editor_settings.show_signature_help_after_edits)
3388 {
3389 this.show_signature_help(&ShowSignatureHelp, cx);
3390 }
3391
3392 let trigger_in_words = !had_active_inline_completion;
3393 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3394 linked_editing_ranges::refresh_linked_ranges(this, cx);
3395 this.refresh_inline_completion(true, false, cx);
3396 });
3397 }
3398
3399 fn find_possible_emoji_shortcode_at_position(
3400 snapshot: &MultiBufferSnapshot,
3401 position: Point,
3402 ) -> Option<String> {
3403 let mut chars = Vec::new();
3404 let mut found_colon = false;
3405 for char in snapshot.reversed_chars_at(position).take(100) {
3406 // Found a possible emoji shortcode in the middle of the buffer
3407 if found_colon {
3408 if char.is_whitespace() {
3409 chars.reverse();
3410 return Some(chars.iter().collect());
3411 }
3412 // If the previous character is not a whitespace, we are in the middle of a word
3413 // and we only want to complete the shortcode if the word is made up of other emojis
3414 let mut containing_word = String::new();
3415 for ch in snapshot
3416 .reversed_chars_at(position)
3417 .skip(chars.len() + 1)
3418 .take(100)
3419 {
3420 if ch.is_whitespace() {
3421 break;
3422 }
3423 containing_word.push(ch);
3424 }
3425 let containing_word = containing_word.chars().rev().collect::<String>();
3426 if util::word_consists_of_emojis(containing_word.as_str()) {
3427 chars.reverse();
3428 return Some(chars.iter().collect());
3429 }
3430 }
3431
3432 if char.is_whitespace() || !char.is_ascii() {
3433 return None;
3434 }
3435 if char == ':' {
3436 found_colon = true;
3437 } else {
3438 chars.push(char);
3439 }
3440 }
3441 // Found a possible emoji shortcode at the beginning of the buffer
3442 chars.reverse();
3443 Some(chars.iter().collect())
3444 }
3445
3446 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3447 self.transact(cx, |this, cx| {
3448 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3449 let selections = this.selections.all::<usize>(cx);
3450 let multi_buffer = this.buffer.read(cx);
3451 let buffer = multi_buffer.snapshot(cx);
3452 selections
3453 .iter()
3454 .map(|selection| {
3455 let start_point = selection.start.to_point(&buffer);
3456 let mut indent =
3457 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3458 indent.len = cmp::min(indent.len, start_point.column);
3459 let start = selection.start;
3460 let end = selection.end;
3461 let selection_is_empty = start == end;
3462 let language_scope = buffer.language_scope_at(start);
3463 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3464 &language_scope
3465 {
3466 let leading_whitespace_len = buffer
3467 .reversed_chars_at(start)
3468 .take_while(|c| c.is_whitespace() && *c != '\n')
3469 .map(|c| c.len_utf8())
3470 .sum::<usize>();
3471
3472 let trailing_whitespace_len = buffer
3473 .chars_at(end)
3474 .take_while(|c| c.is_whitespace() && *c != '\n')
3475 .map(|c| c.len_utf8())
3476 .sum::<usize>();
3477
3478 let insert_extra_newline =
3479 language.brackets().any(|(pair, enabled)| {
3480 let pair_start = pair.start.trim_end();
3481 let pair_end = pair.end.trim_start();
3482
3483 enabled
3484 && pair.newline
3485 && buffer.contains_str_at(
3486 end + trailing_whitespace_len,
3487 pair_end,
3488 )
3489 && buffer.contains_str_at(
3490 (start - leading_whitespace_len)
3491 .saturating_sub(pair_start.len()),
3492 pair_start,
3493 )
3494 });
3495
3496 // Comment extension on newline is allowed only for cursor selections
3497 let comment_delimiter = maybe!({
3498 if !selection_is_empty {
3499 return None;
3500 }
3501
3502 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3503 return None;
3504 }
3505
3506 let delimiters = language.line_comment_prefixes();
3507 let max_len_of_delimiter =
3508 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3509 let (snapshot, range) =
3510 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3511
3512 let mut index_of_first_non_whitespace = 0;
3513 let comment_candidate = snapshot
3514 .chars_for_range(range)
3515 .skip_while(|c| {
3516 let should_skip = c.is_whitespace();
3517 if should_skip {
3518 index_of_first_non_whitespace += 1;
3519 }
3520 should_skip
3521 })
3522 .take(max_len_of_delimiter)
3523 .collect::<String>();
3524 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3525 comment_candidate.starts_with(comment_prefix.as_ref())
3526 })?;
3527 let cursor_is_placed_after_comment_marker =
3528 index_of_first_non_whitespace + comment_prefix.len()
3529 <= start_point.column as usize;
3530 if cursor_is_placed_after_comment_marker {
3531 Some(comment_prefix.clone())
3532 } else {
3533 None
3534 }
3535 });
3536 (comment_delimiter, insert_extra_newline)
3537 } else {
3538 (None, false)
3539 };
3540
3541 let capacity_for_delimiter = comment_delimiter
3542 .as_deref()
3543 .map(str::len)
3544 .unwrap_or_default();
3545 let mut new_text =
3546 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3547 new_text.push('\n');
3548 new_text.extend(indent.chars());
3549 if let Some(delimiter) = &comment_delimiter {
3550 new_text.push_str(delimiter);
3551 }
3552 if insert_extra_newline {
3553 new_text = new_text.repeat(2);
3554 }
3555
3556 let anchor = buffer.anchor_after(end);
3557 let new_selection = selection.map(|_| anchor);
3558 (
3559 (start..end, new_text),
3560 (insert_extra_newline, new_selection),
3561 )
3562 })
3563 .unzip()
3564 };
3565
3566 this.edit_with_autoindent(edits, cx);
3567 let buffer = this.buffer.read(cx).snapshot(cx);
3568 let new_selections = selection_fixup_info
3569 .into_iter()
3570 .map(|(extra_newline_inserted, new_selection)| {
3571 let mut cursor = new_selection.end.to_point(&buffer);
3572 if extra_newline_inserted {
3573 cursor.row -= 1;
3574 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3575 }
3576 new_selection.map(|_| cursor)
3577 })
3578 .collect();
3579
3580 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3581 this.refresh_inline_completion(true, false, cx);
3582 });
3583 }
3584
3585 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3586 let buffer = self.buffer.read(cx);
3587 let snapshot = buffer.snapshot(cx);
3588
3589 let mut edits = Vec::new();
3590 let mut rows = Vec::new();
3591
3592 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3593 let cursor = selection.head();
3594 let row = cursor.row;
3595
3596 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3597
3598 let newline = "\n".to_string();
3599 edits.push((start_of_line..start_of_line, newline));
3600
3601 rows.push(row + rows_inserted as u32);
3602 }
3603
3604 self.transact(cx, |editor, cx| {
3605 editor.edit(edits, cx);
3606
3607 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3608 let mut index = 0;
3609 s.move_cursors_with(|map, _, _| {
3610 let row = rows[index];
3611 index += 1;
3612
3613 let point = Point::new(row, 0);
3614 let boundary = map.next_line_boundary(point).1;
3615 let clipped = map.clip_point(boundary, Bias::Left);
3616
3617 (clipped, SelectionGoal::None)
3618 });
3619 });
3620
3621 let mut indent_edits = Vec::new();
3622 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3623 for row in rows {
3624 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3625 for (row, indent) in indents {
3626 if indent.len == 0 {
3627 continue;
3628 }
3629
3630 let text = match indent.kind {
3631 IndentKind::Space => " ".repeat(indent.len as usize),
3632 IndentKind::Tab => "\t".repeat(indent.len as usize),
3633 };
3634 let point = Point::new(row.0, 0);
3635 indent_edits.push((point..point, text));
3636 }
3637 }
3638 editor.edit(indent_edits, cx);
3639 });
3640 }
3641
3642 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3643 let buffer = self.buffer.read(cx);
3644 let snapshot = buffer.snapshot(cx);
3645
3646 let mut edits = Vec::new();
3647 let mut rows = Vec::new();
3648 let mut rows_inserted = 0;
3649
3650 for selection in self.selections.all_adjusted(cx) {
3651 let cursor = selection.head();
3652 let row = cursor.row;
3653
3654 let point = Point::new(row + 1, 0);
3655 let start_of_line = snapshot.clip_point(point, Bias::Left);
3656
3657 let newline = "\n".to_string();
3658 edits.push((start_of_line..start_of_line, newline));
3659
3660 rows_inserted += 1;
3661 rows.push(row + rows_inserted);
3662 }
3663
3664 self.transact(cx, |editor, cx| {
3665 editor.edit(edits, cx);
3666
3667 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3668 let mut index = 0;
3669 s.move_cursors_with(|map, _, _| {
3670 let row = rows[index];
3671 index += 1;
3672
3673 let point = Point::new(row, 0);
3674 let boundary = map.next_line_boundary(point).1;
3675 let clipped = map.clip_point(boundary, Bias::Left);
3676
3677 (clipped, SelectionGoal::None)
3678 });
3679 });
3680
3681 let mut indent_edits = Vec::new();
3682 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3683 for row in rows {
3684 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3685 for (row, indent) in indents {
3686 if indent.len == 0 {
3687 continue;
3688 }
3689
3690 let text = match indent.kind {
3691 IndentKind::Space => " ".repeat(indent.len as usize),
3692 IndentKind::Tab => "\t".repeat(indent.len as usize),
3693 };
3694 let point = Point::new(row.0, 0);
3695 indent_edits.push((point..point, text));
3696 }
3697 }
3698 editor.edit(indent_edits, cx);
3699 });
3700 }
3701
3702 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3703 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3704 original_indent_columns: Vec::new(),
3705 });
3706 self.insert_with_autoindent_mode(text, autoindent, cx);
3707 }
3708
3709 fn insert_with_autoindent_mode(
3710 &mut self,
3711 text: &str,
3712 autoindent_mode: Option<AutoindentMode>,
3713 cx: &mut ViewContext<Self>,
3714 ) {
3715 if self.read_only(cx) {
3716 return;
3717 }
3718
3719 let text: Arc<str> = text.into();
3720 self.transact(cx, |this, cx| {
3721 let old_selections = this.selections.all_adjusted(cx);
3722 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3723 let anchors = {
3724 let snapshot = buffer.read(cx);
3725 old_selections
3726 .iter()
3727 .map(|s| {
3728 let anchor = snapshot.anchor_after(s.head());
3729 s.map(|_| anchor)
3730 })
3731 .collect::<Vec<_>>()
3732 };
3733 buffer.edit(
3734 old_selections
3735 .iter()
3736 .map(|s| (s.start..s.end, text.clone())),
3737 autoindent_mode,
3738 cx,
3739 );
3740 anchors
3741 });
3742
3743 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3744 s.select_anchors(selection_anchors);
3745 })
3746 });
3747 }
3748
3749 fn trigger_completion_on_input(
3750 &mut self,
3751 text: &str,
3752 trigger_in_words: bool,
3753 cx: &mut ViewContext<Self>,
3754 ) {
3755 if self.is_completion_trigger(text, trigger_in_words, cx) {
3756 self.show_completions(
3757 &ShowCompletions {
3758 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3759 },
3760 cx,
3761 );
3762 } else {
3763 self.hide_context_menu(cx);
3764 }
3765 }
3766
3767 fn is_completion_trigger(
3768 &self,
3769 text: &str,
3770 trigger_in_words: bool,
3771 cx: &mut ViewContext<Self>,
3772 ) -> bool {
3773 let position = self.selections.newest_anchor().head();
3774 let multibuffer = self.buffer.read(cx);
3775 let Some(buffer) = position
3776 .buffer_id
3777 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3778 else {
3779 return false;
3780 };
3781
3782 if let Some(completion_provider) = &self.completion_provider {
3783 completion_provider.is_completion_trigger(
3784 &buffer,
3785 position.text_anchor,
3786 text,
3787 trigger_in_words,
3788 cx,
3789 )
3790 } else {
3791 false
3792 }
3793 }
3794
3795 /// If any empty selections is touching the start of its innermost containing autoclose
3796 /// region, expand it to select the brackets.
3797 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3798 let selections = self.selections.all::<usize>(cx);
3799 let buffer = self.buffer.read(cx).read(cx);
3800 let new_selections = self
3801 .selections_with_autoclose_regions(selections, &buffer)
3802 .map(|(mut selection, region)| {
3803 if !selection.is_empty() {
3804 return selection;
3805 }
3806
3807 if let Some(region) = region {
3808 let mut range = region.range.to_offset(&buffer);
3809 if selection.start == range.start && range.start >= region.pair.start.len() {
3810 range.start -= region.pair.start.len();
3811 if buffer.contains_str_at(range.start, ®ion.pair.start)
3812 && buffer.contains_str_at(range.end, ®ion.pair.end)
3813 {
3814 range.end += region.pair.end.len();
3815 selection.start = range.start;
3816 selection.end = range.end;
3817
3818 return selection;
3819 }
3820 }
3821 }
3822
3823 let always_treat_brackets_as_autoclosed = buffer
3824 .settings_at(selection.start, cx)
3825 .always_treat_brackets_as_autoclosed;
3826
3827 if !always_treat_brackets_as_autoclosed {
3828 return selection;
3829 }
3830
3831 if let Some(scope) = buffer.language_scope_at(selection.start) {
3832 for (pair, enabled) in scope.brackets() {
3833 if !enabled || !pair.close {
3834 continue;
3835 }
3836
3837 if buffer.contains_str_at(selection.start, &pair.end) {
3838 let pair_start_len = pair.start.len();
3839 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3840 {
3841 selection.start -= pair_start_len;
3842 selection.end += pair.end.len();
3843
3844 return selection;
3845 }
3846 }
3847 }
3848 }
3849
3850 selection
3851 })
3852 .collect();
3853
3854 drop(buffer);
3855 self.change_selections(None, cx, |selections| selections.select(new_selections));
3856 }
3857
3858 /// Iterate the given selections, and for each one, find the smallest surrounding
3859 /// autoclose region. This uses the ordering of the selections and the autoclose
3860 /// regions to avoid repeated comparisons.
3861 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3862 &'a self,
3863 selections: impl IntoIterator<Item = Selection<D>>,
3864 buffer: &'a MultiBufferSnapshot,
3865 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3866 let mut i = 0;
3867 let mut regions = self.autoclose_regions.as_slice();
3868 selections.into_iter().map(move |selection| {
3869 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3870
3871 let mut enclosing = None;
3872 while let Some(pair_state) = regions.get(i) {
3873 if pair_state.range.end.to_offset(buffer) < range.start {
3874 regions = ®ions[i + 1..];
3875 i = 0;
3876 } else if pair_state.range.start.to_offset(buffer) > range.end {
3877 break;
3878 } else {
3879 if pair_state.selection_id == selection.id {
3880 enclosing = Some(pair_state);
3881 }
3882 i += 1;
3883 }
3884 }
3885
3886 (selection.clone(), enclosing)
3887 })
3888 }
3889
3890 /// Remove any autoclose regions that no longer contain their selection.
3891 fn invalidate_autoclose_regions(
3892 &mut self,
3893 mut selections: &[Selection<Anchor>],
3894 buffer: &MultiBufferSnapshot,
3895 ) {
3896 self.autoclose_regions.retain(|state| {
3897 let mut i = 0;
3898 while let Some(selection) = selections.get(i) {
3899 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3900 selections = &selections[1..];
3901 continue;
3902 }
3903 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3904 break;
3905 }
3906 if selection.id == state.selection_id {
3907 return true;
3908 } else {
3909 i += 1;
3910 }
3911 }
3912 false
3913 });
3914 }
3915
3916 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3917 let offset = position.to_offset(buffer);
3918 let (word_range, kind) = buffer.surrounding_word(offset, true);
3919 if offset > word_range.start && kind == Some(CharKind::Word) {
3920 Some(
3921 buffer
3922 .text_for_range(word_range.start..offset)
3923 .collect::<String>(),
3924 )
3925 } else {
3926 None
3927 }
3928 }
3929
3930 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3931 self.refresh_inlay_hints(
3932 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3933 cx,
3934 );
3935 }
3936
3937 pub fn inlay_hints_enabled(&self) -> bool {
3938 self.inlay_hint_cache.enabled
3939 }
3940
3941 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3942 if self.project.is_none() || self.mode != EditorMode::Full {
3943 return;
3944 }
3945
3946 let reason_description = reason.description();
3947 let ignore_debounce = matches!(
3948 reason,
3949 InlayHintRefreshReason::SettingsChange(_)
3950 | InlayHintRefreshReason::Toggle(_)
3951 | InlayHintRefreshReason::ExcerptsRemoved(_)
3952 );
3953 let (invalidate_cache, required_languages) = match reason {
3954 InlayHintRefreshReason::Toggle(enabled) => {
3955 self.inlay_hint_cache.enabled = enabled;
3956 if enabled {
3957 (InvalidationStrategy::RefreshRequested, None)
3958 } else {
3959 self.inlay_hint_cache.clear();
3960 self.splice_inlays(
3961 self.visible_inlay_hints(cx)
3962 .iter()
3963 .map(|inlay| inlay.id)
3964 .collect(),
3965 Vec::new(),
3966 cx,
3967 );
3968 return;
3969 }
3970 }
3971 InlayHintRefreshReason::SettingsChange(new_settings) => {
3972 match self.inlay_hint_cache.update_settings(
3973 &self.buffer,
3974 new_settings,
3975 self.visible_inlay_hints(cx),
3976 cx,
3977 ) {
3978 ControlFlow::Break(Some(InlaySplice {
3979 to_remove,
3980 to_insert,
3981 })) => {
3982 self.splice_inlays(to_remove, to_insert, cx);
3983 return;
3984 }
3985 ControlFlow::Break(None) => return,
3986 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3987 }
3988 }
3989 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3990 if let Some(InlaySplice {
3991 to_remove,
3992 to_insert,
3993 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3994 {
3995 self.splice_inlays(to_remove, to_insert, cx);
3996 }
3997 return;
3998 }
3999 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4000 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4001 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4002 }
4003 InlayHintRefreshReason::RefreshRequested => {
4004 (InvalidationStrategy::RefreshRequested, None)
4005 }
4006 };
4007
4008 if let Some(InlaySplice {
4009 to_remove,
4010 to_insert,
4011 }) = self.inlay_hint_cache.spawn_hint_refresh(
4012 reason_description,
4013 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4014 invalidate_cache,
4015 ignore_debounce,
4016 cx,
4017 ) {
4018 self.splice_inlays(to_remove, to_insert, cx);
4019 }
4020 }
4021
4022 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4023 self.display_map
4024 .read(cx)
4025 .current_inlays()
4026 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4027 .cloned()
4028 .collect()
4029 }
4030
4031 pub fn excerpts_for_inlay_hints_query(
4032 &self,
4033 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4034 cx: &mut ViewContext<Editor>,
4035 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4036 let Some(project) = self.project.as_ref() else {
4037 return HashMap::default();
4038 };
4039 let project = project.read(cx);
4040 let multi_buffer = self.buffer().read(cx);
4041 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4042 let multi_buffer_visible_start = self
4043 .scroll_manager
4044 .anchor()
4045 .anchor
4046 .to_point(&multi_buffer_snapshot);
4047 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4048 multi_buffer_visible_start
4049 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4050 Bias::Left,
4051 );
4052 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4053 multi_buffer
4054 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4055 .into_iter()
4056 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4057 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4058 let buffer = buffer_handle.read(cx);
4059 let buffer_file = project::File::from_dyn(buffer.file())?;
4060 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4061 let worktree_entry = buffer_worktree
4062 .read(cx)
4063 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4064 if worktree_entry.is_ignored {
4065 return None;
4066 }
4067
4068 let language = buffer.language()?;
4069 if let Some(restrict_to_languages) = restrict_to_languages {
4070 if !restrict_to_languages.contains(language) {
4071 return None;
4072 }
4073 }
4074 Some((
4075 excerpt_id,
4076 (
4077 buffer_handle,
4078 buffer.version().clone(),
4079 excerpt_visible_range,
4080 ),
4081 ))
4082 })
4083 .collect()
4084 }
4085
4086 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4087 TextLayoutDetails {
4088 text_system: cx.text_system().clone(),
4089 editor_style: self.style.clone().unwrap(),
4090 rem_size: cx.rem_size(),
4091 scroll_anchor: self.scroll_manager.anchor(),
4092 visible_rows: self.visible_line_count(),
4093 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4094 }
4095 }
4096
4097 fn splice_inlays(
4098 &self,
4099 to_remove: Vec<InlayId>,
4100 to_insert: Vec<Inlay>,
4101 cx: &mut ViewContext<Self>,
4102 ) {
4103 self.display_map.update(cx, |display_map, cx| {
4104 display_map.splice_inlays(to_remove, to_insert, cx);
4105 });
4106 cx.notify();
4107 }
4108
4109 fn trigger_on_type_formatting(
4110 &self,
4111 input: String,
4112 cx: &mut ViewContext<Self>,
4113 ) -> Option<Task<Result<()>>> {
4114 if input.len() != 1 {
4115 return None;
4116 }
4117
4118 let project = self.project.as_ref()?;
4119 let position = self.selections.newest_anchor().head();
4120 let (buffer, buffer_position) = self
4121 .buffer
4122 .read(cx)
4123 .text_anchor_for_position(position, cx)?;
4124
4125 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4126 // hence we do LSP request & edit on host side only — add formats to host's history.
4127 let push_to_lsp_host_history = true;
4128 // If this is not the host, append its history with new edits.
4129 let push_to_client_history = project.read(cx).is_via_collab();
4130
4131 let on_type_formatting = project.update(cx, |project, cx| {
4132 project.on_type_format(
4133 buffer.clone(),
4134 buffer_position,
4135 input,
4136 push_to_lsp_host_history,
4137 cx,
4138 )
4139 });
4140 Some(cx.spawn(|editor, mut cx| async move {
4141 if let Some(transaction) = on_type_formatting.await? {
4142 if push_to_client_history {
4143 buffer
4144 .update(&mut cx, |buffer, _| {
4145 buffer.push_transaction(transaction, Instant::now());
4146 })
4147 .ok();
4148 }
4149 editor.update(&mut cx, |editor, cx| {
4150 editor.refresh_document_highlights(cx);
4151 })?;
4152 }
4153 Ok(())
4154 }))
4155 }
4156
4157 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4158 if self.pending_rename.is_some() {
4159 return;
4160 }
4161
4162 let Some(provider) = self.completion_provider.as_ref() else {
4163 return;
4164 };
4165
4166 let position = self.selections.newest_anchor().head();
4167 let (buffer, buffer_position) =
4168 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4169 output
4170 } else {
4171 return;
4172 };
4173
4174 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4175 let is_followup_invoke = {
4176 let context_menu_state = self.context_menu.read();
4177 matches!(
4178 context_menu_state.deref(),
4179 Some(ContextMenu::Completions(_))
4180 )
4181 };
4182 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4183 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4184 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4185 CompletionTriggerKind::TRIGGER_CHARACTER
4186 }
4187
4188 _ => CompletionTriggerKind::INVOKED,
4189 };
4190 let completion_context = CompletionContext {
4191 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4192 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4193 Some(String::from(trigger))
4194 } else {
4195 None
4196 }
4197 }),
4198 trigger_kind,
4199 };
4200 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4201 let sort_completions = provider.sort_completions();
4202
4203 let id = post_inc(&mut self.next_completion_id);
4204 let task = cx.spawn(|this, mut cx| {
4205 async move {
4206 this.update(&mut cx, |this, _| {
4207 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4208 })?;
4209 let completions = completions.await.log_err();
4210 let menu = if let Some(completions) = completions {
4211 let mut menu = CompletionsMenu {
4212 id,
4213 sort_completions,
4214 initial_position: position,
4215 match_candidates: completions
4216 .iter()
4217 .enumerate()
4218 .map(|(id, completion)| {
4219 StringMatchCandidate::new(
4220 id,
4221 completion.label.text[completion.label.filter_range.clone()]
4222 .into(),
4223 )
4224 })
4225 .collect(),
4226 buffer: buffer.clone(),
4227 completions: Arc::new(RwLock::new(completions.into())),
4228 matches: Vec::new().into(),
4229 selected_item: 0,
4230 scroll_handle: UniformListScrollHandle::new(),
4231 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4232 DebouncedDelay::new(),
4233 )),
4234 };
4235 menu.filter(query.as_deref(), cx.background_executor().clone())
4236 .await;
4237
4238 if menu.matches.is_empty() {
4239 None
4240 } else {
4241 this.update(&mut cx, |editor, cx| {
4242 let completions = menu.completions.clone();
4243 let matches = menu.matches.clone();
4244
4245 let delay_ms = EditorSettings::get_global(cx)
4246 .completion_documentation_secondary_query_debounce;
4247 let delay = Duration::from_millis(delay_ms);
4248 editor
4249 .completion_documentation_pre_resolve_debounce
4250 .fire_new(delay, cx, |editor, cx| {
4251 CompletionsMenu::pre_resolve_completion_documentation(
4252 buffer,
4253 completions,
4254 matches,
4255 editor,
4256 cx,
4257 )
4258 });
4259 })
4260 .ok();
4261 Some(menu)
4262 }
4263 } else {
4264 None
4265 };
4266
4267 this.update(&mut cx, |this, cx| {
4268 let mut context_menu = this.context_menu.write();
4269 match context_menu.as_ref() {
4270 None => {}
4271
4272 Some(ContextMenu::Completions(prev_menu)) => {
4273 if prev_menu.id > id {
4274 return;
4275 }
4276 }
4277
4278 _ => return,
4279 }
4280
4281 if this.focus_handle.is_focused(cx) && menu.is_some() {
4282 let menu = menu.unwrap();
4283 *context_menu = Some(ContextMenu::Completions(menu));
4284 drop(context_menu);
4285 this.discard_inline_completion(false, cx);
4286 cx.notify();
4287 } else if this.completion_tasks.len() <= 1 {
4288 // If there are no more completion tasks and the last menu was
4289 // empty, we should hide it. If it was already hidden, we should
4290 // also show the copilot completion when available.
4291 drop(context_menu);
4292 if this.hide_context_menu(cx).is_none() {
4293 this.update_visible_inline_completion(cx);
4294 }
4295 }
4296 })?;
4297
4298 Ok::<_, anyhow::Error>(())
4299 }
4300 .log_err()
4301 });
4302
4303 self.completion_tasks.push((id, task));
4304 }
4305
4306 pub fn confirm_completion(
4307 &mut self,
4308 action: &ConfirmCompletion,
4309 cx: &mut ViewContext<Self>,
4310 ) -> Option<Task<Result<()>>> {
4311 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4312 }
4313
4314 pub fn compose_completion(
4315 &mut self,
4316 action: &ComposeCompletion,
4317 cx: &mut ViewContext<Self>,
4318 ) -> Option<Task<Result<()>>> {
4319 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4320 }
4321
4322 fn do_completion(
4323 &mut self,
4324 item_ix: Option<usize>,
4325 intent: CompletionIntent,
4326 cx: &mut ViewContext<Editor>,
4327 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4328 use language::ToOffset as _;
4329
4330 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4331 menu
4332 } else {
4333 return None;
4334 };
4335
4336 let mat = completions_menu
4337 .matches
4338 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4339 let buffer_handle = completions_menu.buffer;
4340 let completions = completions_menu.completions.read();
4341 let completion = completions.get(mat.candidate_id)?;
4342 cx.stop_propagation();
4343
4344 let snippet;
4345 let text;
4346
4347 if completion.is_snippet() {
4348 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4349 text = snippet.as_ref().unwrap().text.clone();
4350 } else {
4351 snippet = None;
4352 text = completion.new_text.clone();
4353 };
4354 let selections = self.selections.all::<usize>(cx);
4355 let buffer = buffer_handle.read(cx);
4356 let old_range = completion.old_range.to_offset(buffer);
4357 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4358
4359 let newest_selection = self.selections.newest_anchor();
4360 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4361 return None;
4362 }
4363
4364 let lookbehind = newest_selection
4365 .start
4366 .text_anchor
4367 .to_offset(buffer)
4368 .saturating_sub(old_range.start);
4369 let lookahead = old_range
4370 .end
4371 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4372 let mut common_prefix_len = old_text
4373 .bytes()
4374 .zip(text.bytes())
4375 .take_while(|(a, b)| a == b)
4376 .count();
4377
4378 let snapshot = self.buffer.read(cx).snapshot(cx);
4379 let mut range_to_replace: Option<Range<isize>> = None;
4380 let mut ranges = Vec::new();
4381 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4382 for selection in &selections {
4383 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4384 let start = selection.start.saturating_sub(lookbehind);
4385 let end = selection.end + lookahead;
4386 if selection.id == newest_selection.id {
4387 range_to_replace = Some(
4388 ((start + common_prefix_len) as isize - selection.start as isize)
4389 ..(end as isize - selection.start as isize),
4390 );
4391 }
4392 ranges.push(start + common_prefix_len..end);
4393 } else {
4394 common_prefix_len = 0;
4395 ranges.clear();
4396 ranges.extend(selections.iter().map(|s| {
4397 if s.id == newest_selection.id {
4398 range_to_replace = Some(
4399 old_range.start.to_offset_utf16(&snapshot).0 as isize
4400 - selection.start as isize
4401 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4402 - selection.start as isize,
4403 );
4404 old_range.clone()
4405 } else {
4406 s.start..s.end
4407 }
4408 }));
4409 break;
4410 }
4411 if !self.linked_edit_ranges.is_empty() {
4412 let start_anchor = snapshot.anchor_before(selection.head());
4413 let end_anchor = snapshot.anchor_after(selection.tail());
4414 if let Some(ranges) = self
4415 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4416 {
4417 for (buffer, edits) in ranges {
4418 linked_edits.entry(buffer.clone()).or_default().extend(
4419 edits
4420 .into_iter()
4421 .map(|range| (range, text[common_prefix_len..].to_owned())),
4422 );
4423 }
4424 }
4425 }
4426 }
4427 let text = &text[common_prefix_len..];
4428
4429 cx.emit(EditorEvent::InputHandled {
4430 utf16_range_to_replace: range_to_replace,
4431 text: text.into(),
4432 });
4433
4434 self.transact(cx, |this, cx| {
4435 if let Some(mut snippet) = snippet {
4436 snippet.text = text.to_string();
4437 for tabstop in snippet.tabstops.iter_mut().flatten() {
4438 tabstop.start -= common_prefix_len as isize;
4439 tabstop.end -= common_prefix_len as isize;
4440 }
4441
4442 this.insert_snippet(&ranges, snippet, cx).log_err();
4443 } else {
4444 this.buffer.update(cx, |buffer, cx| {
4445 buffer.edit(
4446 ranges.iter().map(|range| (range.clone(), text)),
4447 this.autoindent_mode.clone(),
4448 cx,
4449 );
4450 });
4451 }
4452 for (buffer, edits) in linked_edits {
4453 buffer.update(cx, |buffer, cx| {
4454 let snapshot = buffer.snapshot();
4455 let edits = edits
4456 .into_iter()
4457 .map(|(range, text)| {
4458 use text::ToPoint as TP;
4459 let end_point = TP::to_point(&range.end, &snapshot);
4460 let start_point = TP::to_point(&range.start, &snapshot);
4461 (start_point..end_point, text)
4462 })
4463 .sorted_by_key(|(range, _)| range.start)
4464 .collect::<Vec<_>>();
4465 buffer.edit(edits, None, cx);
4466 })
4467 }
4468
4469 this.refresh_inline_completion(true, false, cx);
4470 });
4471
4472 let show_new_completions_on_confirm = completion
4473 .confirm
4474 .as_ref()
4475 .map_or(false, |confirm| confirm(intent, cx));
4476 if show_new_completions_on_confirm {
4477 self.show_completions(&ShowCompletions { trigger: None }, cx);
4478 }
4479
4480 let provider = self.completion_provider.as_ref()?;
4481 let apply_edits = provider.apply_additional_edits_for_completion(
4482 buffer_handle,
4483 completion.clone(),
4484 true,
4485 cx,
4486 );
4487
4488 let editor_settings = EditorSettings::get_global(cx);
4489 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4490 // After the code completion is finished, users often want to know what signatures are needed.
4491 // so we should automatically call signature_help
4492 self.show_signature_help(&ShowSignatureHelp, cx);
4493 }
4494
4495 Some(cx.foreground_executor().spawn(async move {
4496 apply_edits.await?;
4497 Ok(())
4498 }))
4499 }
4500
4501 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4502 let mut context_menu = self.context_menu.write();
4503 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4504 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4505 // Toggle if we're selecting the same one
4506 *context_menu = None;
4507 cx.notify();
4508 return;
4509 } else {
4510 // Otherwise, clear it and start a new one
4511 *context_menu = None;
4512 cx.notify();
4513 }
4514 }
4515 drop(context_menu);
4516 let snapshot = self.snapshot(cx);
4517 let deployed_from_indicator = action.deployed_from_indicator;
4518 let mut task = self.code_actions_task.take();
4519 let action = action.clone();
4520 cx.spawn(|editor, mut cx| async move {
4521 while let Some(prev_task) = task {
4522 prev_task.await;
4523 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4524 }
4525
4526 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4527 if editor.focus_handle.is_focused(cx) {
4528 let multibuffer_point = action
4529 .deployed_from_indicator
4530 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4531 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4532 let (buffer, buffer_row) = snapshot
4533 .buffer_snapshot
4534 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4535 .and_then(|(buffer_snapshot, range)| {
4536 editor
4537 .buffer
4538 .read(cx)
4539 .buffer(buffer_snapshot.remote_id())
4540 .map(|buffer| (buffer, range.start.row))
4541 })?;
4542 let (_, code_actions) = editor
4543 .available_code_actions
4544 .clone()
4545 .and_then(|(location, code_actions)| {
4546 let snapshot = location.buffer.read(cx).snapshot();
4547 let point_range = location.range.to_point(&snapshot);
4548 let point_range = point_range.start.row..=point_range.end.row;
4549 if point_range.contains(&buffer_row) {
4550 Some((location, code_actions))
4551 } else {
4552 None
4553 }
4554 })
4555 .unzip();
4556 let buffer_id = buffer.read(cx).remote_id();
4557 let tasks = editor
4558 .tasks
4559 .get(&(buffer_id, buffer_row))
4560 .map(|t| Arc::new(t.to_owned()));
4561 if tasks.is_none() && code_actions.is_none() {
4562 return None;
4563 }
4564
4565 editor.completion_tasks.clear();
4566 editor.discard_inline_completion(false, cx);
4567 let task_context =
4568 tasks
4569 .as_ref()
4570 .zip(editor.project.clone())
4571 .map(|(tasks, project)| {
4572 let position = Point::new(buffer_row, tasks.column);
4573 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4574 let location = Location {
4575 buffer: buffer.clone(),
4576 range: range_start..range_start,
4577 };
4578 // Fill in the environmental variables from the tree-sitter captures
4579 let mut captured_task_variables = TaskVariables::default();
4580 for (capture_name, value) in tasks.extra_variables.clone() {
4581 captured_task_variables.insert(
4582 task::VariableName::Custom(capture_name.into()),
4583 value.clone(),
4584 );
4585 }
4586 project.update(cx, |project, cx| {
4587 project.task_context_for_location(
4588 captured_task_variables,
4589 location,
4590 cx,
4591 )
4592 })
4593 });
4594
4595 Some(cx.spawn(|editor, mut cx| async move {
4596 let task_context = match task_context {
4597 Some(task_context) => task_context.await,
4598 None => None,
4599 };
4600 let resolved_tasks =
4601 tasks.zip(task_context).map(|(tasks, task_context)| {
4602 Arc::new(ResolvedTasks {
4603 templates: tasks
4604 .templates
4605 .iter()
4606 .filter_map(|(kind, template)| {
4607 template
4608 .resolve_task(&kind.to_id_base(), &task_context)
4609 .map(|task| (kind.clone(), task))
4610 })
4611 .collect(),
4612 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4613 multibuffer_point.row,
4614 tasks.column,
4615 )),
4616 })
4617 });
4618 let spawn_straight_away = resolved_tasks
4619 .as_ref()
4620 .map_or(false, |tasks| tasks.templates.len() == 1)
4621 && code_actions
4622 .as_ref()
4623 .map_or(true, |actions| actions.is_empty());
4624 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4625 *editor.context_menu.write() =
4626 Some(ContextMenu::CodeActions(CodeActionsMenu {
4627 buffer,
4628 actions: CodeActionContents {
4629 tasks: resolved_tasks,
4630 actions: code_actions,
4631 },
4632 selected_item: Default::default(),
4633 scroll_handle: UniformListScrollHandle::default(),
4634 deployed_from_indicator,
4635 }));
4636 if spawn_straight_away {
4637 if let Some(task) = editor.confirm_code_action(
4638 &ConfirmCodeAction { item_ix: Some(0) },
4639 cx,
4640 ) {
4641 cx.notify();
4642 return task;
4643 }
4644 }
4645 cx.notify();
4646 Task::ready(Ok(()))
4647 }) {
4648 task.await
4649 } else {
4650 Ok(())
4651 }
4652 }))
4653 } else {
4654 Some(Task::ready(Ok(())))
4655 }
4656 })?;
4657 if let Some(task) = spawned_test_task {
4658 task.await?;
4659 }
4660
4661 Ok::<_, anyhow::Error>(())
4662 })
4663 .detach_and_log_err(cx);
4664 }
4665
4666 pub fn confirm_code_action(
4667 &mut self,
4668 action: &ConfirmCodeAction,
4669 cx: &mut ViewContext<Self>,
4670 ) -> Option<Task<Result<()>>> {
4671 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4672 menu
4673 } else {
4674 return None;
4675 };
4676 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4677 let action = actions_menu.actions.get(action_ix)?;
4678 let title = action.label();
4679 let buffer = actions_menu.buffer;
4680 let workspace = self.workspace()?;
4681
4682 match action {
4683 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4684 workspace.update(cx, |workspace, cx| {
4685 workspace::tasks::schedule_resolved_task(
4686 workspace,
4687 task_source_kind,
4688 resolved_task,
4689 false,
4690 cx,
4691 );
4692
4693 Some(Task::ready(Ok(())))
4694 })
4695 }
4696 CodeActionsItem::CodeAction(action) => {
4697 let apply_code_actions = workspace
4698 .read(cx)
4699 .project()
4700 .clone()
4701 .update(cx, |project, cx| {
4702 project.apply_code_action(buffer, action, true, cx)
4703 });
4704 let workspace = workspace.downgrade();
4705 Some(cx.spawn(|editor, cx| async move {
4706 let project_transaction = apply_code_actions.await?;
4707 Self::open_project_transaction(
4708 &editor,
4709 workspace,
4710 project_transaction,
4711 title,
4712 cx,
4713 )
4714 .await
4715 }))
4716 }
4717 }
4718 }
4719
4720 pub async fn open_project_transaction(
4721 this: &WeakView<Editor>,
4722 workspace: WeakView<Workspace>,
4723 transaction: ProjectTransaction,
4724 title: String,
4725 mut cx: AsyncWindowContext,
4726 ) -> Result<()> {
4727 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4728
4729 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4730 cx.update(|cx| {
4731 entries.sort_unstable_by_key(|(buffer, _)| {
4732 buffer.read(cx).file().map(|f| f.path().clone())
4733 });
4734 })?;
4735
4736 // If the project transaction's edits are all contained within this editor, then
4737 // avoid opening a new editor to display them.
4738
4739 if let Some((buffer, transaction)) = entries.first() {
4740 if entries.len() == 1 {
4741 let excerpt = this.update(&mut cx, |editor, cx| {
4742 editor
4743 .buffer()
4744 .read(cx)
4745 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4746 })?;
4747 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4748 if excerpted_buffer == *buffer {
4749 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4750 let excerpt_range = excerpt_range.to_offset(buffer);
4751 buffer
4752 .edited_ranges_for_transaction::<usize>(transaction)
4753 .all(|range| {
4754 excerpt_range.start <= range.start
4755 && excerpt_range.end >= range.end
4756 })
4757 })?;
4758
4759 if all_edits_within_excerpt {
4760 return Ok(());
4761 }
4762 }
4763 }
4764 }
4765 } else {
4766 return Ok(());
4767 }
4768
4769 let mut ranges_to_highlight = Vec::new();
4770 let excerpt_buffer = cx.new_model(|cx| {
4771 let mut multibuffer =
4772 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4773 for (buffer_handle, transaction) in &entries {
4774 let buffer = buffer_handle.read(cx);
4775 ranges_to_highlight.extend(
4776 multibuffer.push_excerpts_with_context_lines(
4777 buffer_handle.clone(),
4778 buffer
4779 .edited_ranges_for_transaction::<usize>(transaction)
4780 .collect(),
4781 DEFAULT_MULTIBUFFER_CONTEXT,
4782 cx,
4783 ),
4784 );
4785 }
4786 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4787 multibuffer
4788 })?;
4789
4790 workspace.update(&mut cx, |workspace, cx| {
4791 let project = workspace.project().clone();
4792 let editor =
4793 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4794 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4795 editor.update(cx, |editor, cx| {
4796 editor.highlight_background::<Self>(
4797 &ranges_to_highlight,
4798 |theme| theme.editor_highlighted_line_background,
4799 cx,
4800 );
4801 });
4802 })?;
4803
4804 Ok(())
4805 }
4806
4807 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4808 let project = self.project.clone()?;
4809 let buffer = self.buffer.read(cx);
4810 let newest_selection = self.selections.newest_anchor().clone();
4811 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4812 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4813 if start_buffer != end_buffer {
4814 return None;
4815 }
4816
4817 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4818 cx.background_executor()
4819 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4820 .await;
4821
4822 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4823 project.code_actions(&start_buffer, start..end, cx)
4824 }) {
4825 code_actions.await
4826 } else {
4827 Vec::new()
4828 };
4829
4830 this.update(&mut cx, |this, cx| {
4831 this.available_code_actions = if actions.is_empty() {
4832 None
4833 } else {
4834 Some((
4835 Location {
4836 buffer: start_buffer,
4837 range: start..end,
4838 },
4839 actions.into(),
4840 ))
4841 };
4842 cx.notify();
4843 })
4844 .log_err();
4845 }));
4846 None
4847 }
4848
4849 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4850 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4851 self.show_git_blame_inline = false;
4852
4853 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4854 cx.background_executor().timer(delay).await;
4855
4856 this.update(&mut cx, |this, cx| {
4857 this.show_git_blame_inline = true;
4858 cx.notify();
4859 })
4860 .log_err();
4861 }));
4862 }
4863 }
4864
4865 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4866 if self.pending_rename.is_some() {
4867 return None;
4868 }
4869
4870 let project = self.project.clone()?;
4871 let buffer = self.buffer.read(cx);
4872 let newest_selection = self.selections.newest_anchor().clone();
4873 let cursor_position = newest_selection.head();
4874 let (cursor_buffer, cursor_buffer_position) =
4875 buffer.text_anchor_for_position(cursor_position, cx)?;
4876 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4877 if cursor_buffer != tail_buffer {
4878 return None;
4879 }
4880
4881 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4882 cx.background_executor()
4883 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4884 .await;
4885
4886 let highlights = if let Some(highlights) = project
4887 .update(&mut cx, |project, cx| {
4888 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4889 })
4890 .log_err()
4891 {
4892 highlights.await.log_err()
4893 } else {
4894 None
4895 };
4896
4897 if let Some(highlights) = highlights {
4898 this.update(&mut cx, |this, cx| {
4899 if this.pending_rename.is_some() {
4900 return;
4901 }
4902
4903 let buffer_id = cursor_position.buffer_id;
4904 let buffer = this.buffer.read(cx);
4905 if !buffer
4906 .text_anchor_for_position(cursor_position, cx)
4907 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4908 {
4909 return;
4910 }
4911
4912 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4913 let mut write_ranges = Vec::new();
4914 let mut read_ranges = Vec::new();
4915 for highlight in highlights {
4916 for (excerpt_id, excerpt_range) in
4917 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4918 {
4919 let start = highlight
4920 .range
4921 .start
4922 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4923 let end = highlight
4924 .range
4925 .end
4926 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4927 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4928 continue;
4929 }
4930
4931 let range = Anchor {
4932 buffer_id,
4933 excerpt_id,
4934 text_anchor: start,
4935 }..Anchor {
4936 buffer_id,
4937 excerpt_id,
4938 text_anchor: end,
4939 };
4940 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4941 write_ranges.push(range);
4942 } else {
4943 read_ranges.push(range);
4944 }
4945 }
4946 }
4947
4948 this.highlight_background::<DocumentHighlightRead>(
4949 &read_ranges,
4950 |theme| theme.editor_document_highlight_read_background,
4951 cx,
4952 );
4953 this.highlight_background::<DocumentHighlightWrite>(
4954 &write_ranges,
4955 |theme| theme.editor_document_highlight_write_background,
4956 cx,
4957 );
4958 cx.notify();
4959 })
4960 .log_err();
4961 }
4962 }));
4963 None
4964 }
4965
4966 pub fn refresh_inline_completion(
4967 &mut self,
4968 debounce: bool,
4969 user_requested: bool,
4970 cx: &mut ViewContext<Self>,
4971 ) -> Option<()> {
4972 let provider = self.inline_completion_provider()?;
4973 let cursor = self.selections.newest_anchor().head();
4974 let (buffer, cursor_buffer_position) =
4975 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4976 if !user_requested
4977 && self.enable_inline_completions
4978 && !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4979 {
4980 self.discard_inline_completion(false, cx);
4981 return None;
4982 }
4983
4984 self.update_visible_inline_completion(cx);
4985 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4986 Some(())
4987 }
4988
4989 fn cycle_inline_completion(
4990 &mut self,
4991 direction: Direction,
4992 cx: &mut ViewContext<Self>,
4993 ) -> Option<()> {
4994 let provider = self.inline_completion_provider()?;
4995 let cursor = self.selections.newest_anchor().head();
4996 let (buffer, cursor_buffer_position) =
4997 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4998 if !self.enable_inline_completions
4999 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5000 {
5001 return None;
5002 }
5003
5004 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5005 self.update_visible_inline_completion(cx);
5006
5007 Some(())
5008 }
5009
5010 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5011 if !self.has_active_inline_completion(cx) {
5012 self.refresh_inline_completion(false, true, cx);
5013 return;
5014 }
5015
5016 self.update_visible_inline_completion(cx);
5017 }
5018
5019 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5020 self.show_cursor_names(cx);
5021 }
5022
5023 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5024 self.show_cursor_names = true;
5025 cx.notify();
5026 cx.spawn(|this, mut cx| async move {
5027 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5028 this.update(&mut cx, |this, cx| {
5029 this.show_cursor_names = false;
5030 cx.notify()
5031 })
5032 .ok()
5033 })
5034 .detach();
5035 }
5036
5037 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5038 if self.has_active_inline_completion(cx) {
5039 self.cycle_inline_completion(Direction::Next, cx);
5040 } else {
5041 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5042 if is_copilot_disabled {
5043 cx.propagate();
5044 }
5045 }
5046 }
5047
5048 pub fn previous_inline_completion(
5049 &mut self,
5050 _: &PreviousInlineCompletion,
5051 cx: &mut ViewContext<Self>,
5052 ) {
5053 if self.has_active_inline_completion(cx) {
5054 self.cycle_inline_completion(Direction::Prev, cx);
5055 } else {
5056 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5057 if is_copilot_disabled {
5058 cx.propagate();
5059 }
5060 }
5061 }
5062
5063 pub fn accept_inline_completion(
5064 &mut self,
5065 _: &AcceptInlineCompletion,
5066 cx: &mut ViewContext<Self>,
5067 ) {
5068 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5069 return;
5070 };
5071 if let Some(provider) = self.inline_completion_provider() {
5072 provider.accept(cx);
5073 }
5074
5075 cx.emit(EditorEvent::InputHandled {
5076 utf16_range_to_replace: None,
5077 text: completion.text.to_string().into(),
5078 });
5079
5080 if let Some(range) = delete_range {
5081 self.change_selections(None, cx, |s| s.select_ranges([range]))
5082 }
5083 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5084 self.refresh_inline_completion(true, true, cx);
5085 cx.notify();
5086 }
5087
5088 pub fn accept_partial_inline_completion(
5089 &mut self,
5090 _: &AcceptPartialInlineCompletion,
5091 cx: &mut ViewContext<Self>,
5092 ) {
5093 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5094 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5095 let mut partial_completion = completion
5096 .text
5097 .chars()
5098 .by_ref()
5099 .take_while(|c| c.is_alphabetic())
5100 .collect::<String>();
5101 if partial_completion.is_empty() {
5102 partial_completion = completion
5103 .text
5104 .chars()
5105 .by_ref()
5106 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5107 .collect::<String>();
5108 }
5109
5110 cx.emit(EditorEvent::InputHandled {
5111 utf16_range_to_replace: None,
5112 text: partial_completion.clone().into(),
5113 });
5114
5115 if let Some(range) = delete_range {
5116 self.change_selections(None, cx, |s| s.select_ranges([range]))
5117 }
5118 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5119
5120 self.refresh_inline_completion(true, true, cx);
5121 cx.notify();
5122 }
5123 }
5124 }
5125
5126 fn discard_inline_completion(
5127 &mut self,
5128 should_report_inline_completion_event: bool,
5129 cx: &mut ViewContext<Self>,
5130 ) -> bool {
5131 if let Some(provider) = self.inline_completion_provider() {
5132 provider.discard(should_report_inline_completion_event, cx);
5133 }
5134
5135 self.take_active_inline_completion(cx).is_some()
5136 }
5137
5138 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5139 if let Some(completion) = self.active_inline_completion.as_ref() {
5140 let buffer = self.buffer.read(cx).read(cx);
5141 completion.0.position.is_valid(&buffer)
5142 } else {
5143 false
5144 }
5145 }
5146
5147 fn take_active_inline_completion(
5148 &mut self,
5149 cx: &mut ViewContext<Self>,
5150 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5151 let completion = self.active_inline_completion.take()?;
5152 self.display_map.update(cx, |map, cx| {
5153 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5154 });
5155 let buffer = self.buffer.read(cx).read(cx);
5156
5157 if completion.0.position.is_valid(&buffer) {
5158 Some(completion)
5159 } else {
5160 None
5161 }
5162 }
5163
5164 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5165 let selection = self.selections.newest_anchor();
5166 let cursor = selection.head();
5167
5168 let excerpt_id = cursor.excerpt_id;
5169
5170 if self.context_menu.read().is_none()
5171 && self.completion_tasks.is_empty()
5172 && selection.start == selection.end
5173 {
5174 if let Some(provider) = self.inline_completion_provider() {
5175 if let Some((buffer, cursor_buffer_position)) =
5176 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5177 {
5178 if let Some((text, text_anchor_range)) =
5179 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5180 {
5181 let text = Rope::from(text);
5182 let mut to_remove = Vec::new();
5183 if let Some(completion) = self.active_inline_completion.take() {
5184 to_remove.push(completion.0.id);
5185 }
5186
5187 let completion_inlay =
5188 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5189
5190 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5191 let snapshot = self.buffer.read(cx).snapshot(cx);
5192 Some(
5193 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5194 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5195 )
5196 });
5197 self.active_inline_completion =
5198 Some((completion_inlay.clone(), multibuffer_anchor_range));
5199
5200 self.display_map.update(cx, move |map, cx| {
5201 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5202 });
5203 cx.notify();
5204 return;
5205 }
5206 }
5207 }
5208 }
5209
5210 self.discard_inline_completion(false, cx);
5211 }
5212
5213 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5214 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5215 }
5216
5217 fn render_code_actions_indicator(
5218 &self,
5219 _style: &EditorStyle,
5220 row: DisplayRow,
5221 is_active: bool,
5222 cx: &mut ViewContext<Self>,
5223 ) -> Option<IconButton> {
5224 if self.available_code_actions.is_some() {
5225 Some(
5226 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5227 .shape(ui::IconButtonShape::Square)
5228 .icon_size(IconSize::XSmall)
5229 .icon_color(Color::Muted)
5230 .selected(is_active)
5231 .on_click(cx.listener(move |editor, _e, cx| {
5232 editor.focus(cx);
5233 editor.toggle_code_actions(
5234 &ToggleCodeActions {
5235 deployed_from_indicator: Some(row),
5236 },
5237 cx,
5238 );
5239 })),
5240 )
5241 } else {
5242 None
5243 }
5244 }
5245
5246 fn clear_tasks(&mut self) {
5247 self.tasks.clear()
5248 }
5249
5250 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5251 if self.tasks.insert(key, value).is_some() {
5252 // This case should hopefully be rare, but just in case...
5253 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5254 }
5255 }
5256
5257 fn render_run_indicator(
5258 &self,
5259 _style: &EditorStyle,
5260 is_active: bool,
5261 row: DisplayRow,
5262 cx: &mut ViewContext<Self>,
5263 ) -> IconButton {
5264 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5265 .shape(ui::IconButtonShape::Square)
5266 .icon_size(IconSize::XSmall)
5267 .icon_color(Color::Muted)
5268 .selected(is_active)
5269 .on_click(cx.listener(move |editor, _e, cx| {
5270 editor.focus(cx);
5271 editor.toggle_code_actions(
5272 &ToggleCodeActions {
5273 deployed_from_indicator: Some(row),
5274 },
5275 cx,
5276 );
5277 }))
5278 }
5279
5280 fn close_hunk_diff_button(
5281 &self,
5282 hunk: HoveredHunk,
5283 row: DisplayRow,
5284 cx: &mut ViewContext<Self>,
5285 ) -> IconButton {
5286 IconButton::new(
5287 ("close_hunk_diff_indicator", row.0 as usize),
5288 ui::IconName::Close,
5289 )
5290 .shape(ui::IconButtonShape::Square)
5291 .icon_size(IconSize::XSmall)
5292 .icon_color(Color::Muted)
5293 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5294 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5295 }
5296
5297 pub fn context_menu_visible(&self) -> bool {
5298 self.context_menu
5299 .read()
5300 .as_ref()
5301 .map_or(false, |menu| menu.visible())
5302 }
5303
5304 fn render_context_menu(
5305 &self,
5306 cursor_position: DisplayPoint,
5307 style: &EditorStyle,
5308 max_height: Pixels,
5309 cx: &mut ViewContext<Editor>,
5310 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5311 self.context_menu.read().as_ref().map(|menu| {
5312 menu.render(
5313 cursor_position,
5314 style,
5315 max_height,
5316 self.workspace.as_ref().map(|(w, _)| w.clone()),
5317 cx,
5318 )
5319 })
5320 }
5321
5322 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5323 cx.notify();
5324 self.completion_tasks.clear();
5325 let context_menu = self.context_menu.write().take();
5326 if context_menu.is_some() {
5327 self.update_visible_inline_completion(cx);
5328 }
5329 context_menu
5330 }
5331
5332 pub fn insert_snippet(
5333 &mut self,
5334 insertion_ranges: &[Range<usize>],
5335 snippet: Snippet,
5336 cx: &mut ViewContext<Self>,
5337 ) -> Result<()> {
5338 struct Tabstop<T> {
5339 is_end_tabstop: bool,
5340 ranges: Vec<Range<T>>,
5341 }
5342
5343 let tabstops = self.buffer.update(cx, |buffer, cx| {
5344 let snippet_text: Arc<str> = snippet.text.clone().into();
5345 buffer.edit(
5346 insertion_ranges
5347 .iter()
5348 .cloned()
5349 .map(|range| (range, snippet_text.clone())),
5350 Some(AutoindentMode::EachLine),
5351 cx,
5352 );
5353
5354 let snapshot = &*buffer.read(cx);
5355 let snippet = &snippet;
5356 snippet
5357 .tabstops
5358 .iter()
5359 .map(|tabstop| {
5360 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5361 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5362 });
5363 let mut tabstop_ranges = tabstop
5364 .iter()
5365 .flat_map(|tabstop_range| {
5366 let mut delta = 0_isize;
5367 insertion_ranges.iter().map(move |insertion_range| {
5368 let insertion_start = insertion_range.start as isize + delta;
5369 delta +=
5370 snippet.text.len() as isize - insertion_range.len() as isize;
5371
5372 let start = ((insertion_start + tabstop_range.start) as usize)
5373 .min(snapshot.len());
5374 let end = ((insertion_start + tabstop_range.end) as usize)
5375 .min(snapshot.len());
5376 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5377 })
5378 })
5379 .collect::<Vec<_>>();
5380 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5381
5382 Tabstop {
5383 is_end_tabstop,
5384 ranges: tabstop_ranges,
5385 }
5386 })
5387 .collect::<Vec<_>>()
5388 });
5389 if let Some(tabstop) = tabstops.first() {
5390 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5391 s.select_ranges(tabstop.ranges.iter().cloned());
5392 });
5393
5394 // If we're already at the last tabstop and it's at the end of the snippet,
5395 // we're done, we don't need to keep the state around.
5396 if !tabstop.is_end_tabstop {
5397 let ranges = tabstops
5398 .into_iter()
5399 .map(|tabstop| tabstop.ranges)
5400 .collect::<Vec<_>>();
5401 self.snippet_stack.push(SnippetState {
5402 active_index: 0,
5403 ranges,
5404 });
5405 }
5406
5407 // Check whether the just-entered snippet ends with an auto-closable bracket.
5408 if self.autoclose_regions.is_empty() {
5409 let snapshot = self.buffer.read(cx).snapshot(cx);
5410 for selection in &mut self.selections.all::<Point>(cx) {
5411 let selection_head = selection.head();
5412 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5413 continue;
5414 };
5415
5416 let mut bracket_pair = None;
5417 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5418 let prev_chars = snapshot
5419 .reversed_chars_at(selection_head)
5420 .collect::<String>();
5421 for (pair, enabled) in scope.brackets() {
5422 if enabled
5423 && pair.close
5424 && prev_chars.starts_with(pair.start.as_str())
5425 && next_chars.starts_with(pair.end.as_str())
5426 {
5427 bracket_pair = Some(pair.clone());
5428 break;
5429 }
5430 }
5431 if let Some(pair) = bracket_pair {
5432 let start = snapshot.anchor_after(selection_head);
5433 let end = snapshot.anchor_after(selection_head);
5434 self.autoclose_regions.push(AutocloseRegion {
5435 selection_id: selection.id,
5436 range: start..end,
5437 pair,
5438 });
5439 }
5440 }
5441 }
5442 }
5443 Ok(())
5444 }
5445
5446 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5447 self.move_to_snippet_tabstop(Bias::Right, cx)
5448 }
5449
5450 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5451 self.move_to_snippet_tabstop(Bias::Left, cx)
5452 }
5453
5454 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5455 if let Some(mut snippet) = self.snippet_stack.pop() {
5456 match bias {
5457 Bias::Left => {
5458 if snippet.active_index > 0 {
5459 snippet.active_index -= 1;
5460 } else {
5461 self.snippet_stack.push(snippet);
5462 return false;
5463 }
5464 }
5465 Bias::Right => {
5466 if snippet.active_index + 1 < snippet.ranges.len() {
5467 snippet.active_index += 1;
5468 } else {
5469 self.snippet_stack.push(snippet);
5470 return false;
5471 }
5472 }
5473 }
5474 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5475 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5476 s.select_anchor_ranges(current_ranges.iter().cloned())
5477 });
5478 // If snippet state is not at the last tabstop, push it back on the stack
5479 if snippet.active_index + 1 < snippet.ranges.len() {
5480 self.snippet_stack.push(snippet);
5481 }
5482 return true;
5483 }
5484 }
5485
5486 false
5487 }
5488
5489 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5490 self.transact(cx, |this, cx| {
5491 this.select_all(&SelectAll, cx);
5492 this.insert("", cx);
5493 });
5494 }
5495
5496 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5497 self.transact(cx, |this, cx| {
5498 this.select_autoclose_pair(cx);
5499 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5500 if !this.linked_edit_ranges.is_empty() {
5501 let selections = this.selections.all::<MultiBufferPoint>(cx);
5502 let snapshot = this.buffer.read(cx).snapshot(cx);
5503
5504 for selection in selections.iter() {
5505 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5506 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5507 if selection_start.buffer_id != selection_end.buffer_id {
5508 continue;
5509 }
5510 if let Some(ranges) =
5511 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5512 {
5513 for (buffer, entries) in ranges {
5514 linked_ranges.entry(buffer).or_default().extend(entries);
5515 }
5516 }
5517 }
5518 }
5519
5520 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5521 if !this.selections.line_mode {
5522 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5523 for selection in &mut selections {
5524 if selection.is_empty() {
5525 let old_head = selection.head();
5526 let mut new_head =
5527 movement::left(&display_map, old_head.to_display_point(&display_map))
5528 .to_point(&display_map);
5529 if let Some((buffer, line_buffer_range)) = display_map
5530 .buffer_snapshot
5531 .buffer_line_for_row(MultiBufferRow(old_head.row))
5532 {
5533 let indent_size =
5534 buffer.indent_size_for_line(line_buffer_range.start.row);
5535 let indent_len = match indent_size.kind {
5536 IndentKind::Space => {
5537 buffer.settings_at(line_buffer_range.start, cx).tab_size
5538 }
5539 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5540 };
5541 if old_head.column <= indent_size.len && old_head.column > 0 {
5542 let indent_len = indent_len.get();
5543 new_head = cmp::min(
5544 new_head,
5545 MultiBufferPoint::new(
5546 old_head.row,
5547 ((old_head.column - 1) / indent_len) * indent_len,
5548 ),
5549 );
5550 }
5551 }
5552
5553 selection.set_head(new_head, SelectionGoal::None);
5554 }
5555 }
5556 }
5557
5558 this.signature_help_state.set_backspace_pressed(true);
5559 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5560 this.insert("", cx);
5561 let empty_str: Arc<str> = Arc::from("");
5562 for (buffer, edits) in linked_ranges {
5563 let snapshot = buffer.read(cx).snapshot();
5564 use text::ToPoint as TP;
5565
5566 let edits = edits
5567 .into_iter()
5568 .map(|range| {
5569 let end_point = TP::to_point(&range.end, &snapshot);
5570 let mut start_point = TP::to_point(&range.start, &snapshot);
5571
5572 if end_point == start_point {
5573 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5574 .saturating_sub(1);
5575 start_point = TP::to_point(&offset, &snapshot);
5576 };
5577
5578 (start_point..end_point, empty_str.clone())
5579 })
5580 .sorted_by_key(|(range, _)| range.start)
5581 .collect::<Vec<_>>();
5582 buffer.update(cx, |this, cx| {
5583 this.edit(edits, None, cx);
5584 })
5585 }
5586 this.refresh_inline_completion(true, false, cx);
5587 linked_editing_ranges::refresh_linked_ranges(this, cx);
5588 });
5589 }
5590
5591 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5592 self.transact(cx, |this, cx| {
5593 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5594 let line_mode = s.line_mode;
5595 s.move_with(|map, selection| {
5596 if selection.is_empty() && !line_mode {
5597 let cursor = movement::right(map, selection.head());
5598 selection.end = cursor;
5599 selection.reversed = true;
5600 selection.goal = SelectionGoal::None;
5601 }
5602 })
5603 });
5604 this.insert("", cx);
5605 this.refresh_inline_completion(true, false, cx);
5606 });
5607 }
5608
5609 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5610 if self.move_to_prev_snippet_tabstop(cx) {
5611 return;
5612 }
5613
5614 self.outdent(&Outdent, cx);
5615 }
5616
5617 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5618 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5619 return;
5620 }
5621
5622 let mut selections = self.selections.all_adjusted(cx);
5623 let buffer = self.buffer.read(cx);
5624 let snapshot = buffer.snapshot(cx);
5625 let rows_iter = selections.iter().map(|s| s.head().row);
5626 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5627
5628 let mut edits = Vec::new();
5629 let mut prev_edited_row = 0;
5630 let mut row_delta = 0;
5631 for selection in &mut selections {
5632 if selection.start.row != prev_edited_row {
5633 row_delta = 0;
5634 }
5635 prev_edited_row = selection.end.row;
5636
5637 // If the selection is non-empty, then increase the indentation of the selected lines.
5638 if !selection.is_empty() {
5639 row_delta =
5640 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5641 continue;
5642 }
5643
5644 // If the selection is empty and the cursor is in the leading whitespace before the
5645 // suggested indentation, then auto-indent the line.
5646 let cursor = selection.head();
5647 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5648 if let Some(suggested_indent) =
5649 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5650 {
5651 if cursor.column < suggested_indent.len
5652 && cursor.column <= current_indent.len
5653 && current_indent.len <= suggested_indent.len
5654 {
5655 selection.start = Point::new(cursor.row, suggested_indent.len);
5656 selection.end = selection.start;
5657 if row_delta == 0 {
5658 edits.extend(Buffer::edit_for_indent_size_adjustment(
5659 cursor.row,
5660 current_indent,
5661 suggested_indent,
5662 ));
5663 row_delta = suggested_indent.len - current_indent.len;
5664 }
5665 continue;
5666 }
5667 }
5668
5669 // Otherwise, insert a hard or soft tab.
5670 let settings = buffer.settings_at(cursor, cx);
5671 let tab_size = if settings.hard_tabs {
5672 IndentSize::tab()
5673 } else {
5674 let tab_size = settings.tab_size.get();
5675 let char_column = snapshot
5676 .text_for_range(Point::new(cursor.row, 0)..cursor)
5677 .flat_map(str::chars)
5678 .count()
5679 + row_delta as usize;
5680 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5681 IndentSize::spaces(chars_to_next_tab_stop)
5682 };
5683 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5684 selection.end = selection.start;
5685 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5686 row_delta += tab_size.len;
5687 }
5688
5689 self.transact(cx, |this, cx| {
5690 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5691 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5692 this.refresh_inline_completion(true, false, cx);
5693 });
5694 }
5695
5696 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5697 if self.read_only(cx) {
5698 return;
5699 }
5700 let mut selections = self.selections.all::<Point>(cx);
5701 let mut prev_edited_row = 0;
5702 let mut row_delta = 0;
5703 let mut edits = Vec::new();
5704 let buffer = self.buffer.read(cx);
5705 let snapshot = buffer.snapshot(cx);
5706 for selection in &mut selections {
5707 if selection.start.row != prev_edited_row {
5708 row_delta = 0;
5709 }
5710 prev_edited_row = selection.end.row;
5711
5712 row_delta =
5713 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5714 }
5715
5716 self.transact(cx, |this, cx| {
5717 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5718 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5719 });
5720 }
5721
5722 fn indent_selection(
5723 buffer: &MultiBuffer,
5724 snapshot: &MultiBufferSnapshot,
5725 selection: &mut Selection<Point>,
5726 edits: &mut Vec<(Range<Point>, String)>,
5727 delta_for_start_row: u32,
5728 cx: &AppContext,
5729 ) -> u32 {
5730 let settings = buffer.settings_at(selection.start, cx);
5731 let tab_size = settings.tab_size.get();
5732 let indent_kind = if settings.hard_tabs {
5733 IndentKind::Tab
5734 } else {
5735 IndentKind::Space
5736 };
5737 let mut start_row = selection.start.row;
5738 let mut end_row = selection.end.row + 1;
5739
5740 // If a selection ends at the beginning of a line, don't indent
5741 // that last line.
5742 if selection.end.column == 0 && selection.end.row > selection.start.row {
5743 end_row -= 1;
5744 }
5745
5746 // Avoid re-indenting a row that has already been indented by a
5747 // previous selection, but still update this selection's column
5748 // to reflect that indentation.
5749 if delta_for_start_row > 0 {
5750 start_row += 1;
5751 selection.start.column += delta_for_start_row;
5752 if selection.end.row == selection.start.row {
5753 selection.end.column += delta_for_start_row;
5754 }
5755 }
5756
5757 let mut delta_for_end_row = 0;
5758 let has_multiple_rows = start_row + 1 != end_row;
5759 for row in start_row..end_row {
5760 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5761 let indent_delta = match (current_indent.kind, indent_kind) {
5762 (IndentKind::Space, IndentKind::Space) => {
5763 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5764 IndentSize::spaces(columns_to_next_tab_stop)
5765 }
5766 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5767 (_, IndentKind::Tab) => IndentSize::tab(),
5768 };
5769
5770 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5771 0
5772 } else {
5773 selection.start.column
5774 };
5775 let row_start = Point::new(row, start);
5776 edits.push((
5777 row_start..row_start,
5778 indent_delta.chars().collect::<String>(),
5779 ));
5780
5781 // Update this selection's endpoints to reflect the indentation.
5782 if row == selection.start.row {
5783 selection.start.column += indent_delta.len;
5784 }
5785 if row == selection.end.row {
5786 selection.end.column += indent_delta.len;
5787 delta_for_end_row = indent_delta.len;
5788 }
5789 }
5790
5791 if selection.start.row == selection.end.row {
5792 delta_for_start_row + delta_for_end_row
5793 } else {
5794 delta_for_end_row
5795 }
5796 }
5797
5798 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5799 if self.read_only(cx) {
5800 return;
5801 }
5802 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5803 let selections = self.selections.all::<Point>(cx);
5804 let mut deletion_ranges = Vec::new();
5805 let mut last_outdent = None;
5806 {
5807 let buffer = self.buffer.read(cx);
5808 let snapshot = buffer.snapshot(cx);
5809 for selection in &selections {
5810 let settings = buffer.settings_at(selection.start, cx);
5811 let tab_size = settings.tab_size.get();
5812 let mut rows = selection.spanned_rows(false, &display_map);
5813
5814 // Avoid re-outdenting a row that has already been outdented by a
5815 // previous selection.
5816 if let Some(last_row) = last_outdent {
5817 if last_row == rows.start {
5818 rows.start = rows.start.next_row();
5819 }
5820 }
5821 let has_multiple_rows = rows.len() > 1;
5822 for row in rows.iter_rows() {
5823 let indent_size = snapshot.indent_size_for_line(row);
5824 if indent_size.len > 0 {
5825 let deletion_len = match indent_size.kind {
5826 IndentKind::Space => {
5827 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5828 if columns_to_prev_tab_stop == 0 {
5829 tab_size
5830 } else {
5831 columns_to_prev_tab_stop
5832 }
5833 }
5834 IndentKind::Tab => 1,
5835 };
5836 let start = if has_multiple_rows
5837 || deletion_len > selection.start.column
5838 || indent_size.len < selection.start.column
5839 {
5840 0
5841 } else {
5842 selection.start.column - deletion_len
5843 };
5844 deletion_ranges.push(
5845 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5846 );
5847 last_outdent = Some(row);
5848 }
5849 }
5850 }
5851 }
5852
5853 self.transact(cx, |this, cx| {
5854 this.buffer.update(cx, |buffer, cx| {
5855 let empty_str: Arc<str> = Arc::default();
5856 buffer.edit(
5857 deletion_ranges
5858 .into_iter()
5859 .map(|range| (range, empty_str.clone())),
5860 None,
5861 cx,
5862 );
5863 });
5864 let selections = this.selections.all::<usize>(cx);
5865 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5866 });
5867 }
5868
5869 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5871 let selections = self.selections.all::<Point>(cx);
5872
5873 let mut new_cursors = Vec::new();
5874 let mut edit_ranges = Vec::new();
5875 let mut selections = selections.iter().peekable();
5876 while let Some(selection) = selections.next() {
5877 let mut rows = selection.spanned_rows(false, &display_map);
5878 let goal_display_column = selection.head().to_display_point(&display_map).column();
5879
5880 // Accumulate contiguous regions of rows that we want to delete.
5881 while let Some(next_selection) = selections.peek() {
5882 let next_rows = next_selection.spanned_rows(false, &display_map);
5883 if next_rows.start <= rows.end {
5884 rows.end = next_rows.end;
5885 selections.next().unwrap();
5886 } else {
5887 break;
5888 }
5889 }
5890
5891 let buffer = &display_map.buffer_snapshot;
5892 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5893 let edit_end;
5894 let cursor_buffer_row;
5895 if buffer.max_point().row >= rows.end.0 {
5896 // If there's a line after the range, delete the \n from the end of the row range
5897 // and position the cursor on the next line.
5898 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5899 cursor_buffer_row = rows.end;
5900 } else {
5901 // If there isn't a line after the range, delete the \n from the line before the
5902 // start of the row range and position the cursor there.
5903 edit_start = edit_start.saturating_sub(1);
5904 edit_end = buffer.len();
5905 cursor_buffer_row = rows.start.previous_row();
5906 }
5907
5908 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5909 *cursor.column_mut() =
5910 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5911
5912 new_cursors.push((
5913 selection.id,
5914 buffer.anchor_after(cursor.to_point(&display_map)),
5915 ));
5916 edit_ranges.push(edit_start..edit_end);
5917 }
5918
5919 self.transact(cx, |this, cx| {
5920 let buffer = this.buffer.update(cx, |buffer, cx| {
5921 let empty_str: Arc<str> = Arc::default();
5922 buffer.edit(
5923 edit_ranges
5924 .into_iter()
5925 .map(|range| (range, empty_str.clone())),
5926 None,
5927 cx,
5928 );
5929 buffer.snapshot(cx)
5930 });
5931 let new_selections = new_cursors
5932 .into_iter()
5933 .map(|(id, cursor)| {
5934 let cursor = cursor.to_point(&buffer);
5935 Selection {
5936 id,
5937 start: cursor,
5938 end: cursor,
5939 reversed: false,
5940 goal: SelectionGoal::None,
5941 }
5942 })
5943 .collect();
5944
5945 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5946 s.select(new_selections);
5947 });
5948 });
5949 }
5950
5951 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5952 if self.read_only(cx) {
5953 return;
5954 }
5955 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5956 for selection in self.selections.all::<Point>(cx) {
5957 let start = MultiBufferRow(selection.start.row);
5958 let end = if selection.start.row == selection.end.row {
5959 MultiBufferRow(selection.start.row + 1)
5960 } else {
5961 MultiBufferRow(selection.end.row)
5962 };
5963
5964 if let Some(last_row_range) = row_ranges.last_mut() {
5965 if start <= last_row_range.end {
5966 last_row_range.end = end;
5967 continue;
5968 }
5969 }
5970 row_ranges.push(start..end);
5971 }
5972
5973 let snapshot = self.buffer.read(cx).snapshot(cx);
5974 let mut cursor_positions = Vec::new();
5975 for row_range in &row_ranges {
5976 let anchor = snapshot.anchor_before(Point::new(
5977 row_range.end.previous_row().0,
5978 snapshot.line_len(row_range.end.previous_row()),
5979 ));
5980 cursor_positions.push(anchor..anchor);
5981 }
5982
5983 self.transact(cx, |this, cx| {
5984 for row_range in row_ranges.into_iter().rev() {
5985 for row in row_range.iter_rows().rev() {
5986 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5987 let next_line_row = row.next_row();
5988 let indent = snapshot.indent_size_for_line(next_line_row);
5989 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5990
5991 let replace = if snapshot.line_len(next_line_row) > indent.len {
5992 " "
5993 } else {
5994 ""
5995 };
5996
5997 this.buffer.update(cx, |buffer, cx| {
5998 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5999 });
6000 }
6001 }
6002
6003 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6004 s.select_anchor_ranges(cursor_positions)
6005 });
6006 });
6007 }
6008
6009 pub fn sort_lines_case_sensitive(
6010 &mut self,
6011 _: &SortLinesCaseSensitive,
6012 cx: &mut ViewContext<Self>,
6013 ) {
6014 self.manipulate_lines(cx, |lines| lines.sort())
6015 }
6016
6017 pub fn sort_lines_case_insensitive(
6018 &mut self,
6019 _: &SortLinesCaseInsensitive,
6020 cx: &mut ViewContext<Self>,
6021 ) {
6022 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6023 }
6024
6025 pub fn unique_lines_case_insensitive(
6026 &mut self,
6027 _: &UniqueLinesCaseInsensitive,
6028 cx: &mut ViewContext<Self>,
6029 ) {
6030 self.manipulate_lines(cx, |lines| {
6031 let mut seen = HashSet::default();
6032 lines.retain(|line| seen.insert(line.to_lowercase()));
6033 })
6034 }
6035
6036 pub fn unique_lines_case_sensitive(
6037 &mut self,
6038 _: &UniqueLinesCaseSensitive,
6039 cx: &mut ViewContext<Self>,
6040 ) {
6041 self.manipulate_lines(cx, |lines| {
6042 let mut seen = HashSet::default();
6043 lines.retain(|line| seen.insert(*line));
6044 })
6045 }
6046
6047 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6048 let mut revert_changes = HashMap::default();
6049 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6050 for hunk in hunks_for_rows(
6051 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6052 &multi_buffer_snapshot,
6053 ) {
6054 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6055 }
6056 if !revert_changes.is_empty() {
6057 self.transact(cx, |editor, cx| {
6058 editor.revert(revert_changes, cx);
6059 });
6060 }
6061 }
6062
6063 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6064 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6065 if !revert_changes.is_empty() {
6066 self.transact(cx, |editor, cx| {
6067 editor.revert(revert_changes, cx);
6068 });
6069 }
6070 }
6071
6072 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6073 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6074 let project_path = buffer.read(cx).project_path(cx)?;
6075 let project = self.project.as_ref()?.read(cx);
6076 let entry = project.entry_for_path(&project_path, cx)?;
6077 let abs_path = project.absolute_path(&project_path, cx)?;
6078 let parent = if entry.is_symlink {
6079 abs_path.canonicalize().ok()?
6080 } else {
6081 abs_path
6082 }
6083 .parent()?
6084 .to_path_buf();
6085 Some(parent)
6086 }) {
6087 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6088 }
6089 }
6090
6091 fn gather_revert_changes(
6092 &mut self,
6093 selections: &[Selection<Anchor>],
6094 cx: &mut ViewContext<'_, Editor>,
6095 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6096 let mut revert_changes = HashMap::default();
6097 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6098 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6099 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6100 }
6101 revert_changes
6102 }
6103
6104 pub fn prepare_revert_change(
6105 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6106 multi_buffer: &Model<MultiBuffer>,
6107 hunk: &DiffHunk<MultiBufferRow>,
6108 cx: &AppContext,
6109 ) -> Option<()> {
6110 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6111 let buffer = buffer.read(cx);
6112 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6113 let buffer_snapshot = buffer.snapshot();
6114 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6115 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6116 probe
6117 .0
6118 .start
6119 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6120 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6121 }) {
6122 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6123 Some(())
6124 } else {
6125 None
6126 }
6127 }
6128
6129 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6130 self.manipulate_lines(cx, |lines| lines.reverse())
6131 }
6132
6133 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6134 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6135 }
6136
6137 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6138 where
6139 Fn: FnMut(&mut Vec<&str>),
6140 {
6141 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6142 let buffer = self.buffer.read(cx).snapshot(cx);
6143
6144 let mut edits = Vec::new();
6145
6146 let selections = self.selections.all::<Point>(cx);
6147 let mut selections = selections.iter().peekable();
6148 let mut contiguous_row_selections = Vec::new();
6149 let mut new_selections = Vec::new();
6150 let mut added_lines = 0;
6151 let mut removed_lines = 0;
6152
6153 while let Some(selection) = selections.next() {
6154 let (start_row, end_row) = consume_contiguous_rows(
6155 &mut contiguous_row_selections,
6156 selection,
6157 &display_map,
6158 &mut selections,
6159 );
6160
6161 let start_point = Point::new(start_row.0, 0);
6162 let end_point = Point::new(
6163 end_row.previous_row().0,
6164 buffer.line_len(end_row.previous_row()),
6165 );
6166 let text = buffer
6167 .text_for_range(start_point..end_point)
6168 .collect::<String>();
6169
6170 let mut lines = text.split('\n').collect_vec();
6171
6172 let lines_before = lines.len();
6173 callback(&mut lines);
6174 let lines_after = lines.len();
6175
6176 edits.push((start_point..end_point, lines.join("\n")));
6177
6178 // Selections must change based on added and removed line count
6179 let start_row =
6180 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6181 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6182 new_selections.push(Selection {
6183 id: selection.id,
6184 start: start_row,
6185 end: end_row,
6186 goal: SelectionGoal::None,
6187 reversed: selection.reversed,
6188 });
6189
6190 if lines_after > lines_before {
6191 added_lines += lines_after - lines_before;
6192 } else if lines_before > lines_after {
6193 removed_lines += lines_before - lines_after;
6194 }
6195 }
6196
6197 self.transact(cx, |this, cx| {
6198 let buffer = this.buffer.update(cx, |buffer, cx| {
6199 buffer.edit(edits, None, cx);
6200 buffer.snapshot(cx)
6201 });
6202
6203 // Recalculate offsets on newly edited buffer
6204 let new_selections = new_selections
6205 .iter()
6206 .map(|s| {
6207 let start_point = Point::new(s.start.0, 0);
6208 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6209 Selection {
6210 id: s.id,
6211 start: buffer.point_to_offset(start_point),
6212 end: buffer.point_to_offset(end_point),
6213 goal: s.goal,
6214 reversed: s.reversed,
6215 }
6216 })
6217 .collect();
6218
6219 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6220 s.select(new_selections);
6221 });
6222
6223 this.request_autoscroll(Autoscroll::fit(), cx);
6224 });
6225 }
6226
6227 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6228 self.manipulate_text(cx, |text| text.to_uppercase())
6229 }
6230
6231 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6232 self.manipulate_text(cx, |text| text.to_lowercase())
6233 }
6234
6235 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6236 self.manipulate_text(cx, |text| {
6237 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6238 // https://github.com/rutrum/convert-case/issues/16
6239 text.split('\n')
6240 .map(|line| line.to_case(Case::Title))
6241 .join("\n")
6242 })
6243 }
6244
6245 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6246 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6247 }
6248
6249 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6250 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6251 }
6252
6253 pub fn convert_to_upper_camel_case(
6254 &mut self,
6255 _: &ConvertToUpperCamelCase,
6256 cx: &mut ViewContext<Self>,
6257 ) {
6258 self.manipulate_text(cx, |text| {
6259 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6260 // https://github.com/rutrum/convert-case/issues/16
6261 text.split('\n')
6262 .map(|line| line.to_case(Case::UpperCamel))
6263 .join("\n")
6264 })
6265 }
6266
6267 pub fn convert_to_lower_camel_case(
6268 &mut self,
6269 _: &ConvertToLowerCamelCase,
6270 cx: &mut ViewContext<Self>,
6271 ) {
6272 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6273 }
6274
6275 pub fn convert_to_opposite_case(
6276 &mut self,
6277 _: &ConvertToOppositeCase,
6278 cx: &mut ViewContext<Self>,
6279 ) {
6280 self.manipulate_text(cx, |text| {
6281 text.chars()
6282 .fold(String::with_capacity(text.len()), |mut t, c| {
6283 if c.is_uppercase() {
6284 t.extend(c.to_lowercase());
6285 } else {
6286 t.extend(c.to_uppercase());
6287 }
6288 t
6289 })
6290 })
6291 }
6292
6293 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6294 where
6295 Fn: FnMut(&str) -> String,
6296 {
6297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6298 let buffer = self.buffer.read(cx).snapshot(cx);
6299
6300 let mut new_selections = Vec::new();
6301 let mut edits = Vec::new();
6302 let mut selection_adjustment = 0i32;
6303
6304 for selection in self.selections.all::<usize>(cx) {
6305 let selection_is_empty = selection.is_empty();
6306
6307 let (start, end) = if selection_is_empty {
6308 let word_range = movement::surrounding_word(
6309 &display_map,
6310 selection.start.to_display_point(&display_map),
6311 );
6312 let start = word_range.start.to_offset(&display_map, Bias::Left);
6313 let end = word_range.end.to_offset(&display_map, Bias::Left);
6314 (start, end)
6315 } else {
6316 (selection.start, selection.end)
6317 };
6318
6319 let text = buffer.text_for_range(start..end).collect::<String>();
6320 let old_length = text.len() as i32;
6321 let text = callback(&text);
6322
6323 new_selections.push(Selection {
6324 start: (start as i32 - selection_adjustment) as usize,
6325 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6326 goal: SelectionGoal::None,
6327 ..selection
6328 });
6329
6330 selection_adjustment += old_length - text.len() as i32;
6331
6332 edits.push((start..end, text));
6333 }
6334
6335 self.transact(cx, |this, cx| {
6336 this.buffer.update(cx, |buffer, cx| {
6337 buffer.edit(edits, None, cx);
6338 });
6339
6340 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6341 s.select(new_selections);
6342 });
6343
6344 this.request_autoscroll(Autoscroll::fit(), cx);
6345 });
6346 }
6347
6348 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6350 let buffer = &display_map.buffer_snapshot;
6351 let selections = self.selections.all::<Point>(cx);
6352
6353 let mut edits = Vec::new();
6354 let mut selections_iter = selections.iter().peekable();
6355 while let Some(selection) = selections_iter.next() {
6356 // Avoid duplicating the same lines twice.
6357 let mut rows = selection.spanned_rows(false, &display_map);
6358
6359 while let Some(next_selection) = selections_iter.peek() {
6360 let next_rows = next_selection.spanned_rows(false, &display_map);
6361 if next_rows.start < rows.end {
6362 rows.end = next_rows.end;
6363 selections_iter.next().unwrap();
6364 } else {
6365 break;
6366 }
6367 }
6368
6369 // Copy the text from the selected row region and splice it either at the start
6370 // or end of the region.
6371 let start = Point::new(rows.start.0, 0);
6372 let end = Point::new(
6373 rows.end.previous_row().0,
6374 buffer.line_len(rows.end.previous_row()),
6375 );
6376 let text = buffer
6377 .text_for_range(start..end)
6378 .chain(Some("\n"))
6379 .collect::<String>();
6380 let insert_location = if upwards {
6381 Point::new(rows.end.0, 0)
6382 } else {
6383 start
6384 };
6385 edits.push((insert_location..insert_location, text));
6386 }
6387
6388 self.transact(cx, |this, cx| {
6389 this.buffer.update(cx, |buffer, cx| {
6390 buffer.edit(edits, None, cx);
6391 });
6392
6393 this.request_autoscroll(Autoscroll::fit(), cx);
6394 });
6395 }
6396
6397 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6398 self.duplicate_line(true, cx);
6399 }
6400
6401 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6402 self.duplicate_line(false, cx);
6403 }
6404
6405 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6407 let buffer = self.buffer.read(cx).snapshot(cx);
6408
6409 let mut edits = Vec::new();
6410 let mut unfold_ranges = Vec::new();
6411 let mut refold_ranges = Vec::new();
6412
6413 let selections = self.selections.all::<Point>(cx);
6414 let mut selections = selections.iter().peekable();
6415 let mut contiguous_row_selections = Vec::new();
6416 let mut new_selections = Vec::new();
6417
6418 while let Some(selection) = selections.next() {
6419 // Find all the selections that span a contiguous row range
6420 let (start_row, end_row) = consume_contiguous_rows(
6421 &mut contiguous_row_selections,
6422 selection,
6423 &display_map,
6424 &mut selections,
6425 );
6426
6427 // Move the text spanned by the row range to be before the line preceding the row range
6428 if start_row.0 > 0 {
6429 let range_to_move = Point::new(
6430 start_row.previous_row().0,
6431 buffer.line_len(start_row.previous_row()),
6432 )
6433 ..Point::new(
6434 end_row.previous_row().0,
6435 buffer.line_len(end_row.previous_row()),
6436 );
6437 let insertion_point = display_map
6438 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6439 .0;
6440
6441 // Don't move lines across excerpts
6442 if buffer
6443 .excerpt_boundaries_in_range((
6444 Bound::Excluded(insertion_point),
6445 Bound::Included(range_to_move.end),
6446 ))
6447 .next()
6448 .is_none()
6449 {
6450 let text = buffer
6451 .text_for_range(range_to_move.clone())
6452 .flat_map(|s| s.chars())
6453 .skip(1)
6454 .chain(['\n'])
6455 .collect::<String>();
6456
6457 edits.push((
6458 buffer.anchor_after(range_to_move.start)
6459 ..buffer.anchor_before(range_to_move.end),
6460 String::new(),
6461 ));
6462 let insertion_anchor = buffer.anchor_after(insertion_point);
6463 edits.push((insertion_anchor..insertion_anchor, text));
6464
6465 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6466
6467 // Move selections up
6468 new_selections.extend(contiguous_row_selections.drain(..).map(
6469 |mut selection| {
6470 selection.start.row -= row_delta;
6471 selection.end.row -= row_delta;
6472 selection
6473 },
6474 ));
6475
6476 // Move folds up
6477 unfold_ranges.push(range_to_move.clone());
6478 for fold in display_map.folds_in_range(
6479 buffer.anchor_before(range_to_move.start)
6480 ..buffer.anchor_after(range_to_move.end),
6481 ) {
6482 let mut start = fold.range.start.to_point(&buffer);
6483 let mut end = fold.range.end.to_point(&buffer);
6484 start.row -= row_delta;
6485 end.row -= row_delta;
6486 refold_ranges.push((start..end, fold.placeholder.clone()));
6487 }
6488 }
6489 }
6490
6491 // If we didn't move line(s), preserve the existing selections
6492 new_selections.append(&mut contiguous_row_selections);
6493 }
6494
6495 self.transact(cx, |this, cx| {
6496 this.unfold_ranges(unfold_ranges, true, true, cx);
6497 this.buffer.update(cx, |buffer, cx| {
6498 for (range, text) in edits {
6499 buffer.edit([(range, text)], None, cx);
6500 }
6501 });
6502 this.fold_ranges(refold_ranges, true, cx);
6503 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6504 s.select(new_selections);
6505 })
6506 });
6507 }
6508
6509 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6510 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6511 let buffer = self.buffer.read(cx).snapshot(cx);
6512
6513 let mut edits = Vec::new();
6514 let mut unfold_ranges = Vec::new();
6515 let mut refold_ranges = Vec::new();
6516
6517 let selections = self.selections.all::<Point>(cx);
6518 let mut selections = selections.iter().peekable();
6519 let mut contiguous_row_selections = Vec::new();
6520 let mut new_selections = Vec::new();
6521
6522 while let Some(selection) = selections.next() {
6523 // Find all the selections that span a contiguous row range
6524 let (start_row, end_row) = consume_contiguous_rows(
6525 &mut contiguous_row_selections,
6526 selection,
6527 &display_map,
6528 &mut selections,
6529 );
6530
6531 // Move the text spanned by the row range to be after the last line of the row range
6532 if end_row.0 <= buffer.max_point().row {
6533 let range_to_move =
6534 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6535 let insertion_point = display_map
6536 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6537 .0;
6538
6539 // Don't move lines across excerpt boundaries
6540 if buffer
6541 .excerpt_boundaries_in_range((
6542 Bound::Excluded(range_to_move.start),
6543 Bound::Included(insertion_point),
6544 ))
6545 .next()
6546 .is_none()
6547 {
6548 let mut text = String::from("\n");
6549 text.extend(buffer.text_for_range(range_to_move.clone()));
6550 text.pop(); // Drop trailing newline
6551 edits.push((
6552 buffer.anchor_after(range_to_move.start)
6553 ..buffer.anchor_before(range_to_move.end),
6554 String::new(),
6555 ));
6556 let insertion_anchor = buffer.anchor_after(insertion_point);
6557 edits.push((insertion_anchor..insertion_anchor, text));
6558
6559 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6560
6561 // Move selections down
6562 new_selections.extend(contiguous_row_selections.drain(..).map(
6563 |mut selection| {
6564 selection.start.row += row_delta;
6565 selection.end.row += row_delta;
6566 selection
6567 },
6568 ));
6569
6570 // Move folds down
6571 unfold_ranges.push(range_to_move.clone());
6572 for fold in display_map.folds_in_range(
6573 buffer.anchor_before(range_to_move.start)
6574 ..buffer.anchor_after(range_to_move.end),
6575 ) {
6576 let mut start = fold.range.start.to_point(&buffer);
6577 let mut end = fold.range.end.to_point(&buffer);
6578 start.row += row_delta;
6579 end.row += row_delta;
6580 refold_ranges.push((start..end, fold.placeholder.clone()));
6581 }
6582 }
6583 }
6584
6585 // If we didn't move line(s), preserve the existing selections
6586 new_selections.append(&mut contiguous_row_selections);
6587 }
6588
6589 self.transact(cx, |this, cx| {
6590 this.unfold_ranges(unfold_ranges, true, true, cx);
6591 this.buffer.update(cx, |buffer, cx| {
6592 for (range, text) in edits {
6593 buffer.edit([(range, text)], None, cx);
6594 }
6595 });
6596 this.fold_ranges(refold_ranges, true, cx);
6597 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6598 });
6599 }
6600
6601 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6602 let text_layout_details = &self.text_layout_details(cx);
6603 self.transact(cx, |this, cx| {
6604 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6605 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6606 let line_mode = s.line_mode;
6607 s.move_with(|display_map, selection| {
6608 if !selection.is_empty() || line_mode {
6609 return;
6610 }
6611
6612 let mut head = selection.head();
6613 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6614 if head.column() == display_map.line_len(head.row()) {
6615 transpose_offset = display_map
6616 .buffer_snapshot
6617 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6618 }
6619
6620 if transpose_offset == 0 {
6621 return;
6622 }
6623
6624 *head.column_mut() += 1;
6625 head = display_map.clip_point(head, Bias::Right);
6626 let goal = SelectionGoal::HorizontalPosition(
6627 display_map
6628 .x_for_display_point(head, text_layout_details)
6629 .into(),
6630 );
6631 selection.collapse_to(head, goal);
6632
6633 let transpose_start = display_map
6634 .buffer_snapshot
6635 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6636 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6637 let transpose_end = display_map
6638 .buffer_snapshot
6639 .clip_offset(transpose_offset + 1, Bias::Right);
6640 if let Some(ch) =
6641 display_map.buffer_snapshot.chars_at(transpose_start).next()
6642 {
6643 edits.push((transpose_start..transpose_offset, String::new()));
6644 edits.push((transpose_end..transpose_end, ch.to_string()));
6645 }
6646 }
6647 });
6648 edits
6649 });
6650 this.buffer
6651 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6652 let selections = this.selections.all::<usize>(cx);
6653 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6654 s.select(selections);
6655 });
6656 });
6657 }
6658
6659 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6660 let mut text = String::new();
6661 let buffer = self.buffer.read(cx).snapshot(cx);
6662 let mut selections = self.selections.all::<Point>(cx);
6663 let mut clipboard_selections = Vec::with_capacity(selections.len());
6664 {
6665 let max_point = buffer.max_point();
6666 let mut is_first = true;
6667 for selection in &mut selections {
6668 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6669 if is_entire_line {
6670 selection.start = Point::new(selection.start.row, 0);
6671 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6672 selection.goal = SelectionGoal::None;
6673 }
6674 if is_first {
6675 is_first = false;
6676 } else {
6677 text += "\n";
6678 }
6679 let mut len = 0;
6680 for chunk in buffer.text_for_range(selection.start..selection.end) {
6681 text.push_str(chunk);
6682 len += chunk.len();
6683 }
6684 clipboard_selections.push(ClipboardSelection {
6685 len,
6686 is_entire_line,
6687 first_line_indent: buffer
6688 .indent_size_for_line(MultiBufferRow(selection.start.row))
6689 .len,
6690 });
6691 }
6692 }
6693
6694 self.transact(cx, |this, cx| {
6695 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6696 s.select(selections);
6697 });
6698 this.insert("", cx);
6699 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6700 text,
6701 clipboard_selections,
6702 ));
6703 });
6704 }
6705
6706 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6707 let selections = self.selections.all::<Point>(cx);
6708 let buffer = self.buffer.read(cx).read(cx);
6709 let mut text = String::new();
6710
6711 let mut clipboard_selections = Vec::with_capacity(selections.len());
6712 {
6713 let max_point = buffer.max_point();
6714 let mut is_first = true;
6715 for selection in selections.iter() {
6716 let mut start = selection.start;
6717 let mut end = selection.end;
6718 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6719 if is_entire_line {
6720 start = Point::new(start.row, 0);
6721 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6722 }
6723 if is_first {
6724 is_first = false;
6725 } else {
6726 text += "\n";
6727 }
6728 let mut len = 0;
6729 for chunk in buffer.text_for_range(start..end) {
6730 text.push_str(chunk);
6731 len += chunk.len();
6732 }
6733 clipboard_selections.push(ClipboardSelection {
6734 len,
6735 is_entire_line,
6736 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6737 });
6738 }
6739 }
6740
6741 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6742 text,
6743 clipboard_selections,
6744 ));
6745 }
6746
6747 pub fn do_paste(
6748 &mut self,
6749 text: &String,
6750 clipboard_selections: Option<Vec<ClipboardSelection>>,
6751 handle_entire_lines: bool,
6752 cx: &mut ViewContext<Self>,
6753 ) {
6754 if self.read_only(cx) {
6755 return;
6756 }
6757
6758 let clipboard_text = Cow::Borrowed(text);
6759
6760 self.transact(cx, |this, cx| {
6761 if let Some(mut clipboard_selections) = clipboard_selections {
6762 let old_selections = this.selections.all::<usize>(cx);
6763 let all_selections_were_entire_line =
6764 clipboard_selections.iter().all(|s| s.is_entire_line);
6765 let first_selection_indent_column =
6766 clipboard_selections.first().map(|s| s.first_line_indent);
6767 if clipboard_selections.len() != old_selections.len() {
6768 clipboard_selections.drain(..);
6769 }
6770
6771 this.buffer.update(cx, |buffer, cx| {
6772 let snapshot = buffer.read(cx);
6773 let mut start_offset = 0;
6774 let mut edits = Vec::new();
6775 let mut original_indent_columns = Vec::new();
6776 for (ix, selection) in old_selections.iter().enumerate() {
6777 let to_insert;
6778 let entire_line;
6779 let original_indent_column;
6780 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6781 let end_offset = start_offset + clipboard_selection.len;
6782 to_insert = &clipboard_text[start_offset..end_offset];
6783 entire_line = clipboard_selection.is_entire_line;
6784 start_offset = end_offset + 1;
6785 original_indent_column = Some(clipboard_selection.first_line_indent);
6786 } else {
6787 to_insert = clipboard_text.as_str();
6788 entire_line = all_selections_were_entire_line;
6789 original_indent_column = first_selection_indent_column
6790 }
6791
6792 // If the corresponding selection was empty when this slice of the
6793 // clipboard text was written, then the entire line containing the
6794 // selection was copied. If this selection is also currently empty,
6795 // then paste the line before the current line of the buffer.
6796 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6797 let column = selection.start.to_point(&snapshot).column as usize;
6798 let line_start = selection.start - column;
6799 line_start..line_start
6800 } else {
6801 selection.range()
6802 };
6803
6804 edits.push((range, to_insert));
6805 original_indent_columns.extend(original_indent_column);
6806 }
6807 drop(snapshot);
6808
6809 buffer.edit(
6810 edits,
6811 Some(AutoindentMode::Block {
6812 original_indent_columns,
6813 }),
6814 cx,
6815 );
6816 });
6817
6818 let selections = this.selections.all::<usize>(cx);
6819 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6820 } else {
6821 this.insert(&clipboard_text, cx);
6822 }
6823 });
6824 }
6825
6826 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6827 if let Some(item) = cx.read_from_clipboard() {
6828 let entries = item.entries();
6829
6830 match entries.first() {
6831 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6832 // of all the pasted entries.
6833 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6834 .do_paste(
6835 clipboard_string.text(),
6836 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6837 true,
6838 cx,
6839 ),
6840 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6841 }
6842 }
6843 }
6844
6845 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6846 if self.read_only(cx) {
6847 return;
6848 }
6849
6850 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6851 if let Some((selections, _)) =
6852 self.selection_history.transaction(transaction_id).cloned()
6853 {
6854 self.change_selections(None, cx, |s| {
6855 s.select_anchors(selections.to_vec());
6856 });
6857 }
6858 self.request_autoscroll(Autoscroll::fit(), cx);
6859 self.unmark_text(cx);
6860 self.refresh_inline_completion(true, false, cx);
6861 cx.emit(EditorEvent::Edited { transaction_id });
6862 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6863 }
6864 }
6865
6866 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6867 if self.read_only(cx) {
6868 return;
6869 }
6870
6871 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6872 if let Some((_, Some(selections))) =
6873 self.selection_history.transaction(transaction_id).cloned()
6874 {
6875 self.change_selections(None, cx, |s| {
6876 s.select_anchors(selections.to_vec());
6877 });
6878 }
6879 self.request_autoscroll(Autoscroll::fit(), cx);
6880 self.unmark_text(cx);
6881 self.refresh_inline_completion(true, false, cx);
6882 cx.emit(EditorEvent::Edited { transaction_id });
6883 }
6884 }
6885
6886 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6887 self.buffer
6888 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6889 }
6890
6891 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6892 self.buffer
6893 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6894 }
6895
6896 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6897 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6898 let line_mode = s.line_mode;
6899 s.move_with(|map, selection| {
6900 let cursor = if selection.is_empty() && !line_mode {
6901 movement::left(map, selection.start)
6902 } else {
6903 selection.start
6904 };
6905 selection.collapse_to(cursor, SelectionGoal::None);
6906 });
6907 })
6908 }
6909
6910 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6912 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6913 })
6914 }
6915
6916 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6917 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6918 let line_mode = s.line_mode;
6919 s.move_with(|map, selection| {
6920 let cursor = if selection.is_empty() && !line_mode {
6921 movement::right(map, selection.end)
6922 } else {
6923 selection.end
6924 };
6925 selection.collapse_to(cursor, SelectionGoal::None)
6926 });
6927 })
6928 }
6929
6930 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6931 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6932 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6933 })
6934 }
6935
6936 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6937 if self.take_rename(true, cx).is_some() {
6938 return;
6939 }
6940
6941 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6942 cx.propagate();
6943 return;
6944 }
6945
6946 let text_layout_details = &self.text_layout_details(cx);
6947 let selection_count = self.selections.count();
6948 let first_selection = self.selections.first_anchor();
6949
6950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6951 let line_mode = s.line_mode;
6952 s.move_with(|map, selection| {
6953 if !selection.is_empty() && !line_mode {
6954 selection.goal = SelectionGoal::None;
6955 }
6956 let (cursor, goal) = movement::up(
6957 map,
6958 selection.start,
6959 selection.goal,
6960 false,
6961 text_layout_details,
6962 );
6963 selection.collapse_to(cursor, goal);
6964 });
6965 });
6966
6967 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6968 {
6969 cx.propagate();
6970 }
6971 }
6972
6973 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6974 if self.take_rename(true, cx).is_some() {
6975 return;
6976 }
6977
6978 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6979 cx.propagate();
6980 return;
6981 }
6982
6983 let text_layout_details = &self.text_layout_details(cx);
6984
6985 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6986 let line_mode = s.line_mode;
6987 s.move_with(|map, selection| {
6988 if !selection.is_empty() && !line_mode {
6989 selection.goal = SelectionGoal::None;
6990 }
6991 let (cursor, goal) = movement::up_by_rows(
6992 map,
6993 selection.start,
6994 action.lines,
6995 selection.goal,
6996 false,
6997 text_layout_details,
6998 );
6999 selection.collapse_to(cursor, goal);
7000 });
7001 })
7002 }
7003
7004 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7005 if self.take_rename(true, cx).is_some() {
7006 return;
7007 }
7008
7009 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7010 cx.propagate();
7011 return;
7012 }
7013
7014 let text_layout_details = &self.text_layout_details(cx);
7015
7016 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7017 let line_mode = s.line_mode;
7018 s.move_with(|map, selection| {
7019 if !selection.is_empty() && !line_mode {
7020 selection.goal = SelectionGoal::None;
7021 }
7022 let (cursor, goal) = movement::down_by_rows(
7023 map,
7024 selection.start,
7025 action.lines,
7026 selection.goal,
7027 false,
7028 text_layout_details,
7029 );
7030 selection.collapse_to(cursor, goal);
7031 });
7032 })
7033 }
7034
7035 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7036 let text_layout_details = &self.text_layout_details(cx);
7037 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7038 s.move_heads_with(|map, head, goal| {
7039 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7040 })
7041 })
7042 }
7043
7044 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7045 let text_layout_details = &self.text_layout_details(cx);
7046 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7047 s.move_heads_with(|map, head, goal| {
7048 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7049 })
7050 })
7051 }
7052
7053 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7054 let Some(row_count) = self.visible_row_count() else {
7055 return;
7056 };
7057
7058 let text_layout_details = &self.text_layout_details(cx);
7059
7060 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7061 s.move_heads_with(|map, head, goal| {
7062 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7063 })
7064 })
7065 }
7066
7067 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7068 if self.take_rename(true, cx).is_some() {
7069 return;
7070 }
7071
7072 if self
7073 .context_menu
7074 .write()
7075 .as_mut()
7076 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7077 .unwrap_or(false)
7078 {
7079 return;
7080 }
7081
7082 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7083 cx.propagate();
7084 return;
7085 }
7086
7087 let Some(row_count) = self.visible_row_count() else {
7088 return;
7089 };
7090
7091 let autoscroll = if action.center_cursor {
7092 Autoscroll::center()
7093 } else {
7094 Autoscroll::fit()
7095 };
7096
7097 let text_layout_details = &self.text_layout_details(cx);
7098
7099 self.change_selections(Some(autoscroll), cx, |s| {
7100 let line_mode = s.line_mode;
7101 s.move_with(|map, selection| {
7102 if !selection.is_empty() && !line_mode {
7103 selection.goal = SelectionGoal::None;
7104 }
7105 let (cursor, goal) = movement::up_by_rows(
7106 map,
7107 selection.end,
7108 row_count,
7109 selection.goal,
7110 false,
7111 text_layout_details,
7112 );
7113 selection.collapse_to(cursor, goal);
7114 });
7115 });
7116 }
7117
7118 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7119 let text_layout_details = &self.text_layout_details(cx);
7120 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7121 s.move_heads_with(|map, head, goal| {
7122 movement::up(map, head, goal, false, text_layout_details)
7123 })
7124 })
7125 }
7126
7127 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7128 self.take_rename(true, cx);
7129
7130 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7131 cx.propagate();
7132 return;
7133 }
7134
7135 let text_layout_details = &self.text_layout_details(cx);
7136 let selection_count = self.selections.count();
7137 let first_selection = self.selections.first_anchor();
7138
7139 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7140 let line_mode = s.line_mode;
7141 s.move_with(|map, selection| {
7142 if !selection.is_empty() && !line_mode {
7143 selection.goal = SelectionGoal::None;
7144 }
7145 let (cursor, goal) = movement::down(
7146 map,
7147 selection.end,
7148 selection.goal,
7149 false,
7150 text_layout_details,
7151 );
7152 selection.collapse_to(cursor, goal);
7153 });
7154 });
7155
7156 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7157 {
7158 cx.propagate();
7159 }
7160 }
7161
7162 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7163 let Some(row_count) = self.visible_row_count() else {
7164 return;
7165 };
7166
7167 let text_layout_details = &self.text_layout_details(cx);
7168
7169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7170 s.move_heads_with(|map, head, goal| {
7171 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7172 })
7173 })
7174 }
7175
7176 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7177 if self.take_rename(true, cx).is_some() {
7178 return;
7179 }
7180
7181 if self
7182 .context_menu
7183 .write()
7184 .as_mut()
7185 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7186 .unwrap_or(false)
7187 {
7188 return;
7189 }
7190
7191 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7192 cx.propagate();
7193 return;
7194 }
7195
7196 let Some(row_count) = self.visible_row_count() else {
7197 return;
7198 };
7199
7200 let autoscroll = if action.center_cursor {
7201 Autoscroll::center()
7202 } else {
7203 Autoscroll::fit()
7204 };
7205
7206 let text_layout_details = &self.text_layout_details(cx);
7207 self.change_selections(Some(autoscroll), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 if !selection.is_empty() && !line_mode {
7211 selection.goal = SelectionGoal::None;
7212 }
7213 let (cursor, goal) = movement::down_by_rows(
7214 map,
7215 selection.end,
7216 row_count,
7217 selection.goal,
7218 false,
7219 text_layout_details,
7220 );
7221 selection.collapse_to(cursor, goal);
7222 });
7223 });
7224 }
7225
7226 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7227 let text_layout_details = &self.text_layout_details(cx);
7228 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7229 s.move_heads_with(|map, head, goal| {
7230 movement::down(map, head, goal, false, text_layout_details)
7231 })
7232 });
7233 }
7234
7235 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7236 if let Some(context_menu) = self.context_menu.write().as_mut() {
7237 context_menu.select_first(self.project.as_ref(), cx);
7238 }
7239 }
7240
7241 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7242 if let Some(context_menu) = self.context_menu.write().as_mut() {
7243 context_menu.select_prev(self.project.as_ref(), cx);
7244 }
7245 }
7246
7247 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7248 if let Some(context_menu) = self.context_menu.write().as_mut() {
7249 context_menu.select_next(self.project.as_ref(), cx);
7250 }
7251 }
7252
7253 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7254 if let Some(context_menu) = self.context_menu.write().as_mut() {
7255 context_menu.select_last(self.project.as_ref(), cx);
7256 }
7257 }
7258
7259 pub fn move_to_previous_word_start(
7260 &mut self,
7261 _: &MoveToPreviousWordStart,
7262 cx: &mut ViewContext<Self>,
7263 ) {
7264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7265 s.move_cursors_with(|map, head, _| {
7266 (
7267 movement::previous_word_start(map, head),
7268 SelectionGoal::None,
7269 )
7270 });
7271 })
7272 }
7273
7274 pub fn move_to_previous_subword_start(
7275 &mut self,
7276 _: &MoveToPreviousSubwordStart,
7277 cx: &mut ViewContext<Self>,
7278 ) {
7279 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7280 s.move_cursors_with(|map, head, _| {
7281 (
7282 movement::previous_subword_start(map, head),
7283 SelectionGoal::None,
7284 )
7285 });
7286 })
7287 }
7288
7289 pub fn select_to_previous_word_start(
7290 &mut self,
7291 _: &SelectToPreviousWordStart,
7292 cx: &mut ViewContext<Self>,
7293 ) {
7294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7295 s.move_heads_with(|map, head, _| {
7296 (
7297 movement::previous_word_start(map, head),
7298 SelectionGoal::None,
7299 )
7300 });
7301 })
7302 }
7303
7304 pub fn select_to_previous_subword_start(
7305 &mut self,
7306 _: &SelectToPreviousSubwordStart,
7307 cx: &mut ViewContext<Self>,
7308 ) {
7309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7310 s.move_heads_with(|map, head, _| {
7311 (
7312 movement::previous_subword_start(map, head),
7313 SelectionGoal::None,
7314 )
7315 });
7316 })
7317 }
7318
7319 pub fn delete_to_previous_word_start(
7320 &mut self,
7321 action: &DeleteToPreviousWordStart,
7322 cx: &mut ViewContext<Self>,
7323 ) {
7324 self.transact(cx, |this, cx| {
7325 this.select_autoclose_pair(cx);
7326 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7327 let line_mode = s.line_mode;
7328 s.move_with(|map, selection| {
7329 if selection.is_empty() && !line_mode {
7330 let cursor = if action.ignore_newlines {
7331 movement::previous_word_start(map, selection.head())
7332 } else {
7333 movement::previous_word_start_or_newline(map, selection.head())
7334 };
7335 selection.set_head(cursor, SelectionGoal::None);
7336 }
7337 });
7338 });
7339 this.insert("", cx);
7340 });
7341 }
7342
7343 pub fn delete_to_previous_subword_start(
7344 &mut self,
7345 _: &DeleteToPreviousSubwordStart,
7346 cx: &mut ViewContext<Self>,
7347 ) {
7348 self.transact(cx, |this, cx| {
7349 this.select_autoclose_pair(cx);
7350 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7351 let line_mode = s.line_mode;
7352 s.move_with(|map, selection| {
7353 if selection.is_empty() && !line_mode {
7354 let cursor = movement::previous_subword_start(map, selection.head());
7355 selection.set_head(cursor, SelectionGoal::None);
7356 }
7357 });
7358 });
7359 this.insert("", cx);
7360 });
7361 }
7362
7363 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7364 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7365 s.move_cursors_with(|map, head, _| {
7366 (movement::next_word_end(map, head), SelectionGoal::None)
7367 });
7368 })
7369 }
7370
7371 pub fn move_to_next_subword_end(
7372 &mut self,
7373 _: &MoveToNextSubwordEnd,
7374 cx: &mut ViewContext<Self>,
7375 ) {
7376 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7377 s.move_cursors_with(|map, head, _| {
7378 (movement::next_subword_end(map, head), SelectionGoal::None)
7379 });
7380 })
7381 }
7382
7383 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7384 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7385 s.move_heads_with(|map, head, _| {
7386 (movement::next_word_end(map, head), SelectionGoal::None)
7387 });
7388 })
7389 }
7390
7391 pub fn select_to_next_subword_end(
7392 &mut self,
7393 _: &SelectToNextSubwordEnd,
7394 cx: &mut ViewContext<Self>,
7395 ) {
7396 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 s.move_heads_with(|map, head, _| {
7398 (movement::next_subword_end(map, head), SelectionGoal::None)
7399 });
7400 })
7401 }
7402
7403 pub fn delete_to_next_word_end(
7404 &mut self,
7405 action: &DeleteToNextWordEnd,
7406 cx: &mut ViewContext<Self>,
7407 ) {
7408 self.transact(cx, |this, cx| {
7409 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7410 let line_mode = s.line_mode;
7411 s.move_with(|map, selection| {
7412 if selection.is_empty() && !line_mode {
7413 let cursor = if action.ignore_newlines {
7414 movement::next_word_end(map, selection.head())
7415 } else {
7416 movement::next_word_end_or_newline(map, selection.head())
7417 };
7418 selection.set_head(cursor, SelectionGoal::None);
7419 }
7420 });
7421 });
7422 this.insert("", cx);
7423 });
7424 }
7425
7426 pub fn delete_to_next_subword_end(
7427 &mut self,
7428 _: &DeleteToNextSubwordEnd,
7429 cx: &mut ViewContext<Self>,
7430 ) {
7431 self.transact(cx, |this, cx| {
7432 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7433 s.move_with(|map, selection| {
7434 if selection.is_empty() {
7435 let cursor = movement::next_subword_end(map, selection.head());
7436 selection.set_head(cursor, SelectionGoal::None);
7437 }
7438 });
7439 });
7440 this.insert("", cx);
7441 });
7442 }
7443
7444 pub fn move_to_beginning_of_line(
7445 &mut self,
7446 action: &MoveToBeginningOfLine,
7447 cx: &mut ViewContext<Self>,
7448 ) {
7449 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7450 s.move_cursors_with(|map, head, _| {
7451 (
7452 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7453 SelectionGoal::None,
7454 )
7455 });
7456 })
7457 }
7458
7459 pub fn select_to_beginning_of_line(
7460 &mut self,
7461 action: &SelectToBeginningOfLine,
7462 cx: &mut ViewContext<Self>,
7463 ) {
7464 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7465 s.move_heads_with(|map, head, _| {
7466 (
7467 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7468 SelectionGoal::None,
7469 )
7470 });
7471 });
7472 }
7473
7474 pub fn delete_to_beginning_of_line(
7475 &mut self,
7476 _: &DeleteToBeginningOfLine,
7477 cx: &mut ViewContext<Self>,
7478 ) {
7479 self.transact(cx, |this, cx| {
7480 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7481 s.move_with(|_, selection| {
7482 selection.reversed = true;
7483 });
7484 });
7485
7486 this.select_to_beginning_of_line(
7487 &SelectToBeginningOfLine {
7488 stop_at_soft_wraps: false,
7489 },
7490 cx,
7491 );
7492 this.backspace(&Backspace, cx);
7493 });
7494 }
7495
7496 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7497 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7498 s.move_cursors_with(|map, head, _| {
7499 (
7500 movement::line_end(map, head, action.stop_at_soft_wraps),
7501 SelectionGoal::None,
7502 )
7503 });
7504 })
7505 }
7506
7507 pub fn select_to_end_of_line(
7508 &mut self,
7509 action: &SelectToEndOfLine,
7510 cx: &mut ViewContext<Self>,
7511 ) {
7512 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7513 s.move_heads_with(|map, head, _| {
7514 (
7515 movement::line_end(map, head, action.stop_at_soft_wraps),
7516 SelectionGoal::None,
7517 )
7518 });
7519 })
7520 }
7521
7522 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7523 self.transact(cx, |this, cx| {
7524 this.select_to_end_of_line(
7525 &SelectToEndOfLine {
7526 stop_at_soft_wraps: false,
7527 },
7528 cx,
7529 );
7530 this.delete(&Delete, cx);
7531 });
7532 }
7533
7534 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7535 self.transact(cx, |this, cx| {
7536 this.select_to_end_of_line(
7537 &SelectToEndOfLine {
7538 stop_at_soft_wraps: false,
7539 },
7540 cx,
7541 );
7542 this.cut(&Cut, cx);
7543 });
7544 }
7545
7546 pub fn move_to_start_of_paragraph(
7547 &mut self,
7548 _: &MoveToStartOfParagraph,
7549 cx: &mut ViewContext<Self>,
7550 ) {
7551 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7552 cx.propagate();
7553 return;
7554 }
7555
7556 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7557 s.move_with(|map, selection| {
7558 selection.collapse_to(
7559 movement::start_of_paragraph(map, selection.head(), 1),
7560 SelectionGoal::None,
7561 )
7562 });
7563 })
7564 }
7565
7566 pub fn move_to_end_of_paragraph(
7567 &mut self,
7568 _: &MoveToEndOfParagraph,
7569 cx: &mut ViewContext<Self>,
7570 ) {
7571 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7572 cx.propagate();
7573 return;
7574 }
7575
7576 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7577 s.move_with(|map, selection| {
7578 selection.collapse_to(
7579 movement::end_of_paragraph(map, selection.head(), 1),
7580 SelectionGoal::None,
7581 )
7582 });
7583 })
7584 }
7585
7586 pub fn select_to_start_of_paragraph(
7587 &mut self,
7588 _: &SelectToStartOfParagraph,
7589 cx: &mut ViewContext<Self>,
7590 ) {
7591 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7592 cx.propagate();
7593 return;
7594 }
7595
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.move_heads_with(|map, head, _| {
7598 (
7599 movement::start_of_paragraph(map, head, 1),
7600 SelectionGoal::None,
7601 )
7602 });
7603 })
7604 }
7605
7606 pub fn select_to_end_of_paragraph(
7607 &mut self,
7608 _: &SelectToEndOfParagraph,
7609 cx: &mut ViewContext<Self>,
7610 ) {
7611 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7612 cx.propagate();
7613 return;
7614 }
7615
7616 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7617 s.move_heads_with(|map, head, _| {
7618 (
7619 movement::end_of_paragraph(map, head, 1),
7620 SelectionGoal::None,
7621 )
7622 });
7623 })
7624 }
7625
7626 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7627 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7628 cx.propagate();
7629 return;
7630 }
7631
7632 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7633 s.select_ranges(vec![0..0]);
7634 });
7635 }
7636
7637 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7638 let mut selection = self.selections.last::<Point>(cx);
7639 selection.set_head(Point::zero(), SelectionGoal::None);
7640
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.select(vec![selection]);
7643 });
7644 }
7645
7646 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7647 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7648 cx.propagate();
7649 return;
7650 }
7651
7652 let cursor = self.buffer.read(cx).read(cx).len();
7653 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 s.select_ranges(vec![cursor..cursor])
7655 });
7656 }
7657
7658 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7659 self.nav_history = nav_history;
7660 }
7661
7662 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7663 self.nav_history.as_ref()
7664 }
7665
7666 fn push_to_nav_history(
7667 &mut self,
7668 cursor_anchor: Anchor,
7669 new_position: Option<Point>,
7670 cx: &mut ViewContext<Self>,
7671 ) {
7672 if let Some(nav_history) = self.nav_history.as_mut() {
7673 let buffer = self.buffer.read(cx).read(cx);
7674 let cursor_position = cursor_anchor.to_point(&buffer);
7675 let scroll_state = self.scroll_manager.anchor();
7676 let scroll_top_row = scroll_state.top_row(&buffer);
7677 drop(buffer);
7678
7679 if let Some(new_position) = new_position {
7680 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7681 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7682 return;
7683 }
7684 }
7685
7686 nav_history.push(
7687 Some(NavigationData {
7688 cursor_anchor,
7689 cursor_position,
7690 scroll_anchor: scroll_state,
7691 scroll_top_row,
7692 }),
7693 cx,
7694 );
7695 }
7696 }
7697
7698 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7699 let buffer = self.buffer.read(cx).snapshot(cx);
7700 let mut selection = self.selections.first::<usize>(cx);
7701 selection.set_head(buffer.len(), SelectionGoal::None);
7702 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7703 s.select(vec![selection]);
7704 });
7705 }
7706
7707 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7708 let end = self.buffer.read(cx).read(cx).len();
7709 self.change_selections(None, cx, |s| {
7710 s.select_ranges(vec![0..end]);
7711 });
7712 }
7713
7714 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7715 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7716 let mut selections = self.selections.all::<Point>(cx);
7717 let max_point = display_map.buffer_snapshot.max_point();
7718 for selection in &mut selections {
7719 let rows = selection.spanned_rows(true, &display_map);
7720 selection.start = Point::new(rows.start.0, 0);
7721 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7722 selection.reversed = false;
7723 }
7724 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7725 s.select(selections);
7726 });
7727 }
7728
7729 pub fn split_selection_into_lines(
7730 &mut self,
7731 _: &SplitSelectionIntoLines,
7732 cx: &mut ViewContext<Self>,
7733 ) {
7734 let mut to_unfold = Vec::new();
7735 let mut new_selection_ranges = Vec::new();
7736 {
7737 let selections = self.selections.all::<Point>(cx);
7738 let buffer = self.buffer.read(cx).read(cx);
7739 for selection in selections {
7740 for row in selection.start.row..selection.end.row {
7741 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7742 new_selection_ranges.push(cursor..cursor);
7743 }
7744 new_selection_ranges.push(selection.end..selection.end);
7745 to_unfold.push(selection.start..selection.end);
7746 }
7747 }
7748 self.unfold_ranges(to_unfold, true, true, cx);
7749 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7750 s.select_ranges(new_selection_ranges);
7751 });
7752 }
7753
7754 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7755 self.add_selection(true, cx);
7756 }
7757
7758 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7759 self.add_selection(false, cx);
7760 }
7761
7762 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7763 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7764 let mut selections = self.selections.all::<Point>(cx);
7765 let text_layout_details = self.text_layout_details(cx);
7766 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7767 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7768 let range = oldest_selection.display_range(&display_map).sorted();
7769
7770 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7771 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7772 let positions = start_x.min(end_x)..start_x.max(end_x);
7773
7774 selections.clear();
7775 let mut stack = Vec::new();
7776 for row in range.start.row().0..=range.end.row().0 {
7777 if let Some(selection) = self.selections.build_columnar_selection(
7778 &display_map,
7779 DisplayRow(row),
7780 &positions,
7781 oldest_selection.reversed,
7782 &text_layout_details,
7783 ) {
7784 stack.push(selection.id);
7785 selections.push(selection);
7786 }
7787 }
7788
7789 if above {
7790 stack.reverse();
7791 }
7792
7793 AddSelectionsState { above, stack }
7794 });
7795
7796 let last_added_selection = *state.stack.last().unwrap();
7797 let mut new_selections = Vec::new();
7798 if above == state.above {
7799 let end_row = if above {
7800 DisplayRow(0)
7801 } else {
7802 display_map.max_point().row()
7803 };
7804
7805 'outer: for selection in selections {
7806 if selection.id == last_added_selection {
7807 let range = selection.display_range(&display_map).sorted();
7808 debug_assert_eq!(range.start.row(), range.end.row());
7809 let mut row = range.start.row();
7810 let positions =
7811 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7812 px(start)..px(end)
7813 } else {
7814 let start_x =
7815 display_map.x_for_display_point(range.start, &text_layout_details);
7816 let end_x =
7817 display_map.x_for_display_point(range.end, &text_layout_details);
7818 start_x.min(end_x)..start_x.max(end_x)
7819 };
7820
7821 while row != end_row {
7822 if above {
7823 row.0 -= 1;
7824 } else {
7825 row.0 += 1;
7826 }
7827
7828 if let Some(new_selection) = self.selections.build_columnar_selection(
7829 &display_map,
7830 row,
7831 &positions,
7832 selection.reversed,
7833 &text_layout_details,
7834 ) {
7835 state.stack.push(new_selection.id);
7836 if above {
7837 new_selections.push(new_selection);
7838 new_selections.push(selection);
7839 } else {
7840 new_selections.push(selection);
7841 new_selections.push(new_selection);
7842 }
7843
7844 continue 'outer;
7845 }
7846 }
7847 }
7848
7849 new_selections.push(selection);
7850 }
7851 } else {
7852 new_selections = selections;
7853 new_selections.retain(|s| s.id != last_added_selection);
7854 state.stack.pop();
7855 }
7856
7857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7858 s.select(new_selections);
7859 });
7860 if state.stack.len() > 1 {
7861 self.add_selections_state = Some(state);
7862 }
7863 }
7864
7865 pub fn select_next_match_internal(
7866 &mut self,
7867 display_map: &DisplaySnapshot,
7868 replace_newest: bool,
7869 autoscroll: Option<Autoscroll>,
7870 cx: &mut ViewContext<Self>,
7871 ) -> Result<()> {
7872 fn select_next_match_ranges(
7873 this: &mut Editor,
7874 range: Range<usize>,
7875 replace_newest: bool,
7876 auto_scroll: Option<Autoscroll>,
7877 cx: &mut ViewContext<Editor>,
7878 ) {
7879 this.unfold_ranges([range.clone()], false, true, cx);
7880 this.change_selections(auto_scroll, cx, |s| {
7881 if replace_newest {
7882 s.delete(s.newest_anchor().id);
7883 }
7884 s.insert_range(range.clone());
7885 });
7886 }
7887
7888 let buffer = &display_map.buffer_snapshot;
7889 let mut selections = self.selections.all::<usize>(cx);
7890 if let Some(mut select_next_state) = self.select_next_state.take() {
7891 let query = &select_next_state.query;
7892 if !select_next_state.done {
7893 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7894 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7895 let mut next_selected_range = None;
7896
7897 let bytes_after_last_selection =
7898 buffer.bytes_in_range(last_selection.end..buffer.len());
7899 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7900 let query_matches = query
7901 .stream_find_iter(bytes_after_last_selection)
7902 .map(|result| (last_selection.end, result))
7903 .chain(
7904 query
7905 .stream_find_iter(bytes_before_first_selection)
7906 .map(|result| (0, result)),
7907 );
7908
7909 for (start_offset, query_match) in query_matches {
7910 let query_match = query_match.unwrap(); // can only fail due to I/O
7911 let offset_range =
7912 start_offset + query_match.start()..start_offset + query_match.end();
7913 let display_range = offset_range.start.to_display_point(display_map)
7914 ..offset_range.end.to_display_point(display_map);
7915
7916 if !select_next_state.wordwise
7917 || (!movement::is_inside_word(display_map, display_range.start)
7918 && !movement::is_inside_word(display_map, display_range.end))
7919 {
7920 // TODO: This is n^2, because we might check all the selections
7921 if !selections
7922 .iter()
7923 .any(|selection| selection.range().overlaps(&offset_range))
7924 {
7925 next_selected_range = Some(offset_range);
7926 break;
7927 }
7928 }
7929 }
7930
7931 if let Some(next_selected_range) = next_selected_range {
7932 select_next_match_ranges(
7933 self,
7934 next_selected_range,
7935 replace_newest,
7936 autoscroll,
7937 cx,
7938 );
7939 } else {
7940 select_next_state.done = true;
7941 }
7942 }
7943
7944 self.select_next_state = Some(select_next_state);
7945 } else {
7946 let mut only_carets = true;
7947 let mut same_text_selected = true;
7948 let mut selected_text = None;
7949
7950 let mut selections_iter = selections.iter().peekable();
7951 while let Some(selection) = selections_iter.next() {
7952 if selection.start != selection.end {
7953 only_carets = false;
7954 }
7955
7956 if same_text_selected {
7957 if selected_text.is_none() {
7958 selected_text =
7959 Some(buffer.text_for_range(selection.range()).collect::<String>());
7960 }
7961
7962 if let Some(next_selection) = selections_iter.peek() {
7963 if next_selection.range().len() == selection.range().len() {
7964 let next_selected_text = buffer
7965 .text_for_range(next_selection.range())
7966 .collect::<String>();
7967 if Some(next_selected_text) != selected_text {
7968 same_text_selected = false;
7969 selected_text = None;
7970 }
7971 } else {
7972 same_text_selected = false;
7973 selected_text = None;
7974 }
7975 }
7976 }
7977 }
7978
7979 if only_carets {
7980 for selection in &mut selections {
7981 let word_range = movement::surrounding_word(
7982 display_map,
7983 selection.start.to_display_point(display_map),
7984 );
7985 selection.start = word_range.start.to_offset(display_map, Bias::Left);
7986 selection.end = word_range.end.to_offset(display_map, Bias::Left);
7987 selection.goal = SelectionGoal::None;
7988 selection.reversed = false;
7989 select_next_match_ranges(
7990 self,
7991 selection.start..selection.end,
7992 replace_newest,
7993 autoscroll,
7994 cx,
7995 );
7996 }
7997
7998 if selections.len() == 1 {
7999 let selection = selections
8000 .last()
8001 .expect("ensured that there's only one selection");
8002 let query = buffer
8003 .text_for_range(selection.start..selection.end)
8004 .collect::<String>();
8005 let is_empty = query.is_empty();
8006 let select_state = SelectNextState {
8007 query: AhoCorasick::new(&[query])?,
8008 wordwise: true,
8009 done: is_empty,
8010 };
8011 self.select_next_state = Some(select_state);
8012 } else {
8013 self.select_next_state = None;
8014 }
8015 } else if let Some(selected_text) = selected_text {
8016 self.select_next_state = Some(SelectNextState {
8017 query: AhoCorasick::new(&[selected_text])?,
8018 wordwise: false,
8019 done: false,
8020 });
8021 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8022 }
8023 }
8024 Ok(())
8025 }
8026
8027 pub fn select_all_matches(
8028 &mut self,
8029 _action: &SelectAllMatches,
8030 cx: &mut ViewContext<Self>,
8031 ) -> Result<()> {
8032 self.push_to_selection_history();
8033 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8034
8035 self.select_next_match_internal(&display_map, false, None, cx)?;
8036 let Some(select_next_state) = self.select_next_state.as_mut() else {
8037 return Ok(());
8038 };
8039 if select_next_state.done {
8040 return Ok(());
8041 }
8042
8043 let mut new_selections = self.selections.all::<usize>(cx);
8044
8045 let buffer = &display_map.buffer_snapshot;
8046 let query_matches = select_next_state
8047 .query
8048 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8049
8050 for query_match in query_matches {
8051 let query_match = query_match.unwrap(); // can only fail due to I/O
8052 let offset_range = query_match.start()..query_match.end();
8053 let display_range = offset_range.start.to_display_point(&display_map)
8054 ..offset_range.end.to_display_point(&display_map);
8055
8056 if !select_next_state.wordwise
8057 || (!movement::is_inside_word(&display_map, display_range.start)
8058 && !movement::is_inside_word(&display_map, display_range.end))
8059 {
8060 self.selections.change_with(cx, |selections| {
8061 new_selections.push(Selection {
8062 id: selections.new_selection_id(),
8063 start: offset_range.start,
8064 end: offset_range.end,
8065 reversed: false,
8066 goal: SelectionGoal::None,
8067 });
8068 });
8069 }
8070 }
8071
8072 new_selections.sort_by_key(|selection| selection.start);
8073 let mut ix = 0;
8074 while ix + 1 < new_selections.len() {
8075 let current_selection = &new_selections[ix];
8076 let next_selection = &new_selections[ix + 1];
8077 if current_selection.range().overlaps(&next_selection.range()) {
8078 if current_selection.id < next_selection.id {
8079 new_selections.remove(ix + 1);
8080 } else {
8081 new_selections.remove(ix);
8082 }
8083 } else {
8084 ix += 1;
8085 }
8086 }
8087
8088 select_next_state.done = true;
8089 self.unfold_ranges(
8090 new_selections.iter().map(|selection| selection.range()),
8091 false,
8092 false,
8093 cx,
8094 );
8095 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8096 selections.select(new_selections)
8097 });
8098
8099 Ok(())
8100 }
8101
8102 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8103 self.push_to_selection_history();
8104 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8105 self.select_next_match_internal(
8106 &display_map,
8107 action.replace_newest,
8108 Some(Autoscroll::newest()),
8109 cx,
8110 )?;
8111 Ok(())
8112 }
8113
8114 pub fn select_previous(
8115 &mut self,
8116 action: &SelectPrevious,
8117 cx: &mut ViewContext<Self>,
8118 ) -> Result<()> {
8119 self.push_to_selection_history();
8120 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8121 let buffer = &display_map.buffer_snapshot;
8122 let mut selections = self.selections.all::<usize>(cx);
8123 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8124 let query = &select_prev_state.query;
8125 if !select_prev_state.done {
8126 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8127 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8128 let mut next_selected_range = None;
8129 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8130 let bytes_before_last_selection =
8131 buffer.reversed_bytes_in_range(0..last_selection.start);
8132 let bytes_after_first_selection =
8133 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8134 let query_matches = query
8135 .stream_find_iter(bytes_before_last_selection)
8136 .map(|result| (last_selection.start, result))
8137 .chain(
8138 query
8139 .stream_find_iter(bytes_after_first_selection)
8140 .map(|result| (buffer.len(), result)),
8141 );
8142 for (end_offset, query_match) in query_matches {
8143 let query_match = query_match.unwrap(); // can only fail due to I/O
8144 let offset_range =
8145 end_offset - query_match.end()..end_offset - query_match.start();
8146 let display_range = offset_range.start.to_display_point(&display_map)
8147 ..offset_range.end.to_display_point(&display_map);
8148
8149 if !select_prev_state.wordwise
8150 || (!movement::is_inside_word(&display_map, display_range.start)
8151 && !movement::is_inside_word(&display_map, display_range.end))
8152 {
8153 next_selected_range = Some(offset_range);
8154 break;
8155 }
8156 }
8157
8158 if let Some(next_selected_range) = next_selected_range {
8159 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8160 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8161 if action.replace_newest {
8162 s.delete(s.newest_anchor().id);
8163 }
8164 s.insert_range(next_selected_range);
8165 });
8166 } else {
8167 select_prev_state.done = true;
8168 }
8169 }
8170
8171 self.select_prev_state = Some(select_prev_state);
8172 } else {
8173 let mut only_carets = true;
8174 let mut same_text_selected = true;
8175 let mut selected_text = None;
8176
8177 let mut selections_iter = selections.iter().peekable();
8178 while let Some(selection) = selections_iter.next() {
8179 if selection.start != selection.end {
8180 only_carets = false;
8181 }
8182
8183 if same_text_selected {
8184 if selected_text.is_none() {
8185 selected_text =
8186 Some(buffer.text_for_range(selection.range()).collect::<String>());
8187 }
8188
8189 if let Some(next_selection) = selections_iter.peek() {
8190 if next_selection.range().len() == selection.range().len() {
8191 let next_selected_text = buffer
8192 .text_for_range(next_selection.range())
8193 .collect::<String>();
8194 if Some(next_selected_text) != selected_text {
8195 same_text_selected = false;
8196 selected_text = None;
8197 }
8198 } else {
8199 same_text_selected = false;
8200 selected_text = None;
8201 }
8202 }
8203 }
8204 }
8205
8206 if only_carets {
8207 for selection in &mut selections {
8208 let word_range = movement::surrounding_word(
8209 &display_map,
8210 selection.start.to_display_point(&display_map),
8211 );
8212 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8213 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8214 selection.goal = SelectionGoal::None;
8215 selection.reversed = false;
8216 }
8217 if selections.len() == 1 {
8218 let selection = selections
8219 .last()
8220 .expect("ensured that there's only one selection");
8221 let query = buffer
8222 .text_for_range(selection.start..selection.end)
8223 .collect::<String>();
8224 let is_empty = query.is_empty();
8225 let select_state = SelectNextState {
8226 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8227 wordwise: true,
8228 done: is_empty,
8229 };
8230 self.select_prev_state = Some(select_state);
8231 } else {
8232 self.select_prev_state = None;
8233 }
8234
8235 self.unfold_ranges(
8236 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8237 false,
8238 true,
8239 cx,
8240 );
8241 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8242 s.select(selections);
8243 });
8244 } else if let Some(selected_text) = selected_text {
8245 self.select_prev_state = Some(SelectNextState {
8246 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8247 wordwise: false,
8248 done: false,
8249 });
8250 self.select_previous(action, cx)?;
8251 }
8252 }
8253 Ok(())
8254 }
8255
8256 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8257 let text_layout_details = &self.text_layout_details(cx);
8258 self.transact(cx, |this, cx| {
8259 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8260 let mut edits = Vec::new();
8261 let mut selection_edit_ranges = Vec::new();
8262 let mut last_toggled_row = None;
8263 let snapshot = this.buffer.read(cx).read(cx);
8264 let empty_str: Arc<str> = Arc::default();
8265 let mut suffixes_inserted = Vec::new();
8266
8267 fn comment_prefix_range(
8268 snapshot: &MultiBufferSnapshot,
8269 row: MultiBufferRow,
8270 comment_prefix: &str,
8271 comment_prefix_whitespace: &str,
8272 ) -> Range<Point> {
8273 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8274
8275 let mut line_bytes = snapshot
8276 .bytes_in_range(start..snapshot.max_point())
8277 .flatten()
8278 .copied();
8279
8280 // If this line currently begins with the line comment prefix, then record
8281 // the range containing the prefix.
8282 if line_bytes
8283 .by_ref()
8284 .take(comment_prefix.len())
8285 .eq(comment_prefix.bytes())
8286 {
8287 // Include any whitespace that matches the comment prefix.
8288 let matching_whitespace_len = line_bytes
8289 .zip(comment_prefix_whitespace.bytes())
8290 .take_while(|(a, b)| a == b)
8291 .count() as u32;
8292 let end = Point::new(
8293 start.row,
8294 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8295 );
8296 start..end
8297 } else {
8298 start..start
8299 }
8300 }
8301
8302 fn comment_suffix_range(
8303 snapshot: &MultiBufferSnapshot,
8304 row: MultiBufferRow,
8305 comment_suffix: &str,
8306 comment_suffix_has_leading_space: bool,
8307 ) -> Range<Point> {
8308 let end = Point::new(row.0, snapshot.line_len(row));
8309 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8310
8311 let mut line_end_bytes = snapshot
8312 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8313 .flatten()
8314 .copied();
8315
8316 let leading_space_len = if suffix_start_column > 0
8317 && line_end_bytes.next() == Some(b' ')
8318 && comment_suffix_has_leading_space
8319 {
8320 1
8321 } else {
8322 0
8323 };
8324
8325 // If this line currently begins with the line comment prefix, then record
8326 // the range containing the prefix.
8327 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8328 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8329 start..end
8330 } else {
8331 end..end
8332 }
8333 }
8334
8335 // TODO: Handle selections that cross excerpts
8336 for selection in &mut selections {
8337 let start_column = snapshot
8338 .indent_size_for_line(MultiBufferRow(selection.start.row))
8339 .len;
8340 let language = if let Some(language) =
8341 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8342 {
8343 language
8344 } else {
8345 continue;
8346 };
8347
8348 selection_edit_ranges.clear();
8349
8350 // If multiple selections contain a given row, avoid processing that
8351 // row more than once.
8352 let mut start_row = MultiBufferRow(selection.start.row);
8353 if last_toggled_row == Some(start_row) {
8354 start_row = start_row.next_row();
8355 }
8356 let end_row =
8357 if selection.end.row > selection.start.row && selection.end.column == 0 {
8358 MultiBufferRow(selection.end.row - 1)
8359 } else {
8360 MultiBufferRow(selection.end.row)
8361 };
8362 last_toggled_row = Some(end_row);
8363
8364 if start_row > end_row {
8365 continue;
8366 }
8367
8368 // If the language has line comments, toggle those.
8369 let full_comment_prefixes = language.line_comment_prefixes();
8370 if !full_comment_prefixes.is_empty() {
8371 let first_prefix = full_comment_prefixes
8372 .first()
8373 .expect("prefixes is non-empty");
8374 let prefix_trimmed_lengths = full_comment_prefixes
8375 .iter()
8376 .map(|p| p.trim_end_matches(' ').len())
8377 .collect::<SmallVec<[usize; 4]>>();
8378
8379 let mut all_selection_lines_are_comments = true;
8380
8381 for row in start_row.0..=end_row.0 {
8382 let row = MultiBufferRow(row);
8383 if start_row < end_row && snapshot.is_line_blank(row) {
8384 continue;
8385 }
8386
8387 let prefix_range = full_comment_prefixes
8388 .iter()
8389 .zip(prefix_trimmed_lengths.iter().copied())
8390 .map(|(prefix, trimmed_prefix_len)| {
8391 comment_prefix_range(
8392 snapshot.deref(),
8393 row,
8394 &prefix[..trimmed_prefix_len],
8395 &prefix[trimmed_prefix_len..],
8396 )
8397 })
8398 .max_by_key(|range| range.end.column - range.start.column)
8399 .expect("prefixes is non-empty");
8400
8401 if prefix_range.is_empty() {
8402 all_selection_lines_are_comments = false;
8403 }
8404
8405 selection_edit_ranges.push(prefix_range);
8406 }
8407
8408 if all_selection_lines_are_comments {
8409 edits.extend(
8410 selection_edit_ranges
8411 .iter()
8412 .cloned()
8413 .map(|range| (range, empty_str.clone())),
8414 );
8415 } else {
8416 let min_column = selection_edit_ranges
8417 .iter()
8418 .map(|range| range.start.column)
8419 .min()
8420 .unwrap_or(0);
8421 edits.extend(selection_edit_ranges.iter().map(|range| {
8422 let position = Point::new(range.start.row, min_column);
8423 (position..position, first_prefix.clone())
8424 }));
8425 }
8426 } else if let Some((full_comment_prefix, comment_suffix)) =
8427 language.block_comment_delimiters()
8428 {
8429 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8430 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8431 let prefix_range = comment_prefix_range(
8432 snapshot.deref(),
8433 start_row,
8434 comment_prefix,
8435 comment_prefix_whitespace,
8436 );
8437 let suffix_range = comment_suffix_range(
8438 snapshot.deref(),
8439 end_row,
8440 comment_suffix.trim_start_matches(' '),
8441 comment_suffix.starts_with(' '),
8442 );
8443
8444 if prefix_range.is_empty() || suffix_range.is_empty() {
8445 edits.push((
8446 prefix_range.start..prefix_range.start,
8447 full_comment_prefix.clone(),
8448 ));
8449 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8450 suffixes_inserted.push((end_row, comment_suffix.len()));
8451 } else {
8452 edits.push((prefix_range, empty_str.clone()));
8453 edits.push((suffix_range, empty_str.clone()));
8454 }
8455 } else {
8456 continue;
8457 }
8458 }
8459
8460 drop(snapshot);
8461 this.buffer.update(cx, |buffer, cx| {
8462 buffer.edit(edits, None, cx);
8463 });
8464
8465 // Adjust selections so that they end before any comment suffixes that
8466 // were inserted.
8467 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8468 let mut selections = this.selections.all::<Point>(cx);
8469 let snapshot = this.buffer.read(cx).read(cx);
8470 for selection in &mut selections {
8471 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8472 match row.cmp(&MultiBufferRow(selection.end.row)) {
8473 Ordering::Less => {
8474 suffixes_inserted.next();
8475 continue;
8476 }
8477 Ordering::Greater => break,
8478 Ordering::Equal => {
8479 if selection.end.column == snapshot.line_len(row) {
8480 if selection.is_empty() {
8481 selection.start.column -= suffix_len as u32;
8482 }
8483 selection.end.column -= suffix_len as u32;
8484 }
8485 break;
8486 }
8487 }
8488 }
8489 }
8490
8491 drop(snapshot);
8492 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8493
8494 let selections = this.selections.all::<Point>(cx);
8495 let selections_on_single_row = selections.windows(2).all(|selections| {
8496 selections[0].start.row == selections[1].start.row
8497 && selections[0].end.row == selections[1].end.row
8498 && selections[0].start.row == selections[0].end.row
8499 });
8500 let selections_selecting = selections
8501 .iter()
8502 .any(|selection| selection.start != selection.end);
8503 let advance_downwards = action.advance_downwards
8504 && selections_on_single_row
8505 && !selections_selecting
8506 && !matches!(this.mode, EditorMode::SingleLine { .. });
8507
8508 if advance_downwards {
8509 let snapshot = this.buffer.read(cx).snapshot(cx);
8510
8511 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8512 s.move_cursors_with(|display_snapshot, display_point, _| {
8513 let mut point = display_point.to_point(display_snapshot);
8514 point.row += 1;
8515 point = snapshot.clip_point(point, Bias::Left);
8516 let display_point = point.to_display_point(display_snapshot);
8517 let goal = SelectionGoal::HorizontalPosition(
8518 display_snapshot
8519 .x_for_display_point(display_point, text_layout_details)
8520 .into(),
8521 );
8522 (display_point, goal)
8523 })
8524 });
8525 }
8526 });
8527 }
8528
8529 pub fn select_enclosing_symbol(
8530 &mut self,
8531 _: &SelectEnclosingSymbol,
8532 cx: &mut ViewContext<Self>,
8533 ) {
8534 let buffer = self.buffer.read(cx).snapshot(cx);
8535 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8536
8537 fn update_selection(
8538 selection: &Selection<usize>,
8539 buffer_snap: &MultiBufferSnapshot,
8540 ) -> Option<Selection<usize>> {
8541 let cursor = selection.head();
8542 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8543 for symbol in symbols.iter().rev() {
8544 let start = symbol.range.start.to_offset(buffer_snap);
8545 let end = symbol.range.end.to_offset(buffer_snap);
8546 let new_range = start..end;
8547 if start < selection.start || end > selection.end {
8548 return Some(Selection {
8549 id: selection.id,
8550 start: new_range.start,
8551 end: new_range.end,
8552 goal: SelectionGoal::None,
8553 reversed: selection.reversed,
8554 });
8555 }
8556 }
8557 None
8558 }
8559
8560 let mut selected_larger_symbol = false;
8561 let new_selections = old_selections
8562 .iter()
8563 .map(|selection| match update_selection(selection, &buffer) {
8564 Some(new_selection) => {
8565 if new_selection.range() != selection.range() {
8566 selected_larger_symbol = true;
8567 }
8568 new_selection
8569 }
8570 None => selection.clone(),
8571 })
8572 .collect::<Vec<_>>();
8573
8574 if selected_larger_symbol {
8575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8576 s.select(new_selections);
8577 });
8578 }
8579 }
8580
8581 pub fn select_larger_syntax_node(
8582 &mut self,
8583 _: &SelectLargerSyntaxNode,
8584 cx: &mut ViewContext<Self>,
8585 ) {
8586 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8587 let buffer = self.buffer.read(cx).snapshot(cx);
8588 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8589
8590 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8591 let mut selected_larger_node = false;
8592 let new_selections = old_selections
8593 .iter()
8594 .map(|selection| {
8595 let old_range = selection.start..selection.end;
8596 let mut new_range = old_range.clone();
8597 while let Some(containing_range) =
8598 buffer.range_for_syntax_ancestor(new_range.clone())
8599 {
8600 new_range = containing_range;
8601 if !display_map.intersects_fold(new_range.start)
8602 && !display_map.intersects_fold(new_range.end)
8603 {
8604 break;
8605 }
8606 }
8607
8608 selected_larger_node |= new_range != old_range;
8609 Selection {
8610 id: selection.id,
8611 start: new_range.start,
8612 end: new_range.end,
8613 goal: SelectionGoal::None,
8614 reversed: selection.reversed,
8615 }
8616 })
8617 .collect::<Vec<_>>();
8618
8619 if selected_larger_node {
8620 stack.push(old_selections);
8621 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8622 s.select(new_selections);
8623 });
8624 }
8625 self.select_larger_syntax_node_stack = stack;
8626 }
8627
8628 pub fn select_smaller_syntax_node(
8629 &mut self,
8630 _: &SelectSmallerSyntaxNode,
8631 cx: &mut ViewContext<Self>,
8632 ) {
8633 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8634 if let Some(selections) = stack.pop() {
8635 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8636 s.select(selections.to_vec());
8637 });
8638 }
8639 self.select_larger_syntax_node_stack = stack;
8640 }
8641
8642 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8643 if !EditorSettings::get_global(cx).gutter.runnables {
8644 self.clear_tasks();
8645 return Task::ready(());
8646 }
8647 let project = self.project.clone();
8648 cx.spawn(|this, mut cx| async move {
8649 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8650 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8651 }) else {
8652 return;
8653 };
8654
8655 let Some(project) = project else {
8656 return;
8657 };
8658
8659 let hide_runnables = project
8660 .update(&mut cx, |project, cx| {
8661 // Do not display any test indicators in non-dev server remote projects.
8662 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8663 })
8664 .unwrap_or(true);
8665 if hide_runnables {
8666 return;
8667 }
8668 let new_rows =
8669 cx.background_executor()
8670 .spawn({
8671 let snapshot = display_snapshot.clone();
8672 async move {
8673 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8674 }
8675 })
8676 .await;
8677 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8678
8679 this.update(&mut cx, |this, _| {
8680 this.clear_tasks();
8681 for (key, value) in rows {
8682 this.insert_tasks(key, value);
8683 }
8684 })
8685 .ok();
8686 })
8687 }
8688 fn fetch_runnable_ranges(
8689 snapshot: &DisplaySnapshot,
8690 range: Range<Anchor>,
8691 ) -> Vec<language::RunnableRange> {
8692 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8693 }
8694
8695 fn runnable_rows(
8696 project: Model<Project>,
8697 snapshot: DisplaySnapshot,
8698 runnable_ranges: Vec<RunnableRange>,
8699 mut cx: AsyncWindowContext,
8700 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8701 runnable_ranges
8702 .into_iter()
8703 .filter_map(|mut runnable| {
8704 let tasks = cx
8705 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8706 .ok()?;
8707 if tasks.is_empty() {
8708 return None;
8709 }
8710
8711 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8712
8713 let row = snapshot
8714 .buffer_snapshot
8715 .buffer_line_for_row(MultiBufferRow(point.row))?
8716 .1
8717 .start
8718 .row;
8719
8720 let context_range =
8721 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8722 Some((
8723 (runnable.buffer_id, row),
8724 RunnableTasks {
8725 templates: tasks,
8726 offset: MultiBufferOffset(runnable.run_range.start),
8727 context_range,
8728 column: point.column,
8729 extra_variables: runnable.extra_captures,
8730 },
8731 ))
8732 })
8733 .collect()
8734 }
8735
8736 fn templates_with_tags(
8737 project: &Model<Project>,
8738 runnable: &mut Runnable,
8739 cx: &WindowContext<'_>,
8740 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8741 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8742 let (worktree_id, file) = project
8743 .buffer_for_id(runnable.buffer, cx)
8744 .and_then(|buffer| buffer.read(cx).file())
8745 .map(|file| (file.worktree_id(cx), file.clone()))
8746 .unzip();
8747
8748 (project.task_inventory().clone(), worktree_id, file)
8749 });
8750
8751 let inventory = inventory.read(cx);
8752 let tags = mem::take(&mut runnable.tags);
8753 let mut tags: Vec<_> = tags
8754 .into_iter()
8755 .flat_map(|tag| {
8756 let tag = tag.0.clone();
8757 inventory
8758 .list_tasks(
8759 file.clone(),
8760 Some(runnable.language.clone()),
8761 worktree_id,
8762 cx,
8763 )
8764 .into_iter()
8765 .filter(move |(_, template)| {
8766 template.tags.iter().any(|source_tag| source_tag == &tag)
8767 })
8768 })
8769 .sorted_by_key(|(kind, _)| kind.to_owned())
8770 .collect();
8771 if let Some((leading_tag_source, _)) = tags.first() {
8772 // Strongest source wins; if we have worktree tag binding, prefer that to
8773 // global and language bindings;
8774 // if we have a global binding, prefer that to language binding.
8775 let first_mismatch = tags
8776 .iter()
8777 .position(|(tag_source, _)| tag_source != leading_tag_source);
8778 if let Some(index) = first_mismatch {
8779 tags.truncate(index);
8780 }
8781 }
8782
8783 tags
8784 }
8785
8786 pub fn move_to_enclosing_bracket(
8787 &mut self,
8788 _: &MoveToEnclosingBracket,
8789 cx: &mut ViewContext<Self>,
8790 ) {
8791 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8792 s.move_offsets_with(|snapshot, selection| {
8793 let Some(enclosing_bracket_ranges) =
8794 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8795 else {
8796 return;
8797 };
8798
8799 let mut best_length = usize::MAX;
8800 let mut best_inside = false;
8801 let mut best_in_bracket_range = false;
8802 let mut best_destination = None;
8803 for (open, close) in enclosing_bracket_ranges {
8804 let close = close.to_inclusive();
8805 let length = close.end() - open.start;
8806 let inside = selection.start >= open.end && selection.end <= *close.start();
8807 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8808 || close.contains(&selection.head());
8809
8810 // If best is next to a bracket and current isn't, skip
8811 if !in_bracket_range && best_in_bracket_range {
8812 continue;
8813 }
8814
8815 // Prefer smaller lengths unless best is inside and current isn't
8816 if length > best_length && (best_inside || !inside) {
8817 continue;
8818 }
8819
8820 best_length = length;
8821 best_inside = inside;
8822 best_in_bracket_range = in_bracket_range;
8823 best_destination = Some(
8824 if close.contains(&selection.start) && close.contains(&selection.end) {
8825 if inside {
8826 open.end
8827 } else {
8828 open.start
8829 }
8830 } else if inside {
8831 *close.start()
8832 } else {
8833 *close.end()
8834 },
8835 );
8836 }
8837
8838 if let Some(destination) = best_destination {
8839 selection.collapse_to(destination, SelectionGoal::None);
8840 }
8841 })
8842 });
8843 }
8844
8845 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8846 self.end_selection(cx);
8847 self.selection_history.mode = SelectionHistoryMode::Undoing;
8848 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8849 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8850 self.select_next_state = entry.select_next_state;
8851 self.select_prev_state = entry.select_prev_state;
8852 self.add_selections_state = entry.add_selections_state;
8853 self.request_autoscroll(Autoscroll::newest(), cx);
8854 }
8855 self.selection_history.mode = SelectionHistoryMode::Normal;
8856 }
8857
8858 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8859 self.end_selection(cx);
8860 self.selection_history.mode = SelectionHistoryMode::Redoing;
8861 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8862 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8863 self.select_next_state = entry.select_next_state;
8864 self.select_prev_state = entry.select_prev_state;
8865 self.add_selections_state = entry.add_selections_state;
8866 self.request_autoscroll(Autoscroll::newest(), cx);
8867 }
8868 self.selection_history.mode = SelectionHistoryMode::Normal;
8869 }
8870
8871 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8872 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8873 }
8874
8875 pub fn expand_excerpts_down(
8876 &mut self,
8877 action: &ExpandExcerptsDown,
8878 cx: &mut ViewContext<Self>,
8879 ) {
8880 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8881 }
8882
8883 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8884 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8885 }
8886
8887 pub fn expand_excerpts_for_direction(
8888 &mut self,
8889 lines: u32,
8890 direction: ExpandExcerptDirection,
8891 cx: &mut ViewContext<Self>,
8892 ) {
8893 let selections = self.selections.disjoint_anchors();
8894
8895 let lines = if lines == 0 {
8896 EditorSettings::get_global(cx).expand_excerpt_lines
8897 } else {
8898 lines
8899 };
8900
8901 self.buffer.update(cx, |buffer, cx| {
8902 buffer.expand_excerpts(
8903 selections
8904 .iter()
8905 .map(|selection| selection.head().excerpt_id)
8906 .dedup(),
8907 lines,
8908 direction,
8909 cx,
8910 )
8911 })
8912 }
8913
8914 pub fn expand_excerpt(
8915 &mut self,
8916 excerpt: ExcerptId,
8917 direction: ExpandExcerptDirection,
8918 cx: &mut ViewContext<Self>,
8919 ) {
8920 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8921 self.buffer.update(cx, |buffer, cx| {
8922 buffer.expand_excerpts([excerpt], lines, direction, cx)
8923 })
8924 }
8925
8926 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8927 self.go_to_diagnostic_impl(Direction::Next, cx)
8928 }
8929
8930 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8931 self.go_to_diagnostic_impl(Direction::Prev, cx)
8932 }
8933
8934 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8935 let buffer = self.buffer.read(cx).snapshot(cx);
8936 let selection = self.selections.newest::<usize>(cx);
8937
8938 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8939 if direction == Direction::Next {
8940 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8941 let (group_id, jump_to) = popover.activation_info();
8942 if self.activate_diagnostics(group_id, cx) {
8943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8944 let mut new_selection = s.newest_anchor().clone();
8945 new_selection.collapse_to(jump_to, SelectionGoal::None);
8946 s.select_anchors(vec![new_selection.clone()]);
8947 });
8948 }
8949 return;
8950 }
8951 }
8952
8953 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8954 active_diagnostics
8955 .primary_range
8956 .to_offset(&buffer)
8957 .to_inclusive()
8958 });
8959 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8960 if active_primary_range.contains(&selection.head()) {
8961 *active_primary_range.start()
8962 } else {
8963 selection.head()
8964 }
8965 } else {
8966 selection.head()
8967 };
8968 let snapshot = self.snapshot(cx);
8969 loop {
8970 let diagnostics = if direction == Direction::Prev {
8971 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8972 } else {
8973 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8974 }
8975 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8976 let group = diagnostics
8977 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8978 // be sorted in a stable way
8979 // skip until we are at current active diagnostic, if it exists
8980 .skip_while(|entry| {
8981 (match direction {
8982 Direction::Prev => entry.range.start >= search_start,
8983 Direction::Next => entry.range.start <= search_start,
8984 }) && self
8985 .active_diagnostics
8986 .as_ref()
8987 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8988 })
8989 .find_map(|entry| {
8990 if entry.diagnostic.is_primary
8991 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8992 && !entry.range.is_empty()
8993 // if we match with the active diagnostic, skip it
8994 && Some(entry.diagnostic.group_id)
8995 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8996 {
8997 Some((entry.range, entry.diagnostic.group_id))
8998 } else {
8999 None
9000 }
9001 });
9002
9003 if let Some((primary_range, group_id)) = group {
9004 if self.activate_diagnostics(group_id, cx) {
9005 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9006 s.select(vec![Selection {
9007 id: selection.id,
9008 start: primary_range.start,
9009 end: primary_range.start,
9010 reversed: false,
9011 goal: SelectionGoal::None,
9012 }]);
9013 });
9014 }
9015 break;
9016 } else {
9017 // Cycle around to the start of the buffer, potentially moving back to the start of
9018 // the currently active diagnostic.
9019 active_primary_range.take();
9020 if direction == Direction::Prev {
9021 if search_start == buffer.len() {
9022 break;
9023 } else {
9024 search_start = buffer.len();
9025 }
9026 } else if search_start == 0 {
9027 break;
9028 } else {
9029 search_start = 0;
9030 }
9031 }
9032 }
9033 }
9034
9035 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9036 let snapshot = self
9037 .display_map
9038 .update(cx, |display_map, cx| display_map.snapshot(cx));
9039 let selection = self.selections.newest::<Point>(cx);
9040
9041 if !self.seek_in_direction(
9042 &snapshot,
9043 selection.head(),
9044 false,
9045 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9046 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9047 ),
9048 cx,
9049 ) {
9050 let wrapped_point = Point::zero();
9051 self.seek_in_direction(
9052 &snapshot,
9053 wrapped_point,
9054 true,
9055 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9056 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9057 ),
9058 cx,
9059 );
9060 }
9061 }
9062
9063 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9064 let snapshot = self
9065 .display_map
9066 .update(cx, |display_map, cx| display_map.snapshot(cx));
9067 let selection = self.selections.newest::<Point>(cx);
9068
9069 if !self.seek_in_direction(
9070 &snapshot,
9071 selection.head(),
9072 false,
9073 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9074 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9075 ),
9076 cx,
9077 ) {
9078 let wrapped_point = snapshot.buffer_snapshot.max_point();
9079 self.seek_in_direction(
9080 &snapshot,
9081 wrapped_point,
9082 true,
9083 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9084 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9085 ),
9086 cx,
9087 );
9088 }
9089 }
9090
9091 fn seek_in_direction(
9092 &mut self,
9093 snapshot: &DisplaySnapshot,
9094 initial_point: Point,
9095 is_wrapped: bool,
9096 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9097 cx: &mut ViewContext<Editor>,
9098 ) -> bool {
9099 let display_point = initial_point.to_display_point(snapshot);
9100 let mut hunks = hunks
9101 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9102 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9103 .dedup();
9104
9105 if let Some(hunk) = hunks.next() {
9106 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9107 let row = hunk.start_display_row();
9108 let point = DisplayPoint::new(row, 0);
9109 s.select_display_ranges([point..point]);
9110 });
9111
9112 true
9113 } else {
9114 false
9115 }
9116 }
9117
9118 pub fn go_to_definition(
9119 &mut self,
9120 _: &GoToDefinition,
9121 cx: &mut ViewContext<Self>,
9122 ) -> Task<Result<Navigated>> {
9123 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9124 cx.spawn(|editor, mut cx| async move {
9125 if definition.await? == Navigated::Yes {
9126 return Ok(Navigated::Yes);
9127 }
9128 match editor.update(&mut cx, |editor, cx| {
9129 editor.find_all_references(&FindAllReferences, cx)
9130 })? {
9131 Some(references) => references.await,
9132 None => Ok(Navigated::No),
9133 }
9134 })
9135 }
9136
9137 pub fn go_to_declaration(
9138 &mut self,
9139 _: &GoToDeclaration,
9140 cx: &mut ViewContext<Self>,
9141 ) -> Task<Result<Navigated>> {
9142 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9143 }
9144
9145 pub fn go_to_declaration_split(
9146 &mut self,
9147 _: &GoToDeclaration,
9148 cx: &mut ViewContext<Self>,
9149 ) -> Task<Result<Navigated>> {
9150 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9151 }
9152
9153 pub fn go_to_implementation(
9154 &mut self,
9155 _: &GoToImplementation,
9156 cx: &mut ViewContext<Self>,
9157 ) -> Task<Result<Navigated>> {
9158 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9159 }
9160
9161 pub fn go_to_implementation_split(
9162 &mut self,
9163 _: &GoToImplementationSplit,
9164 cx: &mut ViewContext<Self>,
9165 ) -> Task<Result<Navigated>> {
9166 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9167 }
9168
9169 pub fn go_to_type_definition(
9170 &mut self,
9171 _: &GoToTypeDefinition,
9172 cx: &mut ViewContext<Self>,
9173 ) -> Task<Result<Navigated>> {
9174 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9175 }
9176
9177 pub fn go_to_definition_split(
9178 &mut self,
9179 _: &GoToDefinitionSplit,
9180 cx: &mut ViewContext<Self>,
9181 ) -> Task<Result<Navigated>> {
9182 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9183 }
9184
9185 pub fn go_to_type_definition_split(
9186 &mut self,
9187 _: &GoToTypeDefinitionSplit,
9188 cx: &mut ViewContext<Self>,
9189 ) -> Task<Result<Navigated>> {
9190 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9191 }
9192
9193 fn go_to_definition_of_kind(
9194 &mut self,
9195 kind: GotoDefinitionKind,
9196 split: bool,
9197 cx: &mut ViewContext<Self>,
9198 ) -> Task<Result<Navigated>> {
9199 let Some(workspace) = self.workspace() else {
9200 return Task::ready(Ok(Navigated::No));
9201 };
9202 let buffer = self.buffer.read(cx);
9203 let head = self.selections.newest::<usize>(cx).head();
9204 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9205 text_anchor
9206 } else {
9207 return Task::ready(Ok(Navigated::No));
9208 };
9209
9210 let project = workspace.read(cx).project().clone();
9211 let definitions = project.update(cx, |project, cx| match kind {
9212 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9213 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9214 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9215 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9216 });
9217
9218 cx.spawn(|editor, mut cx| async move {
9219 let definitions = definitions.await?;
9220 let navigated = editor
9221 .update(&mut cx, |editor, cx| {
9222 editor.navigate_to_hover_links(
9223 Some(kind),
9224 definitions
9225 .into_iter()
9226 .filter(|location| {
9227 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9228 })
9229 .map(HoverLink::Text)
9230 .collect::<Vec<_>>(),
9231 split,
9232 cx,
9233 )
9234 })?
9235 .await?;
9236 anyhow::Ok(navigated)
9237 })
9238 }
9239
9240 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9241 let position = self.selections.newest_anchor().head();
9242 let Some((buffer, buffer_position)) =
9243 self.buffer.read(cx).text_anchor_for_position(position, cx)
9244 else {
9245 return;
9246 };
9247
9248 cx.spawn(|editor, mut cx| async move {
9249 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9250 editor.update(&mut cx, |_, cx| {
9251 cx.open_url(&url);
9252 })
9253 } else {
9254 Ok(())
9255 }
9256 })
9257 .detach();
9258 }
9259
9260 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9261 let Some(workspace) = self.workspace() else {
9262 return;
9263 };
9264
9265 let position = self.selections.newest_anchor().head();
9266
9267 let Some((buffer, buffer_position)) =
9268 self.buffer.read(cx).text_anchor_for_position(position, cx)
9269 else {
9270 return;
9271 };
9272
9273 let Some(project) = self.project.clone() else {
9274 return;
9275 };
9276
9277 cx.spawn(|_, mut cx| async move {
9278 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9279
9280 if let Some((_, path)) = result {
9281 workspace
9282 .update(&mut cx, |workspace, cx| {
9283 workspace.open_resolved_path(path, cx)
9284 })?
9285 .await?;
9286 }
9287 anyhow::Ok(())
9288 })
9289 .detach();
9290 }
9291
9292 pub(crate) fn navigate_to_hover_links(
9293 &mut self,
9294 kind: Option<GotoDefinitionKind>,
9295 mut definitions: Vec<HoverLink>,
9296 split: bool,
9297 cx: &mut ViewContext<Editor>,
9298 ) -> Task<Result<Navigated>> {
9299 // If there is one definition, just open it directly
9300 if definitions.len() == 1 {
9301 let definition = definitions.pop().unwrap();
9302
9303 enum TargetTaskResult {
9304 Location(Option<Location>),
9305 AlreadyNavigated,
9306 }
9307
9308 let target_task = match definition {
9309 HoverLink::Text(link) => {
9310 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9311 }
9312 HoverLink::InlayHint(lsp_location, server_id) => {
9313 let computation = self.compute_target_location(lsp_location, server_id, cx);
9314 cx.background_executor().spawn(async move {
9315 let location = computation.await?;
9316 Ok(TargetTaskResult::Location(location))
9317 })
9318 }
9319 HoverLink::Url(url) => {
9320 cx.open_url(&url);
9321 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9322 }
9323 HoverLink::File(path) => {
9324 if let Some(workspace) = self.workspace() {
9325 cx.spawn(|_, mut cx| async move {
9326 workspace
9327 .update(&mut cx, |workspace, cx| {
9328 workspace.open_resolved_path(path, cx)
9329 })?
9330 .await
9331 .map(|_| TargetTaskResult::AlreadyNavigated)
9332 })
9333 } else {
9334 Task::ready(Ok(TargetTaskResult::Location(None)))
9335 }
9336 }
9337 };
9338 cx.spawn(|editor, mut cx| async move {
9339 let target = match target_task.await.context("target resolution task")? {
9340 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9341 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9342 TargetTaskResult::Location(Some(target)) => target,
9343 };
9344
9345 editor.update(&mut cx, |editor, cx| {
9346 let Some(workspace) = editor.workspace() else {
9347 return Navigated::No;
9348 };
9349 let pane = workspace.read(cx).active_pane().clone();
9350
9351 let range = target.range.to_offset(target.buffer.read(cx));
9352 let range = editor.range_for_match(&range);
9353
9354 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9355 let buffer = target.buffer.read(cx);
9356 let range = check_multiline_range(buffer, range);
9357 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9358 s.select_ranges([range]);
9359 });
9360 } else {
9361 cx.window_context().defer(move |cx| {
9362 let target_editor: View<Self> =
9363 workspace.update(cx, |workspace, cx| {
9364 let pane = if split {
9365 workspace.adjacent_pane(cx)
9366 } else {
9367 workspace.active_pane().clone()
9368 };
9369
9370 workspace.open_project_item(
9371 pane,
9372 target.buffer.clone(),
9373 true,
9374 true,
9375 cx,
9376 )
9377 });
9378 target_editor.update(cx, |target_editor, cx| {
9379 // When selecting a definition in a different buffer, disable the nav history
9380 // to avoid creating a history entry at the previous cursor location.
9381 pane.update(cx, |pane, _| pane.disable_history());
9382 let buffer = target.buffer.read(cx);
9383 let range = check_multiline_range(buffer, range);
9384 target_editor.change_selections(
9385 Some(Autoscroll::focused()),
9386 cx,
9387 |s| {
9388 s.select_ranges([range]);
9389 },
9390 );
9391 pane.update(cx, |pane, _| pane.enable_history());
9392 });
9393 });
9394 }
9395 Navigated::Yes
9396 })
9397 })
9398 } else if !definitions.is_empty() {
9399 let replica_id = self.replica_id(cx);
9400 cx.spawn(|editor, mut cx| async move {
9401 let (title, location_tasks, workspace) = editor
9402 .update(&mut cx, |editor, cx| {
9403 let tab_kind = match kind {
9404 Some(GotoDefinitionKind::Implementation) => "Implementations",
9405 _ => "Definitions",
9406 };
9407 let title = definitions
9408 .iter()
9409 .find_map(|definition| match definition {
9410 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9411 let buffer = origin.buffer.read(cx);
9412 format!(
9413 "{} for {}",
9414 tab_kind,
9415 buffer
9416 .text_for_range(origin.range.clone())
9417 .collect::<String>()
9418 )
9419 }),
9420 HoverLink::InlayHint(_, _) => None,
9421 HoverLink::Url(_) => None,
9422 HoverLink::File(_) => None,
9423 })
9424 .unwrap_or(tab_kind.to_string());
9425 let location_tasks = definitions
9426 .into_iter()
9427 .map(|definition| match definition {
9428 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9429 HoverLink::InlayHint(lsp_location, server_id) => {
9430 editor.compute_target_location(lsp_location, server_id, cx)
9431 }
9432 HoverLink::Url(_) => Task::ready(Ok(None)),
9433 HoverLink::File(_) => Task::ready(Ok(None)),
9434 })
9435 .collect::<Vec<_>>();
9436 (title, location_tasks, editor.workspace().clone())
9437 })
9438 .context("location tasks preparation")?;
9439
9440 let locations = futures::future::join_all(location_tasks)
9441 .await
9442 .into_iter()
9443 .filter_map(|location| location.transpose())
9444 .collect::<Result<_>>()
9445 .context("location tasks")?;
9446
9447 let Some(workspace) = workspace else {
9448 return Ok(Navigated::No);
9449 };
9450 let opened = workspace
9451 .update(&mut cx, |workspace, cx| {
9452 Self::open_locations_in_multibuffer(
9453 workspace, locations, replica_id, title, split, cx,
9454 )
9455 })
9456 .ok();
9457
9458 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9459 })
9460 } else {
9461 Task::ready(Ok(Navigated::No))
9462 }
9463 }
9464
9465 fn compute_target_location(
9466 &self,
9467 lsp_location: lsp::Location,
9468 server_id: LanguageServerId,
9469 cx: &mut ViewContext<Editor>,
9470 ) -> Task<anyhow::Result<Option<Location>>> {
9471 let Some(project) = self.project.clone() else {
9472 return Task::Ready(Some(Ok(None)));
9473 };
9474
9475 cx.spawn(move |editor, mut cx| async move {
9476 let location_task = editor.update(&mut cx, |editor, cx| {
9477 project.update(cx, |project, cx| {
9478 let language_server_name =
9479 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9480 project
9481 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9482 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9483 });
9484 language_server_name.map(|language_server_name| {
9485 project.open_local_buffer_via_lsp(
9486 lsp_location.uri.clone(),
9487 server_id,
9488 language_server_name,
9489 cx,
9490 )
9491 })
9492 })
9493 })?;
9494 let location = match location_task {
9495 Some(task) => Some({
9496 let target_buffer_handle = task.await.context("open local buffer")?;
9497 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9498 let target_start = target_buffer
9499 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9500 let target_end = target_buffer
9501 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9502 target_buffer.anchor_after(target_start)
9503 ..target_buffer.anchor_before(target_end)
9504 })?;
9505 Location {
9506 buffer: target_buffer_handle,
9507 range,
9508 }
9509 }),
9510 None => None,
9511 };
9512 Ok(location)
9513 })
9514 }
9515
9516 pub fn find_all_references(
9517 &mut self,
9518 _: &FindAllReferences,
9519 cx: &mut ViewContext<Self>,
9520 ) -> Option<Task<Result<Navigated>>> {
9521 let multi_buffer = self.buffer.read(cx);
9522 let selection = self.selections.newest::<usize>(cx);
9523 let head = selection.head();
9524
9525 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9526 let head_anchor = multi_buffer_snapshot.anchor_at(
9527 head,
9528 if head < selection.tail() {
9529 Bias::Right
9530 } else {
9531 Bias::Left
9532 },
9533 );
9534
9535 match self
9536 .find_all_references_task_sources
9537 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9538 {
9539 Ok(_) => {
9540 log::info!(
9541 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9542 );
9543 return None;
9544 }
9545 Err(i) => {
9546 self.find_all_references_task_sources.insert(i, head_anchor);
9547 }
9548 }
9549
9550 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9551 let replica_id = self.replica_id(cx);
9552 let workspace = self.workspace()?;
9553 let project = workspace.read(cx).project().clone();
9554 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9555 Some(cx.spawn(|editor, mut cx| async move {
9556 let _cleanup = defer({
9557 let mut cx = cx.clone();
9558 move || {
9559 let _ = editor.update(&mut cx, |editor, _| {
9560 if let Ok(i) =
9561 editor
9562 .find_all_references_task_sources
9563 .binary_search_by(|anchor| {
9564 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9565 })
9566 {
9567 editor.find_all_references_task_sources.remove(i);
9568 }
9569 });
9570 }
9571 });
9572
9573 let locations = references.await?;
9574 if locations.is_empty() {
9575 return anyhow::Ok(Navigated::No);
9576 }
9577
9578 workspace.update(&mut cx, |workspace, cx| {
9579 let title = locations
9580 .first()
9581 .as_ref()
9582 .map(|location| {
9583 let buffer = location.buffer.read(cx);
9584 format!(
9585 "References to `{}`",
9586 buffer
9587 .text_for_range(location.range.clone())
9588 .collect::<String>()
9589 )
9590 })
9591 .unwrap();
9592 Self::open_locations_in_multibuffer(
9593 workspace, locations, replica_id, title, false, cx,
9594 );
9595 Navigated::Yes
9596 })
9597 }))
9598 }
9599
9600 /// Opens a multibuffer with the given project locations in it
9601 pub fn open_locations_in_multibuffer(
9602 workspace: &mut Workspace,
9603 mut locations: Vec<Location>,
9604 replica_id: ReplicaId,
9605 title: String,
9606 split: bool,
9607 cx: &mut ViewContext<Workspace>,
9608 ) {
9609 // If there are multiple definitions, open them in a multibuffer
9610 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9611 let mut locations = locations.into_iter().peekable();
9612 let mut ranges_to_highlight = Vec::new();
9613 let capability = workspace.project().read(cx).capability();
9614
9615 let excerpt_buffer = cx.new_model(|cx| {
9616 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9617 while let Some(location) = locations.next() {
9618 let buffer = location.buffer.read(cx);
9619 let mut ranges_for_buffer = Vec::new();
9620 let range = location.range.to_offset(buffer);
9621 ranges_for_buffer.push(range.clone());
9622
9623 while let Some(next_location) = locations.peek() {
9624 if next_location.buffer == location.buffer {
9625 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9626 locations.next();
9627 } else {
9628 break;
9629 }
9630 }
9631
9632 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9633 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9634 location.buffer.clone(),
9635 ranges_for_buffer,
9636 DEFAULT_MULTIBUFFER_CONTEXT,
9637 cx,
9638 ))
9639 }
9640
9641 multibuffer.with_title(title)
9642 });
9643
9644 let editor = cx.new_view(|cx| {
9645 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9646 });
9647 editor.update(cx, |editor, cx| {
9648 if let Some(first_range) = ranges_to_highlight.first() {
9649 editor.change_selections(None, cx, |selections| {
9650 selections.clear_disjoint();
9651 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9652 });
9653 }
9654 editor.highlight_background::<Self>(
9655 &ranges_to_highlight,
9656 |theme| theme.editor_highlighted_line_background,
9657 cx,
9658 );
9659 });
9660
9661 let item = Box::new(editor);
9662 let item_id = item.item_id();
9663
9664 if split {
9665 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9666 } else {
9667 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9668 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9669 pane.close_current_preview_item(cx)
9670 } else {
9671 None
9672 }
9673 });
9674 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9675 }
9676 workspace.active_pane().update(cx, |pane, cx| {
9677 pane.set_preview_item_id(Some(item_id), cx);
9678 });
9679 }
9680
9681 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9682 use language::ToOffset as _;
9683
9684 let project = self.project.clone()?;
9685 let selection = self.selections.newest_anchor().clone();
9686 let (cursor_buffer, cursor_buffer_position) = self
9687 .buffer
9688 .read(cx)
9689 .text_anchor_for_position(selection.head(), cx)?;
9690 let (tail_buffer, cursor_buffer_position_end) = self
9691 .buffer
9692 .read(cx)
9693 .text_anchor_for_position(selection.tail(), cx)?;
9694 if tail_buffer != cursor_buffer {
9695 return None;
9696 }
9697
9698 let snapshot = cursor_buffer.read(cx).snapshot();
9699 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9700 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9701 let prepare_rename = project.update(cx, |project, cx| {
9702 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9703 });
9704 drop(snapshot);
9705
9706 Some(cx.spawn(|this, mut cx| async move {
9707 let rename_range = if let Some(range) = prepare_rename.await? {
9708 Some(range)
9709 } else {
9710 this.update(&mut cx, |this, cx| {
9711 let buffer = this.buffer.read(cx).snapshot(cx);
9712 let mut buffer_highlights = this
9713 .document_highlights_for_position(selection.head(), &buffer)
9714 .filter(|highlight| {
9715 highlight.start.excerpt_id == selection.head().excerpt_id
9716 && highlight.end.excerpt_id == selection.head().excerpt_id
9717 });
9718 buffer_highlights
9719 .next()
9720 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9721 })?
9722 };
9723 if let Some(rename_range) = rename_range {
9724 this.update(&mut cx, |this, cx| {
9725 let snapshot = cursor_buffer.read(cx).snapshot();
9726 let rename_buffer_range = rename_range.to_offset(&snapshot);
9727 let cursor_offset_in_rename_range =
9728 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9729 let cursor_offset_in_rename_range_end =
9730 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9731
9732 this.take_rename(false, cx);
9733 let buffer = this.buffer.read(cx).read(cx);
9734 let cursor_offset = selection.head().to_offset(&buffer);
9735 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9736 let rename_end = rename_start + rename_buffer_range.len();
9737 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9738 let mut old_highlight_id = None;
9739 let old_name: Arc<str> = buffer
9740 .chunks(rename_start..rename_end, true)
9741 .map(|chunk| {
9742 if old_highlight_id.is_none() {
9743 old_highlight_id = chunk.syntax_highlight_id;
9744 }
9745 chunk.text
9746 })
9747 .collect::<String>()
9748 .into();
9749
9750 drop(buffer);
9751
9752 // Position the selection in the rename editor so that it matches the current selection.
9753 this.show_local_selections = false;
9754 let rename_editor = cx.new_view(|cx| {
9755 let mut editor = Editor::single_line(cx);
9756 editor.buffer.update(cx, |buffer, cx| {
9757 buffer.edit([(0..0, old_name.clone())], None, cx)
9758 });
9759 let rename_selection_range = match cursor_offset_in_rename_range
9760 .cmp(&cursor_offset_in_rename_range_end)
9761 {
9762 Ordering::Equal => {
9763 editor.select_all(&SelectAll, cx);
9764 return editor;
9765 }
9766 Ordering::Less => {
9767 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9768 }
9769 Ordering::Greater => {
9770 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9771 }
9772 };
9773 if rename_selection_range.end > old_name.len() {
9774 editor.select_all(&SelectAll, cx);
9775 } else {
9776 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9777 s.select_ranges([rename_selection_range]);
9778 });
9779 }
9780 editor
9781 });
9782 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9783 if e == &EditorEvent::Focused {
9784 cx.emit(EditorEvent::FocusedIn)
9785 }
9786 })
9787 .detach();
9788
9789 let write_highlights =
9790 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9791 let read_highlights =
9792 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9793 let ranges = write_highlights
9794 .iter()
9795 .flat_map(|(_, ranges)| ranges.iter())
9796 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9797 .cloned()
9798 .collect();
9799
9800 this.highlight_text::<Rename>(
9801 ranges,
9802 HighlightStyle {
9803 fade_out: Some(0.6),
9804 ..Default::default()
9805 },
9806 cx,
9807 );
9808 let rename_focus_handle = rename_editor.focus_handle(cx);
9809 cx.focus(&rename_focus_handle);
9810 let block_id = this.insert_blocks(
9811 [BlockProperties {
9812 style: BlockStyle::Flex,
9813 position: range.start,
9814 height: 1,
9815 render: Box::new({
9816 let rename_editor = rename_editor.clone();
9817 move |cx: &mut BlockContext| {
9818 let mut text_style = cx.editor_style.text.clone();
9819 if let Some(highlight_style) = old_highlight_id
9820 .and_then(|h| h.style(&cx.editor_style.syntax))
9821 {
9822 text_style = text_style.highlight(highlight_style);
9823 }
9824 div()
9825 .pl(cx.anchor_x)
9826 .child(EditorElement::new(
9827 &rename_editor,
9828 EditorStyle {
9829 background: cx.theme().system().transparent,
9830 local_player: cx.editor_style.local_player,
9831 text: text_style,
9832 scrollbar_width: cx.editor_style.scrollbar_width,
9833 syntax: cx.editor_style.syntax.clone(),
9834 status: cx.editor_style.status.clone(),
9835 inlay_hints_style: HighlightStyle {
9836 color: Some(cx.theme().status().hint),
9837 font_weight: Some(FontWeight::BOLD),
9838 ..HighlightStyle::default()
9839 },
9840 suggestions_style: HighlightStyle {
9841 color: Some(cx.theme().status().predictive),
9842 ..HighlightStyle::default()
9843 },
9844 ..EditorStyle::default()
9845 },
9846 ))
9847 .into_any_element()
9848 }
9849 }),
9850 disposition: BlockDisposition::Below,
9851 priority: 0,
9852 }],
9853 Some(Autoscroll::fit()),
9854 cx,
9855 )[0];
9856 this.pending_rename = Some(RenameState {
9857 range,
9858 old_name,
9859 editor: rename_editor,
9860 block_id,
9861 });
9862 })?;
9863 }
9864
9865 Ok(())
9866 }))
9867 }
9868
9869 pub fn confirm_rename(
9870 &mut self,
9871 _: &ConfirmRename,
9872 cx: &mut ViewContext<Self>,
9873 ) -> Option<Task<Result<()>>> {
9874 let rename = self.take_rename(false, cx)?;
9875 let workspace = self.workspace()?;
9876 let (start_buffer, start) = self
9877 .buffer
9878 .read(cx)
9879 .text_anchor_for_position(rename.range.start, cx)?;
9880 let (end_buffer, end) = self
9881 .buffer
9882 .read(cx)
9883 .text_anchor_for_position(rename.range.end, cx)?;
9884 if start_buffer != end_buffer {
9885 return None;
9886 }
9887
9888 let buffer = start_buffer;
9889 let range = start..end;
9890 let old_name = rename.old_name;
9891 let new_name = rename.editor.read(cx).text(cx);
9892
9893 let rename = workspace
9894 .read(cx)
9895 .project()
9896 .clone()
9897 .update(cx, |project, cx| {
9898 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9899 });
9900 let workspace = workspace.downgrade();
9901
9902 Some(cx.spawn(|editor, mut cx| async move {
9903 let project_transaction = rename.await?;
9904 Self::open_project_transaction(
9905 &editor,
9906 workspace,
9907 project_transaction,
9908 format!("Rename: {} → {}", old_name, new_name),
9909 cx.clone(),
9910 )
9911 .await?;
9912
9913 editor.update(&mut cx, |editor, cx| {
9914 editor.refresh_document_highlights(cx);
9915 })?;
9916 Ok(())
9917 }))
9918 }
9919
9920 fn take_rename(
9921 &mut self,
9922 moving_cursor: bool,
9923 cx: &mut ViewContext<Self>,
9924 ) -> Option<RenameState> {
9925 let rename = self.pending_rename.take()?;
9926 if rename.editor.focus_handle(cx).is_focused(cx) {
9927 cx.focus(&self.focus_handle);
9928 }
9929
9930 self.remove_blocks(
9931 [rename.block_id].into_iter().collect(),
9932 Some(Autoscroll::fit()),
9933 cx,
9934 );
9935 self.clear_highlights::<Rename>(cx);
9936 self.show_local_selections = true;
9937
9938 if moving_cursor {
9939 let rename_editor = rename.editor.read(cx);
9940 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9941
9942 // Update the selection to match the position of the selection inside
9943 // the rename editor.
9944 let snapshot = self.buffer.read(cx).read(cx);
9945 let rename_range = rename.range.to_offset(&snapshot);
9946 let cursor_in_editor = snapshot
9947 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9948 .min(rename_range.end);
9949 drop(snapshot);
9950
9951 self.change_selections(None, cx, |s| {
9952 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9953 });
9954 } else {
9955 self.refresh_document_highlights(cx);
9956 }
9957
9958 Some(rename)
9959 }
9960
9961 pub fn pending_rename(&self) -> Option<&RenameState> {
9962 self.pending_rename.as_ref()
9963 }
9964
9965 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9966 let project = match &self.project {
9967 Some(project) => project.clone(),
9968 None => return None,
9969 };
9970
9971 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9972 }
9973
9974 fn perform_format(
9975 &mut self,
9976 project: Model<Project>,
9977 trigger: FormatTrigger,
9978 cx: &mut ViewContext<Self>,
9979 ) -> Task<Result<()>> {
9980 let buffer = self.buffer().clone();
9981 let mut buffers = buffer.read(cx).all_buffers();
9982 if trigger == FormatTrigger::Save {
9983 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9984 }
9985
9986 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9987 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9988
9989 cx.spawn(|_, mut cx| async move {
9990 let transaction = futures::select_biased! {
9991 () = timeout => {
9992 log::warn!("timed out waiting for formatting");
9993 None
9994 }
9995 transaction = format.log_err().fuse() => transaction,
9996 };
9997
9998 buffer
9999 .update(&mut cx, |buffer, cx| {
10000 if let Some(transaction) = transaction {
10001 if !buffer.is_singleton() {
10002 buffer.push_transaction(&transaction.0, cx);
10003 }
10004 }
10005
10006 cx.notify();
10007 })
10008 .ok();
10009
10010 Ok(())
10011 })
10012 }
10013
10014 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10015 if let Some(project) = self.project.clone() {
10016 self.buffer.update(cx, |multi_buffer, cx| {
10017 project.update(cx, |project, cx| {
10018 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10019 });
10020 })
10021 }
10022 }
10023
10024 fn cancel_language_server_work(
10025 &mut self,
10026 _: &CancelLanguageServerWork,
10027 cx: &mut ViewContext<Self>,
10028 ) {
10029 if let Some(project) = self.project.clone() {
10030 self.buffer.update(cx, |multi_buffer, cx| {
10031 project.update(cx, |project, cx| {
10032 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10033 });
10034 })
10035 }
10036 }
10037
10038 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10039 cx.show_character_palette();
10040 }
10041
10042 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10043 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10044 let buffer = self.buffer.read(cx).snapshot(cx);
10045 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10046 let is_valid = buffer
10047 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10048 .any(|entry| {
10049 entry.diagnostic.is_primary
10050 && !entry.range.is_empty()
10051 && entry.range.start == primary_range_start
10052 && entry.diagnostic.message == active_diagnostics.primary_message
10053 });
10054
10055 if is_valid != active_diagnostics.is_valid {
10056 active_diagnostics.is_valid = is_valid;
10057 let mut new_styles = HashMap::default();
10058 for (block_id, diagnostic) in &active_diagnostics.blocks {
10059 new_styles.insert(
10060 *block_id,
10061 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10062 );
10063 }
10064 self.display_map.update(cx, |display_map, _cx| {
10065 display_map.replace_blocks(new_styles)
10066 });
10067 }
10068 }
10069 }
10070
10071 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10072 self.dismiss_diagnostics(cx);
10073 let snapshot = self.snapshot(cx);
10074 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10075 let buffer = self.buffer.read(cx).snapshot(cx);
10076
10077 let mut primary_range = None;
10078 let mut primary_message = None;
10079 let mut group_end = Point::zero();
10080 let diagnostic_group = buffer
10081 .diagnostic_group::<MultiBufferPoint>(group_id)
10082 .filter_map(|entry| {
10083 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10084 && (entry.range.start.row == entry.range.end.row
10085 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10086 {
10087 return None;
10088 }
10089 if entry.range.end > group_end {
10090 group_end = entry.range.end;
10091 }
10092 if entry.diagnostic.is_primary {
10093 primary_range = Some(entry.range.clone());
10094 primary_message = Some(entry.diagnostic.message.clone());
10095 }
10096 Some(entry)
10097 })
10098 .collect::<Vec<_>>();
10099 let primary_range = primary_range?;
10100 let primary_message = primary_message?;
10101 let primary_range =
10102 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10103
10104 let blocks = display_map
10105 .insert_blocks(
10106 diagnostic_group.iter().map(|entry| {
10107 let diagnostic = entry.diagnostic.clone();
10108 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10109 BlockProperties {
10110 style: BlockStyle::Fixed,
10111 position: buffer.anchor_after(entry.range.start),
10112 height: message_height,
10113 render: diagnostic_block_renderer(diagnostic, None, true, true),
10114 disposition: BlockDisposition::Below,
10115 priority: 0,
10116 }
10117 }),
10118 cx,
10119 )
10120 .into_iter()
10121 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10122 .collect();
10123
10124 Some(ActiveDiagnosticGroup {
10125 primary_range,
10126 primary_message,
10127 group_id,
10128 blocks,
10129 is_valid: true,
10130 })
10131 });
10132 self.active_diagnostics.is_some()
10133 }
10134
10135 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10136 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10137 self.display_map.update(cx, |display_map, cx| {
10138 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10139 });
10140 cx.notify();
10141 }
10142 }
10143
10144 pub fn set_selections_from_remote(
10145 &mut self,
10146 selections: Vec<Selection<Anchor>>,
10147 pending_selection: Option<Selection<Anchor>>,
10148 cx: &mut ViewContext<Self>,
10149 ) {
10150 let old_cursor_position = self.selections.newest_anchor().head();
10151 self.selections.change_with(cx, |s| {
10152 s.select_anchors(selections);
10153 if let Some(pending_selection) = pending_selection {
10154 s.set_pending(pending_selection, SelectMode::Character);
10155 } else {
10156 s.clear_pending();
10157 }
10158 });
10159 self.selections_did_change(false, &old_cursor_position, true, cx);
10160 }
10161
10162 fn push_to_selection_history(&mut self) {
10163 self.selection_history.push(SelectionHistoryEntry {
10164 selections: self.selections.disjoint_anchors(),
10165 select_next_state: self.select_next_state.clone(),
10166 select_prev_state: self.select_prev_state.clone(),
10167 add_selections_state: self.add_selections_state.clone(),
10168 });
10169 }
10170
10171 pub fn transact(
10172 &mut self,
10173 cx: &mut ViewContext<Self>,
10174 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10175 ) -> Option<TransactionId> {
10176 self.start_transaction_at(Instant::now(), cx);
10177 update(self, cx);
10178 self.end_transaction_at(Instant::now(), cx)
10179 }
10180
10181 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10182 self.end_selection(cx);
10183 if let Some(tx_id) = self
10184 .buffer
10185 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10186 {
10187 self.selection_history
10188 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10189 cx.emit(EditorEvent::TransactionBegun {
10190 transaction_id: tx_id,
10191 })
10192 }
10193 }
10194
10195 fn end_transaction_at(
10196 &mut self,
10197 now: Instant,
10198 cx: &mut ViewContext<Self>,
10199 ) -> Option<TransactionId> {
10200 if let Some(transaction_id) = self
10201 .buffer
10202 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10203 {
10204 if let Some((_, end_selections)) =
10205 self.selection_history.transaction_mut(transaction_id)
10206 {
10207 *end_selections = Some(self.selections.disjoint_anchors());
10208 } else {
10209 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10210 }
10211
10212 cx.emit(EditorEvent::Edited { transaction_id });
10213 Some(transaction_id)
10214 } else {
10215 None
10216 }
10217 }
10218
10219 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10220 let mut fold_ranges = Vec::new();
10221
10222 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10223
10224 let selections = self.selections.all_adjusted(cx);
10225 for selection in selections {
10226 let range = selection.range().sorted();
10227 let buffer_start_row = range.start.row;
10228
10229 for row in (0..=range.end.row).rev() {
10230 if let Some((foldable_range, fold_text)) =
10231 display_map.foldable_range(MultiBufferRow(row))
10232 {
10233 if foldable_range.end.row >= buffer_start_row {
10234 fold_ranges.push((foldable_range, fold_text));
10235 if row <= range.start.row {
10236 break;
10237 }
10238 }
10239 }
10240 }
10241 }
10242
10243 self.fold_ranges(fold_ranges, true, cx);
10244 }
10245
10246 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10247 let buffer_row = fold_at.buffer_row;
10248 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10249
10250 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10251 let autoscroll = self
10252 .selections
10253 .all::<Point>(cx)
10254 .iter()
10255 .any(|selection| fold_range.overlaps(&selection.range()));
10256
10257 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10258 }
10259 }
10260
10261 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10263 let buffer = &display_map.buffer_snapshot;
10264 let selections = self.selections.all::<Point>(cx);
10265 let ranges = selections
10266 .iter()
10267 .map(|s| {
10268 let range = s.display_range(&display_map).sorted();
10269 let mut start = range.start.to_point(&display_map);
10270 let mut end = range.end.to_point(&display_map);
10271 start.column = 0;
10272 end.column = buffer.line_len(MultiBufferRow(end.row));
10273 start..end
10274 })
10275 .collect::<Vec<_>>();
10276
10277 self.unfold_ranges(ranges, true, true, cx);
10278 }
10279
10280 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10281 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10282
10283 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10284 ..Point::new(
10285 unfold_at.buffer_row.0,
10286 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10287 );
10288
10289 let autoscroll = self
10290 .selections
10291 .all::<Point>(cx)
10292 .iter()
10293 .any(|selection| selection.range().overlaps(&intersection_range));
10294
10295 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10296 }
10297
10298 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10299 let selections = self.selections.all::<Point>(cx);
10300 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10301 let line_mode = self.selections.line_mode;
10302 let ranges = selections.into_iter().map(|s| {
10303 if line_mode {
10304 let start = Point::new(s.start.row, 0);
10305 let end = Point::new(
10306 s.end.row,
10307 display_map
10308 .buffer_snapshot
10309 .line_len(MultiBufferRow(s.end.row)),
10310 );
10311 (start..end, display_map.fold_placeholder.clone())
10312 } else {
10313 (s.start..s.end, display_map.fold_placeholder.clone())
10314 }
10315 });
10316 self.fold_ranges(ranges, true, cx);
10317 }
10318
10319 pub fn fold_ranges<T: ToOffset + Clone>(
10320 &mut self,
10321 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10322 auto_scroll: bool,
10323 cx: &mut ViewContext<Self>,
10324 ) {
10325 let mut fold_ranges = Vec::new();
10326 let mut buffers_affected = HashMap::default();
10327 let multi_buffer = self.buffer().read(cx);
10328 for (fold_range, fold_text) in ranges {
10329 if let Some((_, buffer, _)) =
10330 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10331 {
10332 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10333 };
10334 fold_ranges.push((fold_range, fold_text));
10335 }
10336
10337 let mut ranges = fold_ranges.into_iter().peekable();
10338 if ranges.peek().is_some() {
10339 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10340
10341 if auto_scroll {
10342 self.request_autoscroll(Autoscroll::fit(), cx);
10343 }
10344
10345 for buffer in buffers_affected.into_values() {
10346 self.sync_expanded_diff_hunks(buffer, cx);
10347 }
10348
10349 cx.notify();
10350
10351 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10352 // Clear diagnostics block when folding a range that contains it.
10353 let snapshot = self.snapshot(cx);
10354 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10355 drop(snapshot);
10356 self.active_diagnostics = Some(active_diagnostics);
10357 self.dismiss_diagnostics(cx);
10358 } else {
10359 self.active_diagnostics = Some(active_diagnostics);
10360 }
10361 }
10362
10363 self.scrollbar_marker_state.dirty = true;
10364 }
10365 }
10366
10367 pub fn unfold_ranges<T: ToOffset + Clone>(
10368 &mut self,
10369 ranges: impl IntoIterator<Item = Range<T>>,
10370 inclusive: bool,
10371 auto_scroll: bool,
10372 cx: &mut ViewContext<Self>,
10373 ) {
10374 let mut unfold_ranges = Vec::new();
10375 let mut buffers_affected = HashMap::default();
10376 let multi_buffer = self.buffer().read(cx);
10377 for range in ranges {
10378 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10379 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10380 };
10381 unfold_ranges.push(range);
10382 }
10383
10384 let mut ranges = unfold_ranges.into_iter().peekable();
10385 if ranges.peek().is_some() {
10386 self.display_map
10387 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10388 if auto_scroll {
10389 self.request_autoscroll(Autoscroll::fit(), cx);
10390 }
10391
10392 for buffer in buffers_affected.into_values() {
10393 self.sync_expanded_diff_hunks(buffer, cx);
10394 }
10395
10396 cx.notify();
10397 self.scrollbar_marker_state.dirty = true;
10398 self.active_indent_guides_state.dirty = true;
10399 }
10400 }
10401
10402 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10403 self.display_map.read(cx).fold_placeholder.clone()
10404 }
10405
10406 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10407 if hovered != self.gutter_hovered {
10408 self.gutter_hovered = hovered;
10409 cx.notify();
10410 }
10411 }
10412
10413 pub fn insert_blocks(
10414 &mut self,
10415 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10416 autoscroll: Option<Autoscroll>,
10417 cx: &mut ViewContext<Self>,
10418 ) -> Vec<CustomBlockId> {
10419 let blocks = self
10420 .display_map
10421 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10422 if let Some(autoscroll) = autoscroll {
10423 self.request_autoscroll(autoscroll, cx);
10424 }
10425 cx.notify();
10426 blocks
10427 }
10428
10429 pub fn resize_blocks(
10430 &mut self,
10431 heights: HashMap<CustomBlockId, u32>,
10432 autoscroll: Option<Autoscroll>,
10433 cx: &mut ViewContext<Self>,
10434 ) {
10435 self.display_map
10436 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10437 if let Some(autoscroll) = autoscroll {
10438 self.request_autoscroll(autoscroll, cx);
10439 }
10440 cx.notify();
10441 }
10442
10443 pub fn replace_blocks(
10444 &mut self,
10445 renderers: HashMap<CustomBlockId, RenderBlock>,
10446 autoscroll: Option<Autoscroll>,
10447 cx: &mut ViewContext<Self>,
10448 ) {
10449 self.display_map
10450 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10451 if let Some(autoscroll) = autoscroll {
10452 self.request_autoscroll(autoscroll, cx);
10453 }
10454 cx.notify();
10455 }
10456
10457 pub fn remove_blocks(
10458 &mut self,
10459 block_ids: HashSet<CustomBlockId>,
10460 autoscroll: Option<Autoscroll>,
10461 cx: &mut ViewContext<Self>,
10462 ) {
10463 self.display_map.update(cx, |display_map, cx| {
10464 display_map.remove_blocks(block_ids, cx)
10465 });
10466 if let Some(autoscroll) = autoscroll {
10467 self.request_autoscroll(autoscroll, cx);
10468 }
10469 cx.notify();
10470 }
10471
10472 pub fn row_for_block(
10473 &self,
10474 block_id: CustomBlockId,
10475 cx: &mut ViewContext<Self>,
10476 ) -> Option<DisplayRow> {
10477 self.display_map
10478 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10479 }
10480
10481 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10482 self.focused_block = Some(focused_block);
10483 }
10484
10485 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10486 self.focused_block.take()
10487 }
10488
10489 pub fn insert_creases(
10490 &mut self,
10491 creases: impl IntoIterator<Item = Crease>,
10492 cx: &mut ViewContext<Self>,
10493 ) -> Vec<CreaseId> {
10494 self.display_map
10495 .update(cx, |map, cx| map.insert_creases(creases, cx))
10496 }
10497
10498 pub fn remove_creases(
10499 &mut self,
10500 ids: impl IntoIterator<Item = CreaseId>,
10501 cx: &mut ViewContext<Self>,
10502 ) {
10503 self.display_map
10504 .update(cx, |map, cx| map.remove_creases(ids, cx));
10505 }
10506
10507 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10508 self.display_map
10509 .update(cx, |map, cx| map.snapshot(cx))
10510 .longest_row()
10511 }
10512
10513 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10514 self.display_map
10515 .update(cx, |map, cx| map.snapshot(cx))
10516 .max_point()
10517 }
10518
10519 pub fn text(&self, cx: &AppContext) -> String {
10520 self.buffer.read(cx).read(cx).text()
10521 }
10522
10523 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10524 let text = self.text(cx);
10525 let text = text.trim();
10526
10527 if text.is_empty() {
10528 return None;
10529 }
10530
10531 Some(text.to_string())
10532 }
10533
10534 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10535 self.transact(cx, |this, cx| {
10536 this.buffer
10537 .read(cx)
10538 .as_singleton()
10539 .expect("you can only call set_text on editors for singleton buffers")
10540 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10541 });
10542 }
10543
10544 pub fn display_text(&self, cx: &mut AppContext) -> String {
10545 self.display_map
10546 .update(cx, |map, cx| map.snapshot(cx))
10547 .text()
10548 }
10549
10550 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10551 let mut wrap_guides = smallvec::smallvec![];
10552
10553 if self.show_wrap_guides == Some(false) {
10554 return wrap_guides;
10555 }
10556
10557 let settings = self.buffer.read(cx).settings_at(0, cx);
10558 if settings.show_wrap_guides {
10559 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10560 wrap_guides.push((soft_wrap as usize, true));
10561 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10562 wrap_guides.push((soft_wrap as usize, true));
10563 }
10564 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10565 }
10566
10567 wrap_guides
10568 }
10569
10570 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10571 let settings = self.buffer.read(cx).settings_at(0, cx);
10572 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10573 match mode {
10574 language_settings::SoftWrap::None => SoftWrap::None,
10575 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10576 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10577 language_settings::SoftWrap::PreferredLineLength => {
10578 SoftWrap::Column(settings.preferred_line_length)
10579 }
10580 language_settings::SoftWrap::Bounded => {
10581 SoftWrap::Bounded(settings.preferred_line_length)
10582 }
10583 }
10584 }
10585
10586 pub fn set_soft_wrap_mode(
10587 &mut self,
10588 mode: language_settings::SoftWrap,
10589 cx: &mut ViewContext<Self>,
10590 ) {
10591 self.soft_wrap_mode_override = Some(mode);
10592 cx.notify();
10593 }
10594
10595 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10596 let rem_size = cx.rem_size();
10597 self.display_map.update(cx, |map, cx| {
10598 map.set_font(
10599 style.text.font(),
10600 style.text.font_size.to_pixels(rem_size),
10601 cx,
10602 )
10603 });
10604 self.style = Some(style);
10605 }
10606
10607 pub fn style(&self) -> Option<&EditorStyle> {
10608 self.style.as_ref()
10609 }
10610
10611 // Called by the element. This method is not designed to be called outside of the editor
10612 // element's layout code because it does not notify when rewrapping is computed synchronously.
10613 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10614 self.display_map
10615 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10616 }
10617
10618 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10619 if self.soft_wrap_mode_override.is_some() {
10620 self.soft_wrap_mode_override.take();
10621 } else {
10622 let soft_wrap = match self.soft_wrap_mode(cx) {
10623 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10624 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10625 language_settings::SoftWrap::PreferLine
10626 }
10627 };
10628 self.soft_wrap_mode_override = Some(soft_wrap);
10629 }
10630 cx.notify();
10631 }
10632
10633 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10634 let Some(workspace) = self.workspace() else {
10635 return;
10636 };
10637 let fs = workspace.read(cx).app_state().fs.clone();
10638 let current_show = TabBarSettings::get_global(cx).show;
10639 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10640 setting.show = Some(!current_show);
10641 });
10642 }
10643
10644 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10645 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10646 self.buffer
10647 .read(cx)
10648 .settings_at(0, cx)
10649 .indent_guides
10650 .enabled
10651 });
10652 self.show_indent_guides = Some(!currently_enabled);
10653 cx.notify();
10654 }
10655
10656 fn should_show_indent_guides(&self) -> Option<bool> {
10657 self.show_indent_guides
10658 }
10659
10660 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10661 let mut editor_settings = EditorSettings::get_global(cx).clone();
10662 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10663 EditorSettings::override_global(editor_settings, cx);
10664 }
10665
10666 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10667 self.use_relative_line_numbers
10668 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10669 }
10670
10671 pub fn toggle_relative_line_numbers(
10672 &mut self,
10673 _: &ToggleRelativeLineNumbers,
10674 cx: &mut ViewContext<Self>,
10675 ) {
10676 let is_relative = self.should_use_relative_line_numbers(cx);
10677 self.set_relative_line_number(Some(!is_relative), cx)
10678 }
10679
10680 pub fn set_relative_line_number(
10681 &mut self,
10682 is_relative: Option<bool>,
10683 cx: &mut ViewContext<Self>,
10684 ) {
10685 self.use_relative_line_numbers = is_relative;
10686 cx.notify();
10687 }
10688
10689 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10690 self.show_gutter = show_gutter;
10691 cx.notify();
10692 }
10693
10694 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10695 self.show_line_numbers = Some(show_line_numbers);
10696 cx.notify();
10697 }
10698
10699 pub fn set_show_git_diff_gutter(
10700 &mut self,
10701 show_git_diff_gutter: bool,
10702 cx: &mut ViewContext<Self>,
10703 ) {
10704 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10705 cx.notify();
10706 }
10707
10708 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10709 self.show_code_actions = Some(show_code_actions);
10710 cx.notify();
10711 }
10712
10713 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10714 self.show_runnables = Some(show_runnables);
10715 cx.notify();
10716 }
10717
10718 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10719 if self.display_map.read(cx).masked != masked {
10720 self.display_map.update(cx, |map, _| map.masked = masked);
10721 }
10722 cx.notify()
10723 }
10724
10725 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10726 self.show_wrap_guides = Some(show_wrap_guides);
10727 cx.notify();
10728 }
10729
10730 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10731 self.show_indent_guides = Some(show_indent_guides);
10732 cx.notify();
10733 }
10734
10735 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10736 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10737 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10738 if let Some(dir) = file.abs_path(cx).parent() {
10739 return Some(dir.to_owned());
10740 }
10741 }
10742
10743 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10744 return Some(project_path.path.to_path_buf());
10745 }
10746 }
10747
10748 None
10749 }
10750
10751 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10752 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10753 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10754 cx.reveal_path(&file.abs_path(cx));
10755 }
10756 }
10757 }
10758
10759 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10760 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10761 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10762 if let Some(path) = file.abs_path(cx).to_str() {
10763 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10764 }
10765 }
10766 }
10767 }
10768
10769 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10770 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10771 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10772 if let Some(path) = file.path().to_str() {
10773 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10774 }
10775 }
10776 }
10777 }
10778
10779 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10780 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10781
10782 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10783 self.start_git_blame(true, cx);
10784 }
10785
10786 cx.notify();
10787 }
10788
10789 pub fn toggle_git_blame_inline(
10790 &mut self,
10791 _: &ToggleGitBlameInline,
10792 cx: &mut ViewContext<Self>,
10793 ) {
10794 self.toggle_git_blame_inline_internal(true, cx);
10795 cx.notify();
10796 }
10797
10798 pub fn git_blame_inline_enabled(&self) -> bool {
10799 self.git_blame_inline_enabled
10800 }
10801
10802 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10803 self.show_selection_menu = self
10804 .show_selection_menu
10805 .map(|show_selections_menu| !show_selections_menu)
10806 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10807
10808 cx.notify();
10809 }
10810
10811 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10812 self.show_selection_menu
10813 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10814 }
10815
10816 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10817 if let Some(project) = self.project.as_ref() {
10818 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10819 return;
10820 };
10821
10822 if buffer.read(cx).file().is_none() {
10823 return;
10824 }
10825
10826 let focused = self.focus_handle(cx).contains_focused(cx);
10827
10828 let project = project.clone();
10829 let blame =
10830 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10831 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10832 self.blame = Some(blame);
10833 }
10834 }
10835
10836 fn toggle_git_blame_inline_internal(
10837 &mut self,
10838 user_triggered: bool,
10839 cx: &mut ViewContext<Self>,
10840 ) {
10841 if self.git_blame_inline_enabled {
10842 self.git_blame_inline_enabled = false;
10843 self.show_git_blame_inline = false;
10844 self.show_git_blame_inline_delay_task.take();
10845 } else {
10846 self.git_blame_inline_enabled = true;
10847 self.start_git_blame_inline(user_triggered, cx);
10848 }
10849
10850 cx.notify();
10851 }
10852
10853 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10854 self.start_git_blame(user_triggered, cx);
10855
10856 if ProjectSettings::get_global(cx)
10857 .git
10858 .inline_blame_delay()
10859 .is_some()
10860 {
10861 self.start_inline_blame_timer(cx);
10862 } else {
10863 self.show_git_blame_inline = true
10864 }
10865 }
10866
10867 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10868 self.blame.as_ref()
10869 }
10870
10871 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10872 self.show_git_blame_gutter && self.has_blame_entries(cx)
10873 }
10874
10875 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10876 self.show_git_blame_inline
10877 && self.focus_handle.is_focused(cx)
10878 && !self.newest_selection_head_on_empty_line(cx)
10879 && self.has_blame_entries(cx)
10880 }
10881
10882 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10883 self.blame()
10884 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10885 }
10886
10887 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10888 let cursor_anchor = self.selections.newest_anchor().head();
10889
10890 let snapshot = self.buffer.read(cx).snapshot(cx);
10891 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10892
10893 snapshot.line_len(buffer_row) == 0
10894 }
10895
10896 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10897 let (path, selection, repo) = maybe!({
10898 let project_handle = self.project.as_ref()?.clone();
10899 let project = project_handle.read(cx);
10900
10901 let selection = self.selections.newest::<Point>(cx);
10902 let selection_range = selection.range();
10903
10904 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10905 (buffer, selection_range.start.row..selection_range.end.row)
10906 } else {
10907 let buffer_ranges = self
10908 .buffer()
10909 .read(cx)
10910 .range_to_buffer_ranges(selection_range, cx);
10911
10912 let (buffer, range, _) = if selection.reversed {
10913 buffer_ranges.first()
10914 } else {
10915 buffer_ranges.last()
10916 }?;
10917
10918 let snapshot = buffer.read(cx).snapshot();
10919 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10920 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10921 (buffer.clone(), selection)
10922 };
10923
10924 let path = buffer
10925 .read(cx)
10926 .file()?
10927 .as_local()?
10928 .path()
10929 .to_str()?
10930 .to_string();
10931 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10932 Some((path, selection, repo))
10933 })
10934 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10935
10936 const REMOTE_NAME: &str = "origin";
10937 let origin_url = repo
10938 .remote_url(REMOTE_NAME)
10939 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10940 let sha = repo
10941 .head_sha()
10942 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10943
10944 let (provider, remote) =
10945 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10946 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10947
10948 Ok(provider.build_permalink(
10949 remote,
10950 BuildPermalinkParams {
10951 sha: &sha,
10952 path: &path,
10953 selection: Some(selection),
10954 },
10955 ))
10956 }
10957
10958 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10959 let permalink = self.get_permalink_to_line(cx);
10960
10961 match permalink {
10962 Ok(permalink) => {
10963 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10964 }
10965 Err(err) => {
10966 let message = format!("Failed to copy permalink: {err}");
10967
10968 Err::<(), anyhow::Error>(err).log_err();
10969
10970 if let Some(workspace) = self.workspace() {
10971 workspace.update(cx, |workspace, cx| {
10972 struct CopyPermalinkToLine;
10973
10974 workspace.show_toast(
10975 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10976 cx,
10977 )
10978 })
10979 }
10980 }
10981 }
10982 }
10983
10984 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10985 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10986 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10987 if let Some(path) = file.path().to_str() {
10988 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10989 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10990 }
10991 }
10992 }
10993 }
10994
10995 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10996 let permalink = self.get_permalink_to_line(cx);
10997
10998 match permalink {
10999 Ok(permalink) => {
11000 cx.open_url(permalink.as_ref());
11001 }
11002 Err(err) => {
11003 let message = format!("Failed to open permalink: {err}");
11004
11005 Err::<(), anyhow::Error>(err).log_err();
11006
11007 if let Some(workspace) = self.workspace() {
11008 workspace.update(cx, |workspace, cx| {
11009 struct OpenPermalinkToLine;
11010
11011 workspace.show_toast(
11012 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11013 cx,
11014 )
11015 })
11016 }
11017 }
11018 }
11019 }
11020
11021 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11022 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11023 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11024 pub fn highlight_rows<T: 'static>(
11025 &mut self,
11026 rows: RangeInclusive<Anchor>,
11027 color: Option<Hsla>,
11028 should_autoscroll: bool,
11029 cx: &mut ViewContext<Self>,
11030 ) {
11031 let snapshot = self.buffer().read(cx).snapshot(cx);
11032 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11033 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11034 highlight
11035 .range
11036 .start()
11037 .cmp(rows.start(), &snapshot)
11038 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11039 });
11040 match (color, existing_highlight_index) {
11041 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11042 ix,
11043 RowHighlight {
11044 index: post_inc(&mut self.highlight_order),
11045 range: rows,
11046 should_autoscroll,
11047 color,
11048 },
11049 ),
11050 (None, Ok(i)) => {
11051 row_highlights.remove(i);
11052 }
11053 }
11054 }
11055
11056 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11057 pub fn clear_row_highlights<T: 'static>(&mut self) {
11058 self.highlighted_rows.remove(&TypeId::of::<T>());
11059 }
11060
11061 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11062 pub fn highlighted_rows<T: 'static>(
11063 &self,
11064 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11065 Some(
11066 self.highlighted_rows
11067 .get(&TypeId::of::<T>())?
11068 .iter()
11069 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11070 )
11071 }
11072
11073 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11074 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11075 /// Allows to ignore certain kinds of highlights.
11076 pub fn highlighted_display_rows(
11077 &mut self,
11078 cx: &mut WindowContext,
11079 ) -> BTreeMap<DisplayRow, Hsla> {
11080 let snapshot = self.snapshot(cx);
11081 let mut used_highlight_orders = HashMap::default();
11082 self.highlighted_rows
11083 .iter()
11084 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11085 .fold(
11086 BTreeMap::<DisplayRow, Hsla>::new(),
11087 |mut unique_rows, highlight| {
11088 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11089 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11090 for row in start_row.0..=end_row.0 {
11091 let used_index =
11092 used_highlight_orders.entry(row).or_insert(highlight.index);
11093 if highlight.index >= *used_index {
11094 *used_index = highlight.index;
11095 match highlight.color {
11096 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11097 None => unique_rows.remove(&DisplayRow(row)),
11098 };
11099 }
11100 }
11101 unique_rows
11102 },
11103 )
11104 }
11105
11106 pub fn highlighted_display_row_for_autoscroll(
11107 &self,
11108 snapshot: &DisplaySnapshot,
11109 ) -> Option<DisplayRow> {
11110 self.highlighted_rows
11111 .values()
11112 .flat_map(|highlighted_rows| highlighted_rows.iter())
11113 .filter_map(|highlight| {
11114 if highlight.color.is_none() || !highlight.should_autoscroll {
11115 return None;
11116 }
11117 Some(highlight.range.start().to_display_point(snapshot).row())
11118 })
11119 .min()
11120 }
11121
11122 pub fn set_search_within_ranges(
11123 &mut self,
11124 ranges: &[Range<Anchor>],
11125 cx: &mut ViewContext<Self>,
11126 ) {
11127 self.highlight_background::<SearchWithinRange>(
11128 ranges,
11129 |colors| colors.editor_document_highlight_read_background,
11130 cx,
11131 )
11132 }
11133
11134 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11135 self.breadcrumb_header = Some(new_header);
11136 }
11137
11138 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11139 self.clear_background_highlights::<SearchWithinRange>(cx);
11140 }
11141
11142 pub fn highlight_background<T: 'static>(
11143 &mut self,
11144 ranges: &[Range<Anchor>],
11145 color_fetcher: fn(&ThemeColors) -> Hsla,
11146 cx: &mut ViewContext<Self>,
11147 ) {
11148 self.background_highlights
11149 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11150 self.scrollbar_marker_state.dirty = true;
11151 cx.notify();
11152 }
11153
11154 pub fn clear_background_highlights<T: 'static>(
11155 &mut self,
11156 cx: &mut ViewContext<Self>,
11157 ) -> Option<BackgroundHighlight> {
11158 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11159 if !text_highlights.1.is_empty() {
11160 self.scrollbar_marker_state.dirty = true;
11161 cx.notify();
11162 }
11163 Some(text_highlights)
11164 }
11165
11166 pub fn highlight_gutter<T: 'static>(
11167 &mut self,
11168 ranges: &[Range<Anchor>],
11169 color_fetcher: fn(&AppContext) -> Hsla,
11170 cx: &mut ViewContext<Self>,
11171 ) {
11172 self.gutter_highlights
11173 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11174 cx.notify();
11175 }
11176
11177 pub fn clear_gutter_highlights<T: 'static>(
11178 &mut self,
11179 cx: &mut ViewContext<Self>,
11180 ) -> Option<GutterHighlight> {
11181 cx.notify();
11182 self.gutter_highlights.remove(&TypeId::of::<T>())
11183 }
11184
11185 #[cfg(feature = "test-support")]
11186 pub fn all_text_background_highlights(
11187 &mut self,
11188 cx: &mut ViewContext<Self>,
11189 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11190 let snapshot = self.snapshot(cx);
11191 let buffer = &snapshot.buffer_snapshot;
11192 let start = buffer.anchor_before(0);
11193 let end = buffer.anchor_after(buffer.len());
11194 let theme = cx.theme().colors();
11195 self.background_highlights_in_range(start..end, &snapshot, theme)
11196 }
11197
11198 #[cfg(feature = "test-support")]
11199 pub fn search_background_highlights(
11200 &mut self,
11201 cx: &mut ViewContext<Self>,
11202 ) -> Vec<Range<Point>> {
11203 let snapshot = self.buffer().read(cx).snapshot(cx);
11204
11205 let highlights = self
11206 .background_highlights
11207 .get(&TypeId::of::<items::BufferSearchHighlights>());
11208
11209 if let Some((_color, ranges)) = highlights {
11210 ranges
11211 .iter()
11212 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11213 .collect_vec()
11214 } else {
11215 vec![]
11216 }
11217 }
11218
11219 fn document_highlights_for_position<'a>(
11220 &'a self,
11221 position: Anchor,
11222 buffer: &'a MultiBufferSnapshot,
11223 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11224 let read_highlights = self
11225 .background_highlights
11226 .get(&TypeId::of::<DocumentHighlightRead>())
11227 .map(|h| &h.1);
11228 let write_highlights = self
11229 .background_highlights
11230 .get(&TypeId::of::<DocumentHighlightWrite>())
11231 .map(|h| &h.1);
11232 let left_position = position.bias_left(buffer);
11233 let right_position = position.bias_right(buffer);
11234 read_highlights
11235 .into_iter()
11236 .chain(write_highlights)
11237 .flat_map(move |ranges| {
11238 let start_ix = match ranges.binary_search_by(|probe| {
11239 let cmp = probe.end.cmp(&left_position, buffer);
11240 if cmp.is_ge() {
11241 Ordering::Greater
11242 } else {
11243 Ordering::Less
11244 }
11245 }) {
11246 Ok(i) | Err(i) => i,
11247 };
11248
11249 ranges[start_ix..]
11250 .iter()
11251 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11252 })
11253 }
11254
11255 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11256 self.background_highlights
11257 .get(&TypeId::of::<T>())
11258 .map_or(false, |(_, highlights)| !highlights.is_empty())
11259 }
11260
11261 pub fn background_highlights_in_range(
11262 &self,
11263 search_range: Range<Anchor>,
11264 display_snapshot: &DisplaySnapshot,
11265 theme: &ThemeColors,
11266 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11267 let mut results = Vec::new();
11268 for (color_fetcher, ranges) in self.background_highlights.values() {
11269 let color = color_fetcher(theme);
11270 let start_ix = match ranges.binary_search_by(|probe| {
11271 let cmp = probe
11272 .end
11273 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11274 if cmp.is_gt() {
11275 Ordering::Greater
11276 } else {
11277 Ordering::Less
11278 }
11279 }) {
11280 Ok(i) | Err(i) => i,
11281 };
11282 for range in &ranges[start_ix..] {
11283 if range
11284 .start
11285 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11286 .is_ge()
11287 {
11288 break;
11289 }
11290
11291 let start = range.start.to_display_point(display_snapshot);
11292 let end = range.end.to_display_point(display_snapshot);
11293 results.push((start..end, color))
11294 }
11295 }
11296 results
11297 }
11298
11299 pub fn background_highlight_row_ranges<T: 'static>(
11300 &self,
11301 search_range: Range<Anchor>,
11302 display_snapshot: &DisplaySnapshot,
11303 count: usize,
11304 ) -> Vec<RangeInclusive<DisplayPoint>> {
11305 let mut results = Vec::new();
11306 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11307 return vec![];
11308 };
11309
11310 let start_ix = match ranges.binary_search_by(|probe| {
11311 let cmp = probe
11312 .end
11313 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11314 if cmp.is_gt() {
11315 Ordering::Greater
11316 } else {
11317 Ordering::Less
11318 }
11319 }) {
11320 Ok(i) | Err(i) => i,
11321 };
11322 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11323 if let (Some(start_display), Some(end_display)) = (start, end) {
11324 results.push(
11325 start_display.to_display_point(display_snapshot)
11326 ..=end_display.to_display_point(display_snapshot),
11327 );
11328 }
11329 };
11330 let mut start_row: Option<Point> = None;
11331 let mut end_row: Option<Point> = None;
11332 if ranges.len() > count {
11333 return Vec::new();
11334 }
11335 for range in &ranges[start_ix..] {
11336 if range
11337 .start
11338 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11339 .is_ge()
11340 {
11341 break;
11342 }
11343 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11344 if let Some(current_row) = &end_row {
11345 if end.row == current_row.row {
11346 continue;
11347 }
11348 }
11349 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11350 if start_row.is_none() {
11351 assert_eq!(end_row, None);
11352 start_row = Some(start);
11353 end_row = Some(end);
11354 continue;
11355 }
11356 if let Some(current_end) = end_row.as_mut() {
11357 if start.row > current_end.row + 1 {
11358 push_region(start_row, end_row);
11359 start_row = Some(start);
11360 end_row = Some(end);
11361 } else {
11362 // Merge two hunks.
11363 *current_end = end;
11364 }
11365 } else {
11366 unreachable!();
11367 }
11368 }
11369 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11370 push_region(start_row, end_row);
11371 results
11372 }
11373
11374 pub fn gutter_highlights_in_range(
11375 &self,
11376 search_range: Range<Anchor>,
11377 display_snapshot: &DisplaySnapshot,
11378 cx: &AppContext,
11379 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11380 let mut results = Vec::new();
11381 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11382 let color = color_fetcher(cx);
11383 let start_ix = match ranges.binary_search_by(|probe| {
11384 let cmp = probe
11385 .end
11386 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11387 if cmp.is_gt() {
11388 Ordering::Greater
11389 } else {
11390 Ordering::Less
11391 }
11392 }) {
11393 Ok(i) | Err(i) => i,
11394 };
11395 for range in &ranges[start_ix..] {
11396 if range
11397 .start
11398 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11399 .is_ge()
11400 {
11401 break;
11402 }
11403
11404 let start = range.start.to_display_point(display_snapshot);
11405 let end = range.end.to_display_point(display_snapshot);
11406 results.push((start..end, color))
11407 }
11408 }
11409 results
11410 }
11411
11412 /// Get the text ranges corresponding to the redaction query
11413 pub fn redacted_ranges(
11414 &self,
11415 search_range: Range<Anchor>,
11416 display_snapshot: &DisplaySnapshot,
11417 cx: &WindowContext,
11418 ) -> Vec<Range<DisplayPoint>> {
11419 display_snapshot
11420 .buffer_snapshot
11421 .redacted_ranges(search_range, |file| {
11422 if let Some(file) = file {
11423 file.is_private()
11424 && EditorSettings::get(
11425 Some(SettingsLocation {
11426 worktree_id: file.worktree_id(cx),
11427 path: file.path().as_ref(),
11428 }),
11429 cx,
11430 )
11431 .redact_private_values
11432 } else {
11433 false
11434 }
11435 })
11436 .map(|range| {
11437 range.start.to_display_point(display_snapshot)
11438 ..range.end.to_display_point(display_snapshot)
11439 })
11440 .collect()
11441 }
11442
11443 pub fn highlight_text<T: 'static>(
11444 &mut self,
11445 ranges: Vec<Range<Anchor>>,
11446 style: HighlightStyle,
11447 cx: &mut ViewContext<Self>,
11448 ) {
11449 self.display_map.update(cx, |map, _| {
11450 map.highlight_text(TypeId::of::<T>(), ranges, style)
11451 });
11452 cx.notify();
11453 }
11454
11455 pub(crate) fn highlight_inlays<T: 'static>(
11456 &mut self,
11457 highlights: Vec<InlayHighlight>,
11458 style: HighlightStyle,
11459 cx: &mut ViewContext<Self>,
11460 ) {
11461 self.display_map.update(cx, |map, _| {
11462 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11463 });
11464 cx.notify();
11465 }
11466
11467 pub fn text_highlights<'a, T: 'static>(
11468 &'a self,
11469 cx: &'a AppContext,
11470 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11471 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11472 }
11473
11474 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11475 let cleared = self
11476 .display_map
11477 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11478 if cleared {
11479 cx.notify();
11480 }
11481 }
11482
11483 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11484 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11485 && self.focus_handle.is_focused(cx)
11486 }
11487
11488 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11489 self.show_cursor_when_unfocused = is_enabled;
11490 cx.notify();
11491 }
11492
11493 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11494 cx.notify();
11495 }
11496
11497 fn on_buffer_event(
11498 &mut self,
11499 multibuffer: Model<MultiBuffer>,
11500 event: &multi_buffer::Event,
11501 cx: &mut ViewContext<Self>,
11502 ) {
11503 match event {
11504 multi_buffer::Event::Edited {
11505 singleton_buffer_edited,
11506 } => {
11507 self.scrollbar_marker_state.dirty = true;
11508 self.active_indent_guides_state.dirty = true;
11509 self.refresh_active_diagnostics(cx);
11510 self.refresh_code_actions(cx);
11511 if self.has_active_inline_completion(cx) {
11512 self.update_visible_inline_completion(cx);
11513 }
11514 cx.emit(EditorEvent::BufferEdited);
11515 cx.emit(SearchEvent::MatchesInvalidated);
11516 if *singleton_buffer_edited {
11517 if let Some(project) = &self.project {
11518 let project = project.read(cx);
11519 #[allow(clippy::mutable_key_type)]
11520 let languages_affected = multibuffer
11521 .read(cx)
11522 .all_buffers()
11523 .into_iter()
11524 .filter_map(|buffer| {
11525 let buffer = buffer.read(cx);
11526 let language = buffer.language()?;
11527 if project.is_local_or_ssh()
11528 && project.language_servers_for_buffer(buffer, cx).count() == 0
11529 {
11530 None
11531 } else {
11532 Some(language)
11533 }
11534 })
11535 .cloned()
11536 .collect::<HashSet<_>>();
11537 if !languages_affected.is_empty() {
11538 self.refresh_inlay_hints(
11539 InlayHintRefreshReason::BufferEdited(languages_affected),
11540 cx,
11541 );
11542 }
11543 }
11544 }
11545
11546 let Some(project) = &self.project else { return };
11547 let telemetry = project.read(cx).client().telemetry().clone();
11548 refresh_linked_ranges(self, cx);
11549 telemetry.log_edit_event("editor");
11550 }
11551 multi_buffer::Event::ExcerptsAdded {
11552 buffer,
11553 predecessor,
11554 excerpts,
11555 } => {
11556 self.tasks_update_task = Some(self.refresh_runnables(cx));
11557 cx.emit(EditorEvent::ExcerptsAdded {
11558 buffer: buffer.clone(),
11559 predecessor: *predecessor,
11560 excerpts: excerpts.clone(),
11561 });
11562 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11563 }
11564 multi_buffer::Event::ExcerptsRemoved { ids } => {
11565 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11566 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11567 }
11568 multi_buffer::Event::ExcerptsEdited { ids } => {
11569 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11570 }
11571 multi_buffer::Event::ExcerptsExpanded { ids } => {
11572 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11573 }
11574 multi_buffer::Event::Reparsed(buffer_id) => {
11575 self.tasks_update_task = Some(self.refresh_runnables(cx));
11576
11577 cx.emit(EditorEvent::Reparsed(*buffer_id));
11578 }
11579 multi_buffer::Event::LanguageChanged(buffer_id) => {
11580 linked_editing_ranges::refresh_linked_ranges(self, cx);
11581 cx.emit(EditorEvent::Reparsed(*buffer_id));
11582 cx.notify();
11583 }
11584 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11585 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11586 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11587 cx.emit(EditorEvent::TitleChanged)
11588 }
11589 multi_buffer::Event::DiffBaseChanged => {
11590 self.scrollbar_marker_state.dirty = true;
11591 cx.emit(EditorEvent::DiffBaseChanged);
11592 cx.notify();
11593 }
11594 multi_buffer::Event::DiffUpdated { buffer } => {
11595 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11596 cx.notify();
11597 }
11598 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11599 multi_buffer::Event::DiagnosticsUpdated => {
11600 self.refresh_active_diagnostics(cx);
11601 self.scrollbar_marker_state.dirty = true;
11602 cx.notify();
11603 }
11604 _ => {}
11605 };
11606 }
11607
11608 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11609 cx.notify();
11610 }
11611
11612 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11613 self.tasks_update_task = Some(self.refresh_runnables(cx));
11614 self.refresh_inline_completion(true, false, cx);
11615 self.refresh_inlay_hints(
11616 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11617 self.selections.newest_anchor().head(),
11618 &self.buffer.read(cx).snapshot(cx),
11619 cx,
11620 )),
11621 cx,
11622 );
11623 let editor_settings = EditorSettings::get_global(cx);
11624 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11625 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11626
11627 let project_settings = ProjectSettings::get_global(cx);
11628 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11629
11630 if self.mode == EditorMode::Full {
11631 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11632 if self.git_blame_inline_enabled != inline_blame_enabled {
11633 self.toggle_git_blame_inline_internal(false, cx);
11634 }
11635 }
11636
11637 cx.notify();
11638 }
11639
11640 pub fn set_searchable(&mut self, searchable: bool) {
11641 self.searchable = searchable;
11642 }
11643
11644 pub fn searchable(&self) -> bool {
11645 self.searchable
11646 }
11647
11648 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11649 self.open_excerpts_common(true, cx)
11650 }
11651
11652 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11653 self.open_excerpts_common(false, cx)
11654 }
11655
11656 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11657 let buffer = self.buffer.read(cx);
11658 if buffer.is_singleton() {
11659 cx.propagate();
11660 return;
11661 }
11662
11663 let Some(workspace) = self.workspace() else {
11664 cx.propagate();
11665 return;
11666 };
11667
11668 let mut new_selections_by_buffer = HashMap::default();
11669 for selection in self.selections.all::<usize>(cx) {
11670 for (buffer, mut range, _) in
11671 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11672 {
11673 if selection.reversed {
11674 mem::swap(&mut range.start, &mut range.end);
11675 }
11676 new_selections_by_buffer
11677 .entry(buffer)
11678 .or_insert(Vec::new())
11679 .push(range)
11680 }
11681 }
11682
11683 // We defer the pane interaction because we ourselves are a workspace item
11684 // and activating a new item causes the pane to call a method on us reentrantly,
11685 // which panics if we're on the stack.
11686 cx.window_context().defer(move |cx| {
11687 workspace.update(cx, |workspace, cx| {
11688 let pane = if split {
11689 workspace.adjacent_pane(cx)
11690 } else {
11691 workspace.active_pane().clone()
11692 };
11693
11694 for (buffer, ranges) in new_selections_by_buffer {
11695 let editor =
11696 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11697 editor.update(cx, |editor, cx| {
11698 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11699 s.select_ranges(ranges);
11700 });
11701 });
11702 }
11703 })
11704 });
11705 }
11706
11707 fn jump(
11708 &mut self,
11709 path: ProjectPath,
11710 position: Point,
11711 anchor: language::Anchor,
11712 offset_from_top: u32,
11713 cx: &mut ViewContext<Self>,
11714 ) {
11715 let workspace = self.workspace();
11716 cx.spawn(|_, mut cx| async move {
11717 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11718 let editor = workspace.update(&mut cx, |workspace, cx| {
11719 // Reset the preview item id before opening the new item
11720 workspace.active_pane().update(cx, |pane, cx| {
11721 pane.set_preview_item_id(None, cx);
11722 });
11723 workspace.open_path_preview(path, None, true, true, cx)
11724 })?;
11725 let editor = editor
11726 .await?
11727 .downcast::<Editor>()
11728 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11729 .downgrade();
11730 editor.update(&mut cx, |editor, cx| {
11731 let buffer = editor
11732 .buffer()
11733 .read(cx)
11734 .as_singleton()
11735 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11736 let buffer = buffer.read(cx);
11737 let cursor = if buffer.can_resolve(&anchor) {
11738 language::ToPoint::to_point(&anchor, buffer)
11739 } else {
11740 buffer.clip_point(position, Bias::Left)
11741 };
11742
11743 let nav_history = editor.nav_history.take();
11744 editor.change_selections(
11745 Some(Autoscroll::top_relative(offset_from_top as usize)),
11746 cx,
11747 |s| {
11748 s.select_ranges([cursor..cursor]);
11749 },
11750 );
11751 editor.nav_history = nav_history;
11752
11753 anyhow::Ok(())
11754 })??;
11755
11756 anyhow::Ok(())
11757 })
11758 .detach_and_log_err(cx);
11759 }
11760
11761 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11762 let snapshot = self.buffer.read(cx).read(cx);
11763 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11764 Some(
11765 ranges
11766 .iter()
11767 .map(move |range| {
11768 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11769 })
11770 .collect(),
11771 )
11772 }
11773
11774 fn selection_replacement_ranges(
11775 &self,
11776 range: Range<OffsetUtf16>,
11777 cx: &AppContext,
11778 ) -> Vec<Range<OffsetUtf16>> {
11779 let selections = self.selections.all::<OffsetUtf16>(cx);
11780 let newest_selection = selections
11781 .iter()
11782 .max_by_key(|selection| selection.id)
11783 .unwrap();
11784 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11785 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11786 let snapshot = self.buffer.read(cx).read(cx);
11787 selections
11788 .into_iter()
11789 .map(|mut selection| {
11790 selection.start.0 =
11791 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11792 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11793 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11794 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11795 })
11796 .collect()
11797 }
11798
11799 fn report_editor_event(
11800 &self,
11801 operation: &'static str,
11802 file_extension: Option<String>,
11803 cx: &AppContext,
11804 ) {
11805 if cfg!(any(test, feature = "test-support")) {
11806 return;
11807 }
11808
11809 let Some(project) = &self.project else { return };
11810
11811 // If None, we are in a file without an extension
11812 let file = self
11813 .buffer
11814 .read(cx)
11815 .as_singleton()
11816 .and_then(|b| b.read(cx).file());
11817 let file_extension = file_extension.or(file
11818 .as_ref()
11819 .and_then(|file| Path::new(file.file_name(cx)).extension())
11820 .and_then(|e| e.to_str())
11821 .map(|a| a.to_string()));
11822
11823 let vim_mode = cx
11824 .global::<SettingsStore>()
11825 .raw_user_settings()
11826 .get("vim_mode")
11827 == Some(&serde_json::Value::Bool(true));
11828
11829 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11830 == language::language_settings::InlineCompletionProvider::Copilot;
11831 let copilot_enabled_for_language = self
11832 .buffer
11833 .read(cx)
11834 .settings_at(0, cx)
11835 .show_inline_completions;
11836
11837 let telemetry = project.read(cx).client().telemetry().clone();
11838 telemetry.report_editor_event(
11839 file_extension,
11840 vim_mode,
11841 operation,
11842 copilot_enabled,
11843 copilot_enabled_for_language,
11844 )
11845 }
11846
11847 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11848 /// with each line being an array of {text, highlight} objects.
11849 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11850 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11851 return;
11852 };
11853
11854 #[derive(Serialize)]
11855 struct Chunk<'a> {
11856 text: String,
11857 highlight: Option<&'a str>,
11858 }
11859
11860 let snapshot = buffer.read(cx).snapshot();
11861 let range = self
11862 .selected_text_range(false, cx)
11863 .and_then(|selection| {
11864 if selection.range.is_empty() {
11865 None
11866 } else {
11867 Some(selection.range)
11868 }
11869 })
11870 .unwrap_or_else(|| 0..snapshot.len());
11871
11872 let chunks = snapshot.chunks(range, true);
11873 let mut lines = Vec::new();
11874 let mut line: VecDeque<Chunk> = VecDeque::new();
11875
11876 let Some(style) = self.style.as_ref() else {
11877 return;
11878 };
11879
11880 for chunk in chunks {
11881 let highlight = chunk
11882 .syntax_highlight_id
11883 .and_then(|id| id.name(&style.syntax));
11884 let mut chunk_lines = chunk.text.split('\n').peekable();
11885 while let Some(text) = chunk_lines.next() {
11886 let mut merged_with_last_token = false;
11887 if let Some(last_token) = line.back_mut() {
11888 if last_token.highlight == highlight {
11889 last_token.text.push_str(text);
11890 merged_with_last_token = true;
11891 }
11892 }
11893
11894 if !merged_with_last_token {
11895 line.push_back(Chunk {
11896 text: text.into(),
11897 highlight,
11898 });
11899 }
11900
11901 if chunk_lines.peek().is_some() {
11902 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11903 line.pop_front();
11904 }
11905 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11906 line.pop_back();
11907 }
11908
11909 lines.push(mem::take(&mut line));
11910 }
11911 }
11912 }
11913
11914 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11915 return;
11916 };
11917 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11918 }
11919
11920 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11921 &self.inlay_hint_cache
11922 }
11923
11924 pub fn replay_insert_event(
11925 &mut self,
11926 text: &str,
11927 relative_utf16_range: Option<Range<isize>>,
11928 cx: &mut ViewContext<Self>,
11929 ) {
11930 if !self.input_enabled {
11931 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11932 return;
11933 }
11934 if let Some(relative_utf16_range) = relative_utf16_range {
11935 let selections = self.selections.all::<OffsetUtf16>(cx);
11936 self.change_selections(None, cx, |s| {
11937 let new_ranges = selections.into_iter().map(|range| {
11938 let start = OffsetUtf16(
11939 range
11940 .head()
11941 .0
11942 .saturating_add_signed(relative_utf16_range.start),
11943 );
11944 let end = OffsetUtf16(
11945 range
11946 .head()
11947 .0
11948 .saturating_add_signed(relative_utf16_range.end),
11949 );
11950 start..end
11951 });
11952 s.select_ranges(new_ranges);
11953 });
11954 }
11955
11956 self.handle_input(text, cx);
11957 }
11958
11959 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11960 let Some(project) = self.project.as_ref() else {
11961 return false;
11962 };
11963 let project = project.read(cx);
11964
11965 let mut supports = false;
11966 self.buffer().read(cx).for_each_buffer(|buffer| {
11967 if !supports {
11968 supports = project
11969 .language_servers_for_buffer(buffer.read(cx), cx)
11970 .any(
11971 |(_, server)| match server.capabilities().inlay_hint_provider {
11972 Some(lsp::OneOf::Left(enabled)) => enabled,
11973 Some(lsp::OneOf::Right(_)) => true,
11974 None => false,
11975 },
11976 )
11977 }
11978 });
11979 supports
11980 }
11981
11982 pub fn focus(&self, cx: &mut WindowContext) {
11983 cx.focus(&self.focus_handle)
11984 }
11985
11986 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11987 self.focus_handle.is_focused(cx)
11988 }
11989
11990 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11991 cx.emit(EditorEvent::Focused);
11992
11993 if let Some(descendant) = self
11994 .last_focused_descendant
11995 .take()
11996 .and_then(|descendant| descendant.upgrade())
11997 {
11998 cx.focus(&descendant);
11999 } else {
12000 if let Some(blame) = self.blame.as_ref() {
12001 blame.update(cx, GitBlame::focus)
12002 }
12003
12004 self.blink_manager.update(cx, BlinkManager::enable);
12005 self.show_cursor_names(cx);
12006 self.buffer.update(cx, |buffer, cx| {
12007 buffer.finalize_last_transaction(cx);
12008 if self.leader_peer_id.is_none() {
12009 buffer.set_active_selections(
12010 &self.selections.disjoint_anchors(),
12011 self.selections.line_mode,
12012 self.cursor_shape,
12013 cx,
12014 );
12015 }
12016 });
12017 }
12018 }
12019
12020 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12021 cx.emit(EditorEvent::FocusedIn)
12022 }
12023
12024 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12025 if event.blurred != self.focus_handle {
12026 self.last_focused_descendant = Some(event.blurred);
12027 }
12028 }
12029
12030 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12031 self.blink_manager.update(cx, BlinkManager::disable);
12032 self.buffer
12033 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12034
12035 if let Some(blame) = self.blame.as_ref() {
12036 blame.update(cx, GitBlame::blur)
12037 }
12038 if !self.hover_state.focused(cx) {
12039 hide_hover(self, cx);
12040 }
12041
12042 self.hide_context_menu(cx);
12043 cx.emit(EditorEvent::Blurred);
12044 cx.notify();
12045 }
12046
12047 pub fn register_action<A: Action>(
12048 &mut self,
12049 listener: impl Fn(&A, &mut WindowContext) + 'static,
12050 ) -> Subscription {
12051 let id = self.next_editor_action_id.post_inc();
12052 let listener = Arc::new(listener);
12053 self.editor_actions.borrow_mut().insert(
12054 id,
12055 Box::new(move |cx| {
12056 let cx = cx.window_context();
12057 let listener = listener.clone();
12058 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12059 let action = action.downcast_ref().unwrap();
12060 if phase == DispatchPhase::Bubble {
12061 listener(action, cx)
12062 }
12063 })
12064 }),
12065 );
12066
12067 let editor_actions = self.editor_actions.clone();
12068 Subscription::new(move || {
12069 editor_actions.borrow_mut().remove(&id);
12070 })
12071 }
12072
12073 pub fn file_header_size(&self) -> u32 {
12074 self.file_header_size
12075 }
12076
12077 pub fn revert(
12078 &mut self,
12079 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12080 cx: &mut ViewContext<Self>,
12081 ) {
12082 self.buffer().update(cx, |multi_buffer, cx| {
12083 for (buffer_id, changes) in revert_changes {
12084 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12085 buffer.update(cx, |buffer, cx| {
12086 buffer.edit(
12087 changes.into_iter().map(|(range, text)| {
12088 (range, text.to_string().map(Arc::<str>::from))
12089 }),
12090 None,
12091 cx,
12092 );
12093 });
12094 }
12095 }
12096 });
12097 self.change_selections(None, cx, |selections| selections.refresh());
12098 }
12099
12100 pub fn to_pixel_point(
12101 &mut self,
12102 source: multi_buffer::Anchor,
12103 editor_snapshot: &EditorSnapshot,
12104 cx: &mut ViewContext<Self>,
12105 ) -> Option<gpui::Point<Pixels>> {
12106 let source_point = source.to_display_point(editor_snapshot);
12107 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12108 }
12109
12110 pub fn display_to_pixel_point(
12111 &mut self,
12112 source: DisplayPoint,
12113 editor_snapshot: &EditorSnapshot,
12114 cx: &mut ViewContext<Self>,
12115 ) -> Option<gpui::Point<Pixels>> {
12116 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12117 let text_layout_details = self.text_layout_details(cx);
12118 let scroll_top = text_layout_details
12119 .scroll_anchor
12120 .scroll_position(editor_snapshot)
12121 .y;
12122
12123 if source.row().as_f32() < scroll_top.floor() {
12124 return None;
12125 }
12126 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12127 let source_y = line_height * (source.row().as_f32() - scroll_top);
12128 Some(gpui::Point::new(source_x, source_y))
12129 }
12130
12131 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12132 let bounds = self.last_bounds?;
12133 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12134 }
12135
12136 pub fn has_active_completions_menu(&self) -> bool {
12137 self.context_menu.read().as_ref().map_or(false, |menu| {
12138 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12139 })
12140 }
12141
12142 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12143 self.addons
12144 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12145 }
12146
12147 pub fn unregister_addon<T: Addon>(&mut self) {
12148 self.addons.remove(&std::any::TypeId::of::<T>());
12149 }
12150
12151 pub fn addon<T: Addon>(&self) -> Option<&T> {
12152 let type_id = std::any::TypeId::of::<T>();
12153 self.addons
12154 .get(&type_id)
12155 .and_then(|item| item.to_any().downcast_ref::<T>())
12156 }
12157}
12158
12159fn hunks_for_selections(
12160 multi_buffer_snapshot: &MultiBufferSnapshot,
12161 selections: &[Selection<Anchor>],
12162) -> Vec<DiffHunk<MultiBufferRow>> {
12163 let buffer_rows_for_selections = selections.iter().map(|selection| {
12164 let head = selection.head();
12165 let tail = selection.tail();
12166 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12167 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12168 if start > end {
12169 end..start
12170 } else {
12171 start..end
12172 }
12173 });
12174
12175 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12176}
12177
12178pub fn hunks_for_rows(
12179 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12180 multi_buffer_snapshot: &MultiBufferSnapshot,
12181) -> Vec<DiffHunk<MultiBufferRow>> {
12182 let mut hunks = Vec::new();
12183 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12184 HashMap::default();
12185 for selected_multi_buffer_rows in rows {
12186 let query_rows =
12187 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12188 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12189 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12190 // when the caret is just above or just below the deleted hunk.
12191 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12192 let related_to_selection = if allow_adjacent {
12193 hunk.associated_range.overlaps(&query_rows)
12194 || hunk.associated_range.start == query_rows.end
12195 || hunk.associated_range.end == query_rows.start
12196 } else {
12197 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12198 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12199 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12200 || selected_multi_buffer_rows.end == hunk.associated_range.start
12201 };
12202 if related_to_selection {
12203 if !processed_buffer_rows
12204 .entry(hunk.buffer_id)
12205 .or_default()
12206 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12207 {
12208 continue;
12209 }
12210 hunks.push(hunk);
12211 }
12212 }
12213 }
12214
12215 hunks
12216}
12217
12218pub trait CollaborationHub {
12219 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12220 fn user_participant_indices<'a>(
12221 &self,
12222 cx: &'a AppContext,
12223 ) -> &'a HashMap<u64, ParticipantIndex>;
12224 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12225}
12226
12227impl CollaborationHub for Model<Project> {
12228 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12229 self.read(cx).collaborators()
12230 }
12231
12232 fn user_participant_indices<'a>(
12233 &self,
12234 cx: &'a AppContext,
12235 ) -> &'a HashMap<u64, ParticipantIndex> {
12236 self.read(cx).user_store().read(cx).participant_indices()
12237 }
12238
12239 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12240 let this = self.read(cx);
12241 let user_ids = this.collaborators().values().map(|c| c.user_id);
12242 this.user_store().read_with(cx, |user_store, cx| {
12243 user_store.participant_names(user_ids, cx)
12244 })
12245 }
12246}
12247
12248pub trait CompletionProvider {
12249 fn completions(
12250 &self,
12251 buffer: &Model<Buffer>,
12252 buffer_position: text::Anchor,
12253 trigger: CompletionContext,
12254 cx: &mut ViewContext<Editor>,
12255 ) -> Task<Result<Vec<Completion>>>;
12256
12257 fn resolve_completions(
12258 &self,
12259 buffer: Model<Buffer>,
12260 completion_indices: Vec<usize>,
12261 completions: Arc<RwLock<Box<[Completion]>>>,
12262 cx: &mut ViewContext<Editor>,
12263 ) -> Task<Result<bool>>;
12264
12265 fn apply_additional_edits_for_completion(
12266 &self,
12267 buffer: Model<Buffer>,
12268 completion: Completion,
12269 push_to_history: bool,
12270 cx: &mut ViewContext<Editor>,
12271 ) -> Task<Result<Option<language::Transaction>>>;
12272
12273 fn is_completion_trigger(
12274 &self,
12275 buffer: &Model<Buffer>,
12276 position: language::Anchor,
12277 text: &str,
12278 trigger_in_words: bool,
12279 cx: &mut ViewContext<Editor>,
12280 ) -> bool;
12281
12282 fn sort_completions(&self) -> bool {
12283 true
12284 }
12285}
12286
12287fn snippet_completions(
12288 project: &Project,
12289 buffer: &Model<Buffer>,
12290 buffer_position: text::Anchor,
12291 cx: &mut AppContext,
12292) -> Vec<Completion> {
12293 let language = buffer.read(cx).language_at(buffer_position);
12294 let language_name = language.as_ref().map(|language| language.lsp_id());
12295 let snippet_store = project.snippets().read(cx);
12296 let snippets = snippet_store.snippets_for(language_name, cx);
12297
12298 if snippets.is_empty() {
12299 return vec![];
12300 }
12301 let snapshot = buffer.read(cx).text_snapshot();
12302 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12303
12304 let mut lines = chunks.lines();
12305 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12306 return vec![];
12307 };
12308
12309 let scope = language.map(|language| language.default_scope());
12310 let classifier = CharClassifier::new(scope).for_completion(true);
12311 let mut last_word = line_at
12312 .chars()
12313 .rev()
12314 .take_while(|c| classifier.is_word(*c))
12315 .collect::<String>();
12316 last_word = last_word.chars().rev().collect();
12317 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12318 let to_lsp = |point: &text::Anchor| {
12319 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12320 point_to_lsp(end)
12321 };
12322 let lsp_end = to_lsp(&buffer_position);
12323 snippets
12324 .into_iter()
12325 .filter_map(|snippet| {
12326 let matching_prefix = snippet
12327 .prefix
12328 .iter()
12329 .find(|prefix| prefix.starts_with(&last_word))?;
12330 let start = as_offset - last_word.len();
12331 let start = snapshot.anchor_before(start);
12332 let range = start..buffer_position;
12333 let lsp_start = to_lsp(&start);
12334 let lsp_range = lsp::Range {
12335 start: lsp_start,
12336 end: lsp_end,
12337 };
12338 Some(Completion {
12339 old_range: range,
12340 new_text: snippet.body.clone(),
12341 label: CodeLabel {
12342 text: matching_prefix.clone(),
12343 runs: vec![],
12344 filter_range: 0..matching_prefix.len(),
12345 },
12346 server_id: LanguageServerId(usize::MAX),
12347 documentation: snippet.description.clone().map(Documentation::SingleLine),
12348 lsp_completion: lsp::CompletionItem {
12349 label: snippet.prefix.first().unwrap().clone(),
12350 kind: Some(CompletionItemKind::SNIPPET),
12351 label_details: snippet.description.as_ref().map(|description| {
12352 lsp::CompletionItemLabelDetails {
12353 detail: Some(description.clone()),
12354 description: None,
12355 }
12356 }),
12357 insert_text_format: Some(InsertTextFormat::SNIPPET),
12358 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12359 lsp::InsertReplaceEdit {
12360 new_text: snippet.body.clone(),
12361 insert: lsp_range,
12362 replace: lsp_range,
12363 },
12364 )),
12365 filter_text: Some(snippet.body.clone()),
12366 sort_text: Some(char::MAX.to_string()),
12367 ..Default::default()
12368 },
12369 confirm: None,
12370 })
12371 })
12372 .collect()
12373}
12374
12375impl CompletionProvider for Model<Project> {
12376 fn completions(
12377 &self,
12378 buffer: &Model<Buffer>,
12379 buffer_position: text::Anchor,
12380 options: CompletionContext,
12381 cx: &mut ViewContext<Editor>,
12382 ) -> Task<Result<Vec<Completion>>> {
12383 self.update(cx, |project, cx| {
12384 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12385 let project_completions = project.completions(buffer, buffer_position, options, cx);
12386 cx.background_executor().spawn(async move {
12387 let mut completions = project_completions.await?;
12388 //let snippets = snippets.into_iter().;
12389 completions.extend(snippets);
12390 Ok(completions)
12391 })
12392 })
12393 }
12394
12395 fn resolve_completions(
12396 &self,
12397 buffer: Model<Buffer>,
12398 completion_indices: Vec<usize>,
12399 completions: Arc<RwLock<Box<[Completion]>>>,
12400 cx: &mut ViewContext<Editor>,
12401 ) -> Task<Result<bool>> {
12402 self.update(cx, |project, cx| {
12403 project.resolve_completions(buffer, completion_indices, completions, cx)
12404 })
12405 }
12406
12407 fn apply_additional_edits_for_completion(
12408 &self,
12409 buffer: Model<Buffer>,
12410 completion: Completion,
12411 push_to_history: bool,
12412 cx: &mut ViewContext<Editor>,
12413 ) -> Task<Result<Option<language::Transaction>>> {
12414 self.update(cx, |project, cx| {
12415 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12416 })
12417 }
12418
12419 fn is_completion_trigger(
12420 &self,
12421 buffer: &Model<Buffer>,
12422 position: language::Anchor,
12423 text: &str,
12424 trigger_in_words: bool,
12425 cx: &mut ViewContext<Editor>,
12426 ) -> bool {
12427 if !EditorSettings::get_global(cx).show_completions_on_input {
12428 return false;
12429 }
12430
12431 let mut chars = text.chars();
12432 let char = if let Some(char) = chars.next() {
12433 char
12434 } else {
12435 return false;
12436 };
12437 if chars.next().is_some() {
12438 return false;
12439 }
12440
12441 let buffer = buffer.read(cx);
12442 let classifier = buffer
12443 .snapshot()
12444 .char_classifier_at(position)
12445 .for_completion(true);
12446 if trigger_in_words && classifier.is_word(char) {
12447 return true;
12448 }
12449
12450 buffer
12451 .completion_triggers()
12452 .iter()
12453 .any(|string| string == text)
12454 }
12455}
12456
12457fn inlay_hint_settings(
12458 location: Anchor,
12459 snapshot: &MultiBufferSnapshot,
12460 cx: &mut ViewContext<'_, Editor>,
12461) -> InlayHintSettings {
12462 let file = snapshot.file_at(location);
12463 let language = snapshot.language_at(location);
12464 let settings = all_language_settings(file, cx);
12465 settings
12466 .language(language.map(|l| l.name()).as_deref())
12467 .inlay_hints
12468}
12469
12470fn consume_contiguous_rows(
12471 contiguous_row_selections: &mut Vec<Selection<Point>>,
12472 selection: &Selection<Point>,
12473 display_map: &DisplaySnapshot,
12474 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12475) -> (MultiBufferRow, MultiBufferRow) {
12476 contiguous_row_selections.push(selection.clone());
12477 let start_row = MultiBufferRow(selection.start.row);
12478 let mut end_row = ending_row(selection, display_map);
12479
12480 while let Some(next_selection) = selections.peek() {
12481 if next_selection.start.row <= end_row.0 {
12482 end_row = ending_row(next_selection, display_map);
12483 contiguous_row_selections.push(selections.next().unwrap().clone());
12484 } else {
12485 break;
12486 }
12487 }
12488 (start_row, end_row)
12489}
12490
12491fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12492 if next_selection.end.column > 0 || next_selection.is_empty() {
12493 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12494 } else {
12495 MultiBufferRow(next_selection.end.row)
12496 }
12497}
12498
12499impl EditorSnapshot {
12500 pub fn remote_selections_in_range<'a>(
12501 &'a self,
12502 range: &'a Range<Anchor>,
12503 collaboration_hub: &dyn CollaborationHub,
12504 cx: &'a AppContext,
12505 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12506 let participant_names = collaboration_hub.user_names(cx);
12507 let participant_indices = collaboration_hub.user_participant_indices(cx);
12508 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12509 let collaborators_by_replica_id = collaborators_by_peer_id
12510 .iter()
12511 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12512 .collect::<HashMap<_, _>>();
12513 self.buffer_snapshot
12514 .selections_in_range(range, false)
12515 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12516 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12517 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12518 let user_name = participant_names.get(&collaborator.user_id).cloned();
12519 Some(RemoteSelection {
12520 replica_id,
12521 selection,
12522 cursor_shape,
12523 line_mode,
12524 participant_index,
12525 peer_id: collaborator.peer_id,
12526 user_name,
12527 })
12528 })
12529 }
12530
12531 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12532 self.display_snapshot.buffer_snapshot.language_at(position)
12533 }
12534
12535 pub fn is_focused(&self) -> bool {
12536 self.is_focused
12537 }
12538
12539 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12540 self.placeholder_text.as_ref()
12541 }
12542
12543 pub fn scroll_position(&self) -> gpui::Point<f32> {
12544 self.scroll_anchor.scroll_position(&self.display_snapshot)
12545 }
12546
12547 fn gutter_dimensions(
12548 &self,
12549 font_id: FontId,
12550 font_size: Pixels,
12551 em_width: Pixels,
12552 max_line_number_width: Pixels,
12553 cx: &AppContext,
12554 ) -> GutterDimensions {
12555 if !self.show_gutter {
12556 return GutterDimensions::default();
12557 }
12558 let descent = cx.text_system().descent(font_id, font_size);
12559
12560 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12561 matches!(
12562 ProjectSettings::get_global(cx).git.git_gutter,
12563 Some(GitGutterSetting::TrackedFiles)
12564 )
12565 });
12566 let gutter_settings = EditorSettings::get_global(cx).gutter;
12567 let show_line_numbers = self
12568 .show_line_numbers
12569 .unwrap_or(gutter_settings.line_numbers);
12570 let line_gutter_width = if show_line_numbers {
12571 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12572 let min_width_for_number_on_gutter = em_width * 4.0;
12573 max_line_number_width.max(min_width_for_number_on_gutter)
12574 } else {
12575 0.0.into()
12576 };
12577
12578 let show_code_actions = self
12579 .show_code_actions
12580 .unwrap_or(gutter_settings.code_actions);
12581
12582 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12583
12584 let git_blame_entries_width = self
12585 .render_git_blame_gutter
12586 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12587
12588 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12589 left_padding += if show_code_actions || show_runnables {
12590 em_width * 3.0
12591 } else if show_git_gutter && show_line_numbers {
12592 em_width * 2.0
12593 } else if show_git_gutter || show_line_numbers {
12594 em_width
12595 } else {
12596 px(0.)
12597 };
12598
12599 let right_padding = if gutter_settings.folds && show_line_numbers {
12600 em_width * 4.0
12601 } else if gutter_settings.folds {
12602 em_width * 3.0
12603 } else if show_line_numbers {
12604 em_width
12605 } else {
12606 px(0.)
12607 };
12608
12609 GutterDimensions {
12610 left_padding,
12611 right_padding,
12612 width: line_gutter_width + left_padding + right_padding,
12613 margin: -descent,
12614 git_blame_entries_width,
12615 }
12616 }
12617
12618 pub fn render_fold_toggle(
12619 &self,
12620 buffer_row: MultiBufferRow,
12621 row_contains_cursor: bool,
12622 editor: View<Editor>,
12623 cx: &mut WindowContext,
12624 ) -> Option<AnyElement> {
12625 let folded = self.is_line_folded(buffer_row);
12626
12627 if let Some(crease) = self
12628 .crease_snapshot
12629 .query_row(buffer_row, &self.buffer_snapshot)
12630 {
12631 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12632 if folded {
12633 editor.update(cx, |editor, cx| {
12634 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12635 });
12636 } else {
12637 editor.update(cx, |editor, cx| {
12638 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12639 });
12640 }
12641 });
12642
12643 Some((crease.render_toggle)(
12644 buffer_row,
12645 folded,
12646 toggle_callback,
12647 cx,
12648 ))
12649 } else if folded
12650 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12651 {
12652 Some(
12653 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12654 .selected(folded)
12655 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12656 if folded {
12657 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12658 } else {
12659 this.fold_at(&FoldAt { buffer_row }, cx);
12660 }
12661 }))
12662 .into_any_element(),
12663 )
12664 } else {
12665 None
12666 }
12667 }
12668
12669 pub fn render_crease_trailer(
12670 &self,
12671 buffer_row: MultiBufferRow,
12672 cx: &mut WindowContext,
12673 ) -> Option<AnyElement> {
12674 let folded = self.is_line_folded(buffer_row);
12675 let crease = self
12676 .crease_snapshot
12677 .query_row(buffer_row, &self.buffer_snapshot)?;
12678 Some((crease.render_trailer)(buffer_row, folded, cx))
12679 }
12680}
12681
12682impl Deref for EditorSnapshot {
12683 type Target = DisplaySnapshot;
12684
12685 fn deref(&self) -> &Self::Target {
12686 &self.display_snapshot
12687 }
12688}
12689
12690#[derive(Clone, Debug, PartialEq, Eq)]
12691pub enum EditorEvent {
12692 InputIgnored {
12693 text: Arc<str>,
12694 },
12695 InputHandled {
12696 utf16_range_to_replace: Option<Range<isize>>,
12697 text: Arc<str>,
12698 },
12699 ExcerptsAdded {
12700 buffer: Model<Buffer>,
12701 predecessor: ExcerptId,
12702 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12703 },
12704 ExcerptsRemoved {
12705 ids: Vec<ExcerptId>,
12706 },
12707 ExcerptsEdited {
12708 ids: Vec<ExcerptId>,
12709 },
12710 ExcerptsExpanded {
12711 ids: Vec<ExcerptId>,
12712 },
12713 BufferEdited,
12714 Edited {
12715 transaction_id: clock::Lamport,
12716 },
12717 Reparsed(BufferId),
12718 Focused,
12719 FocusedIn,
12720 Blurred,
12721 DirtyChanged,
12722 Saved,
12723 TitleChanged,
12724 DiffBaseChanged,
12725 SelectionsChanged {
12726 local: bool,
12727 },
12728 ScrollPositionChanged {
12729 local: bool,
12730 autoscroll: bool,
12731 },
12732 Closed,
12733 TransactionUndone {
12734 transaction_id: clock::Lamport,
12735 },
12736 TransactionBegun {
12737 transaction_id: clock::Lamport,
12738 },
12739}
12740
12741impl EventEmitter<EditorEvent> for Editor {}
12742
12743impl FocusableView for Editor {
12744 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12745 self.focus_handle.clone()
12746 }
12747}
12748
12749impl Render for Editor {
12750 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12751 let settings = ThemeSettings::get_global(cx);
12752
12753 let text_style = match self.mode {
12754 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12755 color: cx.theme().colors().editor_foreground,
12756 font_family: settings.ui_font.family.clone(),
12757 font_features: settings.ui_font.features.clone(),
12758 font_fallbacks: settings.ui_font.fallbacks.clone(),
12759 font_size: rems(0.875).into(),
12760 font_weight: settings.ui_font.weight,
12761 line_height: relative(settings.buffer_line_height.value()),
12762 ..Default::default()
12763 },
12764 EditorMode::Full => TextStyle {
12765 color: cx.theme().colors().editor_foreground,
12766 font_family: settings.buffer_font.family.clone(),
12767 font_features: settings.buffer_font.features.clone(),
12768 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12769 font_size: settings.buffer_font_size(cx).into(),
12770 font_weight: settings.buffer_font.weight,
12771 line_height: relative(settings.buffer_line_height.value()),
12772 ..Default::default()
12773 },
12774 };
12775
12776 let background = match self.mode {
12777 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12778 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12779 EditorMode::Full => cx.theme().colors().editor_background,
12780 };
12781
12782 EditorElement::new(
12783 cx.view(),
12784 EditorStyle {
12785 background,
12786 local_player: cx.theme().players().local(),
12787 text: text_style,
12788 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12789 syntax: cx.theme().syntax().clone(),
12790 status: cx.theme().status().clone(),
12791 inlay_hints_style: HighlightStyle {
12792 color: Some(cx.theme().status().hint),
12793 ..HighlightStyle::default()
12794 },
12795 suggestions_style: HighlightStyle {
12796 color: Some(cx.theme().status().predictive),
12797 ..HighlightStyle::default()
12798 },
12799 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12800 },
12801 )
12802 }
12803}
12804
12805impl ViewInputHandler for Editor {
12806 fn text_for_range(
12807 &mut self,
12808 range_utf16: Range<usize>,
12809 cx: &mut ViewContext<Self>,
12810 ) -> Option<String> {
12811 Some(
12812 self.buffer
12813 .read(cx)
12814 .read(cx)
12815 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12816 .collect(),
12817 )
12818 }
12819
12820 fn selected_text_range(
12821 &mut self,
12822 ignore_disabled_input: bool,
12823 cx: &mut ViewContext<Self>,
12824 ) -> Option<UTF16Selection> {
12825 // Prevent the IME menu from appearing when holding down an alphabetic key
12826 // while input is disabled.
12827 if !ignore_disabled_input && !self.input_enabled {
12828 return None;
12829 }
12830
12831 let selection = self.selections.newest::<OffsetUtf16>(cx);
12832 let range = selection.range();
12833
12834 Some(UTF16Selection {
12835 range: range.start.0..range.end.0,
12836 reversed: selection.reversed,
12837 })
12838 }
12839
12840 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12841 let snapshot = self.buffer.read(cx).read(cx);
12842 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
12843 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12844 }
12845
12846 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12847 self.clear_highlights::<InputComposition>(cx);
12848 self.ime_transaction.take();
12849 }
12850
12851 fn replace_text_in_range(
12852 &mut self,
12853 range_utf16: Option<Range<usize>>,
12854 text: &str,
12855 cx: &mut ViewContext<Self>,
12856 ) {
12857 if !self.input_enabled {
12858 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12859 return;
12860 }
12861
12862 self.transact(cx, |this, cx| {
12863 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12864 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12865 Some(this.selection_replacement_ranges(range_utf16, cx))
12866 } else {
12867 this.marked_text_ranges(cx)
12868 };
12869
12870 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12871 let newest_selection_id = this.selections.newest_anchor().id;
12872 this.selections
12873 .all::<OffsetUtf16>(cx)
12874 .iter()
12875 .zip(ranges_to_replace.iter())
12876 .find_map(|(selection, range)| {
12877 if selection.id == newest_selection_id {
12878 Some(
12879 (range.start.0 as isize - selection.head().0 as isize)
12880 ..(range.end.0 as isize - selection.head().0 as isize),
12881 )
12882 } else {
12883 None
12884 }
12885 })
12886 });
12887
12888 cx.emit(EditorEvent::InputHandled {
12889 utf16_range_to_replace: range_to_replace,
12890 text: text.into(),
12891 });
12892
12893 if let Some(new_selected_ranges) = new_selected_ranges {
12894 this.change_selections(None, cx, |selections| {
12895 selections.select_ranges(new_selected_ranges)
12896 });
12897 this.backspace(&Default::default(), cx);
12898 }
12899
12900 this.handle_input(text, cx);
12901 });
12902
12903 if let Some(transaction) = self.ime_transaction {
12904 self.buffer.update(cx, |buffer, cx| {
12905 buffer.group_until_transaction(transaction, cx);
12906 });
12907 }
12908
12909 self.unmark_text(cx);
12910 }
12911
12912 fn replace_and_mark_text_in_range(
12913 &mut self,
12914 range_utf16: Option<Range<usize>>,
12915 text: &str,
12916 new_selected_range_utf16: Option<Range<usize>>,
12917 cx: &mut ViewContext<Self>,
12918 ) {
12919 if !self.input_enabled {
12920 return;
12921 }
12922
12923 let transaction = self.transact(cx, |this, cx| {
12924 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12925 let snapshot = this.buffer.read(cx).read(cx);
12926 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12927 for marked_range in &mut marked_ranges {
12928 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12929 marked_range.start.0 += relative_range_utf16.start;
12930 marked_range.start =
12931 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12932 marked_range.end =
12933 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12934 }
12935 }
12936 Some(marked_ranges)
12937 } else if let Some(range_utf16) = range_utf16 {
12938 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12939 Some(this.selection_replacement_ranges(range_utf16, cx))
12940 } else {
12941 None
12942 };
12943
12944 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12945 let newest_selection_id = this.selections.newest_anchor().id;
12946 this.selections
12947 .all::<OffsetUtf16>(cx)
12948 .iter()
12949 .zip(ranges_to_replace.iter())
12950 .find_map(|(selection, range)| {
12951 if selection.id == newest_selection_id {
12952 Some(
12953 (range.start.0 as isize - selection.head().0 as isize)
12954 ..(range.end.0 as isize - selection.head().0 as isize),
12955 )
12956 } else {
12957 None
12958 }
12959 })
12960 });
12961
12962 cx.emit(EditorEvent::InputHandled {
12963 utf16_range_to_replace: range_to_replace,
12964 text: text.into(),
12965 });
12966
12967 if let Some(ranges) = ranges_to_replace {
12968 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12969 }
12970
12971 let marked_ranges = {
12972 let snapshot = this.buffer.read(cx).read(cx);
12973 this.selections
12974 .disjoint_anchors()
12975 .iter()
12976 .map(|selection| {
12977 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12978 })
12979 .collect::<Vec<_>>()
12980 };
12981
12982 if text.is_empty() {
12983 this.unmark_text(cx);
12984 } else {
12985 this.highlight_text::<InputComposition>(
12986 marked_ranges.clone(),
12987 HighlightStyle {
12988 underline: Some(UnderlineStyle {
12989 thickness: px(1.),
12990 color: None,
12991 wavy: false,
12992 }),
12993 ..Default::default()
12994 },
12995 cx,
12996 );
12997 }
12998
12999 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13000 let use_autoclose = this.use_autoclose;
13001 let use_auto_surround = this.use_auto_surround;
13002 this.set_use_autoclose(false);
13003 this.set_use_auto_surround(false);
13004 this.handle_input(text, cx);
13005 this.set_use_autoclose(use_autoclose);
13006 this.set_use_auto_surround(use_auto_surround);
13007
13008 if let Some(new_selected_range) = new_selected_range_utf16 {
13009 let snapshot = this.buffer.read(cx).read(cx);
13010 let new_selected_ranges = marked_ranges
13011 .into_iter()
13012 .map(|marked_range| {
13013 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13014 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13015 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13016 snapshot.clip_offset_utf16(new_start, Bias::Left)
13017 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13018 })
13019 .collect::<Vec<_>>();
13020
13021 drop(snapshot);
13022 this.change_selections(None, cx, |selections| {
13023 selections.select_ranges(new_selected_ranges)
13024 });
13025 }
13026 });
13027
13028 self.ime_transaction = self.ime_transaction.or(transaction);
13029 if let Some(transaction) = self.ime_transaction {
13030 self.buffer.update(cx, |buffer, cx| {
13031 buffer.group_until_transaction(transaction, cx);
13032 });
13033 }
13034
13035 if self.text_highlights::<InputComposition>(cx).is_none() {
13036 self.ime_transaction.take();
13037 }
13038 }
13039
13040 fn bounds_for_range(
13041 &mut self,
13042 range_utf16: Range<usize>,
13043 element_bounds: gpui::Bounds<Pixels>,
13044 cx: &mut ViewContext<Self>,
13045 ) -> Option<gpui::Bounds<Pixels>> {
13046 let text_layout_details = self.text_layout_details(cx);
13047 let style = &text_layout_details.editor_style;
13048 let font_id = cx.text_system().resolve_font(&style.text.font());
13049 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13050 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13051
13052 let em_width = cx
13053 .text_system()
13054 .typographic_bounds(font_id, font_size, 'm')
13055 .unwrap()
13056 .size
13057 .width;
13058
13059 let snapshot = self.snapshot(cx);
13060 let scroll_position = snapshot.scroll_position();
13061 let scroll_left = scroll_position.x * em_width;
13062
13063 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13064 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13065 + self.gutter_dimensions.width;
13066 let y = line_height * (start.row().as_f32() - scroll_position.y);
13067
13068 Some(Bounds {
13069 origin: element_bounds.origin + point(x, y),
13070 size: size(em_width, line_height),
13071 })
13072 }
13073}
13074
13075trait SelectionExt {
13076 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13077 fn spanned_rows(
13078 &self,
13079 include_end_if_at_line_start: bool,
13080 map: &DisplaySnapshot,
13081 ) -> Range<MultiBufferRow>;
13082}
13083
13084impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13085 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13086 let start = self
13087 .start
13088 .to_point(&map.buffer_snapshot)
13089 .to_display_point(map);
13090 let end = self
13091 .end
13092 .to_point(&map.buffer_snapshot)
13093 .to_display_point(map);
13094 if self.reversed {
13095 end..start
13096 } else {
13097 start..end
13098 }
13099 }
13100
13101 fn spanned_rows(
13102 &self,
13103 include_end_if_at_line_start: bool,
13104 map: &DisplaySnapshot,
13105 ) -> Range<MultiBufferRow> {
13106 let start = self.start.to_point(&map.buffer_snapshot);
13107 let mut end = self.end.to_point(&map.buffer_snapshot);
13108 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13109 end.row -= 1;
13110 }
13111
13112 let buffer_start = map.prev_line_boundary(start).0;
13113 let buffer_end = map.next_line_boundary(end).0;
13114 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13115 }
13116}
13117
13118impl<T: InvalidationRegion> InvalidationStack<T> {
13119 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13120 where
13121 S: Clone + ToOffset,
13122 {
13123 while let Some(region) = self.last() {
13124 let all_selections_inside_invalidation_ranges =
13125 if selections.len() == region.ranges().len() {
13126 selections
13127 .iter()
13128 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13129 .all(|(selection, invalidation_range)| {
13130 let head = selection.head().to_offset(buffer);
13131 invalidation_range.start <= head && invalidation_range.end >= head
13132 })
13133 } else {
13134 false
13135 };
13136
13137 if all_selections_inside_invalidation_ranges {
13138 break;
13139 } else {
13140 self.pop();
13141 }
13142 }
13143 }
13144}
13145
13146impl<T> Default for InvalidationStack<T> {
13147 fn default() -> Self {
13148 Self(Default::default())
13149 }
13150}
13151
13152impl<T> Deref for InvalidationStack<T> {
13153 type Target = Vec<T>;
13154
13155 fn deref(&self) -> &Self::Target {
13156 &self.0
13157 }
13158}
13159
13160impl<T> DerefMut for InvalidationStack<T> {
13161 fn deref_mut(&mut self) -> &mut Self::Target {
13162 &mut self.0
13163 }
13164}
13165
13166impl InvalidationRegion for SnippetState {
13167 fn ranges(&self) -> &[Range<Anchor>] {
13168 &self.ranges[self.active_index]
13169 }
13170}
13171
13172pub fn diagnostic_block_renderer(
13173 diagnostic: Diagnostic,
13174 max_message_rows: Option<u8>,
13175 allow_closing: bool,
13176 _is_valid: bool,
13177) -> RenderBlock {
13178 let (text_without_backticks, code_ranges) =
13179 highlight_diagnostic_message(&diagnostic, max_message_rows);
13180
13181 Box::new(move |cx: &mut BlockContext| {
13182 let group_id: SharedString = cx.block_id.to_string().into();
13183
13184 let mut text_style = cx.text_style().clone();
13185 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13186 let theme_settings = ThemeSettings::get_global(cx);
13187 text_style.font_family = theme_settings.buffer_font.family.clone();
13188 text_style.font_style = theme_settings.buffer_font.style;
13189 text_style.font_features = theme_settings.buffer_font.features.clone();
13190 text_style.font_weight = theme_settings.buffer_font.weight;
13191
13192 let multi_line_diagnostic = diagnostic.message.contains('\n');
13193
13194 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13195 if multi_line_diagnostic {
13196 v_flex()
13197 } else {
13198 h_flex()
13199 }
13200 .when(allow_closing, |div| {
13201 div.children(diagnostic.is_primary.then(|| {
13202 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13203 .icon_color(Color::Muted)
13204 .size(ButtonSize::Compact)
13205 .style(ButtonStyle::Transparent)
13206 .visible_on_hover(group_id.clone())
13207 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13208 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13209 }))
13210 })
13211 .child(
13212 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13213 .icon_color(Color::Muted)
13214 .size(ButtonSize::Compact)
13215 .style(ButtonStyle::Transparent)
13216 .visible_on_hover(group_id.clone())
13217 .on_click({
13218 let message = diagnostic.message.clone();
13219 move |_click, cx| {
13220 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13221 }
13222 })
13223 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13224 )
13225 };
13226
13227 let icon_size = buttons(&diagnostic, cx.block_id)
13228 .into_any_element()
13229 .layout_as_root(AvailableSpace::min_size(), cx);
13230
13231 h_flex()
13232 .id(cx.block_id)
13233 .group(group_id.clone())
13234 .relative()
13235 .size_full()
13236 .pl(cx.gutter_dimensions.width)
13237 .w(cx.max_width + cx.gutter_dimensions.width)
13238 .child(
13239 div()
13240 .flex()
13241 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13242 .flex_shrink(),
13243 )
13244 .child(buttons(&diagnostic, cx.block_id))
13245 .child(div().flex().flex_shrink_0().child(
13246 StyledText::new(text_without_backticks.clone()).with_highlights(
13247 &text_style,
13248 code_ranges.iter().map(|range| {
13249 (
13250 range.clone(),
13251 HighlightStyle {
13252 font_weight: Some(FontWeight::BOLD),
13253 ..Default::default()
13254 },
13255 )
13256 }),
13257 ),
13258 ))
13259 .into_any_element()
13260 })
13261}
13262
13263pub fn highlight_diagnostic_message(
13264 diagnostic: &Diagnostic,
13265 mut max_message_rows: Option<u8>,
13266) -> (SharedString, Vec<Range<usize>>) {
13267 let mut text_without_backticks = String::new();
13268 let mut code_ranges = Vec::new();
13269
13270 if let Some(source) = &diagnostic.source {
13271 text_without_backticks.push_str(source);
13272 code_ranges.push(0..source.len());
13273 text_without_backticks.push_str(": ");
13274 }
13275
13276 let mut prev_offset = 0;
13277 let mut in_code_block = false;
13278 let has_row_limit = max_message_rows.is_some();
13279 let mut newline_indices = diagnostic
13280 .message
13281 .match_indices('\n')
13282 .filter(|_| has_row_limit)
13283 .map(|(ix, _)| ix)
13284 .fuse()
13285 .peekable();
13286
13287 for (quote_ix, _) in diagnostic
13288 .message
13289 .match_indices('`')
13290 .chain([(diagnostic.message.len(), "")])
13291 {
13292 let mut first_newline_ix = None;
13293 let mut last_newline_ix = None;
13294 while let Some(newline_ix) = newline_indices.peek() {
13295 if *newline_ix < quote_ix {
13296 if first_newline_ix.is_none() {
13297 first_newline_ix = Some(*newline_ix);
13298 }
13299 last_newline_ix = Some(*newline_ix);
13300
13301 if let Some(rows_left) = &mut max_message_rows {
13302 if *rows_left == 0 {
13303 break;
13304 } else {
13305 *rows_left -= 1;
13306 }
13307 }
13308 let _ = newline_indices.next();
13309 } else {
13310 break;
13311 }
13312 }
13313 let prev_len = text_without_backticks.len();
13314 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13315 text_without_backticks.push_str(new_text);
13316 if in_code_block {
13317 code_ranges.push(prev_len..text_without_backticks.len());
13318 }
13319 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13320 in_code_block = !in_code_block;
13321 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13322 text_without_backticks.push_str("...");
13323 break;
13324 }
13325 }
13326
13327 (text_without_backticks.into(), code_ranges)
13328}
13329
13330fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13331 match severity {
13332 DiagnosticSeverity::ERROR => colors.error,
13333 DiagnosticSeverity::WARNING => colors.warning,
13334 DiagnosticSeverity::INFORMATION => colors.info,
13335 DiagnosticSeverity::HINT => colors.info,
13336 _ => colors.ignored,
13337 }
13338}
13339
13340pub fn styled_runs_for_code_label<'a>(
13341 label: &'a CodeLabel,
13342 syntax_theme: &'a theme::SyntaxTheme,
13343) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13344 let fade_out = HighlightStyle {
13345 fade_out: Some(0.35),
13346 ..Default::default()
13347 };
13348
13349 let mut prev_end = label.filter_range.end;
13350 label
13351 .runs
13352 .iter()
13353 .enumerate()
13354 .flat_map(move |(ix, (range, highlight_id))| {
13355 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13356 style
13357 } else {
13358 return Default::default();
13359 };
13360 let mut muted_style = style;
13361 muted_style.highlight(fade_out);
13362
13363 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13364 if range.start >= label.filter_range.end {
13365 if range.start > prev_end {
13366 runs.push((prev_end..range.start, fade_out));
13367 }
13368 runs.push((range.clone(), muted_style));
13369 } else if range.end <= label.filter_range.end {
13370 runs.push((range.clone(), style));
13371 } else {
13372 runs.push((range.start..label.filter_range.end, style));
13373 runs.push((label.filter_range.end..range.end, muted_style));
13374 }
13375 prev_end = cmp::max(prev_end, range.end);
13376
13377 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13378 runs.push((prev_end..label.text.len(), fade_out));
13379 }
13380
13381 runs
13382 })
13383}
13384
13385pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13386 let mut prev_index = 0;
13387 let mut prev_codepoint: Option<char> = None;
13388 text.char_indices()
13389 .chain([(text.len(), '\0')])
13390 .filter_map(move |(index, codepoint)| {
13391 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13392 let is_boundary = index == text.len()
13393 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13394 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13395 if is_boundary {
13396 let chunk = &text[prev_index..index];
13397 prev_index = index;
13398 Some(chunk)
13399 } else {
13400 None
13401 }
13402 })
13403}
13404
13405pub trait RangeToAnchorExt: Sized {
13406 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13407
13408 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13409 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13410 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13411 }
13412}
13413
13414impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13415 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13416 let start_offset = self.start.to_offset(snapshot);
13417 let end_offset = self.end.to_offset(snapshot);
13418 if start_offset == end_offset {
13419 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13420 } else {
13421 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13422 }
13423 }
13424}
13425
13426pub trait RowExt {
13427 fn as_f32(&self) -> f32;
13428
13429 fn next_row(&self) -> Self;
13430
13431 fn previous_row(&self) -> Self;
13432
13433 fn minus(&self, other: Self) -> u32;
13434}
13435
13436impl RowExt for DisplayRow {
13437 fn as_f32(&self) -> f32 {
13438 self.0 as f32
13439 }
13440
13441 fn next_row(&self) -> Self {
13442 Self(self.0 + 1)
13443 }
13444
13445 fn previous_row(&self) -> Self {
13446 Self(self.0.saturating_sub(1))
13447 }
13448
13449 fn minus(&self, other: Self) -> u32 {
13450 self.0 - other.0
13451 }
13452}
13453
13454impl RowExt for MultiBufferRow {
13455 fn as_f32(&self) -> f32 {
13456 self.0 as f32
13457 }
13458
13459 fn next_row(&self) -> Self {
13460 Self(self.0 + 1)
13461 }
13462
13463 fn previous_row(&self) -> Self {
13464 Self(self.0.saturating_sub(1))
13465 }
13466
13467 fn minus(&self, other: Self) -> u32 {
13468 self.0 - other.0
13469 }
13470}
13471
13472trait RowRangeExt {
13473 type Row;
13474
13475 fn len(&self) -> usize;
13476
13477 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13478}
13479
13480impl RowRangeExt for Range<MultiBufferRow> {
13481 type Row = MultiBufferRow;
13482
13483 fn len(&self) -> usize {
13484 (self.end.0 - self.start.0) as usize
13485 }
13486
13487 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13488 (self.start.0..self.end.0).map(MultiBufferRow)
13489 }
13490}
13491
13492impl RowRangeExt for Range<DisplayRow> {
13493 type Row = DisplayRow;
13494
13495 fn len(&self) -> usize {
13496 (self.end.0 - self.start.0) as usize
13497 }
13498
13499 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13500 (self.start.0..self.end.0).map(DisplayRow)
13501 }
13502}
13503
13504fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13505 if hunk.diff_base_byte_range.is_empty() {
13506 DiffHunkStatus::Added
13507 } else if hunk.associated_range.is_empty() {
13508 DiffHunkStatus::Removed
13509 } else {
13510 DiffHunkStatus::Modified
13511 }
13512}
13513
13514/// If select range has more than one line, we
13515/// just point the cursor to range.start.
13516fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13517 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13518 range
13519 } else {
13520 range.start..range.start
13521 }
13522}