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, WorktreeId,
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, 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 return 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.len() > 0 {
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 if let Some(selection) = clicked_point_already_selected {
2742 Some(selection.id)
2743 } else {
2744 None
2745 }
2746 }
2747 };
2748
2749 let selections_count = self.selections.count();
2750
2751 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2752 if let Some(point_to_delete) = point_to_delete {
2753 s.delete(point_to_delete);
2754
2755 if selections_count == 1 {
2756 s.set_pending_anchor_range(start..end, mode);
2757 }
2758 } else {
2759 if !add {
2760 s.clear_disjoint();
2761 } else if click_count > 1 {
2762 s.delete(newest_selection.id)
2763 }
2764
2765 s.set_pending_anchor_range(start..end, mode);
2766 }
2767 });
2768 }
2769
2770 fn begin_columnar_selection(
2771 &mut self,
2772 position: DisplayPoint,
2773 goal_column: u32,
2774 reset: bool,
2775 cx: &mut ViewContext<Self>,
2776 ) {
2777 if !self.focus_handle.is_focused(cx) {
2778 self.last_focused_descendant = None;
2779 cx.focus(&self.focus_handle);
2780 }
2781
2782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2783
2784 if reset {
2785 let pointer_position = display_map
2786 .buffer_snapshot
2787 .anchor_before(position.to_point(&display_map));
2788
2789 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2790 s.clear_disjoint();
2791 s.set_pending_anchor_range(
2792 pointer_position..pointer_position,
2793 SelectMode::Character,
2794 );
2795 });
2796 }
2797
2798 let tail = self.selections.newest::<Point>(cx).tail();
2799 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2800
2801 if !reset {
2802 self.select_columns(
2803 tail.to_display_point(&display_map),
2804 position,
2805 goal_column,
2806 &display_map,
2807 cx,
2808 );
2809 }
2810 }
2811
2812 fn update_selection(
2813 &mut self,
2814 position: DisplayPoint,
2815 goal_column: u32,
2816 scroll_delta: gpui::Point<f32>,
2817 cx: &mut ViewContext<Self>,
2818 ) {
2819 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2820
2821 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2822 let tail = tail.to_display_point(&display_map);
2823 self.select_columns(tail, position, goal_column, &display_map, cx);
2824 } else if let Some(mut pending) = self.selections.pending_anchor() {
2825 let buffer = self.buffer.read(cx).snapshot(cx);
2826 let head;
2827 let tail;
2828 let mode = self.selections.pending_mode().unwrap();
2829 match &mode {
2830 SelectMode::Character => {
2831 head = position.to_point(&display_map);
2832 tail = pending.tail().to_point(&buffer);
2833 }
2834 SelectMode::Word(original_range) => {
2835 let original_display_range = original_range.start.to_display_point(&display_map)
2836 ..original_range.end.to_display_point(&display_map);
2837 let original_buffer_range = original_display_range.start.to_point(&display_map)
2838 ..original_display_range.end.to_point(&display_map);
2839 if movement::is_inside_word(&display_map, position)
2840 || original_display_range.contains(&position)
2841 {
2842 let word_range = movement::surrounding_word(&display_map, position);
2843 if word_range.start < original_display_range.start {
2844 head = word_range.start.to_point(&display_map);
2845 } else {
2846 head = word_range.end.to_point(&display_map);
2847 }
2848 } else {
2849 head = position.to_point(&display_map);
2850 }
2851
2852 if head <= original_buffer_range.start {
2853 tail = original_buffer_range.end;
2854 } else {
2855 tail = original_buffer_range.start;
2856 }
2857 }
2858 SelectMode::Line(original_range) => {
2859 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2860
2861 let position = display_map
2862 .clip_point(position, Bias::Left)
2863 .to_point(&display_map);
2864 let line_start = display_map.prev_line_boundary(position).0;
2865 let next_line_start = buffer.clip_point(
2866 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2867 Bias::Left,
2868 );
2869
2870 if line_start < original_range.start {
2871 head = line_start
2872 } else {
2873 head = next_line_start
2874 }
2875
2876 if head <= original_range.start {
2877 tail = original_range.end;
2878 } else {
2879 tail = original_range.start;
2880 }
2881 }
2882 SelectMode::All => {
2883 return;
2884 }
2885 };
2886
2887 if head < tail {
2888 pending.start = buffer.anchor_before(head);
2889 pending.end = buffer.anchor_before(tail);
2890 pending.reversed = true;
2891 } else {
2892 pending.start = buffer.anchor_before(tail);
2893 pending.end = buffer.anchor_before(head);
2894 pending.reversed = false;
2895 }
2896
2897 self.change_selections(None, cx, |s| {
2898 s.set_pending(pending, mode);
2899 });
2900 } else {
2901 log::error!("update_selection dispatched with no pending selection");
2902 return;
2903 }
2904
2905 self.apply_scroll_delta(scroll_delta, cx);
2906 cx.notify();
2907 }
2908
2909 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2910 self.columnar_selection_tail.take();
2911 if self.selections.pending_anchor().is_some() {
2912 let selections = self.selections.all::<usize>(cx);
2913 self.change_selections(None, cx, |s| {
2914 s.select(selections);
2915 s.clear_pending();
2916 });
2917 }
2918 }
2919
2920 fn select_columns(
2921 &mut self,
2922 tail: DisplayPoint,
2923 head: DisplayPoint,
2924 goal_column: u32,
2925 display_map: &DisplaySnapshot,
2926 cx: &mut ViewContext<Self>,
2927 ) {
2928 let start_row = cmp::min(tail.row(), head.row());
2929 let end_row = cmp::max(tail.row(), head.row());
2930 let start_column = cmp::min(tail.column(), goal_column);
2931 let end_column = cmp::max(tail.column(), goal_column);
2932 let reversed = start_column < tail.column();
2933
2934 let selection_ranges = (start_row.0..=end_row.0)
2935 .map(DisplayRow)
2936 .filter_map(|row| {
2937 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2938 let start = display_map
2939 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2940 .to_point(display_map);
2941 let end = display_map
2942 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2943 .to_point(display_map);
2944 if reversed {
2945 Some(end..start)
2946 } else {
2947 Some(start..end)
2948 }
2949 } else {
2950 None
2951 }
2952 })
2953 .collect::<Vec<_>>();
2954
2955 self.change_selections(None, cx, |s| {
2956 s.select_ranges(selection_ranges);
2957 });
2958 cx.notify();
2959 }
2960
2961 pub fn has_pending_nonempty_selection(&self) -> bool {
2962 let pending_nonempty_selection = match self.selections.pending_anchor() {
2963 Some(Selection { start, end, .. }) => start != end,
2964 None => false,
2965 };
2966
2967 pending_nonempty_selection
2968 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2969 }
2970
2971 pub fn has_pending_selection(&self) -> bool {
2972 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2973 }
2974
2975 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2976 if self.clear_clicked_diff_hunks(cx) {
2977 cx.notify();
2978 return;
2979 }
2980 if self.dismiss_menus_and_popups(true, cx) {
2981 return;
2982 }
2983
2984 if self.mode == EditorMode::Full {
2985 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2986 return;
2987 }
2988 }
2989
2990 cx.propagate();
2991 }
2992
2993 pub fn dismiss_menus_and_popups(
2994 &mut self,
2995 should_report_inline_completion_event: bool,
2996 cx: &mut ViewContext<Self>,
2997 ) -> bool {
2998 if self.take_rename(false, cx).is_some() {
2999 return true;
3000 }
3001
3002 if hide_hover(self, cx) {
3003 return true;
3004 }
3005
3006 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3007 return true;
3008 }
3009
3010 if self.hide_context_menu(cx).is_some() {
3011 return true;
3012 }
3013
3014 if self.mouse_context_menu.take().is_some() {
3015 return true;
3016 }
3017
3018 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3019 return true;
3020 }
3021
3022 if self.snippet_stack.pop().is_some() {
3023 return true;
3024 }
3025
3026 if self.mode == EditorMode::Full {
3027 if self.active_diagnostics.is_some() {
3028 self.dismiss_diagnostics(cx);
3029 return true;
3030 }
3031 }
3032
3033 false
3034 }
3035
3036 fn linked_editing_ranges_for(
3037 &self,
3038 selection: Range<text::Anchor>,
3039 cx: &AppContext,
3040 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3041 if self.linked_edit_ranges.is_empty() {
3042 return None;
3043 }
3044 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3045 selection.end.buffer_id.and_then(|end_buffer_id| {
3046 if selection.start.buffer_id != Some(end_buffer_id) {
3047 return None;
3048 }
3049 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3050 let snapshot = buffer.read(cx).snapshot();
3051 self.linked_edit_ranges
3052 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3053 .map(|ranges| (ranges, snapshot, buffer))
3054 })?;
3055 use text::ToOffset as TO;
3056 // find offset from the start of current range to current cursor position
3057 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3058
3059 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3060 let start_difference = start_offset - start_byte_offset;
3061 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3062 let end_difference = end_offset - start_byte_offset;
3063 // Current range has associated linked ranges.
3064 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3065 for range in linked_ranges.iter() {
3066 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3067 let end_offset = start_offset + end_difference;
3068 let start_offset = start_offset + start_difference;
3069 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3070 continue;
3071 }
3072 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3073 if s.start.buffer_id != selection.start.buffer_id
3074 || s.end.buffer_id != selection.end.buffer_id
3075 {
3076 return false;
3077 }
3078 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3079 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3080 }) {
3081 continue;
3082 }
3083 let start = buffer_snapshot.anchor_after(start_offset);
3084 let end = buffer_snapshot.anchor_after(end_offset);
3085 linked_edits
3086 .entry(buffer.clone())
3087 .or_default()
3088 .push(start..end);
3089 }
3090 Some(linked_edits)
3091 }
3092
3093 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3094 let text: Arc<str> = text.into();
3095
3096 if self.read_only(cx) {
3097 return;
3098 }
3099
3100 let selections = self.selections.all_adjusted(cx);
3101 let mut bracket_inserted = false;
3102 let mut edits = Vec::new();
3103 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3104 let mut new_selections = Vec::with_capacity(selections.len());
3105 let mut new_autoclose_regions = Vec::new();
3106 let snapshot = self.buffer.read(cx).read(cx);
3107
3108 for (selection, autoclose_region) in
3109 self.selections_with_autoclose_regions(selections, &snapshot)
3110 {
3111 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3112 // Determine if the inserted text matches the opening or closing
3113 // bracket of any of this language's bracket pairs.
3114 let mut bracket_pair = None;
3115 let mut is_bracket_pair_start = false;
3116 let mut is_bracket_pair_end = false;
3117 if !text.is_empty() {
3118 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3119 // and they are removing the character that triggered IME popup.
3120 for (pair, enabled) in scope.brackets() {
3121 if !pair.close && !pair.surround {
3122 continue;
3123 }
3124
3125 if enabled && pair.start.ends_with(text.as_ref()) {
3126 bracket_pair = Some(pair.clone());
3127 is_bracket_pair_start = true;
3128 break;
3129 }
3130 if pair.end.as_str() == text.as_ref() {
3131 bracket_pair = Some(pair.clone());
3132 is_bracket_pair_end = true;
3133 break;
3134 }
3135 }
3136 }
3137
3138 if let Some(bracket_pair) = bracket_pair {
3139 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3140 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3141 let auto_surround =
3142 self.use_auto_surround && snapshot_settings.use_auto_surround;
3143 if selection.is_empty() {
3144 if is_bracket_pair_start {
3145 let prefix_len = bracket_pair.start.len() - text.len();
3146
3147 // If the inserted text is a suffix of an opening bracket and the
3148 // selection is preceded by the rest of the opening bracket, then
3149 // insert the closing bracket.
3150 let following_text_allows_autoclose = snapshot
3151 .chars_at(selection.start)
3152 .next()
3153 .map_or(true, |c| scope.should_autoclose_before(c));
3154 let preceding_text_matches_prefix = prefix_len == 0
3155 || (selection.start.column >= (prefix_len as u32)
3156 && snapshot.contains_str_at(
3157 Point::new(
3158 selection.start.row,
3159 selection.start.column - (prefix_len as u32),
3160 ),
3161 &bracket_pair.start[..prefix_len],
3162 ));
3163
3164 if autoclose
3165 && bracket_pair.close
3166 && following_text_allows_autoclose
3167 && preceding_text_matches_prefix
3168 {
3169 let anchor = snapshot.anchor_before(selection.end);
3170 new_selections.push((selection.map(|_| anchor), text.len()));
3171 new_autoclose_regions.push((
3172 anchor,
3173 text.len(),
3174 selection.id,
3175 bracket_pair.clone(),
3176 ));
3177 edits.push((
3178 selection.range(),
3179 format!("{}{}", text, bracket_pair.end).into(),
3180 ));
3181 bracket_inserted = true;
3182 continue;
3183 }
3184 }
3185
3186 if let Some(region) = autoclose_region {
3187 // If the selection is followed by an auto-inserted closing bracket,
3188 // then don't insert that closing bracket again; just move the selection
3189 // past the closing bracket.
3190 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3191 && text.as_ref() == region.pair.end.as_str();
3192 if should_skip {
3193 let anchor = snapshot.anchor_after(selection.end);
3194 new_selections
3195 .push((selection.map(|_| anchor), region.pair.end.len()));
3196 continue;
3197 }
3198 }
3199
3200 let always_treat_brackets_as_autoclosed = snapshot
3201 .settings_at(selection.start, cx)
3202 .always_treat_brackets_as_autoclosed;
3203 if always_treat_brackets_as_autoclosed
3204 && is_bracket_pair_end
3205 && snapshot.contains_str_at(selection.end, text.as_ref())
3206 {
3207 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3208 // and the inserted text is a closing bracket and the selection is followed
3209 // by the closing bracket then move the selection past the closing bracket.
3210 let anchor = snapshot.anchor_after(selection.end);
3211 new_selections.push((selection.map(|_| anchor), text.len()));
3212 continue;
3213 }
3214 }
3215 // If an opening bracket is 1 character long and is typed while
3216 // text is selected, then surround that text with the bracket pair.
3217 else if auto_surround
3218 && bracket_pair.surround
3219 && is_bracket_pair_start
3220 && bracket_pair.start.chars().count() == 1
3221 {
3222 edits.push((selection.start..selection.start, text.clone()));
3223 edits.push((
3224 selection.end..selection.end,
3225 bracket_pair.end.as_str().into(),
3226 ));
3227 bracket_inserted = true;
3228 new_selections.push((
3229 Selection {
3230 id: selection.id,
3231 start: snapshot.anchor_after(selection.start),
3232 end: snapshot.anchor_before(selection.end),
3233 reversed: selection.reversed,
3234 goal: selection.goal,
3235 },
3236 0,
3237 ));
3238 continue;
3239 }
3240 }
3241 }
3242
3243 if self.auto_replace_emoji_shortcode
3244 && selection.is_empty()
3245 && text.as_ref().ends_with(':')
3246 {
3247 if let Some(possible_emoji_short_code) =
3248 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3249 {
3250 if !possible_emoji_short_code.is_empty() {
3251 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3252 let emoji_shortcode_start = Point::new(
3253 selection.start.row,
3254 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3255 );
3256
3257 // Remove shortcode from buffer
3258 edits.push((
3259 emoji_shortcode_start..selection.start,
3260 "".to_string().into(),
3261 ));
3262 new_selections.push((
3263 Selection {
3264 id: selection.id,
3265 start: snapshot.anchor_after(emoji_shortcode_start),
3266 end: snapshot.anchor_before(selection.start),
3267 reversed: selection.reversed,
3268 goal: selection.goal,
3269 },
3270 0,
3271 ));
3272
3273 // Insert emoji
3274 let selection_start_anchor = snapshot.anchor_after(selection.start);
3275 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3276 edits.push((selection.start..selection.end, emoji.to_string().into()));
3277
3278 continue;
3279 }
3280 }
3281 }
3282 }
3283
3284 // If not handling any auto-close operation, then just replace the selected
3285 // text with the given input and move the selection to the end of the
3286 // newly inserted text.
3287 let anchor = snapshot.anchor_after(selection.end);
3288 if !self.linked_edit_ranges.is_empty() {
3289 let start_anchor = snapshot.anchor_before(selection.start);
3290
3291 let is_word_char = text.chars().next().map_or(true, |char| {
3292 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3293 classifier.is_word(char)
3294 });
3295
3296 if is_word_char {
3297 if let Some(ranges) = self
3298 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3299 {
3300 for (buffer, edits) in ranges {
3301 linked_edits
3302 .entry(buffer.clone())
3303 .or_default()
3304 .extend(edits.into_iter().map(|range| (range, text.clone())));
3305 }
3306 }
3307 }
3308 }
3309
3310 new_selections.push((selection.map(|_| anchor), 0));
3311 edits.push((selection.start..selection.end, text.clone()));
3312 }
3313
3314 drop(snapshot);
3315
3316 self.transact(cx, |this, cx| {
3317 this.buffer.update(cx, |buffer, cx| {
3318 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3319 });
3320 for (buffer, edits) in linked_edits {
3321 buffer.update(cx, |buffer, cx| {
3322 let snapshot = buffer.snapshot();
3323 let edits = edits
3324 .into_iter()
3325 .map(|(range, text)| {
3326 use text::ToPoint as TP;
3327 let end_point = TP::to_point(&range.end, &snapshot);
3328 let start_point = TP::to_point(&range.start, &snapshot);
3329 (start_point..end_point, text)
3330 })
3331 .sorted_by_key(|(range, _)| range.start)
3332 .collect::<Vec<_>>();
3333 buffer.edit(edits, None, cx);
3334 })
3335 }
3336 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3337 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3338 let snapshot = this.buffer.read(cx).read(cx);
3339 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3340 .zip(new_selection_deltas)
3341 .map(|(selection, delta)| Selection {
3342 id: selection.id,
3343 start: selection.start + delta,
3344 end: selection.end + delta,
3345 reversed: selection.reversed,
3346 goal: SelectionGoal::None,
3347 })
3348 .collect::<Vec<_>>();
3349
3350 let mut i = 0;
3351 for (position, delta, selection_id, pair) in new_autoclose_regions {
3352 let position = position.to_offset(&snapshot) + delta;
3353 let start = snapshot.anchor_before(position);
3354 let end = snapshot.anchor_after(position);
3355 while let Some(existing_state) = this.autoclose_regions.get(i) {
3356 match existing_state.range.start.cmp(&start, &snapshot) {
3357 Ordering::Less => i += 1,
3358 Ordering::Greater => break,
3359 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3360 Ordering::Less => i += 1,
3361 Ordering::Equal => break,
3362 Ordering::Greater => break,
3363 },
3364 }
3365 }
3366 this.autoclose_regions.insert(
3367 i,
3368 AutocloseRegion {
3369 selection_id,
3370 range: start..end,
3371 pair,
3372 },
3373 );
3374 }
3375
3376 drop(snapshot);
3377 let had_active_inline_completion = this.has_active_inline_completion(cx);
3378 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3379 s.select(new_selections)
3380 });
3381
3382 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3383 if let Some(on_type_format_task) =
3384 this.trigger_on_type_formatting(text.to_string(), cx)
3385 {
3386 on_type_format_task.detach_and_log_err(cx);
3387 }
3388 }
3389
3390 let editor_settings = EditorSettings::get_global(cx);
3391 if bracket_inserted
3392 && (editor_settings.auto_signature_help
3393 || editor_settings.show_signature_help_after_edits)
3394 {
3395 this.show_signature_help(&ShowSignatureHelp, cx);
3396 }
3397
3398 let trigger_in_words = !had_active_inline_completion;
3399 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3400 linked_editing_ranges::refresh_linked_ranges(this, cx);
3401 this.refresh_inline_completion(true, false, cx);
3402 });
3403 }
3404
3405 fn find_possible_emoji_shortcode_at_position(
3406 snapshot: &MultiBufferSnapshot,
3407 position: Point,
3408 ) -> Option<String> {
3409 let mut chars = Vec::new();
3410 let mut found_colon = false;
3411 for char in snapshot.reversed_chars_at(position).take(100) {
3412 // Found a possible emoji shortcode in the middle of the buffer
3413 if found_colon {
3414 if char.is_whitespace() {
3415 chars.reverse();
3416 return Some(chars.iter().collect());
3417 }
3418 // If the previous character is not a whitespace, we are in the middle of a word
3419 // and we only want to complete the shortcode if the word is made up of other emojis
3420 let mut containing_word = String::new();
3421 for ch in snapshot
3422 .reversed_chars_at(position)
3423 .skip(chars.len() + 1)
3424 .take(100)
3425 {
3426 if ch.is_whitespace() {
3427 break;
3428 }
3429 containing_word.push(ch);
3430 }
3431 let containing_word = containing_word.chars().rev().collect::<String>();
3432 if util::word_consists_of_emojis(containing_word.as_str()) {
3433 chars.reverse();
3434 return Some(chars.iter().collect());
3435 }
3436 }
3437
3438 if char.is_whitespace() || !char.is_ascii() {
3439 return None;
3440 }
3441 if char == ':' {
3442 found_colon = true;
3443 } else {
3444 chars.push(char);
3445 }
3446 }
3447 // Found a possible emoji shortcode at the beginning of the buffer
3448 chars.reverse();
3449 Some(chars.iter().collect())
3450 }
3451
3452 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3453 self.transact(cx, |this, cx| {
3454 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3455 let selections = this.selections.all::<usize>(cx);
3456 let multi_buffer = this.buffer.read(cx);
3457 let buffer = multi_buffer.snapshot(cx);
3458 selections
3459 .iter()
3460 .map(|selection| {
3461 let start_point = selection.start.to_point(&buffer);
3462 let mut indent =
3463 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3464 indent.len = cmp::min(indent.len, start_point.column);
3465 let start = selection.start;
3466 let end = selection.end;
3467 let selection_is_empty = start == end;
3468 let language_scope = buffer.language_scope_at(start);
3469 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3470 &language_scope
3471 {
3472 let leading_whitespace_len = buffer
3473 .reversed_chars_at(start)
3474 .take_while(|c| c.is_whitespace() && *c != '\n')
3475 .map(|c| c.len_utf8())
3476 .sum::<usize>();
3477
3478 let trailing_whitespace_len = buffer
3479 .chars_at(end)
3480 .take_while(|c| c.is_whitespace() && *c != '\n')
3481 .map(|c| c.len_utf8())
3482 .sum::<usize>();
3483
3484 let insert_extra_newline =
3485 language.brackets().any(|(pair, enabled)| {
3486 let pair_start = pair.start.trim_end();
3487 let pair_end = pair.end.trim_start();
3488
3489 enabled
3490 && pair.newline
3491 && buffer.contains_str_at(
3492 end + trailing_whitespace_len,
3493 pair_end,
3494 )
3495 && buffer.contains_str_at(
3496 (start - leading_whitespace_len)
3497 .saturating_sub(pair_start.len()),
3498 pair_start,
3499 )
3500 });
3501
3502 // Comment extension on newline is allowed only for cursor selections
3503 let comment_delimiter = maybe!({
3504 if !selection_is_empty {
3505 return None;
3506 }
3507
3508 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3509 return None;
3510 }
3511
3512 let delimiters = language.line_comment_prefixes();
3513 let max_len_of_delimiter =
3514 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3515 let (snapshot, range) =
3516 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3517
3518 let mut index_of_first_non_whitespace = 0;
3519 let comment_candidate = snapshot
3520 .chars_for_range(range)
3521 .skip_while(|c| {
3522 let should_skip = c.is_whitespace();
3523 if should_skip {
3524 index_of_first_non_whitespace += 1;
3525 }
3526 should_skip
3527 })
3528 .take(max_len_of_delimiter)
3529 .collect::<String>();
3530 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3531 comment_candidate.starts_with(comment_prefix.as_ref())
3532 })?;
3533 let cursor_is_placed_after_comment_marker =
3534 index_of_first_non_whitespace + comment_prefix.len()
3535 <= start_point.column as usize;
3536 if cursor_is_placed_after_comment_marker {
3537 Some(comment_prefix.clone())
3538 } else {
3539 None
3540 }
3541 });
3542 (comment_delimiter, insert_extra_newline)
3543 } else {
3544 (None, false)
3545 };
3546
3547 let capacity_for_delimiter = comment_delimiter
3548 .as_deref()
3549 .map(str::len)
3550 .unwrap_or_default();
3551 let mut new_text =
3552 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3553 new_text.push_str("\n");
3554 new_text.extend(indent.chars());
3555 if let Some(delimiter) = &comment_delimiter {
3556 new_text.push_str(&delimiter);
3557 }
3558 if insert_extra_newline {
3559 new_text = new_text.repeat(2);
3560 }
3561
3562 let anchor = buffer.anchor_after(end);
3563 let new_selection = selection.map(|_| anchor);
3564 (
3565 (start..end, new_text),
3566 (insert_extra_newline, new_selection),
3567 )
3568 })
3569 .unzip()
3570 };
3571
3572 this.edit_with_autoindent(edits, cx);
3573 let buffer = this.buffer.read(cx).snapshot(cx);
3574 let new_selections = selection_fixup_info
3575 .into_iter()
3576 .map(|(extra_newline_inserted, new_selection)| {
3577 let mut cursor = new_selection.end.to_point(&buffer);
3578 if extra_newline_inserted {
3579 cursor.row -= 1;
3580 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3581 }
3582 new_selection.map(|_| cursor)
3583 })
3584 .collect();
3585
3586 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3587 this.refresh_inline_completion(true, false, cx);
3588 });
3589 }
3590
3591 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3592 let buffer = self.buffer.read(cx);
3593 let snapshot = buffer.snapshot(cx);
3594
3595 let mut edits = Vec::new();
3596 let mut rows = Vec::new();
3597
3598 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3599 let cursor = selection.head();
3600 let row = cursor.row;
3601
3602 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3603
3604 let newline = "\n".to_string();
3605 edits.push((start_of_line..start_of_line, newline));
3606
3607 rows.push(row + rows_inserted as u32);
3608 }
3609
3610 self.transact(cx, |editor, cx| {
3611 editor.edit(edits, cx);
3612
3613 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3614 let mut index = 0;
3615 s.move_cursors_with(|map, _, _| {
3616 let row = rows[index];
3617 index += 1;
3618
3619 let point = Point::new(row, 0);
3620 let boundary = map.next_line_boundary(point).1;
3621 let clipped = map.clip_point(boundary, Bias::Left);
3622
3623 (clipped, SelectionGoal::None)
3624 });
3625 });
3626
3627 let mut indent_edits = Vec::new();
3628 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3629 for row in rows {
3630 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3631 for (row, indent) in indents {
3632 if indent.len == 0 {
3633 continue;
3634 }
3635
3636 let text = match indent.kind {
3637 IndentKind::Space => " ".repeat(indent.len as usize),
3638 IndentKind::Tab => "\t".repeat(indent.len as usize),
3639 };
3640 let point = Point::new(row.0, 0);
3641 indent_edits.push((point..point, text));
3642 }
3643 }
3644 editor.edit(indent_edits, cx);
3645 });
3646 }
3647
3648 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3649 let buffer = self.buffer.read(cx);
3650 let snapshot = buffer.snapshot(cx);
3651
3652 let mut edits = Vec::new();
3653 let mut rows = Vec::new();
3654 let mut rows_inserted = 0;
3655
3656 for selection in self.selections.all_adjusted(cx) {
3657 let cursor = selection.head();
3658 let row = cursor.row;
3659
3660 let point = Point::new(row + 1, 0);
3661 let start_of_line = snapshot.clip_point(point, Bias::Left);
3662
3663 let newline = "\n".to_string();
3664 edits.push((start_of_line..start_of_line, newline));
3665
3666 rows_inserted += 1;
3667 rows.push(row + rows_inserted);
3668 }
3669
3670 self.transact(cx, |editor, cx| {
3671 editor.edit(edits, cx);
3672
3673 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3674 let mut index = 0;
3675 s.move_cursors_with(|map, _, _| {
3676 let row = rows[index];
3677 index += 1;
3678
3679 let point = Point::new(row, 0);
3680 let boundary = map.next_line_boundary(point).1;
3681 let clipped = map.clip_point(boundary, Bias::Left);
3682
3683 (clipped, SelectionGoal::None)
3684 });
3685 });
3686
3687 let mut indent_edits = Vec::new();
3688 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3689 for row in rows {
3690 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3691 for (row, indent) in indents {
3692 if indent.len == 0 {
3693 continue;
3694 }
3695
3696 let text = match indent.kind {
3697 IndentKind::Space => " ".repeat(indent.len as usize),
3698 IndentKind::Tab => "\t".repeat(indent.len as usize),
3699 };
3700 let point = Point::new(row.0, 0);
3701 indent_edits.push((point..point, text));
3702 }
3703 }
3704 editor.edit(indent_edits, cx);
3705 });
3706 }
3707
3708 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3709 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3710 original_indent_columns: Vec::new(),
3711 });
3712 self.insert_with_autoindent_mode(text, autoindent, cx);
3713 }
3714
3715 fn insert_with_autoindent_mode(
3716 &mut self,
3717 text: &str,
3718 autoindent_mode: Option<AutoindentMode>,
3719 cx: &mut ViewContext<Self>,
3720 ) {
3721 if self.read_only(cx) {
3722 return;
3723 }
3724
3725 let text: Arc<str> = text.into();
3726 self.transact(cx, |this, cx| {
3727 let old_selections = this.selections.all_adjusted(cx);
3728 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3729 let anchors = {
3730 let snapshot = buffer.read(cx);
3731 old_selections
3732 .iter()
3733 .map(|s| {
3734 let anchor = snapshot.anchor_after(s.head());
3735 s.map(|_| anchor)
3736 })
3737 .collect::<Vec<_>>()
3738 };
3739 buffer.edit(
3740 old_selections
3741 .iter()
3742 .map(|s| (s.start..s.end, text.clone())),
3743 autoindent_mode,
3744 cx,
3745 );
3746 anchors
3747 });
3748
3749 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3750 s.select_anchors(selection_anchors);
3751 })
3752 });
3753 }
3754
3755 fn trigger_completion_on_input(
3756 &mut self,
3757 text: &str,
3758 trigger_in_words: bool,
3759 cx: &mut ViewContext<Self>,
3760 ) {
3761 if self.is_completion_trigger(text, trigger_in_words, cx) {
3762 self.show_completions(
3763 &ShowCompletions {
3764 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3765 },
3766 cx,
3767 );
3768 } else {
3769 self.hide_context_menu(cx);
3770 }
3771 }
3772
3773 fn is_completion_trigger(
3774 &self,
3775 text: &str,
3776 trigger_in_words: bool,
3777 cx: &mut ViewContext<Self>,
3778 ) -> bool {
3779 let position = self.selections.newest_anchor().head();
3780 let multibuffer = self.buffer.read(cx);
3781 let Some(buffer) = position
3782 .buffer_id
3783 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3784 else {
3785 return false;
3786 };
3787
3788 if let Some(completion_provider) = &self.completion_provider {
3789 completion_provider.is_completion_trigger(
3790 &buffer,
3791 position.text_anchor,
3792 text,
3793 trigger_in_words,
3794 cx,
3795 )
3796 } else {
3797 false
3798 }
3799 }
3800
3801 /// If any empty selections is touching the start of its innermost containing autoclose
3802 /// region, expand it to select the brackets.
3803 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3804 let selections = self.selections.all::<usize>(cx);
3805 let buffer = self.buffer.read(cx).read(cx);
3806 let new_selections = self
3807 .selections_with_autoclose_regions(selections, &buffer)
3808 .map(|(mut selection, region)| {
3809 if !selection.is_empty() {
3810 return selection;
3811 }
3812
3813 if let Some(region) = region {
3814 let mut range = region.range.to_offset(&buffer);
3815 if selection.start == range.start && range.start >= region.pair.start.len() {
3816 range.start -= region.pair.start.len();
3817 if buffer.contains_str_at(range.start, ®ion.pair.start)
3818 && buffer.contains_str_at(range.end, ®ion.pair.end)
3819 {
3820 range.end += region.pair.end.len();
3821 selection.start = range.start;
3822 selection.end = range.end;
3823
3824 return selection;
3825 }
3826 }
3827 }
3828
3829 let always_treat_brackets_as_autoclosed = buffer
3830 .settings_at(selection.start, cx)
3831 .always_treat_brackets_as_autoclosed;
3832
3833 if !always_treat_brackets_as_autoclosed {
3834 return selection;
3835 }
3836
3837 if let Some(scope) = buffer.language_scope_at(selection.start) {
3838 for (pair, enabled) in scope.brackets() {
3839 if !enabled || !pair.close {
3840 continue;
3841 }
3842
3843 if buffer.contains_str_at(selection.start, &pair.end) {
3844 let pair_start_len = pair.start.len();
3845 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3846 {
3847 selection.start -= pair_start_len;
3848 selection.end += pair.end.len();
3849
3850 return selection;
3851 }
3852 }
3853 }
3854 }
3855
3856 selection
3857 })
3858 .collect();
3859
3860 drop(buffer);
3861 self.change_selections(None, cx, |selections| selections.select(new_selections));
3862 }
3863
3864 /// Iterate the given selections, and for each one, find the smallest surrounding
3865 /// autoclose region. This uses the ordering of the selections and the autoclose
3866 /// regions to avoid repeated comparisons.
3867 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3868 &'a self,
3869 selections: impl IntoIterator<Item = Selection<D>>,
3870 buffer: &'a MultiBufferSnapshot,
3871 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3872 let mut i = 0;
3873 let mut regions = self.autoclose_regions.as_slice();
3874 selections.into_iter().map(move |selection| {
3875 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3876
3877 let mut enclosing = None;
3878 while let Some(pair_state) = regions.get(i) {
3879 if pair_state.range.end.to_offset(buffer) < range.start {
3880 regions = ®ions[i + 1..];
3881 i = 0;
3882 } else if pair_state.range.start.to_offset(buffer) > range.end {
3883 break;
3884 } else {
3885 if pair_state.selection_id == selection.id {
3886 enclosing = Some(pair_state);
3887 }
3888 i += 1;
3889 }
3890 }
3891
3892 (selection.clone(), enclosing)
3893 })
3894 }
3895
3896 /// Remove any autoclose regions that no longer contain their selection.
3897 fn invalidate_autoclose_regions(
3898 &mut self,
3899 mut selections: &[Selection<Anchor>],
3900 buffer: &MultiBufferSnapshot,
3901 ) {
3902 self.autoclose_regions.retain(|state| {
3903 let mut i = 0;
3904 while let Some(selection) = selections.get(i) {
3905 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3906 selections = &selections[1..];
3907 continue;
3908 }
3909 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3910 break;
3911 }
3912 if selection.id == state.selection_id {
3913 return true;
3914 } else {
3915 i += 1;
3916 }
3917 }
3918 false
3919 });
3920 }
3921
3922 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3923 let offset = position.to_offset(buffer);
3924 let (word_range, kind) = buffer.surrounding_word(offset, true);
3925 if offset > word_range.start && kind == Some(CharKind::Word) {
3926 Some(
3927 buffer
3928 .text_for_range(word_range.start..offset)
3929 .collect::<String>(),
3930 )
3931 } else {
3932 None
3933 }
3934 }
3935
3936 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3937 self.refresh_inlay_hints(
3938 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3939 cx,
3940 );
3941 }
3942
3943 pub fn inlay_hints_enabled(&self) -> bool {
3944 self.inlay_hint_cache.enabled
3945 }
3946
3947 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3948 if self.project.is_none() || self.mode != EditorMode::Full {
3949 return;
3950 }
3951
3952 let reason_description = reason.description();
3953 let ignore_debounce = matches!(
3954 reason,
3955 InlayHintRefreshReason::SettingsChange(_)
3956 | InlayHintRefreshReason::Toggle(_)
3957 | InlayHintRefreshReason::ExcerptsRemoved(_)
3958 );
3959 let (invalidate_cache, required_languages) = match reason {
3960 InlayHintRefreshReason::Toggle(enabled) => {
3961 self.inlay_hint_cache.enabled = enabled;
3962 if enabled {
3963 (InvalidationStrategy::RefreshRequested, None)
3964 } else {
3965 self.inlay_hint_cache.clear();
3966 self.splice_inlays(
3967 self.visible_inlay_hints(cx)
3968 .iter()
3969 .map(|inlay| inlay.id)
3970 .collect(),
3971 Vec::new(),
3972 cx,
3973 );
3974 return;
3975 }
3976 }
3977 InlayHintRefreshReason::SettingsChange(new_settings) => {
3978 match self.inlay_hint_cache.update_settings(
3979 &self.buffer,
3980 new_settings,
3981 self.visible_inlay_hints(cx),
3982 cx,
3983 ) {
3984 ControlFlow::Break(Some(InlaySplice {
3985 to_remove,
3986 to_insert,
3987 })) => {
3988 self.splice_inlays(to_remove, to_insert, cx);
3989 return;
3990 }
3991 ControlFlow::Break(None) => return,
3992 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3993 }
3994 }
3995 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3996 if let Some(InlaySplice {
3997 to_remove,
3998 to_insert,
3999 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4000 {
4001 self.splice_inlays(to_remove, to_insert, cx);
4002 }
4003 return;
4004 }
4005 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4006 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4007 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4008 }
4009 InlayHintRefreshReason::RefreshRequested => {
4010 (InvalidationStrategy::RefreshRequested, None)
4011 }
4012 };
4013
4014 if let Some(InlaySplice {
4015 to_remove,
4016 to_insert,
4017 }) = self.inlay_hint_cache.spawn_hint_refresh(
4018 reason_description,
4019 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4020 invalidate_cache,
4021 ignore_debounce,
4022 cx,
4023 ) {
4024 self.splice_inlays(to_remove, to_insert, cx);
4025 }
4026 }
4027
4028 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4029 self.display_map
4030 .read(cx)
4031 .current_inlays()
4032 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4033 .cloned()
4034 .collect()
4035 }
4036
4037 pub fn excerpts_for_inlay_hints_query(
4038 &self,
4039 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4040 cx: &mut ViewContext<Editor>,
4041 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4042 let Some(project) = self.project.as_ref() else {
4043 return HashMap::default();
4044 };
4045 let project = project.read(cx);
4046 let multi_buffer = self.buffer().read(cx);
4047 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4048 let multi_buffer_visible_start = self
4049 .scroll_manager
4050 .anchor()
4051 .anchor
4052 .to_point(&multi_buffer_snapshot);
4053 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4054 multi_buffer_visible_start
4055 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4056 Bias::Left,
4057 );
4058 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4059 multi_buffer
4060 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4061 .into_iter()
4062 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4063 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4064 let buffer = buffer_handle.read(cx);
4065 let buffer_file = project::File::from_dyn(buffer.file())?;
4066 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4067 let worktree_entry = buffer_worktree
4068 .read(cx)
4069 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4070 if worktree_entry.is_ignored {
4071 return None;
4072 }
4073
4074 let language = buffer.language()?;
4075 if let Some(restrict_to_languages) = restrict_to_languages {
4076 if !restrict_to_languages.contains(language) {
4077 return None;
4078 }
4079 }
4080 Some((
4081 excerpt_id,
4082 (
4083 buffer_handle,
4084 buffer.version().clone(),
4085 excerpt_visible_range,
4086 ),
4087 ))
4088 })
4089 .collect()
4090 }
4091
4092 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4093 TextLayoutDetails {
4094 text_system: cx.text_system().clone(),
4095 editor_style: self.style.clone().unwrap(),
4096 rem_size: cx.rem_size(),
4097 scroll_anchor: self.scroll_manager.anchor(),
4098 visible_rows: self.visible_line_count(),
4099 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4100 }
4101 }
4102
4103 fn splice_inlays(
4104 &self,
4105 to_remove: Vec<InlayId>,
4106 to_insert: Vec<Inlay>,
4107 cx: &mut ViewContext<Self>,
4108 ) {
4109 self.display_map.update(cx, |display_map, cx| {
4110 display_map.splice_inlays(to_remove, to_insert, cx);
4111 });
4112 cx.notify();
4113 }
4114
4115 fn trigger_on_type_formatting(
4116 &self,
4117 input: String,
4118 cx: &mut ViewContext<Self>,
4119 ) -> Option<Task<Result<()>>> {
4120 if input.len() != 1 {
4121 return None;
4122 }
4123
4124 let project = self.project.as_ref()?;
4125 let position = self.selections.newest_anchor().head();
4126 let (buffer, buffer_position) = self
4127 .buffer
4128 .read(cx)
4129 .text_anchor_for_position(position, cx)?;
4130
4131 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4132 // hence we do LSP request & edit on host side only — add formats to host's history.
4133 let push_to_lsp_host_history = true;
4134 // If this is not the host, append its history with new edits.
4135 let push_to_client_history = project.read(cx).is_via_collab();
4136
4137 let on_type_formatting = project.update(cx, |project, cx| {
4138 project.on_type_format(
4139 buffer.clone(),
4140 buffer_position,
4141 input,
4142 push_to_lsp_host_history,
4143 cx,
4144 )
4145 });
4146 Some(cx.spawn(|editor, mut cx| async move {
4147 if let Some(transaction) = on_type_formatting.await? {
4148 if push_to_client_history {
4149 buffer
4150 .update(&mut cx, |buffer, _| {
4151 buffer.push_transaction(transaction, Instant::now());
4152 })
4153 .ok();
4154 }
4155 editor.update(&mut cx, |editor, cx| {
4156 editor.refresh_document_highlights(cx);
4157 })?;
4158 }
4159 Ok(())
4160 }))
4161 }
4162
4163 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4164 if self.pending_rename.is_some() {
4165 return;
4166 }
4167
4168 let Some(provider) = self.completion_provider.as_ref() else {
4169 return;
4170 };
4171
4172 let position = self.selections.newest_anchor().head();
4173 let (buffer, buffer_position) =
4174 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4175 output
4176 } else {
4177 return;
4178 };
4179
4180 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4181 let is_followup_invoke = {
4182 let context_menu_state = self.context_menu.read();
4183 matches!(
4184 context_menu_state.deref(),
4185 Some(ContextMenu::Completions(_))
4186 )
4187 };
4188 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4189 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4190 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4191 CompletionTriggerKind::TRIGGER_CHARACTER
4192 }
4193
4194 _ => CompletionTriggerKind::INVOKED,
4195 };
4196 let completion_context = CompletionContext {
4197 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4198 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4199 Some(String::from(trigger))
4200 } else {
4201 None
4202 }
4203 }),
4204 trigger_kind,
4205 };
4206 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4207 let sort_completions = provider.sort_completions();
4208
4209 let id = post_inc(&mut self.next_completion_id);
4210 let task = cx.spawn(|this, mut cx| {
4211 async move {
4212 this.update(&mut cx, |this, _| {
4213 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4214 })?;
4215 let completions = completions.await.log_err();
4216 let menu = if let Some(completions) = completions {
4217 let mut menu = CompletionsMenu {
4218 id,
4219 sort_completions,
4220 initial_position: position,
4221 match_candidates: completions
4222 .iter()
4223 .enumerate()
4224 .map(|(id, completion)| {
4225 StringMatchCandidate::new(
4226 id,
4227 completion.label.text[completion.label.filter_range.clone()]
4228 .into(),
4229 )
4230 })
4231 .collect(),
4232 buffer: buffer.clone(),
4233 completions: Arc::new(RwLock::new(completions.into())),
4234 matches: Vec::new().into(),
4235 selected_item: 0,
4236 scroll_handle: UniformListScrollHandle::new(),
4237 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4238 DebouncedDelay::new(),
4239 )),
4240 };
4241 menu.filter(query.as_deref(), cx.background_executor().clone())
4242 .await;
4243
4244 if menu.matches.is_empty() {
4245 None
4246 } else {
4247 this.update(&mut cx, |editor, cx| {
4248 let completions = menu.completions.clone();
4249 let matches = menu.matches.clone();
4250
4251 let delay_ms = EditorSettings::get_global(cx)
4252 .completion_documentation_secondary_query_debounce;
4253 let delay = Duration::from_millis(delay_ms);
4254 editor
4255 .completion_documentation_pre_resolve_debounce
4256 .fire_new(delay, cx, |editor, cx| {
4257 CompletionsMenu::pre_resolve_completion_documentation(
4258 buffer,
4259 completions,
4260 matches,
4261 editor,
4262 cx,
4263 )
4264 });
4265 })
4266 .ok();
4267 Some(menu)
4268 }
4269 } else {
4270 None
4271 };
4272
4273 this.update(&mut cx, |this, cx| {
4274 let mut context_menu = this.context_menu.write();
4275 match context_menu.as_ref() {
4276 None => {}
4277
4278 Some(ContextMenu::Completions(prev_menu)) => {
4279 if prev_menu.id > id {
4280 return;
4281 }
4282 }
4283
4284 _ => return,
4285 }
4286
4287 if this.focus_handle.is_focused(cx) && menu.is_some() {
4288 let menu = menu.unwrap();
4289 *context_menu = Some(ContextMenu::Completions(menu));
4290 drop(context_menu);
4291 this.discard_inline_completion(false, cx);
4292 cx.notify();
4293 } else if this.completion_tasks.len() <= 1 {
4294 // If there are no more completion tasks and the last menu was
4295 // empty, we should hide it. If it was already hidden, we should
4296 // also show the copilot completion when available.
4297 drop(context_menu);
4298 if this.hide_context_menu(cx).is_none() {
4299 this.update_visible_inline_completion(cx);
4300 }
4301 }
4302 })?;
4303
4304 Ok::<_, anyhow::Error>(())
4305 }
4306 .log_err()
4307 });
4308
4309 self.completion_tasks.push((id, task));
4310 }
4311
4312 pub fn confirm_completion(
4313 &mut self,
4314 action: &ConfirmCompletion,
4315 cx: &mut ViewContext<Self>,
4316 ) -> Option<Task<Result<()>>> {
4317 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4318 }
4319
4320 pub fn compose_completion(
4321 &mut self,
4322 action: &ComposeCompletion,
4323 cx: &mut ViewContext<Self>,
4324 ) -> Option<Task<Result<()>>> {
4325 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4326 }
4327
4328 fn do_completion(
4329 &mut self,
4330 item_ix: Option<usize>,
4331 intent: CompletionIntent,
4332 cx: &mut ViewContext<Editor>,
4333 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4334 use language::ToOffset as _;
4335
4336 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4337 menu
4338 } else {
4339 return None;
4340 };
4341
4342 let mat = completions_menu
4343 .matches
4344 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4345 let buffer_handle = completions_menu.buffer;
4346 let completions = completions_menu.completions.read();
4347 let completion = completions.get(mat.candidate_id)?;
4348 cx.stop_propagation();
4349
4350 let snippet;
4351 let text;
4352
4353 if completion.is_snippet() {
4354 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4355 text = snippet.as_ref().unwrap().text.clone();
4356 } else {
4357 snippet = None;
4358 text = completion.new_text.clone();
4359 };
4360 let selections = self.selections.all::<usize>(cx);
4361 let buffer = buffer_handle.read(cx);
4362 let old_range = completion.old_range.to_offset(buffer);
4363 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4364
4365 let newest_selection = self.selections.newest_anchor();
4366 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4367 return None;
4368 }
4369
4370 let lookbehind = newest_selection
4371 .start
4372 .text_anchor
4373 .to_offset(buffer)
4374 .saturating_sub(old_range.start);
4375 let lookahead = old_range
4376 .end
4377 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4378 let mut common_prefix_len = old_text
4379 .bytes()
4380 .zip(text.bytes())
4381 .take_while(|(a, b)| a == b)
4382 .count();
4383
4384 let snapshot = self.buffer.read(cx).snapshot(cx);
4385 let mut range_to_replace: Option<Range<isize>> = None;
4386 let mut ranges = Vec::new();
4387 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4388 for selection in &selections {
4389 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4390 let start = selection.start.saturating_sub(lookbehind);
4391 let end = selection.end + lookahead;
4392 if selection.id == newest_selection.id {
4393 range_to_replace = Some(
4394 ((start + common_prefix_len) as isize - selection.start as isize)
4395 ..(end as isize - selection.start as isize),
4396 );
4397 }
4398 ranges.push(start + common_prefix_len..end);
4399 } else {
4400 common_prefix_len = 0;
4401 ranges.clear();
4402 ranges.extend(selections.iter().map(|s| {
4403 if s.id == newest_selection.id {
4404 range_to_replace = Some(
4405 old_range.start.to_offset_utf16(&snapshot).0 as isize
4406 - selection.start as isize
4407 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4408 - selection.start as isize,
4409 );
4410 old_range.clone()
4411 } else {
4412 s.start..s.end
4413 }
4414 }));
4415 break;
4416 }
4417 if !self.linked_edit_ranges.is_empty() {
4418 let start_anchor = snapshot.anchor_before(selection.head());
4419 let end_anchor = snapshot.anchor_after(selection.tail());
4420 if let Some(ranges) = self
4421 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4422 {
4423 for (buffer, edits) in ranges {
4424 linked_edits.entry(buffer.clone()).or_default().extend(
4425 edits
4426 .into_iter()
4427 .map(|range| (range, text[common_prefix_len..].to_owned())),
4428 );
4429 }
4430 }
4431 }
4432 }
4433 let text = &text[common_prefix_len..];
4434
4435 cx.emit(EditorEvent::InputHandled {
4436 utf16_range_to_replace: range_to_replace,
4437 text: text.into(),
4438 });
4439
4440 self.transact(cx, |this, cx| {
4441 if let Some(mut snippet) = snippet {
4442 snippet.text = text.to_string();
4443 for tabstop in snippet.tabstops.iter_mut().flatten() {
4444 tabstop.start -= common_prefix_len as isize;
4445 tabstop.end -= common_prefix_len as isize;
4446 }
4447
4448 this.insert_snippet(&ranges, snippet, cx).log_err();
4449 } else {
4450 this.buffer.update(cx, |buffer, cx| {
4451 buffer.edit(
4452 ranges.iter().map(|range| (range.clone(), text)),
4453 this.autoindent_mode.clone(),
4454 cx,
4455 );
4456 });
4457 }
4458 for (buffer, edits) in linked_edits {
4459 buffer.update(cx, |buffer, cx| {
4460 let snapshot = buffer.snapshot();
4461 let edits = edits
4462 .into_iter()
4463 .map(|(range, text)| {
4464 use text::ToPoint as TP;
4465 let end_point = TP::to_point(&range.end, &snapshot);
4466 let start_point = TP::to_point(&range.start, &snapshot);
4467 (start_point..end_point, text)
4468 })
4469 .sorted_by_key(|(range, _)| range.start)
4470 .collect::<Vec<_>>();
4471 buffer.edit(edits, None, cx);
4472 })
4473 }
4474
4475 this.refresh_inline_completion(true, false, cx);
4476 });
4477
4478 let show_new_completions_on_confirm = completion
4479 .confirm
4480 .as_ref()
4481 .map_or(false, |confirm| confirm(intent, cx));
4482 if show_new_completions_on_confirm {
4483 self.show_completions(&ShowCompletions { trigger: None }, cx);
4484 }
4485
4486 let provider = self.completion_provider.as_ref()?;
4487 let apply_edits = provider.apply_additional_edits_for_completion(
4488 buffer_handle,
4489 completion.clone(),
4490 true,
4491 cx,
4492 );
4493
4494 let editor_settings = EditorSettings::get_global(cx);
4495 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4496 // After the code completion is finished, users often want to know what signatures are needed.
4497 // so we should automatically call signature_help
4498 self.show_signature_help(&ShowSignatureHelp, cx);
4499 }
4500
4501 Some(cx.foreground_executor().spawn(async move {
4502 apply_edits.await?;
4503 Ok(())
4504 }))
4505 }
4506
4507 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4508 let mut context_menu = self.context_menu.write();
4509 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4510 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4511 // Toggle if we're selecting the same one
4512 *context_menu = None;
4513 cx.notify();
4514 return;
4515 } else {
4516 // Otherwise, clear it and start a new one
4517 *context_menu = None;
4518 cx.notify();
4519 }
4520 }
4521 drop(context_menu);
4522 let snapshot = self.snapshot(cx);
4523 let deployed_from_indicator = action.deployed_from_indicator;
4524 let mut task = self.code_actions_task.take();
4525 let action = action.clone();
4526 cx.spawn(|editor, mut cx| async move {
4527 while let Some(prev_task) = task {
4528 prev_task.await;
4529 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4530 }
4531
4532 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4533 if editor.focus_handle.is_focused(cx) {
4534 let multibuffer_point = action
4535 .deployed_from_indicator
4536 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4537 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4538 let (buffer, buffer_row) = snapshot
4539 .buffer_snapshot
4540 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4541 .and_then(|(buffer_snapshot, range)| {
4542 editor
4543 .buffer
4544 .read(cx)
4545 .buffer(buffer_snapshot.remote_id())
4546 .map(|buffer| (buffer, range.start.row))
4547 })?;
4548 let (_, code_actions) = editor
4549 .available_code_actions
4550 .clone()
4551 .and_then(|(location, code_actions)| {
4552 let snapshot = location.buffer.read(cx).snapshot();
4553 let point_range = location.range.to_point(&snapshot);
4554 let point_range = point_range.start.row..=point_range.end.row;
4555 if point_range.contains(&buffer_row) {
4556 Some((location, code_actions))
4557 } else {
4558 None
4559 }
4560 })
4561 .unzip();
4562 let buffer_id = buffer.read(cx).remote_id();
4563 let tasks = editor
4564 .tasks
4565 .get(&(buffer_id, buffer_row))
4566 .map(|t| Arc::new(t.to_owned()));
4567 if tasks.is_none() && code_actions.is_none() {
4568 return None;
4569 }
4570
4571 editor.completion_tasks.clear();
4572 editor.discard_inline_completion(false, cx);
4573 let task_context =
4574 tasks
4575 .as_ref()
4576 .zip(editor.project.clone())
4577 .map(|(tasks, project)| {
4578 let position = Point::new(buffer_row, tasks.column);
4579 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4580 let location = Location {
4581 buffer: buffer.clone(),
4582 range: range_start..range_start,
4583 };
4584 // Fill in the environmental variables from the tree-sitter captures
4585 let mut captured_task_variables = TaskVariables::default();
4586 for (capture_name, value) in tasks.extra_variables.clone() {
4587 captured_task_variables.insert(
4588 task::VariableName::Custom(capture_name.into()),
4589 value.clone(),
4590 );
4591 }
4592 project.update(cx, |project, cx| {
4593 project.task_context_for_location(
4594 captured_task_variables,
4595 location,
4596 cx,
4597 )
4598 })
4599 });
4600
4601 Some(cx.spawn(|editor, mut cx| async move {
4602 let task_context = match task_context {
4603 Some(task_context) => task_context.await,
4604 None => None,
4605 };
4606 let resolved_tasks =
4607 tasks.zip(task_context).map(|(tasks, task_context)| {
4608 Arc::new(ResolvedTasks {
4609 templates: tasks
4610 .templates
4611 .iter()
4612 .filter_map(|(kind, template)| {
4613 template
4614 .resolve_task(&kind.to_id_base(), &task_context)
4615 .map(|task| (kind.clone(), task))
4616 })
4617 .collect(),
4618 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4619 multibuffer_point.row,
4620 tasks.column,
4621 )),
4622 })
4623 });
4624 let spawn_straight_away = resolved_tasks
4625 .as_ref()
4626 .map_or(false, |tasks| tasks.templates.len() == 1)
4627 && code_actions
4628 .as_ref()
4629 .map_or(true, |actions| actions.is_empty());
4630 if let Some(task) = editor
4631 .update(&mut cx, |editor, cx| {
4632 *editor.context_menu.write() =
4633 Some(ContextMenu::CodeActions(CodeActionsMenu {
4634 buffer,
4635 actions: CodeActionContents {
4636 tasks: resolved_tasks,
4637 actions: code_actions,
4638 },
4639 selected_item: Default::default(),
4640 scroll_handle: UniformListScrollHandle::default(),
4641 deployed_from_indicator,
4642 }));
4643 if spawn_straight_away {
4644 if let Some(task) = editor.confirm_code_action(
4645 &ConfirmCodeAction { item_ix: Some(0) },
4646 cx,
4647 ) {
4648 cx.notify();
4649 return task;
4650 }
4651 }
4652 cx.notify();
4653 Task::ready(Ok(()))
4654 })
4655 .ok()
4656 {
4657 task.await
4658 } else {
4659 Ok(())
4660 }
4661 }))
4662 } else {
4663 Some(Task::ready(Ok(())))
4664 }
4665 })?;
4666 if let Some(task) = spawned_test_task {
4667 task.await?;
4668 }
4669
4670 Ok::<_, anyhow::Error>(())
4671 })
4672 .detach_and_log_err(cx);
4673 }
4674
4675 pub fn confirm_code_action(
4676 &mut self,
4677 action: &ConfirmCodeAction,
4678 cx: &mut ViewContext<Self>,
4679 ) -> Option<Task<Result<()>>> {
4680 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4681 menu
4682 } else {
4683 return None;
4684 };
4685 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4686 let action = actions_menu.actions.get(action_ix)?;
4687 let title = action.label();
4688 let buffer = actions_menu.buffer;
4689 let workspace = self.workspace()?;
4690
4691 match action {
4692 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4693 workspace.update(cx, |workspace, cx| {
4694 workspace::tasks::schedule_resolved_task(
4695 workspace,
4696 task_source_kind,
4697 resolved_task,
4698 false,
4699 cx,
4700 );
4701
4702 Some(Task::ready(Ok(())))
4703 })
4704 }
4705 CodeActionsItem::CodeAction(action) => {
4706 let apply_code_actions = workspace
4707 .read(cx)
4708 .project()
4709 .clone()
4710 .update(cx, |project, cx| {
4711 project.apply_code_action(buffer, action, true, cx)
4712 });
4713 let workspace = workspace.downgrade();
4714 Some(cx.spawn(|editor, cx| async move {
4715 let project_transaction = apply_code_actions.await?;
4716 Self::open_project_transaction(
4717 &editor,
4718 workspace,
4719 project_transaction,
4720 title,
4721 cx,
4722 )
4723 .await
4724 }))
4725 }
4726 }
4727 }
4728
4729 pub async fn open_project_transaction(
4730 this: &WeakView<Editor>,
4731 workspace: WeakView<Workspace>,
4732 transaction: ProjectTransaction,
4733 title: String,
4734 mut cx: AsyncWindowContext,
4735 ) -> Result<()> {
4736 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4737
4738 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4739 cx.update(|cx| {
4740 entries.sort_unstable_by_key(|(buffer, _)| {
4741 buffer.read(cx).file().map(|f| f.path().clone())
4742 });
4743 })?;
4744
4745 // If the project transaction's edits are all contained within this editor, then
4746 // avoid opening a new editor to display them.
4747
4748 if let Some((buffer, transaction)) = entries.first() {
4749 if entries.len() == 1 {
4750 let excerpt = this.update(&mut cx, |editor, cx| {
4751 editor
4752 .buffer()
4753 .read(cx)
4754 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4755 })?;
4756 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4757 if excerpted_buffer == *buffer {
4758 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4759 let excerpt_range = excerpt_range.to_offset(buffer);
4760 buffer
4761 .edited_ranges_for_transaction::<usize>(transaction)
4762 .all(|range| {
4763 excerpt_range.start <= range.start
4764 && excerpt_range.end >= range.end
4765 })
4766 })?;
4767
4768 if all_edits_within_excerpt {
4769 return Ok(());
4770 }
4771 }
4772 }
4773 }
4774 } else {
4775 return Ok(());
4776 }
4777
4778 let mut ranges_to_highlight = Vec::new();
4779 let excerpt_buffer = cx.new_model(|cx| {
4780 let mut multibuffer =
4781 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4782 for (buffer_handle, transaction) in &entries {
4783 let buffer = buffer_handle.read(cx);
4784 ranges_to_highlight.extend(
4785 multibuffer.push_excerpts_with_context_lines(
4786 buffer_handle.clone(),
4787 buffer
4788 .edited_ranges_for_transaction::<usize>(transaction)
4789 .collect(),
4790 DEFAULT_MULTIBUFFER_CONTEXT,
4791 cx,
4792 ),
4793 );
4794 }
4795 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4796 multibuffer
4797 })?;
4798
4799 workspace.update(&mut cx, |workspace, cx| {
4800 let project = workspace.project().clone();
4801 let editor =
4802 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4803 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4804 editor.update(cx, |editor, cx| {
4805 editor.highlight_background::<Self>(
4806 &ranges_to_highlight,
4807 |theme| theme.editor_highlighted_line_background,
4808 cx,
4809 );
4810 });
4811 })?;
4812
4813 Ok(())
4814 }
4815
4816 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4817 let project = self.project.clone()?;
4818 let buffer = self.buffer.read(cx);
4819 let newest_selection = self.selections.newest_anchor().clone();
4820 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4821 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4822 if start_buffer != end_buffer {
4823 return None;
4824 }
4825
4826 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4827 cx.background_executor()
4828 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4829 .await;
4830
4831 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4832 project.code_actions(&start_buffer, start..end, cx)
4833 }) {
4834 code_actions.await
4835 } else {
4836 Vec::new()
4837 };
4838
4839 this.update(&mut cx, |this, cx| {
4840 this.available_code_actions = if actions.is_empty() {
4841 None
4842 } else {
4843 Some((
4844 Location {
4845 buffer: start_buffer,
4846 range: start..end,
4847 },
4848 actions.into(),
4849 ))
4850 };
4851 cx.notify();
4852 })
4853 .log_err();
4854 }));
4855 None
4856 }
4857
4858 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4859 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4860 self.show_git_blame_inline = false;
4861
4862 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4863 cx.background_executor().timer(delay).await;
4864
4865 this.update(&mut cx, |this, cx| {
4866 this.show_git_blame_inline = true;
4867 cx.notify();
4868 })
4869 .log_err();
4870 }));
4871 }
4872 }
4873
4874 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4875 if self.pending_rename.is_some() {
4876 return None;
4877 }
4878
4879 let project = self.project.clone()?;
4880 let buffer = self.buffer.read(cx);
4881 let newest_selection = self.selections.newest_anchor().clone();
4882 let cursor_position = newest_selection.head();
4883 let (cursor_buffer, cursor_buffer_position) =
4884 buffer.text_anchor_for_position(cursor_position, cx)?;
4885 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4886 if cursor_buffer != tail_buffer {
4887 return None;
4888 }
4889
4890 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4891 cx.background_executor()
4892 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4893 .await;
4894
4895 let highlights = if let Some(highlights) = project
4896 .update(&mut cx, |project, cx| {
4897 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4898 })
4899 .log_err()
4900 {
4901 highlights.await.log_err()
4902 } else {
4903 None
4904 };
4905
4906 if let Some(highlights) = highlights {
4907 this.update(&mut cx, |this, cx| {
4908 if this.pending_rename.is_some() {
4909 return;
4910 }
4911
4912 let buffer_id = cursor_position.buffer_id;
4913 let buffer = this.buffer.read(cx);
4914 if !buffer
4915 .text_anchor_for_position(cursor_position, cx)
4916 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4917 {
4918 return;
4919 }
4920
4921 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4922 let mut write_ranges = Vec::new();
4923 let mut read_ranges = Vec::new();
4924 for highlight in highlights {
4925 for (excerpt_id, excerpt_range) in
4926 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4927 {
4928 let start = highlight
4929 .range
4930 .start
4931 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4932 let end = highlight
4933 .range
4934 .end
4935 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4936 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4937 continue;
4938 }
4939
4940 let range = Anchor {
4941 buffer_id,
4942 excerpt_id,
4943 text_anchor: start,
4944 }..Anchor {
4945 buffer_id,
4946 excerpt_id,
4947 text_anchor: end,
4948 };
4949 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4950 write_ranges.push(range);
4951 } else {
4952 read_ranges.push(range);
4953 }
4954 }
4955 }
4956
4957 this.highlight_background::<DocumentHighlightRead>(
4958 &read_ranges,
4959 |theme| theme.editor_document_highlight_read_background,
4960 cx,
4961 );
4962 this.highlight_background::<DocumentHighlightWrite>(
4963 &write_ranges,
4964 |theme| theme.editor_document_highlight_write_background,
4965 cx,
4966 );
4967 cx.notify();
4968 })
4969 .log_err();
4970 }
4971 }));
4972 None
4973 }
4974
4975 pub fn refresh_inline_completion(
4976 &mut self,
4977 debounce: bool,
4978 user_requested: bool,
4979 cx: &mut ViewContext<Self>,
4980 ) -> Option<()> {
4981 let provider = self.inline_completion_provider()?;
4982 let cursor = self.selections.newest_anchor().head();
4983 let (buffer, cursor_buffer_position) =
4984 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4985 if !user_requested
4986 && self.enable_inline_completions
4987 && !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4988 {
4989 self.discard_inline_completion(false, cx);
4990 return None;
4991 }
4992
4993 self.update_visible_inline_completion(cx);
4994 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4995 Some(())
4996 }
4997
4998 fn cycle_inline_completion(
4999 &mut self,
5000 direction: Direction,
5001 cx: &mut ViewContext<Self>,
5002 ) -> Option<()> {
5003 let provider = self.inline_completion_provider()?;
5004 let cursor = self.selections.newest_anchor().head();
5005 let (buffer, cursor_buffer_position) =
5006 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5007 if !self.enable_inline_completions
5008 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5009 {
5010 return None;
5011 }
5012
5013 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5014 self.update_visible_inline_completion(cx);
5015
5016 Some(())
5017 }
5018
5019 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5020 if !self.has_active_inline_completion(cx) {
5021 self.refresh_inline_completion(false, true, cx);
5022 return;
5023 }
5024
5025 self.update_visible_inline_completion(cx);
5026 }
5027
5028 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5029 self.show_cursor_names(cx);
5030 }
5031
5032 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5033 self.show_cursor_names = true;
5034 cx.notify();
5035 cx.spawn(|this, mut cx| async move {
5036 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5037 this.update(&mut cx, |this, cx| {
5038 this.show_cursor_names = false;
5039 cx.notify()
5040 })
5041 .ok()
5042 })
5043 .detach();
5044 }
5045
5046 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5047 if self.has_active_inline_completion(cx) {
5048 self.cycle_inline_completion(Direction::Next, cx);
5049 } else {
5050 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5051 if is_copilot_disabled {
5052 cx.propagate();
5053 }
5054 }
5055 }
5056
5057 pub fn previous_inline_completion(
5058 &mut self,
5059 _: &PreviousInlineCompletion,
5060 cx: &mut ViewContext<Self>,
5061 ) {
5062 if self.has_active_inline_completion(cx) {
5063 self.cycle_inline_completion(Direction::Prev, cx);
5064 } else {
5065 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5066 if is_copilot_disabled {
5067 cx.propagate();
5068 }
5069 }
5070 }
5071
5072 pub fn accept_inline_completion(
5073 &mut self,
5074 _: &AcceptInlineCompletion,
5075 cx: &mut ViewContext<Self>,
5076 ) {
5077 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5078 return;
5079 };
5080 if let Some(provider) = self.inline_completion_provider() {
5081 provider.accept(cx);
5082 }
5083
5084 cx.emit(EditorEvent::InputHandled {
5085 utf16_range_to_replace: None,
5086 text: completion.text.to_string().into(),
5087 });
5088
5089 if let Some(range) = delete_range {
5090 self.change_selections(None, cx, |s| s.select_ranges([range]))
5091 }
5092 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5093 self.refresh_inline_completion(true, true, cx);
5094 cx.notify();
5095 }
5096
5097 pub fn accept_partial_inline_completion(
5098 &mut self,
5099 _: &AcceptPartialInlineCompletion,
5100 cx: &mut ViewContext<Self>,
5101 ) {
5102 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5103 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5104 let mut partial_completion = completion
5105 .text
5106 .chars()
5107 .by_ref()
5108 .take_while(|c| c.is_alphabetic())
5109 .collect::<String>();
5110 if partial_completion.is_empty() {
5111 partial_completion = completion
5112 .text
5113 .chars()
5114 .by_ref()
5115 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5116 .collect::<String>();
5117 }
5118
5119 cx.emit(EditorEvent::InputHandled {
5120 utf16_range_to_replace: None,
5121 text: partial_completion.clone().into(),
5122 });
5123
5124 if let Some(range) = delete_range {
5125 self.change_selections(None, cx, |s| s.select_ranges([range]))
5126 }
5127 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5128
5129 self.refresh_inline_completion(true, true, cx);
5130 cx.notify();
5131 }
5132 }
5133 }
5134
5135 fn discard_inline_completion(
5136 &mut self,
5137 should_report_inline_completion_event: bool,
5138 cx: &mut ViewContext<Self>,
5139 ) -> bool {
5140 if let Some(provider) = self.inline_completion_provider() {
5141 provider.discard(should_report_inline_completion_event, cx);
5142 }
5143
5144 self.take_active_inline_completion(cx).is_some()
5145 }
5146
5147 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5148 if let Some(completion) = self.active_inline_completion.as_ref() {
5149 let buffer = self.buffer.read(cx).read(cx);
5150 completion.0.position.is_valid(&buffer)
5151 } else {
5152 false
5153 }
5154 }
5155
5156 fn take_active_inline_completion(
5157 &mut self,
5158 cx: &mut ViewContext<Self>,
5159 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5160 let completion = self.active_inline_completion.take()?;
5161 self.display_map.update(cx, |map, cx| {
5162 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5163 });
5164 let buffer = self.buffer.read(cx).read(cx);
5165
5166 if completion.0.position.is_valid(&buffer) {
5167 Some(completion)
5168 } else {
5169 None
5170 }
5171 }
5172
5173 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5174 let selection = self.selections.newest_anchor();
5175 let cursor = selection.head();
5176
5177 let excerpt_id = cursor.excerpt_id;
5178
5179 if self.context_menu.read().is_none()
5180 && self.completion_tasks.is_empty()
5181 && selection.start == selection.end
5182 {
5183 if let Some(provider) = self.inline_completion_provider() {
5184 if let Some((buffer, cursor_buffer_position)) =
5185 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5186 {
5187 if let Some((text, text_anchor_range)) =
5188 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5189 {
5190 let text = Rope::from(text);
5191 let mut to_remove = Vec::new();
5192 if let Some(completion) = self.active_inline_completion.take() {
5193 to_remove.push(completion.0.id);
5194 }
5195
5196 let completion_inlay =
5197 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5198
5199 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5200 let snapshot = self.buffer.read(cx).snapshot(cx);
5201 Some(
5202 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5203 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5204 )
5205 });
5206 self.active_inline_completion =
5207 Some((completion_inlay.clone(), multibuffer_anchor_range));
5208
5209 self.display_map.update(cx, move |map, cx| {
5210 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5211 });
5212 cx.notify();
5213 return;
5214 }
5215 }
5216 }
5217 }
5218
5219 self.discard_inline_completion(false, cx);
5220 }
5221
5222 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5223 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5224 }
5225
5226 fn render_code_actions_indicator(
5227 &self,
5228 _style: &EditorStyle,
5229 row: DisplayRow,
5230 is_active: bool,
5231 cx: &mut ViewContext<Self>,
5232 ) -> Option<IconButton> {
5233 if self.available_code_actions.is_some() {
5234 Some(
5235 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5236 .shape(ui::IconButtonShape::Square)
5237 .icon_size(IconSize::XSmall)
5238 .icon_color(Color::Muted)
5239 .selected(is_active)
5240 .on_click(cx.listener(move |editor, _e, cx| {
5241 editor.focus(cx);
5242 editor.toggle_code_actions(
5243 &ToggleCodeActions {
5244 deployed_from_indicator: Some(row),
5245 },
5246 cx,
5247 );
5248 })),
5249 )
5250 } else {
5251 None
5252 }
5253 }
5254
5255 fn clear_tasks(&mut self) {
5256 self.tasks.clear()
5257 }
5258
5259 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5260 if let Some(_) = self.tasks.insert(key, value) {
5261 // This case should hopefully be rare, but just in case...
5262 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5263 }
5264 }
5265
5266 fn render_run_indicator(
5267 &self,
5268 _style: &EditorStyle,
5269 is_active: bool,
5270 row: DisplayRow,
5271 cx: &mut ViewContext<Self>,
5272 ) -> IconButton {
5273 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5274 .shape(ui::IconButtonShape::Square)
5275 .icon_size(IconSize::XSmall)
5276 .icon_color(Color::Muted)
5277 .selected(is_active)
5278 .on_click(cx.listener(move |editor, _e, cx| {
5279 editor.focus(cx);
5280 editor.toggle_code_actions(
5281 &ToggleCodeActions {
5282 deployed_from_indicator: Some(row),
5283 },
5284 cx,
5285 );
5286 }))
5287 }
5288
5289 fn close_hunk_diff_button(
5290 &self,
5291 hunk: HoveredHunk,
5292 row: DisplayRow,
5293 cx: &mut ViewContext<Self>,
5294 ) -> IconButton {
5295 IconButton::new(
5296 ("close_hunk_diff_indicator", row.0 as usize),
5297 ui::IconName::Close,
5298 )
5299 .shape(ui::IconButtonShape::Square)
5300 .icon_size(IconSize::XSmall)
5301 .icon_color(Color::Muted)
5302 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5303 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5304 }
5305
5306 pub fn context_menu_visible(&self) -> bool {
5307 self.context_menu
5308 .read()
5309 .as_ref()
5310 .map_or(false, |menu| menu.visible())
5311 }
5312
5313 fn render_context_menu(
5314 &self,
5315 cursor_position: DisplayPoint,
5316 style: &EditorStyle,
5317 max_height: Pixels,
5318 cx: &mut ViewContext<Editor>,
5319 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5320 self.context_menu.read().as_ref().map(|menu| {
5321 menu.render(
5322 cursor_position,
5323 style,
5324 max_height,
5325 self.workspace.as_ref().map(|(w, _)| w.clone()),
5326 cx,
5327 )
5328 })
5329 }
5330
5331 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5332 cx.notify();
5333 self.completion_tasks.clear();
5334 let context_menu = self.context_menu.write().take();
5335 if context_menu.is_some() {
5336 self.update_visible_inline_completion(cx);
5337 }
5338 context_menu
5339 }
5340
5341 pub fn insert_snippet(
5342 &mut self,
5343 insertion_ranges: &[Range<usize>],
5344 snippet: Snippet,
5345 cx: &mut ViewContext<Self>,
5346 ) -> Result<()> {
5347 struct Tabstop<T> {
5348 is_end_tabstop: bool,
5349 ranges: Vec<Range<T>>,
5350 }
5351
5352 let tabstops = self.buffer.update(cx, |buffer, cx| {
5353 let snippet_text: Arc<str> = snippet.text.clone().into();
5354 buffer.edit(
5355 insertion_ranges
5356 .iter()
5357 .cloned()
5358 .map(|range| (range, snippet_text.clone())),
5359 Some(AutoindentMode::EachLine),
5360 cx,
5361 );
5362
5363 let snapshot = &*buffer.read(cx);
5364 let snippet = &snippet;
5365 snippet
5366 .tabstops
5367 .iter()
5368 .map(|tabstop| {
5369 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5370 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5371 });
5372 let mut tabstop_ranges = tabstop
5373 .iter()
5374 .flat_map(|tabstop_range| {
5375 let mut delta = 0_isize;
5376 insertion_ranges.iter().map(move |insertion_range| {
5377 let insertion_start = insertion_range.start as isize + delta;
5378 delta +=
5379 snippet.text.len() as isize - insertion_range.len() as isize;
5380
5381 let start = ((insertion_start + tabstop_range.start) as usize)
5382 .min(snapshot.len());
5383 let end = ((insertion_start + tabstop_range.end) as usize)
5384 .min(snapshot.len());
5385 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5386 })
5387 })
5388 .collect::<Vec<_>>();
5389 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5390
5391 Tabstop {
5392 is_end_tabstop,
5393 ranges: tabstop_ranges,
5394 }
5395 })
5396 .collect::<Vec<_>>()
5397 });
5398 if let Some(tabstop) = tabstops.first() {
5399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5400 s.select_ranges(tabstop.ranges.iter().cloned());
5401 });
5402
5403 // If we're already at the last tabstop and it's at the end of the snippet,
5404 // we're done, we don't need to keep the state around.
5405 if !tabstop.is_end_tabstop {
5406 let ranges = tabstops
5407 .into_iter()
5408 .map(|tabstop| tabstop.ranges)
5409 .collect::<Vec<_>>();
5410 self.snippet_stack.push(SnippetState {
5411 active_index: 0,
5412 ranges,
5413 });
5414 }
5415
5416 // Check whether the just-entered snippet ends with an auto-closable bracket.
5417 if self.autoclose_regions.is_empty() {
5418 let snapshot = self.buffer.read(cx).snapshot(cx);
5419 for selection in &mut self.selections.all::<Point>(cx) {
5420 let selection_head = selection.head();
5421 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5422 continue;
5423 };
5424
5425 let mut bracket_pair = None;
5426 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5427 let prev_chars = snapshot
5428 .reversed_chars_at(selection_head)
5429 .collect::<String>();
5430 for (pair, enabled) in scope.brackets() {
5431 if enabled
5432 && pair.close
5433 && prev_chars.starts_with(pair.start.as_str())
5434 && next_chars.starts_with(pair.end.as_str())
5435 {
5436 bracket_pair = Some(pair.clone());
5437 break;
5438 }
5439 }
5440 if let Some(pair) = bracket_pair {
5441 let start = snapshot.anchor_after(selection_head);
5442 let end = snapshot.anchor_after(selection_head);
5443 self.autoclose_regions.push(AutocloseRegion {
5444 selection_id: selection.id,
5445 range: start..end,
5446 pair,
5447 });
5448 }
5449 }
5450 }
5451 }
5452 Ok(())
5453 }
5454
5455 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5456 self.move_to_snippet_tabstop(Bias::Right, cx)
5457 }
5458
5459 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5460 self.move_to_snippet_tabstop(Bias::Left, cx)
5461 }
5462
5463 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5464 if let Some(mut snippet) = self.snippet_stack.pop() {
5465 match bias {
5466 Bias::Left => {
5467 if snippet.active_index > 0 {
5468 snippet.active_index -= 1;
5469 } else {
5470 self.snippet_stack.push(snippet);
5471 return false;
5472 }
5473 }
5474 Bias::Right => {
5475 if snippet.active_index + 1 < snippet.ranges.len() {
5476 snippet.active_index += 1;
5477 } else {
5478 self.snippet_stack.push(snippet);
5479 return false;
5480 }
5481 }
5482 }
5483 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5484 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5485 s.select_anchor_ranges(current_ranges.iter().cloned())
5486 });
5487 // If snippet state is not at the last tabstop, push it back on the stack
5488 if snippet.active_index + 1 < snippet.ranges.len() {
5489 self.snippet_stack.push(snippet);
5490 }
5491 return true;
5492 }
5493 }
5494
5495 false
5496 }
5497
5498 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5499 self.transact(cx, |this, cx| {
5500 this.select_all(&SelectAll, cx);
5501 this.insert("", cx);
5502 });
5503 }
5504
5505 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5506 self.transact(cx, |this, cx| {
5507 this.select_autoclose_pair(cx);
5508 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5509 if !this.linked_edit_ranges.is_empty() {
5510 let selections = this.selections.all::<MultiBufferPoint>(cx);
5511 let snapshot = this.buffer.read(cx).snapshot(cx);
5512
5513 for selection in selections.iter() {
5514 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5515 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5516 if selection_start.buffer_id != selection_end.buffer_id {
5517 continue;
5518 }
5519 if let Some(ranges) =
5520 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5521 {
5522 for (buffer, entries) in ranges {
5523 linked_ranges.entry(buffer).or_default().extend(entries);
5524 }
5525 }
5526 }
5527 }
5528
5529 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5530 if !this.selections.line_mode {
5531 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5532 for selection in &mut selections {
5533 if selection.is_empty() {
5534 let old_head = selection.head();
5535 let mut new_head =
5536 movement::left(&display_map, old_head.to_display_point(&display_map))
5537 .to_point(&display_map);
5538 if let Some((buffer, line_buffer_range)) = display_map
5539 .buffer_snapshot
5540 .buffer_line_for_row(MultiBufferRow(old_head.row))
5541 {
5542 let indent_size =
5543 buffer.indent_size_for_line(line_buffer_range.start.row);
5544 let indent_len = match indent_size.kind {
5545 IndentKind::Space => {
5546 buffer.settings_at(line_buffer_range.start, cx).tab_size
5547 }
5548 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5549 };
5550 if old_head.column <= indent_size.len && old_head.column > 0 {
5551 let indent_len = indent_len.get();
5552 new_head = cmp::min(
5553 new_head,
5554 MultiBufferPoint::new(
5555 old_head.row,
5556 ((old_head.column - 1) / indent_len) * indent_len,
5557 ),
5558 );
5559 }
5560 }
5561
5562 selection.set_head(new_head, SelectionGoal::None);
5563 }
5564 }
5565 }
5566
5567 this.signature_help_state.set_backspace_pressed(true);
5568 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5569 this.insert("", cx);
5570 let empty_str: Arc<str> = Arc::from("");
5571 for (buffer, edits) in linked_ranges {
5572 let snapshot = buffer.read(cx).snapshot();
5573 use text::ToPoint as TP;
5574
5575 let edits = edits
5576 .into_iter()
5577 .map(|range| {
5578 let end_point = TP::to_point(&range.end, &snapshot);
5579 let mut start_point = TP::to_point(&range.start, &snapshot);
5580
5581 if end_point == start_point {
5582 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5583 .saturating_sub(1);
5584 start_point = TP::to_point(&offset, &snapshot);
5585 };
5586
5587 (start_point..end_point, empty_str.clone())
5588 })
5589 .sorted_by_key(|(range, _)| range.start)
5590 .collect::<Vec<_>>();
5591 buffer.update(cx, |this, cx| {
5592 this.edit(edits, None, cx);
5593 })
5594 }
5595 this.refresh_inline_completion(true, false, cx);
5596 linked_editing_ranges::refresh_linked_ranges(this, cx);
5597 });
5598 }
5599
5600 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5601 self.transact(cx, |this, cx| {
5602 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5603 let line_mode = s.line_mode;
5604 s.move_with(|map, selection| {
5605 if selection.is_empty() && !line_mode {
5606 let cursor = movement::right(map, selection.head());
5607 selection.end = cursor;
5608 selection.reversed = true;
5609 selection.goal = SelectionGoal::None;
5610 }
5611 })
5612 });
5613 this.insert("", cx);
5614 this.refresh_inline_completion(true, false, cx);
5615 });
5616 }
5617
5618 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5619 if self.move_to_prev_snippet_tabstop(cx) {
5620 return;
5621 }
5622
5623 self.outdent(&Outdent, cx);
5624 }
5625
5626 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5627 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5628 return;
5629 }
5630
5631 let mut selections = self.selections.all_adjusted(cx);
5632 let buffer = self.buffer.read(cx);
5633 let snapshot = buffer.snapshot(cx);
5634 let rows_iter = selections.iter().map(|s| s.head().row);
5635 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5636
5637 let mut edits = Vec::new();
5638 let mut prev_edited_row = 0;
5639 let mut row_delta = 0;
5640 for selection in &mut selections {
5641 if selection.start.row != prev_edited_row {
5642 row_delta = 0;
5643 }
5644 prev_edited_row = selection.end.row;
5645
5646 // If the selection is non-empty, then increase the indentation of the selected lines.
5647 if !selection.is_empty() {
5648 row_delta =
5649 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5650 continue;
5651 }
5652
5653 // If the selection is empty and the cursor is in the leading whitespace before the
5654 // suggested indentation, then auto-indent the line.
5655 let cursor = selection.head();
5656 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5657 if let Some(suggested_indent) =
5658 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5659 {
5660 if cursor.column < suggested_indent.len
5661 && cursor.column <= current_indent.len
5662 && current_indent.len <= suggested_indent.len
5663 {
5664 selection.start = Point::new(cursor.row, suggested_indent.len);
5665 selection.end = selection.start;
5666 if row_delta == 0 {
5667 edits.extend(Buffer::edit_for_indent_size_adjustment(
5668 cursor.row,
5669 current_indent,
5670 suggested_indent,
5671 ));
5672 row_delta = suggested_indent.len - current_indent.len;
5673 }
5674 continue;
5675 }
5676 }
5677
5678 // Otherwise, insert a hard or soft tab.
5679 let settings = buffer.settings_at(cursor, cx);
5680 let tab_size = if settings.hard_tabs {
5681 IndentSize::tab()
5682 } else {
5683 let tab_size = settings.tab_size.get();
5684 let char_column = snapshot
5685 .text_for_range(Point::new(cursor.row, 0)..cursor)
5686 .flat_map(str::chars)
5687 .count()
5688 + row_delta as usize;
5689 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5690 IndentSize::spaces(chars_to_next_tab_stop)
5691 };
5692 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5693 selection.end = selection.start;
5694 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5695 row_delta += tab_size.len;
5696 }
5697
5698 self.transact(cx, |this, cx| {
5699 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5700 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5701 this.refresh_inline_completion(true, false, cx);
5702 });
5703 }
5704
5705 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5706 if self.read_only(cx) {
5707 return;
5708 }
5709 let mut selections = self.selections.all::<Point>(cx);
5710 let mut prev_edited_row = 0;
5711 let mut row_delta = 0;
5712 let mut edits = Vec::new();
5713 let buffer = self.buffer.read(cx);
5714 let snapshot = buffer.snapshot(cx);
5715 for selection in &mut selections {
5716 if selection.start.row != prev_edited_row {
5717 row_delta = 0;
5718 }
5719 prev_edited_row = selection.end.row;
5720
5721 row_delta =
5722 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5723 }
5724
5725 self.transact(cx, |this, cx| {
5726 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5727 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5728 });
5729 }
5730
5731 fn indent_selection(
5732 buffer: &MultiBuffer,
5733 snapshot: &MultiBufferSnapshot,
5734 selection: &mut Selection<Point>,
5735 edits: &mut Vec<(Range<Point>, String)>,
5736 delta_for_start_row: u32,
5737 cx: &AppContext,
5738 ) -> u32 {
5739 let settings = buffer.settings_at(selection.start, cx);
5740 let tab_size = settings.tab_size.get();
5741 let indent_kind = if settings.hard_tabs {
5742 IndentKind::Tab
5743 } else {
5744 IndentKind::Space
5745 };
5746 let mut start_row = selection.start.row;
5747 let mut end_row = selection.end.row + 1;
5748
5749 // If a selection ends at the beginning of a line, don't indent
5750 // that last line.
5751 if selection.end.column == 0 && selection.end.row > selection.start.row {
5752 end_row -= 1;
5753 }
5754
5755 // Avoid re-indenting a row that has already been indented by a
5756 // previous selection, but still update this selection's column
5757 // to reflect that indentation.
5758 if delta_for_start_row > 0 {
5759 start_row += 1;
5760 selection.start.column += delta_for_start_row;
5761 if selection.end.row == selection.start.row {
5762 selection.end.column += delta_for_start_row;
5763 }
5764 }
5765
5766 let mut delta_for_end_row = 0;
5767 let has_multiple_rows = start_row + 1 != end_row;
5768 for row in start_row..end_row {
5769 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5770 let indent_delta = match (current_indent.kind, indent_kind) {
5771 (IndentKind::Space, IndentKind::Space) => {
5772 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5773 IndentSize::spaces(columns_to_next_tab_stop)
5774 }
5775 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5776 (_, IndentKind::Tab) => IndentSize::tab(),
5777 };
5778
5779 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5780 0
5781 } else {
5782 selection.start.column
5783 };
5784 let row_start = Point::new(row, start);
5785 edits.push((
5786 row_start..row_start,
5787 indent_delta.chars().collect::<String>(),
5788 ));
5789
5790 // Update this selection's endpoints to reflect the indentation.
5791 if row == selection.start.row {
5792 selection.start.column += indent_delta.len;
5793 }
5794 if row == selection.end.row {
5795 selection.end.column += indent_delta.len;
5796 delta_for_end_row = indent_delta.len;
5797 }
5798 }
5799
5800 if selection.start.row == selection.end.row {
5801 delta_for_start_row + delta_for_end_row
5802 } else {
5803 delta_for_end_row
5804 }
5805 }
5806
5807 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5808 if self.read_only(cx) {
5809 return;
5810 }
5811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5812 let selections = self.selections.all::<Point>(cx);
5813 let mut deletion_ranges = Vec::new();
5814 let mut last_outdent = None;
5815 {
5816 let buffer = self.buffer.read(cx);
5817 let snapshot = buffer.snapshot(cx);
5818 for selection in &selections {
5819 let settings = buffer.settings_at(selection.start, cx);
5820 let tab_size = settings.tab_size.get();
5821 let mut rows = selection.spanned_rows(false, &display_map);
5822
5823 // Avoid re-outdenting a row that has already been outdented by a
5824 // previous selection.
5825 if let Some(last_row) = last_outdent {
5826 if last_row == rows.start {
5827 rows.start = rows.start.next_row();
5828 }
5829 }
5830 let has_multiple_rows = rows.len() > 1;
5831 for row in rows.iter_rows() {
5832 let indent_size = snapshot.indent_size_for_line(row);
5833 if indent_size.len > 0 {
5834 let deletion_len = match indent_size.kind {
5835 IndentKind::Space => {
5836 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5837 if columns_to_prev_tab_stop == 0 {
5838 tab_size
5839 } else {
5840 columns_to_prev_tab_stop
5841 }
5842 }
5843 IndentKind::Tab => 1,
5844 };
5845 let start = if has_multiple_rows
5846 || deletion_len > selection.start.column
5847 || indent_size.len < selection.start.column
5848 {
5849 0
5850 } else {
5851 selection.start.column - deletion_len
5852 };
5853 deletion_ranges.push(
5854 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5855 );
5856 last_outdent = Some(row);
5857 }
5858 }
5859 }
5860 }
5861
5862 self.transact(cx, |this, cx| {
5863 this.buffer.update(cx, |buffer, cx| {
5864 let empty_str: Arc<str> = Arc::default();
5865 buffer.edit(
5866 deletion_ranges
5867 .into_iter()
5868 .map(|range| (range, empty_str.clone())),
5869 None,
5870 cx,
5871 );
5872 });
5873 let selections = this.selections.all::<usize>(cx);
5874 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5875 });
5876 }
5877
5878 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5880 let selections = self.selections.all::<Point>(cx);
5881
5882 let mut new_cursors = Vec::new();
5883 let mut edit_ranges = Vec::new();
5884 let mut selections = selections.iter().peekable();
5885 while let Some(selection) = selections.next() {
5886 let mut rows = selection.spanned_rows(false, &display_map);
5887 let goal_display_column = selection.head().to_display_point(&display_map).column();
5888
5889 // Accumulate contiguous regions of rows that we want to delete.
5890 while let Some(next_selection) = selections.peek() {
5891 let next_rows = next_selection.spanned_rows(false, &display_map);
5892 if next_rows.start <= rows.end {
5893 rows.end = next_rows.end;
5894 selections.next().unwrap();
5895 } else {
5896 break;
5897 }
5898 }
5899
5900 let buffer = &display_map.buffer_snapshot;
5901 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5902 let edit_end;
5903 let cursor_buffer_row;
5904 if buffer.max_point().row >= rows.end.0 {
5905 // If there's a line after the range, delete the \n from the end of the row range
5906 // and position the cursor on the next line.
5907 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5908 cursor_buffer_row = rows.end;
5909 } else {
5910 // If there isn't a line after the range, delete the \n from the line before the
5911 // start of the row range and position the cursor there.
5912 edit_start = edit_start.saturating_sub(1);
5913 edit_end = buffer.len();
5914 cursor_buffer_row = rows.start.previous_row();
5915 }
5916
5917 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5918 *cursor.column_mut() =
5919 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5920
5921 new_cursors.push((
5922 selection.id,
5923 buffer.anchor_after(cursor.to_point(&display_map)),
5924 ));
5925 edit_ranges.push(edit_start..edit_end);
5926 }
5927
5928 self.transact(cx, |this, cx| {
5929 let buffer = this.buffer.update(cx, |buffer, cx| {
5930 let empty_str: Arc<str> = Arc::default();
5931 buffer.edit(
5932 edit_ranges
5933 .into_iter()
5934 .map(|range| (range, empty_str.clone())),
5935 None,
5936 cx,
5937 );
5938 buffer.snapshot(cx)
5939 });
5940 let new_selections = new_cursors
5941 .into_iter()
5942 .map(|(id, cursor)| {
5943 let cursor = cursor.to_point(&buffer);
5944 Selection {
5945 id,
5946 start: cursor,
5947 end: cursor,
5948 reversed: false,
5949 goal: SelectionGoal::None,
5950 }
5951 })
5952 .collect();
5953
5954 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5955 s.select(new_selections);
5956 });
5957 });
5958 }
5959
5960 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5961 if self.read_only(cx) {
5962 return;
5963 }
5964 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5965 for selection in self.selections.all::<Point>(cx) {
5966 let start = MultiBufferRow(selection.start.row);
5967 let end = if selection.start.row == selection.end.row {
5968 MultiBufferRow(selection.start.row + 1)
5969 } else {
5970 MultiBufferRow(selection.end.row)
5971 };
5972
5973 if let Some(last_row_range) = row_ranges.last_mut() {
5974 if start <= last_row_range.end {
5975 last_row_range.end = end;
5976 continue;
5977 }
5978 }
5979 row_ranges.push(start..end);
5980 }
5981
5982 let snapshot = self.buffer.read(cx).snapshot(cx);
5983 let mut cursor_positions = Vec::new();
5984 for row_range in &row_ranges {
5985 let anchor = snapshot.anchor_before(Point::new(
5986 row_range.end.previous_row().0,
5987 snapshot.line_len(row_range.end.previous_row()),
5988 ));
5989 cursor_positions.push(anchor..anchor);
5990 }
5991
5992 self.transact(cx, |this, cx| {
5993 for row_range in row_ranges.into_iter().rev() {
5994 for row in row_range.iter_rows().rev() {
5995 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5996 let next_line_row = row.next_row();
5997 let indent = snapshot.indent_size_for_line(next_line_row);
5998 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5999
6000 let replace = if snapshot.line_len(next_line_row) > indent.len {
6001 " "
6002 } else {
6003 ""
6004 };
6005
6006 this.buffer.update(cx, |buffer, cx| {
6007 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6008 });
6009 }
6010 }
6011
6012 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6013 s.select_anchor_ranges(cursor_positions)
6014 });
6015 });
6016 }
6017
6018 pub fn sort_lines_case_sensitive(
6019 &mut self,
6020 _: &SortLinesCaseSensitive,
6021 cx: &mut ViewContext<Self>,
6022 ) {
6023 self.manipulate_lines(cx, |lines| lines.sort())
6024 }
6025
6026 pub fn sort_lines_case_insensitive(
6027 &mut self,
6028 _: &SortLinesCaseInsensitive,
6029 cx: &mut ViewContext<Self>,
6030 ) {
6031 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6032 }
6033
6034 pub fn unique_lines_case_insensitive(
6035 &mut self,
6036 _: &UniqueLinesCaseInsensitive,
6037 cx: &mut ViewContext<Self>,
6038 ) {
6039 self.manipulate_lines(cx, |lines| {
6040 let mut seen = HashSet::default();
6041 lines.retain(|line| seen.insert(line.to_lowercase()));
6042 })
6043 }
6044
6045 pub fn unique_lines_case_sensitive(
6046 &mut self,
6047 _: &UniqueLinesCaseSensitive,
6048 cx: &mut ViewContext<Self>,
6049 ) {
6050 self.manipulate_lines(cx, |lines| {
6051 let mut seen = HashSet::default();
6052 lines.retain(|line| seen.insert(*line));
6053 })
6054 }
6055
6056 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6057 let mut revert_changes = HashMap::default();
6058 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6059 for hunk in hunks_for_rows(
6060 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6061 &multi_buffer_snapshot,
6062 ) {
6063 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
6064 }
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 revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6073 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6074 if !revert_changes.is_empty() {
6075 self.transact(cx, |editor, cx| {
6076 editor.revert(revert_changes, cx);
6077 });
6078 }
6079 }
6080
6081 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6082 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6083 let project_path = buffer.read(cx).project_path(cx)?;
6084 let project = self.project.as_ref()?.read(cx);
6085 let entry = project.entry_for_path(&project_path, cx)?;
6086 let abs_path = project.absolute_path(&project_path, cx)?;
6087 let parent = if entry.is_symlink {
6088 abs_path.canonicalize().ok()?
6089 } else {
6090 abs_path
6091 }
6092 .parent()?
6093 .to_path_buf();
6094 Some(parent)
6095 }) {
6096 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6097 }
6098 }
6099
6100 fn gather_revert_changes(
6101 &mut self,
6102 selections: &[Selection<Anchor>],
6103 cx: &mut ViewContext<'_, Editor>,
6104 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6105 let mut revert_changes = HashMap::default();
6106 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6107 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6108 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6109 }
6110 revert_changes
6111 }
6112
6113 pub fn prepare_revert_change(
6114 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6115 multi_buffer: &Model<MultiBuffer>,
6116 hunk: &DiffHunk<MultiBufferRow>,
6117 cx: &AppContext,
6118 ) -> Option<()> {
6119 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6120 let buffer = buffer.read(cx);
6121 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6122 let buffer_snapshot = buffer.snapshot();
6123 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6124 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6125 probe
6126 .0
6127 .start
6128 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6129 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6130 }) {
6131 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6132 Some(())
6133 } else {
6134 None
6135 }
6136 }
6137
6138 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6139 self.manipulate_lines(cx, |lines| lines.reverse())
6140 }
6141
6142 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6143 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6144 }
6145
6146 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6147 where
6148 Fn: FnMut(&mut Vec<&str>),
6149 {
6150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6151 let buffer = self.buffer.read(cx).snapshot(cx);
6152
6153 let mut edits = Vec::new();
6154
6155 let selections = self.selections.all::<Point>(cx);
6156 let mut selections = selections.iter().peekable();
6157 let mut contiguous_row_selections = Vec::new();
6158 let mut new_selections = Vec::new();
6159 let mut added_lines = 0;
6160 let mut removed_lines = 0;
6161
6162 while let Some(selection) = selections.next() {
6163 let (start_row, end_row) = consume_contiguous_rows(
6164 &mut contiguous_row_selections,
6165 selection,
6166 &display_map,
6167 &mut selections,
6168 );
6169
6170 let start_point = Point::new(start_row.0, 0);
6171 let end_point = Point::new(
6172 end_row.previous_row().0,
6173 buffer.line_len(end_row.previous_row()),
6174 );
6175 let text = buffer
6176 .text_for_range(start_point..end_point)
6177 .collect::<String>();
6178
6179 let mut lines = text.split('\n').collect_vec();
6180
6181 let lines_before = lines.len();
6182 callback(&mut lines);
6183 let lines_after = lines.len();
6184
6185 edits.push((start_point..end_point, lines.join("\n")));
6186
6187 // Selections must change based on added and removed line count
6188 let start_row =
6189 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6190 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6191 new_selections.push(Selection {
6192 id: selection.id,
6193 start: start_row,
6194 end: end_row,
6195 goal: SelectionGoal::None,
6196 reversed: selection.reversed,
6197 });
6198
6199 if lines_after > lines_before {
6200 added_lines += lines_after - lines_before;
6201 } else if lines_before > lines_after {
6202 removed_lines += lines_before - lines_after;
6203 }
6204 }
6205
6206 self.transact(cx, |this, cx| {
6207 let buffer = this.buffer.update(cx, |buffer, cx| {
6208 buffer.edit(edits, None, cx);
6209 buffer.snapshot(cx)
6210 });
6211
6212 // Recalculate offsets on newly edited buffer
6213 let new_selections = new_selections
6214 .iter()
6215 .map(|s| {
6216 let start_point = Point::new(s.start.0, 0);
6217 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6218 Selection {
6219 id: s.id,
6220 start: buffer.point_to_offset(start_point),
6221 end: buffer.point_to_offset(end_point),
6222 goal: s.goal,
6223 reversed: s.reversed,
6224 }
6225 })
6226 .collect();
6227
6228 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6229 s.select(new_selections);
6230 });
6231
6232 this.request_autoscroll(Autoscroll::fit(), cx);
6233 });
6234 }
6235
6236 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6237 self.manipulate_text(cx, |text| text.to_uppercase())
6238 }
6239
6240 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6241 self.manipulate_text(cx, |text| text.to_lowercase())
6242 }
6243
6244 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6245 self.manipulate_text(cx, |text| {
6246 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6247 // https://github.com/rutrum/convert-case/issues/16
6248 text.split('\n')
6249 .map(|line| line.to_case(Case::Title))
6250 .join("\n")
6251 })
6252 }
6253
6254 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6255 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6256 }
6257
6258 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6259 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6260 }
6261
6262 pub fn convert_to_upper_camel_case(
6263 &mut self,
6264 _: &ConvertToUpperCamelCase,
6265 cx: &mut ViewContext<Self>,
6266 ) {
6267 self.manipulate_text(cx, |text| {
6268 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6269 // https://github.com/rutrum/convert-case/issues/16
6270 text.split('\n')
6271 .map(|line| line.to_case(Case::UpperCamel))
6272 .join("\n")
6273 })
6274 }
6275
6276 pub fn convert_to_lower_camel_case(
6277 &mut self,
6278 _: &ConvertToLowerCamelCase,
6279 cx: &mut ViewContext<Self>,
6280 ) {
6281 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6282 }
6283
6284 pub fn convert_to_opposite_case(
6285 &mut self,
6286 _: &ConvertToOppositeCase,
6287 cx: &mut ViewContext<Self>,
6288 ) {
6289 self.manipulate_text(cx, |text| {
6290 text.chars()
6291 .fold(String::with_capacity(text.len()), |mut t, c| {
6292 if c.is_uppercase() {
6293 t.extend(c.to_lowercase());
6294 } else {
6295 t.extend(c.to_uppercase());
6296 }
6297 t
6298 })
6299 })
6300 }
6301
6302 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6303 where
6304 Fn: FnMut(&str) -> String,
6305 {
6306 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6307 let buffer = self.buffer.read(cx).snapshot(cx);
6308
6309 let mut new_selections = Vec::new();
6310 let mut edits = Vec::new();
6311 let mut selection_adjustment = 0i32;
6312
6313 for selection in self.selections.all::<usize>(cx) {
6314 let selection_is_empty = selection.is_empty();
6315
6316 let (start, end) = if selection_is_empty {
6317 let word_range = movement::surrounding_word(
6318 &display_map,
6319 selection.start.to_display_point(&display_map),
6320 );
6321 let start = word_range.start.to_offset(&display_map, Bias::Left);
6322 let end = word_range.end.to_offset(&display_map, Bias::Left);
6323 (start, end)
6324 } else {
6325 (selection.start, selection.end)
6326 };
6327
6328 let text = buffer.text_for_range(start..end).collect::<String>();
6329 let old_length = text.len() as i32;
6330 let text = callback(&text);
6331
6332 new_selections.push(Selection {
6333 start: (start as i32 - selection_adjustment) as usize,
6334 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6335 goal: SelectionGoal::None,
6336 ..selection
6337 });
6338
6339 selection_adjustment += old_length - text.len() as i32;
6340
6341 edits.push((start..end, text));
6342 }
6343
6344 self.transact(cx, |this, cx| {
6345 this.buffer.update(cx, |buffer, cx| {
6346 buffer.edit(edits, None, cx);
6347 });
6348
6349 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6350 s.select(new_selections);
6351 });
6352
6353 this.request_autoscroll(Autoscroll::fit(), cx);
6354 });
6355 }
6356
6357 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6358 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6359 let buffer = &display_map.buffer_snapshot;
6360 let selections = self.selections.all::<Point>(cx);
6361
6362 let mut edits = Vec::new();
6363 let mut selections_iter = selections.iter().peekable();
6364 while let Some(selection) = selections_iter.next() {
6365 // Avoid duplicating the same lines twice.
6366 let mut rows = selection.spanned_rows(false, &display_map);
6367
6368 while let Some(next_selection) = selections_iter.peek() {
6369 let next_rows = next_selection.spanned_rows(false, &display_map);
6370 if next_rows.start < rows.end {
6371 rows.end = next_rows.end;
6372 selections_iter.next().unwrap();
6373 } else {
6374 break;
6375 }
6376 }
6377
6378 // Copy the text from the selected row region and splice it either at the start
6379 // or end of the region.
6380 let start = Point::new(rows.start.0, 0);
6381 let end = Point::new(
6382 rows.end.previous_row().0,
6383 buffer.line_len(rows.end.previous_row()),
6384 );
6385 let text = buffer
6386 .text_for_range(start..end)
6387 .chain(Some("\n"))
6388 .collect::<String>();
6389 let insert_location = if upwards {
6390 Point::new(rows.end.0, 0)
6391 } else {
6392 start
6393 };
6394 edits.push((insert_location..insert_location, text));
6395 }
6396
6397 self.transact(cx, |this, cx| {
6398 this.buffer.update(cx, |buffer, cx| {
6399 buffer.edit(edits, None, cx);
6400 });
6401
6402 this.request_autoscroll(Autoscroll::fit(), cx);
6403 });
6404 }
6405
6406 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6407 self.duplicate_line(true, cx);
6408 }
6409
6410 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6411 self.duplicate_line(false, cx);
6412 }
6413
6414 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6415 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6416 let buffer = self.buffer.read(cx).snapshot(cx);
6417
6418 let mut edits = Vec::new();
6419 let mut unfold_ranges = Vec::new();
6420 let mut refold_ranges = Vec::new();
6421
6422 let selections = self.selections.all::<Point>(cx);
6423 let mut selections = selections.iter().peekable();
6424 let mut contiguous_row_selections = Vec::new();
6425 let mut new_selections = Vec::new();
6426
6427 while let Some(selection) = selections.next() {
6428 // Find all the selections that span a contiguous row range
6429 let (start_row, end_row) = consume_contiguous_rows(
6430 &mut contiguous_row_selections,
6431 selection,
6432 &display_map,
6433 &mut selections,
6434 );
6435
6436 // Move the text spanned by the row range to be before the line preceding the row range
6437 if start_row.0 > 0 {
6438 let range_to_move = Point::new(
6439 start_row.previous_row().0,
6440 buffer.line_len(start_row.previous_row()),
6441 )
6442 ..Point::new(
6443 end_row.previous_row().0,
6444 buffer.line_len(end_row.previous_row()),
6445 );
6446 let insertion_point = display_map
6447 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6448 .0;
6449
6450 // Don't move lines across excerpts
6451 if buffer
6452 .excerpt_boundaries_in_range((
6453 Bound::Excluded(insertion_point),
6454 Bound::Included(range_to_move.end),
6455 ))
6456 .next()
6457 .is_none()
6458 {
6459 let text = buffer
6460 .text_for_range(range_to_move.clone())
6461 .flat_map(|s| s.chars())
6462 .skip(1)
6463 .chain(['\n'])
6464 .collect::<String>();
6465
6466 edits.push((
6467 buffer.anchor_after(range_to_move.start)
6468 ..buffer.anchor_before(range_to_move.end),
6469 String::new(),
6470 ));
6471 let insertion_anchor = buffer.anchor_after(insertion_point);
6472 edits.push((insertion_anchor..insertion_anchor, text));
6473
6474 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6475
6476 // Move selections up
6477 new_selections.extend(contiguous_row_selections.drain(..).map(
6478 |mut selection| {
6479 selection.start.row -= row_delta;
6480 selection.end.row -= row_delta;
6481 selection
6482 },
6483 ));
6484
6485 // Move folds up
6486 unfold_ranges.push(range_to_move.clone());
6487 for fold in display_map.folds_in_range(
6488 buffer.anchor_before(range_to_move.start)
6489 ..buffer.anchor_after(range_to_move.end),
6490 ) {
6491 let mut start = fold.range.start.to_point(&buffer);
6492 let mut end = fold.range.end.to_point(&buffer);
6493 start.row -= row_delta;
6494 end.row -= row_delta;
6495 refold_ranges.push((start..end, fold.placeholder.clone()));
6496 }
6497 }
6498 }
6499
6500 // If we didn't move line(s), preserve the existing selections
6501 new_selections.append(&mut contiguous_row_selections);
6502 }
6503
6504 self.transact(cx, |this, cx| {
6505 this.unfold_ranges(unfold_ranges, true, true, cx);
6506 this.buffer.update(cx, |buffer, cx| {
6507 for (range, text) in edits {
6508 buffer.edit([(range, text)], None, cx);
6509 }
6510 });
6511 this.fold_ranges(refold_ranges, true, cx);
6512 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6513 s.select(new_selections);
6514 })
6515 });
6516 }
6517
6518 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6519 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6520 let buffer = self.buffer.read(cx).snapshot(cx);
6521
6522 let mut edits = Vec::new();
6523 let mut unfold_ranges = Vec::new();
6524 let mut refold_ranges = Vec::new();
6525
6526 let selections = self.selections.all::<Point>(cx);
6527 let mut selections = selections.iter().peekable();
6528 let mut contiguous_row_selections = Vec::new();
6529 let mut new_selections = Vec::new();
6530
6531 while let Some(selection) = selections.next() {
6532 // Find all the selections that span a contiguous row range
6533 let (start_row, end_row) = consume_contiguous_rows(
6534 &mut contiguous_row_selections,
6535 selection,
6536 &display_map,
6537 &mut selections,
6538 );
6539
6540 // Move the text spanned by the row range to be after the last line of the row range
6541 if end_row.0 <= buffer.max_point().row {
6542 let range_to_move =
6543 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6544 let insertion_point = display_map
6545 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6546 .0;
6547
6548 // Don't move lines across excerpt boundaries
6549 if buffer
6550 .excerpt_boundaries_in_range((
6551 Bound::Excluded(range_to_move.start),
6552 Bound::Included(insertion_point),
6553 ))
6554 .next()
6555 .is_none()
6556 {
6557 let mut text = String::from("\n");
6558 text.extend(buffer.text_for_range(range_to_move.clone()));
6559 text.pop(); // Drop trailing newline
6560 edits.push((
6561 buffer.anchor_after(range_to_move.start)
6562 ..buffer.anchor_before(range_to_move.end),
6563 String::new(),
6564 ));
6565 let insertion_anchor = buffer.anchor_after(insertion_point);
6566 edits.push((insertion_anchor..insertion_anchor, text));
6567
6568 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6569
6570 // Move selections down
6571 new_selections.extend(contiguous_row_selections.drain(..).map(
6572 |mut selection| {
6573 selection.start.row += row_delta;
6574 selection.end.row += row_delta;
6575 selection
6576 },
6577 ));
6578
6579 // Move folds down
6580 unfold_ranges.push(range_to_move.clone());
6581 for fold in display_map.folds_in_range(
6582 buffer.anchor_before(range_to_move.start)
6583 ..buffer.anchor_after(range_to_move.end),
6584 ) {
6585 let mut start = fold.range.start.to_point(&buffer);
6586 let mut end = fold.range.end.to_point(&buffer);
6587 start.row += row_delta;
6588 end.row += row_delta;
6589 refold_ranges.push((start..end, fold.placeholder.clone()));
6590 }
6591 }
6592 }
6593
6594 // If we didn't move line(s), preserve the existing selections
6595 new_selections.append(&mut contiguous_row_selections);
6596 }
6597
6598 self.transact(cx, |this, cx| {
6599 this.unfold_ranges(unfold_ranges, true, true, cx);
6600 this.buffer.update(cx, |buffer, cx| {
6601 for (range, text) in edits {
6602 buffer.edit([(range, text)], None, cx);
6603 }
6604 });
6605 this.fold_ranges(refold_ranges, true, cx);
6606 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6607 });
6608 }
6609
6610 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6611 let text_layout_details = &self.text_layout_details(cx);
6612 self.transact(cx, |this, cx| {
6613 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6614 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6615 let line_mode = s.line_mode;
6616 s.move_with(|display_map, selection| {
6617 if !selection.is_empty() || line_mode {
6618 return;
6619 }
6620
6621 let mut head = selection.head();
6622 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6623 if head.column() == display_map.line_len(head.row()) {
6624 transpose_offset = display_map
6625 .buffer_snapshot
6626 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6627 }
6628
6629 if transpose_offset == 0 {
6630 return;
6631 }
6632
6633 *head.column_mut() += 1;
6634 head = display_map.clip_point(head, Bias::Right);
6635 let goal = SelectionGoal::HorizontalPosition(
6636 display_map
6637 .x_for_display_point(head, &text_layout_details)
6638 .into(),
6639 );
6640 selection.collapse_to(head, goal);
6641
6642 let transpose_start = display_map
6643 .buffer_snapshot
6644 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6645 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6646 let transpose_end = display_map
6647 .buffer_snapshot
6648 .clip_offset(transpose_offset + 1, Bias::Right);
6649 if let Some(ch) =
6650 display_map.buffer_snapshot.chars_at(transpose_start).next()
6651 {
6652 edits.push((transpose_start..transpose_offset, String::new()));
6653 edits.push((transpose_end..transpose_end, ch.to_string()));
6654 }
6655 }
6656 });
6657 edits
6658 });
6659 this.buffer
6660 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6661 let selections = this.selections.all::<usize>(cx);
6662 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6663 s.select(selections);
6664 });
6665 });
6666 }
6667
6668 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6669 let mut text = String::new();
6670 let buffer = self.buffer.read(cx).snapshot(cx);
6671 let mut selections = self.selections.all::<Point>(cx);
6672 let mut clipboard_selections = Vec::with_capacity(selections.len());
6673 {
6674 let max_point = buffer.max_point();
6675 let mut is_first = true;
6676 for selection in &mut selections {
6677 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6678 if is_entire_line {
6679 selection.start = Point::new(selection.start.row, 0);
6680 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6681 selection.goal = SelectionGoal::None;
6682 }
6683 if is_first {
6684 is_first = false;
6685 } else {
6686 text += "\n";
6687 }
6688 let mut len = 0;
6689 for chunk in buffer.text_for_range(selection.start..selection.end) {
6690 text.push_str(chunk);
6691 len += chunk.len();
6692 }
6693 clipboard_selections.push(ClipboardSelection {
6694 len,
6695 is_entire_line,
6696 first_line_indent: buffer
6697 .indent_size_for_line(MultiBufferRow(selection.start.row))
6698 .len,
6699 });
6700 }
6701 }
6702
6703 self.transact(cx, |this, cx| {
6704 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6705 s.select(selections);
6706 });
6707 this.insert("", cx);
6708 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6709 text,
6710 clipboard_selections,
6711 ));
6712 });
6713 }
6714
6715 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6716 let selections = self.selections.all::<Point>(cx);
6717 let buffer = self.buffer.read(cx).read(cx);
6718 let mut text = String::new();
6719
6720 let mut clipboard_selections = Vec::with_capacity(selections.len());
6721 {
6722 let max_point = buffer.max_point();
6723 let mut is_first = true;
6724 for selection in selections.iter() {
6725 let mut start = selection.start;
6726 let mut end = selection.end;
6727 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6728 if is_entire_line {
6729 start = Point::new(start.row, 0);
6730 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6731 }
6732 if is_first {
6733 is_first = false;
6734 } else {
6735 text += "\n";
6736 }
6737 let mut len = 0;
6738 for chunk in buffer.text_for_range(start..end) {
6739 text.push_str(chunk);
6740 len += chunk.len();
6741 }
6742 clipboard_selections.push(ClipboardSelection {
6743 len,
6744 is_entire_line,
6745 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6746 });
6747 }
6748 }
6749
6750 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6751 text,
6752 clipboard_selections,
6753 ));
6754 }
6755
6756 pub fn do_paste(
6757 &mut self,
6758 text: &String,
6759 clipboard_selections: Option<Vec<ClipboardSelection>>,
6760 handle_entire_lines: bool,
6761 cx: &mut ViewContext<Self>,
6762 ) {
6763 if self.read_only(cx) {
6764 return;
6765 }
6766
6767 let clipboard_text = Cow::Borrowed(text);
6768
6769 self.transact(cx, |this, cx| {
6770 if let Some(mut clipboard_selections) = clipboard_selections {
6771 let old_selections = this.selections.all::<usize>(cx);
6772 let all_selections_were_entire_line =
6773 clipboard_selections.iter().all(|s| s.is_entire_line);
6774 let first_selection_indent_column =
6775 clipboard_selections.first().map(|s| s.first_line_indent);
6776 if clipboard_selections.len() != old_selections.len() {
6777 clipboard_selections.drain(..);
6778 }
6779
6780 this.buffer.update(cx, |buffer, cx| {
6781 let snapshot = buffer.read(cx);
6782 let mut start_offset = 0;
6783 let mut edits = Vec::new();
6784 let mut original_indent_columns = Vec::new();
6785 for (ix, selection) in old_selections.iter().enumerate() {
6786 let to_insert;
6787 let entire_line;
6788 let original_indent_column;
6789 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6790 let end_offset = start_offset + clipboard_selection.len;
6791 to_insert = &clipboard_text[start_offset..end_offset];
6792 entire_line = clipboard_selection.is_entire_line;
6793 start_offset = end_offset + 1;
6794 original_indent_column = Some(clipboard_selection.first_line_indent);
6795 } else {
6796 to_insert = clipboard_text.as_str();
6797 entire_line = all_selections_were_entire_line;
6798 original_indent_column = first_selection_indent_column
6799 }
6800
6801 // If the corresponding selection was empty when this slice of the
6802 // clipboard text was written, then the entire line containing the
6803 // selection was copied. If this selection is also currently empty,
6804 // then paste the line before the current line of the buffer.
6805 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6806 let column = selection.start.to_point(&snapshot).column as usize;
6807 let line_start = selection.start - column;
6808 line_start..line_start
6809 } else {
6810 selection.range()
6811 };
6812
6813 edits.push((range, to_insert));
6814 original_indent_columns.extend(original_indent_column);
6815 }
6816 drop(snapshot);
6817
6818 buffer.edit(
6819 edits,
6820 Some(AutoindentMode::Block {
6821 original_indent_columns,
6822 }),
6823 cx,
6824 );
6825 });
6826
6827 let selections = this.selections.all::<usize>(cx);
6828 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6829 } else {
6830 this.insert(&clipboard_text, cx);
6831 }
6832 });
6833 }
6834
6835 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6836 if let Some(item) = cx.read_from_clipboard() {
6837 let entries = item.entries();
6838
6839 match entries.first() {
6840 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6841 // of all the pasted entries.
6842 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6843 .do_paste(
6844 clipboard_string.text(),
6845 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6846 true,
6847 cx,
6848 ),
6849 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6850 }
6851 }
6852 }
6853
6854 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6855 if self.read_only(cx) {
6856 return;
6857 }
6858
6859 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6860 if let Some((selections, _)) =
6861 self.selection_history.transaction(transaction_id).cloned()
6862 {
6863 self.change_selections(None, cx, |s| {
6864 s.select_anchors(selections.to_vec());
6865 });
6866 }
6867 self.request_autoscroll(Autoscroll::fit(), cx);
6868 self.unmark_text(cx);
6869 self.refresh_inline_completion(true, false, cx);
6870 cx.emit(EditorEvent::Edited { transaction_id });
6871 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6872 }
6873 }
6874
6875 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6876 if self.read_only(cx) {
6877 return;
6878 }
6879
6880 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6881 if let Some((_, Some(selections))) =
6882 self.selection_history.transaction(transaction_id).cloned()
6883 {
6884 self.change_selections(None, cx, |s| {
6885 s.select_anchors(selections.to_vec());
6886 });
6887 }
6888 self.request_autoscroll(Autoscroll::fit(), cx);
6889 self.unmark_text(cx);
6890 self.refresh_inline_completion(true, false, cx);
6891 cx.emit(EditorEvent::Edited { transaction_id });
6892 }
6893 }
6894
6895 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6896 self.buffer
6897 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6898 }
6899
6900 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6901 self.buffer
6902 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6903 }
6904
6905 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6907 let line_mode = s.line_mode;
6908 s.move_with(|map, selection| {
6909 let cursor = if selection.is_empty() && !line_mode {
6910 movement::left(map, selection.start)
6911 } else {
6912 selection.start
6913 };
6914 selection.collapse_to(cursor, SelectionGoal::None);
6915 });
6916 })
6917 }
6918
6919 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6921 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6922 })
6923 }
6924
6925 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6926 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6927 let line_mode = s.line_mode;
6928 s.move_with(|map, selection| {
6929 let cursor = if selection.is_empty() && !line_mode {
6930 movement::right(map, selection.end)
6931 } else {
6932 selection.end
6933 };
6934 selection.collapse_to(cursor, SelectionGoal::None)
6935 });
6936 })
6937 }
6938
6939 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6940 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6941 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6942 })
6943 }
6944
6945 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6946 if self.take_rename(true, cx).is_some() {
6947 return;
6948 }
6949
6950 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6951 cx.propagate();
6952 return;
6953 }
6954
6955 let text_layout_details = &self.text_layout_details(cx);
6956 let selection_count = self.selections.count();
6957 let first_selection = self.selections.first_anchor();
6958
6959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6960 let line_mode = s.line_mode;
6961 s.move_with(|map, selection| {
6962 if !selection.is_empty() && !line_mode {
6963 selection.goal = SelectionGoal::None;
6964 }
6965 let (cursor, goal) = movement::up(
6966 map,
6967 selection.start,
6968 selection.goal,
6969 false,
6970 &text_layout_details,
6971 );
6972 selection.collapse_to(cursor, goal);
6973 });
6974 });
6975
6976 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6977 {
6978 cx.propagate();
6979 }
6980 }
6981
6982 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6983 if self.take_rename(true, cx).is_some() {
6984 return;
6985 }
6986
6987 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6988 cx.propagate();
6989 return;
6990 }
6991
6992 let text_layout_details = &self.text_layout_details(cx);
6993
6994 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6995 let line_mode = s.line_mode;
6996 s.move_with(|map, selection| {
6997 if !selection.is_empty() && !line_mode {
6998 selection.goal = SelectionGoal::None;
6999 }
7000 let (cursor, goal) = movement::up_by_rows(
7001 map,
7002 selection.start,
7003 action.lines,
7004 selection.goal,
7005 false,
7006 &text_layout_details,
7007 );
7008 selection.collapse_to(cursor, goal);
7009 });
7010 })
7011 }
7012
7013 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7014 if self.take_rename(true, cx).is_some() {
7015 return;
7016 }
7017
7018 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7019 cx.propagate();
7020 return;
7021 }
7022
7023 let text_layout_details = &self.text_layout_details(cx);
7024
7025 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7026 let line_mode = s.line_mode;
7027 s.move_with(|map, selection| {
7028 if !selection.is_empty() && !line_mode {
7029 selection.goal = SelectionGoal::None;
7030 }
7031 let (cursor, goal) = movement::down_by_rows(
7032 map,
7033 selection.start,
7034 action.lines,
7035 selection.goal,
7036 false,
7037 &text_layout_details,
7038 );
7039 selection.collapse_to(cursor, goal);
7040 });
7041 })
7042 }
7043
7044 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, 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::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7049 })
7050 })
7051 }
7052
7053 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7054 let text_layout_details = &self.text_layout_details(cx);
7055 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7056 s.move_heads_with(|map, head, goal| {
7057 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7058 })
7059 })
7060 }
7061
7062 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7063 let Some(row_count) = self.visible_row_count() else {
7064 return;
7065 };
7066
7067 let text_layout_details = &self.text_layout_details(cx);
7068
7069 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7070 s.move_heads_with(|map, head, goal| {
7071 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
7072 })
7073 })
7074 }
7075
7076 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7077 if self.take_rename(true, cx).is_some() {
7078 return;
7079 }
7080
7081 if self
7082 .context_menu
7083 .write()
7084 .as_mut()
7085 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7086 .unwrap_or(false)
7087 {
7088 return;
7089 }
7090
7091 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7092 cx.propagate();
7093 return;
7094 }
7095
7096 let Some(row_count) = self.visible_row_count() else {
7097 return;
7098 };
7099
7100 let autoscroll = if action.center_cursor {
7101 Autoscroll::center()
7102 } else {
7103 Autoscroll::fit()
7104 };
7105
7106 let text_layout_details = &self.text_layout_details(cx);
7107
7108 self.change_selections(Some(autoscroll), cx, |s| {
7109 let line_mode = s.line_mode;
7110 s.move_with(|map, selection| {
7111 if !selection.is_empty() && !line_mode {
7112 selection.goal = SelectionGoal::None;
7113 }
7114 let (cursor, goal) = movement::up_by_rows(
7115 map,
7116 selection.end,
7117 row_count,
7118 selection.goal,
7119 false,
7120 &text_layout_details,
7121 );
7122 selection.collapse_to(cursor, goal);
7123 });
7124 });
7125 }
7126
7127 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7128 let text_layout_details = &self.text_layout_details(cx);
7129 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7130 s.move_heads_with(|map, head, goal| {
7131 movement::up(map, head, goal, false, &text_layout_details)
7132 })
7133 })
7134 }
7135
7136 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7137 self.take_rename(true, cx);
7138
7139 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7140 cx.propagate();
7141 return;
7142 }
7143
7144 let text_layout_details = &self.text_layout_details(cx);
7145 let selection_count = self.selections.count();
7146 let first_selection = self.selections.first_anchor();
7147
7148 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7149 let line_mode = s.line_mode;
7150 s.move_with(|map, selection| {
7151 if !selection.is_empty() && !line_mode {
7152 selection.goal = SelectionGoal::None;
7153 }
7154 let (cursor, goal) = movement::down(
7155 map,
7156 selection.end,
7157 selection.goal,
7158 false,
7159 &text_layout_details,
7160 );
7161 selection.collapse_to(cursor, goal);
7162 });
7163 });
7164
7165 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7166 {
7167 cx.propagate();
7168 }
7169 }
7170
7171 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7172 let Some(row_count) = self.visible_row_count() else {
7173 return;
7174 };
7175
7176 let text_layout_details = &self.text_layout_details(cx);
7177
7178 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7179 s.move_heads_with(|map, head, goal| {
7180 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7181 })
7182 })
7183 }
7184
7185 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7186 if self.take_rename(true, cx).is_some() {
7187 return;
7188 }
7189
7190 if self
7191 .context_menu
7192 .write()
7193 .as_mut()
7194 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7195 .unwrap_or(false)
7196 {
7197 return;
7198 }
7199
7200 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7201 cx.propagate();
7202 return;
7203 }
7204
7205 let Some(row_count) = self.visible_row_count() else {
7206 return;
7207 };
7208
7209 let autoscroll = if action.center_cursor {
7210 Autoscroll::center()
7211 } else {
7212 Autoscroll::fit()
7213 };
7214
7215 let text_layout_details = &self.text_layout_details(cx);
7216 self.change_selections(Some(autoscroll), cx, |s| {
7217 let line_mode = s.line_mode;
7218 s.move_with(|map, selection| {
7219 if !selection.is_empty() && !line_mode {
7220 selection.goal = SelectionGoal::None;
7221 }
7222 let (cursor, goal) = movement::down_by_rows(
7223 map,
7224 selection.end,
7225 row_count,
7226 selection.goal,
7227 false,
7228 &text_layout_details,
7229 );
7230 selection.collapse_to(cursor, goal);
7231 });
7232 });
7233 }
7234
7235 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7236 let text_layout_details = &self.text_layout_details(cx);
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 s.move_heads_with(|map, head, goal| {
7239 movement::down(map, head, goal, false, &text_layout_details)
7240 })
7241 });
7242 }
7243
7244 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7245 if let Some(context_menu) = self.context_menu.write().as_mut() {
7246 context_menu.select_first(self.project.as_ref(), cx);
7247 }
7248 }
7249
7250 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7251 if let Some(context_menu) = self.context_menu.write().as_mut() {
7252 context_menu.select_prev(self.project.as_ref(), cx);
7253 }
7254 }
7255
7256 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7257 if let Some(context_menu) = self.context_menu.write().as_mut() {
7258 context_menu.select_next(self.project.as_ref(), cx);
7259 }
7260 }
7261
7262 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7263 if let Some(context_menu) = self.context_menu.write().as_mut() {
7264 context_menu.select_last(self.project.as_ref(), cx);
7265 }
7266 }
7267
7268 pub fn move_to_previous_word_start(
7269 &mut self,
7270 _: &MoveToPreviousWordStart,
7271 cx: &mut ViewContext<Self>,
7272 ) {
7273 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 s.move_cursors_with(|map, head, _| {
7275 (
7276 movement::previous_word_start(map, head),
7277 SelectionGoal::None,
7278 )
7279 });
7280 })
7281 }
7282
7283 pub fn move_to_previous_subword_start(
7284 &mut self,
7285 _: &MoveToPreviousSubwordStart,
7286 cx: &mut ViewContext<Self>,
7287 ) {
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 s.move_cursors_with(|map, head, _| {
7290 (
7291 movement::previous_subword_start(map, head),
7292 SelectionGoal::None,
7293 )
7294 });
7295 })
7296 }
7297
7298 pub fn select_to_previous_word_start(
7299 &mut self,
7300 _: &SelectToPreviousWordStart,
7301 cx: &mut ViewContext<Self>,
7302 ) {
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 s.move_heads_with(|map, head, _| {
7305 (
7306 movement::previous_word_start(map, head),
7307 SelectionGoal::None,
7308 )
7309 });
7310 })
7311 }
7312
7313 pub fn select_to_previous_subword_start(
7314 &mut self,
7315 _: &SelectToPreviousSubwordStart,
7316 cx: &mut ViewContext<Self>,
7317 ) {
7318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7319 s.move_heads_with(|map, head, _| {
7320 (
7321 movement::previous_subword_start(map, head),
7322 SelectionGoal::None,
7323 )
7324 });
7325 })
7326 }
7327
7328 pub fn delete_to_previous_word_start(
7329 &mut self,
7330 action: &DeleteToPreviousWordStart,
7331 cx: &mut ViewContext<Self>,
7332 ) {
7333 self.transact(cx, |this, cx| {
7334 this.select_autoclose_pair(cx);
7335 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7336 let line_mode = s.line_mode;
7337 s.move_with(|map, selection| {
7338 if selection.is_empty() && !line_mode {
7339 let cursor = if action.ignore_newlines {
7340 movement::previous_word_start(map, selection.head())
7341 } else {
7342 movement::previous_word_start_or_newline(map, selection.head())
7343 };
7344 selection.set_head(cursor, SelectionGoal::None);
7345 }
7346 });
7347 });
7348 this.insert("", cx);
7349 });
7350 }
7351
7352 pub fn delete_to_previous_subword_start(
7353 &mut self,
7354 _: &DeleteToPreviousSubwordStart,
7355 cx: &mut ViewContext<Self>,
7356 ) {
7357 self.transact(cx, |this, cx| {
7358 this.select_autoclose_pair(cx);
7359 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7360 let line_mode = s.line_mode;
7361 s.move_with(|map, selection| {
7362 if selection.is_empty() && !line_mode {
7363 let cursor = movement::previous_subword_start(map, selection.head());
7364 selection.set_head(cursor, SelectionGoal::None);
7365 }
7366 });
7367 });
7368 this.insert("", cx);
7369 });
7370 }
7371
7372 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7373 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7374 s.move_cursors_with(|map, head, _| {
7375 (movement::next_word_end(map, head), SelectionGoal::None)
7376 });
7377 })
7378 }
7379
7380 pub fn move_to_next_subword_end(
7381 &mut self,
7382 _: &MoveToNextSubwordEnd,
7383 cx: &mut ViewContext<Self>,
7384 ) {
7385 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7386 s.move_cursors_with(|map, head, _| {
7387 (movement::next_subword_end(map, head), SelectionGoal::None)
7388 });
7389 })
7390 }
7391
7392 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7394 s.move_heads_with(|map, head, _| {
7395 (movement::next_word_end(map, head), SelectionGoal::None)
7396 });
7397 })
7398 }
7399
7400 pub fn select_to_next_subword_end(
7401 &mut self,
7402 _: &SelectToNextSubwordEnd,
7403 cx: &mut ViewContext<Self>,
7404 ) {
7405 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7406 s.move_heads_with(|map, head, _| {
7407 (movement::next_subword_end(map, head), SelectionGoal::None)
7408 });
7409 })
7410 }
7411
7412 pub fn delete_to_next_word_end(
7413 &mut self,
7414 action: &DeleteToNextWordEnd,
7415 cx: &mut ViewContext<Self>,
7416 ) {
7417 self.transact(cx, |this, cx| {
7418 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7419 let line_mode = s.line_mode;
7420 s.move_with(|map, selection| {
7421 if selection.is_empty() && !line_mode {
7422 let cursor = if action.ignore_newlines {
7423 movement::next_word_end(map, selection.head())
7424 } else {
7425 movement::next_word_end_or_newline(map, selection.head())
7426 };
7427 selection.set_head(cursor, SelectionGoal::None);
7428 }
7429 });
7430 });
7431 this.insert("", cx);
7432 });
7433 }
7434
7435 pub fn delete_to_next_subword_end(
7436 &mut self,
7437 _: &DeleteToNextSubwordEnd,
7438 cx: &mut ViewContext<Self>,
7439 ) {
7440 self.transact(cx, |this, cx| {
7441 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7442 s.move_with(|map, selection| {
7443 if selection.is_empty() {
7444 let cursor = movement::next_subword_end(map, selection.head());
7445 selection.set_head(cursor, SelectionGoal::None);
7446 }
7447 });
7448 });
7449 this.insert("", cx);
7450 });
7451 }
7452
7453 pub fn move_to_beginning_of_line(
7454 &mut self,
7455 action: &MoveToBeginningOfLine,
7456 cx: &mut ViewContext<Self>,
7457 ) {
7458 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7459 s.move_cursors_with(|map, head, _| {
7460 (
7461 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7462 SelectionGoal::None,
7463 )
7464 });
7465 })
7466 }
7467
7468 pub fn select_to_beginning_of_line(
7469 &mut self,
7470 action: &SelectToBeginningOfLine,
7471 cx: &mut ViewContext<Self>,
7472 ) {
7473 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7474 s.move_heads_with(|map, head, _| {
7475 (
7476 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7477 SelectionGoal::None,
7478 )
7479 });
7480 });
7481 }
7482
7483 pub fn delete_to_beginning_of_line(
7484 &mut self,
7485 _: &DeleteToBeginningOfLine,
7486 cx: &mut ViewContext<Self>,
7487 ) {
7488 self.transact(cx, |this, cx| {
7489 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7490 s.move_with(|_, selection| {
7491 selection.reversed = true;
7492 });
7493 });
7494
7495 this.select_to_beginning_of_line(
7496 &SelectToBeginningOfLine {
7497 stop_at_soft_wraps: false,
7498 },
7499 cx,
7500 );
7501 this.backspace(&Backspace, cx);
7502 });
7503 }
7504
7505 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7506 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7507 s.move_cursors_with(|map, head, _| {
7508 (
7509 movement::line_end(map, head, action.stop_at_soft_wraps),
7510 SelectionGoal::None,
7511 )
7512 });
7513 })
7514 }
7515
7516 pub fn select_to_end_of_line(
7517 &mut self,
7518 action: &SelectToEndOfLine,
7519 cx: &mut ViewContext<Self>,
7520 ) {
7521 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7522 s.move_heads_with(|map, head, _| {
7523 (
7524 movement::line_end(map, head, action.stop_at_soft_wraps),
7525 SelectionGoal::None,
7526 )
7527 });
7528 })
7529 }
7530
7531 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7532 self.transact(cx, |this, cx| {
7533 this.select_to_end_of_line(
7534 &SelectToEndOfLine {
7535 stop_at_soft_wraps: false,
7536 },
7537 cx,
7538 );
7539 this.delete(&Delete, cx);
7540 });
7541 }
7542
7543 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7544 self.transact(cx, |this, cx| {
7545 this.select_to_end_of_line(
7546 &SelectToEndOfLine {
7547 stop_at_soft_wraps: false,
7548 },
7549 cx,
7550 );
7551 this.cut(&Cut, cx);
7552 });
7553 }
7554
7555 pub fn move_to_start_of_paragraph(
7556 &mut self,
7557 _: &MoveToStartOfParagraph,
7558 cx: &mut ViewContext<Self>,
7559 ) {
7560 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7561 cx.propagate();
7562 return;
7563 }
7564
7565 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7566 s.move_with(|map, selection| {
7567 selection.collapse_to(
7568 movement::start_of_paragraph(map, selection.head(), 1),
7569 SelectionGoal::None,
7570 )
7571 });
7572 })
7573 }
7574
7575 pub fn move_to_end_of_paragraph(
7576 &mut self,
7577 _: &MoveToEndOfParagraph,
7578 cx: &mut ViewContext<Self>,
7579 ) {
7580 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7581 cx.propagate();
7582 return;
7583 }
7584
7585 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7586 s.move_with(|map, selection| {
7587 selection.collapse_to(
7588 movement::end_of_paragraph(map, selection.head(), 1),
7589 SelectionGoal::None,
7590 )
7591 });
7592 })
7593 }
7594
7595 pub fn select_to_start_of_paragraph(
7596 &mut self,
7597 _: &SelectToStartOfParagraph,
7598 cx: &mut ViewContext<Self>,
7599 ) {
7600 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7601 cx.propagate();
7602 return;
7603 }
7604
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 s.move_heads_with(|map, head, _| {
7607 (
7608 movement::start_of_paragraph(map, head, 1),
7609 SelectionGoal::None,
7610 )
7611 });
7612 })
7613 }
7614
7615 pub fn select_to_end_of_paragraph(
7616 &mut self,
7617 _: &SelectToEndOfParagraph,
7618 cx: &mut ViewContext<Self>,
7619 ) {
7620 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7621 cx.propagate();
7622 return;
7623 }
7624
7625 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7626 s.move_heads_with(|map, head, _| {
7627 (
7628 movement::end_of_paragraph(map, head, 1),
7629 SelectionGoal::None,
7630 )
7631 });
7632 })
7633 }
7634
7635 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7636 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7637 cx.propagate();
7638 return;
7639 }
7640
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.select_ranges(vec![0..0]);
7643 });
7644 }
7645
7646 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7647 let mut selection = self.selections.last::<Point>(cx);
7648 selection.set_head(Point::zero(), SelectionGoal::None);
7649
7650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7651 s.select(vec![selection]);
7652 });
7653 }
7654
7655 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7656 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7657 cx.propagate();
7658 return;
7659 }
7660
7661 let cursor = self.buffer.read(cx).read(cx).len();
7662 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 s.select_ranges(vec![cursor..cursor])
7664 });
7665 }
7666
7667 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7668 self.nav_history = nav_history;
7669 }
7670
7671 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7672 self.nav_history.as_ref()
7673 }
7674
7675 fn push_to_nav_history(
7676 &mut self,
7677 cursor_anchor: Anchor,
7678 new_position: Option<Point>,
7679 cx: &mut ViewContext<Self>,
7680 ) {
7681 if let Some(nav_history) = self.nav_history.as_mut() {
7682 let buffer = self.buffer.read(cx).read(cx);
7683 let cursor_position = cursor_anchor.to_point(&buffer);
7684 let scroll_state = self.scroll_manager.anchor();
7685 let scroll_top_row = scroll_state.top_row(&buffer);
7686 drop(buffer);
7687
7688 if let Some(new_position) = new_position {
7689 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7690 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7691 return;
7692 }
7693 }
7694
7695 nav_history.push(
7696 Some(NavigationData {
7697 cursor_anchor,
7698 cursor_position,
7699 scroll_anchor: scroll_state,
7700 scroll_top_row,
7701 }),
7702 cx,
7703 );
7704 }
7705 }
7706
7707 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7708 let buffer = self.buffer.read(cx).snapshot(cx);
7709 let mut selection = self.selections.first::<usize>(cx);
7710 selection.set_head(buffer.len(), SelectionGoal::None);
7711 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7712 s.select(vec![selection]);
7713 });
7714 }
7715
7716 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7717 let end = self.buffer.read(cx).read(cx).len();
7718 self.change_selections(None, cx, |s| {
7719 s.select_ranges(vec![0..end]);
7720 });
7721 }
7722
7723 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7724 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7725 let mut selections = self.selections.all::<Point>(cx);
7726 let max_point = display_map.buffer_snapshot.max_point();
7727 for selection in &mut selections {
7728 let rows = selection.spanned_rows(true, &display_map);
7729 selection.start = Point::new(rows.start.0, 0);
7730 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7731 selection.reversed = false;
7732 }
7733 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7734 s.select(selections);
7735 });
7736 }
7737
7738 pub fn split_selection_into_lines(
7739 &mut self,
7740 _: &SplitSelectionIntoLines,
7741 cx: &mut ViewContext<Self>,
7742 ) {
7743 let mut to_unfold = Vec::new();
7744 let mut new_selection_ranges = Vec::new();
7745 {
7746 let selections = self.selections.all::<Point>(cx);
7747 let buffer = self.buffer.read(cx).read(cx);
7748 for selection in selections {
7749 for row in selection.start.row..selection.end.row {
7750 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7751 new_selection_ranges.push(cursor..cursor);
7752 }
7753 new_selection_ranges.push(selection.end..selection.end);
7754 to_unfold.push(selection.start..selection.end);
7755 }
7756 }
7757 self.unfold_ranges(to_unfold, true, true, cx);
7758 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7759 s.select_ranges(new_selection_ranges);
7760 });
7761 }
7762
7763 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7764 self.add_selection(true, cx);
7765 }
7766
7767 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7768 self.add_selection(false, cx);
7769 }
7770
7771 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7772 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7773 let mut selections = self.selections.all::<Point>(cx);
7774 let text_layout_details = self.text_layout_details(cx);
7775 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7776 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7777 let range = oldest_selection.display_range(&display_map).sorted();
7778
7779 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7780 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7781 let positions = start_x.min(end_x)..start_x.max(end_x);
7782
7783 selections.clear();
7784 let mut stack = Vec::new();
7785 for row in range.start.row().0..=range.end.row().0 {
7786 if let Some(selection) = self.selections.build_columnar_selection(
7787 &display_map,
7788 DisplayRow(row),
7789 &positions,
7790 oldest_selection.reversed,
7791 &text_layout_details,
7792 ) {
7793 stack.push(selection.id);
7794 selections.push(selection);
7795 }
7796 }
7797
7798 if above {
7799 stack.reverse();
7800 }
7801
7802 AddSelectionsState { above, stack }
7803 });
7804
7805 let last_added_selection = *state.stack.last().unwrap();
7806 let mut new_selections = Vec::new();
7807 if above == state.above {
7808 let end_row = if above {
7809 DisplayRow(0)
7810 } else {
7811 display_map.max_point().row()
7812 };
7813
7814 'outer: for selection in selections {
7815 if selection.id == last_added_selection {
7816 let range = selection.display_range(&display_map).sorted();
7817 debug_assert_eq!(range.start.row(), range.end.row());
7818 let mut row = range.start.row();
7819 let positions =
7820 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7821 px(start)..px(end)
7822 } else {
7823 let start_x =
7824 display_map.x_for_display_point(range.start, &text_layout_details);
7825 let end_x =
7826 display_map.x_for_display_point(range.end, &text_layout_details);
7827 start_x.min(end_x)..start_x.max(end_x)
7828 };
7829
7830 while row != end_row {
7831 if above {
7832 row.0 -= 1;
7833 } else {
7834 row.0 += 1;
7835 }
7836
7837 if let Some(new_selection) = self.selections.build_columnar_selection(
7838 &display_map,
7839 row,
7840 &positions,
7841 selection.reversed,
7842 &text_layout_details,
7843 ) {
7844 state.stack.push(new_selection.id);
7845 if above {
7846 new_selections.push(new_selection);
7847 new_selections.push(selection);
7848 } else {
7849 new_selections.push(selection);
7850 new_selections.push(new_selection);
7851 }
7852
7853 continue 'outer;
7854 }
7855 }
7856 }
7857
7858 new_selections.push(selection);
7859 }
7860 } else {
7861 new_selections = selections;
7862 new_selections.retain(|s| s.id != last_added_selection);
7863 state.stack.pop();
7864 }
7865
7866 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7867 s.select(new_selections);
7868 });
7869 if state.stack.len() > 1 {
7870 self.add_selections_state = Some(state);
7871 }
7872 }
7873
7874 pub fn select_next_match_internal(
7875 &mut self,
7876 display_map: &DisplaySnapshot,
7877 replace_newest: bool,
7878 autoscroll: Option<Autoscroll>,
7879 cx: &mut ViewContext<Self>,
7880 ) -> Result<()> {
7881 fn select_next_match_ranges(
7882 this: &mut Editor,
7883 range: Range<usize>,
7884 replace_newest: bool,
7885 auto_scroll: Option<Autoscroll>,
7886 cx: &mut ViewContext<Editor>,
7887 ) {
7888 this.unfold_ranges([range.clone()], false, true, cx);
7889 this.change_selections(auto_scroll, cx, |s| {
7890 if replace_newest {
7891 s.delete(s.newest_anchor().id);
7892 }
7893 s.insert_range(range.clone());
7894 });
7895 }
7896
7897 let buffer = &display_map.buffer_snapshot;
7898 let mut selections = self.selections.all::<usize>(cx);
7899 if let Some(mut select_next_state) = self.select_next_state.take() {
7900 let query = &select_next_state.query;
7901 if !select_next_state.done {
7902 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7903 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7904 let mut next_selected_range = None;
7905
7906 let bytes_after_last_selection =
7907 buffer.bytes_in_range(last_selection.end..buffer.len());
7908 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7909 let query_matches = query
7910 .stream_find_iter(bytes_after_last_selection)
7911 .map(|result| (last_selection.end, result))
7912 .chain(
7913 query
7914 .stream_find_iter(bytes_before_first_selection)
7915 .map(|result| (0, result)),
7916 );
7917
7918 for (start_offset, query_match) in query_matches {
7919 let query_match = query_match.unwrap(); // can only fail due to I/O
7920 let offset_range =
7921 start_offset + query_match.start()..start_offset + query_match.end();
7922 let display_range = offset_range.start.to_display_point(&display_map)
7923 ..offset_range.end.to_display_point(&display_map);
7924
7925 if !select_next_state.wordwise
7926 || (!movement::is_inside_word(&display_map, display_range.start)
7927 && !movement::is_inside_word(&display_map, display_range.end))
7928 {
7929 // TODO: This is n^2, because we might check all the selections
7930 if !selections
7931 .iter()
7932 .any(|selection| selection.range().overlaps(&offset_range))
7933 {
7934 next_selected_range = Some(offset_range);
7935 break;
7936 }
7937 }
7938 }
7939
7940 if let Some(next_selected_range) = next_selected_range {
7941 select_next_match_ranges(
7942 self,
7943 next_selected_range,
7944 replace_newest,
7945 autoscroll,
7946 cx,
7947 );
7948 } else {
7949 select_next_state.done = true;
7950 }
7951 }
7952
7953 self.select_next_state = Some(select_next_state);
7954 } else {
7955 let mut only_carets = true;
7956 let mut same_text_selected = true;
7957 let mut selected_text = None;
7958
7959 let mut selections_iter = selections.iter().peekable();
7960 while let Some(selection) = selections_iter.next() {
7961 if selection.start != selection.end {
7962 only_carets = false;
7963 }
7964
7965 if same_text_selected {
7966 if selected_text.is_none() {
7967 selected_text =
7968 Some(buffer.text_for_range(selection.range()).collect::<String>());
7969 }
7970
7971 if let Some(next_selection) = selections_iter.peek() {
7972 if next_selection.range().len() == selection.range().len() {
7973 let next_selected_text = buffer
7974 .text_for_range(next_selection.range())
7975 .collect::<String>();
7976 if Some(next_selected_text) != selected_text {
7977 same_text_selected = false;
7978 selected_text = None;
7979 }
7980 } else {
7981 same_text_selected = false;
7982 selected_text = None;
7983 }
7984 }
7985 }
7986 }
7987
7988 if only_carets {
7989 for selection in &mut selections {
7990 let word_range = movement::surrounding_word(
7991 &display_map,
7992 selection.start.to_display_point(&display_map),
7993 );
7994 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7995 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7996 selection.goal = SelectionGoal::None;
7997 selection.reversed = false;
7998 select_next_match_ranges(
7999 self,
8000 selection.start..selection.end,
8001 replace_newest,
8002 autoscroll,
8003 cx,
8004 );
8005 }
8006
8007 if selections.len() == 1 {
8008 let selection = selections
8009 .last()
8010 .expect("ensured that there's only one selection");
8011 let query = buffer
8012 .text_for_range(selection.start..selection.end)
8013 .collect::<String>();
8014 let is_empty = query.is_empty();
8015 let select_state = SelectNextState {
8016 query: AhoCorasick::new(&[query])?,
8017 wordwise: true,
8018 done: is_empty,
8019 };
8020 self.select_next_state = Some(select_state);
8021 } else {
8022 self.select_next_state = None;
8023 }
8024 } else if let Some(selected_text) = selected_text {
8025 self.select_next_state = Some(SelectNextState {
8026 query: AhoCorasick::new(&[selected_text])?,
8027 wordwise: false,
8028 done: false,
8029 });
8030 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8031 }
8032 }
8033 Ok(())
8034 }
8035
8036 pub fn select_all_matches(
8037 &mut self,
8038 _action: &SelectAllMatches,
8039 cx: &mut ViewContext<Self>,
8040 ) -> Result<()> {
8041 self.push_to_selection_history();
8042 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8043
8044 self.select_next_match_internal(&display_map, false, None, cx)?;
8045 let Some(select_next_state) = self.select_next_state.as_mut() else {
8046 return Ok(());
8047 };
8048 if select_next_state.done {
8049 return Ok(());
8050 }
8051
8052 let mut new_selections = self.selections.all::<usize>(cx);
8053
8054 let buffer = &display_map.buffer_snapshot;
8055 let query_matches = select_next_state
8056 .query
8057 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8058
8059 for query_match in query_matches {
8060 let query_match = query_match.unwrap(); // can only fail due to I/O
8061 let offset_range = query_match.start()..query_match.end();
8062 let display_range = offset_range.start.to_display_point(&display_map)
8063 ..offset_range.end.to_display_point(&display_map);
8064
8065 if !select_next_state.wordwise
8066 || (!movement::is_inside_word(&display_map, display_range.start)
8067 && !movement::is_inside_word(&display_map, display_range.end))
8068 {
8069 self.selections.change_with(cx, |selections| {
8070 new_selections.push(Selection {
8071 id: selections.new_selection_id(),
8072 start: offset_range.start,
8073 end: offset_range.end,
8074 reversed: false,
8075 goal: SelectionGoal::None,
8076 });
8077 });
8078 }
8079 }
8080
8081 new_selections.sort_by_key(|selection| selection.start);
8082 let mut ix = 0;
8083 while ix + 1 < new_selections.len() {
8084 let current_selection = &new_selections[ix];
8085 let next_selection = &new_selections[ix + 1];
8086 if current_selection.range().overlaps(&next_selection.range()) {
8087 if current_selection.id < next_selection.id {
8088 new_selections.remove(ix + 1);
8089 } else {
8090 new_selections.remove(ix);
8091 }
8092 } else {
8093 ix += 1;
8094 }
8095 }
8096
8097 select_next_state.done = true;
8098 self.unfold_ranges(
8099 new_selections.iter().map(|selection| selection.range()),
8100 false,
8101 false,
8102 cx,
8103 );
8104 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8105 selections.select(new_selections)
8106 });
8107
8108 Ok(())
8109 }
8110
8111 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8112 self.push_to_selection_history();
8113 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8114 self.select_next_match_internal(
8115 &display_map,
8116 action.replace_newest,
8117 Some(Autoscroll::newest()),
8118 cx,
8119 )?;
8120 Ok(())
8121 }
8122
8123 pub fn select_previous(
8124 &mut self,
8125 action: &SelectPrevious,
8126 cx: &mut ViewContext<Self>,
8127 ) -> Result<()> {
8128 self.push_to_selection_history();
8129 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8130 let buffer = &display_map.buffer_snapshot;
8131 let mut selections = self.selections.all::<usize>(cx);
8132 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8133 let query = &select_prev_state.query;
8134 if !select_prev_state.done {
8135 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8136 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8137 let mut next_selected_range = None;
8138 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8139 let bytes_before_last_selection =
8140 buffer.reversed_bytes_in_range(0..last_selection.start);
8141 let bytes_after_first_selection =
8142 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8143 let query_matches = query
8144 .stream_find_iter(bytes_before_last_selection)
8145 .map(|result| (last_selection.start, result))
8146 .chain(
8147 query
8148 .stream_find_iter(bytes_after_first_selection)
8149 .map(|result| (buffer.len(), result)),
8150 );
8151 for (end_offset, query_match) in query_matches {
8152 let query_match = query_match.unwrap(); // can only fail due to I/O
8153 let offset_range =
8154 end_offset - query_match.end()..end_offset - query_match.start();
8155 let display_range = offset_range.start.to_display_point(&display_map)
8156 ..offset_range.end.to_display_point(&display_map);
8157
8158 if !select_prev_state.wordwise
8159 || (!movement::is_inside_word(&display_map, display_range.start)
8160 && !movement::is_inside_word(&display_map, display_range.end))
8161 {
8162 next_selected_range = Some(offset_range);
8163 break;
8164 }
8165 }
8166
8167 if let Some(next_selected_range) = next_selected_range {
8168 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8169 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8170 if action.replace_newest {
8171 s.delete(s.newest_anchor().id);
8172 }
8173 s.insert_range(next_selected_range);
8174 });
8175 } else {
8176 select_prev_state.done = true;
8177 }
8178 }
8179
8180 self.select_prev_state = Some(select_prev_state);
8181 } else {
8182 let mut only_carets = true;
8183 let mut same_text_selected = true;
8184 let mut selected_text = None;
8185
8186 let mut selections_iter = selections.iter().peekable();
8187 while let Some(selection) = selections_iter.next() {
8188 if selection.start != selection.end {
8189 only_carets = false;
8190 }
8191
8192 if same_text_selected {
8193 if selected_text.is_none() {
8194 selected_text =
8195 Some(buffer.text_for_range(selection.range()).collect::<String>());
8196 }
8197
8198 if let Some(next_selection) = selections_iter.peek() {
8199 if next_selection.range().len() == selection.range().len() {
8200 let next_selected_text = buffer
8201 .text_for_range(next_selection.range())
8202 .collect::<String>();
8203 if Some(next_selected_text) != selected_text {
8204 same_text_selected = false;
8205 selected_text = None;
8206 }
8207 } else {
8208 same_text_selected = false;
8209 selected_text = None;
8210 }
8211 }
8212 }
8213 }
8214
8215 if only_carets {
8216 for selection in &mut selections {
8217 let word_range = movement::surrounding_word(
8218 &display_map,
8219 selection.start.to_display_point(&display_map),
8220 );
8221 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8222 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8223 selection.goal = SelectionGoal::None;
8224 selection.reversed = false;
8225 }
8226 if selections.len() == 1 {
8227 let selection = selections
8228 .last()
8229 .expect("ensured that there's only one selection");
8230 let query = buffer
8231 .text_for_range(selection.start..selection.end)
8232 .collect::<String>();
8233 let is_empty = query.is_empty();
8234 let select_state = SelectNextState {
8235 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8236 wordwise: true,
8237 done: is_empty,
8238 };
8239 self.select_prev_state = Some(select_state);
8240 } else {
8241 self.select_prev_state = None;
8242 }
8243
8244 self.unfold_ranges(
8245 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8246 false,
8247 true,
8248 cx,
8249 );
8250 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8251 s.select(selections);
8252 });
8253 } else if let Some(selected_text) = selected_text {
8254 self.select_prev_state = Some(SelectNextState {
8255 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8256 wordwise: false,
8257 done: false,
8258 });
8259 self.select_previous(action, cx)?;
8260 }
8261 }
8262 Ok(())
8263 }
8264
8265 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8266 let text_layout_details = &self.text_layout_details(cx);
8267 self.transact(cx, |this, cx| {
8268 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8269 let mut edits = Vec::new();
8270 let mut selection_edit_ranges = Vec::new();
8271 let mut last_toggled_row = None;
8272 let snapshot = this.buffer.read(cx).read(cx);
8273 let empty_str: Arc<str> = Arc::default();
8274 let mut suffixes_inserted = Vec::new();
8275
8276 fn comment_prefix_range(
8277 snapshot: &MultiBufferSnapshot,
8278 row: MultiBufferRow,
8279 comment_prefix: &str,
8280 comment_prefix_whitespace: &str,
8281 ) -> Range<Point> {
8282 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8283
8284 let mut line_bytes = snapshot
8285 .bytes_in_range(start..snapshot.max_point())
8286 .flatten()
8287 .copied();
8288
8289 // If this line currently begins with the line comment prefix, then record
8290 // the range containing the prefix.
8291 if line_bytes
8292 .by_ref()
8293 .take(comment_prefix.len())
8294 .eq(comment_prefix.bytes())
8295 {
8296 // Include any whitespace that matches the comment prefix.
8297 let matching_whitespace_len = line_bytes
8298 .zip(comment_prefix_whitespace.bytes())
8299 .take_while(|(a, b)| a == b)
8300 .count() as u32;
8301 let end = Point::new(
8302 start.row,
8303 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8304 );
8305 start..end
8306 } else {
8307 start..start
8308 }
8309 }
8310
8311 fn comment_suffix_range(
8312 snapshot: &MultiBufferSnapshot,
8313 row: MultiBufferRow,
8314 comment_suffix: &str,
8315 comment_suffix_has_leading_space: bool,
8316 ) -> Range<Point> {
8317 let end = Point::new(row.0, snapshot.line_len(row));
8318 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8319
8320 let mut line_end_bytes = snapshot
8321 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8322 .flatten()
8323 .copied();
8324
8325 let leading_space_len = if suffix_start_column > 0
8326 && line_end_bytes.next() == Some(b' ')
8327 && comment_suffix_has_leading_space
8328 {
8329 1
8330 } else {
8331 0
8332 };
8333
8334 // If this line currently begins with the line comment prefix, then record
8335 // the range containing the prefix.
8336 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8337 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8338 start..end
8339 } else {
8340 end..end
8341 }
8342 }
8343
8344 // TODO: Handle selections that cross excerpts
8345 for selection in &mut selections {
8346 let start_column = snapshot
8347 .indent_size_for_line(MultiBufferRow(selection.start.row))
8348 .len;
8349 let language = if let Some(language) =
8350 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8351 {
8352 language
8353 } else {
8354 continue;
8355 };
8356
8357 selection_edit_ranges.clear();
8358
8359 // If multiple selections contain a given row, avoid processing that
8360 // row more than once.
8361 let mut start_row = MultiBufferRow(selection.start.row);
8362 if last_toggled_row == Some(start_row) {
8363 start_row = start_row.next_row();
8364 }
8365 let end_row =
8366 if selection.end.row > selection.start.row && selection.end.column == 0 {
8367 MultiBufferRow(selection.end.row - 1)
8368 } else {
8369 MultiBufferRow(selection.end.row)
8370 };
8371 last_toggled_row = Some(end_row);
8372
8373 if start_row > end_row {
8374 continue;
8375 }
8376
8377 // If the language has line comments, toggle those.
8378 let full_comment_prefixes = language.line_comment_prefixes();
8379 if !full_comment_prefixes.is_empty() {
8380 let first_prefix = full_comment_prefixes
8381 .first()
8382 .expect("prefixes is non-empty");
8383 let prefix_trimmed_lengths = full_comment_prefixes
8384 .iter()
8385 .map(|p| p.trim_end_matches(' ').len())
8386 .collect::<SmallVec<[usize; 4]>>();
8387
8388 let mut all_selection_lines_are_comments = true;
8389
8390 for row in start_row.0..=end_row.0 {
8391 let row = MultiBufferRow(row);
8392 if start_row < end_row && snapshot.is_line_blank(row) {
8393 continue;
8394 }
8395
8396 let prefix_range = full_comment_prefixes
8397 .iter()
8398 .zip(prefix_trimmed_lengths.iter().copied())
8399 .map(|(prefix, trimmed_prefix_len)| {
8400 comment_prefix_range(
8401 snapshot.deref(),
8402 row,
8403 &prefix[..trimmed_prefix_len],
8404 &prefix[trimmed_prefix_len..],
8405 )
8406 })
8407 .max_by_key(|range| range.end.column - range.start.column)
8408 .expect("prefixes is non-empty");
8409
8410 if prefix_range.is_empty() {
8411 all_selection_lines_are_comments = false;
8412 }
8413
8414 selection_edit_ranges.push(prefix_range);
8415 }
8416
8417 if all_selection_lines_are_comments {
8418 edits.extend(
8419 selection_edit_ranges
8420 .iter()
8421 .cloned()
8422 .map(|range| (range, empty_str.clone())),
8423 );
8424 } else {
8425 let min_column = selection_edit_ranges
8426 .iter()
8427 .map(|range| range.start.column)
8428 .min()
8429 .unwrap_or(0);
8430 edits.extend(selection_edit_ranges.iter().map(|range| {
8431 let position = Point::new(range.start.row, min_column);
8432 (position..position, first_prefix.clone())
8433 }));
8434 }
8435 } else if let Some((full_comment_prefix, comment_suffix)) =
8436 language.block_comment_delimiters()
8437 {
8438 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8439 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8440 let prefix_range = comment_prefix_range(
8441 snapshot.deref(),
8442 start_row,
8443 comment_prefix,
8444 comment_prefix_whitespace,
8445 );
8446 let suffix_range = comment_suffix_range(
8447 snapshot.deref(),
8448 end_row,
8449 comment_suffix.trim_start_matches(' '),
8450 comment_suffix.starts_with(' '),
8451 );
8452
8453 if prefix_range.is_empty() || suffix_range.is_empty() {
8454 edits.push((
8455 prefix_range.start..prefix_range.start,
8456 full_comment_prefix.clone(),
8457 ));
8458 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8459 suffixes_inserted.push((end_row, comment_suffix.len()));
8460 } else {
8461 edits.push((prefix_range, empty_str.clone()));
8462 edits.push((suffix_range, empty_str.clone()));
8463 }
8464 } else {
8465 continue;
8466 }
8467 }
8468
8469 drop(snapshot);
8470 this.buffer.update(cx, |buffer, cx| {
8471 buffer.edit(edits, None, cx);
8472 });
8473
8474 // Adjust selections so that they end before any comment suffixes that
8475 // were inserted.
8476 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8477 let mut selections = this.selections.all::<Point>(cx);
8478 let snapshot = this.buffer.read(cx).read(cx);
8479 for selection in &mut selections {
8480 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8481 match row.cmp(&MultiBufferRow(selection.end.row)) {
8482 Ordering::Less => {
8483 suffixes_inserted.next();
8484 continue;
8485 }
8486 Ordering::Greater => break,
8487 Ordering::Equal => {
8488 if selection.end.column == snapshot.line_len(row) {
8489 if selection.is_empty() {
8490 selection.start.column -= suffix_len as u32;
8491 }
8492 selection.end.column -= suffix_len as u32;
8493 }
8494 break;
8495 }
8496 }
8497 }
8498 }
8499
8500 drop(snapshot);
8501 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8502
8503 let selections = this.selections.all::<Point>(cx);
8504 let selections_on_single_row = selections.windows(2).all(|selections| {
8505 selections[0].start.row == selections[1].start.row
8506 && selections[0].end.row == selections[1].end.row
8507 && selections[0].start.row == selections[0].end.row
8508 });
8509 let selections_selecting = selections
8510 .iter()
8511 .any(|selection| selection.start != selection.end);
8512 let advance_downwards = action.advance_downwards
8513 && selections_on_single_row
8514 && !selections_selecting
8515 && !matches!(this.mode, EditorMode::SingleLine { .. });
8516
8517 if advance_downwards {
8518 let snapshot = this.buffer.read(cx).snapshot(cx);
8519
8520 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8521 s.move_cursors_with(|display_snapshot, display_point, _| {
8522 let mut point = display_point.to_point(display_snapshot);
8523 point.row += 1;
8524 point = snapshot.clip_point(point, Bias::Left);
8525 let display_point = point.to_display_point(display_snapshot);
8526 let goal = SelectionGoal::HorizontalPosition(
8527 display_snapshot
8528 .x_for_display_point(display_point, &text_layout_details)
8529 .into(),
8530 );
8531 (display_point, goal)
8532 })
8533 });
8534 }
8535 });
8536 }
8537
8538 pub fn select_enclosing_symbol(
8539 &mut self,
8540 _: &SelectEnclosingSymbol,
8541 cx: &mut ViewContext<Self>,
8542 ) {
8543 let buffer = self.buffer.read(cx).snapshot(cx);
8544 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8545
8546 fn update_selection(
8547 selection: &Selection<usize>,
8548 buffer_snap: &MultiBufferSnapshot,
8549 ) -> Option<Selection<usize>> {
8550 let cursor = selection.head();
8551 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8552 for symbol in symbols.iter().rev() {
8553 let start = symbol.range.start.to_offset(&buffer_snap);
8554 let end = symbol.range.end.to_offset(&buffer_snap);
8555 let new_range = start..end;
8556 if start < selection.start || end > selection.end {
8557 return Some(Selection {
8558 id: selection.id,
8559 start: new_range.start,
8560 end: new_range.end,
8561 goal: SelectionGoal::None,
8562 reversed: selection.reversed,
8563 });
8564 }
8565 }
8566 None
8567 }
8568
8569 let mut selected_larger_symbol = false;
8570 let new_selections = old_selections
8571 .iter()
8572 .map(|selection| match update_selection(selection, &buffer) {
8573 Some(new_selection) => {
8574 if new_selection.range() != selection.range() {
8575 selected_larger_symbol = true;
8576 }
8577 new_selection
8578 }
8579 None => selection.clone(),
8580 })
8581 .collect::<Vec<_>>();
8582
8583 if selected_larger_symbol {
8584 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8585 s.select(new_selections);
8586 });
8587 }
8588 }
8589
8590 pub fn select_larger_syntax_node(
8591 &mut self,
8592 _: &SelectLargerSyntaxNode,
8593 cx: &mut ViewContext<Self>,
8594 ) {
8595 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8596 let buffer = self.buffer.read(cx).snapshot(cx);
8597 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8598
8599 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8600 let mut selected_larger_node = false;
8601 let new_selections = old_selections
8602 .iter()
8603 .map(|selection| {
8604 let old_range = selection.start..selection.end;
8605 let mut new_range = old_range.clone();
8606 while let Some(containing_range) =
8607 buffer.range_for_syntax_ancestor(new_range.clone())
8608 {
8609 new_range = containing_range;
8610 if !display_map.intersects_fold(new_range.start)
8611 && !display_map.intersects_fold(new_range.end)
8612 {
8613 break;
8614 }
8615 }
8616
8617 selected_larger_node |= new_range != old_range;
8618 Selection {
8619 id: selection.id,
8620 start: new_range.start,
8621 end: new_range.end,
8622 goal: SelectionGoal::None,
8623 reversed: selection.reversed,
8624 }
8625 })
8626 .collect::<Vec<_>>();
8627
8628 if selected_larger_node {
8629 stack.push(old_selections);
8630 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8631 s.select(new_selections);
8632 });
8633 }
8634 self.select_larger_syntax_node_stack = stack;
8635 }
8636
8637 pub fn select_smaller_syntax_node(
8638 &mut self,
8639 _: &SelectSmallerSyntaxNode,
8640 cx: &mut ViewContext<Self>,
8641 ) {
8642 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8643 if let Some(selections) = stack.pop() {
8644 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8645 s.select(selections.to_vec());
8646 });
8647 }
8648 self.select_larger_syntax_node_stack = stack;
8649 }
8650
8651 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8652 if !EditorSettings::get_global(cx).gutter.runnables {
8653 self.clear_tasks();
8654 return Task::ready(());
8655 }
8656 let project = self.project.clone();
8657 cx.spawn(|this, mut cx| async move {
8658 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8659 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8660 }) else {
8661 return;
8662 };
8663
8664 let Some(project) = project else {
8665 return;
8666 };
8667
8668 let hide_runnables = project
8669 .update(&mut cx, |project, cx| {
8670 // Do not display any test indicators in non-dev server remote projects.
8671 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8672 })
8673 .unwrap_or(true);
8674 if hide_runnables {
8675 return;
8676 }
8677 let new_rows =
8678 cx.background_executor()
8679 .spawn({
8680 let snapshot = display_snapshot.clone();
8681 async move {
8682 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8683 }
8684 })
8685 .await;
8686 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8687
8688 this.update(&mut cx, |this, _| {
8689 this.clear_tasks();
8690 for (key, value) in rows {
8691 this.insert_tasks(key, value);
8692 }
8693 })
8694 .ok();
8695 })
8696 }
8697 fn fetch_runnable_ranges(
8698 snapshot: &DisplaySnapshot,
8699 range: Range<Anchor>,
8700 ) -> Vec<language::RunnableRange> {
8701 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8702 }
8703
8704 fn runnable_rows(
8705 project: Model<Project>,
8706 snapshot: DisplaySnapshot,
8707 runnable_ranges: Vec<RunnableRange>,
8708 mut cx: AsyncWindowContext,
8709 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8710 runnable_ranges
8711 .into_iter()
8712 .filter_map(|mut runnable| {
8713 let tasks = cx
8714 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8715 .ok()?;
8716 if tasks.is_empty() {
8717 return None;
8718 }
8719
8720 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8721
8722 let row = snapshot
8723 .buffer_snapshot
8724 .buffer_line_for_row(MultiBufferRow(point.row))?
8725 .1
8726 .start
8727 .row;
8728
8729 let context_range =
8730 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8731 Some((
8732 (runnable.buffer_id, row),
8733 RunnableTasks {
8734 templates: tasks,
8735 offset: MultiBufferOffset(runnable.run_range.start),
8736 context_range,
8737 column: point.column,
8738 extra_variables: runnable.extra_captures,
8739 },
8740 ))
8741 })
8742 .collect()
8743 }
8744
8745 fn templates_with_tags(
8746 project: &Model<Project>,
8747 runnable: &mut Runnable,
8748 cx: &WindowContext<'_>,
8749 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8750 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8751 let (worktree_id, file) = project
8752 .buffer_for_id(runnable.buffer, cx)
8753 .and_then(|buffer| buffer.read(cx).file())
8754 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8755 .unzip();
8756
8757 (project.task_inventory().clone(), worktree_id, file)
8758 });
8759
8760 let inventory = inventory.read(cx);
8761 let tags = mem::take(&mut runnable.tags);
8762 let mut tags: Vec<_> = tags
8763 .into_iter()
8764 .flat_map(|tag| {
8765 let tag = tag.0.clone();
8766 inventory
8767 .list_tasks(
8768 file.clone(),
8769 Some(runnable.language.clone()),
8770 worktree_id,
8771 cx,
8772 )
8773 .into_iter()
8774 .filter(move |(_, template)| {
8775 template.tags.iter().any(|source_tag| source_tag == &tag)
8776 })
8777 })
8778 .sorted_by_key(|(kind, _)| kind.to_owned())
8779 .collect();
8780 if let Some((leading_tag_source, _)) = tags.first() {
8781 // Strongest source wins; if we have worktree tag binding, prefer that to
8782 // global and language bindings;
8783 // if we have a global binding, prefer that to language binding.
8784 let first_mismatch = tags
8785 .iter()
8786 .position(|(tag_source, _)| tag_source != leading_tag_source);
8787 if let Some(index) = first_mismatch {
8788 tags.truncate(index);
8789 }
8790 }
8791
8792 tags
8793 }
8794
8795 pub fn move_to_enclosing_bracket(
8796 &mut self,
8797 _: &MoveToEnclosingBracket,
8798 cx: &mut ViewContext<Self>,
8799 ) {
8800 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8801 s.move_offsets_with(|snapshot, selection| {
8802 let Some(enclosing_bracket_ranges) =
8803 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8804 else {
8805 return;
8806 };
8807
8808 let mut best_length = usize::MAX;
8809 let mut best_inside = false;
8810 let mut best_in_bracket_range = false;
8811 let mut best_destination = None;
8812 for (open, close) in enclosing_bracket_ranges {
8813 let close = close.to_inclusive();
8814 let length = close.end() - open.start;
8815 let inside = selection.start >= open.end && selection.end <= *close.start();
8816 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8817 || close.contains(&selection.head());
8818
8819 // If best is next to a bracket and current isn't, skip
8820 if !in_bracket_range && best_in_bracket_range {
8821 continue;
8822 }
8823
8824 // Prefer smaller lengths unless best is inside and current isn't
8825 if length > best_length && (best_inside || !inside) {
8826 continue;
8827 }
8828
8829 best_length = length;
8830 best_inside = inside;
8831 best_in_bracket_range = in_bracket_range;
8832 best_destination = Some(
8833 if close.contains(&selection.start) && close.contains(&selection.end) {
8834 if inside {
8835 open.end
8836 } else {
8837 open.start
8838 }
8839 } else {
8840 if inside {
8841 *close.start()
8842 } else {
8843 *close.end()
8844 }
8845 },
8846 );
8847 }
8848
8849 if let Some(destination) = best_destination {
8850 selection.collapse_to(destination, SelectionGoal::None);
8851 }
8852 })
8853 });
8854 }
8855
8856 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8857 self.end_selection(cx);
8858 self.selection_history.mode = SelectionHistoryMode::Undoing;
8859 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8860 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8861 self.select_next_state = entry.select_next_state;
8862 self.select_prev_state = entry.select_prev_state;
8863 self.add_selections_state = entry.add_selections_state;
8864 self.request_autoscroll(Autoscroll::newest(), cx);
8865 }
8866 self.selection_history.mode = SelectionHistoryMode::Normal;
8867 }
8868
8869 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8870 self.end_selection(cx);
8871 self.selection_history.mode = SelectionHistoryMode::Redoing;
8872 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8873 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8874 self.select_next_state = entry.select_next_state;
8875 self.select_prev_state = entry.select_prev_state;
8876 self.add_selections_state = entry.add_selections_state;
8877 self.request_autoscroll(Autoscroll::newest(), cx);
8878 }
8879 self.selection_history.mode = SelectionHistoryMode::Normal;
8880 }
8881
8882 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8883 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8884 }
8885
8886 pub fn expand_excerpts_down(
8887 &mut self,
8888 action: &ExpandExcerptsDown,
8889 cx: &mut ViewContext<Self>,
8890 ) {
8891 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8892 }
8893
8894 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8895 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8896 }
8897
8898 pub fn expand_excerpts_for_direction(
8899 &mut self,
8900 lines: u32,
8901 direction: ExpandExcerptDirection,
8902 cx: &mut ViewContext<Self>,
8903 ) {
8904 let selections = self.selections.disjoint_anchors();
8905
8906 let lines = if lines == 0 {
8907 EditorSettings::get_global(cx).expand_excerpt_lines
8908 } else {
8909 lines
8910 };
8911
8912 self.buffer.update(cx, |buffer, cx| {
8913 buffer.expand_excerpts(
8914 selections
8915 .into_iter()
8916 .map(|selection| selection.head().excerpt_id)
8917 .dedup(),
8918 lines,
8919 direction,
8920 cx,
8921 )
8922 })
8923 }
8924
8925 pub fn expand_excerpt(
8926 &mut self,
8927 excerpt: ExcerptId,
8928 direction: ExpandExcerptDirection,
8929 cx: &mut ViewContext<Self>,
8930 ) {
8931 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8932 self.buffer.update(cx, |buffer, cx| {
8933 buffer.expand_excerpts([excerpt], lines, direction, cx)
8934 })
8935 }
8936
8937 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8938 self.go_to_diagnostic_impl(Direction::Next, cx)
8939 }
8940
8941 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8942 self.go_to_diagnostic_impl(Direction::Prev, cx)
8943 }
8944
8945 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8946 let buffer = self.buffer.read(cx).snapshot(cx);
8947 let selection = self.selections.newest::<usize>(cx);
8948
8949 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8950 if direction == Direction::Next {
8951 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8952 let (group_id, jump_to) = popover.activation_info();
8953 if self.activate_diagnostics(group_id, cx) {
8954 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8955 let mut new_selection = s.newest_anchor().clone();
8956 new_selection.collapse_to(jump_to, SelectionGoal::None);
8957 s.select_anchors(vec![new_selection.clone()]);
8958 });
8959 }
8960 return;
8961 }
8962 }
8963
8964 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8965 active_diagnostics
8966 .primary_range
8967 .to_offset(&buffer)
8968 .to_inclusive()
8969 });
8970 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8971 if active_primary_range.contains(&selection.head()) {
8972 *active_primary_range.start()
8973 } else {
8974 selection.head()
8975 }
8976 } else {
8977 selection.head()
8978 };
8979 let snapshot = self.snapshot(cx);
8980 loop {
8981 let diagnostics = if direction == Direction::Prev {
8982 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8983 } else {
8984 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8985 }
8986 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8987 let group = diagnostics
8988 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8989 // be sorted in a stable way
8990 // skip until we are at current active diagnostic, if it exists
8991 .skip_while(|entry| {
8992 (match direction {
8993 Direction::Prev => entry.range.start >= search_start,
8994 Direction::Next => entry.range.start <= search_start,
8995 }) && self
8996 .active_diagnostics
8997 .as_ref()
8998 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8999 })
9000 .find_map(|entry| {
9001 if entry.diagnostic.is_primary
9002 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9003 && !entry.range.is_empty()
9004 // if we match with the active diagnostic, skip it
9005 && Some(entry.diagnostic.group_id)
9006 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9007 {
9008 Some((entry.range, entry.diagnostic.group_id))
9009 } else {
9010 None
9011 }
9012 });
9013
9014 if let Some((primary_range, group_id)) = group {
9015 if self.activate_diagnostics(group_id, cx) {
9016 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9017 s.select(vec![Selection {
9018 id: selection.id,
9019 start: primary_range.start,
9020 end: primary_range.start,
9021 reversed: false,
9022 goal: SelectionGoal::None,
9023 }]);
9024 });
9025 }
9026 break;
9027 } else {
9028 // Cycle around to the start of the buffer, potentially moving back to the start of
9029 // the currently active diagnostic.
9030 active_primary_range.take();
9031 if direction == Direction::Prev {
9032 if search_start == buffer.len() {
9033 break;
9034 } else {
9035 search_start = buffer.len();
9036 }
9037 } else if search_start == 0 {
9038 break;
9039 } else {
9040 search_start = 0;
9041 }
9042 }
9043 }
9044 }
9045
9046 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9047 let snapshot = self
9048 .display_map
9049 .update(cx, |display_map, cx| display_map.snapshot(cx));
9050 let selection = self.selections.newest::<Point>(cx);
9051
9052 if !self.seek_in_direction(
9053 &snapshot,
9054 selection.head(),
9055 false,
9056 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9057 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9058 ),
9059 cx,
9060 ) {
9061 let wrapped_point = Point::zero();
9062 self.seek_in_direction(
9063 &snapshot,
9064 wrapped_point,
9065 true,
9066 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9067 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9068 ),
9069 cx,
9070 );
9071 }
9072 }
9073
9074 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9075 let snapshot = self
9076 .display_map
9077 .update(cx, |display_map, cx| display_map.snapshot(cx));
9078 let selection = self.selections.newest::<Point>(cx);
9079
9080 if !self.seek_in_direction(
9081 &snapshot,
9082 selection.head(),
9083 false,
9084 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9085 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9086 ),
9087 cx,
9088 ) {
9089 let wrapped_point = snapshot.buffer_snapshot.max_point();
9090 self.seek_in_direction(
9091 &snapshot,
9092 wrapped_point,
9093 true,
9094 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9095 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9096 ),
9097 cx,
9098 );
9099 }
9100 }
9101
9102 fn seek_in_direction(
9103 &mut self,
9104 snapshot: &DisplaySnapshot,
9105 initial_point: Point,
9106 is_wrapped: bool,
9107 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9108 cx: &mut ViewContext<Editor>,
9109 ) -> bool {
9110 let display_point = initial_point.to_display_point(snapshot);
9111 let mut hunks = hunks
9112 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9113 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9114 .dedup();
9115
9116 if let Some(hunk) = hunks.next() {
9117 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9118 let row = hunk.start_display_row();
9119 let point = DisplayPoint::new(row, 0);
9120 s.select_display_ranges([point..point]);
9121 });
9122
9123 true
9124 } else {
9125 false
9126 }
9127 }
9128
9129 pub fn go_to_definition(
9130 &mut self,
9131 _: &GoToDefinition,
9132 cx: &mut ViewContext<Self>,
9133 ) -> Task<Result<Navigated>> {
9134 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9135 cx.spawn(|editor, mut cx| async move {
9136 if definition.await? == Navigated::Yes {
9137 return Ok(Navigated::Yes);
9138 }
9139 match editor.update(&mut cx, |editor, cx| {
9140 editor.find_all_references(&FindAllReferences, cx)
9141 })? {
9142 Some(references) => references.await,
9143 None => Ok(Navigated::No),
9144 }
9145 })
9146 }
9147
9148 pub fn go_to_declaration(
9149 &mut self,
9150 _: &GoToDeclaration,
9151 cx: &mut ViewContext<Self>,
9152 ) -> Task<Result<Navigated>> {
9153 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9154 }
9155
9156 pub fn go_to_declaration_split(
9157 &mut self,
9158 _: &GoToDeclaration,
9159 cx: &mut ViewContext<Self>,
9160 ) -> Task<Result<Navigated>> {
9161 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9162 }
9163
9164 pub fn go_to_implementation(
9165 &mut self,
9166 _: &GoToImplementation,
9167 cx: &mut ViewContext<Self>,
9168 ) -> Task<Result<Navigated>> {
9169 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9170 }
9171
9172 pub fn go_to_implementation_split(
9173 &mut self,
9174 _: &GoToImplementationSplit,
9175 cx: &mut ViewContext<Self>,
9176 ) -> Task<Result<Navigated>> {
9177 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9178 }
9179
9180 pub fn go_to_type_definition(
9181 &mut self,
9182 _: &GoToTypeDefinition,
9183 cx: &mut ViewContext<Self>,
9184 ) -> Task<Result<Navigated>> {
9185 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9186 }
9187
9188 pub fn go_to_definition_split(
9189 &mut self,
9190 _: &GoToDefinitionSplit,
9191 cx: &mut ViewContext<Self>,
9192 ) -> Task<Result<Navigated>> {
9193 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9194 }
9195
9196 pub fn go_to_type_definition_split(
9197 &mut self,
9198 _: &GoToTypeDefinitionSplit,
9199 cx: &mut ViewContext<Self>,
9200 ) -> Task<Result<Navigated>> {
9201 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9202 }
9203
9204 fn go_to_definition_of_kind(
9205 &mut self,
9206 kind: GotoDefinitionKind,
9207 split: bool,
9208 cx: &mut ViewContext<Self>,
9209 ) -> Task<Result<Navigated>> {
9210 let Some(workspace) = self.workspace() else {
9211 return Task::ready(Ok(Navigated::No));
9212 };
9213 let buffer = self.buffer.read(cx);
9214 let head = self.selections.newest::<usize>(cx).head();
9215 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9216 text_anchor
9217 } else {
9218 return Task::ready(Ok(Navigated::No));
9219 };
9220
9221 let project = workspace.read(cx).project().clone();
9222 let definitions = project.update(cx, |project, cx| match kind {
9223 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9224 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9225 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9226 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9227 });
9228
9229 cx.spawn(|editor, mut cx| async move {
9230 let definitions = definitions.await?;
9231 let navigated = editor
9232 .update(&mut cx, |editor, cx| {
9233 editor.navigate_to_hover_links(
9234 Some(kind),
9235 definitions
9236 .into_iter()
9237 .filter(|location| {
9238 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9239 })
9240 .map(HoverLink::Text)
9241 .collect::<Vec<_>>(),
9242 split,
9243 cx,
9244 )
9245 })?
9246 .await?;
9247 anyhow::Ok(navigated)
9248 })
9249 }
9250
9251 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9252 let position = self.selections.newest_anchor().head();
9253 let Some((buffer, buffer_position)) =
9254 self.buffer.read(cx).text_anchor_for_position(position, cx)
9255 else {
9256 return;
9257 };
9258
9259 cx.spawn(|editor, mut cx| async move {
9260 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9261 editor.update(&mut cx, |_, cx| {
9262 cx.open_url(&url);
9263 })
9264 } else {
9265 Ok(())
9266 }
9267 })
9268 .detach();
9269 }
9270
9271 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9272 let Some(workspace) = self.workspace() else {
9273 return;
9274 };
9275
9276 let position = self.selections.newest_anchor().head();
9277
9278 let Some((buffer, buffer_position)) =
9279 self.buffer.read(cx).text_anchor_for_position(position, cx)
9280 else {
9281 return;
9282 };
9283
9284 let Some(project) = self.project.clone() else {
9285 return;
9286 };
9287
9288 cx.spawn(|_, mut cx| async move {
9289 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9290
9291 if let Some((_, path)) = result {
9292 workspace
9293 .update(&mut cx, |workspace, cx| {
9294 workspace.open_resolved_path(path, cx)
9295 })?
9296 .await?;
9297 }
9298 anyhow::Ok(())
9299 })
9300 .detach();
9301 }
9302
9303 pub(crate) fn navigate_to_hover_links(
9304 &mut self,
9305 kind: Option<GotoDefinitionKind>,
9306 mut definitions: Vec<HoverLink>,
9307 split: bool,
9308 cx: &mut ViewContext<Editor>,
9309 ) -> Task<Result<Navigated>> {
9310 // If there is one definition, just open it directly
9311 if definitions.len() == 1 {
9312 let definition = definitions.pop().unwrap();
9313
9314 enum TargetTaskResult {
9315 Location(Option<Location>),
9316 AlreadyNavigated,
9317 }
9318
9319 let target_task = match definition {
9320 HoverLink::Text(link) => {
9321 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9322 }
9323 HoverLink::InlayHint(lsp_location, server_id) => {
9324 let computation = self.compute_target_location(lsp_location, server_id, cx);
9325 cx.background_executor().spawn(async move {
9326 let location = computation.await?;
9327 Ok(TargetTaskResult::Location(location))
9328 })
9329 }
9330 HoverLink::Url(url) => {
9331 cx.open_url(&url);
9332 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9333 }
9334 HoverLink::File(path) => {
9335 if let Some(workspace) = self.workspace() {
9336 cx.spawn(|_, mut cx| async move {
9337 workspace
9338 .update(&mut cx, |workspace, cx| {
9339 workspace.open_resolved_path(path, cx)
9340 })?
9341 .await
9342 .map(|_| TargetTaskResult::AlreadyNavigated)
9343 })
9344 } else {
9345 Task::ready(Ok(TargetTaskResult::Location(None)))
9346 }
9347 }
9348 };
9349 cx.spawn(|editor, mut cx| async move {
9350 let target = match target_task.await.context("target resolution task")? {
9351 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9352 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9353 TargetTaskResult::Location(Some(target)) => target,
9354 };
9355
9356 editor.update(&mut cx, |editor, cx| {
9357 let Some(workspace) = editor.workspace() else {
9358 return Navigated::No;
9359 };
9360 let pane = workspace.read(cx).active_pane().clone();
9361
9362 let range = target.range.to_offset(target.buffer.read(cx));
9363 let range = editor.range_for_match(&range);
9364
9365 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9366 let buffer = target.buffer.read(cx);
9367 let range = check_multiline_range(buffer, range);
9368 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9369 s.select_ranges([range]);
9370 });
9371 } else {
9372 cx.window_context().defer(move |cx| {
9373 let target_editor: View<Self> =
9374 workspace.update(cx, |workspace, cx| {
9375 let pane = if split {
9376 workspace.adjacent_pane(cx)
9377 } else {
9378 workspace.active_pane().clone()
9379 };
9380
9381 workspace.open_project_item(
9382 pane,
9383 target.buffer.clone(),
9384 true,
9385 true,
9386 cx,
9387 )
9388 });
9389 target_editor.update(cx, |target_editor, cx| {
9390 // When selecting a definition in a different buffer, disable the nav history
9391 // to avoid creating a history entry at the previous cursor location.
9392 pane.update(cx, |pane, _| pane.disable_history());
9393 let buffer = target.buffer.read(cx);
9394 let range = check_multiline_range(buffer, range);
9395 target_editor.change_selections(
9396 Some(Autoscroll::focused()),
9397 cx,
9398 |s| {
9399 s.select_ranges([range]);
9400 },
9401 );
9402 pane.update(cx, |pane, _| pane.enable_history());
9403 });
9404 });
9405 }
9406 Navigated::Yes
9407 })
9408 })
9409 } else if !definitions.is_empty() {
9410 let replica_id = self.replica_id(cx);
9411 cx.spawn(|editor, mut cx| async move {
9412 let (title, location_tasks, workspace) = editor
9413 .update(&mut cx, |editor, cx| {
9414 let tab_kind = match kind {
9415 Some(GotoDefinitionKind::Implementation) => "Implementations",
9416 _ => "Definitions",
9417 };
9418 let title = definitions
9419 .iter()
9420 .find_map(|definition| match definition {
9421 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9422 let buffer = origin.buffer.read(cx);
9423 format!(
9424 "{} for {}",
9425 tab_kind,
9426 buffer
9427 .text_for_range(origin.range.clone())
9428 .collect::<String>()
9429 )
9430 }),
9431 HoverLink::InlayHint(_, _) => None,
9432 HoverLink::Url(_) => None,
9433 HoverLink::File(_) => None,
9434 })
9435 .unwrap_or(tab_kind.to_string());
9436 let location_tasks = definitions
9437 .into_iter()
9438 .map(|definition| match definition {
9439 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9440 HoverLink::InlayHint(lsp_location, server_id) => {
9441 editor.compute_target_location(lsp_location, server_id, cx)
9442 }
9443 HoverLink::Url(_) => Task::ready(Ok(None)),
9444 HoverLink::File(_) => Task::ready(Ok(None)),
9445 })
9446 .collect::<Vec<_>>();
9447 (title, location_tasks, editor.workspace().clone())
9448 })
9449 .context("location tasks preparation")?;
9450
9451 let locations = futures::future::join_all(location_tasks)
9452 .await
9453 .into_iter()
9454 .filter_map(|location| location.transpose())
9455 .collect::<Result<_>>()
9456 .context("location tasks")?;
9457
9458 let Some(workspace) = workspace else {
9459 return Ok(Navigated::No);
9460 };
9461 let opened = workspace
9462 .update(&mut cx, |workspace, cx| {
9463 Self::open_locations_in_multibuffer(
9464 workspace, locations, replica_id, title, split, cx,
9465 )
9466 })
9467 .ok();
9468
9469 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9470 })
9471 } else {
9472 Task::ready(Ok(Navigated::No))
9473 }
9474 }
9475
9476 fn compute_target_location(
9477 &self,
9478 lsp_location: lsp::Location,
9479 server_id: LanguageServerId,
9480 cx: &mut ViewContext<Editor>,
9481 ) -> Task<anyhow::Result<Option<Location>>> {
9482 let Some(project) = self.project.clone() else {
9483 return Task::Ready(Some(Ok(None)));
9484 };
9485
9486 cx.spawn(move |editor, mut cx| async move {
9487 let location_task = editor.update(&mut cx, |editor, cx| {
9488 project.update(cx, |project, cx| {
9489 let language_server_name =
9490 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9491 project
9492 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9493 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9494 });
9495 language_server_name.map(|language_server_name| {
9496 project.open_local_buffer_via_lsp(
9497 lsp_location.uri.clone(),
9498 server_id,
9499 language_server_name,
9500 cx,
9501 )
9502 })
9503 })
9504 })?;
9505 let location = match location_task {
9506 Some(task) => Some({
9507 let target_buffer_handle = task.await.context("open local buffer")?;
9508 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9509 let target_start = target_buffer
9510 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9511 let target_end = target_buffer
9512 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9513 target_buffer.anchor_after(target_start)
9514 ..target_buffer.anchor_before(target_end)
9515 })?;
9516 Location {
9517 buffer: target_buffer_handle,
9518 range,
9519 }
9520 }),
9521 None => None,
9522 };
9523 Ok(location)
9524 })
9525 }
9526
9527 pub fn find_all_references(
9528 &mut self,
9529 _: &FindAllReferences,
9530 cx: &mut ViewContext<Self>,
9531 ) -> Option<Task<Result<Navigated>>> {
9532 let multi_buffer = self.buffer.read(cx);
9533 let selection = self.selections.newest::<usize>(cx);
9534 let head = selection.head();
9535
9536 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9537 let head_anchor = multi_buffer_snapshot.anchor_at(
9538 head,
9539 if head < selection.tail() {
9540 Bias::Right
9541 } else {
9542 Bias::Left
9543 },
9544 );
9545
9546 match self
9547 .find_all_references_task_sources
9548 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9549 {
9550 Ok(_) => {
9551 log::info!(
9552 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9553 );
9554 return None;
9555 }
9556 Err(i) => {
9557 self.find_all_references_task_sources.insert(i, head_anchor);
9558 }
9559 }
9560
9561 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9562 let replica_id = self.replica_id(cx);
9563 let workspace = self.workspace()?;
9564 let project = workspace.read(cx).project().clone();
9565 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9566 Some(cx.spawn(|editor, mut cx| async move {
9567 let _cleanup = defer({
9568 let mut cx = cx.clone();
9569 move || {
9570 let _ = editor.update(&mut cx, |editor, _| {
9571 if let Ok(i) =
9572 editor
9573 .find_all_references_task_sources
9574 .binary_search_by(|anchor| {
9575 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9576 })
9577 {
9578 editor.find_all_references_task_sources.remove(i);
9579 }
9580 });
9581 }
9582 });
9583
9584 let locations = references.await?;
9585 if locations.is_empty() {
9586 return anyhow::Ok(Navigated::No);
9587 }
9588
9589 workspace.update(&mut cx, |workspace, cx| {
9590 let title = locations
9591 .first()
9592 .as_ref()
9593 .map(|location| {
9594 let buffer = location.buffer.read(cx);
9595 format!(
9596 "References to `{}`",
9597 buffer
9598 .text_for_range(location.range.clone())
9599 .collect::<String>()
9600 )
9601 })
9602 .unwrap();
9603 Self::open_locations_in_multibuffer(
9604 workspace, locations, replica_id, title, false, cx,
9605 );
9606 Navigated::Yes
9607 })
9608 }))
9609 }
9610
9611 /// Opens a multibuffer with the given project locations in it
9612 pub fn open_locations_in_multibuffer(
9613 workspace: &mut Workspace,
9614 mut locations: Vec<Location>,
9615 replica_id: ReplicaId,
9616 title: String,
9617 split: bool,
9618 cx: &mut ViewContext<Workspace>,
9619 ) {
9620 // If there are multiple definitions, open them in a multibuffer
9621 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9622 let mut locations = locations.into_iter().peekable();
9623 let mut ranges_to_highlight = Vec::new();
9624 let capability = workspace.project().read(cx).capability();
9625
9626 let excerpt_buffer = cx.new_model(|cx| {
9627 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9628 while let Some(location) = locations.next() {
9629 let buffer = location.buffer.read(cx);
9630 let mut ranges_for_buffer = Vec::new();
9631 let range = location.range.to_offset(buffer);
9632 ranges_for_buffer.push(range.clone());
9633
9634 while let Some(next_location) = locations.peek() {
9635 if next_location.buffer == location.buffer {
9636 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9637 locations.next();
9638 } else {
9639 break;
9640 }
9641 }
9642
9643 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9644 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9645 location.buffer.clone(),
9646 ranges_for_buffer,
9647 DEFAULT_MULTIBUFFER_CONTEXT,
9648 cx,
9649 ))
9650 }
9651
9652 multibuffer.with_title(title)
9653 });
9654
9655 let editor = cx.new_view(|cx| {
9656 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9657 });
9658 editor.update(cx, |editor, cx| {
9659 if let Some(first_range) = ranges_to_highlight.first() {
9660 editor.change_selections(None, cx, |selections| {
9661 selections.clear_disjoint();
9662 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9663 });
9664 }
9665 editor.highlight_background::<Self>(
9666 &ranges_to_highlight,
9667 |theme| theme.editor_highlighted_line_background,
9668 cx,
9669 );
9670 });
9671
9672 let item = Box::new(editor);
9673 let item_id = item.item_id();
9674
9675 if split {
9676 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9677 } else {
9678 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9679 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9680 pane.close_current_preview_item(cx)
9681 } else {
9682 None
9683 }
9684 });
9685 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9686 }
9687 workspace.active_pane().update(cx, |pane, cx| {
9688 pane.set_preview_item_id(Some(item_id), cx);
9689 });
9690 }
9691
9692 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9693 use language::ToOffset as _;
9694
9695 let project = self.project.clone()?;
9696 let selection = self.selections.newest_anchor().clone();
9697 let (cursor_buffer, cursor_buffer_position) = self
9698 .buffer
9699 .read(cx)
9700 .text_anchor_for_position(selection.head(), cx)?;
9701 let (tail_buffer, cursor_buffer_position_end) = self
9702 .buffer
9703 .read(cx)
9704 .text_anchor_for_position(selection.tail(), cx)?;
9705 if tail_buffer != cursor_buffer {
9706 return None;
9707 }
9708
9709 let snapshot = cursor_buffer.read(cx).snapshot();
9710 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9711 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9712 let prepare_rename = project.update(cx, |project, cx| {
9713 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9714 });
9715 drop(snapshot);
9716
9717 Some(cx.spawn(|this, mut cx| async move {
9718 let rename_range = if let Some(range) = prepare_rename.await? {
9719 Some(range)
9720 } else {
9721 this.update(&mut cx, |this, cx| {
9722 let buffer = this.buffer.read(cx).snapshot(cx);
9723 let mut buffer_highlights = this
9724 .document_highlights_for_position(selection.head(), &buffer)
9725 .filter(|highlight| {
9726 highlight.start.excerpt_id == selection.head().excerpt_id
9727 && highlight.end.excerpt_id == selection.head().excerpt_id
9728 });
9729 buffer_highlights
9730 .next()
9731 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9732 })?
9733 };
9734 if let Some(rename_range) = rename_range {
9735 this.update(&mut cx, |this, cx| {
9736 let snapshot = cursor_buffer.read(cx).snapshot();
9737 let rename_buffer_range = rename_range.to_offset(&snapshot);
9738 let cursor_offset_in_rename_range =
9739 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9740 let cursor_offset_in_rename_range_end =
9741 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9742
9743 this.take_rename(false, cx);
9744 let buffer = this.buffer.read(cx).read(cx);
9745 let cursor_offset = selection.head().to_offset(&buffer);
9746 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9747 let rename_end = rename_start + rename_buffer_range.len();
9748 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9749 let mut old_highlight_id = None;
9750 let old_name: Arc<str> = buffer
9751 .chunks(rename_start..rename_end, true)
9752 .map(|chunk| {
9753 if old_highlight_id.is_none() {
9754 old_highlight_id = chunk.syntax_highlight_id;
9755 }
9756 chunk.text
9757 })
9758 .collect::<String>()
9759 .into();
9760
9761 drop(buffer);
9762
9763 // Position the selection in the rename editor so that it matches the current selection.
9764 this.show_local_selections = false;
9765 let rename_editor = cx.new_view(|cx| {
9766 let mut editor = Editor::single_line(cx);
9767 editor.buffer.update(cx, |buffer, cx| {
9768 buffer.edit([(0..0, old_name.clone())], None, cx)
9769 });
9770 let rename_selection_range = match cursor_offset_in_rename_range
9771 .cmp(&cursor_offset_in_rename_range_end)
9772 {
9773 Ordering::Equal => {
9774 editor.select_all(&SelectAll, cx);
9775 return editor;
9776 }
9777 Ordering::Less => {
9778 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9779 }
9780 Ordering::Greater => {
9781 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9782 }
9783 };
9784 if rename_selection_range.end > old_name.len() {
9785 editor.select_all(&SelectAll, cx);
9786 } else {
9787 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9788 s.select_ranges([rename_selection_range]);
9789 });
9790 }
9791 editor
9792 });
9793 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9794 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9795 _ => {}
9796 })
9797 .detach();
9798
9799 let write_highlights =
9800 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9801 let read_highlights =
9802 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9803 let ranges = write_highlights
9804 .iter()
9805 .flat_map(|(_, ranges)| ranges.iter())
9806 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9807 .cloned()
9808 .collect();
9809
9810 this.highlight_text::<Rename>(
9811 ranges,
9812 HighlightStyle {
9813 fade_out: Some(0.6),
9814 ..Default::default()
9815 },
9816 cx,
9817 );
9818 let rename_focus_handle = rename_editor.focus_handle(cx);
9819 cx.focus(&rename_focus_handle);
9820 let block_id = this.insert_blocks(
9821 [BlockProperties {
9822 style: BlockStyle::Flex,
9823 position: range.start,
9824 height: 1,
9825 render: Box::new({
9826 let rename_editor = rename_editor.clone();
9827 move |cx: &mut BlockContext| {
9828 let mut text_style = cx.editor_style.text.clone();
9829 if let Some(highlight_style) = old_highlight_id
9830 .and_then(|h| h.style(&cx.editor_style.syntax))
9831 {
9832 text_style = text_style.highlight(highlight_style);
9833 }
9834 div()
9835 .pl(cx.anchor_x)
9836 .child(EditorElement::new(
9837 &rename_editor,
9838 EditorStyle {
9839 background: cx.theme().system().transparent,
9840 local_player: cx.editor_style.local_player,
9841 text: text_style,
9842 scrollbar_width: cx.editor_style.scrollbar_width,
9843 syntax: cx.editor_style.syntax.clone(),
9844 status: cx.editor_style.status.clone(),
9845 inlay_hints_style: HighlightStyle {
9846 color: Some(cx.theme().status().hint),
9847 font_weight: Some(FontWeight::BOLD),
9848 ..HighlightStyle::default()
9849 },
9850 suggestions_style: HighlightStyle {
9851 color: Some(cx.theme().status().predictive),
9852 ..HighlightStyle::default()
9853 },
9854 ..EditorStyle::default()
9855 },
9856 ))
9857 .into_any_element()
9858 }
9859 }),
9860 disposition: BlockDisposition::Below,
9861 priority: 0,
9862 }],
9863 Some(Autoscroll::fit()),
9864 cx,
9865 )[0];
9866 this.pending_rename = Some(RenameState {
9867 range,
9868 old_name,
9869 editor: rename_editor,
9870 block_id,
9871 });
9872 })?;
9873 }
9874
9875 Ok(())
9876 }))
9877 }
9878
9879 pub fn confirm_rename(
9880 &mut self,
9881 _: &ConfirmRename,
9882 cx: &mut ViewContext<Self>,
9883 ) -> Option<Task<Result<()>>> {
9884 let rename = self.take_rename(false, cx)?;
9885 let workspace = self.workspace()?;
9886 let (start_buffer, start) = self
9887 .buffer
9888 .read(cx)
9889 .text_anchor_for_position(rename.range.start, cx)?;
9890 let (end_buffer, end) = self
9891 .buffer
9892 .read(cx)
9893 .text_anchor_for_position(rename.range.end, cx)?;
9894 if start_buffer != end_buffer {
9895 return None;
9896 }
9897
9898 let buffer = start_buffer;
9899 let range = start..end;
9900 let old_name = rename.old_name;
9901 let new_name = rename.editor.read(cx).text(cx);
9902
9903 let rename = workspace
9904 .read(cx)
9905 .project()
9906 .clone()
9907 .update(cx, |project, cx| {
9908 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9909 });
9910 let workspace = workspace.downgrade();
9911
9912 Some(cx.spawn(|editor, mut cx| async move {
9913 let project_transaction = rename.await?;
9914 Self::open_project_transaction(
9915 &editor,
9916 workspace,
9917 project_transaction,
9918 format!("Rename: {} → {}", old_name, new_name),
9919 cx.clone(),
9920 )
9921 .await?;
9922
9923 editor.update(&mut cx, |editor, cx| {
9924 editor.refresh_document_highlights(cx);
9925 })?;
9926 Ok(())
9927 }))
9928 }
9929
9930 fn take_rename(
9931 &mut self,
9932 moving_cursor: bool,
9933 cx: &mut ViewContext<Self>,
9934 ) -> Option<RenameState> {
9935 let rename = self.pending_rename.take()?;
9936 if rename.editor.focus_handle(cx).is_focused(cx) {
9937 cx.focus(&self.focus_handle);
9938 }
9939
9940 self.remove_blocks(
9941 [rename.block_id].into_iter().collect(),
9942 Some(Autoscroll::fit()),
9943 cx,
9944 );
9945 self.clear_highlights::<Rename>(cx);
9946 self.show_local_selections = true;
9947
9948 if moving_cursor {
9949 let rename_editor = rename.editor.read(cx);
9950 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9951
9952 // Update the selection to match the position of the selection inside
9953 // the rename editor.
9954 let snapshot = self.buffer.read(cx).read(cx);
9955 let rename_range = rename.range.to_offset(&snapshot);
9956 let cursor_in_editor = snapshot
9957 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9958 .min(rename_range.end);
9959 drop(snapshot);
9960
9961 self.change_selections(None, cx, |s| {
9962 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9963 });
9964 } else {
9965 self.refresh_document_highlights(cx);
9966 }
9967
9968 Some(rename)
9969 }
9970
9971 pub fn pending_rename(&self) -> Option<&RenameState> {
9972 self.pending_rename.as_ref()
9973 }
9974
9975 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9976 let project = match &self.project {
9977 Some(project) => project.clone(),
9978 None => return None,
9979 };
9980
9981 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9982 }
9983
9984 fn perform_format(
9985 &mut self,
9986 project: Model<Project>,
9987 trigger: FormatTrigger,
9988 cx: &mut ViewContext<Self>,
9989 ) -> Task<Result<()>> {
9990 let buffer = self.buffer().clone();
9991 let mut buffers = buffer.read(cx).all_buffers();
9992 if trigger == FormatTrigger::Save {
9993 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9994 }
9995
9996 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9997 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9998
9999 cx.spawn(|_, mut cx| async move {
10000 let transaction = futures::select_biased! {
10001 () = timeout => {
10002 log::warn!("timed out waiting for formatting");
10003 None
10004 }
10005 transaction = format.log_err().fuse() => transaction,
10006 };
10007
10008 buffer
10009 .update(&mut cx, |buffer, cx| {
10010 if let Some(transaction) = transaction {
10011 if !buffer.is_singleton() {
10012 buffer.push_transaction(&transaction.0, cx);
10013 }
10014 }
10015
10016 cx.notify();
10017 })
10018 .ok();
10019
10020 Ok(())
10021 })
10022 }
10023
10024 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10025 if let Some(project) = self.project.clone() {
10026 self.buffer.update(cx, |multi_buffer, cx| {
10027 project.update(cx, |project, cx| {
10028 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10029 });
10030 })
10031 }
10032 }
10033
10034 fn cancel_language_server_work(
10035 &mut self,
10036 _: &CancelLanguageServerWork,
10037 cx: &mut ViewContext<Self>,
10038 ) {
10039 if let Some(project) = self.project.clone() {
10040 self.buffer.update(cx, |multi_buffer, cx| {
10041 project.update(cx, |project, cx| {
10042 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10043 });
10044 })
10045 }
10046 }
10047
10048 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10049 cx.show_character_palette();
10050 }
10051
10052 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10053 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10054 let buffer = self.buffer.read(cx).snapshot(cx);
10055 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10056 let is_valid = buffer
10057 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10058 .any(|entry| {
10059 entry.diagnostic.is_primary
10060 && !entry.range.is_empty()
10061 && entry.range.start == primary_range_start
10062 && entry.diagnostic.message == active_diagnostics.primary_message
10063 });
10064
10065 if is_valid != active_diagnostics.is_valid {
10066 active_diagnostics.is_valid = is_valid;
10067 let mut new_styles = HashMap::default();
10068 for (block_id, diagnostic) in &active_diagnostics.blocks {
10069 new_styles.insert(
10070 *block_id,
10071 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10072 );
10073 }
10074 self.display_map.update(cx, |display_map, _cx| {
10075 display_map.replace_blocks(new_styles)
10076 });
10077 }
10078 }
10079 }
10080
10081 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10082 self.dismiss_diagnostics(cx);
10083 let snapshot = self.snapshot(cx);
10084 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10085 let buffer = self.buffer.read(cx).snapshot(cx);
10086
10087 let mut primary_range = None;
10088 let mut primary_message = None;
10089 let mut group_end = Point::zero();
10090 let diagnostic_group = buffer
10091 .diagnostic_group::<MultiBufferPoint>(group_id)
10092 .filter_map(|entry| {
10093 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10094 && (entry.range.start.row == entry.range.end.row
10095 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10096 {
10097 return None;
10098 }
10099 if entry.range.end > group_end {
10100 group_end = entry.range.end;
10101 }
10102 if entry.diagnostic.is_primary {
10103 primary_range = Some(entry.range.clone());
10104 primary_message = Some(entry.diagnostic.message.clone());
10105 }
10106 Some(entry)
10107 })
10108 .collect::<Vec<_>>();
10109 let primary_range = primary_range?;
10110 let primary_message = primary_message?;
10111 let primary_range =
10112 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10113
10114 let blocks = display_map
10115 .insert_blocks(
10116 diagnostic_group.iter().map(|entry| {
10117 let diagnostic = entry.diagnostic.clone();
10118 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10119 BlockProperties {
10120 style: BlockStyle::Fixed,
10121 position: buffer.anchor_after(entry.range.start),
10122 height: message_height,
10123 render: diagnostic_block_renderer(diagnostic, None, true, true),
10124 disposition: BlockDisposition::Below,
10125 priority: 0,
10126 }
10127 }),
10128 cx,
10129 )
10130 .into_iter()
10131 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10132 .collect();
10133
10134 Some(ActiveDiagnosticGroup {
10135 primary_range,
10136 primary_message,
10137 group_id,
10138 blocks,
10139 is_valid: true,
10140 })
10141 });
10142 self.active_diagnostics.is_some()
10143 }
10144
10145 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10146 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10147 self.display_map.update(cx, |display_map, cx| {
10148 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10149 });
10150 cx.notify();
10151 }
10152 }
10153
10154 pub fn set_selections_from_remote(
10155 &mut self,
10156 selections: Vec<Selection<Anchor>>,
10157 pending_selection: Option<Selection<Anchor>>,
10158 cx: &mut ViewContext<Self>,
10159 ) {
10160 let old_cursor_position = self.selections.newest_anchor().head();
10161 self.selections.change_with(cx, |s| {
10162 s.select_anchors(selections);
10163 if let Some(pending_selection) = pending_selection {
10164 s.set_pending(pending_selection, SelectMode::Character);
10165 } else {
10166 s.clear_pending();
10167 }
10168 });
10169 self.selections_did_change(false, &old_cursor_position, true, cx);
10170 }
10171
10172 fn push_to_selection_history(&mut self) {
10173 self.selection_history.push(SelectionHistoryEntry {
10174 selections: self.selections.disjoint_anchors(),
10175 select_next_state: self.select_next_state.clone(),
10176 select_prev_state: self.select_prev_state.clone(),
10177 add_selections_state: self.add_selections_state.clone(),
10178 });
10179 }
10180
10181 pub fn transact(
10182 &mut self,
10183 cx: &mut ViewContext<Self>,
10184 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10185 ) -> Option<TransactionId> {
10186 self.start_transaction_at(Instant::now(), cx);
10187 update(self, cx);
10188 self.end_transaction_at(Instant::now(), cx)
10189 }
10190
10191 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10192 self.end_selection(cx);
10193 if let Some(tx_id) = self
10194 .buffer
10195 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10196 {
10197 self.selection_history
10198 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10199 cx.emit(EditorEvent::TransactionBegun {
10200 transaction_id: tx_id,
10201 })
10202 }
10203 }
10204
10205 fn end_transaction_at(
10206 &mut self,
10207 now: Instant,
10208 cx: &mut ViewContext<Self>,
10209 ) -> Option<TransactionId> {
10210 if let Some(transaction_id) = self
10211 .buffer
10212 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10213 {
10214 if let Some((_, end_selections)) =
10215 self.selection_history.transaction_mut(transaction_id)
10216 {
10217 *end_selections = Some(self.selections.disjoint_anchors());
10218 } else {
10219 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10220 }
10221
10222 cx.emit(EditorEvent::Edited { transaction_id });
10223 Some(transaction_id)
10224 } else {
10225 None
10226 }
10227 }
10228
10229 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10230 let mut fold_ranges = Vec::new();
10231
10232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10233
10234 let selections = self.selections.all_adjusted(cx);
10235 for selection in selections {
10236 let range = selection.range().sorted();
10237 let buffer_start_row = range.start.row;
10238
10239 for row in (0..=range.end.row).rev() {
10240 if let Some((foldable_range, fold_text)) =
10241 display_map.foldable_range(MultiBufferRow(row))
10242 {
10243 if foldable_range.end.row >= buffer_start_row {
10244 fold_ranges.push((foldable_range, fold_text));
10245 if row <= range.start.row {
10246 break;
10247 }
10248 }
10249 }
10250 }
10251 }
10252
10253 self.fold_ranges(fold_ranges, true, cx);
10254 }
10255
10256 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10257 let buffer_row = fold_at.buffer_row;
10258 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10259
10260 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10261 let autoscroll = self
10262 .selections
10263 .all::<Point>(cx)
10264 .iter()
10265 .any(|selection| fold_range.overlaps(&selection.range()));
10266
10267 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10268 }
10269 }
10270
10271 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10273 let buffer = &display_map.buffer_snapshot;
10274 let selections = self.selections.all::<Point>(cx);
10275 let ranges = selections
10276 .iter()
10277 .map(|s| {
10278 let range = s.display_range(&display_map).sorted();
10279 let mut start = range.start.to_point(&display_map);
10280 let mut end = range.end.to_point(&display_map);
10281 start.column = 0;
10282 end.column = buffer.line_len(MultiBufferRow(end.row));
10283 start..end
10284 })
10285 .collect::<Vec<_>>();
10286
10287 self.unfold_ranges(ranges, true, true, cx);
10288 }
10289
10290 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10292
10293 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10294 ..Point::new(
10295 unfold_at.buffer_row.0,
10296 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10297 );
10298
10299 let autoscroll = self
10300 .selections
10301 .all::<Point>(cx)
10302 .iter()
10303 .any(|selection| selection.range().overlaps(&intersection_range));
10304
10305 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10306 }
10307
10308 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10309 let selections = self.selections.all::<Point>(cx);
10310 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10311 let line_mode = self.selections.line_mode;
10312 let ranges = selections.into_iter().map(|s| {
10313 if line_mode {
10314 let start = Point::new(s.start.row, 0);
10315 let end = Point::new(
10316 s.end.row,
10317 display_map
10318 .buffer_snapshot
10319 .line_len(MultiBufferRow(s.end.row)),
10320 );
10321 (start..end, display_map.fold_placeholder.clone())
10322 } else {
10323 (s.start..s.end, display_map.fold_placeholder.clone())
10324 }
10325 });
10326 self.fold_ranges(ranges, true, cx);
10327 }
10328
10329 pub fn fold_ranges<T: ToOffset + Clone>(
10330 &mut self,
10331 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10332 auto_scroll: bool,
10333 cx: &mut ViewContext<Self>,
10334 ) {
10335 let mut fold_ranges = Vec::new();
10336 let mut buffers_affected = HashMap::default();
10337 let multi_buffer = self.buffer().read(cx);
10338 for (fold_range, fold_text) in ranges {
10339 if let Some((_, buffer, _)) =
10340 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10341 {
10342 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10343 };
10344 fold_ranges.push((fold_range, fold_text));
10345 }
10346
10347 let mut ranges = fold_ranges.into_iter().peekable();
10348 if ranges.peek().is_some() {
10349 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10350
10351 if auto_scroll {
10352 self.request_autoscroll(Autoscroll::fit(), cx);
10353 }
10354
10355 for buffer in buffers_affected.into_values() {
10356 self.sync_expanded_diff_hunks(buffer, cx);
10357 }
10358
10359 cx.notify();
10360
10361 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10362 // Clear diagnostics block when folding a range that contains it.
10363 let snapshot = self.snapshot(cx);
10364 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10365 drop(snapshot);
10366 self.active_diagnostics = Some(active_diagnostics);
10367 self.dismiss_diagnostics(cx);
10368 } else {
10369 self.active_diagnostics = Some(active_diagnostics);
10370 }
10371 }
10372
10373 self.scrollbar_marker_state.dirty = true;
10374 }
10375 }
10376
10377 pub fn unfold_ranges<T: ToOffset + Clone>(
10378 &mut self,
10379 ranges: impl IntoIterator<Item = Range<T>>,
10380 inclusive: bool,
10381 auto_scroll: bool,
10382 cx: &mut ViewContext<Self>,
10383 ) {
10384 let mut unfold_ranges = Vec::new();
10385 let mut buffers_affected = HashMap::default();
10386 let multi_buffer = self.buffer().read(cx);
10387 for range in ranges {
10388 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10389 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10390 };
10391 unfold_ranges.push(range);
10392 }
10393
10394 let mut ranges = unfold_ranges.into_iter().peekable();
10395 if ranges.peek().is_some() {
10396 self.display_map
10397 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10398 if auto_scroll {
10399 self.request_autoscroll(Autoscroll::fit(), cx);
10400 }
10401
10402 for buffer in buffers_affected.into_values() {
10403 self.sync_expanded_diff_hunks(buffer, cx);
10404 }
10405
10406 cx.notify();
10407 self.scrollbar_marker_state.dirty = true;
10408 self.active_indent_guides_state.dirty = true;
10409 }
10410 }
10411
10412 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10413 self.display_map.read(cx).fold_placeholder.clone()
10414 }
10415
10416 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10417 if hovered != self.gutter_hovered {
10418 self.gutter_hovered = hovered;
10419 cx.notify();
10420 }
10421 }
10422
10423 pub fn insert_blocks(
10424 &mut self,
10425 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10426 autoscroll: Option<Autoscroll>,
10427 cx: &mut ViewContext<Self>,
10428 ) -> Vec<CustomBlockId> {
10429 let blocks = self
10430 .display_map
10431 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10432 if let Some(autoscroll) = autoscroll {
10433 self.request_autoscroll(autoscroll, cx);
10434 }
10435 cx.notify();
10436 blocks
10437 }
10438
10439 pub fn resize_blocks(
10440 &mut self,
10441 heights: HashMap<CustomBlockId, u32>,
10442 autoscroll: Option<Autoscroll>,
10443 cx: &mut ViewContext<Self>,
10444 ) {
10445 self.display_map
10446 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10447 if let Some(autoscroll) = autoscroll {
10448 self.request_autoscroll(autoscroll, cx);
10449 }
10450 cx.notify();
10451 }
10452
10453 pub fn replace_blocks(
10454 &mut self,
10455 renderers: HashMap<CustomBlockId, RenderBlock>,
10456 autoscroll: Option<Autoscroll>,
10457 cx: &mut ViewContext<Self>,
10458 ) {
10459 self.display_map
10460 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10461 if let Some(autoscroll) = autoscroll {
10462 self.request_autoscroll(autoscroll, cx);
10463 }
10464 cx.notify();
10465 }
10466
10467 pub fn remove_blocks(
10468 &mut self,
10469 block_ids: HashSet<CustomBlockId>,
10470 autoscroll: Option<Autoscroll>,
10471 cx: &mut ViewContext<Self>,
10472 ) {
10473 self.display_map.update(cx, |display_map, cx| {
10474 display_map.remove_blocks(block_ids, cx)
10475 });
10476 if let Some(autoscroll) = autoscroll {
10477 self.request_autoscroll(autoscroll, cx);
10478 }
10479 cx.notify();
10480 }
10481
10482 pub fn row_for_block(
10483 &self,
10484 block_id: CustomBlockId,
10485 cx: &mut ViewContext<Self>,
10486 ) -> Option<DisplayRow> {
10487 self.display_map
10488 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10489 }
10490
10491 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10492 self.focused_block = Some(focused_block);
10493 }
10494
10495 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10496 self.focused_block.take()
10497 }
10498
10499 pub fn insert_creases(
10500 &mut self,
10501 creases: impl IntoIterator<Item = Crease>,
10502 cx: &mut ViewContext<Self>,
10503 ) -> Vec<CreaseId> {
10504 self.display_map
10505 .update(cx, |map, cx| map.insert_creases(creases, cx))
10506 }
10507
10508 pub fn remove_creases(
10509 &mut self,
10510 ids: impl IntoIterator<Item = CreaseId>,
10511 cx: &mut ViewContext<Self>,
10512 ) {
10513 self.display_map
10514 .update(cx, |map, cx| map.remove_creases(ids, cx));
10515 }
10516
10517 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10518 self.display_map
10519 .update(cx, |map, cx| map.snapshot(cx))
10520 .longest_row()
10521 }
10522
10523 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10524 self.display_map
10525 .update(cx, |map, cx| map.snapshot(cx))
10526 .max_point()
10527 }
10528
10529 pub fn text(&self, cx: &AppContext) -> String {
10530 self.buffer.read(cx).read(cx).text()
10531 }
10532
10533 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10534 let text = self.text(cx);
10535 let text = text.trim();
10536
10537 if text.is_empty() {
10538 return None;
10539 }
10540
10541 Some(text.to_string())
10542 }
10543
10544 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10545 self.transact(cx, |this, cx| {
10546 this.buffer
10547 .read(cx)
10548 .as_singleton()
10549 .expect("you can only call set_text on editors for singleton buffers")
10550 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10551 });
10552 }
10553
10554 pub fn display_text(&self, cx: &mut AppContext) -> String {
10555 self.display_map
10556 .update(cx, |map, cx| map.snapshot(cx))
10557 .text()
10558 }
10559
10560 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10561 let mut wrap_guides = smallvec::smallvec![];
10562
10563 if self.show_wrap_guides == Some(false) {
10564 return wrap_guides;
10565 }
10566
10567 let settings = self.buffer.read(cx).settings_at(0, cx);
10568 if settings.show_wrap_guides {
10569 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10570 wrap_guides.push((soft_wrap as usize, true));
10571 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10572 wrap_guides.push((soft_wrap as usize, true));
10573 }
10574 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10575 }
10576
10577 wrap_guides
10578 }
10579
10580 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10581 let settings = self.buffer.read(cx).settings_at(0, cx);
10582 let mode = self
10583 .soft_wrap_mode_override
10584 .unwrap_or_else(|| settings.soft_wrap);
10585 match mode {
10586 language_settings::SoftWrap::None => SoftWrap::None,
10587 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10588 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10589 language_settings::SoftWrap::PreferredLineLength => {
10590 SoftWrap::Column(settings.preferred_line_length)
10591 }
10592 language_settings::SoftWrap::Bounded => {
10593 SoftWrap::Bounded(settings.preferred_line_length)
10594 }
10595 }
10596 }
10597
10598 pub fn set_soft_wrap_mode(
10599 &mut self,
10600 mode: language_settings::SoftWrap,
10601 cx: &mut ViewContext<Self>,
10602 ) {
10603 self.soft_wrap_mode_override = Some(mode);
10604 cx.notify();
10605 }
10606
10607 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10608 let rem_size = cx.rem_size();
10609 self.display_map.update(cx, |map, cx| {
10610 map.set_font(
10611 style.text.font(),
10612 style.text.font_size.to_pixels(rem_size),
10613 cx,
10614 )
10615 });
10616 self.style = Some(style);
10617 }
10618
10619 pub fn style(&self) -> Option<&EditorStyle> {
10620 self.style.as_ref()
10621 }
10622
10623 // Called by the element. This method is not designed to be called outside of the editor
10624 // element's layout code because it does not notify when rewrapping is computed synchronously.
10625 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10626 self.display_map
10627 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10628 }
10629
10630 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10631 if self.soft_wrap_mode_override.is_some() {
10632 self.soft_wrap_mode_override.take();
10633 } else {
10634 let soft_wrap = match self.soft_wrap_mode(cx) {
10635 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10636 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10637 language_settings::SoftWrap::PreferLine
10638 }
10639 };
10640 self.soft_wrap_mode_override = Some(soft_wrap);
10641 }
10642 cx.notify();
10643 }
10644
10645 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10646 let Some(workspace) = self.workspace() else {
10647 return;
10648 };
10649 let fs = workspace.read(cx).app_state().fs.clone();
10650 let current_show = TabBarSettings::get_global(cx).show;
10651 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10652 setting.show = Some(!current_show);
10653 });
10654 }
10655
10656 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10657 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10658 self.buffer
10659 .read(cx)
10660 .settings_at(0, cx)
10661 .indent_guides
10662 .enabled
10663 });
10664 self.show_indent_guides = Some(!currently_enabled);
10665 cx.notify();
10666 }
10667
10668 fn should_show_indent_guides(&self) -> Option<bool> {
10669 self.show_indent_guides
10670 }
10671
10672 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10673 let mut editor_settings = EditorSettings::get_global(cx).clone();
10674 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10675 EditorSettings::override_global(editor_settings, cx);
10676 }
10677
10678 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10679 self.use_relative_line_numbers
10680 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10681 }
10682
10683 pub fn toggle_relative_line_numbers(
10684 &mut self,
10685 _: &ToggleRelativeLineNumbers,
10686 cx: &mut ViewContext<Self>,
10687 ) {
10688 let is_relative = self.should_use_relative_line_numbers(cx);
10689 self.set_relative_line_number(Some(!is_relative), cx)
10690 }
10691
10692 pub fn set_relative_line_number(
10693 &mut self,
10694 is_relative: Option<bool>,
10695 cx: &mut ViewContext<Self>,
10696 ) {
10697 self.use_relative_line_numbers = is_relative;
10698 cx.notify();
10699 }
10700
10701 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10702 self.show_gutter = show_gutter;
10703 cx.notify();
10704 }
10705
10706 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10707 self.show_line_numbers = Some(show_line_numbers);
10708 cx.notify();
10709 }
10710
10711 pub fn set_show_git_diff_gutter(
10712 &mut self,
10713 show_git_diff_gutter: bool,
10714 cx: &mut ViewContext<Self>,
10715 ) {
10716 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10717 cx.notify();
10718 }
10719
10720 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10721 self.show_code_actions = Some(show_code_actions);
10722 cx.notify();
10723 }
10724
10725 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10726 self.show_runnables = Some(show_runnables);
10727 cx.notify();
10728 }
10729
10730 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10731 if self.display_map.read(cx).masked != masked {
10732 self.display_map.update(cx, |map, _| map.masked = masked);
10733 }
10734 cx.notify()
10735 }
10736
10737 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10738 self.show_wrap_guides = Some(show_wrap_guides);
10739 cx.notify();
10740 }
10741
10742 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10743 self.show_indent_guides = Some(show_indent_guides);
10744 cx.notify();
10745 }
10746
10747 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10748 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10749 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10750 if let Some(dir) = file.abs_path(cx).parent() {
10751 return Some(dir.to_owned());
10752 }
10753 }
10754
10755 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10756 return Some(project_path.path.to_path_buf());
10757 }
10758 }
10759
10760 None
10761 }
10762
10763 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10764 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10765 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10766 cx.reveal_path(&file.abs_path(cx));
10767 }
10768 }
10769 }
10770
10771 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10772 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10773 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10774 if let Some(path) = file.abs_path(cx).to_str() {
10775 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10776 }
10777 }
10778 }
10779 }
10780
10781 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10782 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10783 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10784 if let Some(path) = file.path().to_str() {
10785 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10786 }
10787 }
10788 }
10789 }
10790
10791 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10792 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10793
10794 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10795 self.start_git_blame(true, cx);
10796 }
10797
10798 cx.notify();
10799 }
10800
10801 pub fn toggle_git_blame_inline(
10802 &mut self,
10803 _: &ToggleGitBlameInline,
10804 cx: &mut ViewContext<Self>,
10805 ) {
10806 self.toggle_git_blame_inline_internal(true, cx);
10807 cx.notify();
10808 }
10809
10810 pub fn git_blame_inline_enabled(&self) -> bool {
10811 self.git_blame_inline_enabled
10812 }
10813
10814 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10815 self.show_selection_menu = self
10816 .show_selection_menu
10817 .map(|show_selections_menu| !show_selections_menu)
10818 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10819
10820 cx.notify();
10821 }
10822
10823 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10824 self.show_selection_menu
10825 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10826 }
10827
10828 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10829 if let Some(project) = self.project.as_ref() {
10830 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10831 return;
10832 };
10833
10834 if buffer.read(cx).file().is_none() {
10835 return;
10836 }
10837
10838 let focused = self.focus_handle(cx).contains_focused(cx);
10839
10840 let project = project.clone();
10841 let blame =
10842 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10843 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10844 self.blame = Some(blame);
10845 }
10846 }
10847
10848 fn toggle_git_blame_inline_internal(
10849 &mut self,
10850 user_triggered: bool,
10851 cx: &mut ViewContext<Self>,
10852 ) {
10853 if self.git_blame_inline_enabled {
10854 self.git_blame_inline_enabled = false;
10855 self.show_git_blame_inline = false;
10856 self.show_git_blame_inline_delay_task.take();
10857 } else {
10858 self.git_blame_inline_enabled = true;
10859 self.start_git_blame_inline(user_triggered, cx);
10860 }
10861
10862 cx.notify();
10863 }
10864
10865 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10866 self.start_git_blame(user_triggered, cx);
10867
10868 if ProjectSettings::get_global(cx)
10869 .git
10870 .inline_blame_delay()
10871 .is_some()
10872 {
10873 self.start_inline_blame_timer(cx);
10874 } else {
10875 self.show_git_blame_inline = true
10876 }
10877 }
10878
10879 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10880 self.blame.as_ref()
10881 }
10882
10883 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10884 self.show_git_blame_gutter && self.has_blame_entries(cx)
10885 }
10886
10887 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10888 self.show_git_blame_inline
10889 && self.focus_handle.is_focused(cx)
10890 && !self.newest_selection_head_on_empty_line(cx)
10891 && self.has_blame_entries(cx)
10892 }
10893
10894 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10895 self.blame()
10896 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10897 }
10898
10899 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10900 let cursor_anchor = self.selections.newest_anchor().head();
10901
10902 let snapshot = self.buffer.read(cx).snapshot(cx);
10903 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10904
10905 snapshot.line_len(buffer_row) == 0
10906 }
10907
10908 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10909 let (path, selection, repo) = maybe!({
10910 let project_handle = self.project.as_ref()?.clone();
10911 let project = project_handle.read(cx);
10912
10913 let selection = self.selections.newest::<Point>(cx);
10914 let selection_range = selection.range();
10915
10916 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10917 (buffer, selection_range.start.row..selection_range.end.row)
10918 } else {
10919 let buffer_ranges = self
10920 .buffer()
10921 .read(cx)
10922 .range_to_buffer_ranges(selection_range, cx);
10923
10924 let (buffer, range, _) = if selection.reversed {
10925 buffer_ranges.first()
10926 } else {
10927 buffer_ranges.last()
10928 }?;
10929
10930 let snapshot = buffer.read(cx).snapshot();
10931 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10932 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10933 (buffer.clone(), selection)
10934 };
10935
10936 let path = buffer
10937 .read(cx)
10938 .file()?
10939 .as_local()?
10940 .path()
10941 .to_str()?
10942 .to_string();
10943 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10944 Some((path, selection, repo))
10945 })
10946 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10947
10948 const REMOTE_NAME: &str = "origin";
10949 let origin_url = repo
10950 .remote_url(REMOTE_NAME)
10951 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10952 let sha = repo
10953 .head_sha()
10954 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10955
10956 let (provider, remote) =
10957 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10958 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10959
10960 Ok(provider.build_permalink(
10961 remote,
10962 BuildPermalinkParams {
10963 sha: &sha,
10964 path: &path,
10965 selection: Some(selection),
10966 },
10967 ))
10968 }
10969
10970 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10971 let permalink = self.get_permalink_to_line(cx);
10972
10973 match permalink {
10974 Ok(permalink) => {
10975 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10976 }
10977 Err(err) => {
10978 let message = format!("Failed to copy permalink: {err}");
10979
10980 Err::<(), anyhow::Error>(err).log_err();
10981
10982 if let Some(workspace) = self.workspace() {
10983 workspace.update(cx, |workspace, cx| {
10984 struct CopyPermalinkToLine;
10985
10986 workspace.show_toast(
10987 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10988 cx,
10989 )
10990 })
10991 }
10992 }
10993 }
10994 }
10995
10996 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10997 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10998 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10999 if let Some(path) = file.path().to_str() {
11000 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11001 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11002 }
11003 }
11004 }
11005 }
11006
11007 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11008 let permalink = self.get_permalink_to_line(cx);
11009
11010 match permalink {
11011 Ok(permalink) => {
11012 cx.open_url(permalink.as_ref());
11013 }
11014 Err(err) => {
11015 let message = format!("Failed to open permalink: {err}");
11016
11017 Err::<(), anyhow::Error>(err).log_err();
11018
11019 if let Some(workspace) = self.workspace() {
11020 workspace.update(cx, |workspace, cx| {
11021 struct OpenPermalinkToLine;
11022
11023 workspace.show_toast(
11024 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11025 cx,
11026 )
11027 })
11028 }
11029 }
11030 }
11031 }
11032
11033 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11034 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11035 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11036 pub fn highlight_rows<T: 'static>(
11037 &mut self,
11038 rows: RangeInclusive<Anchor>,
11039 color: Option<Hsla>,
11040 should_autoscroll: bool,
11041 cx: &mut ViewContext<Self>,
11042 ) {
11043 let snapshot = self.buffer().read(cx).snapshot(cx);
11044 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11045 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11046 highlight
11047 .range
11048 .start()
11049 .cmp(&rows.start(), &snapshot)
11050 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
11051 });
11052 match (color, existing_highlight_index) {
11053 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11054 ix,
11055 RowHighlight {
11056 index: post_inc(&mut self.highlight_order),
11057 range: rows,
11058 should_autoscroll,
11059 color,
11060 },
11061 ),
11062 (None, Ok(i)) => {
11063 row_highlights.remove(i);
11064 }
11065 }
11066 }
11067
11068 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11069 pub fn clear_row_highlights<T: 'static>(&mut self) {
11070 self.highlighted_rows.remove(&TypeId::of::<T>());
11071 }
11072
11073 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11074 pub fn highlighted_rows<T: 'static>(
11075 &self,
11076 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11077 Some(
11078 self.highlighted_rows
11079 .get(&TypeId::of::<T>())?
11080 .iter()
11081 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11082 )
11083 }
11084
11085 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11086 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11087 /// Allows to ignore certain kinds of highlights.
11088 pub fn highlighted_display_rows(
11089 &mut self,
11090 cx: &mut WindowContext,
11091 ) -> BTreeMap<DisplayRow, Hsla> {
11092 let snapshot = self.snapshot(cx);
11093 let mut used_highlight_orders = HashMap::default();
11094 self.highlighted_rows
11095 .iter()
11096 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11097 .fold(
11098 BTreeMap::<DisplayRow, Hsla>::new(),
11099 |mut unique_rows, highlight| {
11100 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11101 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11102 for row in start_row.0..=end_row.0 {
11103 let used_index =
11104 used_highlight_orders.entry(row).or_insert(highlight.index);
11105 if highlight.index >= *used_index {
11106 *used_index = highlight.index;
11107 match highlight.color {
11108 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11109 None => unique_rows.remove(&DisplayRow(row)),
11110 };
11111 }
11112 }
11113 unique_rows
11114 },
11115 )
11116 }
11117
11118 pub fn highlighted_display_row_for_autoscroll(
11119 &self,
11120 snapshot: &DisplaySnapshot,
11121 ) -> Option<DisplayRow> {
11122 self.highlighted_rows
11123 .values()
11124 .flat_map(|highlighted_rows| highlighted_rows.iter())
11125 .filter_map(|highlight| {
11126 if highlight.color.is_none() || !highlight.should_autoscroll {
11127 return None;
11128 }
11129 Some(highlight.range.start().to_display_point(&snapshot).row())
11130 })
11131 .min()
11132 }
11133
11134 pub fn set_search_within_ranges(
11135 &mut self,
11136 ranges: &[Range<Anchor>],
11137 cx: &mut ViewContext<Self>,
11138 ) {
11139 self.highlight_background::<SearchWithinRange>(
11140 ranges,
11141 |colors| colors.editor_document_highlight_read_background,
11142 cx,
11143 )
11144 }
11145
11146 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11147 self.breadcrumb_header = Some(new_header);
11148 }
11149
11150 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11151 self.clear_background_highlights::<SearchWithinRange>(cx);
11152 }
11153
11154 pub fn highlight_background<T: 'static>(
11155 &mut self,
11156 ranges: &[Range<Anchor>],
11157 color_fetcher: fn(&ThemeColors) -> Hsla,
11158 cx: &mut ViewContext<Self>,
11159 ) {
11160 self.background_highlights
11161 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11162 self.scrollbar_marker_state.dirty = true;
11163 cx.notify();
11164 }
11165
11166 pub fn clear_background_highlights<T: 'static>(
11167 &mut self,
11168 cx: &mut ViewContext<Self>,
11169 ) -> Option<BackgroundHighlight> {
11170 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11171 if !text_highlights.1.is_empty() {
11172 self.scrollbar_marker_state.dirty = true;
11173 cx.notify();
11174 }
11175 Some(text_highlights)
11176 }
11177
11178 pub fn highlight_gutter<T: 'static>(
11179 &mut self,
11180 ranges: &[Range<Anchor>],
11181 color_fetcher: fn(&AppContext) -> Hsla,
11182 cx: &mut ViewContext<Self>,
11183 ) {
11184 self.gutter_highlights
11185 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11186 cx.notify();
11187 }
11188
11189 pub fn clear_gutter_highlights<T: 'static>(
11190 &mut self,
11191 cx: &mut ViewContext<Self>,
11192 ) -> Option<GutterHighlight> {
11193 cx.notify();
11194 self.gutter_highlights.remove(&TypeId::of::<T>())
11195 }
11196
11197 #[cfg(feature = "test-support")]
11198 pub fn all_text_background_highlights(
11199 &mut self,
11200 cx: &mut ViewContext<Self>,
11201 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11202 let snapshot = self.snapshot(cx);
11203 let buffer = &snapshot.buffer_snapshot;
11204 let start = buffer.anchor_before(0);
11205 let end = buffer.anchor_after(buffer.len());
11206 let theme = cx.theme().colors();
11207 self.background_highlights_in_range(start..end, &snapshot, theme)
11208 }
11209
11210 #[cfg(feature = "test-support")]
11211 pub fn search_background_highlights(
11212 &mut self,
11213 cx: &mut ViewContext<Self>,
11214 ) -> Vec<Range<Point>> {
11215 let snapshot = self.buffer().read(cx).snapshot(cx);
11216
11217 let highlights = self
11218 .background_highlights
11219 .get(&TypeId::of::<items::BufferSearchHighlights>());
11220
11221 if let Some((_color, ranges)) = highlights {
11222 ranges
11223 .iter()
11224 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11225 .collect_vec()
11226 } else {
11227 vec![]
11228 }
11229 }
11230
11231 fn document_highlights_for_position<'a>(
11232 &'a self,
11233 position: Anchor,
11234 buffer: &'a MultiBufferSnapshot,
11235 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11236 let read_highlights = self
11237 .background_highlights
11238 .get(&TypeId::of::<DocumentHighlightRead>())
11239 .map(|h| &h.1);
11240 let write_highlights = self
11241 .background_highlights
11242 .get(&TypeId::of::<DocumentHighlightWrite>())
11243 .map(|h| &h.1);
11244 let left_position = position.bias_left(buffer);
11245 let right_position = position.bias_right(buffer);
11246 read_highlights
11247 .into_iter()
11248 .chain(write_highlights)
11249 .flat_map(move |ranges| {
11250 let start_ix = match ranges.binary_search_by(|probe| {
11251 let cmp = probe.end.cmp(&left_position, buffer);
11252 if cmp.is_ge() {
11253 Ordering::Greater
11254 } else {
11255 Ordering::Less
11256 }
11257 }) {
11258 Ok(i) | Err(i) => i,
11259 };
11260
11261 ranges[start_ix..]
11262 .iter()
11263 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11264 })
11265 }
11266
11267 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11268 self.background_highlights
11269 .get(&TypeId::of::<T>())
11270 .map_or(false, |(_, highlights)| !highlights.is_empty())
11271 }
11272
11273 pub fn background_highlights_in_range(
11274 &self,
11275 search_range: Range<Anchor>,
11276 display_snapshot: &DisplaySnapshot,
11277 theme: &ThemeColors,
11278 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11279 let mut results = Vec::new();
11280 for (color_fetcher, ranges) in self.background_highlights.values() {
11281 let color = color_fetcher(theme);
11282 let start_ix = match ranges.binary_search_by(|probe| {
11283 let cmp = probe
11284 .end
11285 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11286 if cmp.is_gt() {
11287 Ordering::Greater
11288 } else {
11289 Ordering::Less
11290 }
11291 }) {
11292 Ok(i) | Err(i) => i,
11293 };
11294 for range in &ranges[start_ix..] {
11295 if range
11296 .start
11297 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11298 .is_ge()
11299 {
11300 break;
11301 }
11302
11303 let start = range.start.to_display_point(&display_snapshot);
11304 let end = range.end.to_display_point(&display_snapshot);
11305 results.push((start..end, color))
11306 }
11307 }
11308 results
11309 }
11310
11311 pub fn background_highlight_row_ranges<T: 'static>(
11312 &self,
11313 search_range: Range<Anchor>,
11314 display_snapshot: &DisplaySnapshot,
11315 count: usize,
11316 ) -> Vec<RangeInclusive<DisplayPoint>> {
11317 let mut results = Vec::new();
11318 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11319 return vec![];
11320 };
11321
11322 let start_ix = match ranges.binary_search_by(|probe| {
11323 let cmp = probe
11324 .end
11325 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11326 if cmp.is_gt() {
11327 Ordering::Greater
11328 } else {
11329 Ordering::Less
11330 }
11331 }) {
11332 Ok(i) | Err(i) => i,
11333 };
11334 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11335 if let (Some(start_display), Some(end_display)) = (start, end) {
11336 results.push(
11337 start_display.to_display_point(display_snapshot)
11338 ..=end_display.to_display_point(display_snapshot),
11339 );
11340 }
11341 };
11342 let mut start_row: Option<Point> = None;
11343 let mut end_row: Option<Point> = None;
11344 if ranges.len() > count {
11345 return Vec::new();
11346 }
11347 for range in &ranges[start_ix..] {
11348 if range
11349 .start
11350 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11351 .is_ge()
11352 {
11353 break;
11354 }
11355 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11356 if let Some(current_row) = &end_row {
11357 if end.row == current_row.row {
11358 continue;
11359 }
11360 }
11361 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11362 if start_row.is_none() {
11363 assert_eq!(end_row, None);
11364 start_row = Some(start);
11365 end_row = Some(end);
11366 continue;
11367 }
11368 if let Some(current_end) = end_row.as_mut() {
11369 if start.row > current_end.row + 1 {
11370 push_region(start_row, end_row);
11371 start_row = Some(start);
11372 end_row = Some(end);
11373 } else {
11374 // Merge two hunks.
11375 *current_end = end;
11376 }
11377 } else {
11378 unreachable!();
11379 }
11380 }
11381 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11382 push_region(start_row, end_row);
11383 results
11384 }
11385
11386 pub fn gutter_highlights_in_range(
11387 &self,
11388 search_range: Range<Anchor>,
11389 display_snapshot: &DisplaySnapshot,
11390 cx: &AppContext,
11391 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11392 let mut results = Vec::new();
11393 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11394 let color = color_fetcher(cx);
11395 let start_ix = match ranges.binary_search_by(|probe| {
11396 let cmp = probe
11397 .end
11398 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11399 if cmp.is_gt() {
11400 Ordering::Greater
11401 } else {
11402 Ordering::Less
11403 }
11404 }) {
11405 Ok(i) | Err(i) => i,
11406 };
11407 for range in &ranges[start_ix..] {
11408 if range
11409 .start
11410 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11411 .is_ge()
11412 {
11413 break;
11414 }
11415
11416 let start = range.start.to_display_point(&display_snapshot);
11417 let end = range.end.to_display_point(&display_snapshot);
11418 results.push((start..end, color))
11419 }
11420 }
11421 results
11422 }
11423
11424 /// Get the text ranges corresponding to the redaction query
11425 pub fn redacted_ranges(
11426 &self,
11427 search_range: Range<Anchor>,
11428 display_snapshot: &DisplaySnapshot,
11429 cx: &WindowContext,
11430 ) -> Vec<Range<DisplayPoint>> {
11431 display_snapshot
11432 .buffer_snapshot
11433 .redacted_ranges(search_range, |file| {
11434 if let Some(file) = file {
11435 file.is_private()
11436 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11437 } else {
11438 false
11439 }
11440 })
11441 .map(|range| {
11442 range.start.to_display_point(display_snapshot)
11443 ..range.end.to_display_point(display_snapshot)
11444 })
11445 .collect()
11446 }
11447
11448 pub fn highlight_text<T: 'static>(
11449 &mut self,
11450 ranges: Vec<Range<Anchor>>,
11451 style: HighlightStyle,
11452 cx: &mut ViewContext<Self>,
11453 ) {
11454 self.display_map.update(cx, |map, _| {
11455 map.highlight_text(TypeId::of::<T>(), ranges, style)
11456 });
11457 cx.notify();
11458 }
11459
11460 pub(crate) fn highlight_inlays<T: 'static>(
11461 &mut self,
11462 highlights: Vec<InlayHighlight>,
11463 style: HighlightStyle,
11464 cx: &mut ViewContext<Self>,
11465 ) {
11466 self.display_map.update(cx, |map, _| {
11467 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11468 });
11469 cx.notify();
11470 }
11471
11472 pub fn text_highlights<'a, T: 'static>(
11473 &'a self,
11474 cx: &'a AppContext,
11475 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11476 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11477 }
11478
11479 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11480 let cleared = self
11481 .display_map
11482 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11483 if cleared {
11484 cx.notify();
11485 }
11486 }
11487
11488 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11489 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11490 && self.focus_handle.is_focused(cx)
11491 }
11492
11493 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11494 self.show_cursor_when_unfocused = is_enabled;
11495 cx.notify();
11496 }
11497
11498 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11499 cx.notify();
11500 }
11501
11502 fn on_buffer_event(
11503 &mut self,
11504 multibuffer: Model<MultiBuffer>,
11505 event: &multi_buffer::Event,
11506 cx: &mut ViewContext<Self>,
11507 ) {
11508 match event {
11509 multi_buffer::Event::Edited {
11510 singleton_buffer_edited,
11511 } => {
11512 self.scrollbar_marker_state.dirty = true;
11513 self.active_indent_guides_state.dirty = true;
11514 self.refresh_active_diagnostics(cx);
11515 self.refresh_code_actions(cx);
11516 if self.has_active_inline_completion(cx) {
11517 self.update_visible_inline_completion(cx);
11518 }
11519 cx.emit(EditorEvent::BufferEdited);
11520 cx.emit(SearchEvent::MatchesInvalidated);
11521 if *singleton_buffer_edited {
11522 if let Some(project) = &self.project {
11523 let project = project.read(cx);
11524 #[allow(clippy::mutable_key_type)]
11525 let languages_affected = multibuffer
11526 .read(cx)
11527 .all_buffers()
11528 .into_iter()
11529 .filter_map(|buffer| {
11530 let buffer = buffer.read(cx);
11531 let language = buffer.language()?;
11532 if project.is_local_or_ssh()
11533 && project.language_servers_for_buffer(buffer, cx).count() == 0
11534 {
11535 None
11536 } else {
11537 Some(language)
11538 }
11539 })
11540 .cloned()
11541 .collect::<HashSet<_>>();
11542 if !languages_affected.is_empty() {
11543 self.refresh_inlay_hints(
11544 InlayHintRefreshReason::BufferEdited(languages_affected),
11545 cx,
11546 );
11547 }
11548 }
11549 }
11550
11551 let Some(project) = &self.project else { return };
11552 let telemetry = project.read(cx).client().telemetry().clone();
11553 refresh_linked_ranges(self, cx);
11554 telemetry.log_edit_event("editor");
11555 }
11556 multi_buffer::Event::ExcerptsAdded {
11557 buffer,
11558 predecessor,
11559 excerpts,
11560 } => {
11561 self.tasks_update_task = Some(self.refresh_runnables(cx));
11562 cx.emit(EditorEvent::ExcerptsAdded {
11563 buffer: buffer.clone(),
11564 predecessor: *predecessor,
11565 excerpts: excerpts.clone(),
11566 });
11567 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11568 }
11569 multi_buffer::Event::ExcerptsRemoved { ids } => {
11570 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11571 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11572 }
11573 multi_buffer::Event::ExcerptsEdited { ids } => {
11574 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11575 }
11576 multi_buffer::Event::ExcerptsExpanded { ids } => {
11577 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11578 }
11579 multi_buffer::Event::Reparsed(buffer_id) => {
11580 self.tasks_update_task = Some(self.refresh_runnables(cx));
11581
11582 cx.emit(EditorEvent::Reparsed(*buffer_id));
11583 }
11584 multi_buffer::Event::LanguageChanged(buffer_id) => {
11585 linked_editing_ranges::refresh_linked_ranges(self, cx);
11586 cx.emit(EditorEvent::Reparsed(*buffer_id));
11587 cx.notify();
11588 }
11589 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11590 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11591 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11592 cx.emit(EditorEvent::TitleChanged)
11593 }
11594 multi_buffer::Event::DiffBaseChanged => {
11595 self.scrollbar_marker_state.dirty = true;
11596 cx.emit(EditorEvent::DiffBaseChanged);
11597 cx.notify();
11598 }
11599 multi_buffer::Event::DiffUpdated { buffer } => {
11600 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11601 cx.notify();
11602 }
11603 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11604 multi_buffer::Event::DiagnosticsUpdated => {
11605 self.refresh_active_diagnostics(cx);
11606 self.scrollbar_marker_state.dirty = true;
11607 cx.notify();
11608 }
11609 _ => {}
11610 };
11611 }
11612
11613 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11614 cx.notify();
11615 }
11616
11617 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11618 self.tasks_update_task = Some(self.refresh_runnables(cx));
11619 self.refresh_inline_completion(true, false, cx);
11620 self.refresh_inlay_hints(
11621 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11622 self.selections.newest_anchor().head(),
11623 &self.buffer.read(cx).snapshot(cx),
11624 cx,
11625 )),
11626 cx,
11627 );
11628 let editor_settings = EditorSettings::get_global(cx);
11629 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11630 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11631
11632 let project_settings = ProjectSettings::get_global(cx);
11633 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11634
11635 if self.mode == EditorMode::Full {
11636 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11637 if self.git_blame_inline_enabled != inline_blame_enabled {
11638 self.toggle_git_blame_inline_internal(false, cx);
11639 }
11640 }
11641
11642 cx.notify();
11643 }
11644
11645 pub fn set_searchable(&mut self, searchable: bool) {
11646 self.searchable = searchable;
11647 }
11648
11649 pub fn searchable(&self) -> bool {
11650 self.searchable
11651 }
11652
11653 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11654 self.open_excerpts_common(true, cx)
11655 }
11656
11657 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11658 self.open_excerpts_common(false, cx)
11659 }
11660
11661 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11662 let buffer = self.buffer.read(cx);
11663 if buffer.is_singleton() {
11664 cx.propagate();
11665 return;
11666 }
11667
11668 let Some(workspace) = self.workspace() else {
11669 cx.propagate();
11670 return;
11671 };
11672
11673 let mut new_selections_by_buffer = HashMap::default();
11674 for selection in self.selections.all::<usize>(cx) {
11675 for (buffer, mut range, _) in
11676 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11677 {
11678 if selection.reversed {
11679 mem::swap(&mut range.start, &mut range.end);
11680 }
11681 new_selections_by_buffer
11682 .entry(buffer)
11683 .or_insert(Vec::new())
11684 .push(range)
11685 }
11686 }
11687
11688 // We defer the pane interaction because we ourselves are a workspace item
11689 // and activating a new item causes the pane to call a method on us reentrantly,
11690 // which panics if we're on the stack.
11691 cx.window_context().defer(move |cx| {
11692 workspace.update(cx, |workspace, cx| {
11693 let pane = if split {
11694 workspace.adjacent_pane(cx)
11695 } else {
11696 workspace.active_pane().clone()
11697 };
11698
11699 for (buffer, ranges) in new_selections_by_buffer {
11700 let editor =
11701 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11702 editor.update(cx, |editor, cx| {
11703 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11704 s.select_ranges(ranges);
11705 });
11706 });
11707 }
11708 })
11709 });
11710 }
11711
11712 fn jump(
11713 &mut self,
11714 path: ProjectPath,
11715 position: Point,
11716 anchor: language::Anchor,
11717 offset_from_top: u32,
11718 cx: &mut ViewContext<Self>,
11719 ) {
11720 let workspace = self.workspace();
11721 cx.spawn(|_, mut cx| async move {
11722 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11723 let editor = workspace.update(&mut cx, |workspace, cx| {
11724 // Reset the preview item id before opening the new item
11725 workspace.active_pane().update(cx, |pane, cx| {
11726 pane.set_preview_item_id(None, cx);
11727 });
11728 workspace.open_path_preview(path, None, true, true, cx)
11729 })?;
11730 let editor = editor
11731 .await?
11732 .downcast::<Editor>()
11733 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11734 .downgrade();
11735 editor.update(&mut cx, |editor, cx| {
11736 let buffer = editor
11737 .buffer()
11738 .read(cx)
11739 .as_singleton()
11740 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11741 let buffer = buffer.read(cx);
11742 let cursor = if buffer.can_resolve(&anchor) {
11743 language::ToPoint::to_point(&anchor, buffer)
11744 } else {
11745 buffer.clip_point(position, Bias::Left)
11746 };
11747
11748 let nav_history = editor.nav_history.take();
11749 editor.change_selections(
11750 Some(Autoscroll::top_relative(offset_from_top as usize)),
11751 cx,
11752 |s| {
11753 s.select_ranges([cursor..cursor]);
11754 },
11755 );
11756 editor.nav_history = nav_history;
11757
11758 anyhow::Ok(())
11759 })??;
11760
11761 anyhow::Ok(())
11762 })
11763 .detach_and_log_err(cx);
11764 }
11765
11766 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11767 let snapshot = self.buffer.read(cx).read(cx);
11768 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11769 Some(
11770 ranges
11771 .iter()
11772 .map(move |range| {
11773 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11774 })
11775 .collect(),
11776 )
11777 }
11778
11779 fn selection_replacement_ranges(
11780 &self,
11781 range: Range<OffsetUtf16>,
11782 cx: &AppContext,
11783 ) -> Vec<Range<OffsetUtf16>> {
11784 let selections = self.selections.all::<OffsetUtf16>(cx);
11785 let newest_selection = selections
11786 .iter()
11787 .max_by_key(|selection| selection.id)
11788 .unwrap();
11789 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11790 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11791 let snapshot = self.buffer.read(cx).read(cx);
11792 selections
11793 .into_iter()
11794 .map(|mut selection| {
11795 selection.start.0 =
11796 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11797 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11798 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11799 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11800 })
11801 .collect()
11802 }
11803
11804 fn report_editor_event(
11805 &self,
11806 operation: &'static str,
11807 file_extension: Option<String>,
11808 cx: &AppContext,
11809 ) {
11810 if cfg!(any(test, feature = "test-support")) {
11811 return;
11812 }
11813
11814 let Some(project) = &self.project else { return };
11815
11816 // If None, we are in a file without an extension
11817 let file = self
11818 .buffer
11819 .read(cx)
11820 .as_singleton()
11821 .and_then(|b| b.read(cx).file());
11822 let file_extension = file_extension.or(file
11823 .as_ref()
11824 .and_then(|file| Path::new(file.file_name(cx)).extension())
11825 .and_then(|e| e.to_str())
11826 .map(|a| a.to_string()));
11827
11828 let vim_mode = cx
11829 .global::<SettingsStore>()
11830 .raw_user_settings()
11831 .get("vim_mode")
11832 == Some(&serde_json::Value::Bool(true));
11833
11834 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11835 == language::language_settings::InlineCompletionProvider::Copilot;
11836 let copilot_enabled_for_language = self
11837 .buffer
11838 .read(cx)
11839 .settings_at(0, cx)
11840 .show_inline_completions;
11841
11842 let telemetry = project.read(cx).client().telemetry().clone();
11843 telemetry.report_editor_event(
11844 file_extension,
11845 vim_mode,
11846 operation,
11847 copilot_enabled,
11848 copilot_enabled_for_language,
11849 )
11850 }
11851
11852 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11853 /// with each line being an array of {text, highlight} objects.
11854 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11855 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11856 return;
11857 };
11858
11859 #[derive(Serialize)]
11860 struct Chunk<'a> {
11861 text: String,
11862 highlight: Option<&'a str>,
11863 }
11864
11865 let snapshot = buffer.read(cx).snapshot();
11866 let range = self
11867 .selected_text_range(false, cx)
11868 .and_then(|selection| {
11869 if selection.range.is_empty() {
11870 None
11871 } else {
11872 Some(selection.range)
11873 }
11874 })
11875 .unwrap_or_else(|| 0..snapshot.len());
11876
11877 let chunks = snapshot.chunks(range, true);
11878 let mut lines = Vec::new();
11879 let mut line: VecDeque<Chunk> = VecDeque::new();
11880
11881 let Some(style) = self.style.as_ref() else {
11882 return;
11883 };
11884
11885 for chunk in chunks {
11886 let highlight = chunk
11887 .syntax_highlight_id
11888 .and_then(|id| id.name(&style.syntax));
11889 let mut chunk_lines = chunk.text.split('\n').peekable();
11890 while let Some(text) = chunk_lines.next() {
11891 let mut merged_with_last_token = false;
11892 if let Some(last_token) = line.back_mut() {
11893 if last_token.highlight == highlight {
11894 last_token.text.push_str(text);
11895 merged_with_last_token = true;
11896 }
11897 }
11898
11899 if !merged_with_last_token {
11900 line.push_back(Chunk {
11901 text: text.into(),
11902 highlight,
11903 });
11904 }
11905
11906 if chunk_lines.peek().is_some() {
11907 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11908 line.pop_front();
11909 }
11910 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11911 line.pop_back();
11912 }
11913
11914 lines.push(mem::take(&mut line));
11915 }
11916 }
11917 }
11918
11919 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11920 return;
11921 };
11922 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11923 }
11924
11925 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11926 &self.inlay_hint_cache
11927 }
11928
11929 pub fn replay_insert_event(
11930 &mut self,
11931 text: &str,
11932 relative_utf16_range: Option<Range<isize>>,
11933 cx: &mut ViewContext<Self>,
11934 ) {
11935 if !self.input_enabled {
11936 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11937 return;
11938 }
11939 if let Some(relative_utf16_range) = relative_utf16_range {
11940 let selections = self.selections.all::<OffsetUtf16>(cx);
11941 self.change_selections(None, cx, |s| {
11942 let new_ranges = selections.into_iter().map(|range| {
11943 let start = OffsetUtf16(
11944 range
11945 .head()
11946 .0
11947 .saturating_add_signed(relative_utf16_range.start),
11948 );
11949 let end = OffsetUtf16(
11950 range
11951 .head()
11952 .0
11953 .saturating_add_signed(relative_utf16_range.end),
11954 );
11955 start..end
11956 });
11957 s.select_ranges(new_ranges);
11958 });
11959 }
11960
11961 self.handle_input(text, cx);
11962 }
11963
11964 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11965 let Some(project) = self.project.as_ref() else {
11966 return false;
11967 };
11968 let project = project.read(cx);
11969
11970 let mut supports = false;
11971 self.buffer().read(cx).for_each_buffer(|buffer| {
11972 if !supports {
11973 supports = project
11974 .language_servers_for_buffer(buffer.read(cx), cx)
11975 .any(
11976 |(_, server)| match server.capabilities().inlay_hint_provider {
11977 Some(lsp::OneOf::Left(enabled)) => enabled,
11978 Some(lsp::OneOf::Right(_)) => true,
11979 None => false,
11980 },
11981 )
11982 }
11983 });
11984 supports
11985 }
11986
11987 pub fn focus(&self, cx: &mut WindowContext) {
11988 cx.focus(&self.focus_handle)
11989 }
11990
11991 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11992 self.focus_handle.is_focused(cx)
11993 }
11994
11995 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11996 cx.emit(EditorEvent::Focused);
11997
11998 if let Some(descendant) = self
11999 .last_focused_descendant
12000 .take()
12001 .and_then(|descendant| descendant.upgrade())
12002 {
12003 cx.focus(&descendant);
12004 } else {
12005 if let Some(blame) = self.blame.as_ref() {
12006 blame.update(cx, GitBlame::focus)
12007 }
12008
12009 self.blink_manager.update(cx, BlinkManager::enable);
12010 self.show_cursor_names(cx);
12011 self.buffer.update(cx, |buffer, cx| {
12012 buffer.finalize_last_transaction(cx);
12013 if self.leader_peer_id.is_none() {
12014 buffer.set_active_selections(
12015 &self.selections.disjoint_anchors(),
12016 self.selections.line_mode,
12017 self.cursor_shape,
12018 cx,
12019 );
12020 }
12021 });
12022 }
12023 }
12024
12025 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12026 cx.emit(EditorEvent::FocusedIn)
12027 }
12028
12029 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12030 if event.blurred != self.focus_handle {
12031 self.last_focused_descendant = Some(event.blurred);
12032 }
12033 }
12034
12035 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12036 self.blink_manager.update(cx, BlinkManager::disable);
12037 self.buffer
12038 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12039
12040 if let Some(blame) = self.blame.as_ref() {
12041 blame.update(cx, GitBlame::blur)
12042 }
12043 if !self.hover_state.focused(cx) {
12044 hide_hover(self, cx);
12045 }
12046
12047 self.hide_context_menu(cx);
12048 cx.emit(EditorEvent::Blurred);
12049 cx.notify();
12050 }
12051
12052 pub fn register_action<A: Action>(
12053 &mut self,
12054 listener: impl Fn(&A, &mut WindowContext) + 'static,
12055 ) -> Subscription {
12056 let id = self.next_editor_action_id.post_inc();
12057 let listener = Arc::new(listener);
12058 self.editor_actions.borrow_mut().insert(
12059 id,
12060 Box::new(move |cx| {
12061 let cx = cx.window_context();
12062 let listener = listener.clone();
12063 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12064 let action = action.downcast_ref().unwrap();
12065 if phase == DispatchPhase::Bubble {
12066 listener(action, cx)
12067 }
12068 })
12069 }),
12070 );
12071
12072 let editor_actions = self.editor_actions.clone();
12073 Subscription::new(move || {
12074 editor_actions.borrow_mut().remove(&id);
12075 })
12076 }
12077
12078 pub fn file_header_size(&self) -> u32 {
12079 self.file_header_size
12080 }
12081
12082 pub fn revert(
12083 &mut self,
12084 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12085 cx: &mut ViewContext<Self>,
12086 ) {
12087 self.buffer().update(cx, |multi_buffer, cx| {
12088 for (buffer_id, changes) in revert_changes {
12089 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12090 buffer.update(cx, |buffer, cx| {
12091 buffer.edit(
12092 changes.into_iter().map(|(range, text)| {
12093 (range, text.to_string().map(Arc::<str>::from))
12094 }),
12095 None,
12096 cx,
12097 );
12098 });
12099 }
12100 }
12101 });
12102 self.change_selections(None, cx, |selections| selections.refresh());
12103 }
12104
12105 pub fn to_pixel_point(
12106 &mut self,
12107 source: multi_buffer::Anchor,
12108 editor_snapshot: &EditorSnapshot,
12109 cx: &mut ViewContext<Self>,
12110 ) -> Option<gpui::Point<Pixels>> {
12111 let source_point = source.to_display_point(editor_snapshot);
12112 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12113 }
12114
12115 pub fn display_to_pixel_point(
12116 &mut self,
12117 source: DisplayPoint,
12118 editor_snapshot: &EditorSnapshot,
12119 cx: &mut ViewContext<Self>,
12120 ) -> Option<gpui::Point<Pixels>> {
12121 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12122 let text_layout_details = self.text_layout_details(cx);
12123 let scroll_top = text_layout_details
12124 .scroll_anchor
12125 .scroll_position(editor_snapshot)
12126 .y;
12127
12128 if source.row().as_f32() < scroll_top.floor() {
12129 return None;
12130 }
12131 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12132 let source_y = line_height * (source.row().as_f32() - scroll_top);
12133 Some(gpui::Point::new(source_x, source_y))
12134 }
12135
12136 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12137 let bounds = self.last_bounds?;
12138 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12139 }
12140
12141 pub fn has_active_completions_menu(&self) -> bool {
12142 self.context_menu.read().as_ref().map_or(false, |menu| {
12143 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12144 })
12145 }
12146
12147 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12148 self.addons
12149 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12150 }
12151
12152 pub fn unregister_addon<T: Addon>(&mut self) {
12153 self.addons.remove(&std::any::TypeId::of::<T>());
12154 }
12155
12156 pub fn addon<T: Addon>(&self) -> Option<&T> {
12157 let type_id = std::any::TypeId::of::<T>();
12158 self.addons
12159 .get(&type_id)
12160 .and_then(|item| item.to_any().downcast_ref::<T>())
12161 }
12162}
12163
12164fn hunks_for_selections(
12165 multi_buffer_snapshot: &MultiBufferSnapshot,
12166 selections: &[Selection<Anchor>],
12167) -> Vec<DiffHunk<MultiBufferRow>> {
12168 let buffer_rows_for_selections = selections.iter().map(|selection| {
12169 let head = selection.head();
12170 let tail = selection.tail();
12171 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12172 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12173 if start > end {
12174 end..start
12175 } else {
12176 start..end
12177 }
12178 });
12179
12180 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12181}
12182
12183pub fn hunks_for_rows(
12184 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12185 multi_buffer_snapshot: &MultiBufferSnapshot,
12186) -> Vec<DiffHunk<MultiBufferRow>> {
12187 let mut hunks = Vec::new();
12188 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12189 HashMap::default();
12190 for selected_multi_buffer_rows in rows {
12191 let query_rows =
12192 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12193 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12194 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12195 // when the caret is just above or just below the deleted hunk.
12196 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12197 let related_to_selection = if allow_adjacent {
12198 hunk.associated_range.overlaps(&query_rows)
12199 || hunk.associated_range.start == query_rows.end
12200 || hunk.associated_range.end == query_rows.start
12201 } else {
12202 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12203 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12204 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12205 || selected_multi_buffer_rows.end == hunk.associated_range.start
12206 };
12207 if related_to_selection {
12208 if !processed_buffer_rows
12209 .entry(hunk.buffer_id)
12210 .or_default()
12211 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12212 {
12213 continue;
12214 }
12215 hunks.push(hunk);
12216 }
12217 }
12218 }
12219
12220 hunks
12221}
12222
12223pub trait CollaborationHub {
12224 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12225 fn user_participant_indices<'a>(
12226 &self,
12227 cx: &'a AppContext,
12228 ) -> &'a HashMap<u64, ParticipantIndex>;
12229 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12230}
12231
12232impl CollaborationHub for Model<Project> {
12233 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12234 self.read(cx).collaborators()
12235 }
12236
12237 fn user_participant_indices<'a>(
12238 &self,
12239 cx: &'a AppContext,
12240 ) -> &'a HashMap<u64, ParticipantIndex> {
12241 self.read(cx).user_store().read(cx).participant_indices()
12242 }
12243
12244 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12245 let this = self.read(cx);
12246 let user_ids = this.collaborators().values().map(|c| c.user_id);
12247 this.user_store().read_with(cx, |user_store, cx| {
12248 user_store.participant_names(user_ids, cx)
12249 })
12250 }
12251}
12252
12253pub trait CompletionProvider {
12254 fn completions(
12255 &self,
12256 buffer: &Model<Buffer>,
12257 buffer_position: text::Anchor,
12258 trigger: CompletionContext,
12259 cx: &mut ViewContext<Editor>,
12260 ) -> Task<Result<Vec<Completion>>>;
12261
12262 fn resolve_completions(
12263 &self,
12264 buffer: Model<Buffer>,
12265 completion_indices: Vec<usize>,
12266 completions: Arc<RwLock<Box<[Completion]>>>,
12267 cx: &mut ViewContext<Editor>,
12268 ) -> Task<Result<bool>>;
12269
12270 fn apply_additional_edits_for_completion(
12271 &self,
12272 buffer: Model<Buffer>,
12273 completion: Completion,
12274 push_to_history: bool,
12275 cx: &mut ViewContext<Editor>,
12276 ) -> Task<Result<Option<language::Transaction>>>;
12277
12278 fn is_completion_trigger(
12279 &self,
12280 buffer: &Model<Buffer>,
12281 position: language::Anchor,
12282 text: &str,
12283 trigger_in_words: bool,
12284 cx: &mut ViewContext<Editor>,
12285 ) -> bool;
12286
12287 fn sort_completions(&self) -> bool {
12288 true
12289 }
12290}
12291
12292fn snippet_completions(
12293 project: &Project,
12294 buffer: &Model<Buffer>,
12295 buffer_position: text::Anchor,
12296 cx: &mut AppContext,
12297) -> Vec<Completion> {
12298 let language = buffer.read(cx).language_at(buffer_position);
12299 let language_name = language.as_ref().map(|language| language.lsp_id());
12300 let snippet_store = project.snippets().read(cx);
12301 let snippets = snippet_store.snippets_for(language_name, cx);
12302
12303 if snippets.is_empty() {
12304 return vec![];
12305 }
12306 let snapshot = buffer.read(cx).text_snapshot();
12307 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12308
12309 let mut lines = chunks.lines();
12310 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12311 return vec![];
12312 };
12313
12314 let scope = language.map(|language| language.default_scope());
12315 let classifier = CharClassifier::new(scope).for_completion(true);
12316 let mut last_word = line_at
12317 .chars()
12318 .rev()
12319 .take_while(|c| classifier.is_word(*c))
12320 .collect::<String>();
12321 last_word = last_word.chars().rev().collect();
12322 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12323 let to_lsp = |point: &text::Anchor| {
12324 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12325 point_to_lsp(end)
12326 };
12327 let lsp_end = to_lsp(&buffer_position);
12328 snippets
12329 .into_iter()
12330 .filter_map(|snippet| {
12331 let matching_prefix = snippet
12332 .prefix
12333 .iter()
12334 .find(|prefix| prefix.starts_with(&last_word))?;
12335 let start = as_offset - last_word.len();
12336 let start = snapshot.anchor_before(start);
12337 let range = start..buffer_position;
12338 let lsp_start = to_lsp(&start);
12339 let lsp_range = lsp::Range {
12340 start: lsp_start,
12341 end: lsp_end,
12342 };
12343 Some(Completion {
12344 old_range: range,
12345 new_text: snippet.body.clone(),
12346 label: CodeLabel {
12347 text: matching_prefix.clone(),
12348 runs: vec![],
12349 filter_range: 0..matching_prefix.len(),
12350 },
12351 server_id: LanguageServerId(usize::MAX),
12352 documentation: snippet
12353 .description
12354 .clone()
12355 .map(|description| Documentation::SingleLine(description)),
12356 lsp_completion: lsp::CompletionItem {
12357 label: snippet.prefix.first().unwrap().clone(),
12358 kind: Some(CompletionItemKind::SNIPPET),
12359 label_details: snippet.description.as_ref().map(|description| {
12360 lsp::CompletionItemLabelDetails {
12361 detail: Some(description.clone()),
12362 description: None,
12363 }
12364 }),
12365 insert_text_format: Some(InsertTextFormat::SNIPPET),
12366 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12367 lsp::InsertReplaceEdit {
12368 new_text: snippet.body.clone(),
12369 insert: lsp_range,
12370 replace: lsp_range,
12371 },
12372 )),
12373 filter_text: Some(snippet.body.clone()),
12374 sort_text: Some(char::MAX.to_string()),
12375 ..Default::default()
12376 },
12377 confirm: None,
12378 })
12379 })
12380 .collect()
12381}
12382
12383impl CompletionProvider for Model<Project> {
12384 fn completions(
12385 &self,
12386 buffer: &Model<Buffer>,
12387 buffer_position: text::Anchor,
12388 options: CompletionContext,
12389 cx: &mut ViewContext<Editor>,
12390 ) -> Task<Result<Vec<Completion>>> {
12391 self.update(cx, |project, cx| {
12392 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12393 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12394 cx.background_executor().spawn(async move {
12395 let mut completions = project_completions.await?;
12396 //let snippets = snippets.into_iter().;
12397 completions.extend(snippets);
12398 Ok(completions)
12399 })
12400 })
12401 }
12402
12403 fn resolve_completions(
12404 &self,
12405 buffer: Model<Buffer>,
12406 completion_indices: Vec<usize>,
12407 completions: Arc<RwLock<Box<[Completion]>>>,
12408 cx: &mut ViewContext<Editor>,
12409 ) -> Task<Result<bool>> {
12410 self.update(cx, |project, cx| {
12411 project.resolve_completions(buffer, completion_indices, completions, cx)
12412 })
12413 }
12414
12415 fn apply_additional_edits_for_completion(
12416 &self,
12417 buffer: Model<Buffer>,
12418 completion: Completion,
12419 push_to_history: bool,
12420 cx: &mut ViewContext<Editor>,
12421 ) -> Task<Result<Option<language::Transaction>>> {
12422 self.update(cx, |project, cx| {
12423 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12424 })
12425 }
12426
12427 fn is_completion_trigger(
12428 &self,
12429 buffer: &Model<Buffer>,
12430 position: language::Anchor,
12431 text: &str,
12432 trigger_in_words: bool,
12433 cx: &mut ViewContext<Editor>,
12434 ) -> bool {
12435 if !EditorSettings::get_global(cx).show_completions_on_input {
12436 return false;
12437 }
12438
12439 let mut chars = text.chars();
12440 let char = if let Some(char) = chars.next() {
12441 char
12442 } else {
12443 return false;
12444 };
12445 if chars.next().is_some() {
12446 return false;
12447 }
12448
12449 let buffer = buffer.read(cx);
12450 let classifier = buffer
12451 .snapshot()
12452 .char_classifier_at(position)
12453 .for_completion(true);
12454 if trigger_in_words && classifier.is_word(char) {
12455 return true;
12456 }
12457
12458 buffer
12459 .completion_triggers()
12460 .iter()
12461 .any(|string| string == text)
12462 }
12463}
12464
12465fn inlay_hint_settings(
12466 location: Anchor,
12467 snapshot: &MultiBufferSnapshot,
12468 cx: &mut ViewContext<'_, Editor>,
12469) -> InlayHintSettings {
12470 let file = snapshot.file_at(location);
12471 let language = snapshot.language_at(location);
12472 let settings = all_language_settings(file, cx);
12473 settings
12474 .language(language.map(|l| l.name()).as_deref())
12475 .inlay_hints
12476}
12477
12478fn consume_contiguous_rows(
12479 contiguous_row_selections: &mut Vec<Selection<Point>>,
12480 selection: &Selection<Point>,
12481 display_map: &DisplaySnapshot,
12482 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12483) -> (MultiBufferRow, MultiBufferRow) {
12484 contiguous_row_selections.push(selection.clone());
12485 let start_row = MultiBufferRow(selection.start.row);
12486 let mut end_row = ending_row(selection, display_map);
12487
12488 while let Some(next_selection) = selections.peek() {
12489 if next_selection.start.row <= end_row.0 {
12490 end_row = ending_row(next_selection, display_map);
12491 contiguous_row_selections.push(selections.next().unwrap().clone());
12492 } else {
12493 break;
12494 }
12495 }
12496 (start_row, end_row)
12497}
12498
12499fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12500 if next_selection.end.column > 0 || next_selection.is_empty() {
12501 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12502 } else {
12503 MultiBufferRow(next_selection.end.row)
12504 }
12505}
12506
12507impl EditorSnapshot {
12508 pub fn remote_selections_in_range<'a>(
12509 &'a self,
12510 range: &'a Range<Anchor>,
12511 collaboration_hub: &dyn CollaborationHub,
12512 cx: &'a AppContext,
12513 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12514 let participant_names = collaboration_hub.user_names(cx);
12515 let participant_indices = collaboration_hub.user_participant_indices(cx);
12516 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12517 let collaborators_by_replica_id = collaborators_by_peer_id
12518 .iter()
12519 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12520 .collect::<HashMap<_, _>>();
12521 self.buffer_snapshot
12522 .selections_in_range(range, false)
12523 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12524 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12525 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12526 let user_name = participant_names.get(&collaborator.user_id).cloned();
12527 Some(RemoteSelection {
12528 replica_id,
12529 selection,
12530 cursor_shape,
12531 line_mode,
12532 participant_index,
12533 peer_id: collaborator.peer_id,
12534 user_name,
12535 })
12536 })
12537 }
12538
12539 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12540 self.display_snapshot.buffer_snapshot.language_at(position)
12541 }
12542
12543 pub fn is_focused(&self) -> bool {
12544 self.is_focused
12545 }
12546
12547 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12548 self.placeholder_text.as_ref()
12549 }
12550
12551 pub fn scroll_position(&self) -> gpui::Point<f32> {
12552 self.scroll_anchor.scroll_position(&self.display_snapshot)
12553 }
12554
12555 fn gutter_dimensions(
12556 &self,
12557 font_id: FontId,
12558 font_size: Pixels,
12559 em_width: Pixels,
12560 max_line_number_width: Pixels,
12561 cx: &AppContext,
12562 ) -> GutterDimensions {
12563 if !self.show_gutter {
12564 return GutterDimensions::default();
12565 }
12566 let descent = cx.text_system().descent(font_id, font_size);
12567
12568 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12569 matches!(
12570 ProjectSettings::get_global(cx).git.git_gutter,
12571 Some(GitGutterSetting::TrackedFiles)
12572 )
12573 });
12574 let gutter_settings = EditorSettings::get_global(cx).gutter;
12575 let show_line_numbers = self
12576 .show_line_numbers
12577 .unwrap_or(gutter_settings.line_numbers);
12578 let line_gutter_width = if show_line_numbers {
12579 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12580 let min_width_for_number_on_gutter = em_width * 4.0;
12581 max_line_number_width.max(min_width_for_number_on_gutter)
12582 } else {
12583 0.0.into()
12584 };
12585
12586 let show_code_actions = self
12587 .show_code_actions
12588 .unwrap_or(gutter_settings.code_actions);
12589
12590 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12591
12592 let git_blame_entries_width = self
12593 .render_git_blame_gutter
12594 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12595
12596 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12597 left_padding += if show_code_actions || show_runnables {
12598 em_width * 3.0
12599 } else if show_git_gutter && show_line_numbers {
12600 em_width * 2.0
12601 } else if show_git_gutter || show_line_numbers {
12602 em_width
12603 } else {
12604 px(0.)
12605 };
12606
12607 let right_padding = if gutter_settings.folds && show_line_numbers {
12608 em_width * 4.0
12609 } else if gutter_settings.folds {
12610 em_width * 3.0
12611 } else if show_line_numbers {
12612 em_width
12613 } else {
12614 px(0.)
12615 };
12616
12617 GutterDimensions {
12618 left_padding,
12619 right_padding,
12620 width: line_gutter_width + left_padding + right_padding,
12621 margin: -descent,
12622 git_blame_entries_width,
12623 }
12624 }
12625
12626 pub fn render_fold_toggle(
12627 &self,
12628 buffer_row: MultiBufferRow,
12629 row_contains_cursor: bool,
12630 editor: View<Editor>,
12631 cx: &mut WindowContext,
12632 ) -> Option<AnyElement> {
12633 let folded = self.is_line_folded(buffer_row);
12634
12635 if let Some(crease) = self
12636 .crease_snapshot
12637 .query_row(buffer_row, &self.buffer_snapshot)
12638 {
12639 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12640 if folded {
12641 editor.update(cx, |editor, cx| {
12642 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12643 });
12644 } else {
12645 editor.update(cx, |editor, cx| {
12646 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12647 });
12648 }
12649 });
12650
12651 Some((crease.render_toggle)(
12652 buffer_row,
12653 folded,
12654 toggle_callback,
12655 cx,
12656 ))
12657 } else if folded
12658 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12659 {
12660 Some(
12661 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12662 .selected(folded)
12663 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12664 if folded {
12665 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12666 } else {
12667 this.fold_at(&FoldAt { buffer_row }, cx);
12668 }
12669 }))
12670 .into_any_element(),
12671 )
12672 } else {
12673 None
12674 }
12675 }
12676
12677 pub fn render_crease_trailer(
12678 &self,
12679 buffer_row: MultiBufferRow,
12680 cx: &mut WindowContext,
12681 ) -> Option<AnyElement> {
12682 let folded = self.is_line_folded(buffer_row);
12683 let crease = self
12684 .crease_snapshot
12685 .query_row(buffer_row, &self.buffer_snapshot)?;
12686 Some((crease.render_trailer)(buffer_row, folded, cx))
12687 }
12688}
12689
12690impl Deref for EditorSnapshot {
12691 type Target = DisplaySnapshot;
12692
12693 fn deref(&self) -> &Self::Target {
12694 &self.display_snapshot
12695 }
12696}
12697
12698#[derive(Clone, Debug, PartialEq, Eq)]
12699pub enum EditorEvent {
12700 InputIgnored {
12701 text: Arc<str>,
12702 },
12703 InputHandled {
12704 utf16_range_to_replace: Option<Range<isize>>,
12705 text: Arc<str>,
12706 },
12707 ExcerptsAdded {
12708 buffer: Model<Buffer>,
12709 predecessor: ExcerptId,
12710 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12711 },
12712 ExcerptsRemoved {
12713 ids: Vec<ExcerptId>,
12714 },
12715 ExcerptsEdited {
12716 ids: Vec<ExcerptId>,
12717 },
12718 ExcerptsExpanded {
12719 ids: Vec<ExcerptId>,
12720 },
12721 BufferEdited,
12722 Edited {
12723 transaction_id: clock::Lamport,
12724 },
12725 Reparsed(BufferId),
12726 Focused,
12727 FocusedIn,
12728 Blurred,
12729 DirtyChanged,
12730 Saved,
12731 TitleChanged,
12732 DiffBaseChanged,
12733 SelectionsChanged {
12734 local: bool,
12735 },
12736 ScrollPositionChanged {
12737 local: bool,
12738 autoscroll: bool,
12739 },
12740 Closed,
12741 TransactionUndone {
12742 transaction_id: clock::Lamport,
12743 },
12744 TransactionBegun {
12745 transaction_id: clock::Lamport,
12746 },
12747}
12748
12749impl EventEmitter<EditorEvent> for Editor {}
12750
12751impl FocusableView for Editor {
12752 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12753 self.focus_handle.clone()
12754 }
12755}
12756
12757impl Render for Editor {
12758 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12759 let settings = ThemeSettings::get_global(cx);
12760
12761 let text_style = match self.mode {
12762 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12763 color: cx.theme().colors().editor_foreground,
12764 font_family: settings.ui_font.family.clone(),
12765 font_features: settings.ui_font.features.clone(),
12766 font_fallbacks: settings.ui_font.fallbacks.clone(),
12767 font_size: rems(0.875).into(),
12768 font_weight: settings.ui_font.weight,
12769 line_height: relative(settings.buffer_line_height.value()),
12770 ..Default::default()
12771 },
12772 EditorMode::Full => TextStyle {
12773 color: cx.theme().colors().editor_foreground,
12774 font_family: settings.buffer_font.family.clone(),
12775 font_features: settings.buffer_font.features.clone(),
12776 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12777 font_size: settings.buffer_font_size(cx).into(),
12778 font_weight: settings.buffer_font.weight,
12779 line_height: relative(settings.buffer_line_height.value()),
12780 ..Default::default()
12781 },
12782 };
12783
12784 let background = match self.mode {
12785 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12786 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12787 EditorMode::Full => cx.theme().colors().editor_background,
12788 };
12789
12790 EditorElement::new(
12791 cx.view(),
12792 EditorStyle {
12793 background,
12794 local_player: cx.theme().players().local(),
12795 text: text_style,
12796 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12797 syntax: cx.theme().syntax().clone(),
12798 status: cx.theme().status().clone(),
12799 inlay_hints_style: HighlightStyle {
12800 color: Some(cx.theme().status().hint),
12801 ..HighlightStyle::default()
12802 },
12803 suggestions_style: HighlightStyle {
12804 color: Some(cx.theme().status().predictive),
12805 ..HighlightStyle::default()
12806 },
12807 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12808 },
12809 )
12810 }
12811}
12812
12813impl ViewInputHandler for Editor {
12814 fn text_for_range(
12815 &mut self,
12816 range_utf16: Range<usize>,
12817 cx: &mut ViewContext<Self>,
12818 ) -> Option<String> {
12819 Some(
12820 self.buffer
12821 .read(cx)
12822 .read(cx)
12823 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12824 .collect(),
12825 )
12826 }
12827
12828 fn selected_text_range(
12829 &mut self,
12830 ignore_disabled_input: bool,
12831 cx: &mut ViewContext<Self>,
12832 ) -> Option<UTF16Selection> {
12833 // Prevent the IME menu from appearing when holding down an alphabetic key
12834 // while input is disabled.
12835 if !ignore_disabled_input && !self.input_enabled {
12836 return None;
12837 }
12838
12839 let selection = self.selections.newest::<OffsetUtf16>(cx);
12840 let range = selection.range();
12841
12842 Some(UTF16Selection {
12843 range: range.start.0..range.end.0,
12844 reversed: selection.reversed,
12845 })
12846 }
12847
12848 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12849 let snapshot = self.buffer.read(cx).read(cx);
12850 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12851 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12852 }
12853
12854 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12855 self.clear_highlights::<InputComposition>(cx);
12856 self.ime_transaction.take();
12857 }
12858
12859 fn replace_text_in_range(
12860 &mut self,
12861 range_utf16: Option<Range<usize>>,
12862 text: &str,
12863 cx: &mut ViewContext<Self>,
12864 ) {
12865 if !self.input_enabled {
12866 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12867 return;
12868 }
12869
12870 self.transact(cx, |this, cx| {
12871 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12872 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12873 Some(this.selection_replacement_ranges(range_utf16, cx))
12874 } else {
12875 this.marked_text_ranges(cx)
12876 };
12877
12878 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12879 let newest_selection_id = this.selections.newest_anchor().id;
12880 this.selections
12881 .all::<OffsetUtf16>(cx)
12882 .iter()
12883 .zip(ranges_to_replace.iter())
12884 .find_map(|(selection, range)| {
12885 if selection.id == newest_selection_id {
12886 Some(
12887 (range.start.0 as isize - selection.head().0 as isize)
12888 ..(range.end.0 as isize - selection.head().0 as isize),
12889 )
12890 } else {
12891 None
12892 }
12893 })
12894 });
12895
12896 cx.emit(EditorEvent::InputHandled {
12897 utf16_range_to_replace: range_to_replace,
12898 text: text.into(),
12899 });
12900
12901 if let Some(new_selected_ranges) = new_selected_ranges {
12902 this.change_selections(None, cx, |selections| {
12903 selections.select_ranges(new_selected_ranges)
12904 });
12905 this.backspace(&Default::default(), cx);
12906 }
12907
12908 this.handle_input(text, cx);
12909 });
12910
12911 if let Some(transaction) = self.ime_transaction {
12912 self.buffer.update(cx, |buffer, cx| {
12913 buffer.group_until_transaction(transaction, cx);
12914 });
12915 }
12916
12917 self.unmark_text(cx);
12918 }
12919
12920 fn replace_and_mark_text_in_range(
12921 &mut self,
12922 range_utf16: Option<Range<usize>>,
12923 text: &str,
12924 new_selected_range_utf16: Option<Range<usize>>,
12925 cx: &mut ViewContext<Self>,
12926 ) {
12927 if !self.input_enabled {
12928 return;
12929 }
12930
12931 let transaction = self.transact(cx, |this, cx| {
12932 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12933 let snapshot = this.buffer.read(cx).read(cx);
12934 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12935 for marked_range in &mut marked_ranges {
12936 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12937 marked_range.start.0 += relative_range_utf16.start;
12938 marked_range.start =
12939 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12940 marked_range.end =
12941 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12942 }
12943 }
12944 Some(marked_ranges)
12945 } else if let Some(range_utf16) = range_utf16 {
12946 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12947 Some(this.selection_replacement_ranges(range_utf16, cx))
12948 } else {
12949 None
12950 };
12951
12952 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12953 let newest_selection_id = this.selections.newest_anchor().id;
12954 this.selections
12955 .all::<OffsetUtf16>(cx)
12956 .iter()
12957 .zip(ranges_to_replace.iter())
12958 .find_map(|(selection, range)| {
12959 if selection.id == newest_selection_id {
12960 Some(
12961 (range.start.0 as isize - selection.head().0 as isize)
12962 ..(range.end.0 as isize - selection.head().0 as isize),
12963 )
12964 } else {
12965 None
12966 }
12967 })
12968 });
12969
12970 cx.emit(EditorEvent::InputHandled {
12971 utf16_range_to_replace: range_to_replace,
12972 text: text.into(),
12973 });
12974
12975 if let Some(ranges) = ranges_to_replace {
12976 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12977 }
12978
12979 let marked_ranges = {
12980 let snapshot = this.buffer.read(cx).read(cx);
12981 this.selections
12982 .disjoint_anchors()
12983 .iter()
12984 .map(|selection| {
12985 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12986 })
12987 .collect::<Vec<_>>()
12988 };
12989
12990 if text.is_empty() {
12991 this.unmark_text(cx);
12992 } else {
12993 this.highlight_text::<InputComposition>(
12994 marked_ranges.clone(),
12995 HighlightStyle {
12996 underline: Some(UnderlineStyle {
12997 thickness: px(1.),
12998 color: None,
12999 wavy: false,
13000 }),
13001 ..Default::default()
13002 },
13003 cx,
13004 );
13005 }
13006
13007 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13008 let use_autoclose = this.use_autoclose;
13009 let use_auto_surround = this.use_auto_surround;
13010 this.set_use_autoclose(false);
13011 this.set_use_auto_surround(false);
13012 this.handle_input(text, cx);
13013 this.set_use_autoclose(use_autoclose);
13014 this.set_use_auto_surround(use_auto_surround);
13015
13016 if let Some(new_selected_range) = new_selected_range_utf16 {
13017 let snapshot = this.buffer.read(cx).read(cx);
13018 let new_selected_ranges = marked_ranges
13019 .into_iter()
13020 .map(|marked_range| {
13021 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13022 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13023 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13024 snapshot.clip_offset_utf16(new_start, Bias::Left)
13025 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13026 })
13027 .collect::<Vec<_>>();
13028
13029 drop(snapshot);
13030 this.change_selections(None, cx, |selections| {
13031 selections.select_ranges(new_selected_ranges)
13032 });
13033 }
13034 });
13035
13036 self.ime_transaction = self.ime_transaction.or(transaction);
13037 if let Some(transaction) = self.ime_transaction {
13038 self.buffer.update(cx, |buffer, cx| {
13039 buffer.group_until_transaction(transaction, cx);
13040 });
13041 }
13042
13043 if self.text_highlights::<InputComposition>(cx).is_none() {
13044 self.ime_transaction.take();
13045 }
13046 }
13047
13048 fn bounds_for_range(
13049 &mut self,
13050 range_utf16: Range<usize>,
13051 element_bounds: gpui::Bounds<Pixels>,
13052 cx: &mut ViewContext<Self>,
13053 ) -> Option<gpui::Bounds<Pixels>> {
13054 let text_layout_details = self.text_layout_details(cx);
13055 let style = &text_layout_details.editor_style;
13056 let font_id = cx.text_system().resolve_font(&style.text.font());
13057 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13058 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13059
13060 let em_width = cx
13061 .text_system()
13062 .typographic_bounds(font_id, font_size, 'm')
13063 .unwrap()
13064 .size
13065 .width;
13066
13067 let snapshot = self.snapshot(cx);
13068 let scroll_position = snapshot.scroll_position();
13069 let scroll_left = scroll_position.x * em_width;
13070
13071 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13072 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13073 + self.gutter_dimensions.width;
13074 let y = line_height * (start.row().as_f32() - scroll_position.y);
13075
13076 Some(Bounds {
13077 origin: element_bounds.origin + point(x, y),
13078 size: size(em_width, line_height),
13079 })
13080 }
13081}
13082
13083trait SelectionExt {
13084 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13085 fn spanned_rows(
13086 &self,
13087 include_end_if_at_line_start: bool,
13088 map: &DisplaySnapshot,
13089 ) -> Range<MultiBufferRow>;
13090}
13091
13092impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13093 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13094 let start = self
13095 .start
13096 .to_point(&map.buffer_snapshot)
13097 .to_display_point(map);
13098 let end = self
13099 .end
13100 .to_point(&map.buffer_snapshot)
13101 .to_display_point(map);
13102 if self.reversed {
13103 end..start
13104 } else {
13105 start..end
13106 }
13107 }
13108
13109 fn spanned_rows(
13110 &self,
13111 include_end_if_at_line_start: bool,
13112 map: &DisplaySnapshot,
13113 ) -> Range<MultiBufferRow> {
13114 let start = self.start.to_point(&map.buffer_snapshot);
13115 let mut end = self.end.to_point(&map.buffer_snapshot);
13116 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13117 end.row -= 1;
13118 }
13119
13120 let buffer_start = map.prev_line_boundary(start).0;
13121 let buffer_end = map.next_line_boundary(end).0;
13122 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13123 }
13124}
13125
13126impl<T: InvalidationRegion> InvalidationStack<T> {
13127 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13128 where
13129 S: Clone + ToOffset,
13130 {
13131 while let Some(region) = self.last() {
13132 let all_selections_inside_invalidation_ranges =
13133 if selections.len() == region.ranges().len() {
13134 selections
13135 .iter()
13136 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13137 .all(|(selection, invalidation_range)| {
13138 let head = selection.head().to_offset(buffer);
13139 invalidation_range.start <= head && invalidation_range.end >= head
13140 })
13141 } else {
13142 false
13143 };
13144
13145 if all_selections_inside_invalidation_ranges {
13146 break;
13147 } else {
13148 self.pop();
13149 }
13150 }
13151 }
13152}
13153
13154impl<T> Default for InvalidationStack<T> {
13155 fn default() -> Self {
13156 Self(Default::default())
13157 }
13158}
13159
13160impl<T> Deref for InvalidationStack<T> {
13161 type Target = Vec<T>;
13162
13163 fn deref(&self) -> &Self::Target {
13164 &self.0
13165 }
13166}
13167
13168impl<T> DerefMut for InvalidationStack<T> {
13169 fn deref_mut(&mut self) -> &mut Self::Target {
13170 &mut self.0
13171 }
13172}
13173
13174impl InvalidationRegion for SnippetState {
13175 fn ranges(&self) -> &[Range<Anchor>] {
13176 &self.ranges[self.active_index]
13177 }
13178}
13179
13180pub fn diagnostic_block_renderer(
13181 diagnostic: Diagnostic,
13182 max_message_rows: Option<u8>,
13183 allow_closing: bool,
13184 _is_valid: bool,
13185) -> RenderBlock {
13186 let (text_without_backticks, code_ranges) =
13187 highlight_diagnostic_message(&diagnostic, max_message_rows);
13188
13189 Box::new(move |cx: &mut BlockContext| {
13190 let group_id: SharedString = cx.block_id.to_string().into();
13191
13192 let mut text_style = cx.text_style().clone();
13193 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13194 let theme_settings = ThemeSettings::get_global(cx);
13195 text_style.font_family = theme_settings.buffer_font.family.clone();
13196 text_style.font_style = theme_settings.buffer_font.style;
13197 text_style.font_features = theme_settings.buffer_font.features.clone();
13198 text_style.font_weight = theme_settings.buffer_font.weight;
13199
13200 let multi_line_diagnostic = diagnostic.message.contains('\n');
13201
13202 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13203 if multi_line_diagnostic {
13204 v_flex()
13205 } else {
13206 h_flex()
13207 }
13208 .when(allow_closing, |div| {
13209 div.children(diagnostic.is_primary.then(|| {
13210 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13211 .icon_color(Color::Muted)
13212 .size(ButtonSize::Compact)
13213 .style(ButtonStyle::Transparent)
13214 .visible_on_hover(group_id.clone())
13215 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13216 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13217 }))
13218 })
13219 .child(
13220 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13221 .icon_color(Color::Muted)
13222 .size(ButtonSize::Compact)
13223 .style(ButtonStyle::Transparent)
13224 .visible_on_hover(group_id.clone())
13225 .on_click({
13226 let message = diagnostic.message.clone();
13227 move |_click, cx| {
13228 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13229 }
13230 })
13231 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13232 )
13233 };
13234
13235 let icon_size = buttons(&diagnostic, cx.block_id)
13236 .into_any_element()
13237 .layout_as_root(AvailableSpace::min_size(), cx);
13238
13239 h_flex()
13240 .id(cx.block_id)
13241 .group(group_id.clone())
13242 .relative()
13243 .size_full()
13244 .pl(cx.gutter_dimensions.width)
13245 .w(cx.max_width + cx.gutter_dimensions.width)
13246 .child(
13247 div()
13248 .flex()
13249 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13250 .flex_shrink(),
13251 )
13252 .child(buttons(&diagnostic, cx.block_id))
13253 .child(div().flex().flex_shrink_0().child(
13254 StyledText::new(text_without_backticks.clone()).with_highlights(
13255 &text_style,
13256 code_ranges.iter().map(|range| {
13257 (
13258 range.clone(),
13259 HighlightStyle {
13260 font_weight: Some(FontWeight::BOLD),
13261 ..Default::default()
13262 },
13263 )
13264 }),
13265 ),
13266 ))
13267 .into_any_element()
13268 })
13269}
13270
13271pub fn highlight_diagnostic_message(
13272 diagnostic: &Diagnostic,
13273 mut max_message_rows: Option<u8>,
13274) -> (SharedString, Vec<Range<usize>>) {
13275 let mut text_without_backticks = String::new();
13276 let mut code_ranges = Vec::new();
13277
13278 if let Some(source) = &diagnostic.source {
13279 text_without_backticks.push_str(&source);
13280 code_ranges.push(0..source.len());
13281 text_without_backticks.push_str(": ");
13282 }
13283
13284 let mut prev_offset = 0;
13285 let mut in_code_block = false;
13286 let has_row_limit = max_message_rows.is_some();
13287 let mut newline_indices = diagnostic
13288 .message
13289 .match_indices('\n')
13290 .filter(|_| has_row_limit)
13291 .map(|(ix, _)| ix)
13292 .fuse()
13293 .peekable();
13294
13295 for (quote_ix, _) in diagnostic
13296 .message
13297 .match_indices('`')
13298 .chain([(diagnostic.message.len(), "")])
13299 {
13300 let mut first_newline_ix = None;
13301 let mut last_newline_ix = None;
13302 while let Some(newline_ix) = newline_indices.peek() {
13303 if *newline_ix < quote_ix {
13304 if first_newline_ix.is_none() {
13305 first_newline_ix = Some(*newline_ix);
13306 }
13307 last_newline_ix = Some(*newline_ix);
13308
13309 if let Some(rows_left) = &mut max_message_rows {
13310 if *rows_left == 0 {
13311 break;
13312 } else {
13313 *rows_left -= 1;
13314 }
13315 }
13316 let _ = newline_indices.next();
13317 } else {
13318 break;
13319 }
13320 }
13321 let prev_len = text_without_backticks.len();
13322 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13323 text_without_backticks.push_str(new_text);
13324 if in_code_block {
13325 code_ranges.push(prev_len..text_without_backticks.len());
13326 }
13327 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13328 in_code_block = !in_code_block;
13329 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13330 text_without_backticks.push_str("...");
13331 break;
13332 }
13333 }
13334
13335 (text_without_backticks.into(), code_ranges)
13336}
13337
13338fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13339 match severity {
13340 DiagnosticSeverity::ERROR => colors.error,
13341 DiagnosticSeverity::WARNING => colors.warning,
13342 DiagnosticSeverity::INFORMATION => colors.info,
13343 DiagnosticSeverity::HINT => colors.info,
13344 _ => colors.ignored,
13345 }
13346}
13347
13348pub fn styled_runs_for_code_label<'a>(
13349 label: &'a CodeLabel,
13350 syntax_theme: &'a theme::SyntaxTheme,
13351) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13352 let fade_out = HighlightStyle {
13353 fade_out: Some(0.35),
13354 ..Default::default()
13355 };
13356
13357 let mut prev_end = label.filter_range.end;
13358 label
13359 .runs
13360 .iter()
13361 .enumerate()
13362 .flat_map(move |(ix, (range, highlight_id))| {
13363 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13364 style
13365 } else {
13366 return Default::default();
13367 };
13368 let mut muted_style = style;
13369 muted_style.highlight(fade_out);
13370
13371 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13372 if range.start >= label.filter_range.end {
13373 if range.start > prev_end {
13374 runs.push((prev_end..range.start, fade_out));
13375 }
13376 runs.push((range.clone(), muted_style));
13377 } else if range.end <= label.filter_range.end {
13378 runs.push((range.clone(), style));
13379 } else {
13380 runs.push((range.start..label.filter_range.end, style));
13381 runs.push((label.filter_range.end..range.end, muted_style));
13382 }
13383 prev_end = cmp::max(prev_end, range.end);
13384
13385 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13386 runs.push((prev_end..label.text.len(), fade_out));
13387 }
13388
13389 runs
13390 })
13391}
13392
13393pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13394 let mut prev_index = 0;
13395 let mut prev_codepoint: Option<char> = None;
13396 text.char_indices()
13397 .chain([(text.len(), '\0')])
13398 .filter_map(move |(index, codepoint)| {
13399 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13400 let is_boundary = index == text.len()
13401 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13402 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13403 if is_boundary {
13404 let chunk = &text[prev_index..index];
13405 prev_index = index;
13406 Some(chunk)
13407 } else {
13408 None
13409 }
13410 })
13411}
13412
13413pub trait RangeToAnchorExt: Sized {
13414 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13415
13416 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13417 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13418 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13419 }
13420}
13421
13422impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13423 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13424 let start_offset = self.start.to_offset(snapshot);
13425 let end_offset = self.end.to_offset(snapshot);
13426 if start_offset == end_offset {
13427 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13428 } else {
13429 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13430 }
13431 }
13432}
13433
13434pub trait RowExt {
13435 fn as_f32(&self) -> f32;
13436
13437 fn next_row(&self) -> Self;
13438
13439 fn previous_row(&self) -> Self;
13440
13441 fn minus(&self, other: Self) -> u32;
13442}
13443
13444impl RowExt for DisplayRow {
13445 fn as_f32(&self) -> f32 {
13446 self.0 as f32
13447 }
13448
13449 fn next_row(&self) -> Self {
13450 Self(self.0 + 1)
13451 }
13452
13453 fn previous_row(&self) -> Self {
13454 Self(self.0.saturating_sub(1))
13455 }
13456
13457 fn minus(&self, other: Self) -> u32 {
13458 self.0 - other.0
13459 }
13460}
13461
13462impl RowExt for MultiBufferRow {
13463 fn as_f32(&self) -> f32 {
13464 self.0 as f32
13465 }
13466
13467 fn next_row(&self) -> Self {
13468 Self(self.0 + 1)
13469 }
13470
13471 fn previous_row(&self) -> Self {
13472 Self(self.0.saturating_sub(1))
13473 }
13474
13475 fn minus(&self, other: Self) -> u32 {
13476 self.0 - other.0
13477 }
13478}
13479
13480trait RowRangeExt {
13481 type Row;
13482
13483 fn len(&self) -> usize;
13484
13485 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13486}
13487
13488impl RowRangeExt for Range<MultiBufferRow> {
13489 type Row = MultiBufferRow;
13490
13491 fn len(&self) -> usize {
13492 (self.end.0 - self.start.0) as usize
13493 }
13494
13495 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13496 (self.start.0..self.end.0).map(MultiBufferRow)
13497 }
13498}
13499
13500impl RowRangeExt for Range<DisplayRow> {
13501 type Row = DisplayRow;
13502
13503 fn len(&self) -> usize {
13504 (self.end.0 - self.start.0) as usize
13505 }
13506
13507 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13508 (self.start.0..self.end.0).map(DisplayRow)
13509 }
13510}
13511
13512fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13513 if hunk.diff_base_byte_range.is_empty() {
13514 DiffHunkStatus::Added
13515 } else if hunk.associated_range.is_empty() {
13516 DiffHunkStatus::Removed
13517 } else {
13518 DiffHunkStatus::Modified
13519 }
13520}
13521
13522/// If select range has more than one line, we
13523/// just point the cursor to range.start.
13524fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13525 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13526 range
13527 } else {
13528 range.start..range.start
13529 }
13530}