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::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::FutureExt;
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use git::diff_hunk_to_display;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86use hunk_diff::ExpandedHunks;
87pub(crate) use hunk_diff::HoveredHunk;
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101use similar::{ChangeTag, TextDiff};
102use task::{ResolvedTask, TaskTemplate, TaskVariables};
103
104use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
105pub use lsp::CompletionContext;
106use lsp::{
107 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
108 LanguageServerId,
109};
110use mouse_context_menu::MouseContextMenu;
111use movement::TextLayoutDetails;
112pub use multi_buffer::{
113 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
114 ToPoint,
115};
116use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
117use ordered_float::OrderedFloat;
118use parking_lot::{Mutex, RwLock};
119use project::project_settings::{GitGutterSetting, ProjectSettings};
120use project::{
121 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
122 ProjectTransaction, TaskSourceKind,
123};
124use rand::prelude::*;
125use rpc::{proto::*, ErrorExt};
126use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
127use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
128use serde::{Deserialize, Serialize};
129use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
130use smallvec::SmallVec;
131use snippet::Snippet;
132use std::{
133 any::TypeId,
134 borrow::Cow,
135 cell::RefCell,
136 cmp::{self, Ordering, Reverse},
137 mem,
138 num::NonZeroU32,
139 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
140 path::{Path, PathBuf},
141 rc::Rc,
142 sync::Arc,
143 time::{Duration, Instant},
144};
145pub use sum_tree::Bias;
146use sum_tree::TreeMap;
147use text::{BufferId, OffsetUtf16, Rope};
148use theme::{
149 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
150 ThemeColors, ThemeSettings,
151};
152use ui::{
153 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
154 ListItem, Popover, Tooltip,
155};
156use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
157use workspace::item::{ItemHandle, PreviewTabsSettings};
158use workspace::notifications::{DetachAndPromptErr, NotificationId};
159use workspace::{
160 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
161};
162use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
163
164use crate::hover_links::find_url;
165use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
166
167pub const FILE_HEADER_HEIGHT: u32 = 1;
168pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
169pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
170pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
171const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
172const MAX_LINE_LEN: usize = 1024;
173const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
174const MAX_SELECTION_HISTORY_LEN: usize = 1024;
175pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
176#[doc(hidden)]
177pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
178#[doc(hidden)]
179pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
180
181pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
182pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
183
184pub fn render_parsed_markdown(
185 element_id: impl Into<ElementId>,
186 parsed: &language::ParsedMarkdown,
187 editor_style: &EditorStyle,
188 workspace: Option<WeakView<Workspace>>,
189 cx: &mut WindowContext,
190) -> InteractiveText {
191 let code_span_background_color = cx
192 .theme()
193 .colors()
194 .editor_document_highlight_read_background;
195
196 let highlights = gpui::combine_highlights(
197 parsed.highlights.iter().filter_map(|(range, highlight)| {
198 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
199 Some((range.clone(), highlight))
200 }),
201 parsed
202 .regions
203 .iter()
204 .zip(&parsed.region_ranges)
205 .filter_map(|(region, range)| {
206 if region.code {
207 Some((
208 range.clone(),
209 HighlightStyle {
210 background_color: Some(code_span_background_color),
211 ..Default::default()
212 },
213 ))
214 } else {
215 None
216 }
217 }),
218 );
219
220 let mut links = Vec::new();
221 let mut link_ranges = Vec::new();
222 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
223 if let Some(link) = region.link.clone() {
224 links.push(link);
225 link_ranges.push(range.clone());
226 }
227 }
228
229 InteractiveText::new(
230 element_id,
231 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
232 )
233 .on_click(link_ranges, move |clicked_range_ix, cx| {
234 match &links[clicked_range_ix] {
235 markdown::Link::Web { url } => cx.open_url(url),
236 markdown::Link::Path { path } => {
237 if let Some(workspace) = &workspace {
238 _ = workspace.update(cx, |workspace, cx| {
239 workspace.open_abs_path(path.clone(), false, cx).detach();
240 });
241 }
242 }
243 }
244 })
245}
246
247#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
248pub(crate) enum InlayId {
249 Suggestion(usize),
250 Hint(usize),
251}
252
253impl InlayId {
254 fn id(&self) -> usize {
255 match self {
256 Self::Suggestion(id) => *id,
257 Self::Hint(id) => *id,
258 }
259 }
260}
261
262enum DiffRowHighlight {}
263enum DocumentHighlightRead {}
264enum DocumentHighlightWrite {}
265enum InputComposition {}
266
267#[derive(Copy, Clone, PartialEq, Eq)]
268pub enum Direction {
269 Prev,
270 Next,
271}
272
273#[derive(Debug, Copy, Clone, PartialEq, Eq)]
274pub enum Navigated {
275 Yes,
276 No,
277}
278
279impl Navigated {
280 pub fn from_bool(yes: bool) -> Navigated {
281 if yes {
282 Navigated::Yes
283 } else {
284 Navigated::No
285 }
286 }
287}
288
289pub fn init_settings(cx: &mut AppContext) {
290 EditorSettings::register(cx);
291}
292
293pub fn init(cx: &mut AppContext) {
294 init_settings(cx);
295
296 workspace::register_project_item::<Editor>(cx);
297 workspace::FollowableViewRegistry::register::<Editor>(cx);
298 workspace::register_serializable_item::<Editor>(cx);
299
300 cx.observe_new_views(
301 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
302 workspace.register_action(Editor::new_file);
303 workspace.register_action(Editor::new_file_vertical);
304 workspace.register_action(Editor::new_file_horizontal);
305 },
306 )
307 .detach();
308
309 cx.on_action(move |_: &workspace::NewFile, cx| {
310 let app_state = workspace::AppState::global(cx);
311 if let Some(app_state) = app_state.upgrade() {
312 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
313 Editor::new_file(workspace, &Default::default(), cx)
314 })
315 .detach();
316 }
317 });
318 cx.on_action(move |_: &workspace::NewWindow, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327}
328
329pub struct SearchWithinRange;
330
331trait InvalidationRegion {
332 fn ranges(&self) -> &[Range<Anchor>];
333}
334
335#[derive(Clone, Debug, PartialEq)]
336pub enum SelectPhase {
337 Begin {
338 position: DisplayPoint,
339 add: bool,
340 click_count: usize,
341 },
342 BeginColumnar {
343 position: DisplayPoint,
344 reset: bool,
345 goal_column: u32,
346 },
347 Extend {
348 position: DisplayPoint,
349 click_count: usize,
350 },
351 Update {
352 position: DisplayPoint,
353 goal_column: u32,
354 scroll_delta: gpui::Point<f32>,
355 },
356 End,
357}
358
359#[derive(Clone, Debug)]
360pub enum SelectMode {
361 Character,
362 Word(Range<Anchor>),
363 Line(Range<Anchor>),
364 All,
365}
366
367#[derive(Copy, Clone, PartialEq, Eq, Debug)]
368pub enum EditorMode {
369 SingleLine { auto_width: bool },
370 AutoHeight { max_lines: usize },
371 Full,
372}
373
374#[derive(Clone, Debug)]
375pub enum SoftWrap {
376 None,
377 PreferLine,
378 EditorWidth,
379 Column(u32),
380 Bounded(u32),
381}
382
383#[derive(Clone)]
384pub struct EditorStyle {
385 pub background: Hsla,
386 pub local_player: PlayerColor,
387 pub text: TextStyle,
388 pub scrollbar_width: Pixels,
389 pub syntax: Arc<SyntaxTheme>,
390 pub status: StatusColors,
391 pub inlay_hints_style: HighlightStyle,
392 pub suggestions_style: HighlightStyle,
393 pub unnecessary_code_fade: f32,
394}
395
396impl Default for EditorStyle {
397 fn default() -> Self {
398 Self {
399 background: Hsla::default(),
400 local_player: PlayerColor::default(),
401 text: TextStyle::default(),
402 scrollbar_width: Pixels::default(),
403 syntax: Default::default(),
404 // HACK: Status colors don't have a real default.
405 // We should look into removing the status colors from the editor
406 // style and retrieve them directly from the theme.
407 status: StatusColors::dark(),
408 inlay_hints_style: HighlightStyle::default(),
409 suggestions_style: HighlightStyle::default(),
410 unnecessary_code_fade: Default::default(),
411 }
412 }
413}
414
415type CompletionId = usize;
416
417#[derive(Clone, Debug)]
418struct CompletionState {
419 // render_inlay_ids represents the inlay hints that are inserted
420 // for rendering the inline completions. They may be discontinuous
421 // in the event that the completion provider returns some intersection
422 // with the existing content.
423 render_inlay_ids: Vec<InlayId>,
424 // text is the resulting rope that is inserted when the user accepts a completion.
425 text: Rope,
426 // position is the position of the cursor when the completion was triggered.
427 position: multi_buffer::Anchor,
428 // delete_range is the range of text that this completion state covers.
429 // if the completion is accepted, this range should be deleted.
430 delete_range: Option<Range<multi_buffer::Anchor>>,
431}
432
433#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
434struct EditorActionId(usize);
435
436impl EditorActionId {
437 pub fn post_inc(&mut self) -> Self {
438 let answer = self.0;
439
440 *self = Self(answer + 1);
441
442 Self(answer)
443 }
444}
445
446// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
447// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
448
449type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
450type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
451
452#[derive(Default)]
453struct ScrollbarMarkerState {
454 scrollbar_size: Size<Pixels>,
455 dirty: bool,
456 markers: Arc<[PaintQuad]>,
457 pending_refresh: Option<Task<Result<()>>>,
458}
459
460impl ScrollbarMarkerState {
461 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
462 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
463 }
464}
465
466#[derive(Clone, Debug)]
467struct RunnableTasks {
468 templates: Vec<(TaskSourceKind, TaskTemplate)>,
469 offset: MultiBufferOffset,
470 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
471 column: u32,
472 // Values of all named captures, including those starting with '_'
473 extra_variables: HashMap<String, String>,
474 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
475 context_range: Range<BufferOffset>,
476}
477
478#[derive(Clone)]
479struct ResolvedTasks {
480 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
481 position: Anchor,
482}
483#[derive(Copy, Clone, Debug)]
484struct MultiBufferOffset(usize);
485#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
486struct BufferOffset(usize);
487
488// Addons allow storing per-editor state in other crates (e.g. Vim)
489pub trait Addon: 'static {
490 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
491
492 fn to_any(&self) -> &dyn std::any::Any;
493}
494
495/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
496///
497/// See the [module level documentation](self) for more information.
498pub struct Editor {
499 focus_handle: FocusHandle,
500 last_focused_descendant: Option<WeakFocusHandle>,
501 /// The text buffer being edited
502 buffer: Model<MultiBuffer>,
503 /// Map of how text in the buffer should be displayed.
504 /// Handles soft wraps, folds, fake inlay text insertions, etc.
505 pub display_map: Model<DisplayMap>,
506 pub selections: SelectionsCollection,
507 pub scroll_manager: ScrollManager,
508 /// When inline assist editors are linked, they all render cursors because
509 /// typing enters text into each of them, even the ones that aren't focused.
510 pub(crate) show_cursor_when_unfocused: bool,
511 columnar_selection_tail: Option<Anchor>,
512 add_selections_state: Option<AddSelectionsState>,
513 select_next_state: Option<SelectNextState>,
514 select_prev_state: Option<SelectNextState>,
515 selection_history: SelectionHistory,
516 autoclose_regions: Vec<AutocloseRegion>,
517 snippet_stack: InvalidationStack<SnippetState>,
518 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
519 ime_transaction: Option<TransactionId>,
520 active_diagnostics: Option<ActiveDiagnosticGroup>,
521 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
522 project: Option<Model<Project>>,
523 completion_provider: Option<Box<dyn CompletionProvider>>,
524 collaboration_hub: Option<Box<dyn CollaborationHub>>,
525 blink_manager: Model<BlinkManager>,
526 show_cursor_names: bool,
527 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
528 pub show_local_selections: bool,
529 mode: EditorMode,
530 show_breadcrumbs: bool,
531 show_gutter: bool,
532 show_line_numbers: Option<bool>,
533 use_relative_line_numbers: Option<bool>,
534 show_git_diff_gutter: Option<bool>,
535 show_code_actions: Option<bool>,
536 show_runnables: Option<bool>,
537 show_wrap_guides: Option<bool>,
538 show_indent_guides: Option<bool>,
539 placeholder_text: Option<Arc<str>>,
540 highlight_order: usize,
541 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
542 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
543 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
544 scrollbar_marker_state: ScrollbarMarkerState,
545 active_indent_guides_state: ActiveIndentGuidesState,
546 nav_history: Option<ItemNavHistory>,
547 context_menu: RwLock<Option<ContextMenu>>,
548 mouse_context_menu: Option<MouseContextMenu>,
549 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
550 signature_help_state: SignatureHelpState,
551 auto_signature_help: Option<bool>,
552 find_all_references_task_sources: Vec<Anchor>,
553 next_completion_id: CompletionId,
554 completion_documentation_pre_resolve_debounce: DebouncedDelay,
555 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
556 code_actions_task: Option<Task<()>>,
557 document_highlights_task: Option<Task<()>>,
558 linked_editing_range_task: Option<Task<Option<()>>>,
559 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
560 pending_rename: Option<RenameState>,
561 searchable: bool,
562 cursor_shape: CursorShape,
563 current_line_highlight: Option<CurrentLineHighlight>,
564 collapse_matches: bool,
565 autoindent_mode: Option<AutoindentMode>,
566 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
567 input_enabled: bool,
568 use_modal_editing: bool,
569 read_only: bool,
570 leader_peer_id: Option<PeerId>,
571 remote_id: Option<ViewId>,
572 hover_state: HoverState,
573 gutter_hovered: bool,
574 hovered_link_state: Option<HoveredLinkState>,
575 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
576 active_inline_completion: Option<CompletionState>,
577 // enable_inline_completions is a switch that Vim can use to disable
578 // inline completions based on its mode.
579 enable_inline_completions: bool,
580 show_inline_completions_override: Option<bool>,
581 inlay_hint_cache: InlayHintCache,
582 expanded_hunks: ExpandedHunks,
583 next_inlay_id: usize,
584 _subscriptions: Vec<Subscription>,
585 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
586 gutter_dimensions: GutterDimensions,
587 style: Option<EditorStyle>,
588 next_editor_action_id: EditorActionId,
589 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
590 use_autoclose: bool,
591 use_auto_surround: bool,
592 auto_replace_emoji_shortcode: bool,
593 show_git_blame_gutter: bool,
594 show_git_blame_inline: bool,
595 show_git_blame_inline_delay_task: Option<Task<()>>,
596 git_blame_inline_enabled: bool,
597 serialize_dirty_buffers: bool,
598 show_selection_menu: Option<bool>,
599 blame: Option<Model<GitBlame>>,
600 blame_subscription: Option<Subscription>,
601 custom_context_menu: Option<
602 Box<
603 dyn 'static
604 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
605 >,
606 >,
607 last_bounds: Option<Bounds<Pixels>>,
608 expect_bounds_change: Option<Bounds<Pixels>>,
609 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
610 tasks_update_task: Option<Task<()>>,
611 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
612 file_header_size: u32,
613 breadcrumb_header: Option<String>,
614 focused_block: Option<FocusedBlock>,
615 next_scroll_position: NextScrollCursorCenterTopBottom,
616 addons: HashMap<TypeId, Box<dyn Addon>>,
617 _scroll_cursor_center_top_bottom_task: Task<()>,
618}
619
620#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
621enum NextScrollCursorCenterTopBottom {
622 #[default]
623 Center,
624 Top,
625 Bottom,
626}
627
628impl NextScrollCursorCenterTopBottom {
629 fn next(&self) -> Self {
630 match self {
631 Self::Center => Self::Top,
632 Self::Top => Self::Bottom,
633 Self::Bottom => Self::Center,
634 }
635 }
636}
637
638#[derive(Clone)]
639pub struct EditorSnapshot {
640 pub mode: EditorMode,
641 show_gutter: bool,
642 show_line_numbers: Option<bool>,
643 show_git_diff_gutter: Option<bool>,
644 show_code_actions: Option<bool>,
645 show_runnables: Option<bool>,
646 render_git_blame_gutter: bool,
647 pub display_snapshot: DisplaySnapshot,
648 pub placeholder_text: Option<Arc<str>>,
649 is_focused: bool,
650 scroll_anchor: ScrollAnchor,
651 ongoing_scroll: OngoingScroll,
652 current_line_highlight: CurrentLineHighlight,
653 gutter_hovered: bool,
654}
655
656const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
657
658#[derive(Default, Debug, Clone, Copy)]
659pub struct GutterDimensions {
660 pub left_padding: Pixels,
661 pub right_padding: Pixels,
662 pub width: Pixels,
663 pub margin: Pixels,
664 pub git_blame_entries_width: Option<Pixels>,
665}
666
667impl GutterDimensions {
668 /// The full width of the space taken up by the gutter.
669 pub fn full_width(&self) -> Pixels {
670 self.margin + self.width
671 }
672
673 /// The width of the space reserved for the fold indicators,
674 /// use alongside 'justify_end' and `gutter_width` to
675 /// right align content with the line numbers
676 pub fn fold_area_width(&self) -> Pixels {
677 self.margin + self.right_padding
678 }
679}
680
681#[derive(Debug)]
682pub struct RemoteSelection {
683 pub replica_id: ReplicaId,
684 pub selection: Selection<Anchor>,
685 pub cursor_shape: CursorShape,
686 pub peer_id: PeerId,
687 pub line_mode: bool,
688 pub participant_index: Option<ParticipantIndex>,
689 pub user_name: Option<SharedString>,
690}
691
692#[derive(Clone, Debug)]
693struct SelectionHistoryEntry {
694 selections: Arc<[Selection<Anchor>]>,
695 select_next_state: Option<SelectNextState>,
696 select_prev_state: Option<SelectNextState>,
697 add_selections_state: Option<AddSelectionsState>,
698}
699
700enum SelectionHistoryMode {
701 Normal,
702 Undoing,
703 Redoing,
704}
705
706#[derive(Clone, PartialEq, Eq, Hash)]
707struct HoveredCursor {
708 replica_id: u16,
709 selection_id: usize,
710}
711
712impl Default for SelectionHistoryMode {
713 fn default() -> Self {
714 Self::Normal
715 }
716}
717
718#[derive(Default)]
719struct SelectionHistory {
720 #[allow(clippy::type_complexity)]
721 selections_by_transaction:
722 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
723 mode: SelectionHistoryMode,
724 undo_stack: VecDeque<SelectionHistoryEntry>,
725 redo_stack: VecDeque<SelectionHistoryEntry>,
726}
727
728impl SelectionHistory {
729 fn insert_transaction(
730 &mut self,
731 transaction_id: TransactionId,
732 selections: Arc<[Selection<Anchor>]>,
733 ) {
734 self.selections_by_transaction
735 .insert(transaction_id, (selections, None));
736 }
737
738 #[allow(clippy::type_complexity)]
739 fn transaction(
740 &self,
741 transaction_id: TransactionId,
742 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
743 self.selections_by_transaction.get(&transaction_id)
744 }
745
746 #[allow(clippy::type_complexity)]
747 fn transaction_mut(
748 &mut self,
749 transaction_id: TransactionId,
750 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
751 self.selections_by_transaction.get_mut(&transaction_id)
752 }
753
754 fn push(&mut self, entry: SelectionHistoryEntry) {
755 if !entry.selections.is_empty() {
756 match self.mode {
757 SelectionHistoryMode::Normal => {
758 self.push_undo(entry);
759 self.redo_stack.clear();
760 }
761 SelectionHistoryMode::Undoing => self.push_redo(entry),
762 SelectionHistoryMode::Redoing => self.push_undo(entry),
763 }
764 }
765 }
766
767 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
768 if self
769 .undo_stack
770 .back()
771 .map_or(true, |e| e.selections != entry.selections)
772 {
773 self.undo_stack.push_back(entry);
774 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
775 self.undo_stack.pop_front();
776 }
777 }
778 }
779
780 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
781 if self
782 .redo_stack
783 .back()
784 .map_or(true, |e| e.selections != entry.selections)
785 {
786 self.redo_stack.push_back(entry);
787 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
788 self.redo_stack.pop_front();
789 }
790 }
791 }
792}
793
794struct RowHighlight {
795 index: usize,
796 range: RangeInclusive<Anchor>,
797 color: Option<Hsla>,
798 should_autoscroll: bool,
799}
800
801#[derive(Clone, Debug)]
802struct AddSelectionsState {
803 above: bool,
804 stack: Vec<usize>,
805}
806
807#[derive(Clone)]
808struct SelectNextState {
809 query: AhoCorasick,
810 wordwise: bool,
811 done: bool,
812}
813
814impl std::fmt::Debug for SelectNextState {
815 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
816 f.debug_struct(std::any::type_name::<Self>())
817 .field("wordwise", &self.wordwise)
818 .field("done", &self.done)
819 .finish()
820 }
821}
822
823#[derive(Debug)]
824struct AutocloseRegion {
825 selection_id: usize,
826 range: Range<Anchor>,
827 pair: BracketPair,
828}
829
830#[derive(Debug)]
831struct SnippetState {
832 ranges: Vec<Vec<Range<Anchor>>>,
833 active_index: usize,
834}
835
836#[doc(hidden)]
837pub struct RenameState {
838 pub range: Range<Anchor>,
839 pub old_name: Arc<str>,
840 pub editor: View<Editor>,
841 block_id: CustomBlockId,
842}
843
844struct InvalidationStack<T>(Vec<T>);
845
846struct RegisteredInlineCompletionProvider {
847 provider: Arc<dyn InlineCompletionProviderHandle>,
848 _subscription: Subscription,
849}
850
851enum ContextMenu {
852 Completions(CompletionsMenu),
853 CodeActions(CodeActionsMenu),
854}
855
856impl ContextMenu {
857 fn select_first(
858 &mut self,
859 project: Option<&Model<Project>>,
860 cx: &mut ViewContext<Editor>,
861 ) -> bool {
862 if self.visible() {
863 match self {
864 ContextMenu::Completions(menu) => menu.select_first(project, cx),
865 ContextMenu::CodeActions(menu) => menu.select_first(cx),
866 }
867 true
868 } else {
869 false
870 }
871 }
872
873 fn select_prev(
874 &mut self,
875 project: Option<&Model<Project>>,
876 cx: &mut ViewContext<Editor>,
877 ) -> bool {
878 if self.visible() {
879 match self {
880 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
881 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
882 }
883 true
884 } else {
885 false
886 }
887 }
888
889 fn select_next(
890 &mut self,
891 project: Option<&Model<Project>>,
892 cx: &mut ViewContext<Editor>,
893 ) -> bool {
894 if self.visible() {
895 match self {
896 ContextMenu::Completions(menu) => menu.select_next(project, cx),
897 ContextMenu::CodeActions(menu) => menu.select_next(cx),
898 }
899 true
900 } else {
901 false
902 }
903 }
904
905 fn select_last(
906 &mut self,
907 project: Option<&Model<Project>>,
908 cx: &mut ViewContext<Editor>,
909 ) -> bool {
910 if self.visible() {
911 match self {
912 ContextMenu::Completions(menu) => menu.select_last(project, cx),
913 ContextMenu::CodeActions(menu) => menu.select_last(cx),
914 }
915 true
916 } else {
917 false
918 }
919 }
920
921 fn visible(&self) -> bool {
922 match self {
923 ContextMenu::Completions(menu) => menu.visible(),
924 ContextMenu::CodeActions(menu) => menu.visible(),
925 }
926 }
927
928 fn render(
929 &self,
930 cursor_position: DisplayPoint,
931 style: &EditorStyle,
932 max_height: Pixels,
933 workspace: Option<WeakView<Workspace>>,
934 cx: &mut ViewContext<Editor>,
935 ) -> (ContextMenuOrigin, AnyElement) {
936 match self {
937 ContextMenu::Completions(menu) => (
938 ContextMenuOrigin::EditorPoint(cursor_position),
939 menu.render(style, max_height, workspace, cx),
940 ),
941 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
942 }
943 }
944}
945
946enum ContextMenuOrigin {
947 EditorPoint(DisplayPoint),
948 GutterIndicator(DisplayRow),
949}
950
951#[derive(Clone)]
952struct CompletionsMenu {
953 id: CompletionId,
954 sort_completions: bool,
955 initial_position: Anchor,
956 buffer: Model<Buffer>,
957 completions: Arc<RwLock<Box<[Completion]>>>,
958 match_candidates: Arc<[StringMatchCandidate]>,
959 matches: Arc<[StringMatch]>,
960 selected_item: usize,
961 scroll_handle: UniformListScrollHandle,
962 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
963}
964
965impl CompletionsMenu {
966 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
967 self.selected_item = 0;
968 self.scroll_handle.scroll_to_item(self.selected_item);
969 self.attempt_resolve_selected_completion_documentation(project, cx);
970 cx.notify();
971 }
972
973 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
974 if self.selected_item > 0 {
975 self.selected_item -= 1;
976 } else {
977 self.selected_item = self.matches.len() - 1;
978 }
979 self.scroll_handle.scroll_to_item(self.selected_item);
980 self.attempt_resolve_selected_completion_documentation(project, cx);
981 cx.notify();
982 }
983
984 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
985 if self.selected_item + 1 < self.matches.len() {
986 self.selected_item += 1;
987 } else {
988 self.selected_item = 0;
989 }
990 self.scroll_handle.scroll_to_item(self.selected_item);
991 self.attempt_resolve_selected_completion_documentation(project, cx);
992 cx.notify();
993 }
994
995 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
996 self.selected_item = self.matches.len() - 1;
997 self.scroll_handle.scroll_to_item(self.selected_item);
998 self.attempt_resolve_selected_completion_documentation(project, cx);
999 cx.notify();
1000 }
1001
1002 fn pre_resolve_completion_documentation(
1003 buffer: Model<Buffer>,
1004 completions: Arc<RwLock<Box<[Completion]>>>,
1005 matches: Arc<[StringMatch]>,
1006 editor: &Editor,
1007 cx: &mut ViewContext<Editor>,
1008 ) -> Task<()> {
1009 let settings = EditorSettings::get_global(cx);
1010 if !settings.show_completion_documentation {
1011 return Task::ready(());
1012 }
1013
1014 let Some(provider) = editor.completion_provider.as_ref() else {
1015 return Task::ready(());
1016 };
1017
1018 let resolve_task = provider.resolve_completions(
1019 buffer,
1020 matches.iter().map(|m| m.candidate_id).collect(),
1021 completions.clone(),
1022 cx,
1023 );
1024
1025 cx.spawn(move |this, mut cx| async move {
1026 if let Some(true) = resolve_task.await.log_err() {
1027 this.update(&mut cx, |_, cx| cx.notify()).ok();
1028 }
1029 })
1030 }
1031
1032 fn attempt_resolve_selected_completion_documentation(
1033 &mut self,
1034 project: Option<&Model<Project>>,
1035 cx: &mut ViewContext<Editor>,
1036 ) {
1037 let settings = EditorSettings::get_global(cx);
1038 if !settings.show_completion_documentation {
1039 return;
1040 }
1041
1042 let completion_index = self.matches[self.selected_item].candidate_id;
1043 let Some(project) = project else {
1044 return;
1045 };
1046
1047 let resolve_task = project.update(cx, |project, cx| {
1048 project.resolve_completions(
1049 self.buffer.clone(),
1050 vec![completion_index],
1051 self.completions.clone(),
1052 cx,
1053 )
1054 });
1055
1056 let delay_ms =
1057 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1058 let delay = Duration::from_millis(delay_ms);
1059
1060 self.selected_completion_documentation_resolve_debounce
1061 .lock()
1062 .fire_new(delay, cx, |_, cx| {
1063 cx.spawn(move |this, mut cx| async move {
1064 if let Some(true) = resolve_task.await.log_err() {
1065 this.update(&mut cx, |_, cx| cx.notify()).ok();
1066 }
1067 })
1068 });
1069 }
1070
1071 fn visible(&self) -> bool {
1072 !self.matches.is_empty()
1073 }
1074
1075 fn render(
1076 &self,
1077 style: &EditorStyle,
1078 max_height: Pixels,
1079 workspace: Option<WeakView<Workspace>>,
1080 cx: &mut ViewContext<Editor>,
1081 ) -> AnyElement {
1082 let settings = EditorSettings::get_global(cx);
1083 let show_completion_documentation = settings.show_completion_documentation;
1084
1085 let widest_completion_ix = self
1086 .matches
1087 .iter()
1088 .enumerate()
1089 .max_by_key(|(_, mat)| {
1090 let completions = self.completions.read();
1091 let completion = &completions[mat.candidate_id];
1092 let documentation = &completion.documentation;
1093
1094 let mut len = completion.label.text.chars().count();
1095 if let Some(Documentation::SingleLine(text)) = documentation {
1096 if show_completion_documentation {
1097 len += text.chars().count();
1098 }
1099 }
1100
1101 len
1102 })
1103 .map(|(ix, _)| ix);
1104
1105 let completions = self.completions.clone();
1106 let matches = self.matches.clone();
1107 let selected_item = self.selected_item;
1108 let style = style.clone();
1109
1110 let multiline_docs = if show_completion_documentation {
1111 let mat = &self.matches[selected_item];
1112 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1113 Some(Documentation::MultiLinePlainText(text)) => {
1114 Some(div().child(SharedString::from(text.clone())))
1115 }
1116 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1117 Some(div().child(render_parsed_markdown(
1118 "completions_markdown",
1119 parsed,
1120 &style,
1121 workspace,
1122 cx,
1123 )))
1124 }
1125 _ => None,
1126 };
1127 multiline_docs.map(|div| {
1128 div.id("multiline_docs")
1129 .max_h(max_height)
1130 .flex_1()
1131 .px_1p5()
1132 .py_1()
1133 .min_w(px(260.))
1134 .max_w(px(640.))
1135 .w(px(500.))
1136 .overflow_y_scroll()
1137 .occlude()
1138 })
1139 } else {
1140 None
1141 };
1142
1143 let list = uniform_list(
1144 cx.view().clone(),
1145 "completions",
1146 matches.len(),
1147 move |_editor, range, cx| {
1148 let start_ix = range.start;
1149 let completions_guard = completions.read();
1150
1151 matches[range]
1152 .iter()
1153 .enumerate()
1154 .map(|(ix, mat)| {
1155 let item_ix = start_ix + ix;
1156 let candidate_id = mat.candidate_id;
1157 let completion = &completions_guard[candidate_id];
1158
1159 let documentation = if show_completion_documentation {
1160 &completion.documentation
1161 } else {
1162 &None
1163 };
1164
1165 let highlights = gpui::combine_highlights(
1166 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1167 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1168 |(range, mut highlight)| {
1169 // Ignore font weight for syntax highlighting, as we'll use it
1170 // for fuzzy matches.
1171 highlight.font_weight = None;
1172
1173 if completion.lsp_completion.deprecated.unwrap_or(false) {
1174 highlight.strikethrough = Some(StrikethroughStyle {
1175 thickness: 1.0.into(),
1176 ..Default::default()
1177 });
1178 highlight.color = Some(cx.theme().colors().text_muted);
1179 }
1180
1181 (range, highlight)
1182 },
1183 ),
1184 );
1185 let completion_label = StyledText::new(completion.label.text.clone())
1186 .with_highlights(&style.text, highlights);
1187 let documentation_label =
1188 if let Some(Documentation::SingleLine(text)) = documentation {
1189 if text.trim().is_empty() {
1190 None
1191 } else {
1192 Some(
1193 Label::new(text.clone())
1194 .ml_4()
1195 .size(LabelSize::Small)
1196 .color(Color::Muted),
1197 )
1198 }
1199 } else {
1200 None
1201 };
1202
1203 div().min_w(px(220.)).max_w(px(540.)).child(
1204 ListItem::new(mat.candidate_id)
1205 .inset(true)
1206 .selected(item_ix == selected_item)
1207 .on_click(cx.listener(move |editor, _event, cx| {
1208 cx.stop_propagation();
1209 if let Some(task) = editor.confirm_completion(
1210 &ConfirmCompletion {
1211 item_ix: Some(item_ix),
1212 },
1213 cx,
1214 ) {
1215 task.detach_and_log_err(cx)
1216 }
1217 }))
1218 .child(h_flex().overflow_hidden().child(completion_label))
1219 .end_slot::<Label>(documentation_label),
1220 )
1221 })
1222 .collect()
1223 },
1224 )
1225 .occlude()
1226 .max_h(max_height)
1227 .track_scroll(self.scroll_handle.clone())
1228 .with_width_from_item(widest_completion_ix)
1229 .with_sizing_behavior(ListSizingBehavior::Infer);
1230
1231 Popover::new()
1232 .child(list)
1233 .when_some(multiline_docs, |popover, multiline_docs| {
1234 popover.aside(multiline_docs)
1235 })
1236 .into_any_element()
1237 }
1238
1239 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1240 let mut matches = if let Some(query) = query {
1241 fuzzy::match_strings(
1242 &self.match_candidates,
1243 query,
1244 query.chars().any(|c| c.is_uppercase()),
1245 100,
1246 &Default::default(),
1247 executor,
1248 )
1249 .await
1250 } else {
1251 self.match_candidates
1252 .iter()
1253 .enumerate()
1254 .map(|(candidate_id, candidate)| StringMatch {
1255 candidate_id,
1256 score: Default::default(),
1257 positions: Default::default(),
1258 string: candidate.string.clone(),
1259 })
1260 .collect()
1261 };
1262
1263 // Remove all candidates where the query's start does not match the start of any word in the candidate
1264 if let Some(query) = query {
1265 if let Some(query_start) = query.chars().next() {
1266 matches.retain(|string_match| {
1267 split_words(&string_match.string).any(|word| {
1268 // Check that the first codepoint of the word as lowercase matches the first
1269 // codepoint of the query as lowercase
1270 word.chars()
1271 .flat_map(|codepoint| codepoint.to_lowercase())
1272 .zip(query_start.to_lowercase())
1273 .all(|(word_cp, query_cp)| word_cp == query_cp)
1274 })
1275 });
1276 }
1277 }
1278
1279 let completions = self.completions.read();
1280 if self.sort_completions {
1281 matches.sort_unstable_by_key(|mat| {
1282 // We do want to strike a balance here between what the language server tells us
1283 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1284 // `Creat` and there is a local variable called `CreateComponent`).
1285 // So what we do is: we bucket all matches into two buckets
1286 // - Strong matches
1287 // - Weak matches
1288 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1289 // and the Weak matches are the rest.
1290 //
1291 // For the strong matches, we sort by the language-servers score first and for the weak
1292 // matches, we prefer our fuzzy finder first.
1293 //
1294 // The thinking behind that: it's useless to take the sort_text the language-server gives
1295 // us into account when it's obviously a bad match.
1296
1297 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1298 enum MatchScore<'a> {
1299 Strong {
1300 sort_text: Option<&'a str>,
1301 score: Reverse<OrderedFloat<f64>>,
1302 sort_key: (usize, &'a str),
1303 },
1304 Weak {
1305 score: Reverse<OrderedFloat<f64>>,
1306 sort_text: Option<&'a str>,
1307 sort_key: (usize, &'a str),
1308 },
1309 }
1310
1311 let completion = &completions[mat.candidate_id];
1312 let sort_key = completion.sort_key();
1313 let sort_text = completion.lsp_completion.sort_text.as_deref();
1314 let score = Reverse(OrderedFloat(mat.score));
1315
1316 if mat.score >= 0.2 {
1317 MatchScore::Strong {
1318 sort_text,
1319 score,
1320 sort_key,
1321 }
1322 } else {
1323 MatchScore::Weak {
1324 score,
1325 sort_text,
1326 sort_key,
1327 }
1328 }
1329 });
1330 }
1331
1332 for mat in &mut matches {
1333 let completion = &completions[mat.candidate_id];
1334 mat.string.clone_from(&completion.label.text);
1335 for position in &mut mat.positions {
1336 *position += completion.label.filter_range.start;
1337 }
1338 }
1339 drop(completions);
1340
1341 self.matches = matches.into();
1342 self.selected_item = 0;
1343 }
1344}
1345
1346#[derive(Clone)]
1347struct CodeActionContents {
1348 tasks: Option<Arc<ResolvedTasks>>,
1349 actions: Option<Arc<[CodeAction]>>,
1350}
1351
1352impl CodeActionContents {
1353 fn len(&self) -> usize {
1354 match (&self.tasks, &self.actions) {
1355 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1356 (Some(tasks), None) => tasks.templates.len(),
1357 (None, Some(actions)) => actions.len(),
1358 (None, None) => 0,
1359 }
1360 }
1361
1362 fn is_empty(&self) -> bool {
1363 match (&self.tasks, &self.actions) {
1364 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1365 (Some(tasks), None) => tasks.templates.is_empty(),
1366 (None, Some(actions)) => actions.is_empty(),
1367 (None, None) => true,
1368 }
1369 }
1370
1371 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1372 self.tasks
1373 .iter()
1374 .flat_map(|tasks| {
1375 tasks
1376 .templates
1377 .iter()
1378 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1379 })
1380 .chain(self.actions.iter().flat_map(|actions| {
1381 actions
1382 .iter()
1383 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1384 }))
1385 }
1386 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1387 match (&self.tasks, &self.actions) {
1388 (Some(tasks), Some(actions)) => {
1389 if index < tasks.templates.len() {
1390 tasks
1391 .templates
1392 .get(index)
1393 .cloned()
1394 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1395 } else {
1396 actions
1397 .get(index - tasks.templates.len())
1398 .cloned()
1399 .map(CodeActionsItem::CodeAction)
1400 }
1401 }
1402 (Some(tasks), None) => tasks
1403 .templates
1404 .get(index)
1405 .cloned()
1406 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1407 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1408 (None, None) => None,
1409 }
1410 }
1411}
1412
1413#[allow(clippy::large_enum_variant)]
1414#[derive(Clone)]
1415enum CodeActionsItem {
1416 Task(TaskSourceKind, ResolvedTask),
1417 CodeAction(CodeAction),
1418}
1419
1420impl CodeActionsItem {
1421 fn as_task(&self) -> Option<&ResolvedTask> {
1422 let Self::Task(_, task) = self else {
1423 return None;
1424 };
1425 Some(task)
1426 }
1427 fn as_code_action(&self) -> Option<&CodeAction> {
1428 let Self::CodeAction(action) = self else {
1429 return None;
1430 };
1431 Some(action)
1432 }
1433 fn label(&self) -> String {
1434 match self {
1435 Self::CodeAction(action) => action.lsp_action.title.clone(),
1436 Self::Task(_, task) => task.resolved_label.clone(),
1437 }
1438 }
1439}
1440
1441struct CodeActionsMenu {
1442 actions: CodeActionContents,
1443 buffer: Model<Buffer>,
1444 selected_item: usize,
1445 scroll_handle: UniformListScrollHandle,
1446 deployed_from_indicator: Option<DisplayRow>,
1447}
1448
1449impl CodeActionsMenu {
1450 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1451 self.selected_item = 0;
1452 self.scroll_handle.scroll_to_item(self.selected_item);
1453 cx.notify()
1454 }
1455
1456 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1457 if self.selected_item > 0 {
1458 self.selected_item -= 1;
1459 } else {
1460 self.selected_item = self.actions.len() - 1;
1461 }
1462 self.scroll_handle.scroll_to_item(self.selected_item);
1463 cx.notify();
1464 }
1465
1466 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1467 if self.selected_item + 1 < self.actions.len() {
1468 self.selected_item += 1;
1469 } else {
1470 self.selected_item = 0;
1471 }
1472 self.scroll_handle.scroll_to_item(self.selected_item);
1473 cx.notify();
1474 }
1475
1476 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1477 self.selected_item = self.actions.len() - 1;
1478 self.scroll_handle.scroll_to_item(self.selected_item);
1479 cx.notify()
1480 }
1481
1482 fn visible(&self) -> bool {
1483 !self.actions.is_empty()
1484 }
1485
1486 fn render(
1487 &self,
1488 cursor_position: DisplayPoint,
1489 _style: &EditorStyle,
1490 max_height: Pixels,
1491 cx: &mut ViewContext<Editor>,
1492 ) -> (ContextMenuOrigin, AnyElement) {
1493 let actions = self.actions.clone();
1494 let selected_item = self.selected_item;
1495 let element = uniform_list(
1496 cx.view().clone(),
1497 "code_actions_menu",
1498 self.actions.len(),
1499 move |_this, range, cx| {
1500 actions
1501 .iter()
1502 .skip(range.start)
1503 .take(range.end - range.start)
1504 .enumerate()
1505 .map(|(ix, action)| {
1506 let item_ix = range.start + ix;
1507 let selected = selected_item == item_ix;
1508 let colors = cx.theme().colors();
1509 div()
1510 .px_1()
1511 .rounded_md()
1512 .text_color(colors.text)
1513 .when(selected, |style| {
1514 style
1515 .bg(colors.element_active)
1516 .text_color(colors.text_accent)
1517 })
1518 .hover(|style| {
1519 style
1520 .bg(colors.element_hover)
1521 .text_color(colors.text_accent)
1522 })
1523 .whitespace_nowrap()
1524 .when_some(action.as_code_action(), |this, action| {
1525 this.on_mouse_down(
1526 MouseButton::Left,
1527 cx.listener(move |editor, _, cx| {
1528 cx.stop_propagation();
1529 if let Some(task) = editor.confirm_code_action(
1530 &ConfirmCodeAction {
1531 item_ix: Some(item_ix),
1532 },
1533 cx,
1534 ) {
1535 task.detach_and_log_err(cx)
1536 }
1537 }),
1538 )
1539 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1540 .child(SharedString::from(action.lsp_action.title.clone()))
1541 })
1542 .when_some(action.as_task(), |this, task| {
1543 this.on_mouse_down(
1544 MouseButton::Left,
1545 cx.listener(move |editor, _, cx| {
1546 cx.stop_propagation();
1547 if let Some(task) = editor.confirm_code_action(
1548 &ConfirmCodeAction {
1549 item_ix: Some(item_ix),
1550 },
1551 cx,
1552 ) {
1553 task.detach_and_log_err(cx)
1554 }
1555 }),
1556 )
1557 .child(SharedString::from(task.resolved_label.clone()))
1558 })
1559 })
1560 .collect()
1561 },
1562 )
1563 .elevation_1(cx)
1564 .p_1()
1565 .max_h(max_height)
1566 .occlude()
1567 .track_scroll(self.scroll_handle.clone())
1568 .with_width_from_item(
1569 self.actions
1570 .iter()
1571 .enumerate()
1572 .max_by_key(|(_, action)| match action {
1573 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1574 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1575 })
1576 .map(|(ix, _)| ix),
1577 )
1578 .with_sizing_behavior(ListSizingBehavior::Infer)
1579 .into_any_element();
1580
1581 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1582 ContextMenuOrigin::GutterIndicator(row)
1583 } else {
1584 ContextMenuOrigin::EditorPoint(cursor_position)
1585 };
1586
1587 (cursor_position, element)
1588 }
1589}
1590
1591#[derive(Debug)]
1592struct ActiveDiagnosticGroup {
1593 primary_range: Range<Anchor>,
1594 primary_message: String,
1595 group_id: usize,
1596 blocks: HashMap<CustomBlockId, Diagnostic>,
1597 is_valid: bool,
1598}
1599
1600#[derive(Serialize, Deserialize, Clone, Debug)]
1601pub struct ClipboardSelection {
1602 pub len: usize,
1603 pub is_entire_line: bool,
1604 pub first_line_indent: u32,
1605}
1606
1607#[derive(Debug)]
1608pub(crate) struct NavigationData {
1609 cursor_anchor: Anchor,
1610 cursor_position: Point,
1611 scroll_anchor: ScrollAnchor,
1612 scroll_top_row: u32,
1613}
1614
1615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1616enum GotoDefinitionKind {
1617 Symbol,
1618 Declaration,
1619 Type,
1620 Implementation,
1621}
1622
1623#[derive(Debug, Clone)]
1624enum InlayHintRefreshReason {
1625 Toggle(bool),
1626 SettingsChange(InlayHintSettings),
1627 NewLinesShown,
1628 BufferEdited(HashSet<Arc<Language>>),
1629 RefreshRequested,
1630 ExcerptsRemoved(Vec<ExcerptId>),
1631}
1632
1633impl InlayHintRefreshReason {
1634 fn description(&self) -> &'static str {
1635 match self {
1636 Self::Toggle(_) => "toggle",
1637 Self::SettingsChange(_) => "settings change",
1638 Self::NewLinesShown => "new lines shown",
1639 Self::BufferEdited(_) => "buffer edited",
1640 Self::RefreshRequested => "refresh requested",
1641 Self::ExcerptsRemoved(_) => "excerpts removed",
1642 }
1643 }
1644}
1645
1646pub(crate) struct FocusedBlock {
1647 id: BlockId,
1648 focus_handle: WeakFocusHandle,
1649}
1650
1651impl Editor {
1652 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1653 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1654 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1655 Self::new(
1656 EditorMode::SingleLine { auto_width: false },
1657 buffer,
1658 None,
1659 false,
1660 cx,
1661 )
1662 }
1663
1664 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1665 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1666 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1667 Self::new(EditorMode::Full, buffer, None, false, cx)
1668 }
1669
1670 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1671 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1672 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1673 Self::new(
1674 EditorMode::SingleLine { auto_width: true },
1675 buffer,
1676 None,
1677 false,
1678 cx,
1679 )
1680 }
1681
1682 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1683 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1684 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1685 Self::new(
1686 EditorMode::AutoHeight { max_lines },
1687 buffer,
1688 None,
1689 false,
1690 cx,
1691 )
1692 }
1693
1694 pub fn for_buffer(
1695 buffer: Model<Buffer>,
1696 project: Option<Model<Project>>,
1697 cx: &mut ViewContext<Self>,
1698 ) -> Self {
1699 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1700 Self::new(EditorMode::Full, buffer, project, false, cx)
1701 }
1702
1703 pub fn for_multibuffer(
1704 buffer: Model<MultiBuffer>,
1705 project: Option<Model<Project>>,
1706 show_excerpt_controls: bool,
1707 cx: &mut ViewContext<Self>,
1708 ) -> Self {
1709 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1710 }
1711
1712 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1713 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1714 let mut clone = Self::new(
1715 self.mode,
1716 self.buffer.clone(),
1717 self.project.clone(),
1718 show_excerpt_controls,
1719 cx,
1720 );
1721 self.display_map.update(cx, |display_map, cx| {
1722 let snapshot = display_map.snapshot(cx);
1723 clone.display_map.update(cx, |display_map, cx| {
1724 display_map.set_state(&snapshot, cx);
1725 });
1726 });
1727 clone.selections.clone_state(&self.selections);
1728 clone.scroll_manager.clone_state(&self.scroll_manager);
1729 clone.searchable = self.searchable;
1730 clone
1731 }
1732
1733 pub fn new(
1734 mode: EditorMode,
1735 buffer: Model<MultiBuffer>,
1736 project: Option<Model<Project>>,
1737 show_excerpt_controls: bool,
1738 cx: &mut ViewContext<Self>,
1739 ) -> Self {
1740 let style = cx.text_style();
1741 let font_size = style.font_size.to_pixels(cx.rem_size());
1742 let editor = cx.view().downgrade();
1743 let fold_placeholder = FoldPlaceholder {
1744 constrain_width: true,
1745 render: Arc::new(move |fold_id, fold_range, cx| {
1746 let editor = editor.clone();
1747 div()
1748 .id(fold_id)
1749 .bg(cx.theme().colors().ghost_element_background)
1750 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1751 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1752 .rounded_sm()
1753 .size_full()
1754 .cursor_pointer()
1755 .child("⋯")
1756 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1757 .on_click(move |_, cx| {
1758 editor
1759 .update(cx, |editor, cx| {
1760 editor.unfold_ranges(
1761 [fold_range.start..fold_range.end],
1762 true,
1763 false,
1764 cx,
1765 );
1766 cx.stop_propagation();
1767 })
1768 .ok();
1769 })
1770 .into_any()
1771 }),
1772 merge_adjacent: true,
1773 };
1774 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1775 let display_map = cx.new_model(|cx| {
1776 DisplayMap::new(
1777 buffer.clone(),
1778 style.font(),
1779 font_size,
1780 None,
1781 show_excerpt_controls,
1782 file_header_size,
1783 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1784 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1785 fold_placeholder,
1786 cx,
1787 )
1788 });
1789
1790 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1791
1792 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1793
1794 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1795 .then(|| language_settings::SoftWrap::PreferLine);
1796
1797 let mut project_subscriptions = Vec::new();
1798 if mode == EditorMode::Full {
1799 if let Some(project) = project.as_ref() {
1800 if buffer.read(cx).is_singleton() {
1801 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1802 cx.emit(EditorEvent::TitleChanged);
1803 }));
1804 }
1805 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1806 if let project::Event::RefreshInlayHints = event {
1807 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1808 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1809 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1810 let focus_handle = editor.focus_handle(cx);
1811 if focus_handle.is_focused(cx) {
1812 let snapshot = buffer.read(cx).snapshot();
1813 for (range, snippet) in snippet_edits {
1814 let editor_range =
1815 language::range_from_lsp(*range).to_offset(&snapshot);
1816 editor
1817 .insert_snippet(&[editor_range], snippet.clone(), cx)
1818 .ok();
1819 }
1820 }
1821 }
1822 }
1823 }));
1824 let task_inventory = project.read(cx).task_inventory().clone();
1825 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1826 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1827 }));
1828 }
1829 }
1830
1831 let inlay_hint_settings = inlay_hint_settings(
1832 selections.newest_anchor().head(),
1833 &buffer.read(cx).snapshot(cx),
1834 cx,
1835 );
1836 let focus_handle = cx.focus_handle();
1837 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1838 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1839 .detach();
1840 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1841 .detach();
1842 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1843
1844 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1845 Some(false)
1846 } else {
1847 None
1848 };
1849
1850 let mut this = Self {
1851 focus_handle,
1852 show_cursor_when_unfocused: false,
1853 last_focused_descendant: None,
1854 buffer: buffer.clone(),
1855 display_map: display_map.clone(),
1856 selections,
1857 scroll_manager: ScrollManager::new(cx),
1858 columnar_selection_tail: None,
1859 add_selections_state: None,
1860 select_next_state: None,
1861 select_prev_state: None,
1862 selection_history: Default::default(),
1863 autoclose_regions: Default::default(),
1864 snippet_stack: Default::default(),
1865 select_larger_syntax_node_stack: Vec::new(),
1866 ime_transaction: Default::default(),
1867 active_diagnostics: None,
1868 soft_wrap_mode_override,
1869 completion_provider: project.clone().map(|project| Box::new(project) as _),
1870 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1871 project,
1872 blink_manager: blink_manager.clone(),
1873 show_local_selections: true,
1874 mode,
1875 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1876 show_gutter: mode == EditorMode::Full,
1877 show_line_numbers: None,
1878 use_relative_line_numbers: None,
1879 show_git_diff_gutter: None,
1880 show_code_actions: None,
1881 show_runnables: None,
1882 show_wrap_guides: None,
1883 show_indent_guides,
1884 placeholder_text: None,
1885 highlight_order: 0,
1886 highlighted_rows: HashMap::default(),
1887 background_highlights: Default::default(),
1888 gutter_highlights: TreeMap::default(),
1889 scrollbar_marker_state: ScrollbarMarkerState::default(),
1890 active_indent_guides_state: ActiveIndentGuidesState::default(),
1891 nav_history: None,
1892 context_menu: RwLock::new(None),
1893 mouse_context_menu: None,
1894 completion_tasks: Default::default(),
1895 signature_help_state: SignatureHelpState::default(),
1896 auto_signature_help: None,
1897 find_all_references_task_sources: Vec::new(),
1898 next_completion_id: 0,
1899 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1900 next_inlay_id: 0,
1901 available_code_actions: Default::default(),
1902 code_actions_task: Default::default(),
1903 document_highlights_task: Default::default(),
1904 linked_editing_range_task: Default::default(),
1905 pending_rename: Default::default(),
1906 searchable: true,
1907 cursor_shape: EditorSettings::get_global(cx)
1908 .cursor_shape
1909 .unwrap_or_default(),
1910 current_line_highlight: None,
1911 autoindent_mode: Some(AutoindentMode::EachLine),
1912 collapse_matches: false,
1913 workspace: None,
1914 input_enabled: true,
1915 use_modal_editing: mode == EditorMode::Full,
1916 read_only: false,
1917 use_autoclose: true,
1918 use_auto_surround: true,
1919 auto_replace_emoji_shortcode: false,
1920 leader_peer_id: None,
1921 remote_id: None,
1922 hover_state: Default::default(),
1923 hovered_link_state: Default::default(),
1924 inline_completion_provider: None,
1925 active_inline_completion: None,
1926 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1927 expanded_hunks: ExpandedHunks::default(),
1928 gutter_hovered: false,
1929 pixel_position_of_newest_cursor: None,
1930 last_bounds: None,
1931 expect_bounds_change: None,
1932 gutter_dimensions: GutterDimensions::default(),
1933 style: None,
1934 show_cursor_names: false,
1935 hovered_cursors: Default::default(),
1936 next_editor_action_id: EditorActionId::default(),
1937 editor_actions: Rc::default(),
1938 show_inline_completions_override: None,
1939 enable_inline_completions: true,
1940 custom_context_menu: None,
1941 show_git_blame_gutter: false,
1942 show_git_blame_inline: false,
1943 show_selection_menu: None,
1944 show_git_blame_inline_delay_task: None,
1945 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1946 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1947 .session
1948 .restore_unsaved_buffers,
1949 blame: None,
1950 blame_subscription: None,
1951 file_header_size,
1952 tasks: Default::default(),
1953 _subscriptions: vec![
1954 cx.observe(&buffer, Self::on_buffer_changed),
1955 cx.subscribe(&buffer, Self::on_buffer_event),
1956 cx.observe(&display_map, Self::on_display_map_changed),
1957 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1958 cx.observe_global::<SettingsStore>(Self::settings_changed),
1959 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1960 cx.observe_window_activation(|editor, cx| {
1961 let active = cx.is_window_active();
1962 editor.blink_manager.update(cx, |blink_manager, cx| {
1963 if active {
1964 blink_manager.enable(cx);
1965 } else {
1966 blink_manager.disable(cx);
1967 }
1968 });
1969 }),
1970 ],
1971 tasks_update_task: None,
1972 linked_edit_ranges: Default::default(),
1973 previous_search_ranges: None,
1974 breadcrumb_header: None,
1975 focused_block: None,
1976 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1977 addons: HashMap::default(),
1978 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1979 };
1980 this.tasks_update_task = Some(this.refresh_runnables(cx));
1981 this._subscriptions.extend(project_subscriptions);
1982
1983 this.end_selection(cx);
1984 this.scroll_manager.show_scrollbar(cx);
1985
1986 if mode == EditorMode::Full {
1987 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1988 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1989
1990 if this.git_blame_inline_enabled {
1991 this.git_blame_inline_enabled = true;
1992 this.start_git_blame_inline(false, cx);
1993 }
1994 }
1995
1996 this.report_editor_event("open", None, cx);
1997 this
1998 }
1999
2000 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2001 self.mouse_context_menu
2002 .as_ref()
2003 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2004 }
2005
2006 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2007 let mut key_context = KeyContext::new_with_defaults();
2008 key_context.add("Editor");
2009 let mode = match self.mode {
2010 EditorMode::SingleLine { .. } => "single_line",
2011 EditorMode::AutoHeight { .. } => "auto_height",
2012 EditorMode::Full => "full",
2013 };
2014
2015 if EditorSettings::jupyter_enabled(cx) {
2016 key_context.add("jupyter");
2017 }
2018
2019 key_context.set("mode", mode);
2020 if self.pending_rename.is_some() {
2021 key_context.add("renaming");
2022 }
2023 if self.context_menu_visible() {
2024 match self.context_menu.read().as_ref() {
2025 Some(ContextMenu::Completions(_)) => {
2026 key_context.add("menu");
2027 key_context.add("showing_completions")
2028 }
2029 Some(ContextMenu::CodeActions(_)) => {
2030 key_context.add("menu");
2031 key_context.add("showing_code_actions")
2032 }
2033 None => {}
2034 }
2035 }
2036
2037 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2038 if !self.focus_handle(cx).contains_focused(cx)
2039 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2040 {
2041 for addon in self.addons.values() {
2042 addon.extend_key_context(&mut key_context, cx)
2043 }
2044 }
2045
2046 if let Some(extension) = self
2047 .buffer
2048 .read(cx)
2049 .as_singleton()
2050 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2051 {
2052 key_context.set("extension", extension.to_string());
2053 }
2054
2055 if self.has_active_inline_completion(cx) {
2056 key_context.add("copilot_suggestion");
2057 key_context.add("inline_completion");
2058 }
2059
2060 key_context
2061 }
2062
2063 pub fn new_file(
2064 workspace: &mut Workspace,
2065 _: &workspace::NewFile,
2066 cx: &mut ViewContext<Workspace>,
2067 ) {
2068 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2069 "Failed to create buffer",
2070 cx,
2071 |e, _| match e.error_code() {
2072 ErrorCode::RemoteUpgradeRequired => Some(format!(
2073 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2074 e.error_tag("required").unwrap_or("the latest version")
2075 )),
2076 _ => None,
2077 },
2078 );
2079 }
2080
2081 pub fn new_in_workspace(
2082 workspace: &mut Workspace,
2083 cx: &mut ViewContext<Workspace>,
2084 ) -> Task<Result<View<Editor>>> {
2085 let project = workspace.project().clone();
2086 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2087
2088 cx.spawn(|workspace, mut cx| async move {
2089 let buffer = create.await?;
2090 workspace.update(&mut cx, |workspace, cx| {
2091 let editor =
2092 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2093 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2094 editor
2095 })
2096 })
2097 }
2098
2099 fn new_file_vertical(
2100 workspace: &mut Workspace,
2101 _: &workspace::NewFileSplitVertical,
2102 cx: &mut ViewContext<Workspace>,
2103 ) {
2104 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2105 }
2106
2107 fn new_file_horizontal(
2108 workspace: &mut Workspace,
2109 _: &workspace::NewFileSplitHorizontal,
2110 cx: &mut ViewContext<Workspace>,
2111 ) {
2112 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2113 }
2114
2115 fn new_file_in_direction(
2116 workspace: &mut Workspace,
2117 direction: SplitDirection,
2118 cx: &mut ViewContext<Workspace>,
2119 ) {
2120 let project = workspace.project().clone();
2121 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2122
2123 cx.spawn(|workspace, mut cx| async move {
2124 let buffer = create.await?;
2125 workspace.update(&mut cx, move |workspace, cx| {
2126 workspace.split_item(
2127 direction,
2128 Box::new(
2129 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2130 ),
2131 cx,
2132 )
2133 })?;
2134 anyhow::Ok(())
2135 })
2136 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2137 ErrorCode::RemoteUpgradeRequired => Some(format!(
2138 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2139 e.error_tag("required").unwrap_or("the latest version")
2140 )),
2141 _ => None,
2142 });
2143 }
2144
2145 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2146 self.buffer.read(cx).replica_id()
2147 }
2148
2149 pub fn leader_peer_id(&self) -> Option<PeerId> {
2150 self.leader_peer_id
2151 }
2152
2153 pub fn buffer(&self) -> &Model<MultiBuffer> {
2154 &self.buffer
2155 }
2156
2157 pub fn workspace(&self) -> Option<View<Workspace>> {
2158 self.workspace.as_ref()?.0.upgrade()
2159 }
2160
2161 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2162 self.buffer().read(cx).title(cx)
2163 }
2164
2165 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2166 EditorSnapshot {
2167 mode: self.mode,
2168 show_gutter: self.show_gutter,
2169 show_line_numbers: self.show_line_numbers,
2170 show_git_diff_gutter: self.show_git_diff_gutter,
2171 show_code_actions: self.show_code_actions,
2172 show_runnables: self.show_runnables,
2173 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2174 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2175 scroll_anchor: self.scroll_manager.anchor(),
2176 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2177 placeholder_text: self.placeholder_text.clone(),
2178 is_focused: self.focus_handle.is_focused(cx),
2179 current_line_highlight: self
2180 .current_line_highlight
2181 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2182 gutter_hovered: self.gutter_hovered,
2183 }
2184 }
2185
2186 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2187 self.buffer.read(cx).language_at(point, cx)
2188 }
2189
2190 pub fn file_at<T: ToOffset>(
2191 &self,
2192 point: T,
2193 cx: &AppContext,
2194 ) -> Option<Arc<dyn language::File>> {
2195 self.buffer.read(cx).read(cx).file_at(point).cloned()
2196 }
2197
2198 pub fn active_excerpt(
2199 &self,
2200 cx: &AppContext,
2201 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2202 self.buffer
2203 .read(cx)
2204 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2205 }
2206
2207 pub fn mode(&self) -> EditorMode {
2208 self.mode
2209 }
2210
2211 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2212 self.collaboration_hub.as_deref()
2213 }
2214
2215 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2216 self.collaboration_hub = Some(hub);
2217 }
2218
2219 pub fn set_custom_context_menu(
2220 &mut self,
2221 f: impl 'static
2222 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2223 ) {
2224 self.custom_context_menu = Some(Box::new(f))
2225 }
2226
2227 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2228 self.completion_provider = Some(provider);
2229 }
2230
2231 pub fn set_inline_completion_provider<T>(
2232 &mut self,
2233 provider: Option<Model<T>>,
2234 cx: &mut ViewContext<Self>,
2235 ) where
2236 T: InlineCompletionProvider,
2237 {
2238 self.inline_completion_provider =
2239 provider.map(|provider| RegisteredInlineCompletionProvider {
2240 _subscription: cx.observe(&provider, |this, _, cx| {
2241 if this.focus_handle.is_focused(cx) {
2242 this.update_visible_inline_completion(cx);
2243 }
2244 }),
2245 provider: Arc::new(provider),
2246 });
2247 self.refresh_inline_completion(false, false, cx);
2248 }
2249
2250 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2251 self.placeholder_text.as_deref()
2252 }
2253
2254 pub fn set_placeholder_text(
2255 &mut self,
2256 placeholder_text: impl Into<Arc<str>>,
2257 cx: &mut ViewContext<Self>,
2258 ) {
2259 let placeholder_text = Some(placeholder_text.into());
2260 if self.placeholder_text != placeholder_text {
2261 self.placeholder_text = placeholder_text;
2262 cx.notify();
2263 }
2264 }
2265
2266 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2267 self.cursor_shape = cursor_shape;
2268
2269 // Disrupt blink for immediate user feedback that the cursor shape has changed
2270 self.blink_manager.update(cx, BlinkManager::show_cursor);
2271
2272 cx.notify();
2273 }
2274
2275 pub fn set_current_line_highlight(
2276 &mut self,
2277 current_line_highlight: Option<CurrentLineHighlight>,
2278 ) {
2279 self.current_line_highlight = current_line_highlight;
2280 }
2281
2282 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2283 self.collapse_matches = collapse_matches;
2284 }
2285
2286 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2287 if self.collapse_matches {
2288 return range.start..range.start;
2289 }
2290 range.clone()
2291 }
2292
2293 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2294 if self.display_map.read(cx).clip_at_line_ends != clip {
2295 self.display_map
2296 .update(cx, |map, _| map.clip_at_line_ends = clip);
2297 }
2298 }
2299
2300 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2301 self.input_enabled = input_enabled;
2302 }
2303
2304 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2305 self.enable_inline_completions = enabled;
2306 }
2307
2308 pub fn set_autoindent(&mut self, autoindent: bool) {
2309 if autoindent {
2310 self.autoindent_mode = Some(AutoindentMode::EachLine);
2311 } else {
2312 self.autoindent_mode = None;
2313 }
2314 }
2315
2316 pub fn read_only(&self, cx: &AppContext) -> bool {
2317 self.read_only || self.buffer.read(cx).read_only()
2318 }
2319
2320 pub fn set_read_only(&mut self, read_only: bool) {
2321 self.read_only = read_only;
2322 }
2323
2324 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2325 self.use_autoclose = autoclose;
2326 }
2327
2328 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2329 self.use_auto_surround = auto_surround;
2330 }
2331
2332 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2333 self.auto_replace_emoji_shortcode = auto_replace;
2334 }
2335
2336 pub fn toggle_inline_completions(
2337 &mut self,
2338 _: &ToggleInlineCompletions,
2339 cx: &mut ViewContext<Self>,
2340 ) {
2341 if self.show_inline_completions_override.is_some() {
2342 self.set_show_inline_completions(None, cx);
2343 } else {
2344 let cursor = self.selections.newest_anchor().head();
2345 if let Some((buffer, cursor_buffer_position)) =
2346 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2347 {
2348 let show_inline_completions =
2349 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2350 self.set_show_inline_completions(Some(show_inline_completions), cx);
2351 }
2352 }
2353 }
2354
2355 pub fn set_show_inline_completions(
2356 &mut self,
2357 show_inline_completions: Option<bool>,
2358 cx: &mut ViewContext<Self>,
2359 ) {
2360 self.show_inline_completions_override = show_inline_completions;
2361 self.refresh_inline_completion(false, true, cx);
2362 }
2363
2364 fn should_show_inline_completions(
2365 &self,
2366 buffer: &Model<Buffer>,
2367 buffer_position: language::Anchor,
2368 cx: &AppContext,
2369 ) -> bool {
2370 if let Some(provider) = self.inline_completion_provider() {
2371 if let Some(show_inline_completions) = self.show_inline_completions_override {
2372 show_inline_completions
2373 } else {
2374 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2375 }
2376 } else {
2377 false
2378 }
2379 }
2380
2381 pub fn set_use_modal_editing(&mut self, to: bool) {
2382 self.use_modal_editing = to;
2383 }
2384
2385 pub fn use_modal_editing(&self) -> bool {
2386 self.use_modal_editing
2387 }
2388
2389 fn selections_did_change(
2390 &mut self,
2391 local: bool,
2392 old_cursor_position: &Anchor,
2393 show_completions: bool,
2394 cx: &mut ViewContext<Self>,
2395 ) {
2396 cx.invalidate_character_coordinates();
2397
2398 // Copy selections to primary selection buffer
2399 #[cfg(target_os = "linux")]
2400 if local {
2401 let selections = self.selections.all::<usize>(cx);
2402 let buffer_handle = self.buffer.read(cx).read(cx);
2403
2404 let mut text = String::new();
2405 for (index, selection) in selections.iter().enumerate() {
2406 let text_for_selection = buffer_handle
2407 .text_for_range(selection.start..selection.end)
2408 .collect::<String>();
2409
2410 text.push_str(&text_for_selection);
2411 if index != selections.len() - 1 {
2412 text.push('\n');
2413 }
2414 }
2415
2416 if !text.is_empty() {
2417 cx.write_to_primary(ClipboardItem::new_string(text));
2418 }
2419 }
2420
2421 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2422 self.buffer.update(cx, |buffer, cx| {
2423 buffer.set_active_selections(
2424 &self.selections.disjoint_anchors(),
2425 self.selections.line_mode,
2426 self.cursor_shape,
2427 cx,
2428 )
2429 });
2430 }
2431 let display_map = self
2432 .display_map
2433 .update(cx, |display_map, cx| display_map.snapshot(cx));
2434 let buffer = &display_map.buffer_snapshot;
2435 self.add_selections_state = None;
2436 self.select_next_state = None;
2437 self.select_prev_state = None;
2438 self.select_larger_syntax_node_stack.clear();
2439 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2440 self.snippet_stack
2441 .invalidate(&self.selections.disjoint_anchors(), buffer);
2442 self.take_rename(false, cx);
2443
2444 let new_cursor_position = self.selections.newest_anchor().head();
2445
2446 self.push_to_nav_history(
2447 *old_cursor_position,
2448 Some(new_cursor_position.to_point(buffer)),
2449 cx,
2450 );
2451
2452 if local {
2453 let new_cursor_position = self.selections.newest_anchor().head();
2454 let mut context_menu = self.context_menu.write();
2455 let completion_menu = match context_menu.as_ref() {
2456 Some(ContextMenu::Completions(menu)) => Some(menu),
2457
2458 _ => {
2459 *context_menu = None;
2460 None
2461 }
2462 };
2463
2464 if let Some(completion_menu) = completion_menu {
2465 let cursor_position = new_cursor_position.to_offset(buffer);
2466 let (word_range, kind) =
2467 buffer.surrounding_word(completion_menu.initial_position, true);
2468 if kind == Some(CharKind::Word)
2469 && word_range.to_inclusive().contains(&cursor_position)
2470 {
2471 let mut completion_menu = completion_menu.clone();
2472 drop(context_menu);
2473
2474 let query = Self::completion_query(buffer, cursor_position);
2475 cx.spawn(move |this, mut cx| async move {
2476 completion_menu
2477 .filter(query.as_deref(), cx.background_executor().clone())
2478 .await;
2479
2480 this.update(&mut cx, |this, cx| {
2481 let mut context_menu = this.context_menu.write();
2482 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2483 return;
2484 };
2485
2486 if menu.id > completion_menu.id {
2487 return;
2488 }
2489
2490 *context_menu = Some(ContextMenu::Completions(completion_menu));
2491 drop(context_menu);
2492 cx.notify();
2493 })
2494 })
2495 .detach();
2496
2497 if show_completions {
2498 self.show_completions(&ShowCompletions { trigger: None }, cx);
2499 }
2500 } else {
2501 drop(context_menu);
2502 self.hide_context_menu(cx);
2503 }
2504 } else {
2505 drop(context_menu);
2506 }
2507
2508 hide_hover(self, cx);
2509
2510 if old_cursor_position.to_display_point(&display_map).row()
2511 != new_cursor_position.to_display_point(&display_map).row()
2512 {
2513 self.available_code_actions.take();
2514 }
2515 self.refresh_code_actions(cx);
2516 self.refresh_document_highlights(cx);
2517 refresh_matching_bracket_highlights(self, cx);
2518 self.discard_inline_completion(false, cx);
2519 linked_editing_ranges::refresh_linked_ranges(self, cx);
2520 if self.git_blame_inline_enabled {
2521 self.start_inline_blame_timer(cx);
2522 }
2523 }
2524
2525 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2526 cx.emit(EditorEvent::SelectionsChanged { local });
2527
2528 if self.selections.disjoint_anchors().len() == 1 {
2529 cx.emit(SearchEvent::ActiveMatchChanged)
2530 }
2531 cx.notify();
2532 }
2533
2534 pub fn change_selections<R>(
2535 &mut self,
2536 autoscroll: Option<Autoscroll>,
2537 cx: &mut ViewContext<Self>,
2538 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2539 ) -> R {
2540 self.change_selections_inner(autoscroll, true, cx, change)
2541 }
2542
2543 pub fn change_selections_inner<R>(
2544 &mut self,
2545 autoscroll: Option<Autoscroll>,
2546 request_completions: bool,
2547 cx: &mut ViewContext<Self>,
2548 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2549 ) -> R {
2550 let old_cursor_position = self.selections.newest_anchor().head();
2551 self.push_to_selection_history();
2552
2553 let (changed, result) = self.selections.change_with(cx, change);
2554
2555 if changed {
2556 if let Some(autoscroll) = autoscroll {
2557 self.request_autoscroll(autoscroll, cx);
2558 }
2559 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2560
2561 if self.should_open_signature_help_automatically(
2562 &old_cursor_position,
2563 self.signature_help_state.backspace_pressed(),
2564 cx,
2565 ) {
2566 self.show_signature_help(&ShowSignatureHelp, cx);
2567 }
2568 self.signature_help_state.set_backspace_pressed(false);
2569 }
2570
2571 result
2572 }
2573
2574 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2575 where
2576 I: IntoIterator<Item = (Range<S>, T)>,
2577 S: ToOffset,
2578 T: Into<Arc<str>>,
2579 {
2580 if self.read_only(cx) {
2581 return;
2582 }
2583
2584 self.buffer
2585 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2586 }
2587
2588 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2589 where
2590 I: IntoIterator<Item = (Range<S>, T)>,
2591 S: ToOffset,
2592 T: Into<Arc<str>>,
2593 {
2594 if self.read_only(cx) {
2595 return;
2596 }
2597
2598 self.buffer.update(cx, |buffer, cx| {
2599 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2600 });
2601 }
2602
2603 pub fn edit_with_block_indent<I, S, T>(
2604 &mut self,
2605 edits: I,
2606 original_indent_columns: Vec<u32>,
2607 cx: &mut ViewContext<Self>,
2608 ) where
2609 I: IntoIterator<Item = (Range<S>, T)>,
2610 S: ToOffset,
2611 T: Into<Arc<str>>,
2612 {
2613 if self.read_only(cx) {
2614 return;
2615 }
2616
2617 self.buffer.update(cx, |buffer, cx| {
2618 buffer.edit(
2619 edits,
2620 Some(AutoindentMode::Block {
2621 original_indent_columns,
2622 }),
2623 cx,
2624 )
2625 });
2626 }
2627
2628 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2629 self.hide_context_menu(cx);
2630
2631 match phase {
2632 SelectPhase::Begin {
2633 position,
2634 add,
2635 click_count,
2636 } => self.begin_selection(position, add, click_count, cx),
2637 SelectPhase::BeginColumnar {
2638 position,
2639 goal_column,
2640 reset,
2641 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2642 SelectPhase::Extend {
2643 position,
2644 click_count,
2645 } => self.extend_selection(position, click_count, cx),
2646 SelectPhase::Update {
2647 position,
2648 goal_column,
2649 scroll_delta,
2650 } => self.update_selection(position, goal_column, scroll_delta, cx),
2651 SelectPhase::End => self.end_selection(cx),
2652 }
2653 }
2654
2655 fn extend_selection(
2656 &mut self,
2657 position: DisplayPoint,
2658 click_count: usize,
2659 cx: &mut ViewContext<Self>,
2660 ) {
2661 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2662 let tail = self.selections.newest::<usize>(cx).tail();
2663 self.begin_selection(position, false, click_count, cx);
2664
2665 let position = position.to_offset(&display_map, Bias::Left);
2666 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2667
2668 let mut pending_selection = self
2669 .selections
2670 .pending_anchor()
2671 .expect("extend_selection not called with pending selection");
2672 if position >= tail {
2673 pending_selection.start = tail_anchor;
2674 } else {
2675 pending_selection.end = tail_anchor;
2676 pending_selection.reversed = true;
2677 }
2678
2679 let mut pending_mode = self.selections.pending_mode().unwrap();
2680 match &mut pending_mode {
2681 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2682 _ => {}
2683 }
2684
2685 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2686 s.set_pending(pending_selection, pending_mode)
2687 });
2688 }
2689
2690 fn begin_selection(
2691 &mut self,
2692 position: DisplayPoint,
2693 add: bool,
2694 click_count: usize,
2695 cx: &mut ViewContext<Self>,
2696 ) {
2697 if !self.focus_handle.is_focused(cx) {
2698 self.last_focused_descendant = None;
2699 cx.focus(&self.focus_handle);
2700 }
2701
2702 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2703 let buffer = &display_map.buffer_snapshot;
2704 let newest_selection = self.selections.newest_anchor().clone();
2705 let position = display_map.clip_point(position, Bias::Left);
2706
2707 let start;
2708 let end;
2709 let mode;
2710 let auto_scroll;
2711 match click_count {
2712 1 => {
2713 start = buffer.anchor_before(position.to_point(&display_map));
2714 end = start;
2715 mode = SelectMode::Character;
2716 auto_scroll = true;
2717 }
2718 2 => {
2719 let range = movement::surrounding_word(&display_map, position);
2720 start = buffer.anchor_before(range.start.to_point(&display_map));
2721 end = buffer.anchor_before(range.end.to_point(&display_map));
2722 mode = SelectMode::Word(start..end);
2723 auto_scroll = true;
2724 }
2725 3 => {
2726 let position = display_map
2727 .clip_point(position, Bias::Left)
2728 .to_point(&display_map);
2729 let line_start = display_map.prev_line_boundary(position).0;
2730 let next_line_start = buffer.clip_point(
2731 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2732 Bias::Left,
2733 );
2734 start = buffer.anchor_before(line_start);
2735 end = buffer.anchor_before(next_line_start);
2736 mode = SelectMode::Line(start..end);
2737 auto_scroll = true;
2738 }
2739 _ => {
2740 start = buffer.anchor_before(0);
2741 end = buffer.anchor_before(buffer.len());
2742 mode = SelectMode::All;
2743 auto_scroll = false;
2744 }
2745 }
2746
2747 let point_to_delete: Option<usize> = {
2748 let selected_points: Vec<Selection<Point>> =
2749 self.selections.disjoint_in_range(start..end, cx);
2750
2751 if !add || click_count > 1 {
2752 None
2753 } else if !selected_points.is_empty() {
2754 Some(selected_points[0].id)
2755 } else {
2756 let clicked_point_already_selected =
2757 self.selections.disjoint.iter().find(|selection| {
2758 selection.start.to_point(buffer) == start.to_point(buffer)
2759 || selection.end.to_point(buffer) == end.to_point(buffer)
2760 });
2761
2762 clicked_point_already_selected.map(|selection| selection.id)
2763 }
2764 };
2765
2766 let selections_count = self.selections.count();
2767
2768 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2769 if let Some(point_to_delete) = point_to_delete {
2770 s.delete(point_to_delete);
2771
2772 if selections_count == 1 {
2773 s.set_pending_anchor_range(start..end, mode);
2774 }
2775 } else {
2776 if !add {
2777 s.clear_disjoint();
2778 } else if click_count > 1 {
2779 s.delete(newest_selection.id)
2780 }
2781
2782 s.set_pending_anchor_range(start..end, mode);
2783 }
2784 });
2785 }
2786
2787 fn begin_columnar_selection(
2788 &mut self,
2789 position: DisplayPoint,
2790 goal_column: u32,
2791 reset: bool,
2792 cx: &mut ViewContext<Self>,
2793 ) {
2794 if !self.focus_handle.is_focused(cx) {
2795 self.last_focused_descendant = None;
2796 cx.focus(&self.focus_handle);
2797 }
2798
2799 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2800
2801 if reset {
2802 let pointer_position = display_map
2803 .buffer_snapshot
2804 .anchor_before(position.to_point(&display_map));
2805
2806 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2807 s.clear_disjoint();
2808 s.set_pending_anchor_range(
2809 pointer_position..pointer_position,
2810 SelectMode::Character,
2811 );
2812 });
2813 }
2814
2815 let tail = self.selections.newest::<Point>(cx).tail();
2816 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2817
2818 if !reset {
2819 self.select_columns(
2820 tail.to_display_point(&display_map),
2821 position,
2822 goal_column,
2823 &display_map,
2824 cx,
2825 );
2826 }
2827 }
2828
2829 fn update_selection(
2830 &mut self,
2831 position: DisplayPoint,
2832 goal_column: u32,
2833 scroll_delta: gpui::Point<f32>,
2834 cx: &mut ViewContext<Self>,
2835 ) {
2836 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2837
2838 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2839 let tail = tail.to_display_point(&display_map);
2840 self.select_columns(tail, position, goal_column, &display_map, cx);
2841 } else if let Some(mut pending) = self.selections.pending_anchor() {
2842 let buffer = self.buffer.read(cx).snapshot(cx);
2843 let head;
2844 let tail;
2845 let mode = self.selections.pending_mode().unwrap();
2846 match &mode {
2847 SelectMode::Character => {
2848 head = position.to_point(&display_map);
2849 tail = pending.tail().to_point(&buffer);
2850 }
2851 SelectMode::Word(original_range) => {
2852 let original_display_range = original_range.start.to_display_point(&display_map)
2853 ..original_range.end.to_display_point(&display_map);
2854 let original_buffer_range = original_display_range.start.to_point(&display_map)
2855 ..original_display_range.end.to_point(&display_map);
2856 if movement::is_inside_word(&display_map, position)
2857 || original_display_range.contains(&position)
2858 {
2859 let word_range = movement::surrounding_word(&display_map, position);
2860 if word_range.start < original_display_range.start {
2861 head = word_range.start.to_point(&display_map);
2862 } else {
2863 head = word_range.end.to_point(&display_map);
2864 }
2865 } else {
2866 head = position.to_point(&display_map);
2867 }
2868
2869 if head <= original_buffer_range.start {
2870 tail = original_buffer_range.end;
2871 } else {
2872 tail = original_buffer_range.start;
2873 }
2874 }
2875 SelectMode::Line(original_range) => {
2876 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2877
2878 let position = display_map
2879 .clip_point(position, Bias::Left)
2880 .to_point(&display_map);
2881 let line_start = display_map.prev_line_boundary(position).0;
2882 let next_line_start = buffer.clip_point(
2883 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2884 Bias::Left,
2885 );
2886
2887 if line_start < original_range.start {
2888 head = line_start
2889 } else {
2890 head = next_line_start
2891 }
2892
2893 if head <= original_range.start {
2894 tail = original_range.end;
2895 } else {
2896 tail = original_range.start;
2897 }
2898 }
2899 SelectMode::All => {
2900 return;
2901 }
2902 };
2903
2904 if head < tail {
2905 pending.start = buffer.anchor_before(head);
2906 pending.end = buffer.anchor_before(tail);
2907 pending.reversed = true;
2908 } else {
2909 pending.start = buffer.anchor_before(tail);
2910 pending.end = buffer.anchor_before(head);
2911 pending.reversed = false;
2912 }
2913
2914 self.change_selections(None, cx, |s| {
2915 s.set_pending(pending, mode);
2916 });
2917 } else {
2918 log::error!("update_selection dispatched with no pending selection");
2919 return;
2920 }
2921
2922 self.apply_scroll_delta(scroll_delta, cx);
2923 cx.notify();
2924 }
2925
2926 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2927 self.columnar_selection_tail.take();
2928 if self.selections.pending_anchor().is_some() {
2929 let selections = self.selections.all::<usize>(cx);
2930 self.change_selections(None, cx, |s| {
2931 s.select(selections);
2932 s.clear_pending();
2933 });
2934 }
2935 }
2936
2937 fn select_columns(
2938 &mut self,
2939 tail: DisplayPoint,
2940 head: DisplayPoint,
2941 goal_column: u32,
2942 display_map: &DisplaySnapshot,
2943 cx: &mut ViewContext<Self>,
2944 ) {
2945 let start_row = cmp::min(tail.row(), head.row());
2946 let end_row = cmp::max(tail.row(), head.row());
2947 let start_column = cmp::min(tail.column(), goal_column);
2948 let end_column = cmp::max(tail.column(), goal_column);
2949 let reversed = start_column < tail.column();
2950
2951 let selection_ranges = (start_row.0..=end_row.0)
2952 .map(DisplayRow)
2953 .filter_map(|row| {
2954 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2955 let start = display_map
2956 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2957 .to_point(display_map);
2958 let end = display_map
2959 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2960 .to_point(display_map);
2961 if reversed {
2962 Some(end..start)
2963 } else {
2964 Some(start..end)
2965 }
2966 } else {
2967 None
2968 }
2969 })
2970 .collect::<Vec<_>>();
2971
2972 self.change_selections(None, cx, |s| {
2973 s.select_ranges(selection_ranges);
2974 });
2975 cx.notify();
2976 }
2977
2978 pub fn has_pending_nonempty_selection(&self) -> bool {
2979 let pending_nonempty_selection = match self.selections.pending_anchor() {
2980 Some(Selection { start, end, .. }) => start != end,
2981 None => false,
2982 };
2983
2984 pending_nonempty_selection
2985 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2986 }
2987
2988 pub fn has_pending_selection(&self) -> bool {
2989 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2990 }
2991
2992 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2993 if self.clear_clicked_diff_hunks(cx) {
2994 cx.notify();
2995 return;
2996 }
2997 if self.dismiss_menus_and_popups(true, cx) {
2998 return;
2999 }
3000
3001 if self.mode == EditorMode::Full
3002 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3003 {
3004 return;
3005 }
3006
3007 cx.propagate();
3008 }
3009
3010 pub fn dismiss_menus_and_popups(
3011 &mut self,
3012 should_report_inline_completion_event: bool,
3013 cx: &mut ViewContext<Self>,
3014 ) -> bool {
3015 if self.take_rename(false, cx).is_some() {
3016 return true;
3017 }
3018
3019 if hide_hover(self, cx) {
3020 return true;
3021 }
3022
3023 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3024 return true;
3025 }
3026
3027 if self.hide_context_menu(cx).is_some() {
3028 return true;
3029 }
3030
3031 if self.mouse_context_menu.take().is_some() {
3032 return true;
3033 }
3034
3035 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3036 return true;
3037 }
3038
3039 if self.snippet_stack.pop().is_some() {
3040 return true;
3041 }
3042
3043 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3044 self.dismiss_diagnostics(cx);
3045 return true;
3046 }
3047
3048 false
3049 }
3050
3051 fn linked_editing_ranges_for(
3052 &self,
3053 selection: Range<text::Anchor>,
3054 cx: &AppContext,
3055 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3056 if self.linked_edit_ranges.is_empty() {
3057 return None;
3058 }
3059 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3060 selection.end.buffer_id.and_then(|end_buffer_id| {
3061 if selection.start.buffer_id != Some(end_buffer_id) {
3062 return None;
3063 }
3064 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3065 let snapshot = buffer.read(cx).snapshot();
3066 self.linked_edit_ranges
3067 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3068 .map(|ranges| (ranges, snapshot, buffer))
3069 })?;
3070 use text::ToOffset as TO;
3071 // find offset from the start of current range to current cursor position
3072 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3073
3074 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3075 let start_difference = start_offset - start_byte_offset;
3076 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3077 let end_difference = end_offset - start_byte_offset;
3078 // Current range has associated linked ranges.
3079 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3080 for range in linked_ranges.iter() {
3081 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3082 let end_offset = start_offset + end_difference;
3083 let start_offset = start_offset + start_difference;
3084 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3085 continue;
3086 }
3087 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3088 if s.start.buffer_id != selection.start.buffer_id
3089 || s.end.buffer_id != selection.end.buffer_id
3090 {
3091 return false;
3092 }
3093 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3094 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3095 }) {
3096 continue;
3097 }
3098 let start = buffer_snapshot.anchor_after(start_offset);
3099 let end = buffer_snapshot.anchor_after(end_offset);
3100 linked_edits
3101 .entry(buffer.clone())
3102 .or_default()
3103 .push(start..end);
3104 }
3105 Some(linked_edits)
3106 }
3107
3108 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3109 let text: Arc<str> = text.into();
3110
3111 if self.read_only(cx) {
3112 return;
3113 }
3114
3115 let selections = self.selections.all_adjusted(cx);
3116 let mut bracket_inserted = false;
3117 let mut edits = Vec::new();
3118 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3119 let mut new_selections = Vec::with_capacity(selections.len());
3120 let mut new_autoclose_regions = Vec::new();
3121 let snapshot = self.buffer.read(cx).read(cx);
3122
3123 for (selection, autoclose_region) in
3124 self.selections_with_autoclose_regions(selections, &snapshot)
3125 {
3126 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3127 // Determine if the inserted text matches the opening or closing
3128 // bracket of any of this language's bracket pairs.
3129 let mut bracket_pair = None;
3130 let mut is_bracket_pair_start = false;
3131 let mut is_bracket_pair_end = false;
3132 if !text.is_empty() {
3133 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3134 // and they are removing the character that triggered IME popup.
3135 for (pair, enabled) in scope.brackets() {
3136 if !pair.close && !pair.surround {
3137 continue;
3138 }
3139
3140 if enabled && pair.start.ends_with(text.as_ref()) {
3141 bracket_pair = Some(pair.clone());
3142 is_bracket_pair_start = true;
3143 break;
3144 }
3145 if pair.end.as_str() == text.as_ref() {
3146 bracket_pair = Some(pair.clone());
3147 is_bracket_pair_end = true;
3148 break;
3149 }
3150 }
3151 }
3152
3153 if let Some(bracket_pair) = bracket_pair {
3154 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3155 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3156 let auto_surround =
3157 self.use_auto_surround && snapshot_settings.use_auto_surround;
3158 if selection.is_empty() {
3159 if is_bracket_pair_start {
3160 let prefix_len = bracket_pair.start.len() - text.len();
3161
3162 // If the inserted text is a suffix of an opening bracket and the
3163 // selection is preceded by the rest of the opening bracket, then
3164 // insert the closing bracket.
3165 let following_text_allows_autoclose = snapshot
3166 .chars_at(selection.start)
3167 .next()
3168 .map_or(true, |c| scope.should_autoclose_before(c));
3169 let preceding_text_matches_prefix = prefix_len == 0
3170 || (selection.start.column >= (prefix_len as u32)
3171 && snapshot.contains_str_at(
3172 Point::new(
3173 selection.start.row,
3174 selection.start.column - (prefix_len as u32),
3175 ),
3176 &bracket_pair.start[..prefix_len],
3177 ));
3178
3179 if autoclose
3180 && bracket_pair.close
3181 && following_text_allows_autoclose
3182 && preceding_text_matches_prefix
3183 {
3184 let anchor = snapshot.anchor_before(selection.end);
3185 new_selections.push((selection.map(|_| anchor), text.len()));
3186 new_autoclose_regions.push((
3187 anchor,
3188 text.len(),
3189 selection.id,
3190 bracket_pair.clone(),
3191 ));
3192 edits.push((
3193 selection.range(),
3194 format!("{}{}", text, bracket_pair.end).into(),
3195 ));
3196 bracket_inserted = true;
3197 continue;
3198 }
3199 }
3200
3201 if let Some(region) = autoclose_region {
3202 // If the selection is followed by an auto-inserted closing bracket,
3203 // then don't insert that closing bracket again; just move the selection
3204 // past the closing bracket.
3205 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3206 && text.as_ref() == region.pair.end.as_str();
3207 if should_skip {
3208 let anchor = snapshot.anchor_after(selection.end);
3209 new_selections
3210 .push((selection.map(|_| anchor), region.pair.end.len()));
3211 continue;
3212 }
3213 }
3214
3215 let always_treat_brackets_as_autoclosed = snapshot
3216 .settings_at(selection.start, cx)
3217 .always_treat_brackets_as_autoclosed;
3218 if always_treat_brackets_as_autoclosed
3219 && is_bracket_pair_end
3220 && snapshot.contains_str_at(selection.end, text.as_ref())
3221 {
3222 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3223 // and the inserted text is a closing bracket and the selection is followed
3224 // by the closing bracket then move the selection past the closing bracket.
3225 let anchor = snapshot.anchor_after(selection.end);
3226 new_selections.push((selection.map(|_| anchor), text.len()));
3227 continue;
3228 }
3229 }
3230 // If an opening bracket is 1 character long and is typed while
3231 // text is selected, then surround that text with the bracket pair.
3232 else if auto_surround
3233 && bracket_pair.surround
3234 && is_bracket_pair_start
3235 && bracket_pair.start.chars().count() == 1
3236 {
3237 edits.push((selection.start..selection.start, text.clone()));
3238 edits.push((
3239 selection.end..selection.end,
3240 bracket_pair.end.as_str().into(),
3241 ));
3242 bracket_inserted = true;
3243 new_selections.push((
3244 Selection {
3245 id: selection.id,
3246 start: snapshot.anchor_after(selection.start),
3247 end: snapshot.anchor_before(selection.end),
3248 reversed: selection.reversed,
3249 goal: selection.goal,
3250 },
3251 0,
3252 ));
3253 continue;
3254 }
3255 }
3256 }
3257
3258 if self.auto_replace_emoji_shortcode
3259 && selection.is_empty()
3260 && text.as_ref().ends_with(':')
3261 {
3262 if let Some(possible_emoji_short_code) =
3263 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3264 {
3265 if !possible_emoji_short_code.is_empty() {
3266 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3267 let emoji_shortcode_start = Point::new(
3268 selection.start.row,
3269 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3270 );
3271
3272 // Remove shortcode from buffer
3273 edits.push((
3274 emoji_shortcode_start..selection.start,
3275 "".to_string().into(),
3276 ));
3277 new_selections.push((
3278 Selection {
3279 id: selection.id,
3280 start: snapshot.anchor_after(emoji_shortcode_start),
3281 end: snapshot.anchor_before(selection.start),
3282 reversed: selection.reversed,
3283 goal: selection.goal,
3284 },
3285 0,
3286 ));
3287
3288 // Insert emoji
3289 let selection_start_anchor = snapshot.anchor_after(selection.start);
3290 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3291 edits.push((selection.start..selection.end, emoji.to_string().into()));
3292
3293 continue;
3294 }
3295 }
3296 }
3297 }
3298
3299 // If not handling any auto-close operation, then just replace the selected
3300 // text with the given input and move the selection to the end of the
3301 // newly inserted text.
3302 let anchor = snapshot.anchor_after(selection.end);
3303 if !self.linked_edit_ranges.is_empty() {
3304 let start_anchor = snapshot.anchor_before(selection.start);
3305
3306 let is_word_char = text.chars().next().map_or(true, |char| {
3307 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3308 classifier.is_word(char)
3309 });
3310
3311 if is_word_char {
3312 if let Some(ranges) = self
3313 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3314 {
3315 for (buffer, edits) in ranges {
3316 linked_edits
3317 .entry(buffer.clone())
3318 .or_default()
3319 .extend(edits.into_iter().map(|range| (range, text.clone())));
3320 }
3321 }
3322 }
3323 }
3324
3325 new_selections.push((selection.map(|_| anchor), 0));
3326 edits.push((selection.start..selection.end, text.clone()));
3327 }
3328
3329 drop(snapshot);
3330
3331 self.transact(cx, |this, cx| {
3332 this.buffer.update(cx, |buffer, cx| {
3333 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3334 });
3335 for (buffer, edits) in linked_edits {
3336 buffer.update(cx, |buffer, cx| {
3337 let snapshot = buffer.snapshot();
3338 let edits = edits
3339 .into_iter()
3340 .map(|(range, text)| {
3341 use text::ToPoint as TP;
3342 let end_point = TP::to_point(&range.end, &snapshot);
3343 let start_point = TP::to_point(&range.start, &snapshot);
3344 (start_point..end_point, text)
3345 })
3346 .sorted_by_key(|(range, _)| range.start)
3347 .collect::<Vec<_>>();
3348 buffer.edit(edits, None, cx);
3349 })
3350 }
3351 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3352 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3353 let snapshot = this.buffer.read(cx).read(cx);
3354 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3355 .zip(new_selection_deltas)
3356 .map(|(selection, delta)| Selection {
3357 id: selection.id,
3358 start: selection.start + delta,
3359 end: selection.end + delta,
3360 reversed: selection.reversed,
3361 goal: SelectionGoal::None,
3362 })
3363 .collect::<Vec<_>>();
3364
3365 let mut i = 0;
3366 for (position, delta, selection_id, pair) in new_autoclose_regions {
3367 let position = position.to_offset(&snapshot) + delta;
3368 let start = snapshot.anchor_before(position);
3369 let end = snapshot.anchor_after(position);
3370 while let Some(existing_state) = this.autoclose_regions.get(i) {
3371 match existing_state.range.start.cmp(&start, &snapshot) {
3372 Ordering::Less => i += 1,
3373 Ordering::Greater => break,
3374 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3375 Ordering::Less => i += 1,
3376 Ordering::Equal => break,
3377 Ordering::Greater => break,
3378 },
3379 }
3380 }
3381 this.autoclose_regions.insert(
3382 i,
3383 AutocloseRegion {
3384 selection_id,
3385 range: start..end,
3386 pair,
3387 },
3388 );
3389 }
3390
3391 drop(snapshot);
3392 let had_active_inline_completion = this.has_active_inline_completion(cx);
3393 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3394 s.select(new_selections)
3395 });
3396
3397 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3398 if let Some(on_type_format_task) =
3399 this.trigger_on_type_formatting(text.to_string(), cx)
3400 {
3401 on_type_format_task.detach_and_log_err(cx);
3402 }
3403 }
3404
3405 let editor_settings = EditorSettings::get_global(cx);
3406 if bracket_inserted
3407 && (editor_settings.auto_signature_help
3408 || editor_settings.show_signature_help_after_edits)
3409 {
3410 this.show_signature_help(&ShowSignatureHelp, cx);
3411 }
3412
3413 let trigger_in_words = !had_active_inline_completion;
3414 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3415 linked_editing_ranges::refresh_linked_ranges(this, cx);
3416 this.refresh_inline_completion(true, false, cx);
3417 });
3418 }
3419
3420 fn find_possible_emoji_shortcode_at_position(
3421 snapshot: &MultiBufferSnapshot,
3422 position: Point,
3423 ) -> Option<String> {
3424 let mut chars = Vec::new();
3425 let mut found_colon = false;
3426 for char in snapshot.reversed_chars_at(position).take(100) {
3427 // Found a possible emoji shortcode in the middle of the buffer
3428 if found_colon {
3429 if char.is_whitespace() {
3430 chars.reverse();
3431 return Some(chars.iter().collect());
3432 }
3433 // If the previous character is not a whitespace, we are in the middle of a word
3434 // and we only want to complete the shortcode if the word is made up of other emojis
3435 let mut containing_word = String::new();
3436 for ch in snapshot
3437 .reversed_chars_at(position)
3438 .skip(chars.len() + 1)
3439 .take(100)
3440 {
3441 if ch.is_whitespace() {
3442 break;
3443 }
3444 containing_word.push(ch);
3445 }
3446 let containing_word = containing_word.chars().rev().collect::<String>();
3447 if util::word_consists_of_emojis(containing_word.as_str()) {
3448 chars.reverse();
3449 return Some(chars.iter().collect());
3450 }
3451 }
3452
3453 if char.is_whitespace() || !char.is_ascii() {
3454 return None;
3455 }
3456 if char == ':' {
3457 found_colon = true;
3458 } else {
3459 chars.push(char);
3460 }
3461 }
3462 // Found a possible emoji shortcode at the beginning of the buffer
3463 chars.reverse();
3464 Some(chars.iter().collect())
3465 }
3466
3467 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3468 self.transact(cx, |this, cx| {
3469 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3470 let selections = this.selections.all::<usize>(cx);
3471 let multi_buffer = this.buffer.read(cx);
3472 let buffer = multi_buffer.snapshot(cx);
3473 selections
3474 .iter()
3475 .map(|selection| {
3476 let start_point = selection.start.to_point(&buffer);
3477 let mut indent =
3478 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3479 indent.len = cmp::min(indent.len, start_point.column);
3480 let start = selection.start;
3481 let end = selection.end;
3482 let selection_is_empty = start == end;
3483 let language_scope = buffer.language_scope_at(start);
3484 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3485 &language_scope
3486 {
3487 let leading_whitespace_len = buffer
3488 .reversed_chars_at(start)
3489 .take_while(|c| c.is_whitespace() && *c != '\n')
3490 .map(|c| c.len_utf8())
3491 .sum::<usize>();
3492
3493 let trailing_whitespace_len = buffer
3494 .chars_at(end)
3495 .take_while(|c| c.is_whitespace() && *c != '\n')
3496 .map(|c| c.len_utf8())
3497 .sum::<usize>();
3498
3499 let insert_extra_newline =
3500 language.brackets().any(|(pair, enabled)| {
3501 let pair_start = pair.start.trim_end();
3502 let pair_end = pair.end.trim_start();
3503
3504 enabled
3505 && pair.newline
3506 && buffer.contains_str_at(
3507 end + trailing_whitespace_len,
3508 pair_end,
3509 )
3510 && buffer.contains_str_at(
3511 (start - leading_whitespace_len)
3512 .saturating_sub(pair_start.len()),
3513 pair_start,
3514 )
3515 });
3516
3517 // Comment extension on newline is allowed only for cursor selections
3518 let comment_delimiter = maybe!({
3519 if !selection_is_empty {
3520 return None;
3521 }
3522
3523 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3524 return None;
3525 }
3526
3527 let delimiters = language.line_comment_prefixes();
3528 let max_len_of_delimiter =
3529 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3530 let (snapshot, range) =
3531 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3532
3533 let mut index_of_first_non_whitespace = 0;
3534 let comment_candidate = snapshot
3535 .chars_for_range(range)
3536 .skip_while(|c| {
3537 let should_skip = c.is_whitespace();
3538 if should_skip {
3539 index_of_first_non_whitespace += 1;
3540 }
3541 should_skip
3542 })
3543 .take(max_len_of_delimiter)
3544 .collect::<String>();
3545 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3546 comment_candidate.starts_with(comment_prefix.as_ref())
3547 })?;
3548 let cursor_is_placed_after_comment_marker =
3549 index_of_first_non_whitespace + comment_prefix.len()
3550 <= start_point.column as usize;
3551 if cursor_is_placed_after_comment_marker {
3552 Some(comment_prefix.clone())
3553 } else {
3554 None
3555 }
3556 });
3557 (comment_delimiter, insert_extra_newline)
3558 } else {
3559 (None, false)
3560 };
3561
3562 let capacity_for_delimiter = comment_delimiter
3563 .as_deref()
3564 .map(str::len)
3565 .unwrap_or_default();
3566 let mut new_text =
3567 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3568 new_text.push('\n');
3569 new_text.extend(indent.chars());
3570 if let Some(delimiter) = &comment_delimiter {
3571 new_text.push_str(delimiter);
3572 }
3573 if insert_extra_newline {
3574 new_text = new_text.repeat(2);
3575 }
3576
3577 let anchor = buffer.anchor_after(end);
3578 let new_selection = selection.map(|_| anchor);
3579 (
3580 (start..end, new_text),
3581 (insert_extra_newline, new_selection),
3582 )
3583 })
3584 .unzip()
3585 };
3586
3587 this.edit_with_autoindent(edits, cx);
3588 let buffer = this.buffer.read(cx).snapshot(cx);
3589 let new_selections = selection_fixup_info
3590 .into_iter()
3591 .map(|(extra_newline_inserted, new_selection)| {
3592 let mut cursor = new_selection.end.to_point(&buffer);
3593 if extra_newline_inserted {
3594 cursor.row -= 1;
3595 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3596 }
3597 new_selection.map(|_| cursor)
3598 })
3599 .collect();
3600
3601 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3602 this.refresh_inline_completion(true, false, cx);
3603 });
3604 }
3605
3606 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3607 let buffer = self.buffer.read(cx);
3608 let snapshot = buffer.snapshot(cx);
3609
3610 let mut edits = Vec::new();
3611 let mut rows = Vec::new();
3612
3613 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3614 let cursor = selection.head();
3615 let row = cursor.row;
3616
3617 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3618
3619 let newline = "\n".to_string();
3620 edits.push((start_of_line..start_of_line, newline));
3621
3622 rows.push(row + rows_inserted as u32);
3623 }
3624
3625 self.transact(cx, |editor, cx| {
3626 editor.edit(edits, cx);
3627
3628 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3629 let mut index = 0;
3630 s.move_cursors_with(|map, _, _| {
3631 let row = rows[index];
3632 index += 1;
3633
3634 let point = Point::new(row, 0);
3635 let boundary = map.next_line_boundary(point).1;
3636 let clipped = map.clip_point(boundary, Bias::Left);
3637
3638 (clipped, SelectionGoal::None)
3639 });
3640 });
3641
3642 let mut indent_edits = Vec::new();
3643 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3644 for row in rows {
3645 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3646 for (row, indent) in indents {
3647 if indent.len == 0 {
3648 continue;
3649 }
3650
3651 let text = match indent.kind {
3652 IndentKind::Space => " ".repeat(indent.len as usize),
3653 IndentKind::Tab => "\t".repeat(indent.len as usize),
3654 };
3655 let point = Point::new(row.0, 0);
3656 indent_edits.push((point..point, text));
3657 }
3658 }
3659 editor.edit(indent_edits, cx);
3660 });
3661 }
3662
3663 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3664 let buffer = self.buffer.read(cx);
3665 let snapshot = buffer.snapshot(cx);
3666
3667 let mut edits = Vec::new();
3668 let mut rows = Vec::new();
3669 let mut rows_inserted = 0;
3670
3671 for selection in self.selections.all_adjusted(cx) {
3672 let cursor = selection.head();
3673 let row = cursor.row;
3674
3675 let point = Point::new(row + 1, 0);
3676 let start_of_line = snapshot.clip_point(point, Bias::Left);
3677
3678 let newline = "\n".to_string();
3679 edits.push((start_of_line..start_of_line, newline));
3680
3681 rows_inserted += 1;
3682 rows.push(row + rows_inserted);
3683 }
3684
3685 self.transact(cx, |editor, cx| {
3686 editor.edit(edits, cx);
3687
3688 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3689 let mut index = 0;
3690 s.move_cursors_with(|map, _, _| {
3691 let row = rows[index];
3692 index += 1;
3693
3694 let point = Point::new(row, 0);
3695 let boundary = map.next_line_boundary(point).1;
3696 let clipped = map.clip_point(boundary, Bias::Left);
3697
3698 (clipped, SelectionGoal::None)
3699 });
3700 });
3701
3702 let mut indent_edits = Vec::new();
3703 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3704 for row in rows {
3705 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3706 for (row, indent) in indents {
3707 if indent.len == 0 {
3708 continue;
3709 }
3710
3711 let text = match indent.kind {
3712 IndentKind::Space => " ".repeat(indent.len as usize),
3713 IndentKind::Tab => "\t".repeat(indent.len as usize),
3714 };
3715 let point = Point::new(row.0, 0);
3716 indent_edits.push((point..point, text));
3717 }
3718 }
3719 editor.edit(indent_edits, cx);
3720 });
3721 }
3722
3723 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3724 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3725 original_indent_columns: Vec::new(),
3726 });
3727 self.insert_with_autoindent_mode(text, autoindent, cx);
3728 }
3729
3730 fn insert_with_autoindent_mode(
3731 &mut self,
3732 text: &str,
3733 autoindent_mode: Option<AutoindentMode>,
3734 cx: &mut ViewContext<Self>,
3735 ) {
3736 if self.read_only(cx) {
3737 return;
3738 }
3739
3740 let text: Arc<str> = text.into();
3741 self.transact(cx, |this, cx| {
3742 let old_selections = this.selections.all_adjusted(cx);
3743 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3744 let anchors = {
3745 let snapshot = buffer.read(cx);
3746 old_selections
3747 .iter()
3748 .map(|s| {
3749 let anchor = snapshot.anchor_after(s.head());
3750 s.map(|_| anchor)
3751 })
3752 .collect::<Vec<_>>()
3753 };
3754 buffer.edit(
3755 old_selections
3756 .iter()
3757 .map(|s| (s.start..s.end, text.clone())),
3758 autoindent_mode,
3759 cx,
3760 );
3761 anchors
3762 });
3763
3764 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3765 s.select_anchors(selection_anchors);
3766 })
3767 });
3768 }
3769
3770 fn trigger_completion_on_input(
3771 &mut self,
3772 text: &str,
3773 trigger_in_words: bool,
3774 cx: &mut ViewContext<Self>,
3775 ) {
3776 if self.is_completion_trigger(text, trigger_in_words, cx) {
3777 self.show_completions(
3778 &ShowCompletions {
3779 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3780 },
3781 cx,
3782 );
3783 } else {
3784 self.hide_context_menu(cx);
3785 }
3786 }
3787
3788 fn is_completion_trigger(
3789 &self,
3790 text: &str,
3791 trigger_in_words: bool,
3792 cx: &mut ViewContext<Self>,
3793 ) -> bool {
3794 let position = self.selections.newest_anchor().head();
3795 let multibuffer = self.buffer.read(cx);
3796 let Some(buffer) = position
3797 .buffer_id
3798 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3799 else {
3800 return false;
3801 };
3802
3803 if let Some(completion_provider) = &self.completion_provider {
3804 completion_provider.is_completion_trigger(
3805 &buffer,
3806 position.text_anchor,
3807 text,
3808 trigger_in_words,
3809 cx,
3810 )
3811 } else {
3812 false
3813 }
3814 }
3815
3816 /// If any empty selections is touching the start of its innermost containing autoclose
3817 /// region, expand it to select the brackets.
3818 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3819 let selections = self.selections.all::<usize>(cx);
3820 let buffer = self.buffer.read(cx).read(cx);
3821 let new_selections = self
3822 .selections_with_autoclose_regions(selections, &buffer)
3823 .map(|(mut selection, region)| {
3824 if !selection.is_empty() {
3825 return selection;
3826 }
3827
3828 if let Some(region) = region {
3829 let mut range = region.range.to_offset(&buffer);
3830 if selection.start == range.start && range.start >= region.pair.start.len() {
3831 range.start -= region.pair.start.len();
3832 if buffer.contains_str_at(range.start, ®ion.pair.start)
3833 && buffer.contains_str_at(range.end, ®ion.pair.end)
3834 {
3835 range.end += region.pair.end.len();
3836 selection.start = range.start;
3837 selection.end = range.end;
3838
3839 return selection;
3840 }
3841 }
3842 }
3843
3844 let always_treat_brackets_as_autoclosed = buffer
3845 .settings_at(selection.start, cx)
3846 .always_treat_brackets_as_autoclosed;
3847
3848 if !always_treat_brackets_as_autoclosed {
3849 return selection;
3850 }
3851
3852 if let Some(scope) = buffer.language_scope_at(selection.start) {
3853 for (pair, enabled) in scope.brackets() {
3854 if !enabled || !pair.close {
3855 continue;
3856 }
3857
3858 if buffer.contains_str_at(selection.start, &pair.end) {
3859 let pair_start_len = pair.start.len();
3860 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3861 {
3862 selection.start -= pair_start_len;
3863 selection.end += pair.end.len();
3864
3865 return selection;
3866 }
3867 }
3868 }
3869 }
3870
3871 selection
3872 })
3873 .collect();
3874
3875 drop(buffer);
3876 self.change_selections(None, cx, |selections| selections.select(new_selections));
3877 }
3878
3879 /// Iterate the given selections, and for each one, find the smallest surrounding
3880 /// autoclose region. This uses the ordering of the selections and the autoclose
3881 /// regions to avoid repeated comparisons.
3882 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3883 &'a self,
3884 selections: impl IntoIterator<Item = Selection<D>>,
3885 buffer: &'a MultiBufferSnapshot,
3886 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3887 let mut i = 0;
3888 let mut regions = self.autoclose_regions.as_slice();
3889 selections.into_iter().map(move |selection| {
3890 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3891
3892 let mut enclosing = None;
3893 while let Some(pair_state) = regions.get(i) {
3894 if pair_state.range.end.to_offset(buffer) < range.start {
3895 regions = ®ions[i + 1..];
3896 i = 0;
3897 } else if pair_state.range.start.to_offset(buffer) > range.end {
3898 break;
3899 } else {
3900 if pair_state.selection_id == selection.id {
3901 enclosing = Some(pair_state);
3902 }
3903 i += 1;
3904 }
3905 }
3906
3907 (selection.clone(), enclosing)
3908 })
3909 }
3910
3911 /// Remove any autoclose regions that no longer contain their selection.
3912 fn invalidate_autoclose_regions(
3913 &mut self,
3914 mut selections: &[Selection<Anchor>],
3915 buffer: &MultiBufferSnapshot,
3916 ) {
3917 self.autoclose_regions.retain(|state| {
3918 let mut i = 0;
3919 while let Some(selection) = selections.get(i) {
3920 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3921 selections = &selections[1..];
3922 continue;
3923 }
3924 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3925 break;
3926 }
3927 if selection.id == state.selection_id {
3928 return true;
3929 } else {
3930 i += 1;
3931 }
3932 }
3933 false
3934 });
3935 }
3936
3937 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3938 let offset = position.to_offset(buffer);
3939 let (word_range, kind) = buffer.surrounding_word(offset, true);
3940 if offset > word_range.start && kind == Some(CharKind::Word) {
3941 Some(
3942 buffer
3943 .text_for_range(word_range.start..offset)
3944 .collect::<String>(),
3945 )
3946 } else {
3947 None
3948 }
3949 }
3950
3951 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3952 self.refresh_inlay_hints(
3953 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3954 cx,
3955 );
3956 }
3957
3958 pub fn inlay_hints_enabled(&self) -> bool {
3959 self.inlay_hint_cache.enabled
3960 }
3961
3962 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3963 if self.project.is_none() || self.mode != EditorMode::Full {
3964 return;
3965 }
3966
3967 let reason_description = reason.description();
3968 let ignore_debounce = matches!(
3969 reason,
3970 InlayHintRefreshReason::SettingsChange(_)
3971 | InlayHintRefreshReason::Toggle(_)
3972 | InlayHintRefreshReason::ExcerptsRemoved(_)
3973 );
3974 let (invalidate_cache, required_languages) = match reason {
3975 InlayHintRefreshReason::Toggle(enabled) => {
3976 self.inlay_hint_cache.enabled = enabled;
3977 if enabled {
3978 (InvalidationStrategy::RefreshRequested, None)
3979 } else {
3980 self.inlay_hint_cache.clear();
3981 self.splice_inlays(
3982 self.visible_inlay_hints(cx)
3983 .iter()
3984 .map(|inlay| inlay.id)
3985 .collect(),
3986 Vec::new(),
3987 cx,
3988 );
3989 return;
3990 }
3991 }
3992 InlayHintRefreshReason::SettingsChange(new_settings) => {
3993 match self.inlay_hint_cache.update_settings(
3994 &self.buffer,
3995 new_settings,
3996 self.visible_inlay_hints(cx),
3997 cx,
3998 ) {
3999 ControlFlow::Break(Some(InlaySplice {
4000 to_remove,
4001 to_insert,
4002 })) => {
4003 self.splice_inlays(to_remove, to_insert, cx);
4004 return;
4005 }
4006 ControlFlow::Break(None) => return,
4007 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4008 }
4009 }
4010 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4011 if let Some(InlaySplice {
4012 to_remove,
4013 to_insert,
4014 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4015 {
4016 self.splice_inlays(to_remove, to_insert, cx);
4017 }
4018 return;
4019 }
4020 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4021 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4022 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4023 }
4024 InlayHintRefreshReason::RefreshRequested => {
4025 (InvalidationStrategy::RefreshRequested, None)
4026 }
4027 };
4028
4029 if let Some(InlaySplice {
4030 to_remove,
4031 to_insert,
4032 }) = self.inlay_hint_cache.spawn_hint_refresh(
4033 reason_description,
4034 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4035 invalidate_cache,
4036 ignore_debounce,
4037 cx,
4038 ) {
4039 self.splice_inlays(to_remove, to_insert, cx);
4040 }
4041 }
4042
4043 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4044 self.display_map
4045 .read(cx)
4046 .current_inlays()
4047 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4048 .cloned()
4049 .collect()
4050 }
4051
4052 pub fn excerpts_for_inlay_hints_query(
4053 &self,
4054 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4055 cx: &mut ViewContext<Editor>,
4056 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4057 let Some(project) = self.project.as_ref() else {
4058 return HashMap::default();
4059 };
4060 let project = project.read(cx);
4061 let multi_buffer = self.buffer().read(cx);
4062 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4063 let multi_buffer_visible_start = self
4064 .scroll_manager
4065 .anchor()
4066 .anchor
4067 .to_point(&multi_buffer_snapshot);
4068 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4069 multi_buffer_visible_start
4070 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4071 Bias::Left,
4072 );
4073 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4074 multi_buffer
4075 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4076 .into_iter()
4077 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4078 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4079 let buffer = buffer_handle.read(cx);
4080 let buffer_file = project::File::from_dyn(buffer.file())?;
4081 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4082 let worktree_entry = buffer_worktree
4083 .read(cx)
4084 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4085 if worktree_entry.is_ignored {
4086 return None;
4087 }
4088
4089 let language = buffer.language()?;
4090 if let Some(restrict_to_languages) = restrict_to_languages {
4091 if !restrict_to_languages.contains(language) {
4092 return None;
4093 }
4094 }
4095 Some((
4096 excerpt_id,
4097 (
4098 buffer_handle,
4099 buffer.version().clone(),
4100 excerpt_visible_range,
4101 ),
4102 ))
4103 })
4104 .collect()
4105 }
4106
4107 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4108 TextLayoutDetails {
4109 text_system: cx.text_system().clone(),
4110 editor_style: self.style.clone().unwrap(),
4111 rem_size: cx.rem_size(),
4112 scroll_anchor: self.scroll_manager.anchor(),
4113 visible_rows: self.visible_line_count(),
4114 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4115 }
4116 }
4117
4118 fn splice_inlays(
4119 &self,
4120 to_remove: Vec<InlayId>,
4121 to_insert: Vec<Inlay>,
4122 cx: &mut ViewContext<Self>,
4123 ) {
4124 self.display_map.update(cx, |display_map, cx| {
4125 display_map.splice_inlays(to_remove, to_insert, cx);
4126 });
4127 cx.notify();
4128 }
4129
4130 fn trigger_on_type_formatting(
4131 &self,
4132 input: String,
4133 cx: &mut ViewContext<Self>,
4134 ) -> Option<Task<Result<()>>> {
4135 if input.len() != 1 {
4136 return None;
4137 }
4138
4139 let project = self.project.as_ref()?;
4140 let position = self.selections.newest_anchor().head();
4141 let (buffer, buffer_position) = self
4142 .buffer
4143 .read(cx)
4144 .text_anchor_for_position(position, cx)?;
4145
4146 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4147 // hence we do LSP request & edit on host side only — add formats to host's history.
4148 let push_to_lsp_host_history = true;
4149 // If this is not the host, append its history with new edits.
4150 let push_to_client_history = project.read(cx).is_via_collab();
4151
4152 let on_type_formatting = project.update(cx, |project, cx| {
4153 project.on_type_format(
4154 buffer.clone(),
4155 buffer_position,
4156 input,
4157 push_to_lsp_host_history,
4158 cx,
4159 )
4160 });
4161 Some(cx.spawn(|editor, mut cx| async move {
4162 if let Some(transaction) = on_type_formatting.await? {
4163 if push_to_client_history {
4164 buffer
4165 .update(&mut cx, |buffer, _| {
4166 buffer.push_transaction(transaction, Instant::now());
4167 })
4168 .ok();
4169 }
4170 editor.update(&mut cx, |editor, cx| {
4171 editor.refresh_document_highlights(cx);
4172 })?;
4173 }
4174 Ok(())
4175 }))
4176 }
4177
4178 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4179 if self.pending_rename.is_some() {
4180 return;
4181 }
4182
4183 let Some(provider) = self.completion_provider.as_ref() else {
4184 return;
4185 };
4186
4187 let position = self.selections.newest_anchor().head();
4188 let (buffer, buffer_position) =
4189 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4190 output
4191 } else {
4192 return;
4193 };
4194
4195 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4196 let is_followup_invoke = {
4197 let context_menu_state = self.context_menu.read();
4198 matches!(
4199 context_menu_state.deref(),
4200 Some(ContextMenu::Completions(_))
4201 )
4202 };
4203 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4204 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4205 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4206 CompletionTriggerKind::TRIGGER_CHARACTER
4207 }
4208
4209 _ => CompletionTriggerKind::INVOKED,
4210 };
4211 let completion_context = CompletionContext {
4212 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4213 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4214 Some(String::from(trigger))
4215 } else {
4216 None
4217 }
4218 }),
4219 trigger_kind,
4220 };
4221 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4222 let sort_completions = provider.sort_completions();
4223
4224 let id = post_inc(&mut self.next_completion_id);
4225 let task = cx.spawn(|this, mut cx| {
4226 async move {
4227 this.update(&mut cx, |this, _| {
4228 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4229 })?;
4230 let completions = completions.await.log_err();
4231 let menu = if let Some(completions) = completions {
4232 let mut menu = CompletionsMenu {
4233 id,
4234 sort_completions,
4235 initial_position: position,
4236 match_candidates: completions
4237 .iter()
4238 .enumerate()
4239 .map(|(id, completion)| {
4240 StringMatchCandidate::new(
4241 id,
4242 completion.label.text[completion.label.filter_range.clone()]
4243 .into(),
4244 )
4245 })
4246 .collect(),
4247 buffer: buffer.clone(),
4248 completions: Arc::new(RwLock::new(completions.into())),
4249 matches: Vec::new().into(),
4250 selected_item: 0,
4251 scroll_handle: UniformListScrollHandle::new(),
4252 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4253 DebouncedDelay::new(),
4254 )),
4255 };
4256 menu.filter(query.as_deref(), cx.background_executor().clone())
4257 .await;
4258
4259 if menu.matches.is_empty() {
4260 None
4261 } else {
4262 this.update(&mut cx, |editor, cx| {
4263 let completions = menu.completions.clone();
4264 let matches = menu.matches.clone();
4265
4266 let delay_ms = EditorSettings::get_global(cx)
4267 .completion_documentation_secondary_query_debounce;
4268 let delay = Duration::from_millis(delay_ms);
4269 editor
4270 .completion_documentation_pre_resolve_debounce
4271 .fire_new(delay, cx, |editor, cx| {
4272 CompletionsMenu::pre_resolve_completion_documentation(
4273 buffer,
4274 completions,
4275 matches,
4276 editor,
4277 cx,
4278 )
4279 });
4280 })
4281 .ok();
4282 Some(menu)
4283 }
4284 } else {
4285 None
4286 };
4287
4288 this.update(&mut cx, |this, cx| {
4289 let mut context_menu = this.context_menu.write();
4290 match context_menu.as_ref() {
4291 None => {}
4292
4293 Some(ContextMenu::Completions(prev_menu)) => {
4294 if prev_menu.id > id {
4295 return;
4296 }
4297 }
4298
4299 _ => return,
4300 }
4301
4302 if this.focus_handle.is_focused(cx) && menu.is_some() {
4303 let menu = menu.unwrap();
4304 *context_menu = Some(ContextMenu::Completions(menu));
4305 drop(context_menu);
4306 this.discard_inline_completion(false, cx);
4307 cx.notify();
4308 } else if this.completion_tasks.len() <= 1 {
4309 // If there are no more completion tasks and the last menu was
4310 // empty, we should hide it. If it was already hidden, we should
4311 // also show the copilot completion when available.
4312 drop(context_menu);
4313 if this.hide_context_menu(cx).is_none() {
4314 this.update_visible_inline_completion(cx);
4315 }
4316 }
4317 })?;
4318
4319 Ok::<_, anyhow::Error>(())
4320 }
4321 .log_err()
4322 });
4323
4324 self.completion_tasks.push((id, task));
4325 }
4326
4327 pub fn confirm_completion(
4328 &mut self,
4329 action: &ConfirmCompletion,
4330 cx: &mut ViewContext<Self>,
4331 ) -> Option<Task<Result<()>>> {
4332 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4333 }
4334
4335 pub fn compose_completion(
4336 &mut self,
4337 action: &ComposeCompletion,
4338 cx: &mut ViewContext<Self>,
4339 ) -> Option<Task<Result<()>>> {
4340 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4341 }
4342
4343 fn do_completion(
4344 &mut self,
4345 item_ix: Option<usize>,
4346 intent: CompletionIntent,
4347 cx: &mut ViewContext<Editor>,
4348 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4349 use language::ToOffset as _;
4350
4351 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4352 menu
4353 } else {
4354 return None;
4355 };
4356
4357 let mat = completions_menu
4358 .matches
4359 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4360 let buffer_handle = completions_menu.buffer;
4361 let completions = completions_menu.completions.read();
4362 let completion = completions.get(mat.candidate_id)?;
4363 cx.stop_propagation();
4364
4365 let snippet;
4366 let text;
4367
4368 if completion.is_snippet() {
4369 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4370 text = snippet.as_ref().unwrap().text.clone();
4371 } else {
4372 snippet = None;
4373 text = completion.new_text.clone();
4374 };
4375 let selections = self.selections.all::<usize>(cx);
4376 let buffer = buffer_handle.read(cx);
4377 let old_range = completion.old_range.to_offset(buffer);
4378 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4379
4380 let newest_selection = self.selections.newest_anchor();
4381 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4382 return None;
4383 }
4384
4385 let lookbehind = newest_selection
4386 .start
4387 .text_anchor
4388 .to_offset(buffer)
4389 .saturating_sub(old_range.start);
4390 let lookahead = old_range
4391 .end
4392 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4393 let mut common_prefix_len = old_text
4394 .bytes()
4395 .zip(text.bytes())
4396 .take_while(|(a, b)| a == b)
4397 .count();
4398
4399 let snapshot = self.buffer.read(cx).snapshot(cx);
4400 let mut range_to_replace: Option<Range<isize>> = None;
4401 let mut ranges = Vec::new();
4402 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4403 for selection in &selections {
4404 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4405 let start = selection.start.saturating_sub(lookbehind);
4406 let end = selection.end + lookahead;
4407 if selection.id == newest_selection.id {
4408 range_to_replace = Some(
4409 ((start + common_prefix_len) as isize - selection.start as isize)
4410 ..(end as isize - selection.start as isize),
4411 );
4412 }
4413 ranges.push(start + common_prefix_len..end);
4414 } else {
4415 common_prefix_len = 0;
4416 ranges.clear();
4417 ranges.extend(selections.iter().map(|s| {
4418 if s.id == newest_selection.id {
4419 range_to_replace = Some(
4420 old_range.start.to_offset_utf16(&snapshot).0 as isize
4421 - selection.start as isize
4422 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4423 - selection.start as isize,
4424 );
4425 old_range.clone()
4426 } else {
4427 s.start..s.end
4428 }
4429 }));
4430 break;
4431 }
4432 if !self.linked_edit_ranges.is_empty() {
4433 let start_anchor = snapshot.anchor_before(selection.head());
4434 let end_anchor = snapshot.anchor_after(selection.tail());
4435 if let Some(ranges) = self
4436 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4437 {
4438 for (buffer, edits) in ranges {
4439 linked_edits.entry(buffer.clone()).or_default().extend(
4440 edits
4441 .into_iter()
4442 .map(|range| (range, text[common_prefix_len..].to_owned())),
4443 );
4444 }
4445 }
4446 }
4447 }
4448 let text = &text[common_prefix_len..];
4449
4450 cx.emit(EditorEvent::InputHandled {
4451 utf16_range_to_replace: range_to_replace,
4452 text: text.into(),
4453 });
4454
4455 self.transact(cx, |this, cx| {
4456 if let Some(mut snippet) = snippet {
4457 snippet.text = text.to_string();
4458 for tabstop in snippet.tabstops.iter_mut().flatten() {
4459 tabstop.start -= common_prefix_len as isize;
4460 tabstop.end -= common_prefix_len as isize;
4461 }
4462
4463 this.insert_snippet(&ranges, snippet, cx).log_err();
4464 } else {
4465 this.buffer.update(cx, |buffer, cx| {
4466 buffer.edit(
4467 ranges.iter().map(|range| (range.clone(), text)),
4468 this.autoindent_mode.clone(),
4469 cx,
4470 );
4471 });
4472 }
4473 for (buffer, edits) in linked_edits {
4474 buffer.update(cx, |buffer, cx| {
4475 let snapshot = buffer.snapshot();
4476 let edits = edits
4477 .into_iter()
4478 .map(|(range, text)| {
4479 use text::ToPoint as TP;
4480 let end_point = TP::to_point(&range.end, &snapshot);
4481 let start_point = TP::to_point(&range.start, &snapshot);
4482 (start_point..end_point, text)
4483 })
4484 .sorted_by_key(|(range, _)| range.start)
4485 .collect::<Vec<_>>();
4486 buffer.edit(edits, None, cx);
4487 })
4488 }
4489
4490 this.refresh_inline_completion(true, false, cx);
4491 });
4492
4493 let show_new_completions_on_confirm = completion
4494 .confirm
4495 .as_ref()
4496 .map_or(false, |confirm| confirm(intent, cx));
4497 if show_new_completions_on_confirm {
4498 self.show_completions(&ShowCompletions { trigger: None }, cx);
4499 }
4500
4501 let provider = self.completion_provider.as_ref()?;
4502 let apply_edits = provider.apply_additional_edits_for_completion(
4503 buffer_handle,
4504 completion.clone(),
4505 true,
4506 cx,
4507 );
4508
4509 let editor_settings = EditorSettings::get_global(cx);
4510 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4511 // After the code completion is finished, users often want to know what signatures are needed.
4512 // so we should automatically call signature_help
4513 self.show_signature_help(&ShowSignatureHelp, cx);
4514 }
4515
4516 Some(cx.foreground_executor().spawn(async move {
4517 apply_edits.await?;
4518 Ok(())
4519 }))
4520 }
4521
4522 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4523 let mut context_menu = self.context_menu.write();
4524 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4525 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4526 // Toggle if we're selecting the same one
4527 *context_menu = None;
4528 cx.notify();
4529 return;
4530 } else {
4531 // Otherwise, clear it and start a new one
4532 *context_menu = None;
4533 cx.notify();
4534 }
4535 }
4536 drop(context_menu);
4537 let snapshot = self.snapshot(cx);
4538 let deployed_from_indicator = action.deployed_from_indicator;
4539 let mut task = self.code_actions_task.take();
4540 let action = action.clone();
4541 cx.spawn(|editor, mut cx| async move {
4542 while let Some(prev_task) = task {
4543 prev_task.await;
4544 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4545 }
4546
4547 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4548 if editor.focus_handle.is_focused(cx) {
4549 let multibuffer_point = action
4550 .deployed_from_indicator
4551 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4552 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4553 let (buffer, buffer_row) = snapshot
4554 .buffer_snapshot
4555 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4556 .and_then(|(buffer_snapshot, range)| {
4557 editor
4558 .buffer
4559 .read(cx)
4560 .buffer(buffer_snapshot.remote_id())
4561 .map(|buffer| (buffer, range.start.row))
4562 })?;
4563 let (_, code_actions) = editor
4564 .available_code_actions
4565 .clone()
4566 .and_then(|(location, code_actions)| {
4567 let snapshot = location.buffer.read(cx).snapshot();
4568 let point_range = location.range.to_point(&snapshot);
4569 let point_range = point_range.start.row..=point_range.end.row;
4570 if point_range.contains(&buffer_row) {
4571 Some((location, code_actions))
4572 } else {
4573 None
4574 }
4575 })
4576 .unzip();
4577 let buffer_id = buffer.read(cx).remote_id();
4578 let tasks = editor
4579 .tasks
4580 .get(&(buffer_id, buffer_row))
4581 .map(|t| Arc::new(t.to_owned()));
4582 if tasks.is_none() && code_actions.is_none() {
4583 return None;
4584 }
4585
4586 editor.completion_tasks.clear();
4587 editor.discard_inline_completion(false, cx);
4588 let task_context =
4589 tasks
4590 .as_ref()
4591 .zip(editor.project.clone())
4592 .map(|(tasks, project)| {
4593 let position = Point::new(buffer_row, tasks.column);
4594 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4595 let location = Location {
4596 buffer: buffer.clone(),
4597 range: range_start..range_start,
4598 };
4599 // Fill in the environmental variables from the tree-sitter captures
4600 let mut captured_task_variables = TaskVariables::default();
4601 for (capture_name, value) in tasks.extra_variables.clone() {
4602 captured_task_variables.insert(
4603 task::VariableName::Custom(capture_name.into()),
4604 value.clone(),
4605 );
4606 }
4607 project.update(cx, |project, cx| {
4608 project.task_context_for_location(
4609 captured_task_variables,
4610 location,
4611 cx,
4612 )
4613 })
4614 });
4615
4616 Some(cx.spawn(|editor, mut cx| async move {
4617 let task_context = match task_context {
4618 Some(task_context) => task_context.await,
4619 None => None,
4620 };
4621 let resolved_tasks =
4622 tasks.zip(task_context).map(|(tasks, task_context)| {
4623 Arc::new(ResolvedTasks {
4624 templates: tasks
4625 .templates
4626 .iter()
4627 .filter_map(|(kind, template)| {
4628 template
4629 .resolve_task(&kind.to_id_base(), &task_context)
4630 .map(|task| (kind.clone(), task))
4631 })
4632 .collect(),
4633 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4634 multibuffer_point.row,
4635 tasks.column,
4636 )),
4637 })
4638 });
4639 let spawn_straight_away = resolved_tasks
4640 .as_ref()
4641 .map_or(false, |tasks| tasks.templates.len() == 1)
4642 && code_actions
4643 .as_ref()
4644 .map_or(true, |actions| actions.is_empty());
4645 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4646 *editor.context_menu.write() =
4647 Some(ContextMenu::CodeActions(CodeActionsMenu {
4648 buffer,
4649 actions: CodeActionContents {
4650 tasks: resolved_tasks,
4651 actions: code_actions,
4652 },
4653 selected_item: Default::default(),
4654 scroll_handle: UniformListScrollHandle::default(),
4655 deployed_from_indicator,
4656 }));
4657 if spawn_straight_away {
4658 if let Some(task) = editor.confirm_code_action(
4659 &ConfirmCodeAction { item_ix: Some(0) },
4660 cx,
4661 ) {
4662 cx.notify();
4663 return task;
4664 }
4665 }
4666 cx.notify();
4667 Task::ready(Ok(()))
4668 }) {
4669 task.await
4670 } else {
4671 Ok(())
4672 }
4673 }))
4674 } else {
4675 Some(Task::ready(Ok(())))
4676 }
4677 })?;
4678 if let Some(task) = spawned_test_task {
4679 task.await?;
4680 }
4681
4682 Ok::<_, anyhow::Error>(())
4683 })
4684 .detach_and_log_err(cx);
4685 }
4686
4687 pub fn confirm_code_action(
4688 &mut self,
4689 action: &ConfirmCodeAction,
4690 cx: &mut ViewContext<Self>,
4691 ) -> Option<Task<Result<()>>> {
4692 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4693 menu
4694 } else {
4695 return None;
4696 };
4697 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4698 let action = actions_menu.actions.get(action_ix)?;
4699 let title = action.label();
4700 let buffer = actions_menu.buffer;
4701 let workspace = self.workspace()?;
4702
4703 match action {
4704 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4705 workspace.update(cx, |workspace, cx| {
4706 workspace::tasks::schedule_resolved_task(
4707 workspace,
4708 task_source_kind,
4709 resolved_task,
4710 false,
4711 cx,
4712 );
4713
4714 Some(Task::ready(Ok(())))
4715 })
4716 }
4717 CodeActionsItem::CodeAction(action) => {
4718 let apply_code_actions = workspace
4719 .read(cx)
4720 .project()
4721 .clone()
4722 .update(cx, |project, cx| {
4723 project.apply_code_action(buffer, action, true, cx)
4724 });
4725 let workspace = workspace.downgrade();
4726 Some(cx.spawn(|editor, cx| async move {
4727 let project_transaction = apply_code_actions.await?;
4728 Self::open_project_transaction(
4729 &editor,
4730 workspace,
4731 project_transaction,
4732 title,
4733 cx,
4734 )
4735 .await
4736 }))
4737 }
4738 }
4739 }
4740
4741 pub async fn open_project_transaction(
4742 this: &WeakView<Editor>,
4743 workspace: WeakView<Workspace>,
4744 transaction: ProjectTransaction,
4745 title: String,
4746 mut cx: AsyncWindowContext,
4747 ) -> Result<()> {
4748 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4749
4750 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4751 cx.update(|cx| {
4752 entries.sort_unstable_by_key(|(buffer, _)| {
4753 buffer.read(cx).file().map(|f| f.path().clone())
4754 });
4755 })?;
4756
4757 // If the project transaction's edits are all contained within this editor, then
4758 // avoid opening a new editor to display them.
4759
4760 if let Some((buffer, transaction)) = entries.first() {
4761 if entries.len() == 1 {
4762 let excerpt = this.update(&mut cx, |editor, cx| {
4763 editor
4764 .buffer()
4765 .read(cx)
4766 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4767 })?;
4768 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4769 if excerpted_buffer == *buffer {
4770 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4771 let excerpt_range = excerpt_range.to_offset(buffer);
4772 buffer
4773 .edited_ranges_for_transaction::<usize>(transaction)
4774 .all(|range| {
4775 excerpt_range.start <= range.start
4776 && excerpt_range.end >= range.end
4777 })
4778 })?;
4779
4780 if all_edits_within_excerpt {
4781 return Ok(());
4782 }
4783 }
4784 }
4785 }
4786 } else {
4787 return Ok(());
4788 }
4789
4790 let mut ranges_to_highlight = Vec::new();
4791 let excerpt_buffer = cx.new_model(|cx| {
4792 let mut multibuffer =
4793 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4794 for (buffer_handle, transaction) in &entries {
4795 let buffer = buffer_handle.read(cx);
4796 ranges_to_highlight.extend(
4797 multibuffer.push_excerpts_with_context_lines(
4798 buffer_handle.clone(),
4799 buffer
4800 .edited_ranges_for_transaction::<usize>(transaction)
4801 .collect(),
4802 DEFAULT_MULTIBUFFER_CONTEXT,
4803 cx,
4804 ),
4805 );
4806 }
4807 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4808 multibuffer
4809 })?;
4810
4811 workspace.update(&mut cx, |workspace, cx| {
4812 let project = workspace.project().clone();
4813 let editor =
4814 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4815 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4816 editor.update(cx, |editor, cx| {
4817 editor.highlight_background::<Self>(
4818 &ranges_to_highlight,
4819 |theme| theme.editor_highlighted_line_background,
4820 cx,
4821 );
4822 });
4823 })?;
4824
4825 Ok(())
4826 }
4827
4828 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4829 let project = self.project.clone()?;
4830 let buffer = self.buffer.read(cx);
4831 let newest_selection = self.selections.newest_anchor().clone();
4832 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4833 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4834 if start_buffer != end_buffer {
4835 return None;
4836 }
4837
4838 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4839 cx.background_executor()
4840 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4841 .await;
4842
4843 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4844 project.code_actions(&start_buffer, start..end, cx)
4845 }) {
4846 code_actions.await
4847 } else {
4848 Vec::new()
4849 };
4850
4851 this.update(&mut cx, |this, cx| {
4852 this.available_code_actions = if actions.is_empty() {
4853 None
4854 } else {
4855 Some((
4856 Location {
4857 buffer: start_buffer,
4858 range: start..end,
4859 },
4860 actions.into(),
4861 ))
4862 };
4863 cx.notify();
4864 })
4865 .log_err();
4866 }));
4867 None
4868 }
4869
4870 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4871 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4872 self.show_git_blame_inline = false;
4873
4874 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4875 cx.background_executor().timer(delay).await;
4876
4877 this.update(&mut cx, |this, cx| {
4878 this.show_git_blame_inline = true;
4879 cx.notify();
4880 })
4881 .log_err();
4882 }));
4883 }
4884 }
4885
4886 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4887 if self.pending_rename.is_some() {
4888 return None;
4889 }
4890
4891 let project = self.project.clone()?;
4892 let buffer = self.buffer.read(cx);
4893 let newest_selection = self.selections.newest_anchor().clone();
4894 let cursor_position = newest_selection.head();
4895 let (cursor_buffer, cursor_buffer_position) =
4896 buffer.text_anchor_for_position(cursor_position, cx)?;
4897 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4898 if cursor_buffer != tail_buffer {
4899 return None;
4900 }
4901
4902 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4903 cx.background_executor()
4904 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4905 .await;
4906
4907 let highlights = if let Some(highlights) = project
4908 .update(&mut cx, |project, cx| {
4909 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4910 })
4911 .log_err()
4912 {
4913 highlights.await.log_err()
4914 } else {
4915 None
4916 };
4917
4918 if let Some(highlights) = highlights {
4919 this.update(&mut cx, |this, cx| {
4920 if this.pending_rename.is_some() {
4921 return;
4922 }
4923
4924 let buffer_id = cursor_position.buffer_id;
4925 let buffer = this.buffer.read(cx);
4926 if !buffer
4927 .text_anchor_for_position(cursor_position, cx)
4928 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4929 {
4930 return;
4931 }
4932
4933 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4934 let mut write_ranges = Vec::new();
4935 let mut read_ranges = Vec::new();
4936 for highlight in highlights {
4937 for (excerpt_id, excerpt_range) in
4938 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4939 {
4940 let start = highlight
4941 .range
4942 .start
4943 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4944 let end = highlight
4945 .range
4946 .end
4947 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4948 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4949 continue;
4950 }
4951
4952 let range = Anchor {
4953 buffer_id,
4954 excerpt_id,
4955 text_anchor: start,
4956 }..Anchor {
4957 buffer_id,
4958 excerpt_id,
4959 text_anchor: end,
4960 };
4961 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4962 write_ranges.push(range);
4963 } else {
4964 read_ranges.push(range);
4965 }
4966 }
4967 }
4968
4969 this.highlight_background::<DocumentHighlightRead>(
4970 &read_ranges,
4971 |theme| theme.editor_document_highlight_read_background,
4972 cx,
4973 );
4974 this.highlight_background::<DocumentHighlightWrite>(
4975 &write_ranges,
4976 |theme| theme.editor_document_highlight_write_background,
4977 cx,
4978 );
4979 cx.notify();
4980 })
4981 .log_err();
4982 }
4983 }));
4984 None
4985 }
4986
4987 pub fn refresh_inline_completion(
4988 &mut self,
4989 debounce: bool,
4990 user_requested: bool,
4991 cx: &mut ViewContext<Self>,
4992 ) -> Option<()> {
4993 let provider = self.inline_completion_provider()?;
4994 let cursor = self.selections.newest_anchor().head();
4995 let (buffer, cursor_buffer_position) =
4996 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4997
4998 if !user_requested
4999 && (!self.enable_inline_completions
5000 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5001 {
5002 self.discard_inline_completion(false, cx);
5003 return None;
5004 }
5005
5006 self.update_visible_inline_completion(cx);
5007 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5008 Some(())
5009 }
5010
5011 fn cycle_inline_completion(
5012 &mut self,
5013 direction: Direction,
5014 cx: &mut ViewContext<Self>,
5015 ) -> Option<()> {
5016 let provider = self.inline_completion_provider()?;
5017 let cursor = self.selections.newest_anchor().head();
5018 let (buffer, cursor_buffer_position) =
5019 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5020 if !self.enable_inline_completions
5021 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5022 {
5023 return None;
5024 }
5025
5026 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5027 self.update_visible_inline_completion(cx);
5028
5029 Some(())
5030 }
5031
5032 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5033 if !self.has_active_inline_completion(cx) {
5034 self.refresh_inline_completion(false, true, cx);
5035 return;
5036 }
5037
5038 self.update_visible_inline_completion(cx);
5039 }
5040
5041 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5042 self.show_cursor_names(cx);
5043 }
5044
5045 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5046 self.show_cursor_names = true;
5047 cx.notify();
5048 cx.spawn(|this, mut cx| async move {
5049 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5050 this.update(&mut cx, |this, cx| {
5051 this.show_cursor_names = false;
5052 cx.notify()
5053 })
5054 .ok()
5055 })
5056 .detach();
5057 }
5058
5059 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5060 if self.has_active_inline_completion(cx) {
5061 self.cycle_inline_completion(Direction::Next, cx);
5062 } else {
5063 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5064 if is_copilot_disabled {
5065 cx.propagate();
5066 }
5067 }
5068 }
5069
5070 pub fn previous_inline_completion(
5071 &mut self,
5072 _: &PreviousInlineCompletion,
5073 cx: &mut ViewContext<Self>,
5074 ) {
5075 if self.has_active_inline_completion(cx) {
5076 self.cycle_inline_completion(Direction::Prev, cx);
5077 } else {
5078 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5079 if is_copilot_disabled {
5080 cx.propagate();
5081 }
5082 }
5083 }
5084
5085 pub fn accept_inline_completion(
5086 &mut self,
5087 _: &AcceptInlineCompletion,
5088 cx: &mut ViewContext<Self>,
5089 ) {
5090 let Some(completion) = self.take_active_inline_completion(cx) else {
5091 return;
5092 };
5093 if let Some(provider) = self.inline_completion_provider() {
5094 provider.accept(cx);
5095 }
5096
5097 cx.emit(EditorEvent::InputHandled {
5098 utf16_range_to_replace: None,
5099 text: completion.text.to_string().into(),
5100 });
5101
5102 if let Some(range) = completion.delete_range {
5103 self.change_selections(None, cx, |s| s.select_ranges([range]))
5104 }
5105 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5106 self.refresh_inline_completion(true, true, cx);
5107 cx.notify();
5108 }
5109
5110 pub fn accept_partial_inline_completion(
5111 &mut self,
5112 _: &AcceptPartialInlineCompletion,
5113 cx: &mut ViewContext<Self>,
5114 ) {
5115 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5116 if let Some(completion) = self.take_active_inline_completion(cx) {
5117 let mut partial_completion = completion
5118 .text
5119 .chars()
5120 .by_ref()
5121 .take_while(|c| c.is_alphabetic())
5122 .collect::<String>();
5123 if partial_completion.is_empty() {
5124 partial_completion = completion
5125 .text
5126 .chars()
5127 .by_ref()
5128 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5129 .collect::<String>();
5130 }
5131
5132 cx.emit(EditorEvent::InputHandled {
5133 utf16_range_to_replace: None,
5134 text: partial_completion.clone().into(),
5135 });
5136
5137 if let Some(range) = completion.delete_range {
5138 self.change_selections(None, cx, |s| s.select_ranges([range]))
5139 }
5140 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5141
5142 self.refresh_inline_completion(true, true, cx);
5143 cx.notify();
5144 }
5145 }
5146 }
5147
5148 fn discard_inline_completion(
5149 &mut self,
5150 should_report_inline_completion_event: bool,
5151 cx: &mut ViewContext<Self>,
5152 ) -> bool {
5153 if let Some(provider) = self.inline_completion_provider() {
5154 provider.discard(should_report_inline_completion_event, cx);
5155 }
5156
5157 self.take_active_inline_completion(cx).is_some()
5158 }
5159
5160 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5161 if let Some(completion) = self.active_inline_completion.as_ref() {
5162 let buffer = self.buffer.read(cx).read(cx);
5163 completion.position.is_valid(&buffer)
5164 } else {
5165 false
5166 }
5167 }
5168
5169 fn take_active_inline_completion(
5170 &mut self,
5171 cx: &mut ViewContext<Self>,
5172 ) -> Option<CompletionState> {
5173 let completion = self.active_inline_completion.take()?;
5174 let render_inlay_ids = completion.render_inlay_ids.clone();
5175 self.display_map.update(cx, |map, cx| {
5176 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5177 });
5178 let buffer = self.buffer.read(cx).read(cx);
5179
5180 if completion.position.is_valid(&buffer) {
5181 Some(completion)
5182 } else {
5183 None
5184 }
5185 }
5186
5187 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5188 let selection = self.selections.newest_anchor();
5189 let cursor = selection.head();
5190
5191 let excerpt_id = cursor.excerpt_id;
5192
5193 if self.context_menu.read().is_none()
5194 && self.completion_tasks.is_empty()
5195 && selection.start == selection.end
5196 {
5197 if let Some(provider) = self.inline_completion_provider() {
5198 if let Some((buffer, cursor_buffer_position)) =
5199 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5200 {
5201 if let Some(proposal) =
5202 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5203 {
5204 let mut to_remove = Vec::new();
5205 if let Some(completion) = self.active_inline_completion.take() {
5206 to_remove.extend(completion.render_inlay_ids.iter());
5207 }
5208
5209 let to_add = proposal
5210 .inlays
5211 .iter()
5212 .filter_map(|inlay| {
5213 let snapshot = self.buffer.read(cx).snapshot(cx);
5214 let id = post_inc(&mut self.next_inlay_id);
5215 match inlay {
5216 InlayProposal::Hint(position, hint) => {
5217 let position =
5218 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5219 Some(Inlay::hint(id, position, hint))
5220 }
5221 InlayProposal::Suggestion(position, text) => {
5222 let position =
5223 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5224 Some(Inlay::suggestion(id, position, text.clone()))
5225 }
5226 }
5227 })
5228 .collect_vec();
5229
5230 self.active_inline_completion = Some(CompletionState {
5231 position: cursor,
5232 text: proposal.text,
5233 delete_range: proposal.delete_range.and_then(|range| {
5234 let snapshot = self.buffer.read(cx).snapshot(cx);
5235 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5236 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5237 Some(start?..end?)
5238 }),
5239 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5240 });
5241
5242 self.display_map
5243 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5244
5245 cx.notify();
5246 return;
5247 }
5248 }
5249 }
5250 }
5251
5252 self.discard_inline_completion(false, cx);
5253 }
5254
5255 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5256 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5257 }
5258
5259 fn render_code_actions_indicator(
5260 &self,
5261 _style: &EditorStyle,
5262 row: DisplayRow,
5263 is_active: bool,
5264 cx: &mut ViewContext<Self>,
5265 ) -> Option<IconButton> {
5266 if self.available_code_actions.is_some() {
5267 Some(
5268 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5269 .shape(ui::IconButtonShape::Square)
5270 .icon_size(IconSize::XSmall)
5271 .icon_color(Color::Muted)
5272 .selected(is_active)
5273 .on_click(cx.listener(move |editor, _e, cx| {
5274 editor.focus(cx);
5275 editor.toggle_code_actions(
5276 &ToggleCodeActions {
5277 deployed_from_indicator: Some(row),
5278 },
5279 cx,
5280 );
5281 })),
5282 )
5283 } else {
5284 None
5285 }
5286 }
5287
5288 fn clear_tasks(&mut self) {
5289 self.tasks.clear()
5290 }
5291
5292 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5293 if self.tasks.insert(key, value).is_some() {
5294 // This case should hopefully be rare, but just in case...
5295 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5296 }
5297 }
5298
5299 fn render_run_indicator(
5300 &self,
5301 _style: &EditorStyle,
5302 is_active: bool,
5303 row: DisplayRow,
5304 cx: &mut ViewContext<Self>,
5305 ) -> IconButton {
5306 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5307 .shape(ui::IconButtonShape::Square)
5308 .icon_size(IconSize::XSmall)
5309 .icon_color(Color::Muted)
5310 .selected(is_active)
5311 .on_click(cx.listener(move |editor, _e, cx| {
5312 editor.focus(cx);
5313 editor.toggle_code_actions(
5314 &ToggleCodeActions {
5315 deployed_from_indicator: Some(row),
5316 },
5317 cx,
5318 );
5319 }))
5320 }
5321
5322 fn close_hunk_diff_button(
5323 &self,
5324 hunk: HoveredHunk,
5325 row: DisplayRow,
5326 cx: &mut ViewContext<Self>,
5327 ) -> IconButton {
5328 IconButton::new(
5329 ("close_hunk_diff_indicator", row.0 as usize),
5330 ui::IconName::Close,
5331 )
5332 .shape(ui::IconButtonShape::Square)
5333 .icon_size(IconSize::XSmall)
5334 .icon_color(Color::Muted)
5335 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5336 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5337 }
5338
5339 pub fn context_menu_visible(&self) -> bool {
5340 self.context_menu
5341 .read()
5342 .as_ref()
5343 .map_or(false, |menu| menu.visible())
5344 }
5345
5346 fn render_context_menu(
5347 &self,
5348 cursor_position: DisplayPoint,
5349 style: &EditorStyle,
5350 max_height: Pixels,
5351 cx: &mut ViewContext<Editor>,
5352 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5353 self.context_menu.read().as_ref().map(|menu| {
5354 menu.render(
5355 cursor_position,
5356 style,
5357 max_height,
5358 self.workspace.as_ref().map(|(w, _)| w.clone()),
5359 cx,
5360 )
5361 })
5362 }
5363
5364 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5365 cx.notify();
5366 self.completion_tasks.clear();
5367 let context_menu = self.context_menu.write().take();
5368 if context_menu.is_some() {
5369 self.update_visible_inline_completion(cx);
5370 }
5371 context_menu
5372 }
5373
5374 pub fn insert_snippet(
5375 &mut self,
5376 insertion_ranges: &[Range<usize>],
5377 snippet: Snippet,
5378 cx: &mut ViewContext<Self>,
5379 ) -> Result<()> {
5380 struct Tabstop<T> {
5381 is_end_tabstop: bool,
5382 ranges: Vec<Range<T>>,
5383 }
5384
5385 let tabstops = self.buffer.update(cx, |buffer, cx| {
5386 let snippet_text: Arc<str> = snippet.text.clone().into();
5387 buffer.edit(
5388 insertion_ranges
5389 .iter()
5390 .cloned()
5391 .map(|range| (range, snippet_text.clone())),
5392 Some(AutoindentMode::EachLine),
5393 cx,
5394 );
5395
5396 let snapshot = &*buffer.read(cx);
5397 let snippet = &snippet;
5398 snippet
5399 .tabstops
5400 .iter()
5401 .map(|tabstop| {
5402 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5403 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5404 });
5405 let mut tabstop_ranges = tabstop
5406 .iter()
5407 .flat_map(|tabstop_range| {
5408 let mut delta = 0_isize;
5409 insertion_ranges.iter().map(move |insertion_range| {
5410 let insertion_start = insertion_range.start as isize + delta;
5411 delta +=
5412 snippet.text.len() as isize - insertion_range.len() as isize;
5413
5414 let start = ((insertion_start + tabstop_range.start) as usize)
5415 .min(snapshot.len());
5416 let end = ((insertion_start + tabstop_range.end) as usize)
5417 .min(snapshot.len());
5418 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5419 })
5420 })
5421 .collect::<Vec<_>>();
5422 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5423
5424 Tabstop {
5425 is_end_tabstop,
5426 ranges: tabstop_ranges,
5427 }
5428 })
5429 .collect::<Vec<_>>()
5430 });
5431 if let Some(tabstop) = tabstops.first() {
5432 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5433 s.select_ranges(tabstop.ranges.iter().cloned());
5434 });
5435
5436 // If we're already at the last tabstop and it's at the end of the snippet,
5437 // we're done, we don't need to keep the state around.
5438 if !tabstop.is_end_tabstop {
5439 let ranges = tabstops
5440 .into_iter()
5441 .map(|tabstop| tabstop.ranges)
5442 .collect::<Vec<_>>();
5443 self.snippet_stack.push(SnippetState {
5444 active_index: 0,
5445 ranges,
5446 });
5447 }
5448
5449 // Check whether the just-entered snippet ends with an auto-closable bracket.
5450 if self.autoclose_regions.is_empty() {
5451 let snapshot = self.buffer.read(cx).snapshot(cx);
5452 for selection in &mut self.selections.all::<Point>(cx) {
5453 let selection_head = selection.head();
5454 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5455 continue;
5456 };
5457
5458 let mut bracket_pair = None;
5459 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5460 let prev_chars = snapshot
5461 .reversed_chars_at(selection_head)
5462 .collect::<String>();
5463 for (pair, enabled) in scope.brackets() {
5464 if enabled
5465 && pair.close
5466 && prev_chars.starts_with(pair.start.as_str())
5467 && next_chars.starts_with(pair.end.as_str())
5468 {
5469 bracket_pair = Some(pair.clone());
5470 break;
5471 }
5472 }
5473 if let Some(pair) = bracket_pair {
5474 let start = snapshot.anchor_after(selection_head);
5475 let end = snapshot.anchor_after(selection_head);
5476 self.autoclose_regions.push(AutocloseRegion {
5477 selection_id: selection.id,
5478 range: start..end,
5479 pair,
5480 });
5481 }
5482 }
5483 }
5484 }
5485 Ok(())
5486 }
5487
5488 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5489 self.move_to_snippet_tabstop(Bias::Right, cx)
5490 }
5491
5492 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5493 self.move_to_snippet_tabstop(Bias::Left, cx)
5494 }
5495
5496 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5497 if let Some(mut snippet) = self.snippet_stack.pop() {
5498 match bias {
5499 Bias::Left => {
5500 if snippet.active_index > 0 {
5501 snippet.active_index -= 1;
5502 } else {
5503 self.snippet_stack.push(snippet);
5504 return false;
5505 }
5506 }
5507 Bias::Right => {
5508 if snippet.active_index + 1 < snippet.ranges.len() {
5509 snippet.active_index += 1;
5510 } else {
5511 self.snippet_stack.push(snippet);
5512 return false;
5513 }
5514 }
5515 }
5516 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5517 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5518 s.select_anchor_ranges(current_ranges.iter().cloned())
5519 });
5520 // If snippet state is not at the last tabstop, push it back on the stack
5521 if snippet.active_index + 1 < snippet.ranges.len() {
5522 self.snippet_stack.push(snippet);
5523 }
5524 return true;
5525 }
5526 }
5527
5528 false
5529 }
5530
5531 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5532 self.transact(cx, |this, cx| {
5533 this.select_all(&SelectAll, cx);
5534 this.insert("", cx);
5535 });
5536 }
5537
5538 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5539 self.transact(cx, |this, cx| {
5540 this.select_autoclose_pair(cx);
5541 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5542 if !this.linked_edit_ranges.is_empty() {
5543 let selections = this.selections.all::<MultiBufferPoint>(cx);
5544 let snapshot = this.buffer.read(cx).snapshot(cx);
5545
5546 for selection in selections.iter() {
5547 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5548 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5549 if selection_start.buffer_id != selection_end.buffer_id {
5550 continue;
5551 }
5552 if let Some(ranges) =
5553 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5554 {
5555 for (buffer, entries) in ranges {
5556 linked_ranges.entry(buffer).or_default().extend(entries);
5557 }
5558 }
5559 }
5560 }
5561
5562 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5563 if !this.selections.line_mode {
5564 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5565 for selection in &mut selections {
5566 if selection.is_empty() {
5567 let old_head = selection.head();
5568 let mut new_head =
5569 movement::left(&display_map, old_head.to_display_point(&display_map))
5570 .to_point(&display_map);
5571 if let Some((buffer, line_buffer_range)) = display_map
5572 .buffer_snapshot
5573 .buffer_line_for_row(MultiBufferRow(old_head.row))
5574 {
5575 let indent_size =
5576 buffer.indent_size_for_line(line_buffer_range.start.row);
5577 let indent_len = match indent_size.kind {
5578 IndentKind::Space => {
5579 buffer.settings_at(line_buffer_range.start, cx).tab_size
5580 }
5581 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5582 };
5583 if old_head.column <= indent_size.len && old_head.column > 0 {
5584 let indent_len = indent_len.get();
5585 new_head = cmp::min(
5586 new_head,
5587 MultiBufferPoint::new(
5588 old_head.row,
5589 ((old_head.column - 1) / indent_len) * indent_len,
5590 ),
5591 );
5592 }
5593 }
5594
5595 selection.set_head(new_head, SelectionGoal::None);
5596 }
5597 }
5598 }
5599
5600 this.signature_help_state.set_backspace_pressed(true);
5601 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5602 this.insert("", cx);
5603 let empty_str: Arc<str> = Arc::from("");
5604 for (buffer, edits) in linked_ranges {
5605 let snapshot = buffer.read(cx).snapshot();
5606 use text::ToPoint as TP;
5607
5608 let edits = edits
5609 .into_iter()
5610 .map(|range| {
5611 let end_point = TP::to_point(&range.end, &snapshot);
5612 let mut start_point = TP::to_point(&range.start, &snapshot);
5613
5614 if end_point == start_point {
5615 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5616 .saturating_sub(1);
5617 start_point = TP::to_point(&offset, &snapshot);
5618 };
5619
5620 (start_point..end_point, empty_str.clone())
5621 })
5622 .sorted_by_key(|(range, _)| range.start)
5623 .collect::<Vec<_>>();
5624 buffer.update(cx, |this, cx| {
5625 this.edit(edits, None, cx);
5626 })
5627 }
5628 this.refresh_inline_completion(true, false, cx);
5629 linked_editing_ranges::refresh_linked_ranges(this, cx);
5630 });
5631 }
5632
5633 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5634 self.transact(cx, |this, cx| {
5635 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5636 let line_mode = s.line_mode;
5637 s.move_with(|map, selection| {
5638 if selection.is_empty() && !line_mode {
5639 let cursor = movement::right(map, selection.head());
5640 selection.end = cursor;
5641 selection.reversed = true;
5642 selection.goal = SelectionGoal::None;
5643 }
5644 })
5645 });
5646 this.insert("", cx);
5647 this.refresh_inline_completion(true, false, cx);
5648 });
5649 }
5650
5651 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5652 if self.move_to_prev_snippet_tabstop(cx) {
5653 return;
5654 }
5655
5656 self.outdent(&Outdent, cx);
5657 }
5658
5659 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5660 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5661 return;
5662 }
5663
5664 let mut selections = self.selections.all_adjusted(cx);
5665 let buffer = self.buffer.read(cx);
5666 let snapshot = buffer.snapshot(cx);
5667 let rows_iter = selections.iter().map(|s| s.head().row);
5668 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5669
5670 let mut edits = Vec::new();
5671 let mut prev_edited_row = 0;
5672 let mut row_delta = 0;
5673 for selection in &mut selections {
5674 if selection.start.row != prev_edited_row {
5675 row_delta = 0;
5676 }
5677 prev_edited_row = selection.end.row;
5678
5679 // If the selection is non-empty, then increase the indentation of the selected lines.
5680 if !selection.is_empty() {
5681 row_delta =
5682 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5683 continue;
5684 }
5685
5686 // If the selection is empty and the cursor is in the leading whitespace before the
5687 // suggested indentation, then auto-indent the line.
5688 let cursor = selection.head();
5689 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5690 if let Some(suggested_indent) =
5691 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5692 {
5693 if cursor.column < suggested_indent.len
5694 && cursor.column <= current_indent.len
5695 && current_indent.len <= suggested_indent.len
5696 {
5697 selection.start = Point::new(cursor.row, suggested_indent.len);
5698 selection.end = selection.start;
5699 if row_delta == 0 {
5700 edits.extend(Buffer::edit_for_indent_size_adjustment(
5701 cursor.row,
5702 current_indent,
5703 suggested_indent,
5704 ));
5705 row_delta = suggested_indent.len - current_indent.len;
5706 }
5707 continue;
5708 }
5709 }
5710
5711 // Otherwise, insert a hard or soft tab.
5712 let settings = buffer.settings_at(cursor, cx);
5713 let tab_size = if settings.hard_tabs {
5714 IndentSize::tab()
5715 } else {
5716 let tab_size = settings.tab_size.get();
5717 let char_column = snapshot
5718 .text_for_range(Point::new(cursor.row, 0)..cursor)
5719 .flat_map(str::chars)
5720 .count()
5721 + row_delta as usize;
5722 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5723 IndentSize::spaces(chars_to_next_tab_stop)
5724 };
5725 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5726 selection.end = selection.start;
5727 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5728 row_delta += tab_size.len;
5729 }
5730
5731 self.transact(cx, |this, cx| {
5732 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5733 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5734 this.refresh_inline_completion(true, false, cx);
5735 });
5736 }
5737
5738 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5739 if self.read_only(cx) {
5740 return;
5741 }
5742 let mut selections = self.selections.all::<Point>(cx);
5743 let mut prev_edited_row = 0;
5744 let mut row_delta = 0;
5745 let mut edits = Vec::new();
5746 let buffer = self.buffer.read(cx);
5747 let snapshot = buffer.snapshot(cx);
5748 for selection in &mut selections {
5749 if selection.start.row != prev_edited_row {
5750 row_delta = 0;
5751 }
5752 prev_edited_row = selection.end.row;
5753
5754 row_delta =
5755 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5756 }
5757
5758 self.transact(cx, |this, cx| {
5759 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5760 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5761 });
5762 }
5763
5764 fn indent_selection(
5765 buffer: &MultiBuffer,
5766 snapshot: &MultiBufferSnapshot,
5767 selection: &mut Selection<Point>,
5768 edits: &mut Vec<(Range<Point>, String)>,
5769 delta_for_start_row: u32,
5770 cx: &AppContext,
5771 ) -> u32 {
5772 let settings = buffer.settings_at(selection.start, cx);
5773 let tab_size = settings.tab_size.get();
5774 let indent_kind = if settings.hard_tabs {
5775 IndentKind::Tab
5776 } else {
5777 IndentKind::Space
5778 };
5779 let mut start_row = selection.start.row;
5780 let mut end_row = selection.end.row + 1;
5781
5782 // If a selection ends at the beginning of a line, don't indent
5783 // that last line.
5784 if selection.end.column == 0 && selection.end.row > selection.start.row {
5785 end_row -= 1;
5786 }
5787
5788 // Avoid re-indenting a row that has already been indented by a
5789 // previous selection, but still update this selection's column
5790 // to reflect that indentation.
5791 if delta_for_start_row > 0 {
5792 start_row += 1;
5793 selection.start.column += delta_for_start_row;
5794 if selection.end.row == selection.start.row {
5795 selection.end.column += delta_for_start_row;
5796 }
5797 }
5798
5799 let mut delta_for_end_row = 0;
5800 let has_multiple_rows = start_row + 1 != end_row;
5801 for row in start_row..end_row {
5802 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5803 let indent_delta = match (current_indent.kind, indent_kind) {
5804 (IndentKind::Space, IndentKind::Space) => {
5805 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5806 IndentSize::spaces(columns_to_next_tab_stop)
5807 }
5808 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5809 (_, IndentKind::Tab) => IndentSize::tab(),
5810 };
5811
5812 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5813 0
5814 } else {
5815 selection.start.column
5816 };
5817 let row_start = Point::new(row, start);
5818 edits.push((
5819 row_start..row_start,
5820 indent_delta.chars().collect::<String>(),
5821 ));
5822
5823 // Update this selection's endpoints to reflect the indentation.
5824 if row == selection.start.row {
5825 selection.start.column += indent_delta.len;
5826 }
5827 if row == selection.end.row {
5828 selection.end.column += indent_delta.len;
5829 delta_for_end_row = indent_delta.len;
5830 }
5831 }
5832
5833 if selection.start.row == selection.end.row {
5834 delta_for_start_row + delta_for_end_row
5835 } else {
5836 delta_for_end_row
5837 }
5838 }
5839
5840 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5841 if self.read_only(cx) {
5842 return;
5843 }
5844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5845 let selections = self.selections.all::<Point>(cx);
5846 let mut deletion_ranges = Vec::new();
5847 let mut last_outdent = None;
5848 {
5849 let buffer = self.buffer.read(cx);
5850 let snapshot = buffer.snapshot(cx);
5851 for selection in &selections {
5852 let settings = buffer.settings_at(selection.start, cx);
5853 let tab_size = settings.tab_size.get();
5854 let mut rows = selection.spanned_rows(false, &display_map);
5855
5856 // Avoid re-outdenting a row that has already been outdented by a
5857 // previous selection.
5858 if let Some(last_row) = last_outdent {
5859 if last_row == rows.start {
5860 rows.start = rows.start.next_row();
5861 }
5862 }
5863 let has_multiple_rows = rows.len() > 1;
5864 for row in rows.iter_rows() {
5865 let indent_size = snapshot.indent_size_for_line(row);
5866 if indent_size.len > 0 {
5867 let deletion_len = match indent_size.kind {
5868 IndentKind::Space => {
5869 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5870 if columns_to_prev_tab_stop == 0 {
5871 tab_size
5872 } else {
5873 columns_to_prev_tab_stop
5874 }
5875 }
5876 IndentKind::Tab => 1,
5877 };
5878 let start = if has_multiple_rows
5879 || deletion_len > selection.start.column
5880 || indent_size.len < selection.start.column
5881 {
5882 0
5883 } else {
5884 selection.start.column - deletion_len
5885 };
5886 deletion_ranges.push(
5887 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5888 );
5889 last_outdent = Some(row);
5890 }
5891 }
5892 }
5893 }
5894
5895 self.transact(cx, |this, cx| {
5896 this.buffer.update(cx, |buffer, cx| {
5897 let empty_str: Arc<str> = Arc::default();
5898 buffer.edit(
5899 deletion_ranges
5900 .into_iter()
5901 .map(|range| (range, empty_str.clone())),
5902 None,
5903 cx,
5904 );
5905 });
5906 let selections = this.selections.all::<usize>(cx);
5907 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5908 });
5909 }
5910
5911 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5912 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5913 let selections = self.selections.all::<Point>(cx);
5914
5915 let mut new_cursors = Vec::new();
5916 let mut edit_ranges = Vec::new();
5917 let mut selections = selections.iter().peekable();
5918 while let Some(selection) = selections.next() {
5919 let mut rows = selection.spanned_rows(false, &display_map);
5920 let goal_display_column = selection.head().to_display_point(&display_map).column();
5921
5922 // Accumulate contiguous regions of rows that we want to delete.
5923 while let Some(next_selection) = selections.peek() {
5924 let next_rows = next_selection.spanned_rows(false, &display_map);
5925 if next_rows.start <= rows.end {
5926 rows.end = next_rows.end;
5927 selections.next().unwrap();
5928 } else {
5929 break;
5930 }
5931 }
5932
5933 let buffer = &display_map.buffer_snapshot;
5934 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5935 let edit_end;
5936 let cursor_buffer_row;
5937 if buffer.max_point().row >= rows.end.0 {
5938 // If there's a line after the range, delete the \n from the end of the row range
5939 // and position the cursor on the next line.
5940 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5941 cursor_buffer_row = rows.end;
5942 } else {
5943 // If there isn't a line after the range, delete the \n from the line before the
5944 // start of the row range and position the cursor there.
5945 edit_start = edit_start.saturating_sub(1);
5946 edit_end = buffer.len();
5947 cursor_buffer_row = rows.start.previous_row();
5948 }
5949
5950 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5951 *cursor.column_mut() =
5952 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5953
5954 new_cursors.push((
5955 selection.id,
5956 buffer.anchor_after(cursor.to_point(&display_map)),
5957 ));
5958 edit_ranges.push(edit_start..edit_end);
5959 }
5960
5961 self.transact(cx, |this, cx| {
5962 let buffer = this.buffer.update(cx, |buffer, cx| {
5963 let empty_str: Arc<str> = Arc::default();
5964 buffer.edit(
5965 edit_ranges
5966 .into_iter()
5967 .map(|range| (range, empty_str.clone())),
5968 None,
5969 cx,
5970 );
5971 buffer.snapshot(cx)
5972 });
5973 let new_selections = new_cursors
5974 .into_iter()
5975 .map(|(id, cursor)| {
5976 let cursor = cursor.to_point(&buffer);
5977 Selection {
5978 id,
5979 start: cursor,
5980 end: cursor,
5981 reversed: false,
5982 goal: SelectionGoal::None,
5983 }
5984 })
5985 .collect();
5986
5987 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5988 s.select(new_selections);
5989 });
5990 });
5991 }
5992
5993 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5994 if self.read_only(cx) {
5995 return;
5996 }
5997 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5998 for selection in self.selections.all::<Point>(cx) {
5999 let start = MultiBufferRow(selection.start.row);
6000 let end = if selection.start.row == selection.end.row {
6001 MultiBufferRow(selection.start.row + 1)
6002 } else {
6003 MultiBufferRow(selection.end.row)
6004 };
6005
6006 if let Some(last_row_range) = row_ranges.last_mut() {
6007 if start <= last_row_range.end {
6008 last_row_range.end = end;
6009 continue;
6010 }
6011 }
6012 row_ranges.push(start..end);
6013 }
6014
6015 let snapshot = self.buffer.read(cx).snapshot(cx);
6016 let mut cursor_positions = Vec::new();
6017 for row_range in &row_ranges {
6018 let anchor = snapshot.anchor_before(Point::new(
6019 row_range.end.previous_row().0,
6020 snapshot.line_len(row_range.end.previous_row()),
6021 ));
6022 cursor_positions.push(anchor..anchor);
6023 }
6024
6025 self.transact(cx, |this, cx| {
6026 for row_range in row_ranges.into_iter().rev() {
6027 for row in row_range.iter_rows().rev() {
6028 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6029 let next_line_row = row.next_row();
6030 let indent = snapshot.indent_size_for_line(next_line_row);
6031 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6032
6033 let replace = if snapshot.line_len(next_line_row) > indent.len {
6034 " "
6035 } else {
6036 ""
6037 };
6038
6039 this.buffer.update(cx, |buffer, cx| {
6040 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6041 });
6042 }
6043 }
6044
6045 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6046 s.select_anchor_ranges(cursor_positions)
6047 });
6048 });
6049 }
6050
6051 pub fn sort_lines_case_sensitive(
6052 &mut self,
6053 _: &SortLinesCaseSensitive,
6054 cx: &mut ViewContext<Self>,
6055 ) {
6056 self.manipulate_lines(cx, |lines| lines.sort())
6057 }
6058
6059 pub fn sort_lines_case_insensitive(
6060 &mut self,
6061 _: &SortLinesCaseInsensitive,
6062 cx: &mut ViewContext<Self>,
6063 ) {
6064 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6065 }
6066
6067 pub fn unique_lines_case_insensitive(
6068 &mut self,
6069 _: &UniqueLinesCaseInsensitive,
6070 cx: &mut ViewContext<Self>,
6071 ) {
6072 self.manipulate_lines(cx, |lines| {
6073 let mut seen = HashSet::default();
6074 lines.retain(|line| seen.insert(line.to_lowercase()));
6075 })
6076 }
6077
6078 pub fn unique_lines_case_sensitive(
6079 &mut self,
6080 _: &UniqueLinesCaseSensitive,
6081 cx: &mut ViewContext<Self>,
6082 ) {
6083 self.manipulate_lines(cx, |lines| {
6084 let mut seen = HashSet::default();
6085 lines.retain(|line| seen.insert(*line));
6086 })
6087 }
6088
6089 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6090 let mut revert_changes = HashMap::default();
6091 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6092 for hunk in hunks_for_rows(
6093 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6094 &multi_buffer_snapshot,
6095 ) {
6096 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6097 }
6098 if !revert_changes.is_empty() {
6099 self.transact(cx, |editor, cx| {
6100 editor.revert(revert_changes, cx);
6101 });
6102 }
6103 }
6104
6105 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6106 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6107 if !revert_changes.is_empty() {
6108 self.transact(cx, |editor, cx| {
6109 editor.revert(revert_changes, cx);
6110 });
6111 }
6112 }
6113
6114 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6115 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6116 let project_path = buffer.read(cx).project_path(cx)?;
6117 let project = self.project.as_ref()?.read(cx);
6118 let entry = project.entry_for_path(&project_path, cx)?;
6119 let abs_path = project.absolute_path(&project_path, cx)?;
6120 let parent = if entry.is_symlink {
6121 abs_path.canonicalize().ok()?
6122 } else {
6123 abs_path
6124 }
6125 .parent()?
6126 .to_path_buf();
6127 Some(parent)
6128 }) {
6129 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6130 }
6131 }
6132
6133 fn gather_revert_changes(
6134 &mut self,
6135 selections: &[Selection<Anchor>],
6136 cx: &mut ViewContext<'_, Editor>,
6137 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6138 let mut revert_changes = HashMap::default();
6139 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6140 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6141 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6142 }
6143 revert_changes
6144 }
6145
6146 pub fn prepare_revert_change(
6147 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6148 multi_buffer: &Model<MultiBuffer>,
6149 hunk: &DiffHunk<MultiBufferRow>,
6150 cx: &AppContext,
6151 ) -> Option<()> {
6152 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6153 let buffer = buffer.read(cx);
6154 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6155 let buffer_snapshot = buffer.snapshot();
6156 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6157 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6158 probe
6159 .0
6160 .start
6161 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6162 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6163 }) {
6164 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6165 Some(())
6166 } else {
6167 None
6168 }
6169 }
6170
6171 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6172 self.manipulate_lines(cx, |lines| lines.reverse())
6173 }
6174
6175 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6176 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6177 }
6178
6179 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6180 where
6181 Fn: FnMut(&mut Vec<&str>),
6182 {
6183 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6184 let buffer = self.buffer.read(cx).snapshot(cx);
6185
6186 let mut edits = Vec::new();
6187
6188 let selections = self.selections.all::<Point>(cx);
6189 let mut selections = selections.iter().peekable();
6190 let mut contiguous_row_selections = Vec::new();
6191 let mut new_selections = Vec::new();
6192 let mut added_lines = 0;
6193 let mut removed_lines = 0;
6194
6195 while let Some(selection) = selections.next() {
6196 let (start_row, end_row) = consume_contiguous_rows(
6197 &mut contiguous_row_selections,
6198 selection,
6199 &display_map,
6200 &mut selections,
6201 );
6202
6203 let start_point = Point::new(start_row.0, 0);
6204 let end_point = Point::new(
6205 end_row.previous_row().0,
6206 buffer.line_len(end_row.previous_row()),
6207 );
6208 let text = buffer
6209 .text_for_range(start_point..end_point)
6210 .collect::<String>();
6211
6212 let mut lines = text.split('\n').collect_vec();
6213
6214 let lines_before = lines.len();
6215 callback(&mut lines);
6216 let lines_after = lines.len();
6217
6218 edits.push((start_point..end_point, lines.join("\n")));
6219
6220 // Selections must change based on added and removed line count
6221 let start_row =
6222 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6223 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6224 new_selections.push(Selection {
6225 id: selection.id,
6226 start: start_row,
6227 end: end_row,
6228 goal: SelectionGoal::None,
6229 reversed: selection.reversed,
6230 });
6231
6232 if lines_after > lines_before {
6233 added_lines += lines_after - lines_before;
6234 } else if lines_before > lines_after {
6235 removed_lines += lines_before - lines_after;
6236 }
6237 }
6238
6239 self.transact(cx, |this, cx| {
6240 let buffer = this.buffer.update(cx, |buffer, cx| {
6241 buffer.edit(edits, None, cx);
6242 buffer.snapshot(cx)
6243 });
6244
6245 // Recalculate offsets on newly edited buffer
6246 let new_selections = new_selections
6247 .iter()
6248 .map(|s| {
6249 let start_point = Point::new(s.start.0, 0);
6250 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6251 Selection {
6252 id: s.id,
6253 start: buffer.point_to_offset(start_point),
6254 end: buffer.point_to_offset(end_point),
6255 goal: s.goal,
6256 reversed: s.reversed,
6257 }
6258 })
6259 .collect();
6260
6261 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6262 s.select(new_selections);
6263 });
6264
6265 this.request_autoscroll(Autoscroll::fit(), cx);
6266 });
6267 }
6268
6269 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6270 self.manipulate_text(cx, |text| text.to_uppercase())
6271 }
6272
6273 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6274 self.manipulate_text(cx, |text| text.to_lowercase())
6275 }
6276
6277 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6278 self.manipulate_text(cx, |text| {
6279 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6280 // https://github.com/rutrum/convert-case/issues/16
6281 text.split('\n')
6282 .map(|line| line.to_case(Case::Title))
6283 .join("\n")
6284 })
6285 }
6286
6287 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6288 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6289 }
6290
6291 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6292 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6293 }
6294
6295 pub fn convert_to_upper_camel_case(
6296 &mut self,
6297 _: &ConvertToUpperCamelCase,
6298 cx: &mut ViewContext<Self>,
6299 ) {
6300 self.manipulate_text(cx, |text| {
6301 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6302 // https://github.com/rutrum/convert-case/issues/16
6303 text.split('\n')
6304 .map(|line| line.to_case(Case::UpperCamel))
6305 .join("\n")
6306 })
6307 }
6308
6309 pub fn convert_to_lower_camel_case(
6310 &mut self,
6311 _: &ConvertToLowerCamelCase,
6312 cx: &mut ViewContext<Self>,
6313 ) {
6314 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6315 }
6316
6317 pub fn convert_to_opposite_case(
6318 &mut self,
6319 _: &ConvertToOppositeCase,
6320 cx: &mut ViewContext<Self>,
6321 ) {
6322 self.manipulate_text(cx, |text| {
6323 text.chars()
6324 .fold(String::with_capacity(text.len()), |mut t, c| {
6325 if c.is_uppercase() {
6326 t.extend(c.to_lowercase());
6327 } else {
6328 t.extend(c.to_uppercase());
6329 }
6330 t
6331 })
6332 })
6333 }
6334
6335 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6336 where
6337 Fn: FnMut(&str) -> String,
6338 {
6339 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6340 let buffer = self.buffer.read(cx).snapshot(cx);
6341
6342 let mut new_selections = Vec::new();
6343 let mut edits = Vec::new();
6344 let mut selection_adjustment = 0i32;
6345
6346 for selection in self.selections.all::<usize>(cx) {
6347 let selection_is_empty = selection.is_empty();
6348
6349 let (start, end) = if selection_is_empty {
6350 let word_range = movement::surrounding_word(
6351 &display_map,
6352 selection.start.to_display_point(&display_map),
6353 );
6354 let start = word_range.start.to_offset(&display_map, Bias::Left);
6355 let end = word_range.end.to_offset(&display_map, Bias::Left);
6356 (start, end)
6357 } else {
6358 (selection.start, selection.end)
6359 };
6360
6361 let text = buffer.text_for_range(start..end).collect::<String>();
6362 let old_length = text.len() as i32;
6363 let text = callback(&text);
6364
6365 new_selections.push(Selection {
6366 start: (start as i32 - selection_adjustment) as usize,
6367 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6368 goal: SelectionGoal::None,
6369 ..selection
6370 });
6371
6372 selection_adjustment += old_length - text.len() as i32;
6373
6374 edits.push((start..end, text));
6375 }
6376
6377 self.transact(cx, |this, cx| {
6378 this.buffer.update(cx, |buffer, cx| {
6379 buffer.edit(edits, None, cx);
6380 });
6381
6382 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6383 s.select(new_selections);
6384 });
6385
6386 this.request_autoscroll(Autoscroll::fit(), cx);
6387 });
6388 }
6389
6390 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6391 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6392 let buffer = &display_map.buffer_snapshot;
6393 let selections = self.selections.all::<Point>(cx);
6394
6395 let mut edits = Vec::new();
6396 let mut selections_iter = selections.iter().peekable();
6397 while let Some(selection) = selections_iter.next() {
6398 // Avoid duplicating the same lines twice.
6399 let mut rows = selection.spanned_rows(false, &display_map);
6400
6401 while let Some(next_selection) = selections_iter.peek() {
6402 let next_rows = next_selection.spanned_rows(false, &display_map);
6403 if next_rows.start < rows.end {
6404 rows.end = next_rows.end;
6405 selections_iter.next().unwrap();
6406 } else {
6407 break;
6408 }
6409 }
6410
6411 // Copy the text from the selected row region and splice it either at the start
6412 // or end of the region.
6413 let start = Point::new(rows.start.0, 0);
6414 let end = Point::new(
6415 rows.end.previous_row().0,
6416 buffer.line_len(rows.end.previous_row()),
6417 );
6418 let text = buffer
6419 .text_for_range(start..end)
6420 .chain(Some("\n"))
6421 .collect::<String>();
6422 let insert_location = if upwards {
6423 Point::new(rows.end.0, 0)
6424 } else {
6425 start
6426 };
6427 edits.push((insert_location..insert_location, text));
6428 }
6429
6430 self.transact(cx, |this, cx| {
6431 this.buffer.update(cx, |buffer, cx| {
6432 buffer.edit(edits, None, cx);
6433 });
6434
6435 this.request_autoscroll(Autoscroll::fit(), cx);
6436 });
6437 }
6438
6439 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6440 self.duplicate_line(true, cx);
6441 }
6442
6443 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6444 self.duplicate_line(false, cx);
6445 }
6446
6447 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6448 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6449 let buffer = self.buffer.read(cx).snapshot(cx);
6450
6451 let mut edits = Vec::new();
6452 let mut unfold_ranges = Vec::new();
6453 let mut refold_ranges = Vec::new();
6454
6455 let selections = self.selections.all::<Point>(cx);
6456 let mut selections = selections.iter().peekable();
6457 let mut contiguous_row_selections = Vec::new();
6458 let mut new_selections = Vec::new();
6459
6460 while let Some(selection) = selections.next() {
6461 // Find all the selections that span a contiguous row range
6462 let (start_row, end_row) = consume_contiguous_rows(
6463 &mut contiguous_row_selections,
6464 selection,
6465 &display_map,
6466 &mut selections,
6467 );
6468
6469 // Move the text spanned by the row range to be before the line preceding the row range
6470 if start_row.0 > 0 {
6471 let range_to_move = Point::new(
6472 start_row.previous_row().0,
6473 buffer.line_len(start_row.previous_row()),
6474 )
6475 ..Point::new(
6476 end_row.previous_row().0,
6477 buffer.line_len(end_row.previous_row()),
6478 );
6479 let insertion_point = display_map
6480 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6481 .0;
6482
6483 // Don't move lines across excerpts
6484 if buffer
6485 .excerpt_boundaries_in_range((
6486 Bound::Excluded(insertion_point),
6487 Bound::Included(range_to_move.end),
6488 ))
6489 .next()
6490 .is_none()
6491 {
6492 let text = buffer
6493 .text_for_range(range_to_move.clone())
6494 .flat_map(|s| s.chars())
6495 .skip(1)
6496 .chain(['\n'])
6497 .collect::<String>();
6498
6499 edits.push((
6500 buffer.anchor_after(range_to_move.start)
6501 ..buffer.anchor_before(range_to_move.end),
6502 String::new(),
6503 ));
6504 let insertion_anchor = buffer.anchor_after(insertion_point);
6505 edits.push((insertion_anchor..insertion_anchor, text));
6506
6507 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6508
6509 // Move selections up
6510 new_selections.extend(contiguous_row_selections.drain(..).map(
6511 |mut selection| {
6512 selection.start.row -= row_delta;
6513 selection.end.row -= row_delta;
6514 selection
6515 },
6516 ));
6517
6518 // Move folds up
6519 unfold_ranges.push(range_to_move.clone());
6520 for fold in display_map.folds_in_range(
6521 buffer.anchor_before(range_to_move.start)
6522 ..buffer.anchor_after(range_to_move.end),
6523 ) {
6524 let mut start = fold.range.start.to_point(&buffer);
6525 let mut end = fold.range.end.to_point(&buffer);
6526 start.row -= row_delta;
6527 end.row -= row_delta;
6528 refold_ranges.push((start..end, fold.placeholder.clone()));
6529 }
6530 }
6531 }
6532
6533 // If we didn't move line(s), preserve the existing selections
6534 new_selections.append(&mut contiguous_row_selections);
6535 }
6536
6537 self.transact(cx, |this, cx| {
6538 this.unfold_ranges(unfold_ranges, true, true, cx);
6539 this.buffer.update(cx, |buffer, cx| {
6540 for (range, text) in edits {
6541 buffer.edit([(range, text)], None, cx);
6542 }
6543 });
6544 this.fold_ranges(refold_ranges, true, cx);
6545 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6546 s.select(new_selections);
6547 })
6548 });
6549 }
6550
6551 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6552 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6553 let buffer = self.buffer.read(cx).snapshot(cx);
6554
6555 let mut edits = Vec::new();
6556 let mut unfold_ranges = Vec::new();
6557 let mut refold_ranges = Vec::new();
6558
6559 let selections = self.selections.all::<Point>(cx);
6560 let mut selections = selections.iter().peekable();
6561 let mut contiguous_row_selections = Vec::new();
6562 let mut new_selections = Vec::new();
6563
6564 while let Some(selection) = selections.next() {
6565 // Find all the selections that span a contiguous row range
6566 let (start_row, end_row) = consume_contiguous_rows(
6567 &mut contiguous_row_selections,
6568 selection,
6569 &display_map,
6570 &mut selections,
6571 );
6572
6573 // Move the text spanned by the row range to be after the last line of the row range
6574 if end_row.0 <= buffer.max_point().row {
6575 let range_to_move =
6576 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6577 let insertion_point = display_map
6578 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6579 .0;
6580
6581 // Don't move lines across excerpt boundaries
6582 if buffer
6583 .excerpt_boundaries_in_range((
6584 Bound::Excluded(range_to_move.start),
6585 Bound::Included(insertion_point),
6586 ))
6587 .next()
6588 .is_none()
6589 {
6590 let mut text = String::from("\n");
6591 text.extend(buffer.text_for_range(range_to_move.clone()));
6592 text.pop(); // Drop trailing newline
6593 edits.push((
6594 buffer.anchor_after(range_to_move.start)
6595 ..buffer.anchor_before(range_to_move.end),
6596 String::new(),
6597 ));
6598 let insertion_anchor = buffer.anchor_after(insertion_point);
6599 edits.push((insertion_anchor..insertion_anchor, text));
6600
6601 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6602
6603 // Move selections down
6604 new_selections.extend(contiguous_row_selections.drain(..).map(
6605 |mut selection| {
6606 selection.start.row += row_delta;
6607 selection.end.row += row_delta;
6608 selection
6609 },
6610 ));
6611
6612 // Move folds down
6613 unfold_ranges.push(range_to_move.clone());
6614 for fold in display_map.folds_in_range(
6615 buffer.anchor_before(range_to_move.start)
6616 ..buffer.anchor_after(range_to_move.end),
6617 ) {
6618 let mut start = fold.range.start.to_point(&buffer);
6619 let mut end = fold.range.end.to_point(&buffer);
6620 start.row += row_delta;
6621 end.row += row_delta;
6622 refold_ranges.push((start..end, fold.placeholder.clone()));
6623 }
6624 }
6625 }
6626
6627 // If we didn't move line(s), preserve the existing selections
6628 new_selections.append(&mut contiguous_row_selections);
6629 }
6630
6631 self.transact(cx, |this, cx| {
6632 this.unfold_ranges(unfold_ranges, true, true, cx);
6633 this.buffer.update(cx, |buffer, cx| {
6634 for (range, text) in edits {
6635 buffer.edit([(range, text)], None, cx);
6636 }
6637 });
6638 this.fold_ranges(refold_ranges, true, cx);
6639 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6640 });
6641 }
6642
6643 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6644 let text_layout_details = &self.text_layout_details(cx);
6645 self.transact(cx, |this, cx| {
6646 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6647 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6648 let line_mode = s.line_mode;
6649 s.move_with(|display_map, selection| {
6650 if !selection.is_empty() || line_mode {
6651 return;
6652 }
6653
6654 let mut head = selection.head();
6655 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6656 if head.column() == display_map.line_len(head.row()) {
6657 transpose_offset = display_map
6658 .buffer_snapshot
6659 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6660 }
6661
6662 if transpose_offset == 0 {
6663 return;
6664 }
6665
6666 *head.column_mut() += 1;
6667 head = display_map.clip_point(head, Bias::Right);
6668 let goal = SelectionGoal::HorizontalPosition(
6669 display_map
6670 .x_for_display_point(head, text_layout_details)
6671 .into(),
6672 );
6673 selection.collapse_to(head, goal);
6674
6675 let transpose_start = display_map
6676 .buffer_snapshot
6677 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6678 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6679 let transpose_end = display_map
6680 .buffer_snapshot
6681 .clip_offset(transpose_offset + 1, Bias::Right);
6682 if let Some(ch) =
6683 display_map.buffer_snapshot.chars_at(transpose_start).next()
6684 {
6685 edits.push((transpose_start..transpose_offset, String::new()));
6686 edits.push((transpose_end..transpose_end, ch.to_string()));
6687 }
6688 }
6689 });
6690 edits
6691 });
6692 this.buffer
6693 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6694 let selections = this.selections.all::<usize>(cx);
6695 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6696 s.select(selections);
6697 });
6698 });
6699 }
6700
6701 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6702 let buffer = self.buffer.read(cx).snapshot(cx);
6703 let selections = self.selections.all::<Point>(cx);
6704 let mut selections = selections.iter().peekable();
6705
6706 let mut edits = Vec::new();
6707 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6708
6709 while let Some(selection) = selections.next() {
6710 let mut start_row = selection.start.row;
6711 let mut end_row = selection.end.row;
6712
6713 // Skip selections that overlap with a range that has already been rewrapped.
6714 let selection_range = start_row..end_row;
6715 if rewrapped_row_ranges
6716 .iter()
6717 .any(|range| range.overlaps(&selection_range))
6718 {
6719 continue;
6720 }
6721
6722 let mut should_rewrap = false;
6723
6724 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6725 match language_scope.language_name().0.as_ref() {
6726 "Markdown" | "Plain Text" => {
6727 should_rewrap = true;
6728 }
6729 _ => {}
6730 }
6731 }
6732
6733 let row = selection.head().row;
6734 let indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
6735 let indent_end = Point::new(row, indent_size.len);
6736
6737 let mut line_prefix = indent_size.chars().collect::<String>();
6738
6739 if let Some(comment_prefix) =
6740 buffer
6741 .language_scope_at(selection.head())
6742 .and_then(|language| {
6743 language
6744 .line_comment_prefixes()
6745 .iter()
6746 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6747 .cloned()
6748 })
6749 {
6750 line_prefix.push_str(&comment_prefix);
6751 should_rewrap = true;
6752 }
6753
6754 if selection.is_empty() {
6755 'expand_upwards: while start_row > 0 {
6756 let prev_row = start_row - 1;
6757 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6758 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6759 {
6760 start_row = prev_row;
6761 } else {
6762 break 'expand_upwards;
6763 }
6764 }
6765
6766 'expand_downwards: while end_row < buffer.max_point().row {
6767 let next_row = end_row + 1;
6768 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6769 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6770 {
6771 end_row = next_row;
6772 } else {
6773 break 'expand_downwards;
6774 }
6775 }
6776 }
6777
6778 if !should_rewrap {
6779 continue;
6780 }
6781
6782 let start = Point::new(start_row, 0);
6783 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6784 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6785 let unwrapped_text = selection_text
6786 .lines()
6787 .map(|line| line.strip_prefix(&line_prefix).unwrap())
6788 .join(" ");
6789 let wrap_column = buffer
6790 .settings_at(Point::new(start_row, 0), cx)
6791 .preferred_line_length as usize;
6792 let mut wrapped_text = String::new();
6793 let mut current_line = line_prefix.clone();
6794 for word in unwrapped_text.split_whitespace() {
6795 if current_line.len() + word.len() >= wrap_column {
6796 wrapped_text.push_str(¤t_line);
6797 wrapped_text.push('\n');
6798 current_line.truncate(line_prefix.len());
6799 }
6800
6801 if current_line.len() > line_prefix.len() {
6802 current_line.push(' ');
6803 }
6804
6805 current_line.push_str(word);
6806 }
6807
6808 if !current_line.is_empty() {
6809 wrapped_text.push_str(¤t_line);
6810 }
6811
6812 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6813 let mut offset = start.to_offset(&buffer);
6814 let mut moved_since_edit = true;
6815
6816 for change in diff.iter_all_changes() {
6817 let value = change.value();
6818 match change.tag() {
6819 ChangeTag::Equal => {
6820 offset += value.len();
6821 moved_since_edit = true;
6822 }
6823 ChangeTag::Delete => {
6824 let start = buffer.anchor_after(offset);
6825 let end = buffer.anchor_before(offset + value.len());
6826
6827 if moved_since_edit {
6828 edits.push((start..end, String::new()));
6829 } else {
6830 edits.last_mut().unwrap().0.end = end;
6831 }
6832
6833 offset += value.len();
6834 moved_since_edit = false;
6835 }
6836 ChangeTag::Insert => {
6837 if moved_since_edit {
6838 let anchor = buffer.anchor_after(offset);
6839 edits.push((anchor..anchor, value.to_string()));
6840 } else {
6841 edits.last_mut().unwrap().1.push_str(value);
6842 }
6843
6844 moved_since_edit = false;
6845 }
6846 }
6847 }
6848
6849 rewrapped_row_ranges.push(start_row..=end_row);
6850 }
6851
6852 self.buffer
6853 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6854 }
6855
6856 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6857 let mut text = String::new();
6858 let buffer = self.buffer.read(cx).snapshot(cx);
6859 let mut selections = self.selections.all::<Point>(cx);
6860 let mut clipboard_selections = Vec::with_capacity(selections.len());
6861 {
6862 let max_point = buffer.max_point();
6863 let mut is_first = true;
6864 for selection in &mut selections {
6865 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6866 if is_entire_line {
6867 selection.start = Point::new(selection.start.row, 0);
6868 if !selection.is_empty() && selection.end.column == 0 {
6869 selection.end = cmp::min(max_point, selection.end);
6870 } else {
6871 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6872 }
6873 selection.goal = SelectionGoal::None;
6874 }
6875 if is_first {
6876 is_first = false;
6877 } else {
6878 text += "\n";
6879 }
6880 let mut len = 0;
6881 for chunk in buffer.text_for_range(selection.start..selection.end) {
6882 text.push_str(chunk);
6883 len += chunk.len();
6884 }
6885 clipboard_selections.push(ClipboardSelection {
6886 len,
6887 is_entire_line,
6888 first_line_indent: buffer
6889 .indent_size_for_line(MultiBufferRow(selection.start.row))
6890 .len,
6891 });
6892 }
6893 }
6894
6895 self.transact(cx, |this, cx| {
6896 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6897 s.select(selections);
6898 });
6899 this.insert("", cx);
6900 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6901 text,
6902 clipboard_selections,
6903 ));
6904 });
6905 }
6906
6907 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6908 let selections = self.selections.all::<Point>(cx);
6909 let buffer = self.buffer.read(cx).read(cx);
6910 let mut text = String::new();
6911
6912 let mut clipboard_selections = Vec::with_capacity(selections.len());
6913 {
6914 let max_point = buffer.max_point();
6915 let mut is_first = true;
6916 for selection in selections.iter() {
6917 let mut start = selection.start;
6918 let mut end = selection.end;
6919 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6920 if is_entire_line {
6921 start = Point::new(start.row, 0);
6922 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6923 }
6924 if is_first {
6925 is_first = false;
6926 } else {
6927 text += "\n";
6928 }
6929 let mut len = 0;
6930 for chunk in buffer.text_for_range(start..end) {
6931 text.push_str(chunk);
6932 len += chunk.len();
6933 }
6934 clipboard_selections.push(ClipboardSelection {
6935 len,
6936 is_entire_line,
6937 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6938 });
6939 }
6940 }
6941
6942 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6943 text,
6944 clipboard_selections,
6945 ));
6946 }
6947
6948 pub fn do_paste(
6949 &mut self,
6950 text: &String,
6951 clipboard_selections: Option<Vec<ClipboardSelection>>,
6952 handle_entire_lines: bool,
6953 cx: &mut ViewContext<Self>,
6954 ) {
6955 if self.read_only(cx) {
6956 return;
6957 }
6958
6959 let clipboard_text = Cow::Borrowed(text);
6960
6961 self.transact(cx, |this, cx| {
6962 if let Some(mut clipboard_selections) = clipboard_selections {
6963 let old_selections = this.selections.all::<usize>(cx);
6964 let all_selections_were_entire_line =
6965 clipboard_selections.iter().all(|s| s.is_entire_line);
6966 let first_selection_indent_column =
6967 clipboard_selections.first().map(|s| s.first_line_indent);
6968 if clipboard_selections.len() != old_selections.len() {
6969 clipboard_selections.drain(..);
6970 }
6971
6972 this.buffer.update(cx, |buffer, cx| {
6973 let snapshot = buffer.read(cx);
6974 let mut start_offset = 0;
6975 let mut edits = Vec::new();
6976 let mut original_indent_columns = Vec::new();
6977 for (ix, selection) in old_selections.iter().enumerate() {
6978 let to_insert;
6979 let entire_line;
6980 let original_indent_column;
6981 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6982 let end_offset = start_offset + clipboard_selection.len;
6983 to_insert = &clipboard_text[start_offset..end_offset];
6984 entire_line = clipboard_selection.is_entire_line;
6985 start_offset = end_offset + 1;
6986 original_indent_column = Some(clipboard_selection.first_line_indent);
6987 } else {
6988 to_insert = clipboard_text.as_str();
6989 entire_line = all_selections_were_entire_line;
6990 original_indent_column = first_selection_indent_column
6991 }
6992
6993 // If the corresponding selection was empty when this slice of the
6994 // clipboard text was written, then the entire line containing the
6995 // selection was copied. If this selection is also currently empty,
6996 // then paste the line before the current line of the buffer.
6997 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6998 let column = selection.start.to_point(&snapshot).column as usize;
6999 let line_start = selection.start - column;
7000 line_start..line_start
7001 } else {
7002 selection.range()
7003 };
7004
7005 edits.push((range, to_insert));
7006 original_indent_columns.extend(original_indent_column);
7007 }
7008 drop(snapshot);
7009
7010 buffer.edit(
7011 edits,
7012 Some(AutoindentMode::Block {
7013 original_indent_columns,
7014 }),
7015 cx,
7016 );
7017 });
7018
7019 let selections = this.selections.all::<usize>(cx);
7020 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7021 } else {
7022 this.insert(&clipboard_text, cx);
7023 }
7024 });
7025 }
7026
7027 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7028 if let Some(item) = cx.read_from_clipboard() {
7029 let entries = item.entries();
7030
7031 match entries.first() {
7032 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7033 // of all the pasted entries.
7034 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7035 .do_paste(
7036 clipboard_string.text(),
7037 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7038 true,
7039 cx,
7040 ),
7041 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7042 }
7043 }
7044 }
7045
7046 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7047 if self.read_only(cx) {
7048 return;
7049 }
7050
7051 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7052 if let Some((selections, _)) =
7053 self.selection_history.transaction(transaction_id).cloned()
7054 {
7055 self.change_selections(None, cx, |s| {
7056 s.select_anchors(selections.to_vec());
7057 });
7058 }
7059 self.request_autoscroll(Autoscroll::fit(), cx);
7060 self.unmark_text(cx);
7061 self.refresh_inline_completion(true, false, cx);
7062 cx.emit(EditorEvent::Edited { transaction_id });
7063 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7064 }
7065 }
7066
7067 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7068 if self.read_only(cx) {
7069 return;
7070 }
7071
7072 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7073 if let Some((_, Some(selections))) =
7074 self.selection_history.transaction(transaction_id).cloned()
7075 {
7076 self.change_selections(None, cx, |s| {
7077 s.select_anchors(selections.to_vec());
7078 });
7079 }
7080 self.request_autoscroll(Autoscroll::fit(), cx);
7081 self.unmark_text(cx);
7082 self.refresh_inline_completion(true, false, cx);
7083 cx.emit(EditorEvent::Edited { transaction_id });
7084 }
7085 }
7086
7087 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7088 self.buffer
7089 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7090 }
7091
7092 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7093 self.buffer
7094 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7095 }
7096
7097 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7098 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7099 let line_mode = s.line_mode;
7100 s.move_with(|map, selection| {
7101 let cursor = if selection.is_empty() && !line_mode {
7102 movement::left(map, selection.start)
7103 } else {
7104 selection.start
7105 };
7106 selection.collapse_to(cursor, SelectionGoal::None);
7107 });
7108 })
7109 }
7110
7111 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7112 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7113 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7114 })
7115 }
7116
7117 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7118 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7119 let line_mode = s.line_mode;
7120 s.move_with(|map, selection| {
7121 let cursor = if selection.is_empty() && !line_mode {
7122 movement::right(map, selection.end)
7123 } else {
7124 selection.end
7125 };
7126 selection.collapse_to(cursor, SelectionGoal::None)
7127 });
7128 })
7129 }
7130
7131 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7132 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7133 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7134 })
7135 }
7136
7137 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7138 if self.take_rename(true, cx).is_some() {
7139 return;
7140 }
7141
7142 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7143 cx.propagate();
7144 return;
7145 }
7146
7147 let text_layout_details = &self.text_layout_details(cx);
7148 let selection_count = self.selections.count();
7149 let first_selection = self.selections.first_anchor();
7150
7151 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7152 let line_mode = s.line_mode;
7153 s.move_with(|map, selection| {
7154 if !selection.is_empty() && !line_mode {
7155 selection.goal = SelectionGoal::None;
7156 }
7157 let (cursor, goal) = movement::up(
7158 map,
7159 selection.start,
7160 selection.goal,
7161 false,
7162 text_layout_details,
7163 );
7164 selection.collapse_to(cursor, goal);
7165 });
7166 });
7167
7168 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7169 {
7170 cx.propagate();
7171 }
7172 }
7173
7174 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7175 if self.take_rename(true, cx).is_some() {
7176 return;
7177 }
7178
7179 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7180 cx.propagate();
7181 return;
7182 }
7183
7184 let text_layout_details = &self.text_layout_details(cx);
7185
7186 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7187 let line_mode = s.line_mode;
7188 s.move_with(|map, selection| {
7189 if !selection.is_empty() && !line_mode {
7190 selection.goal = SelectionGoal::None;
7191 }
7192 let (cursor, goal) = movement::up_by_rows(
7193 map,
7194 selection.start,
7195 action.lines,
7196 selection.goal,
7197 false,
7198 text_layout_details,
7199 );
7200 selection.collapse_to(cursor, goal);
7201 });
7202 })
7203 }
7204
7205 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7206 if self.take_rename(true, cx).is_some() {
7207 return;
7208 }
7209
7210 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7211 cx.propagate();
7212 return;
7213 }
7214
7215 let text_layout_details = &self.text_layout_details(cx);
7216
7217 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7218 let line_mode = s.line_mode;
7219 s.move_with(|map, selection| {
7220 if !selection.is_empty() && !line_mode {
7221 selection.goal = SelectionGoal::None;
7222 }
7223 let (cursor, goal) = movement::down_by_rows(
7224 map,
7225 selection.start,
7226 action.lines,
7227 selection.goal,
7228 false,
7229 text_layout_details,
7230 );
7231 selection.collapse_to(cursor, goal);
7232 });
7233 })
7234 }
7235
7236 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7237 let text_layout_details = &self.text_layout_details(cx);
7238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7239 s.move_heads_with(|map, head, goal| {
7240 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7241 })
7242 })
7243 }
7244
7245 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7246 let text_layout_details = &self.text_layout_details(cx);
7247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7248 s.move_heads_with(|map, head, goal| {
7249 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7250 })
7251 })
7252 }
7253
7254 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7255 let Some(row_count) = self.visible_row_count() else {
7256 return;
7257 };
7258
7259 let text_layout_details = &self.text_layout_details(cx);
7260
7261 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7262 s.move_heads_with(|map, head, goal| {
7263 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7264 })
7265 })
7266 }
7267
7268 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7269 if self.take_rename(true, cx).is_some() {
7270 return;
7271 }
7272
7273 if self
7274 .context_menu
7275 .write()
7276 .as_mut()
7277 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7278 .unwrap_or(false)
7279 {
7280 return;
7281 }
7282
7283 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7284 cx.propagate();
7285 return;
7286 }
7287
7288 let Some(row_count) = self.visible_row_count() else {
7289 return;
7290 };
7291
7292 let autoscroll = if action.center_cursor {
7293 Autoscroll::center()
7294 } else {
7295 Autoscroll::fit()
7296 };
7297
7298 let text_layout_details = &self.text_layout_details(cx);
7299
7300 self.change_selections(Some(autoscroll), cx, |s| {
7301 let line_mode = s.line_mode;
7302 s.move_with(|map, selection| {
7303 if !selection.is_empty() && !line_mode {
7304 selection.goal = SelectionGoal::None;
7305 }
7306 let (cursor, goal) = movement::up_by_rows(
7307 map,
7308 selection.end,
7309 row_count,
7310 selection.goal,
7311 false,
7312 text_layout_details,
7313 );
7314 selection.collapse_to(cursor, goal);
7315 });
7316 });
7317 }
7318
7319 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7320 let text_layout_details = &self.text_layout_details(cx);
7321 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7322 s.move_heads_with(|map, head, goal| {
7323 movement::up(map, head, goal, false, text_layout_details)
7324 })
7325 })
7326 }
7327
7328 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7329 self.take_rename(true, cx);
7330
7331 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7332 cx.propagate();
7333 return;
7334 }
7335
7336 let text_layout_details = &self.text_layout_details(cx);
7337 let selection_count = self.selections.count();
7338 let first_selection = self.selections.first_anchor();
7339
7340 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7341 let line_mode = s.line_mode;
7342 s.move_with(|map, selection| {
7343 if !selection.is_empty() && !line_mode {
7344 selection.goal = SelectionGoal::None;
7345 }
7346 let (cursor, goal) = movement::down(
7347 map,
7348 selection.end,
7349 selection.goal,
7350 false,
7351 text_layout_details,
7352 );
7353 selection.collapse_to(cursor, goal);
7354 });
7355 });
7356
7357 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7358 {
7359 cx.propagate();
7360 }
7361 }
7362
7363 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7364 let Some(row_count) = self.visible_row_count() else {
7365 return;
7366 };
7367
7368 let text_layout_details = &self.text_layout_details(cx);
7369
7370 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7371 s.move_heads_with(|map, head, goal| {
7372 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7373 })
7374 })
7375 }
7376
7377 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7378 if self.take_rename(true, cx).is_some() {
7379 return;
7380 }
7381
7382 if self
7383 .context_menu
7384 .write()
7385 .as_mut()
7386 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7387 .unwrap_or(false)
7388 {
7389 return;
7390 }
7391
7392 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7393 cx.propagate();
7394 return;
7395 }
7396
7397 let Some(row_count) = self.visible_row_count() else {
7398 return;
7399 };
7400
7401 let autoscroll = if action.center_cursor {
7402 Autoscroll::center()
7403 } else {
7404 Autoscroll::fit()
7405 };
7406
7407 let text_layout_details = &self.text_layout_details(cx);
7408 self.change_selections(Some(autoscroll), cx, |s| {
7409 let line_mode = s.line_mode;
7410 s.move_with(|map, selection| {
7411 if !selection.is_empty() && !line_mode {
7412 selection.goal = SelectionGoal::None;
7413 }
7414 let (cursor, goal) = movement::down_by_rows(
7415 map,
7416 selection.end,
7417 row_count,
7418 selection.goal,
7419 false,
7420 text_layout_details,
7421 );
7422 selection.collapse_to(cursor, goal);
7423 });
7424 });
7425 }
7426
7427 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7428 let text_layout_details = &self.text_layout_details(cx);
7429 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7430 s.move_heads_with(|map, head, goal| {
7431 movement::down(map, head, goal, false, text_layout_details)
7432 })
7433 });
7434 }
7435
7436 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7437 if let Some(context_menu) = self.context_menu.write().as_mut() {
7438 context_menu.select_first(self.project.as_ref(), cx);
7439 }
7440 }
7441
7442 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7443 if let Some(context_menu) = self.context_menu.write().as_mut() {
7444 context_menu.select_prev(self.project.as_ref(), cx);
7445 }
7446 }
7447
7448 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7449 if let Some(context_menu) = self.context_menu.write().as_mut() {
7450 context_menu.select_next(self.project.as_ref(), cx);
7451 }
7452 }
7453
7454 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7455 if let Some(context_menu) = self.context_menu.write().as_mut() {
7456 context_menu.select_last(self.project.as_ref(), cx);
7457 }
7458 }
7459
7460 pub fn move_to_previous_word_start(
7461 &mut self,
7462 _: &MoveToPreviousWordStart,
7463 cx: &mut ViewContext<Self>,
7464 ) {
7465 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7466 s.move_cursors_with(|map, head, _| {
7467 (
7468 movement::previous_word_start(map, head),
7469 SelectionGoal::None,
7470 )
7471 });
7472 })
7473 }
7474
7475 pub fn move_to_previous_subword_start(
7476 &mut self,
7477 _: &MoveToPreviousSubwordStart,
7478 cx: &mut ViewContext<Self>,
7479 ) {
7480 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7481 s.move_cursors_with(|map, head, _| {
7482 (
7483 movement::previous_subword_start(map, head),
7484 SelectionGoal::None,
7485 )
7486 });
7487 })
7488 }
7489
7490 pub fn select_to_previous_word_start(
7491 &mut self,
7492 _: &SelectToPreviousWordStart,
7493 cx: &mut ViewContext<Self>,
7494 ) {
7495 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7496 s.move_heads_with(|map, head, _| {
7497 (
7498 movement::previous_word_start(map, head),
7499 SelectionGoal::None,
7500 )
7501 });
7502 })
7503 }
7504
7505 pub fn select_to_previous_subword_start(
7506 &mut self,
7507 _: &SelectToPreviousSubwordStart,
7508 cx: &mut ViewContext<Self>,
7509 ) {
7510 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7511 s.move_heads_with(|map, head, _| {
7512 (
7513 movement::previous_subword_start(map, head),
7514 SelectionGoal::None,
7515 )
7516 });
7517 })
7518 }
7519
7520 pub fn delete_to_previous_word_start(
7521 &mut self,
7522 action: &DeleteToPreviousWordStart,
7523 cx: &mut ViewContext<Self>,
7524 ) {
7525 self.transact(cx, |this, cx| {
7526 this.select_autoclose_pair(cx);
7527 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7528 let line_mode = s.line_mode;
7529 s.move_with(|map, selection| {
7530 if selection.is_empty() && !line_mode {
7531 let cursor = if action.ignore_newlines {
7532 movement::previous_word_start(map, selection.head())
7533 } else {
7534 movement::previous_word_start_or_newline(map, selection.head())
7535 };
7536 selection.set_head(cursor, SelectionGoal::None);
7537 }
7538 });
7539 });
7540 this.insert("", cx);
7541 });
7542 }
7543
7544 pub fn delete_to_previous_subword_start(
7545 &mut self,
7546 _: &DeleteToPreviousSubwordStart,
7547 cx: &mut ViewContext<Self>,
7548 ) {
7549 self.transact(cx, |this, cx| {
7550 this.select_autoclose_pair(cx);
7551 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 let line_mode = s.line_mode;
7553 s.move_with(|map, selection| {
7554 if selection.is_empty() && !line_mode {
7555 let cursor = movement::previous_subword_start(map, selection.head());
7556 selection.set_head(cursor, SelectionGoal::None);
7557 }
7558 });
7559 });
7560 this.insert("", cx);
7561 });
7562 }
7563
7564 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7565 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7566 s.move_cursors_with(|map, head, _| {
7567 (movement::next_word_end(map, head), SelectionGoal::None)
7568 });
7569 })
7570 }
7571
7572 pub fn move_to_next_subword_end(
7573 &mut self,
7574 _: &MoveToNextSubwordEnd,
7575 cx: &mut ViewContext<Self>,
7576 ) {
7577 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7578 s.move_cursors_with(|map, head, _| {
7579 (movement::next_subword_end(map, head), SelectionGoal::None)
7580 });
7581 })
7582 }
7583
7584 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7585 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7586 s.move_heads_with(|map, head, _| {
7587 (movement::next_word_end(map, head), SelectionGoal::None)
7588 });
7589 })
7590 }
7591
7592 pub fn select_to_next_subword_end(
7593 &mut self,
7594 _: &SelectToNextSubwordEnd,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_heads_with(|map, head, _| {
7599 (movement::next_subword_end(map, head), SelectionGoal::None)
7600 });
7601 })
7602 }
7603
7604 pub fn delete_to_next_word_end(
7605 &mut self,
7606 action: &DeleteToNextWordEnd,
7607 cx: &mut ViewContext<Self>,
7608 ) {
7609 self.transact(cx, |this, cx| {
7610 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7611 let line_mode = s.line_mode;
7612 s.move_with(|map, selection| {
7613 if selection.is_empty() && !line_mode {
7614 let cursor = if action.ignore_newlines {
7615 movement::next_word_end(map, selection.head())
7616 } else {
7617 movement::next_word_end_or_newline(map, selection.head())
7618 };
7619 selection.set_head(cursor, SelectionGoal::None);
7620 }
7621 });
7622 });
7623 this.insert("", cx);
7624 });
7625 }
7626
7627 pub fn delete_to_next_subword_end(
7628 &mut self,
7629 _: &DeleteToNextSubwordEnd,
7630 cx: &mut ViewContext<Self>,
7631 ) {
7632 self.transact(cx, |this, cx| {
7633 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7634 s.move_with(|map, selection| {
7635 if selection.is_empty() {
7636 let cursor = movement::next_subword_end(map, selection.head());
7637 selection.set_head(cursor, SelectionGoal::None);
7638 }
7639 });
7640 });
7641 this.insert("", cx);
7642 });
7643 }
7644
7645 pub fn move_to_beginning_of_line(
7646 &mut self,
7647 action: &MoveToBeginningOfLine,
7648 cx: &mut ViewContext<Self>,
7649 ) {
7650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7651 s.move_cursors_with(|map, head, _| {
7652 (
7653 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7654 SelectionGoal::None,
7655 )
7656 });
7657 })
7658 }
7659
7660 pub fn select_to_beginning_of_line(
7661 &mut self,
7662 action: &SelectToBeginningOfLine,
7663 cx: &mut ViewContext<Self>,
7664 ) {
7665 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7666 s.move_heads_with(|map, head, _| {
7667 (
7668 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7669 SelectionGoal::None,
7670 )
7671 });
7672 });
7673 }
7674
7675 pub fn delete_to_beginning_of_line(
7676 &mut self,
7677 _: &DeleteToBeginningOfLine,
7678 cx: &mut ViewContext<Self>,
7679 ) {
7680 self.transact(cx, |this, cx| {
7681 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7682 s.move_with(|_, selection| {
7683 selection.reversed = true;
7684 });
7685 });
7686
7687 this.select_to_beginning_of_line(
7688 &SelectToBeginningOfLine {
7689 stop_at_soft_wraps: false,
7690 },
7691 cx,
7692 );
7693 this.backspace(&Backspace, cx);
7694 });
7695 }
7696
7697 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7699 s.move_cursors_with(|map, head, _| {
7700 (
7701 movement::line_end(map, head, action.stop_at_soft_wraps),
7702 SelectionGoal::None,
7703 )
7704 });
7705 })
7706 }
7707
7708 pub fn select_to_end_of_line(
7709 &mut self,
7710 action: &SelectToEndOfLine,
7711 cx: &mut ViewContext<Self>,
7712 ) {
7713 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7714 s.move_heads_with(|map, head, _| {
7715 (
7716 movement::line_end(map, head, action.stop_at_soft_wraps),
7717 SelectionGoal::None,
7718 )
7719 });
7720 })
7721 }
7722
7723 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7724 self.transact(cx, |this, cx| {
7725 this.select_to_end_of_line(
7726 &SelectToEndOfLine {
7727 stop_at_soft_wraps: false,
7728 },
7729 cx,
7730 );
7731 this.delete(&Delete, cx);
7732 });
7733 }
7734
7735 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7736 self.transact(cx, |this, cx| {
7737 this.select_to_end_of_line(
7738 &SelectToEndOfLine {
7739 stop_at_soft_wraps: false,
7740 },
7741 cx,
7742 );
7743 this.cut(&Cut, cx);
7744 });
7745 }
7746
7747 pub fn move_to_start_of_paragraph(
7748 &mut self,
7749 _: &MoveToStartOfParagraph,
7750 cx: &mut ViewContext<Self>,
7751 ) {
7752 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7753 cx.propagate();
7754 return;
7755 }
7756
7757 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7758 s.move_with(|map, selection| {
7759 selection.collapse_to(
7760 movement::start_of_paragraph(map, selection.head(), 1),
7761 SelectionGoal::None,
7762 )
7763 });
7764 })
7765 }
7766
7767 pub fn move_to_end_of_paragraph(
7768 &mut self,
7769 _: &MoveToEndOfParagraph,
7770 cx: &mut ViewContext<Self>,
7771 ) {
7772 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7773 cx.propagate();
7774 return;
7775 }
7776
7777 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7778 s.move_with(|map, selection| {
7779 selection.collapse_to(
7780 movement::end_of_paragraph(map, selection.head(), 1),
7781 SelectionGoal::None,
7782 )
7783 });
7784 })
7785 }
7786
7787 pub fn select_to_start_of_paragraph(
7788 &mut self,
7789 _: &SelectToStartOfParagraph,
7790 cx: &mut ViewContext<Self>,
7791 ) {
7792 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7793 cx.propagate();
7794 return;
7795 }
7796
7797 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7798 s.move_heads_with(|map, head, _| {
7799 (
7800 movement::start_of_paragraph(map, head, 1),
7801 SelectionGoal::None,
7802 )
7803 });
7804 })
7805 }
7806
7807 pub fn select_to_end_of_paragraph(
7808 &mut self,
7809 _: &SelectToEndOfParagraph,
7810 cx: &mut ViewContext<Self>,
7811 ) {
7812 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7813 cx.propagate();
7814 return;
7815 }
7816
7817 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7818 s.move_heads_with(|map, head, _| {
7819 (
7820 movement::end_of_paragraph(map, head, 1),
7821 SelectionGoal::None,
7822 )
7823 });
7824 })
7825 }
7826
7827 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7828 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7829 cx.propagate();
7830 return;
7831 }
7832
7833 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7834 s.select_ranges(vec![0..0]);
7835 });
7836 }
7837
7838 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7839 let mut selection = self.selections.last::<Point>(cx);
7840 selection.set_head(Point::zero(), SelectionGoal::None);
7841
7842 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7843 s.select(vec![selection]);
7844 });
7845 }
7846
7847 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7848 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7849 cx.propagate();
7850 return;
7851 }
7852
7853 let cursor = self.buffer.read(cx).read(cx).len();
7854 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7855 s.select_ranges(vec![cursor..cursor])
7856 });
7857 }
7858
7859 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7860 self.nav_history = nav_history;
7861 }
7862
7863 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7864 self.nav_history.as_ref()
7865 }
7866
7867 fn push_to_nav_history(
7868 &mut self,
7869 cursor_anchor: Anchor,
7870 new_position: Option<Point>,
7871 cx: &mut ViewContext<Self>,
7872 ) {
7873 if let Some(nav_history) = self.nav_history.as_mut() {
7874 let buffer = self.buffer.read(cx).read(cx);
7875 let cursor_position = cursor_anchor.to_point(&buffer);
7876 let scroll_state = self.scroll_manager.anchor();
7877 let scroll_top_row = scroll_state.top_row(&buffer);
7878 drop(buffer);
7879
7880 if let Some(new_position) = new_position {
7881 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7882 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7883 return;
7884 }
7885 }
7886
7887 nav_history.push(
7888 Some(NavigationData {
7889 cursor_anchor,
7890 cursor_position,
7891 scroll_anchor: scroll_state,
7892 scroll_top_row,
7893 }),
7894 cx,
7895 );
7896 }
7897 }
7898
7899 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7900 let buffer = self.buffer.read(cx).snapshot(cx);
7901 let mut selection = self.selections.first::<usize>(cx);
7902 selection.set_head(buffer.len(), SelectionGoal::None);
7903 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7904 s.select(vec![selection]);
7905 });
7906 }
7907
7908 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7909 let end = self.buffer.read(cx).read(cx).len();
7910 self.change_selections(None, cx, |s| {
7911 s.select_ranges(vec![0..end]);
7912 });
7913 }
7914
7915 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7916 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7917 let mut selections = self.selections.all::<Point>(cx);
7918 let max_point = display_map.buffer_snapshot.max_point();
7919 for selection in &mut selections {
7920 let rows = selection.spanned_rows(true, &display_map);
7921 selection.start = Point::new(rows.start.0, 0);
7922 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7923 selection.reversed = false;
7924 }
7925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7926 s.select(selections);
7927 });
7928 }
7929
7930 pub fn split_selection_into_lines(
7931 &mut self,
7932 _: &SplitSelectionIntoLines,
7933 cx: &mut ViewContext<Self>,
7934 ) {
7935 let mut to_unfold = Vec::new();
7936 let mut new_selection_ranges = Vec::new();
7937 {
7938 let selections = self.selections.all::<Point>(cx);
7939 let buffer = self.buffer.read(cx).read(cx);
7940 for selection in selections {
7941 for row in selection.start.row..selection.end.row {
7942 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7943 new_selection_ranges.push(cursor..cursor);
7944 }
7945 new_selection_ranges.push(selection.end..selection.end);
7946 to_unfold.push(selection.start..selection.end);
7947 }
7948 }
7949 self.unfold_ranges(to_unfold, true, true, cx);
7950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7951 s.select_ranges(new_selection_ranges);
7952 });
7953 }
7954
7955 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7956 self.add_selection(true, cx);
7957 }
7958
7959 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7960 self.add_selection(false, cx);
7961 }
7962
7963 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7965 let mut selections = self.selections.all::<Point>(cx);
7966 let text_layout_details = self.text_layout_details(cx);
7967 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7968 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7969 let range = oldest_selection.display_range(&display_map).sorted();
7970
7971 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7972 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7973 let positions = start_x.min(end_x)..start_x.max(end_x);
7974
7975 selections.clear();
7976 let mut stack = Vec::new();
7977 for row in range.start.row().0..=range.end.row().0 {
7978 if let Some(selection) = self.selections.build_columnar_selection(
7979 &display_map,
7980 DisplayRow(row),
7981 &positions,
7982 oldest_selection.reversed,
7983 &text_layout_details,
7984 ) {
7985 stack.push(selection.id);
7986 selections.push(selection);
7987 }
7988 }
7989
7990 if above {
7991 stack.reverse();
7992 }
7993
7994 AddSelectionsState { above, stack }
7995 });
7996
7997 let last_added_selection = *state.stack.last().unwrap();
7998 let mut new_selections = Vec::new();
7999 if above == state.above {
8000 let end_row = if above {
8001 DisplayRow(0)
8002 } else {
8003 display_map.max_point().row()
8004 };
8005
8006 'outer: for selection in selections {
8007 if selection.id == last_added_selection {
8008 let range = selection.display_range(&display_map).sorted();
8009 debug_assert_eq!(range.start.row(), range.end.row());
8010 let mut row = range.start.row();
8011 let positions =
8012 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8013 px(start)..px(end)
8014 } else {
8015 let start_x =
8016 display_map.x_for_display_point(range.start, &text_layout_details);
8017 let end_x =
8018 display_map.x_for_display_point(range.end, &text_layout_details);
8019 start_x.min(end_x)..start_x.max(end_x)
8020 };
8021
8022 while row != end_row {
8023 if above {
8024 row.0 -= 1;
8025 } else {
8026 row.0 += 1;
8027 }
8028
8029 if let Some(new_selection) = self.selections.build_columnar_selection(
8030 &display_map,
8031 row,
8032 &positions,
8033 selection.reversed,
8034 &text_layout_details,
8035 ) {
8036 state.stack.push(new_selection.id);
8037 if above {
8038 new_selections.push(new_selection);
8039 new_selections.push(selection);
8040 } else {
8041 new_selections.push(selection);
8042 new_selections.push(new_selection);
8043 }
8044
8045 continue 'outer;
8046 }
8047 }
8048 }
8049
8050 new_selections.push(selection);
8051 }
8052 } else {
8053 new_selections = selections;
8054 new_selections.retain(|s| s.id != last_added_selection);
8055 state.stack.pop();
8056 }
8057
8058 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8059 s.select(new_selections);
8060 });
8061 if state.stack.len() > 1 {
8062 self.add_selections_state = Some(state);
8063 }
8064 }
8065
8066 pub fn select_next_match_internal(
8067 &mut self,
8068 display_map: &DisplaySnapshot,
8069 replace_newest: bool,
8070 autoscroll: Option<Autoscroll>,
8071 cx: &mut ViewContext<Self>,
8072 ) -> Result<()> {
8073 fn select_next_match_ranges(
8074 this: &mut Editor,
8075 range: Range<usize>,
8076 replace_newest: bool,
8077 auto_scroll: Option<Autoscroll>,
8078 cx: &mut ViewContext<Editor>,
8079 ) {
8080 this.unfold_ranges([range.clone()], false, true, cx);
8081 this.change_selections(auto_scroll, cx, |s| {
8082 if replace_newest {
8083 s.delete(s.newest_anchor().id);
8084 }
8085 s.insert_range(range.clone());
8086 });
8087 }
8088
8089 let buffer = &display_map.buffer_snapshot;
8090 let mut selections = self.selections.all::<usize>(cx);
8091 if let Some(mut select_next_state) = self.select_next_state.take() {
8092 let query = &select_next_state.query;
8093 if !select_next_state.done {
8094 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8095 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8096 let mut next_selected_range = None;
8097
8098 let bytes_after_last_selection =
8099 buffer.bytes_in_range(last_selection.end..buffer.len());
8100 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8101 let query_matches = query
8102 .stream_find_iter(bytes_after_last_selection)
8103 .map(|result| (last_selection.end, result))
8104 .chain(
8105 query
8106 .stream_find_iter(bytes_before_first_selection)
8107 .map(|result| (0, result)),
8108 );
8109
8110 for (start_offset, query_match) in query_matches {
8111 let query_match = query_match.unwrap(); // can only fail due to I/O
8112 let offset_range =
8113 start_offset + query_match.start()..start_offset + query_match.end();
8114 let display_range = offset_range.start.to_display_point(display_map)
8115 ..offset_range.end.to_display_point(display_map);
8116
8117 if !select_next_state.wordwise
8118 || (!movement::is_inside_word(display_map, display_range.start)
8119 && !movement::is_inside_word(display_map, display_range.end))
8120 {
8121 // TODO: This is n^2, because we might check all the selections
8122 if !selections
8123 .iter()
8124 .any(|selection| selection.range().overlaps(&offset_range))
8125 {
8126 next_selected_range = Some(offset_range);
8127 break;
8128 }
8129 }
8130 }
8131
8132 if let Some(next_selected_range) = next_selected_range {
8133 select_next_match_ranges(
8134 self,
8135 next_selected_range,
8136 replace_newest,
8137 autoscroll,
8138 cx,
8139 );
8140 } else {
8141 select_next_state.done = true;
8142 }
8143 }
8144
8145 self.select_next_state = Some(select_next_state);
8146 } else {
8147 let mut only_carets = true;
8148 let mut same_text_selected = true;
8149 let mut selected_text = None;
8150
8151 let mut selections_iter = selections.iter().peekable();
8152 while let Some(selection) = selections_iter.next() {
8153 if selection.start != selection.end {
8154 only_carets = false;
8155 }
8156
8157 if same_text_selected {
8158 if selected_text.is_none() {
8159 selected_text =
8160 Some(buffer.text_for_range(selection.range()).collect::<String>());
8161 }
8162
8163 if let Some(next_selection) = selections_iter.peek() {
8164 if next_selection.range().len() == selection.range().len() {
8165 let next_selected_text = buffer
8166 .text_for_range(next_selection.range())
8167 .collect::<String>();
8168 if Some(next_selected_text) != selected_text {
8169 same_text_selected = false;
8170 selected_text = None;
8171 }
8172 } else {
8173 same_text_selected = false;
8174 selected_text = None;
8175 }
8176 }
8177 }
8178 }
8179
8180 if only_carets {
8181 for selection in &mut selections {
8182 let word_range = movement::surrounding_word(
8183 display_map,
8184 selection.start.to_display_point(display_map),
8185 );
8186 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8187 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8188 selection.goal = SelectionGoal::None;
8189 selection.reversed = false;
8190 select_next_match_ranges(
8191 self,
8192 selection.start..selection.end,
8193 replace_newest,
8194 autoscroll,
8195 cx,
8196 );
8197 }
8198
8199 if selections.len() == 1 {
8200 let selection = selections
8201 .last()
8202 .expect("ensured that there's only one selection");
8203 let query = buffer
8204 .text_for_range(selection.start..selection.end)
8205 .collect::<String>();
8206 let is_empty = query.is_empty();
8207 let select_state = SelectNextState {
8208 query: AhoCorasick::new(&[query])?,
8209 wordwise: true,
8210 done: is_empty,
8211 };
8212 self.select_next_state = Some(select_state);
8213 } else {
8214 self.select_next_state = None;
8215 }
8216 } else if let Some(selected_text) = selected_text {
8217 self.select_next_state = Some(SelectNextState {
8218 query: AhoCorasick::new(&[selected_text])?,
8219 wordwise: false,
8220 done: false,
8221 });
8222 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8223 }
8224 }
8225 Ok(())
8226 }
8227
8228 pub fn select_all_matches(
8229 &mut self,
8230 _action: &SelectAllMatches,
8231 cx: &mut ViewContext<Self>,
8232 ) -> Result<()> {
8233 self.push_to_selection_history();
8234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8235
8236 self.select_next_match_internal(&display_map, false, None, cx)?;
8237 let Some(select_next_state) = self.select_next_state.as_mut() else {
8238 return Ok(());
8239 };
8240 if select_next_state.done {
8241 return Ok(());
8242 }
8243
8244 let mut new_selections = self.selections.all::<usize>(cx);
8245
8246 let buffer = &display_map.buffer_snapshot;
8247 let query_matches = select_next_state
8248 .query
8249 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8250
8251 for query_match in query_matches {
8252 let query_match = query_match.unwrap(); // can only fail due to I/O
8253 let offset_range = query_match.start()..query_match.end();
8254 let display_range = offset_range.start.to_display_point(&display_map)
8255 ..offset_range.end.to_display_point(&display_map);
8256
8257 if !select_next_state.wordwise
8258 || (!movement::is_inside_word(&display_map, display_range.start)
8259 && !movement::is_inside_word(&display_map, display_range.end))
8260 {
8261 self.selections.change_with(cx, |selections| {
8262 new_selections.push(Selection {
8263 id: selections.new_selection_id(),
8264 start: offset_range.start,
8265 end: offset_range.end,
8266 reversed: false,
8267 goal: SelectionGoal::None,
8268 });
8269 });
8270 }
8271 }
8272
8273 new_selections.sort_by_key(|selection| selection.start);
8274 let mut ix = 0;
8275 while ix + 1 < new_selections.len() {
8276 let current_selection = &new_selections[ix];
8277 let next_selection = &new_selections[ix + 1];
8278 if current_selection.range().overlaps(&next_selection.range()) {
8279 if current_selection.id < next_selection.id {
8280 new_selections.remove(ix + 1);
8281 } else {
8282 new_selections.remove(ix);
8283 }
8284 } else {
8285 ix += 1;
8286 }
8287 }
8288
8289 select_next_state.done = true;
8290 self.unfold_ranges(
8291 new_selections.iter().map(|selection| selection.range()),
8292 false,
8293 false,
8294 cx,
8295 );
8296 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8297 selections.select(new_selections)
8298 });
8299
8300 Ok(())
8301 }
8302
8303 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8304 self.push_to_selection_history();
8305 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8306 self.select_next_match_internal(
8307 &display_map,
8308 action.replace_newest,
8309 Some(Autoscroll::newest()),
8310 cx,
8311 )?;
8312 Ok(())
8313 }
8314
8315 pub fn select_previous(
8316 &mut self,
8317 action: &SelectPrevious,
8318 cx: &mut ViewContext<Self>,
8319 ) -> Result<()> {
8320 self.push_to_selection_history();
8321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8322 let buffer = &display_map.buffer_snapshot;
8323 let mut selections = self.selections.all::<usize>(cx);
8324 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8325 let query = &select_prev_state.query;
8326 if !select_prev_state.done {
8327 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8328 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8329 let mut next_selected_range = None;
8330 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8331 let bytes_before_last_selection =
8332 buffer.reversed_bytes_in_range(0..last_selection.start);
8333 let bytes_after_first_selection =
8334 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8335 let query_matches = query
8336 .stream_find_iter(bytes_before_last_selection)
8337 .map(|result| (last_selection.start, result))
8338 .chain(
8339 query
8340 .stream_find_iter(bytes_after_first_selection)
8341 .map(|result| (buffer.len(), result)),
8342 );
8343 for (end_offset, query_match) in query_matches {
8344 let query_match = query_match.unwrap(); // can only fail due to I/O
8345 let offset_range =
8346 end_offset - query_match.end()..end_offset - query_match.start();
8347 let display_range = offset_range.start.to_display_point(&display_map)
8348 ..offset_range.end.to_display_point(&display_map);
8349
8350 if !select_prev_state.wordwise
8351 || (!movement::is_inside_word(&display_map, display_range.start)
8352 && !movement::is_inside_word(&display_map, display_range.end))
8353 {
8354 next_selected_range = Some(offset_range);
8355 break;
8356 }
8357 }
8358
8359 if let Some(next_selected_range) = next_selected_range {
8360 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8361 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8362 if action.replace_newest {
8363 s.delete(s.newest_anchor().id);
8364 }
8365 s.insert_range(next_selected_range);
8366 });
8367 } else {
8368 select_prev_state.done = true;
8369 }
8370 }
8371
8372 self.select_prev_state = Some(select_prev_state);
8373 } else {
8374 let mut only_carets = true;
8375 let mut same_text_selected = true;
8376 let mut selected_text = None;
8377
8378 let mut selections_iter = selections.iter().peekable();
8379 while let Some(selection) = selections_iter.next() {
8380 if selection.start != selection.end {
8381 only_carets = false;
8382 }
8383
8384 if same_text_selected {
8385 if selected_text.is_none() {
8386 selected_text =
8387 Some(buffer.text_for_range(selection.range()).collect::<String>());
8388 }
8389
8390 if let Some(next_selection) = selections_iter.peek() {
8391 if next_selection.range().len() == selection.range().len() {
8392 let next_selected_text = buffer
8393 .text_for_range(next_selection.range())
8394 .collect::<String>();
8395 if Some(next_selected_text) != selected_text {
8396 same_text_selected = false;
8397 selected_text = None;
8398 }
8399 } else {
8400 same_text_selected = false;
8401 selected_text = None;
8402 }
8403 }
8404 }
8405 }
8406
8407 if only_carets {
8408 for selection in &mut selections {
8409 let word_range = movement::surrounding_word(
8410 &display_map,
8411 selection.start.to_display_point(&display_map),
8412 );
8413 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8414 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8415 selection.goal = SelectionGoal::None;
8416 selection.reversed = false;
8417 }
8418 if selections.len() == 1 {
8419 let selection = selections
8420 .last()
8421 .expect("ensured that there's only one selection");
8422 let query = buffer
8423 .text_for_range(selection.start..selection.end)
8424 .collect::<String>();
8425 let is_empty = query.is_empty();
8426 let select_state = SelectNextState {
8427 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8428 wordwise: true,
8429 done: is_empty,
8430 };
8431 self.select_prev_state = Some(select_state);
8432 } else {
8433 self.select_prev_state = None;
8434 }
8435
8436 self.unfold_ranges(
8437 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8438 false,
8439 true,
8440 cx,
8441 );
8442 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8443 s.select(selections);
8444 });
8445 } else if let Some(selected_text) = selected_text {
8446 self.select_prev_state = Some(SelectNextState {
8447 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8448 wordwise: false,
8449 done: false,
8450 });
8451 self.select_previous(action, cx)?;
8452 }
8453 }
8454 Ok(())
8455 }
8456
8457 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8458 let text_layout_details = &self.text_layout_details(cx);
8459 self.transact(cx, |this, cx| {
8460 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8461 let mut edits = Vec::new();
8462 let mut selection_edit_ranges = Vec::new();
8463 let mut last_toggled_row = None;
8464 let snapshot = this.buffer.read(cx).read(cx);
8465 let empty_str: Arc<str> = Arc::default();
8466 let mut suffixes_inserted = Vec::new();
8467
8468 fn comment_prefix_range(
8469 snapshot: &MultiBufferSnapshot,
8470 row: MultiBufferRow,
8471 comment_prefix: &str,
8472 comment_prefix_whitespace: &str,
8473 ) -> Range<Point> {
8474 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8475
8476 let mut line_bytes = snapshot
8477 .bytes_in_range(start..snapshot.max_point())
8478 .flatten()
8479 .copied();
8480
8481 // If this line currently begins with the line comment prefix, then record
8482 // the range containing the prefix.
8483 if line_bytes
8484 .by_ref()
8485 .take(comment_prefix.len())
8486 .eq(comment_prefix.bytes())
8487 {
8488 // Include any whitespace that matches the comment prefix.
8489 let matching_whitespace_len = line_bytes
8490 .zip(comment_prefix_whitespace.bytes())
8491 .take_while(|(a, b)| a == b)
8492 .count() as u32;
8493 let end = Point::new(
8494 start.row,
8495 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8496 );
8497 start..end
8498 } else {
8499 start..start
8500 }
8501 }
8502
8503 fn comment_suffix_range(
8504 snapshot: &MultiBufferSnapshot,
8505 row: MultiBufferRow,
8506 comment_suffix: &str,
8507 comment_suffix_has_leading_space: bool,
8508 ) -> Range<Point> {
8509 let end = Point::new(row.0, snapshot.line_len(row));
8510 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8511
8512 let mut line_end_bytes = snapshot
8513 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8514 .flatten()
8515 .copied();
8516
8517 let leading_space_len = if suffix_start_column > 0
8518 && line_end_bytes.next() == Some(b' ')
8519 && comment_suffix_has_leading_space
8520 {
8521 1
8522 } else {
8523 0
8524 };
8525
8526 // If this line currently begins with the line comment prefix, then record
8527 // the range containing the prefix.
8528 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8529 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8530 start..end
8531 } else {
8532 end..end
8533 }
8534 }
8535
8536 // TODO: Handle selections that cross excerpts
8537 for selection in &mut selections {
8538 let start_column = snapshot
8539 .indent_size_for_line(MultiBufferRow(selection.start.row))
8540 .len;
8541 let language = if let Some(language) =
8542 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8543 {
8544 language
8545 } else {
8546 continue;
8547 };
8548
8549 selection_edit_ranges.clear();
8550
8551 // If multiple selections contain a given row, avoid processing that
8552 // row more than once.
8553 let mut start_row = MultiBufferRow(selection.start.row);
8554 if last_toggled_row == Some(start_row) {
8555 start_row = start_row.next_row();
8556 }
8557 let end_row =
8558 if selection.end.row > selection.start.row && selection.end.column == 0 {
8559 MultiBufferRow(selection.end.row - 1)
8560 } else {
8561 MultiBufferRow(selection.end.row)
8562 };
8563 last_toggled_row = Some(end_row);
8564
8565 if start_row > end_row {
8566 continue;
8567 }
8568
8569 // If the language has line comments, toggle those.
8570 let full_comment_prefixes = language.line_comment_prefixes();
8571 if !full_comment_prefixes.is_empty() {
8572 let first_prefix = full_comment_prefixes
8573 .first()
8574 .expect("prefixes is non-empty");
8575 let prefix_trimmed_lengths = full_comment_prefixes
8576 .iter()
8577 .map(|p| p.trim_end_matches(' ').len())
8578 .collect::<SmallVec<[usize; 4]>>();
8579
8580 let mut all_selection_lines_are_comments = true;
8581
8582 for row in start_row.0..=end_row.0 {
8583 let row = MultiBufferRow(row);
8584 if start_row < end_row && snapshot.is_line_blank(row) {
8585 continue;
8586 }
8587
8588 let prefix_range = full_comment_prefixes
8589 .iter()
8590 .zip(prefix_trimmed_lengths.iter().copied())
8591 .map(|(prefix, trimmed_prefix_len)| {
8592 comment_prefix_range(
8593 snapshot.deref(),
8594 row,
8595 &prefix[..trimmed_prefix_len],
8596 &prefix[trimmed_prefix_len..],
8597 )
8598 })
8599 .max_by_key(|range| range.end.column - range.start.column)
8600 .expect("prefixes is non-empty");
8601
8602 if prefix_range.is_empty() {
8603 all_selection_lines_are_comments = false;
8604 }
8605
8606 selection_edit_ranges.push(prefix_range);
8607 }
8608
8609 if all_selection_lines_are_comments {
8610 edits.extend(
8611 selection_edit_ranges
8612 .iter()
8613 .cloned()
8614 .map(|range| (range, empty_str.clone())),
8615 );
8616 } else {
8617 let min_column = selection_edit_ranges
8618 .iter()
8619 .map(|range| range.start.column)
8620 .min()
8621 .unwrap_or(0);
8622 edits.extend(selection_edit_ranges.iter().map(|range| {
8623 let position = Point::new(range.start.row, min_column);
8624 (position..position, first_prefix.clone())
8625 }));
8626 }
8627 } else if let Some((full_comment_prefix, comment_suffix)) =
8628 language.block_comment_delimiters()
8629 {
8630 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8631 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8632 let prefix_range = comment_prefix_range(
8633 snapshot.deref(),
8634 start_row,
8635 comment_prefix,
8636 comment_prefix_whitespace,
8637 );
8638 let suffix_range = comment_suffix_range(
8639 snapshot.deref(),
8640 end_row,
8641 comment_suffix.trim_start_matches(' '),
8642 comment_suffix.starts_with(' '),
8643 );
8644
8645 if prefix_range.is_empty() || suffix_range.is_empty() {
8646 edits.push((
8647 prefix_range.start..prefix_range.start,
8648 full_comment_prefix.clone(),
8649 ));
8650 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8651 suffixes_inserted.push((end_row, comment_suffix.len()));
8652 } else {
8653 edits.push((prefix_range, empty_str.clone()));
8654 edits.push((suffix_range, empty_str.clone()));
8655 }
8656 } else {
8657 continue;
8658 }
8659 }
8660
8661 drop(snapshot);
8662 this.buffer.update(cx, |buffer, cx| {
8663 buffer.edit(edits, None, cx);
8664 });
8665
8666 // Adjust selections so that they end before any comment suffixes that
8667 // were inserted.
8668 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8669 let mut selections = this.selections.all::<Point>(cx);
8670 let snapshot = this.buffer.read(cx).read(cx);
8671 for selection in &mut selections {
8672 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8673 match row.cmp(&MultiBufferRow(selection.end.row)) {
8674 Ordering::Less => {
8675 suffixes_inserted.next();
8676 continue;
8677 }
8678 Ordering::Greater => break,
8679 Ordering::Equal => {
8680 if selection.end.column == snapshot.line_len(row) {
8681 if selection.is_empty() {
8682 selection.start.column -= suffix_len as u32;
8683 }
8684 selection.end.column -= suffix_len as u32;
8685 }
8686 break;
8687 }
8688 }
8689 }
8690 }
8691
8692 drop(snapshot);
8693 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8694
8695 let selections = this.selections.all::<Point>(cx);
8696 let selections_on_single_row = selections.windows(2).all(|selections| {
8697 selections[0].start.row == selections[1].start.row
8698 && selections[0].end.row == selections[1].end.row
8699 && selections[0].start.row == selections[0].end.row
8700 });
8701 let selections_selecting = selections
8702 .iter()
8703 .any(|selection| selection.start != selection.end);
8704 let advance_downwards = action.advance_downwards
8705 && selections_on_single_row
8706 && !selections_selecting
8707 && !matches!(this.mode, EditorMode::SingleLine { .. });
8708
8709 if advance_downwards {
8710 let snapshot = this.buffer.read(cx).snapshot(cx);
8711
8712 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8713 s.move_cursors_with(|display_snapshot, display_point, _| {
8714 let mut point = display_point.to_point(display_snapshot);
8715 point.row += 1;
8716 point = snapshot.clip_point(point, Bias::Left);
8717 let display_point = point.to_display_point(display_snapshot);
8718 let goal = SelectionGoal::HorizontalPosition(
8719 display_snapshot
8720 .x_for_display_point(display_point, text_layout_details)
8721 .into(),
8722 );
8723 (display_point, goal)
8724 })
8725 });
8726 }
8727 });
8728 }
8729
8730 pub fn select_enclosing_symbol(
8731 &mut self,
8732 _: &SelectEnclosingSymbol,
8733 cx: &mut ViewContext<Self>,
8734 ) {
8735 let buffer = self.buffer.read(cx).snapshot(cx);
8736 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8737
8738 fn update_selection(
8739 selection: &Selection<usize>,
8740 buffer_snap: &MultiBufferSnapshot,
8741 ) -> Option<Selection<usize>> {
8742 let cursor = selection.head();
8743 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8744 for symbol in symbols.iter().rev() {
8745 let start = symbol.range.start.to_offset(buffer_snap);
8746 let end = symbol.range.end.to_offset(buffer_snap);
8747 let new_range = start..end;
8748 if start < selection.start || end > selection.end {
8749 return Some(Selection {
8750 id: selection.id,
8751 start: new_range.start,
8752 end: new_range.end,
8753 goal: SelectionGoal::None,
8754 reversed: selection.reversed,
8755 });
8756 }
8757 }
8758 None
8759 }
8760
8761 let mut selected_larger_symbol = false;
8762 let new_selections = old_selections
8763 .iter()
8764 .map(|selection| match update_selection(selection, &buffer) {
8765 Some(new_selection) => {
8766 if new_selection.range() != selection.range() {
8767 selected_larger_symbol = true;
8768 }
8769 new_selection
8770 }
8771 None => selection.clone(),
8772 })
8773 .collect::<Vec<_>>();
8774
8775 if selected_larger_symbol {
8776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8777 s.select(new_selections);
8778 });
8779 }
8780 }
8781
8782 pub fn select_larger_syntax_node(
8783 &mut self,
8784 _: &SelectLargerSyntaxNode,
8785 cx: &mut ViewContext<Self>,
8786 ) {
8787 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8788 let buffer = self.buffer.read(cx).snapshot(cx);
8789 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8790
8791 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8792 let mut selected_larger_node = false;
8793 let new_selections = old_selections
8794 .iter()
8795 .map(|selection| {
8796 let old_range = selection.start..selection.end;
8797 let mut new_range = old_range.clone();
8798 while let Some(containing_range) =
8799 buffer.range_for_syntax_ancestor(new_range.clone())
8800 {
8801 new_range = containing_range;
8802 if !display_map.intersects_fold(new_range.start)
8803 && !display_map.intersects_fold(new_range.end)
8804 {
8805 break;
8806 }
8807 }
8808
8809 selected_larger_node |= new_range != old_range;
8810 Selection {
8811 id: selection.id,
8812 start: new_range.start,
8813 end: new_range.end,
8814 goal: SelectionGoal::None,
8815 reversed: selection.reversed,
8816 }
8817 })
8818 .collect::<Vec<_>>();
8819
8820 if selected_larger_node {
8821 stack.push(old_selections);
8822 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8823 s.select(new_selections);
8824 });
8825 }
8826 self.select_larger_syntax_node_stack = stack;
8827 }
8828
8829 pub fn select_smaller_syntax_node(
8830 &mut self,
8831 _: &SelectSmallerSyntaxNode,
8832 cx: &mut ViewContext<Self>,
8833 ) {
8834 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8835 if let Some(selections) = stack.pop() {
8836 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8837 s.select(selections.to_vec());
8838 });
8839 }
8840 self.select_larger_syntax_node_stack = stack;
8841 }
8842
8843 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8844 if !EditorSettings::get_global(cx).gutter.runnables {
8845 self.clear_tasks();
8846 return Task::ready(());
8847 }
8848 let project = self.project.clone();
8849 cx.spawn(|this, mut cx| async move {
8850 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8851 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8852 }) else {
8853 return;
8854 };
8855
8856 let Some(project) = project else {
8857 return;
8858 };
8859
8860 let hide_runnables = project
8861 .update(&mut cx, |project, cx| {
8862 // Do not display any test indicators in non-dev server remote projects.
8863 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8864 })
8865 .unwrap_or(true);
8866 if hide_runnables {
8867 return;
8868 }
8869 let new_rows =
8870 cx.background_executor()
8871 .spawn({
8872 let snapshot = display_snapshot.clone();
8873 async move {
8874 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8875 }
8876 })
8877 .await;
8878 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8879
8880 this.update(&mut cx, |this, _| {
8881 this.clear_tasks();
8882 for (key, value) in rows {
8883 this.insert_tasks(key, value);
8884 }
8885 })
8886 .ok();
8887 })
8888 }
8889 fn fetch_runnable_ranges(
8890 snapshot: &DisplaySnapshot,
8891 range: Range<Anchor>,
8892 ) -> Vec<language::RunnableRange> {
8893 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8894 }
8895
8896 fn runnable_rows(
8897 project: Model<Project>,
8898 snapshot: DisplaySnapshot,
8899 runnable_ranges: Vec<RunnableRange>,
8900 mut cx: AsyncWindowContext,
8901 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8902 runnable_ranges
8903 .into_iter()
8904 .filter_map(|mut runnable| {
8905 let tasks = cx
8906 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8907 .ok()?;
8908 if tasks.is_empty() {
8909 return None;
8910 }
8911
8912 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8913
8914 let row = snapshot
8915 .buffer_snapshot
8916 .buffer_line_for_row(MultiBufferRow(point.row))?
8917 .1
8918 .start
8919 .row;
8920
8921 let context_range =
8922 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8923 Some((
8924 (runnable.buffer_id, row),
8925 RunnableTasks {
8926 templates: tasks,
8927 offset: MultiBufferOffset(runnable.run_range.start),
8928 context_range,
8929 column: point.column,
8930 extra_variables: runnable.extra_captures,
8931 },
8932 ))
8933 })
8934 .collect()
8935 }
8936
8937 fn templates_with_tags(
8938 project: &Model<Project>,
8939 runnable: &mut Runnable,
8940 cx: &WindowContext<'_>,
8941 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8942 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8943 let (worktree_id, file) = project
8944 .buffer_for_id(runnable.buffer, cx)
8945 .and_then(|buffer| buffer.read(cx).file())
8946 .map(|file| (file.worktree_id(cx), file.clone()))
8947 .unzip();
8948
8949 (project.task_inventory().clone(), worktree_id, file)
8950 });
8951
8952 let inventory = inventory.read(cx);
8953 let tags = mem::take(&mut runnable.tags);
8954 let mut tags: Vec<_> = tags
8955 .into_iter()
8956 .flat_map(|tag| {
8957 let tag = tag.0.clone();
8958 inventory
8959 .list_tasks(
8960 file.clone(),
8961 Some(runnable.language.clone()),
8962 worktree_id,
8963 cx,
8964 )
8965 .into_iter()
8966 .filter(move |(_, template)| {
8967 template.tags.iter().any(|source_tag| source_tag == &tag)
8968 })
8969 })
8970 .sorted_by_key(|(kind, _)| kind.to_owned())
8971 .collect();
8972 if let Some((leading_tag_source, _)) = tags.first() {
8973 // Strongest source wins; if we have worktree tag binding, prefer that to
8974 // global and language bindings;
8975 // if we have a global binding, prefer that to language binding.
8976 let first_mismatch = tags
8977 .iter()
8978 .position(|(tag_source, _)| tag_source != leading_tag_source);
8979 if let Some(index) = first_mismatch {
8980 tags.truncate(index);
8981 }
8982 }
8983
8984 tags
8985 }
8986
8987 pub fn move_to_enclosing_bracket(
8988 &mut self,
8989 _: &MoveToEnclosingBracket,
8990 cx: &mut ViewContext<Self>,
8991 ) {
8992 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8993 s.move_offsets_with(|snapshot, selection| {
8994 let Some(enclosing_bracket_ranges) =
8995 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8996 else {
8997 return;
8998 };
8999
9000 let mut best_length = usize::MAX;
9001 let mut best_inside = false;
9002 let mut best_in_bracket_range = false;
9003 let mut best_destination = None;
9004 for (open, close) in enclosing_bracket_ranges {
9005 let close = close.to_inclusive();
9006 let length = close.end() - open.start;
9007 let inside = selection.start >= open.end && selection.end <= *close.start();
9008 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9009 || close.contains(&selection.head());
9010
9011 // If best is next to a bracket and current isn't, skip
9012 if !in_bracket_range && best_in_bracket_range {
9013 continue;
9014 }
9015
9016 // Prefer smaller lengths unless best is inside and current isn't
9017 if length > best_length && (best_inside || !inside) {
9018 continue;
9019 }
9020
9021 best_length = length;
9022 best_inside = inside;
9023 best_in_bracket_range = in_bracket_range;
9024 best_destination = Some(
9025 if close.contains(&selection.start) && close.contains(&selection.end) {
9026 if inside {
9027 open.end
9028 } else {
9029 open.start
9030 }
9031 } else if inside {
9032 *close.start()
9033 } else {
9034 *close.end()
9035 },
9036 );
9037 }
9038
9039 if let Some(destination) = best_destination {
9040 selection.collapse_to(destination, SelectionGoal::None);
9041 }
9042 })
9043 });
9044 }
9045
9046 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9047 self.end_selection(cx);
9048 self.selection_history.mode = SelectionHistoryMode::Undoing;
9049 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9050 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9051 self.select_next_state = entry.select_next_state;
9052 self.select_prev_state = entry.select_prev_state;
9053 self.add_selections_state = entry.add_selections_state;
9054 self.request_autoscroll(Autoscroll::newest(), cx);
9055 }
9056 self.selection_history.mode = SelectionHistoryMode::Normal;
9057 }
9058
9059 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9060 self.end_selection(cx);
9061 self.selection_history.mode = SelectionHistoryMode::Redoing;
9062 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9063 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9064 self.select_next_state = entry.select_next_state;
9065 self.select_prev_state = entry.select_prev_state;
9066 self.add_selections_state = entry.add_selections_state;
9067 self.request_autoscroll(Autoscroll::newest(), cx);
9068 }
9069 self.selection_history.mode = SelectionHistoryMode::Normal;
9070 }
9071
9072 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9073 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9074 }
9075
9076 pub fn expand_excerpts_down(
9077 &mut self,
9078 action: &ExpandExcerptsDown,
9079 cx: &mut ViewContext<Self>,
9080 ) {
9081 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9082 }
9083
9084 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9085 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9086 }
9087
9088 pub fn expand_excerpts_for_direction(
9089 &mut self,
9090 lines: u32,
9091 direction: ExpandExcerptDirection,
9092 cx: &mut ViewContext<Self>,
9093 ) {
9094 let selections = self.selections.disjoint_anchors();
9095
9096 let lines = if lines == 0 {
9097 EditorSettings::get_global(cx).expand_excerpt_lines
9098 } else {
9099 lines
9100 };
9101
9102 self.buffer.update(cx, |buffer, cx| {
9103 buffer.expand_excerpts(
9104 selections
9105 .iter()
9106 .map(|selection| selection.head().excerpt_id)
9107 .dedup(),
9108 lines,
9109 direction,
9110 cx,
9111 )
9112 })
9113 }
9114
9115 pub fn expand_excerpt(
9116 &mut self,
9117 excerpt: ExcerptId,
9118 direction: ExpandExcerptDirection,
9119 cx: &mut ViewContext<Self>,
9120 ) {
9121 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9122 self.buffer.update(cx, |buffer, cx| {
9123 buffer.expand_excerpts([excerpt], lines, direction, cx)
9124 })
9125 }
9126
9127 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9128 self.go_to_diagnostic_impl(Direction::Next, cx)
9129 }
9130
9131 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9132 self.go_to_diagnostic_impl(Direction::Prev, cx)
9133 }
9134
9135 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9136 let buffer = self.buffer.read(cx).snapshot(cx);
9137 let selection = self.selections.newest::<usize>(cx);
9138
9139 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9140 if direction == Direction::Next {
9141 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9142 let (group_id, jump_to) = popover.activation_info();
9143 if self.activate_diagnostics(group_id, cx) {
9144 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9145 let mut new_selection = s.newest_anchor().clone();
9146 new_selection.collapse_to(jump_to, SelectionGoal::None);
9147 s.select_anchors(vec![new_selection.clone()]);
9148 });
9149 }
9150 return;
9151 }
9152 }
9153
9154 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9155 active_diagnostics
9156 .primary_range
9157 .to_offset(&buffer)
9158 .to_inclusive()
9159 });
9160 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9161 if active_primary_range.contains(&selection.head()) {
9162 *active_primary_range.start()
9163 } else {
9164 selection.head()
9165 }
9166 } else {
9167 selection.head()
9168 };
9169 let snapshot = self.snapshot(cx);
9170 loop {
9171 let diagnostics = if direction == Direction::Prev {
9172 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9173 } else {
9174 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9175 }
9176 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9177 let group = diagnostics
9178 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9179 // be sorted in a stable way
9180 // skip until we are at current active diagnostic, if it exists
9181 .skip_while(|entry| {
9182 (match direction {
9183 Direction::Prev => entry.range.start >= search_start,
9184 Direction::Next => entry.range.start <= search_start,
9185 }) && self
9186 .active_diagnostics
9187 .as_ref()
9188 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9189 })
9190 .find_map(|entry| {
9191 if entry.diagnostic.is_primary
9192 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9193 && !entry.range.is_empty()
9194 // if we match with the active diagnostic, skip it
9195 && Some(entry.diagnostic.group_id)
9196 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9197 {
9198 Some((entry.range, entry.diagnostic.group_id))
9199 } else {
9200 None
9201 }
9202 });
9203
9204 if let Some((primary_range, group_id)) = group {
9205 if self.activate_diagnostics(group_id, cx) {
9206 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9207 s.select(vec![Selection {
9208 id: selection.id,
9209 start: primary_range.start,
9210 end: primary_range.start,
9211 reversed: false,
9212 goal: SelectionGoal::None,
9213 }]);
9214 });
9215 }
9216 break;
9217 } else {
9218 // Cycle around to the start of the buffer, potentially moving back to the start of
9219 // the currently active diagnostic.
9220 active_primary_range.take();
9221 if direction == Direction::Prev {
9222 if search_start == buffer.len() {
9223 break;
9224 } else {
9225 search_start = buffer.len();
9226 }
9227 } else if search_start == 0 {
9228 break;
9229 } else {
9230 search_start = 0;
9231 }
9232 }
9233 }
9234 }
9235
9236 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9237 let snapshot = self
9238 .display_map
9239 .update(cx, |display_map, cx| display_map.snapshot(cx));
9240 let selection = self.selections.newest::<Point>(cx);
9241
9242 if !self.seek_in_direction(
9243 &snapshot,
9244 selection.head(),
9245 false,
9246 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9247 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9248 ),
9249 cx,
9250 ) {
9251 let wrapped_point = Point::zero();
9252 self.seek_in_direction(
9253 &snapshot,
9254 wrapped_point,
9255 true,
9256 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9257 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9258 ),
9259 cx,
9260 );
9261 }
9262 }
9263
9264 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9265 let snapshot = self
9266 .display_map
9267 .update(cx, |display_map, cx| display_map.snapshot(cx));
9268 let selection = self.selections.newest::<Point>(cx);
9269
9270 if !self.seek_in_direction(
9271 &snapshot,
9272 selection.head(),
9273 false,
9274 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9275 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9276 ),
9277 cx,
9278 ) {
9279 let wrapped_point = snapshot.buffer_snapshot.max_point();
9280 self.seek_in_direction(
9281 &snapshot,
9282 wrapped_point,
9283 true,
9284 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9285 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9286 ),
9287 cx,
9288 );
9289 }
9290 }
9291
9292 fn seek_in_direction(
9293 &mut self,
9294 snapshot: &DisplaySnapshot,
9295 initial_point: Point,
9296 is_wrapped: bool,
9297 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9298 cx: &mut ViewContext<Editor>,
9299 ) -> bool {
9300 let display_point = initial_point.to_display_point(snapshot);
9301 let mut hunks = hunks
9302 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9303 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9304 .dedup();
9305
9306 if let Some(hunk) = hunks.next() {
9307 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9308 let row = hunk.start_display_row();
9309 let point = DisplayPoint::new(row, 0);
9310 s.select_display_ranges([point..point]);
9311 });
9312
9313 true
9314 } else {
9315 false
9316 }
9317 }
9318
9319 pub fn go_to_definition(
9320 &mut self,
9321 _: &GoToDefinition,
9322 cx: &mut ViewContext<Self>,
9323 ) -> Task<Result<Navigated>> {
9324 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9325 cx.spawn(|editor, mut cx| async move {
9326 if definition.await? == Navigated::Yes {
9327 return Ok(Navigated::Yes);
9328 }
9329 match editor.update(&mut cx, |editor, cx| {
9330 editor.find_all_references(&FindAllReferences, cx)
9331 })? {
9332 Some(references) => references.await,
9333 None => Ok(Navigated::No),
9334 }
9335 })
9336 }
9337
9338 pub fn go_to_declaration(
9339 &mut self,
9340 _: &GoToDeclaration,
9341 cx: &mut ViewContext<Self>,
9342 ) -> Task<Result<Navigated>> {
9343 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9344 }
9345
9346 pub fn go_to_declaration_split(
9347 &mut self,
9348 _: &GoToDeclaration,
9349 cx: &mut ViewContext<Self>,
9350 ) -> Task<Result<Navigated>> {
9351 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9352 }
9353
9354 pub fn go_to_implementation(
9355 &mut self,
9356 _: &GoToImplementation,
9357 cx: &mut ViewContext<Self>,
9358 ) -> Task<Result<Navigated>> {
9359 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9360 }
9361
9362 pub fn go_to_implementation_split(
9363 &mut self,
9364 _: &GoToImplementationSplit,
9365 cx: &mut ViewContext<Self>,
9366 ) -> Task<Result<Navigated>> {
9367 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9368 }
9369
9370 pub fn go_to_type_definition(
9371 &mut self,
9372 _: &GoToTypeDefinition,
9373 cx: &mut ViewContext<Self>,
9374 ) -> Task<Result<Navigated>> {
9375 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9376 }
9377
9378 pub fn go_to_definition_split(
9379 &mut self,
9380 _: &GoToDefinitionSplit,
9381 cx: &mut ViewContext<Self>,
9382 ) -> Task<Result<Navigated>> {
9383 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9384 }
9385
9386 pub fn go_to_type_definition_split(
9387 &mut self,
9388 _: &GoToTypeDefinitionSplit,
9389 cx: &mut ViewContext<Self>,
9390 ) -> Task<Result<Navigated>> {
9391 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9392 }
9393
9394 fn go_to_definition_of_kind(
9395 &mut self,
9396 kind: GotoDefinitionKind,
9397 split: bool,
9398 cx: &mut ViewContext<Self>,
9399 ) -> Task<Result<Navigated>> {
9400 let Some(workspace) = self.workspace() else {
9401 return Task::ready(Ok(Navigated::No));
9402 };
9403 let buffer = self.buffer.read(cx);
9404 let head = self.selections.newest::<usize>(cx).head();
9405 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9406 text_anchor
9407 } else {
9408 return Task::ready(Ok(Navigated::No));
9409 };
9410
9411 let project = workspace.read(cx).project().clone();
9412 let definitions = project.update(cx, |project, cx| match kind {
9413 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9414 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9415 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9416 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9417 });
9418
9419 cx.spawn(|editor, mut cx| async move {
9420 let definitions = definitions.await?;
9421 let navigated = editor
9422 .update(&mut cx, |editor, cx| {
9423 editor.navigate_to_hover_links(
9424 Some(kind),
9425 definitions
9426 .into_iter()
9427 .filter(|location| {
9428 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9429 })
9430 .map(HoverLink::Text)
9431 .collect::<Vec<_>>(),
9432 split,
9433 cx,
9434 )
9435 })?
9436 .await?;
9437 anyhow::Ok(navigated)
9438 })
9439 }
9440
9441 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9442 let position = self.selections.newest_anchor().head();
9443 let Some((buffer, buffer_position)) =
9444 self.buffer.read(cx).text_anchor_for_position(position, cx)
9445 else {
9446 return;
9447 };
9448
9449 cx.spawn(|editor, mut cx| async move {
9450 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9451 editor.update(&mut cx, |_, cx| {
9452 cx.open_url(&url);
9453 })
9454 } else {
9455 Ok(())
9456 }
9457 })
9458 .detach();
9459 }
9460
9461 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9462 let Some(workspace) = self.workspace() else {
9463 return;
9464 };
9465
9466 let position = self.selections.newest_anchor().head();
9467
9468 let Some((buffer, buffer_position)) =
9469 self.buffer.read(cx).text_anchor_for_position(position, cx)
9470 else {
9471 return;
9472 };
9473
9474 let Some(project) = self.project.clone() else {
9475 return;
9476 };
9477
9478 cx.spawn(|_, mut cx| async move {
9479 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9480
9481 if let Some((_, path)) = result {
9482 workspace
9483 .update(&mut cx, |workspace, cx| {
9484 workspace.open_resolved_path(path, cx)
9485 })?
9486 .await?;
9487 }
9488 anyhow::Ok(())
9489 })
9490 .detach();
9491 }
9492
9493 pub(crate) fn navigate_to_hover_links(
9494 &mut self,
9495 kind: Option<GotoDefinitionKind>,
9496 mut definitions: Vec<HoverLink>,
9497 split: bool,
9498 cx: &mut ViewContext<Editor>,
9499 ) -> Task<Result<Navigated>> {
9500 // If there is one definition, just open it directly
9501 if definitions.len() == 1 {
9502 let definition = definitions.pop().unwrap();
9503
9504 enum TargetTaskResult {
9505 Location(Option<Location>),
9506 AlreadyNavigated,
9507 }
9508
9509 let target_task = match definition {
9510 HoverLink::Text(link) => {
9511 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9512 }
9513 HoverLink::InlayHint(lsp_location, server_id) => {
9514 let computation = self.compute_target_location(lsp_location, server_id, cx);
9515 cx.background_executor().spawn(async move {
9516 let location = computation.await?;
9517 Ok(TargetTaskResult::Location(location))
9518 })
9519 }
9520 HoverLink::Url(url) => {
9521 cx.open_url(&url);
9522 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9523 }
9524 HoverLink::File(path) => {
9525 if let Some(workspace) = self.workspace() {
9526 cx.spawn(|_, mut cx| async move {
9527 workspace
9528 .update(&mut cx, |workspace, cx| {
9529 workspace.open_resolved_path(path, cx)
9530 })?
9531 .await
9532 .map(|_| TargetTaskResult::AlreadyNavigated)
9533 })
9534 } else {
9535 Task::ready(Ok(TargetTaskResult::Location(None)))
9536 }
9537 }
9538 };
9539 cx.spawn(|editor, mut cx| async move {
9540 let target = match target_task.await.context("target resolution task")? {
9541 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9542 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9543 TargetTaskResult::Location(Some(target)) => target,
9544 };
9545
9546 editor.update(&mut cx, |editor, cx| {
9547 let Some(workspace) = editor.workspace() else {
9548 return Navigated::No;
9549 };
9550 let pane = workspace.read(cx).active_pane().clone();
9551
9552 let range = target.range.to_offset(target.buffer.read(cx));
9553 let range = editor.range_for_match(&range);
9554
9555 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9556 let buffer = target.buffer.read(cx);
9557 let range = check_multiline_range(buffer, range);
9558 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9559 s.select_ranges([range]);
9560 });
9561 } else {
9562 cx.window_context().defer(move |cx| {
9563 let target_editor: View<Self> =
9564 workspace.update(cx, |workspace, cx| {
9565 let pane = if split {
9566 workspace.adjacent_pane(cx)
9567 } else {
9568 workspace.active_pane().clone()
9569 };
9570
9571 workspace.open_project_item(
9572 pane,
9573 target.buffer.clone(),
9574 true,
9575 true,
9576 cx,
9577 )
9578 });
9579 target_editor.update(cx, |target_editor, cx| {
9580 // When selecting a definition in a different buffer, disable the nav history
9581 // to avoid creating a history entry at the previous cursor location.
9582 pane.update(cx, |pane, _| pane.disable_history());
9583 let buffer = target.buffer.read(cx);
9584 let range = check_multiline_range(buffer, range);
9585 target_editor.change_selections(
9586 Some(Autoscroll::focused()),
9587 cx,
9588 |s| {
9589 s.select_ranges([range]);
9590 },
9591 );
9592 pane.update(cx, |pane, _| pane.enable_history());
9593 });
9594 });
9595 }
9596 Navigated::Yes
9597 })
9598 })
9599 } else if !definitions.is_empty() {
9600 let replica_id = self.replica_id(cx);
9601 cx.spawn(|editor, mut cx| async move {
9602 let (title, location_tasks, workspace) = editor
9603 .update(&mut cx, |editor, cx| {
9604 let tab_kind = match kind {
9605 Some(GotoDefinitionKind::Implementation) => "Implementations",
9606 _ => "Definitions",
9607 };
9608 let title = definitions
9609 .iter()
9610 .find_map(|definition| match definition {
9611 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9612 let buffer = origin.buffer.read(cx);
9613 format!(
9614 "{} for {}",
9615 tab_kind,
9616 buffer
9617 .text_for_range(origin.range.clone())
9618 .collect::<String>()
9619 )
9620 }),
9621 HoverLink::InlayHint(_, _) => None,
9622 HoverLink::Url(_) => None,
9623 HoverLink::File(_) => None,
9624 })
9625 .unwrap_or(tab_kind.to_string());
9626 let location_tasks = definitions
9627 .into_iter()
9628 .map(|definition| match definition {
9629 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9630 HoverLink::InlayHint(lsp_location, server_id) => {
9631 editor.compute_target_location(lsp_location, server_id, cx)
9632 }
9633 HoverLink::Url(_) => Task::ready(Ok(None)),
9634 HoverLink::File(_) => Task::ready(Ok(None)),
9635 })
9636 .collect::<Vec<_>>();
9637 (title, location_tasks, editor.workspace().clone())
9638 })
9639 .context("location tasks preparation")?;
9640
9641 let locations = futures::future::join_all(location_tasks)
9642 .await
9643 .into_iter()
9644 .filter_map(|location| location.transpose())
9645 .collect::<Result<_>>()
9646 .context("location tasks")?;
9647
9648 let Some(workspace) = workspace else {
9649 return Ok(Navigated::No);
9650 };
9651 let opened = workspace
9652 .update(&mut cx, |workspace, cx| {
9653 Self::open_locations_in_multibuffer(
9654 workspace, locations, replica_id, title, split, cx,
9655 )
9656 })
9657 .ok();
9658
9659 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9660 })
9661 } else {
9662 Task::ready(Ok(Navigated::No))
9663 }
9664 }
9665
9666 fn compute_target_location(
9667 &self,
9668 lsp_location: lsp::Location,
9669 server_id: LanguageServerId,
9670 cx: &mut ViewContext<Editor>,
9671 ) -> Task<anyhow::Result<Option<Location>>> {
9672 let Some(project) = self.project.clone() else {
9673 return Task::Ready(Some(Ok(None)));
9674 };
9675
9676 cx.spawn(move |editor, mut cx| async move {
9677 let location_task = editor.update(&mut cx, |editor, cx| {
9678 project.update(cx, |project, cx| {
9679 let language_server_name =
9680 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9681 project
9682 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9683 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9684 });
9685 language_server_name.map(|language_server_name| {
9686 project.open_local_buffer_via_lsp(
9687 lsp_location.uri.clone(),
9688 server_id,
9689 language_server_name,
9690 cx,
9691 )
9692 })
9693 })
9694 })?;
9695 let location = match location_task {
9696 Some(task) => Some({
9697 let target_buffer_handle = task.await.context("open local buffer")?;
9698 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9699 let target_start = target_buffer
9700 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9701 let target_end = target_buffer
9702 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9703 target_buffer.anchor_after(target_start)
9704 ..target_buffer.anchor_before(target_end)
9705 })?;
9706 Location {
9707 buffer: target_buffer_handle,
9708 range,
9709 }
9710 }),
9711 None => None,
9712 };
9713 Ok(location)
9714 })
9715 }
9716
9717 pub fn find_all_references(
9718 &mut self,
9719 _: &FindAllReferences,
9720 cx: &mut ViewContext<Self>,
9721 ) -> Option<Task<Result<Navigated>>> {
9722 let multi_buffer = self.buffer.read(cx);
9723 let selection = self.selections.newest::<usize>(cx);
9724 let head = selection.head();
9725
9726 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9727 let head_anchor = multi_buffer_snapshot.anchor_at(
9728 head,
9729 if head < selection.tail() {
9730 Bias::Right
9731 } else {
9732 Bias::Left
9733 },
9734 );
9735
9736 match self
9737 .find_all_references_task_sources
9738 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9739 {
9740 Ok(_) => {
9741 log::info!(
9742 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9743 );
9744 return None;
9745 }
9746 Err(i) => {
9747 self.find_all_references_task_sources.insert(i, head_anchor);
9748 }
9749 }
9750
9751 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9752 let replica_id = self.replica_id(cx);
9753 let workspace = self.workspace()?;
9754 let project = workspace.read(cx).project().clone();
9755 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9756 Some(cx.spawn(|editor, mut cx| async move {
9757 let _cleanup = defer({
9758 let mut cx = cx.clone();
9759 move || {
9760 let _ = editor.update(&mut cx, |editor, _| {
9761 if let Ok(i) =
9762 editor
9763 .find_all_references_task_sources
9764 .binary_search_by(|anchor| {
9765 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9766 })
9767 {
9768 editor.find_all_references_task_sources.remove(i);
9769 }
9770 });
9771 }
9772 });
9773
9774 let locations = references.await?;
9775 if locations.is_empty() {
9776 return anyhow::Ok(Navigated::No);
9777 }
9778
9779 workspace.update(&mut cx, |workspace, cx| {
9780 let title = locations
9781 .first()
9782 .as_ref()
9783 .map(|location| {
9784 let buffer = location.buffer.read(cx);
9785 format!(
9786 "References to `{}`",
9787 buffer
9788 .text_for_range(location.range.clone())
9789 .collect::<String>()
9790 )
9791 })
9792 .unwrap();
9793 Self::open_locations_in_multibuffer(
9794 workspace, locations, replica_id, title, false, cx,
9795 );
9796 Navigated::Yes
9797 })
9798 }))
9799 }
9800
9801 /// Opens a multibuffer with the given project locations in it
9802 pub fn open_locations_in_multibuffer(
9803 workspace: &mut Workspace,
9804 mut locations: Vec<Location>,
9805 replica_id: ReplicaId,
9806 title: String,
9807 split: bool,
9808 cx: &mut ViewContext<Workspace>,
9809 ) {
9810 // If there are multiple definitions, open them in a multibuffer
9811 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9812 let mut locations = locations.into_iter().peekable();
9813 let mut ranges_to_highlight = Vec::new();
9814 let capability = workspace.project().read(cx).capability();
9815
9816 let excerpt_buffer = cx.new_model(|cx| {
9817 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9818 while let Some(location) = locations.next() {
9819 let buffer = location.buffer.read(cx);
9820 let mut ranges_for_buffer = Vec::new();
9821 let range = location.range.to_offset(buffer);
9822 ranges_for_buffer.push(range.clone());
9823
9824 while let Some(next_location) = locations.peek() {
9825 if next_location.buffer == location.buffer {
9826 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9827 locations.next();
9828 } else {
9829 break;
9830 }
9831 }
9832
9833 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9834 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9835 location.buffer.clone(),
9836 ranges_for_buffer,
9837 DEFAULT_MULTIBUFFER_CONTEXT,
9838 cx,
9839 ))
9840 }
9841
9842 multibuffer.with_title(title)
9843 });
9844
9845 let editor = cx.new_view(|cx| {
9846 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9847 });
9848 editor.update(cx, |editor, cx| {
9849 if let Some(first_range) = ranges_to_highlight.first() {
9850 editor.change_selections(None, cx, |selections| {
9851 selections.clear_disjoint();
9852 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9853 });
9854 }
9855 editor.highlight_background::<Self>(
9856 &ranges_to_highlight,
9857 |theme| theme.editor_highlighted_line_background,
9858 cx,
9859 );
9860 });
9861
9862 let item = Box::new(editor);
9863 let item_id = item.item_id();
9864
9865 if split {
9866 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9867 } else {
9868 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9869 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9870 pane.close_current_preview_item(cx)
9871 } else {
9872 None
9873 }
9874 });
9875 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9876 }
9877 workspace.active_pane().update(cx, |pane, cx| {
9878 pane.set_preview_item_id(Some(item_id), cx);
9879 });
9880 }
9881
9882 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9883 use language::ToOffset as _;
9884
9885 let project = self.project.clone()?;
9886 let selection = self.selections.newest_anchor().clone();
9887 let (cursor_buffer, cursor_buffer_position) = self
9888 .buffer
9889 .read(cx)
9890 .text_anchor_for_position(selection.head(), cx)?;
9891 let (tail_buffer, cursor_buffer_position_end) = self
9892 .buffer
9893 .read(cx)
9894 .text_anchor_for_position(selection.tail(), cx)?;
9895 if tail_buffer != cursor_buffer {
9896 return None;
9897 }
9898
9899 let snapshot = cursor_buffer.read(cx).snapshot();
9900 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9901 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9902 let prepare_rename = project.update(cx, |project, cx| {
9903 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9904 });
9905 drop(snapshot);
9906
9907 Some(cx.spawn(|this, mut cx| async move {
9908 let rename_range = if let Some(range) = prepare_rename.await? {
9909 Some(range)
9910 } else {
9911 this.update(&mut cx, |this, cx| {
9912 let buffer = this.buffer.read(cx).snapshot(cx);
9913 let mut buffer_highlights = this
9914 .document_highlights_for_position(selection.head(), &buffer)
9915 .filter(|highlight| {
9916 highlight.start.excerpt_id == selection.head().excerpt_id
9917 && highlight.end.excerpt_id == selection.head().excerpt_id
9918 });
9919 buffer_highlights
9920 .next()
9921 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9922 })?
9923 };
9924 if let Some(rename_range) = rename_range {
9925 this.update(&mut cx, |this, cx| {
9926 let snapshot = cursor_buffer.read(cx).snapshot();
9927 let rename_buffer_range = rename_range.to_offset(&snapshot);
9928 let cursor_offset_in_rename_range =
9929 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9930 let cursor_offset_in_rename_range_end =
9931 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9932
9933 this.take_rename(false, cx);
9934 let buffer = this.buffer.read(cx).read(cx);
9935 let cursor_offset = selection.head().to_offset(&buffer);
9936 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9937 let rename_end = rename_start + rename_buffer_range.len();
9938 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9939 let mut old_highlight_id = None;
9940 let old_name: Arc<str> = buffer
9941 .chunks(rename_start..rename_end, true)
9942 .map(|chunk| {
9943 if old_highlight_id.is_none() {
9944 old_highlight_id = chunk.syntax_highlight_id;
9945 }
9946 chunk.text
9947 })
9948 .collect::<String>()
9949 .into();
9950
9951 drop(buffer);
9952
9953 // Position the selection in the rename editor so that it matches the current selection.
9954 this.show_local_selections = false;
9955 let rename_editor = cx.new_view(|cx| {
9956 let mut editor = Editor::single_line(cx);
9957 editor.buffer.update(cx, |buffer, cx| {
9958 buffer.edit([(0..0, old_name.clone())], None, cx)
9959 });
9960 let rename_selection_range = match cursor_offset_in_rename_range
9961 .cmp(&cursor_offset_in_rename_range_end)
9962 {
9963 Ordering::Equal => {
9964 editor.select_all(&SelectAll, cx);
9965 return editor;
9966 }
9967 Ordering::Less => {
9968 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9969 }
9970 Ordering::Greater => {
9971 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9972 }
9973 };
9974 if rename_selection_range.end > old_name.len() {
9975 editor.select_all(&SelectAll, cx);
9976 } else {
9977 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9978 s.select_ranges([rename_selection_range]);
9979 });
9980 }
9981 editor
9982 });
9983 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9984 if e == &EditorEvent::Focused {
9985 cx.emit(EditorEvent::FocusedIn)
9986 }
9987 })
9988 .detach();
9989
9990 let write_highlights =
9991 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9992 let read_highlights =
9993 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9994 let ranges = write_highlights
9995 .iter()
9996 .flat_map(|(_, ranges)| ranges.iter())
9997 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9998 .cloned()
9999 .collect();
10000
10001 this.highlight_text::<Rename>(
10002 ranges,
10003 HighlightStyle {
10004 fade_out: Some(0.6),
10005 ..Default::default()
10006 },
10007 cx,
10008 );
10009 let rename_focus_handle = rename_editor.focus_handle(cx);
10010 cx.focus(&rename_focus_handle);
10011 let block_id = this.insert_blocks(
10012 [BlockProperties {
10013 style: BlockStyle::Flex,
10014 position: range.start,
10015 height: 1,
10016 render: Box::new({
10017 let rename_editor = rename_editor.clone();
10018 move |cx: &mut BlockContext| {
10019 let mut text_style = cx.editor_style.text.clone();
10020 if let Some(highlight_style) = old_highlight_id
10021 .and_then(|h| h.style(&cx.editor_style.syntax))
10022 {
10023 text_style = text_style.highlight(highlight_style);
10024 }
10025 div()
10026 .pl(cx.anchor_x)
10027 .child(EditorElement::new(
10028 &rename_editor,
10029 EditorStyle {
10030 background: cx.theme().system().transparent,
10031 local_player: cx.editor_style.local_player,
10032 text: text_style,
10033 scrollbar_width: cx.editor_style.scrollbar_width,
10034 syntax: cx.editor_style.syntax.clone(),
10035 status: cx.editor_style.status.clone(),
10036 inlay_hints_style: HighlightStyle {
10037 color: Some(cx.theme().status().hint),
10038 font_weight: Some(FontWeight::BOLD),
10039 ..HighlightStyle::default()
10040 },
10041 suggestions_style: HighlightStyle {
10042 color: Some(cx.theme().status().predictive),
10043 ..HighlightStyle::default()
10044 },
10045 ..EditorStyle::default()
10046 },
10047 ))
10048 .into_any_element()
10049 }
10050 }),
10051 disposition: BlockDisposition::Below,
10052 priority: 0,
10053 }],
10054 Some(Autoscroll::fit()),
10055 cx,
10056 )[0];
10057 this.pending_rename = Some(RenameState {
10058 range,
10059 old_name,
10060 editor: rename_editor,
10061 block_id,
10062 });
10063 })?;
10064 }
10065
10066 Ok(())
10067 }))
10068 }
10069
10070 pub fn confirm_rename(
10071 &mut self,
10072 _: &ConfirmRename,
10073 cx: &mut ViewContext<Self>,
10074 ) -> Option<Task<Result<()>>> {
10075 let rename = self.take_rename(false, cx)?;
10076 let workspace = self.workspace()?;
10077 let (start_buffer, start) = self
10078 .buffer
10079 .read(cx)
10080 .text_anchor_for_position(rename.range.start, cx)?;
10081 let (end_buffer, end) = self
10082 .buffer
10083 .read(cx)
10084 .text_anchor_for_position(rename.range.end, cx)?;
10085 if start_buffer != end_buffer {
10086 return None;
10087 }
10088
10089 let buffer = start_buffer;
10090 let range = start..end;
10091 let old_name = rename.old_name;
10092 let new_name = rename.editor.read(cx).text(cx);
10093
10094 let rename = workspace
10095 .read(cx)
10096 .project()
10097 .clone()
10098 .update(cx, |project, cx| {
10099 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10100 });
10101 let workspace = workspace.downgrade();
10102
10103 Some(cx.spawn(|editor, mut cx| async move {
10104 let project_transaction = rename.await?;
10105 Self::open_project_transaction(
10106 &editor,
10107 workspace,
10108 project_transaction,
10109 format!("Rename: {} → {}", old_name, new_name),
10110 cx.clone(),
10111 )
10112 .await?;
10113
10114 editor.update(&mut cx, |editor, cx| {
10115 editor.refresh_document_highlights(cx);
10116 })?;
10117 Ok(())
10118 }))
10119 }
10120
10121 fn take_rename(
10122 &mut self,
10123 moving_cursor: bool,
10124 cx: &mut ViewContext<Self>,
10125 ) -> Option<RenameState> {
10126 let rename = self.pending_rename.take()?;
10127 if rename.editor.focus_handle(cx).is_focused(cx) {
10128 cx.focus(&self.focus_handle);
10129 }
10130
10131 self.remove_blocks(
10132 [rename.block_id].into_iter().collect(),
10133 Some(Autoscroll::fit()),
10134 cx,
10135 );
10136 self.clear_highlights::<Rename>(cx);
10137 self.show_local_selections = true;
10138
10139 if moving_cursor {
10140 let rename_editor = rename.editor.read(cx);
10141 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10142
10143 // Update the selection to match the position of the selection inside
10144 // the rename editor.
10145 let snapshot = self.buffer.read(cx).read(cx);
10146 let rename_range = rename.range.to_offset(&snapshot);
10147 let cursor_in_editor = snapshot
10148 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10149 .min(rename_range.end);
10150 drop(snapshot);
10151
10152 self.change_selections(None, cx, |s| {
10153 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10154 });
10155 } else {
10156 self.refresh_document_highlights(cx);
10157 }
10158
10159 Some(rename)
10160 }
10161
10162 pub fn pending_rename(&self) -> Option<&RenameState> {
10163 self.pending_rename.as_ref()
10164 }
10165
10166 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10167 let project = match &self.project {
10168 Some(project) => project.clone(),
10169 None => return None,
10170 };
10171
10172 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10173 }
10174
10175 fn perform_format(
10176 &mut self,
10177 project: Model<Project>,
10178 trigger: FormatTrigger,
10179 cx: &mut ViewContext<Self>,
10180 ) -> Task<Result<()>> {
10181 let buffer = self.buffer().clone();
10182 let mut buffers = buffer.read(cx).all_buffers();
10183 if trigger == FormatTrigger::Save {
10184 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10185 }
10186
10187 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10188 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10189
10190 cx.spawn(|_, mut cx| async move {
10191 let transaction = futures::select_biased! {
10192 () = timeout => {
10193 log::warn!("timed out waiting for formatting");
10194 None
10195 }
10196 transaction = format.log_err().fuse() => transaction,
10197 };
10198
10199 buffer
10200 .update(&mut cx, |buffer, cx| {
10201 if let Some(transaction) = transaction {
10202 if !buffer.is_singleton() {
10203 buffer.push_transaction(&transaction.0, cx);
10204 }
10205 }
10206
10207 cx.notify();
10208 })
10209 .ok();
10210
10211 Ok(())
10212 })
10213 }
10214
10215 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10216 if let Some(project) = self.project.clone() {
10217 self.buffer.update(cx, |multi_buffer, cx| {
10218 project.update(cx, |project, cx| {
10219 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10220 });
10221 })
10222 }
10223 }
10224
10225 fn cancel_language_server_work(
10226 &mut self,
10227 _: &CancelLanguageServerWork,
10228 cx: &mut ViewContext<Self>,
10229 ) {
10230 if let Some(project) = self.project.clone() {
10231 self.buffer.update(cx, |multi_buffer, cx| {
10232 project.update(cx, |project, cx| {
10233 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10234 });
10235 })
10236 }
10237 }
10238
10239 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10240 cx.show_character_palette();
10241 }
10242
10243 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10244 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10245 let buffer = self.buffer.read(cx).snapshot(cx);
10246 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10247 let is_valid = buffer
10248 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10249 .any(|entry| {
10250 entry.diagnostic.is_primary
10251 && !entry.range.is_empty()
10252 && entry.range.start == primary_range_start
10253 && entry.diagnostic.message == active_diagnostics.primary_message
10254 });
10255
10256 if is_valid != active_diagnostics.is_valid {
10257 active_diagnostics.is_valid = is_valid;
10258 let mut new_styles = HashMap::default();
10259 for (block_id, diagnostic) in &active_diagnostics.blocks {
10260 new_styles.insert(
10261 *block_id,
10262 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10263 );
10264 }
10265 self.display_map.update(cx, |display_map, _cx| {
10266 display_map.replace_blocks(new_styles)
10267 });
10268 }
10269 }
10270 }
10271
10272 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10273 self.dismiss_diagnostics(cx);
10274 let snapshot = self.snapshot(cx);
10275 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10276 let buffer = self.buffer.read(cx).snapshot(cx);
10277
10278 let mut primary_range = None;
10279 let mut primary_message = None;
10280 let mut group_end = Point::zero();
10281 let diagnostic_group = buffer
10282 .diagnostic_group::<MultiBufferPoint>(group_id)
10283 .filter_map(|entry| {
10284 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10285 && (entry.range.start.row == entry.range.end.row
10286 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10287 {
10288 return None;
10289 }
10290 if entry.range.end > group_end {
10291 group_end = entry.range.end;
10292 }
10293 if entry.diagnostic.is_primary {
10294 primary_range = Some(entry.range.clone());
10295 primary_message = Some(entry.diagnostic.message.clone());
10296 }
10297 Some(entry)
10298 })
10299 .collect::<Vec<_>>();
10300 let primary_range = primary_range?;
10301 let primary_message = primary_message?;
10302 let primary_range =
10303 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10304
10305 let blocks = display_map
10306 .insert_blocks(
10307 diagnostic_group.iter().map(|entry| {
10308 let diagnostic = entry.diagnostic.clone();
10309 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10310 BlockProperties {
10311 style: BlockStyle::Fixed,
10312 position: buffer.anchor_after(entry.range.start),
10313 height: message_height,
10314 render: diagnostic_block_renderer(diagnostic, None, true, true),
10315 disposition: BlockDisposition::Below,
10316 priority: 0,
10317 }
10318 }),
10319 cx,
10320 )
10321 .into_iter()
10322 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10323 .collect();
10324
10325 Some(ActiveDiagnosticGroup {
10326 primary_range,
10327 primary_message,
10328 group_id,
10329 blocks,
10330 is_valid: true,
10331 })
10332 });
10333 self.active_diagnostics.is_some()
10334 }
10335
10336 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10337 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10338 self.display_map.update(cx, |display_map, cx| {
10339 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10340 });
10341 cx.notify();
10342 }
10343 }
10344
10345 pub fn set_selections_from_remote(
10346 &mut self,
10347 selections: Vec<Selection<Anchor>>,
10348 pending_selection: Option<Selection<Anchor>>,
10349 cx: &mut ViewContext<Self>,
10350 ) {
10351 let old_cursor_position = self.selections.newest_anchor().head();
10352 self.selections.change_with(cx, |s| {
10353 s.select_anchors(selections);
10354 if let Some(pending_selection) = pending_selection {
10355 s.set_pending(pending_selection, SelectMode::Character);
10356 } else {
10357 s.clear_pending();
10358 }
10359 });
10360 self.selections_did_change(false, &old_cursor_position, true, cx);
10361 }
10362
10363 fn push_to_selection_history(&mut self) {
10364 self.selection_history.push(SelectionHistoryEntry {
10365 selections: self.selections.disjoint_anchors(),
10366 select_next_state: self.select_next_state.clone(),
10367 select_prev_state: self.select_prev_state.clone(),
10368 add_selections_state: self.add_selections_state.clone(),
10369 });
10370 }
10371
10372 pub fn transact(
10373 &mut self,
10374 cx: &mut ViewContext<Self>,
10375 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10376 ) -> Option<TransactionId> {
10377 self.start_transaction_at(Instant::now(), cx);
10378 update(self, cx);
10379 self.end_transaction_at(Instant::now(), cx)
10380 }
10381
10382 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10383 self.end_selection(cx);
10384 if let Some(tx_id) = self
10385 .buffer
10386 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10387 {
10388 self.selection_history
10389 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10390 cx.emit(EditorEvent::TransactionBegun {
10391 transaction_id: tx_id,
10392 })
10393 }
10394 }
10395
10396 fn end_transaction_at(
10397 &mut self,
10398 now: Instant,
10399 cx: &mut ViewContext<Self>,
10400 ) -> Option<TransactionId> {
10401 if let Some(transaction_id) = self
10402 .buffer
10403 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10404 {
10405 if let Some((_, end_selections)) =
10406 self.selection_history.transaction_mut(transaction_id)
10407 {
10408 *end_selections = Some(self.selections.disjoint_anchors());
10409 } else {
10410 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10411 }
10412
10413 cx.emit(EditorEvent::Edited { transaction_id });
10414 Some(transaction_id)
10415 } else {
10416 None
10417 }
10418 }
10419
10420 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10421 let mut fold_ranges = Vec::new();
10422
10423 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10424
10425 let selections = self.selections.all_adjusted(cx);
10426 for selection in selections {
10427 let range = selection.range().sorted();
10428 let buffer_start_row = range.start.row;
10429
10430 for row in (0..=range.end.row).rev() {
10431 if let Some((foldable_range, fold_text)) =
10432 display_map.foldable_range(MultiBufferRow(row))
10433 {
10434 if foldable_range.end.row >= buffer_start_row {
10435 fold_ranges.push((foldable_range, fold_text));
10436 if row <= range.start.row {
10437 break;
10438 }
10439 }
10440 }
10441 }
10442 }
10443
10444 self.fold_ranges(fold_ranges, true, cx);
10445 }
10446
10447 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10448 let buffer_row = fold_at.buffer_row;
10449 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10450
10451 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10452 let autoscroll = self
10453 .selections
10454 .all::<Point>(cx)
10455 .iter()
10456 .any(|selection| fold_range.overlaps(&selection.range()));
10457
10458 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10459 }
10460 }
10461
10462 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10463 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10464 let buffer = &display_map.buffer_snapshot;
10465 let selections = self.selections.all::<Point>(cx);
10466 let ranges = selections
10467 .iter()
10468 .map(|s| {
10469 let range = s.display_range(&display_map).sorted();
10470 let mut start = range.start.to_point(&display_map);
10471 let mut end = range.end.to_point(&display_map);
10472 start.column = 0;
10473 end.column = buffer.line_len(MultiBufferRow(end.row));
10474 start..end
10475 })
10476 .collect::<Vec<_>>();
10477
10478 self.unfold_ranges(ranges, true, true, cx);
10479 }
10480
10481 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10482 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10483
10484 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10485 ..Point::new(
10486 unfold_at.buffer_row.0,
10487 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10488 );
10489
10490 let autoscroll = self
10491 .selections
10492 .all::<Point>(cx)
10493 .iter()
10494 .any(|selection| selection.range().overlaps(&intersection_range));
10495
10496 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10497 }
10498
10499 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10500 let selections = self.selections.all::<Point>(cx);
10501 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10502 let line_mode = self.selections.line_mode;
10503 let ranges = selections.into_iter().map(|s| {
10504 if line_mode {
10505 let start = Point::new(s.start.row, 0);
10506 let end = Point::new(
10507 s.end.row,
10508 display_map
10509 .buffer_snapshot
10510 .line_len(MultiBufferRow(s.end.row)),
10511 );
10512 (start..end, display_map.fold_placeholder.clone())
10513 } else {
10514 (s.start..s.end, display_map.fold_placeholder.clone())
10515 }
10516 });
10517 self.fold_ranges(ranges, true, cx);
10518 }
10519
10520 pub fn fold_ranges<T: ToOffset + Clone>(
10521 &mut self,
10522 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10523 auto_scroll: bool,
10524 cx: &mut ViewContext<Self>,
10525 ) {
10526 let mut fold_ranges = Vec::new();
10527 let mut buffers_affected = HashMap::default();
10528 let multi_buffer = self.buffer().read(cx);
10529 for (fold_range, fold_text) in ranges {
10530 if let Some((_, buffer, _)) =
10531 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10532 {
10533 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10534 };
10535 fold_ranges.push((fold_range, fold_text));
10536 }
10537
10538 let mut ranges = fold_ranges.into_iter().peekable();
10539 if ranges.peek().is_some() {
10540 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10541
10542 if auto_scroll {
10543 self.request_autoscroll(Autoscroll::fit(), cx);
10544 }
10545
10546 for buffer in buffers_affected.into_values() {
10547 self.sync_expanded_diff_hunks(buffer, cx);
10548 }
10549
10550 cx.notify();
10551
10552 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10553 // Clear diagnostics block when folding a range that contains it.
10554 let snapshot = self.snapshot(cx);
10555 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10556 drop(snapshot);
10557 self.active_diagnostics = Some(active_diagnostics);
10558 self.dismiss_diagnostics(cx);
10559 } else {
10560 self.active_diagnostics = Some(active_diagnostics);
10561 }
10562 }
10563
10564 self.scrollbar_marker_state.dirty = true;
10565 }
10566 }
10567
10568 pub fn unfold_ranges<T: ToOffset + Clone>(
10569 &mut self,
10570 ranges: impl IntoIterator<Item = Range<T>>,
10571 inclusive: bool,
10572 auto_scroll: bool,
10573 cx: &mut ViewContext<Self>,
10574 ) {
10575 let mut unfold_ranges = Vec::new();
10576 let mut buffers_affected = HashMap::default();
10577 let multi_buffer = self.buffer().read(cx);
10578 for range in ranges {
10579 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10580 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10581 };
10582 unfold_ranges.push(range);
10583 }
10584
10585 let mut ranges = unfold_ranges.into_iter().peekable();
10586 if ranges.peek().is_some() {
10587 self.display_map
10588 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10589 if auto_scroll {
10590 self.request_autoscroll(Autoscroll::fit(), cx);
10591 }
10592
10593 for buffer in buffers_affected.into_values() {
10594 self.sync_expanded_diff_hunks(buffer, cx);
10595 }
10596
10597 cx.notify();
10598 self.scrollbar_marker_state.dirty = true;
10599 self.active_indent_guides_state.dirty = true;
10600 }
10601 }
10602
10603 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10604 self.display_map.read(cx).fold_placeholder.clone()
10605 }
10606
10607 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10608 if hovered != self.gutter_hovered {
10609 self.gutter_hovered = hovered;
10610 cx.notify();
10611 }
10612 }
10613
10614 pub fn insert_blocks(
10615 &mut self,
10616 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10617 autoscroll: Option<Autoscroll>,
10618 cx: &mut ViewContext<Self>,
10619 ) -> Vec<CustomBlockId> {
10620 let blocks = self
10621 .display_map
10622 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10623 if let Some(autoscroll) = autoscroll {
10624 self.request_autoscroll(autoscroll, cx);
10625 }
10626 cx.notify();
10627 blocks
10628 }
10629
10630 pub fn resize_blocks(
10631 &mut self,
10632 heights: HashMap<CustomBlockId, u32>,
10633 autoscroll: Option<Autoscroll>,
10634 cx: &mut ViewContext<Self>,
10635 ) {
10636 self.display_map
10637 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10638 if let Some(autoscroll) = autoscroll {
10639 self.request_autoscroll(autoscroll, cx);
10640 }
10641 cx.notify();
10642 }
10643
10644 pub fn replace_blocks(
10645 &mut self,
10646 renderers: HashMap<CustomBlockId, RenderBlock>,
10647 autoscroll: Option<Autoscroll>,
10648 cx: &mut ViewContext<Self>,
10649 ) {
10650 self.display_map
10651 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10652 if let Some(autoscroll) = autoscroll {
10653 self.request_autoscroll(autoscroll, cx);
10654 }
10655 cx.notify();
10656 }
10657
10658 pub fn remove_blocks(
10659 &mut self,
10660 block_ids: HashSet<CustomBlockId>,
10661 autoscroll: Option<Autoscroll>,
10662 cx: &mut ViewContext<Self>,
10663 ) {
10664 self.display_map.update(cx, |display_map, cx| {
10665 display_map.remove_blocks(block_ids, cx)
10666 });
10667 if let Some(autoscroll) = autoscroll {
10668 self.request_autoscroll(autoscroll, cx);
10669 }
10670 cx.notify();
10671 }
10672
10673 pub fn row_for_block(
10674 &self,
10675 block_id: CustomBlockId,
10676 cx: &mut ViewContext<Self>,
10677 ) -> Option<DisplayRow> {
10678 self.display_map
10679 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10680 }
10681
10682 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10683 self.focused_block = Some(focused_block);
10684 }
10685
10686 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10687 self.focused_block.take()
10688 }
10689
10690 pub fn insert_creases(
10691 &mut self,
10692 creases: impl IntoIterator<Item = Crease>,
10693 cx: &mut ViewContext<Self>,
10694 ) -> Vec<CreaseId> {
10695 self.display_map
10696 .update(cx, |map, cx| map.insert_creases(creases, cx))
10697 }
10698
10699 pub fn remove_creases(
10700 &mut self,
10701 ids: impl IntoIterator<Item = CreaseId>,
10702 cx: &mut ViewContext<Self>,
10703 ) {
10704 self.display_map
10705 .update(cx, |map, cx| map.remove_creases(ids, cx));
10706 }
10707
10708 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10709 self.display_map
10710 .update(cx, |map, cx| map.snapshot(cx))
10711 .longest_row()
10712 }
10713
10714 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10715 self.display_map
10716 .update(cx, |map, cx| map.snapshot(cx))
10717 .max_point()
10718 }
10719
10720 pub fn text(&self, cx: &AppContext) -> String {
10721 self.buffer.read(cx).read(cx).text()
10722 }
10723
10724 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10725 let text = self.text(cx);
10726 let text = text.trim();
10727
10728 if text.is_empty() {
10729 return None;
10730 }
10731
10732 Some(text.to_string())
10733 }
10734
10735 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10736 self.transact(cx, |this, cx| {
10737 this.buffer
10738 .read(cx)
10739 .as_singleton()
10740 .expect("you can only call set_text on editors for singleton buffers")
10741 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10742 });
10743 }
10744
10745 pub fn display_text(&self, cx: &mut AppContext) -> String {
10746 self.display_map
10747 .update(cx, |map, cx| map.snapshot(cx))
10748 .text()
10749 }
10750
10751 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10752 let mut wrap_guides = smallvec::smallvec![];
10753
10754 if self.show_wrap_guides == Some(false) {
10755 return wrap_guides;
10756 }
10757
10758 let settings = self.buffer.read(cx).settings_at(0, cx);
10759 if settings.show_wrap_guides {
10760 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10761 wrap_guides.push((soft_wrap as usize, true));
10762 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10763 wrap_guides.push((soft_wrap as usize, true));
10764 }
10765 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10766 }
10767
10768 wrap_guides
10769 }
10770
10771 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10772 let settings = self.buffer.read(cx).settings_at(0, cx);
10773 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10774 match mode {
10775 language_settings::SoftWrap::None => SoftWrap::None,
10776 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10777 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10778 language_settings::SoftWrap::PreferredLineLength => {
10779 SoftWrap::Column(settings.preferred_line_length)
10780 }
10781 language_settings::SoftWrap::Bounded => {
10782 SoftWrap::Bounded(settings.preferred_line_length)
10783 }
10784 }
10785 }
10786
10787 pub fn set_soft_wrap_mode(
10788 &mut self,
10789 mode: language_settings::SoftWrap,
10790 cx: &mut ViewContext<Self>,
10791 ) {
10792 self.soft_wrap_mode_override = Some(mode);
10793 cx.notify();
10794 }
10795
10796 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10797 let rem_size = cx.rem_size();
10798 self.display_map.update(cx, |map, cx| {
10799 map.set_font(
10800 style.text.font(),
10801 style.text.font_size.to_pixels(rem_size),
10802 cx,
10803 )
10804 });
10805 self.style = Some(style);
10806 }
10807
10808 pub fn style(&self) -> Option<&EditorStyle> {
10809 self.style.as_ref()
10810 }
10811
10812 // Called by the element. This method is not designed to be called outside of the editor
10813 // element's layout code because it does not notify when rewrapping is computed synchronously.
10814 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10815 self.display_map
10816 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10817 }
10818
10819 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10820 if self.soft_wrap_mode_override.is_some() {
10821 self.soft_wrap_mode_override.take();
10822 } else {
10823 let soft_wrap = match self.soft_wrap_mode(cx) {
10824 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10825 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10826 language_settings::SoftWrap::PreferLine
10827 }
10828 };
10829 self.soft_wrap_mode_override = Some(soft_wrap);
10830 }
10831 cx.notify();
10832 }
10833
10834 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10835 let Some(workspace) = self.workspace() else {
10836 return;
10837 };
10838 let fs = workspace.read(cx).app_state().fs.clone();
10839 let current_show = TabBarSettings::get_global(cx).show;
10840 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10841 setting.show = Some(!current_show);
10842 });
10843 }
10844
10845 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10846 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10847 self.buffer
10848 .read(cx)
10849 .settings_at(0, cx)
10850 .indent_guides
10851 .enabled
10852 });
10853 self.show_indent_guides = Some(!currently_enabled);
10854 cx.notify();
10855 }
10856
10857 fn should_show_indent_guides(&self) -> Option<bool> {
10858 self.show_indent_guides
10859 }
10860
10861 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10862 let mut editor_settings = EditorSettings::get_global(cx).clone();
10863 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10864 EditorSettings::override_global(editor_settings, cx);
10865 }
10866
10867 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10868 self.use_relative_line_numbers
10869 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10870 }
10871
10872 pub fn toggle_relative_line_numbers(
10873 &mut self,
10874 _: &ToggleRelativeLineNumbers,
10875 cx: &mut ViewContext<Self>,
10876 ) {
10877 let is_relative = self.should_use_relative_line_numbers(cx);
10878 self.set_relative_line_number(Some(!is_relative), cx)
10879 }
10880
10881 pub fn set_relative_line_number(
10882 &mut self,
10883 is_relative: Option<bool>,
10884 cx: &mut ViewContext<Self>,
10885 ) {
10886 self.use_relative_line_numbers = is_relative;
10887 cx.notify();
10888 }
10889
10890 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10891 self.show_gutter = show_gutter;
10892 cx.notify();
10893 }
10894
10895 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10896 self.show_line_numbers = Some(show_line_numbers);
10897 cx.notify();
10898 }
10899
10900 pub fn set_show_git_diff_gutter(
10901 &mut self,
10902 show_git_diff_gutter: bool,
10903 cx: &mut ViewContext<Self>,
10904 ) {
10905 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10906 cx.notify();
10907 }
10908
10909 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10910 self.show_code_actions = Some(show_code_actions);
10911 cx.notify();
10912 }
10913
10914 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10915 self.show_runnables = Some(show_runnables);
10916 cx.notify();
10917 }
10918
10919 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10920 if self.display_map.read(cx).masked != masked {
10921 self.display_map.update(cx, |map, _| map.masked = masked);
10922 }
10923 cx.notify()
10924 }
10925
10926 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10927 self.show_wrap_guides = Some(show_wrap_guides);
10928 cx.notify();
10929 }
10930
10931 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10932 self.show_indent_guides = Some(show_indent_guides);
10933 cx.notify();
10934 }
10935
10936 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10937 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10938 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10939 if let Some(dir) = file.abs_path(cx).parent() {
10940 return Some(dir.to_owned());
10941 }
10942 }
10943
10944 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10945 return Some(project_path.path.to_path_buf());
10946 }
10947 }
10948
10949 None
10950 }
10951
10952 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10953 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10954 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10955 cx.reveal_path(&file.abs_path(cx));
10956 }
10957 }
10958 }
10959
10960 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10961 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10962 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10963 if let Some(path) = file.abs_path(cx).to_str() {
10964 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10965 }
10966 }
10967 }
10968 }
10969
10970 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10971 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10972 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10973 if let Some(path) = file.path().to_str() {
10974 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10975 }
10976 }
10977 }
10978 }
10979
10980 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10981 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10982
10983 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10984 self.start_git_blame(true, cx);
10985 }
10986
10987 cx.notify();
10988 }
10989
10990 pub fn toggle_git_blame_inline(
10991 &mut self,
10992 _: &ToggleGitBlameInline,
10993 cx: &mut ViewContext<Self>,
10994 ) {
10995 self.toggle_git_blame_inline_internal(true, cx);
10996 cx.notify();
10997 }
10998
10999 pub fn git_blame_inline_enabled(&self) -> bool {
11000 self.git_blame_inline_enabled
11001 }
11002
11003 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11004 self.show_selection_menu = self
11005 .show_selection_menu
11006 .map(|show_selections_menu| !show_selections_menu)
11007 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11008
11009 cx.notify();
11010 }
11011
11012 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11013 self.show_selection_menu
11014 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11015 }
11016
11017 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11018 if let Some(project) = self.project.as_ref() {
11019 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11020 return;
11021 };
11022
11023 if buffer.read(cx).file().is_none() {
11024 return;
11025 }
11026
11027 let focused = self.focus_handle(cx).contains_focused(cx);
11028
11029 let project = project.clone();
11030 let blame =
11031 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11032 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11033 self.blame = Some(blame);
11034 }
11035 }
11036
11037 fn toggle_git_blame_inline_internal(
11038 &mut self,
11039 user_triggered: bool,
11040 cx: &mut ViewContext<Self>,
11041 ) {
11042 if self.git_blame_inline_enabled {
11043 self.git_blame_inline_enabled = false;
11044 self.show_git_blame_inline = false;
11045 self.show_git_blame_inline_delay_task.take();
11046 } else {
11047 self.git_blame_inline_enabled = true;
11048 self.start_git_blame_inline(user_triggered, cx);
11049 }
11050
11051 cx.notify();
11052 }
11053
11054 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11055 self.start_git_blame(user_triggered, cx);
11056
11057 if ProjectSettings::get_global(cx)
11058 .git
11059 .inline_blame_delay()
11060 .is_some()
11061 {
11062 self.start_inline_blame_timer(cx);
11063 } else {
11064 self.show_git_blame_inline = true
11065 }
11066 }
11067
11068 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11069 self.blame.as_ref()
11070 }
11071
11072 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11073 self.show_git_blame_gutter && self.has_blame_entries(cx)
11074 }
11075
11076 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11077 self.show_git_blame_inline
11078 && self.focus_handle.is_focused(cx)
11079 && !self.newest_selection_head_on_empty_line(cx)
11080 && self.has_blame_entries(cx)
11081 }
11082
11083 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11084 self.blame()
11085 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11086 }
11087
11088 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11089 let cursor_anchor = self.selections.newest_anchor().head();
11090
11091 let snapshot = self.buffer.read(cx).snapshot(cx);
11092 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11093
11094 snapshot.line_len(buffer_row) == 0
11095 }
11096
11097 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11098 let (path, selection, repo) = maybe!({
11099 let project_handle = self.project.as_ref()?.clone();
11100 let project = project_handle.read(cx);
11101
11102 let selection = self.selections.newest::<Point>(cx);
11103 let selection_range = selection.range();
11104
11105 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11106 (buffer, selection_range.start.row..selection_range.end.row)
11107 } else {
11108 let buffer_ranges = self
11109 .buffer()
11110 .read(cx)
11111 .range_to_buffer_ranges(selection_range, cx);
11112
11113 let (buffer, range, _) = if selection.reversed {
11114 buffer_ranges.first()
11115 } else {
11116 buffer_ranges.last()
11117 }?;
11118
11119 let snapshot = buffer.read(cx).snapshot();
11120 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11121 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11122 (buffer.clone(), selection)
11123 };
11124
11125 let path = buffer
11126 .read(cx)
11127 .file()?
11128 .as_local()?
11129 .path()
11130 .to_str()?
11131 .to_string();
11132 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11133 Some((path, selection, repo))
11134 })
11135 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11136
11137 const REMOTE_NAME: &str = "origin";
11138 let origin_url = repo
11139 .remote_url(REMOTE_NAME)
11140 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11141 let sha = repo
11142 .head_sha()
11143 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11144
11145 let (provider, remote) =
11146 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11147 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11148
11149 Ok(provider.build_permalink(
11150 remote,
11151 BuildPermalinkParams {
11152 sha: &sha,
11153 path: &path,
11154 selection: Some(selection),
11155 },
11156 ))
11157 }
11158
11159 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11160 let permalink = self.get_permalink_to_line(cx);
11161
11162 match permalink {
11163 Ok(permalink) => {
11164 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11165 }
11166 Err(err) => {
11167 let message = format!("Failed to copy permalink: {err}");
11168
11169 Err::<(), anyhow::Error>(err).log_err();
11170
11171 if let Some(workspace) = self.workspace() {
11172 workspace.update(cx, |workspace, cx| {
11173 struct CopyPermalinkToLine;
11174
11175 workspace.show_toast(
11176 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11177 cx,
11178 )
11179 })
11180 }
11181 }
11182 }
11183 }
11184
11185 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11186 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11187 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11188 if let Some(path) = file.path().to_str() {
11189 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11190 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11191 }
11192 }
11193 }
11194 }
11195
11196 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11197 let permalink = self.get_permalink_to_line(cx);
11198
11199 match permalink {
11200 Ok(permalink) => {
11201 cx.open_url(permalink.as_ref());
11202 }
11203 Err(err) => {
11204 let message = format!("Failed to open permalink: {err}");
11205
11206 Err::<(), anyhow::Error>(err).log_err();
11207
11208 if let Some(workspace) = self.workspace() {
11209 workspace.update(cx, |workspace, cx| {
11210 struct OpenPermalinkToLine;
11211
11212 workspace.show_toast(
11213 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11214 cx,
11215 )
11216 })
11217 }
11218 }
11219 }
11220 }
11221
11222 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11223 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11224 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11225 pub fn highlight_rows<T: 'static>(
11226 &mut self,
11227 rows: RangeInclusive<Anchor>,
11228 color: Option<Hsla>,
11229 should_autoscroll: bool,
11230 cx: &mut ViewContext<Self>,
11231 ) {
11232 let snapshot = self.buffer().read(cx).snapshot(cx);
11233 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11234 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11235 highlight
11236 .range
11237 .start()
11238 .cmp(rows.start(), &snapshot)
11239 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11240 });
11241 match (color, existing_highlight_index) {
11242 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11243 ix,
11244 RowHighlight {
11245 index: post_inc(&mut self.highlight_order),
11246 range: rows,
11247 should_autoscroll,
11248 color,
11249 },
11250 ),
11251 (None, Ok(i)) => {
11252 row_highlights.remove(i);
11253 }
11254 }
11255 }
11256
11257 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11258 pub fn clear_row_highlights<T: 'static>(&mut self) {
11259 self.highlighted_rows.remove(&TypeId::of::<T>());
11260 }
11261
11262 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11263 pub fn highlighted_rows<T: 'static>(
11264 &self,
11265 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11266 Some(
11267 self.highlighted_rows
11268 .get(&TypeId::of::<T>())?
11269 .iter()
11270 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11271 )
11272 }
11273
11274 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11275 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11276 /// Allows to ignore certain kinds of highlights.
11277 pub fn highlighted_display_rows(
11278 &mut self,
11279 cx: &mut WindowContext,
11280 ) -> BTreeMap<DisplayRow, Hsla> {
11281 let snapshot = self.snapshot(cx);
11282 let mut used_highlight_orders = HashMap::default();
11283 self.highlighted_rows
11284 .iter()
11285 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11286 .fold(
11287 BTreeMap::<DisplayRow, Hsla>::new(),
11288 |mut unique_rows, highlight| {
11289 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11290 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11291 for row in start_row.0..=end_row.0 {
11292 let used_index =
11293 used_highlight_orders.entry(row).or_insert(highlight.index);
11294 if highlight.index >= *used_index {
11295 *used_index = highlight.index;
11296 match highlight.color {
11297 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11298 None => unique_rows.remove(&DisplayRow(row)),
11299 };
11300 }
11301 }
11302 unique_rows
11303 },
11304 )
11305 }
11306
11307 pub fn highlighted_display_row_for_autoscroll(
11308 &self,
11309 snapshot: &DisplaySnapshot,
11310 ) -> Option<DisplayRow> {
11311 self.highlighted_rows
11312 .values()
11313 .flat_map(|highlighted_rows| highlighted_rows.iter())
11314 .filter_map(|highlight| {
11315 if highlight.color.is_none() || !highlight.should_autoscroll {
11316 return None;
11317 }
11318 Some(highlight.range.start().to_display_point(snapshot).row())
11319 })
11320 .min()
11321 }
11322
11323 pub fn set_search_within_ranges(
11324 &mut self,
11325 ranges: &[Range<Anchor>],
11326 cx: &mut ViewContext<Self>,
11327 ) {
11328 self.highlight_background::<SearchWithinRange>(
11329 ranges,
11330 |colors| colors.editor_document_highlight_read_background,
11331 cx,
11332 )
11333 }
11334
11335 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11336 self.breadcrumb_header = Some(new_header);
11337 }
11338
11339 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11340 self.clear_background_highlights::<SearchWithinRange>(cx);
11341 }
11342
11343 pub fn highlight_background<T: 'static>(
11344 &mut self,
11345 ranges: &[Range<Anchor>],
11346 color_fetcher: fn(&ThemeColors) -> Hsla,
11347 cx: &mut ViewContext<Self>,
11348 ) {
11349 self.background_highlights
11350 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11351 self.scrollbar_marker_state.dirty = true;
11352 cx.notify();
11353 }
11354
11355 pub fn clear_background_highlights<T: 'static>(
11356 &mut self,
11357 cx: &mut ViewContext<Self>,
11358 ) -> Option<BackgroundHighlight> {
11359 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11360 if !text_highlights.1.is_empty() {
11361 self.scrollbar_marker_state.dirty = true;
11362 cx.notify();
11363 }
11364 Some(text_highlights)
11365 }
11366
11367 pub fn highlight_gutter<T: 'static>(
11368 &mut self,
11369 ranges: &[Range<Anchor>],
11370 color_fetcher: fn(&AppContext) -> Hsla,
11371 cx: &mut ViewContext<Self>,
11372 ) {
11373 self.gutter_highlights
11374 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11375 cx.notify();
11376 }
11377
11378 pub fn clear_gutter_highlights<T: 'static>(
11379 &mut self,
11380 cx: &mut ViewContext<Self>,
11381 ) -> Option<GutterHighlight> {
11382 cx.notify();
11383 self.gutter_highlights.remove(&TypeId::of::<T>())
11384 }
11385
11386 #[cfg(feature = "test-support")]
11387 pub fn all_text_background_highlights(
11388 &mut self,
11389 cx: &mut ViewContext<Self>,
11390 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11391 let snapshot = self.snapshot(cx);
11392 let buffer = &snapshot.buffer_snapshot;
11393 let start = buffer.anchor_before(0);
11394 let end = buffer.anchor_after(buffer.len());
11395 let theme = cx.theme().colors();
11396 self.background_highlights_in_range(start..end, &snapshot, theme)
11397 }
11398
11399 #[cfg(feature = "test-support")]
11400 pub fn search_background_highlights(
11401 &mut self,
11402 cx: &mut ViewContext<Self>,
11403 ) -> Vec<Range<Point>> {
11404 let snapshot = self.buffer().read(cx).snapshot(cx);
11405
11406 let highlights = self
11407 .background_highlights
11408 .get(&TypeId::of::<items::BufferSearchHighlights>());
11409
11410 if let Some((_color, ranges)) = highlights {
11411 ranges
11412 .iter()
11413 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11414 .collect_vec()
11415 } else {
11416 vec![]
11417 }
11418 }
11419
11420 fn document_highlights_for_position<'a>(
11421 &'a self,
11422 position: Anchor,
11423 buffer: &'a MultiBufferSnapshot,
11424 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11425 let read_highlights = self
11426 .background_highlights
11427 .get(&TypeId::of::<DocumentHighlightRead>())
11428 .map(|h| &h.1);
11429 let write_highlights = self
11430 .background_highlights
11431 .get(&TypeId::of::<DocumentHighlightWrite>())
11432 .map(|h| &h.1);
11433 let left_position = position.bias_left(buffer);
11434 let right_position = position.bias_right(buffer);
11435 read_highlights
11436 .into_iter()
11437 .chain(write_highlights)
11438 .flat_map(move |ranges| {
11439 let start_ix = match ranges.binary_search_by(|probe| {
11440 let cmp = probe.end.cmp(&left_position, buffer);
11441 if cmp.is_ge() {
11442 Ordering::Greater
11443 } else {
11444 Ordering::Less
11445 }
11446 }) {
11447 Ok(i) | Err(i) => i,
11448 };
11449
11450 ranges[start_ix..]
11451 .iter()
11452 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11453 })
11454 }
11455
11456 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11457 self.background_highlights
11458 .get(&TypeId::of::<T>())
11459 .map_or(false, |(_, highlights)| !highlights.is_empty())
11460 }
11461
11462 pub fn background_highlights_in_range(
11463 &self,
11464 search_range: Range<Anchor>,
11465 display_snapshot: &DisplaySnapshot,
11466 theme: &ThemeColors,
11467 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11468 let mut results = Vec::new();
11469 for (color_fetcher, ranges) in self.background_highlights.values() {
11470 let color = color_fetcher(theme);
11471 let start_ix = match ranges.binary_search_by(|probe| {
11472 let cmp = probe
11473 .end
11474 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11475 if cmp.is_gt() {
11476 Ordering::Greater
11477 } else {
11478 Ordering::Less
11479 }
11480 }) {
11481 Ok(i) | Err(i) => i,
11482 };
11483 for range in &ranges[start_ix..] {
11484 if range
11485 .start
11486 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11487 .is_ge()
11488 {
11489 break;
11490 }
11491
11492 let start = range.start.to_display_point(display_snapshot);
11493 let end = range.end.to_display_point(display_snapshot);
11494 results.push((start..end, color))
11495 }
11496 }
11497 results
11498 }
11499
11500 pub fn background_highlight_row_ranges<T: 'static>(
11501 &self,
11502 search_range: Range<Anchor>,
11503 display_snapshot: &DisplaySnapshot,
11504 count: usize,
11505 ) -> Vec<RangeInclusive<DisplayPoint>> {
11506 let mut results = Vec::new();
11507 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11508 return vec![];
11509 };
11510
11511 let start_ix = match ranges.binary_search_by(|probe| {
11512 let cmp = probe
11513 .end
11514 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11515 if cmp.is_gt() {
11516 Ordering::Greater
11517 } else {
11518 Ordering::Less
11519 }
11520 }) {
11521 Ok(i) | Err(i) => i,
11522 };
11523 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11524 if let (Some(start_display), Some(end_display)) = (start, end) {
11525 results.push(
11526 start_display.to_display_point(display_snapshot)
11527 ..=end_display.to_display_point(display_snapshot),
11528 );
11529 }
11530 };
11531 let mut start_row: Option<Point> = None;
11532 let mut end_row: Option<Point> = None;
11533 if ranges.len() > count {
11534 return Vec::new();
11535 }
11536 for range in &ranges[start_ix..] {
11537 if range
11538 .start
11539 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11540 .is_ge()
11541 {
11542 break;
11543 }
11544 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11545 if let Some(current_row) = &end_row {
11546 if end.row == current_row.row {
11547 continue;
11548 }
11549 }
11550 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11551 if start_row.is_none() {
11552 assert_eq!(end_row, None);
11553 start_row = Some(start);
11554 end_row = Some(end);
11555 continue;
11556 }
11557 if let Some(current_end) = end_row.as_mut() {
11558 if start.row > current_end.row + 1 {
11559 push_region(start_row, end_row);
11560 start_row = Some(start);
11561 end_row = Some(end);
11562 } else {
11563 // Merge two hunks.
11564 *current_end = end;
11565 }
11566 } else {
11567 unreachable!();
11568 }
11569 }
11570 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11571 push_region(start_row, end_row);
11572 results
11573 }
11574
11575 pub fn gutter_highlights_in_range(
11576 &self,
11577 search_range: Range<Anchor>,
11578 display_snapshot: &DisplaySnapshot,
11579 cx: &AppContext,
11580 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11581 let mut results = Vec::new();
11582 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11583 let color = color_fetcher(cx);
11584 let start_ix = match ranges.binary_search_by(|probe| {
11585 let cmp = probe
11586 .end
11587 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11588 if cmp.is_gt() {
11589 Ordering::Greater
11590 } else {
11591 Ordering::Less
11592 }
11593 }) {
11594 Ok(i) | Err(i) => i,
11595 };
11596 for range in &ranges[start_ix..] {
11597 if range
11598 .start
11599 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11600 .is_ge()
11601 {
11602 break;
11603 }
11604
11605 let start = range.start.to_display_point(display_snapshot);
11606 let end = range.end.to_display_point(display_snapshot);
11607 results.push((start..end, color))
11608 }
11609 }
11610 results
11611 }
11612
11613 /// Get the text ranges corresponding to the redaction query
11614 pub fn redacted_ranges(
11615 &self,
11616 search_range: Range<Anchor>,
11617 display_snapshot: &DisplaySnapshot,
11618 cx: &WindowContext,
11619 ) -> Vec<Range<DisplayPoint>> {
11620 display_snapshot
11621 .buffer_snapshot
11622 .redacted_ranges(search_range, |file| {
11623 if let Some(file) = file {
11624 file.is_private()
11625 && EditorSettings::get(
11626 Some(SettingsLocation {
11627 worktree_id: file.worktree_id(cx),
11628 path: file.path().as_ref(),
11629 }),
11630 cx,
11631 )
11632 .redact_private_values
11633 } else {
11634 false
11635 }
11636 })
11637 .map(|range| {
11638 range.start.to_display_point(display_snapshot)
11639 ..range.end.to_display_point(display_snapshot)
11640 })
11641 .collect()
11642 }
11643
11644 pub fn highlight_text<T: 'static>(
11645 &mut self,
11646 ranges: Vec<Range<Anchor>>,
11647 style: HighlightStyle,
11648 cx: &mut ViewContext<Self>,
11649 ) {
11650 self.display_map.update(cx, |map, _| {
11651 map.highlight_text(TypeId::of::<T>(), ranges, style)
11652 });
11653 cx.notify();
11654 }
11655
11656 pub(crate) fn highlight_inlays<T: 'static>(
11657 &mut self,
11658 highlights: Vec<InlayHighlight>,
11659 style: HighlightStyle,
11660 cx: &mut ViewContext<Self>,
11661 ) {
11662 self.display_map.update(cx, |map, _| {
11663 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11664 });
11665 cx.notify();
11666 }
11667
11668 pub fn text_highlights<'a, T: 'static>(
11669 &'a self,
11670 cx: &'a AppContext,
11671 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11672 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11673 }
11674
11675 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11676 let cleared = self
11677 .display_map
11678 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11679 if cleared {
11680 cx.notify();
11681 }
11682 }
11683
11684 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11685 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11686 && self.focus_handle.is_focused(cx)
11687 }
11688
11689 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11690 self.show_cursor_when_unfocused = is_enabled;
11691 cx.notify();
11692 }
11693
11694 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11695 cx.notify();
11696 }
11697
11698 fn on_buffer_event(
11699 &mut self,
11700 multibuffer: Model<MultiBuffer>,
11701 event: &multi_buffer::Event,
11702 cx: &mut ViewContext<Self>,
11703 ) {
11704 match event {
11705 multi_buffer::Event::Edited {
11706 singleton_buffer_edited,
11707 } => {
11708 self.scrollbar_marker_state.dirty = true;
11709 self.active_indent_guides_state.dirty = true;
11710 self.refresh_active_diagnostics(cx);
11711 self.refresh_code_actions(cx);
11712 if self.has_active_inline_completion(cx) {
11713 self.update_visible_inline_completion(cx);
11714 }
11715 cx.emit(EditorEvent::BufferEdited);
11716 cx.emit(SearchEvent::MatchesInvalidated);
11717 if *singleton_buffer_edited {
11718 if let Some(project) = &self.project {
11719 let project = project.read(cx);
11720 #[allow(clippy::mutable_key_type)]
11721 let languages_affected = multibuffer
11722 .read(cx)
11723 .all_buffers()
11724 .into_iter()
11725 .filter_map(|buffer| {
11726 let buffer = buffer.read(cx);
11727 let language = buffer.language()?;
11728 if project.is_local_or_ssh()
11729 && project.language_servers_for_buffer(buffer, cx).count() == 0
11730 {
11731 None
11732 } else {
11733 Some(language)
11734 }
11735 })
11736 .cloned()
11737 .collect::<HashSet<_>>();
11738 if !languages_affected.is_empty() {
11739 self.refresh_inlay_hints(
11740 InlayHintRefreshReason::BufferEdited(languages_affected),
11741 cx,
11742 );
11743 }
11744 }
11745 }
11746
11747 let Some(project) = &self.project else { return };
11748 let telemetry = project.read(cx).client().telemetry().clone();
11749 refresh_linked_ranges(self, cx);
11750 telemetry.log_edit_event("editor");
11751 }
11752 multi_buffer::Event::ExcerptsAdded {
11753 buffer,
11754 predecessor,
11755 excerpts,
11756 } => {
11757 self.tasks_update_task = Some(self.refresh_runnables(cx));
11758 cx.emit(EditorEvent::ExcerptsAdded {
11759 buffer: buffer.clone(),
11760 predecessor: *predecessor,
11761 excerpts: excerpts.clone(),
11762 });
11763 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11764 }
11765 multi_buffer::Event::ExcerptsRemoved { ids } => {
11766 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11767 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11768 }
11769 multi_buffer::Event::ExcerptsEdited { ids } => {
11770 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11771 }
11772 multi_buffer::Event::ExcerptsExpanded { ids } => {
11773 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11774 }
11775 multi_buffer::Event::Reparsed(buffer_id) => {
11776 self.tasks_update_task = Some(self.refresh_runnables(cx));
11777
11778 cx.emit(EditorEvent::Reparsed(*buffer_id));
11779 }
11780 multi_buffer::Event::LanguageChanged(buffer_id) => {
11781 linked_editing_ranges::refresh_linked_ranges(self, cx);
11782 cx.emit(EditorEvent::Reparsed(*buffer_id));
11783 cx.notify();
11784 }
11785 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11786 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11787 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11788 cx.emit(EditorEvent::TitleChanged)
11789 }
11790 multi_buffer::Event::DiffBaseChanged => {
11791 self.scrollbar_marker_state.dirty = true;
11792 cx.emit(EditorEvent::DiffBaseChanged);
11793 cx.notify();
11794 }
11795 multi_buffer::Event::DiffUpdated { buffer } => {
11796 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11797 cx.notify();
11798 }
11799 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11800 multi_buffer::Event::DiagnosticsUpdated => {
11801 self.refresh_active_diagnostics(cx);
11802 self.scrollbar_marker_state.dirty = true;
11803 cx.notify();
11804 }
11805 _ => {}
11806 };
11807 }
11808
11809 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11810 cx.notify();
11811 }
11812
11813 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11814 self.tasks_update_task = Some(self.refresh_runnables(cx));
11815 self.refresh_inline_completion(true, false, cx);
11816 self.refresh_inlay_hints(
11817 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11818 self.selections.newest_anchor().head(),
11819 &self.buffer.read(cx).snapshot(cx),
11820 cx,
11821 )),
11822 cx,
11823 );
11824 let editor_settings = EditorSettings::get_global(cx);
11825 if let Some(cursor_shape) = editor_settings.cursor_shape {
11826 self.cursor_shape = cursor_shape;
11827 }
11828 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11829 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11830
11831 let project_settings = ProjectSettings::get_global(cx);
11832 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11833
11834 if self.mode == EditorMode::Full {
11835 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11836 if self.git_blame_inline_enabled != inline_blame_enabled {
11837 self.toggle_git_blame_inline_internal(false, cx);
11838 }
11839 }
11840
11841 cx.notify();
11842 }
11843
11844 pub fn set_searchable(&mut self, searchable: bool) {
11845 self.searchable = searchable;
11846 }
11847
11848 pub fn searchable(&self) -> bool {
11849 self.searchable
11850 }
11851
11852 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11853 self.open_excerpts_common(true, cx)
11854 }
11855
11856 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11857 self.open_excerpts_common(false, cx)
11858 }
11859
11860 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11861 let buffer = self.buffer.read(cx);
11862 if buffer.is_singleton() {
11863 cx.propagate();
11864 return;
11865 }
11866
11867 let Some(workspace) = self.workspace() else {
11868 cx.propagate();
11869 return;
11870 };
11871
11872 let mut new_selections_by_buffer = HashMap::default();
11873 for selection in self.selections.all::<usize>(cx) {
11874 for (buffer, mut range, _) in
11875 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11876 {
11877 if selection.reversed {
11878 mem::swap(&mut range.start, &mut range.end);
11879 }
11880 new_selections_by_buffer
11881 .entry(buffer)
11882 .or_insert(Vec::new())
11883 .push(range)
11884 }
11885 }
11886
11887 // We defer the pane interaction because we ourselves are a workspace item
11888 // and activating a new item causes the pane to call a method on us reentrantly,
11889 // which panics if we're on the stack.
11890 cx.window_context().defer(move |cx| {
11891 workspace.update(cx, |workspace, cx| {
11892 let pane = if split {
11893 workspace.adjacent_pane(cx)
11894 } else {
11895 workspace.active_pane().clone()
11896 };
11897
11898 for (buffer, ranges) in new_selections_by_buffer {
11899 let editor =
11900 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11901 editor.update(cx, |editor, cx| {
11902 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11903 s.select_ranges(ranges);
11904 });
11905 });
11906 }
11907 })
11908 });
11909 }
11910
11911 fn jump(
11912 &mut self,
11913 path: ProjectPath,
11914 position: Point,
11915 anchor: language::Anchor,
11916 offset_from_top: u32,
11917 cx: &mut ViewContext<Self>,
11918 ) {
11919 let workspace = self.workspace();
11920 cx.spawn(|_, mut cx| async move {
11921 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11922 let editor = workspace.update(&mut cx, |workspace, cx| {
11923 // Reset the preview item id before opening the new item
11924 workspace.active_pane().update(cx, |pane, cx| {
11925 pane.set_preview_item_id(None, cx);
11926 });
11927 workspace.open_path_preview(path, None, true, true, cx)
11928 })?;
11929 let editor = editor
11930 .await?
11931 .downcast::<Editor>()
11932 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11933 .downgrade();
11934 editor.update(&mut cx, |editor, cx| {
11935 let buffer = editor
11936 .buffer()
11937 .read(cx)
11938 .as_singleton()
11939 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11940 let buffer = buffer.read(cx);
11941 let cursor = if buffer.can_resolve(&anchor) {
11942 language::ToPoint::to_point(&anchor, buffer)
11943 } else {
11944 buffer.clip_point(position, Bias::Left)
11945 };
11946
11947 let nav_history = editor.nav_history.take();
11948 editor.change_selections(
11949 Some(Autoscroll::top_relative(offset_from_top as usize)),
11950 cx,
11951 |s| {
11952 s.select_ranges([cursor..cursor]);
11953 },
11954 );
11955 editor.nav_history = nav_history;
11956
11957 anyhow::Ok(())
11958 })??;
11959
11960 anyhow::Ok(())
11961 })
11962 .detach_and_log_err(cx);
11963 }
11964
11965 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11966 let snapshot = self.buffer.read(cx).read(cx);
11967 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11968 Some(
11969 ranges
11970 .iter()
11971 .map(move |range| {
11972 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11973 })
11974 .collect(),
11975 )
11976 }
11977
11978 fn selection_replacement_ranges(
11979 &self,
11980 range: Range<OffsetUtf16>,
11981 cx: &AppContext,
11982 ) -> Vec<Range<OffsetUtf16>> {
11983 let selections = self.selections.all::<OffsetUtf16>(cx);
11984 let newest_selection = selections
11985 .iter()
11986 .max_by_key(|selection| selection.id)
11987 .unwrap();
11988 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11989 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11990 let snapshot = self.buffer.read(cx).read(cx);
11991 selections
11992 .into_iter()
11993 .map(|mut selection| {
11994 selection.start.0 =
11995 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11996 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11997 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11998 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11999 })
12000 .collect()
12001 }
12002
12003 fn report_editor_event(
12004 &self,
12005 operation: &'static str,
12006 file_extension: Option<String>,
12007 cx: &AppContext,
12008 ) {
12009 if cfg!(any(test, feature = "test-support")) {
12010 return;
12011 }
12012
12013 let Some(project) = &self.project else { return };
12014
12015 // If None, we are in a file without an extension
12016 let file = self
12017 .buffer
12018 .read(cx)
12019 .as_singleton()
12020 .and_then(|b| b.read(cx).file());
12021 let file_extension = file_extension.or(file
12022 .as_ref()
12023 .and_then(|file| Path::new(file.file_name(cx)).extension())
12024 .and_then(|e| e.to_str())
12025 .map(|a| a.to_string()));
12026
12027 let vim_mode = cx
12028 .global::<SettingsStore>()
12029 .raw_user_settings()
12030 .get("vim_mode")
12031 == Some(&serde_json::Value::Bool(true));
12032
12033 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12034 == language::language_settings::InlineCompletionProvider::Copilot;
12035 let copilot_enabled_for_language = self
12036 .buffer
12037 .read(cx)
12038 .settings_at(0, cx)
12039 .show_inline_completions;
12040
12041 let telemetry = project.read(cx).client().telemetry().clone();
12042 telemetry.report_editor_event(
12043 file_extension,
12044 vim_mode,
12045 operation,
12046 copilot_enabled,
12047 copilot_enabled_for_language,
12048 )
12049 }
12050
12051 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12052 /// with each line being an array of {text, highlight} objects.
12053 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12054 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12055 return;
12056 };
12057
12058 #[derive(Serialize)]
12059 struct Chunk<'a> {
12060 text: String,
12061 highlight: Option<&'a str>,
12062 }
12063
12064 let snapshot = buffer.read(cx).snapshot();
12065 let range = self
12066 .selected_text_range(false, cx)
12067 .and_then(|selection| {
12068 if selection.range.is_empty() {
12069 None
12070 } else {
12071 Some(selection.range)
12072 }
12073 })
12074 .unwrap_or_else(|| 0..snapshot.len());
12075
12076 let chunks = snapshot.chunks(range, true);
12077 let mut lines = Vec::new();
12078 let mut line: VecDeque<Chunk> = VecDeque::new();
12079
12080 let Some(style) = self.style.as_ref() else {
12081 return;
12082 };
12083
12084 for chunk in chunks {
12085 let highlight = chunk
12086 .syntax_highlight_id
12087 .and_then(|id| id.name(&style.syntax));
12088 let mut chunk_lines = chunk.text.split('\n').peekable();
12089 while let Some(text) = chunk_lines.next() {
12090 let mut merged_with_last_token = false;
12091 if let Some(last_token) = line.back_mut() {
12092 if last_token.highlight == highlight {
12093 last_token.text.push_str(text);
12094 merged_with_last_token = true;
12095 }
12096 }
12097
12098 if !merged_with_last_token {
12099 line.push_back(Chunk {
12100 text: text.into(),
12101 highlight,
12102 });
12103 }
12104
12105 if chunk_lines.peek().is_some() {
12106 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12107 line.pop_front();
12108 }
12109 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12110 line.pop_back();
12111 }
12112
12113 lines.push(mem::take(&mut line));
12114 }
12115 }
12116 }
12117
12118 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12119 return;
12120 };
12121 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12122 }
12123
12124 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12125 &self.inlay_hint_cache
12126 }
12127
12128 pub fn replay_insert_event(
12129 &mut self,
12130 text: &str,
12131 relative_utf16_range: Option<Range<isize>>,
12132 cx: &mut ViewContext<Self>,
12133 ) {
12134 if !self.input_enabled {
12135 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12136 return;
12137 }
12138 if let Some(relative_utf16_range) = relative_utf16_range {
12139 let selections = self.selections.all::<OffsetUtf16>(cx);
12140 self.change_selections(None, cx, |s| {
12141 let new_ranges = selections.into_iter().map(|range| {
12142 let start = OffsetUtf16(
12143 range
12144 .head()
12145 .0
12146 .saturating_add_signed(relative_utf16_range.start),
12147 );
12148 let end = OffsetUtf16(
12149 range
12150 .head()
12151 .0
12152 .saturating_add_signed(relative_utf16_range.end),
12153 );
12154 start..end
12155 });
12156 s.select_ranges(new_ranges);
12157 });
12158 }
12159
12160 self.handle_input(text, cx);
12161 }
12162
12163 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12164 let Some(project) = self.project.as_ref() else {
12165 return false;
12166 };
12167 let project = project.read(cx);
12168
12169 let mut supports = false;
12170 self.buffer().read(cx).for_each_buffer(|buffer| {
12171 if !supports {
12172 supports = project
12173 .language_servers_for_buffer(buffer.read(cx), cx)
12174 .any(
12175 |(_, server)| match server.capabilities().inlay_hint_provider {
12176 Some(lsp::OneOf::Left(enabled)) => enabled,
12177 Some(lsp::OneOf::Right(_)) => true,
12178 None => false,
12179 },
12180 )
12181 }
12182 });
12183 supports
12184 }
12185
12186 pub fn focus(&self, cx: &mut WindowContext) {
12187 cx.focus(&self.focus_handle)
12188 }
12189
12190 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12191 self.focus_handle.is_focused(cx)
12192 }
12193
12194 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12195 cx.emit(EditorEvent::Focused);
12196
12197 if let Some(descendant) = self
12198 .last_focused_descendant
12199 .take()
12200 .and_then(|descendant| descendant.upgrade())
12201 {
12202 cx.focus(&descendant);
12203 } else {
12204 if let Some(blame) = self.blame.as_ref() {
12205 blame.update(cx, GitBlame::focus)
12206 }
12207
12208 self.blink_manager.update(cx, BlinkManager::enable);
12209 self.show_cursor_names(cx);
12210 self.buffer.update(cx, |buffer, cx| {
12211 buffer.finalize_last_transaction(cx);
12212 if self.leader_peer_id.is_none() {
12213 buffer.set_active_selections(
12214 &self.selections.disjoint_anchors(),
12215 self.selections.line_mode,
12216 self.cursor_shape,
12217 cx,
12218 );
12219 }
12220 });
12221 }
12222 }
12223
12224 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12225 cx.emit(EditorEvent::FocusedIn)
12226 }
12227
12228 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12229 if event.blurred != self.focus_handle {
12230 self.last_focused_descendant = Some(event.blurred);
12231 }
12232 }
12233
12234 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12235 self.blink_manager.update(cx, BlinkManager::disable);
12236 self.buffer
12237 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12238
12239 if let Some(blame) = self.blame.as_ref() {
12240 blame.update(cx, GitBlame::blur)
12241 }
12242 if !self.hover_state.focused(cx) {
12243 hide_hover(self, cx);
12244 }
12245
12246 self.hide_context_menu(cx);
12247 cx.emit(EditorEvent::Blurred);
12248 cx.notify();
12249 }
12250
12251 pub fn register_action<A: Action>(
12252 &mut self,
12253 listener: impl Fn(&A, &mut WindowContext) + 'static,
12254 ) -> Subscription {
12255 let id = self.next_editor_action_id.post_inc();
12256 let listener = Arc::new(listener);
12257 self.editor_actions.borrow_mut().insert(
12258 id,
12259 Box::new(move |cx| {
12260 let cx = cx.window_context();
12261 let listener = listener.clone();
12262 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12263 let action = action.downcast_ref().unwrap();
12264 if phase == DispatchPhase::Bubble {
12265 listener(action, cx)
12266 }
12267 })
12268 }),
12269 );
12270
12271 let editor_actions = self.editor_actions.clone();
12272 Subscription::new(move || {
12273 editor_actions.borrow_mut().remove(&id);
12274 })
12275 }
12276
12277 pub fn file_header_size(&self) -> u32 {
12278 self.file_header_size
12279 }
12280
12281 pub fn revert(
12282 &mut self,
12283 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12284 cx: &mut ViewContext<Self>,
12285 ) {
12286 self.buffer().update(cx, |multi_buffer, cx| {
12287 for (buffer_id, changes) in revert_changes {
12288 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12289 buffer.update(cx, |buffer, cx| {
12290 buffer.edit(
12291 changes.into_iter().map(|(range, text)| {
12292 (range, text.to_string().map(Arc::<str>::from))
12293 }),
12294 None,
12295 cx,
12296 );
12297 });
12298 }
12299 }
12300 });
12301 self.change_selections(None, cx, |selections| selections.refresh());
12302 }
12303
12304 pub fn to_pixel_point(
12305 &mut self,
12306 source: multi_buffer::Anchor,
12307 editor_snapshot: &EditorSnapshot,
12308 cx: &mut ViewContext<Self>,
12309 ) -> Option<gpui::Point<Pixels>> {
12310 let source_point = source.to_display_point(editor_snapshot);
12311 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12312 }
12313
12314 pub fn display_to_pixel_point(
12315 &mut self,
12316 source: DisplayPoint,
12317 editor_snapshot: &EditorSnapshot,
12318 cx: &mut ViewContext<Self>,
12319 ) -> Option<gpui::Point<Pixels>> {
12320 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12321 let text_layout_details = self.text_layout_details(cx);
12322 let scroll_top = text_layout_details
12323 .scroll_anchor
12324 .scroll_position(editor_snapshot)
12325 .y;
12326
12327 if source.row().as_f32() < scroll_top.floor() {
12328 return None;
12329 }
12330 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12331 let source_y = line_height * (source.row().as_f32() - scroll_top);
12332 Some(gpui::Point::new(source_x, source_y))
12333 }
12334
12335 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12336 let bounds = self.last_bounds?;
12337 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12338 }
12339
12340 pub fn has_active_completions_menu(&self) -> bool {
12341 self.context_menu.read().as_ref().map_or(false, |menu| {
12342 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12343 })
12344 }
12345
12346 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12347 self.addons
12348 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12349 }
12350
12351 pub fn unregister_addon<T: Addon>(&mut self) {
12352 self.addons.remove(&std::any::TypeId::of::<T>());
12353 }
12354
12355 pub fn addon<T: Addon>(&self) -> Option<&T> {
12356 let type_id = std::any::TypeId::of::<T>();
12357 self.addons
12358 .get(&type_id)
12359 .and_then(|item| item.to_any().downcast_ref::<T>())
12360 }
12361}
12362
12363fn hunks_for_selections(
12364 multi_buffer_snapshot: &MultiBufferSnapshot,
12365 selections: &[Selection<Anchor>],
12366) -> Vec<DiffHunk<MultiBufferRow>> {
12367 let buffer_rows_for_selections = selections.iter().map(|selection| {
12368 let head = selection.head();
12369 let tail = selection.tail();
12370 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12371 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12372 if start > end {
12373 end..start
12374 } else {
12375 start..end
12376 }
12377 });
12378
12379 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12380}
12381
12382pub fn hunks_for_rows(
12383 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12384 multi_buffer_snapshot: &MultiBufferSnapshot,
12385) -> Vec<DiffHunk<MultiBufferRow>> {
12386 let mut hunks = Vec::new();
12387 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12388 HashMap::default();
12389 for selected_multi_buffer_rows in rows {
12390 let query_rows =
12391 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12392 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12393 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12394 // when the caret is just above or just below the deleted hunk.
12395 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12396 let related_to_selection = if allow_adjacent {
12397 hunk.associated_range.overlaps(&query_rows)
12398 || hunk.associated_range.start == query_rows.end
12399 || hunk.associated_range.end == query_rows.start
12400 } else {
12401 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12402 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12403 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12404 || selected_multi_buffer_rows.end == hunk.associated_range.start
12405 };
12406 if related_to_selection {
12407 if !processed_buffer_rows
12408 .entry(hunk.buffer_id)
12409 .or_default()
12410 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12411 {
12412 continue;
12413 }
12414 hunks.push(hunk);
12415 }
12416 }
12417 }
12418
12419 hunks
12420}
12421
12422pub trait CollaborationHub {
12423 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12424 fn user_participant_indices<'a>(
12425 &self,
12426 cx: &'a AppContext,
12427 ) -> &'a HashMap<u64, ParticipantIndex>;
12428 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12429}
12430
12431impl CollaborationHub for Model<Project> {
12432 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12433 self.read(cx).collaborators()
12434 }
12435
12436 fn user_participant_indices<'a>(
12437 &self,
12438 cx: &'a AppContext,
12439 ) -> &'a HashMap<u64, ParticipantIndex> {
12440 self.read(cx).user_store().read(cx).participant_indices()
12441 }
12442
12443 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12444 let this = self.read(cx);
12445 let user_ids = this.collaborators().values().map(|c| c.user_id);
12446 this.user_store().read_with(cx, |user_store, cx| {
12447 user_store.participant_names(user_ids, cx)
12448 })
12449 }
12450}
12451
12452pub trait CompletionProvider {
12453 fn completions(
12454 &self,
12455 buffer: &Model<Buffer>,
12456 buffer_position: text::Anchor,
12457 trigger: CompletionContext,
12458 cx: &mut ViewContext<Editor>,
12459 ) -> Task<Result<Vec<Completion>>>;
12460
12461 fn resolve_completions(
12462 &self,
12463 buffer: Model<Buffer>,
12464 completion_indices: Vec<usize>,
12465 completions: Arc<RwLock<Box<[Completion]>>>,
12466 cx: &mut ViewContext<Editor>,
12467 ) -> Task<Result<bool>>;
12468
12469 fn apply_additional_edits_for_completion(
12470 &self,
12471 buffer: Model<Buffer>,
12472 completion: Completion,
12473 push_to_history: bool,
12474 cx: &mut ViewContext<Editor>,
12475 ) -> Task<Result<Option<language::Transaction>>>;
12476
12477 fn is_completion_trigger(
12478 &self,
12479 buffer: &Model<Buffer>,
12480 position: language::Anchor,
12481 text: &str,
12482 trigger_in_words: bool,
12483 cx: &mut ViewContext<Editor>,
12484 ) -> bool;
12485
12486 fn sort_completions(&self) -> bool {
12487 true
12488 }
12489}
12490
12491fn snippet_completions(
12492 project: &Project,
12493 buffer: &Model<Buffer>,
12494 buffer_position: text::Anchor,
12495 cx: &mut AppContext,
12496) -> Vec<Completion> {
12497 let language = buffer.read(cx).language_at(buffer_position);
12498 let language_name = language.as_ref().map(|language| language.lsp_id());
12499 let snippet_store = project.snippets().read(cx);
12500 let snippets = snippet_store.snippets_for(language_name, cx);
12501
12502 if snippets.is_empty() {
12503 return vec![];
12504 }
12505 let snapshot = buffer.read(cx).text_snapshot();
12506 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12507
12508 let mut lines = chunks.lines();
12509 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12510 return vec![];
12511 };
12512
12513 let scope = language.map(|language| language.default_scope());
12514 let classifier = CharClassifier::new(scope).for_completion(true);
12515 let mut last_word = line_at
12516 .chars()
12517 .rev()
12518 .take_while(|c| classifier.is_word(*c))
12519 .collect::<String>();
12520 last_word = last_word.chars().rev().collect();
12521 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12522 let to_lsp = |point: &text::Anchor| {
12523 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12524 point_to_lsp(end)
12525 };
12526 let lsp_end = to_lsp(&buffer_position);
12527 snippets
12528 .into_iter()
12529 .filter_map(|snippet| {
12530 let matching_prefix = snippet
12531 .prefix
12532 .iter()
12533 .find(|prefix| prefix.starts_with(&last_word))?;
12534 let start = as_offset - last_word.len();
12535 let start = snapshot.anchor_before(start);
12536 let range = start..buffer_position;
12537 let lsp_start = to_lsp(&start);
12538 let lsp_range = lsp::Range {
12539 start: lsp_start,
12540 end: lsp_end,
12541 };
12542 Some(Completion {
12543 old_range: range,
12544 new_text: snippet.body.clone(),
12545 label: CodeLabel {
12546 text: matching_prefix.clone(),
12547 runs: vec![],
12548 filter_range: 0..matching_prefix.len(),
12549 },
12550 server_id: LanguageServerId(usize::MAX),
12551 documentation: snippet.description.clone().map(Documentation::SingleLine),
12552 lsp_completion: lsp::CompletionItem {
12553 label: snippet.prefix.first().unwrap().clone(),
12554 kind: Some(CompletionItemKind::SNIPPET),
12555 label_details: snippet.description.as_ref().map(|description| {
12556 lsp::CompletionItemLabelDetails {
12557 detail: Some(description.clone()),
12558 description: None,
12559 }
12560 }),
12561 insert_text_format: Some(InsertTextFormat::SNIPPET),
12562 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12563 lsp::InsertReplaceEdit {
12564 new_text: snippet.body.clone(),
12565 insert: lsp_range,
12566 replace: lsp_range,
12567 },
12568 )),
12569 filter_text: Some(snippet.body.clone()),
12570 sort_text: Some(char::MAX.to_string()),
12571 ..Default::default()
12572 },
12573 confirm: None,
12574 })
12575 })
12576 .collect()
12577}
12578
12579impl CompletionProvider for Model<Project> {
12580 fn completions(
12581 &self,
12582 buffer: &Model<Buffer>,
12583 buffer_position: text::Anchor,
12584 options: CompletionContext,
12585 cx: &mut ViewContext<Editor>,
12586 ) -> Task<Result<Vec<Completion>>> {
12587 self.update(cx, |project, cx| {
12588 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12589 let project_completions = project.completions(buffer, buffer_position, options, cx);
12590 cx.background_executor().spawn(async move {
12591 let mut completions = project_completions.await?;
12592 //let snippets = snippets.into_iter().;
12593 completions.extend(snippets);
12594 Ok(completions)
12595 })
12596 })
12597 }
12598
12599 fn resolve_completions(
12600 &self,
12601 buffer: Model<Buffer>,
12602 completion_indices: Vec<usize>,
12603 completions: Arc<RwLock<Box<[Completion]>>>,
12604 cx: &mut ViewContext<Editor>,
12605 ) -> Task<Result<bool>> {
12606 self.update(cx, |project, cx| {
12607 project.resolve_completions(buffer, completion_indices, completions, cx)
12608 })
12609 }
12610
12611 fn apply_additional_edits_for_completion(
12612 &self,
12613 buffer: Model<Buffer>,
12614 completion: Completion,
12615 push_to_history: bool,
12616 cx: &mut ViewContext<Editor>,
12617 ) -> Task<Result<Option<language::Transaction>>> {
12618 self.update(cx, |project, cx| {
12619 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12620 })
12621 }
12622
12623 fn is_completion_trigger(
12624 &self,
12625 buffer: &Model<Buffer>,
12626 position: language::Anchor,
12627 text: &str,
12628 trigger_in_words: bool,
12629 cx: &mut ViewContext<Editor>,
12630 ) -> bool {
12631 if !EditorSettings::get_global(cx).show_completions_on_input {
12632 return false;
12633 }
12634
12635 let mut chars = text.chars();
12636 let char = if let Some(char) = chars.next() {
12637 char
12638 } else {
12639 return false;
12640 };
12641 if chars.next().is_some() {
12642 return false;
12643 }
12644
12645 let buffer = buffer.read(cx);
12646 let classifier = buffer
12647 .snapshot()
12648 .char_classifier_at(position)
12649 .for_completion(true);
12650 if trigger_in_words && classifier.is_word(char) {
12651 return true;
12652 }
12653
12654 buffer
12655 .completion_triggers()
12656 .iter()
12657 .any(|string| string == text)
12658 }
12659}
12660
12661fn inlay_hint_settings(
12662 location: Anchor,
12663 snapshot: &MultiBufferSnapshot,
12664 cx: &mut ViewContext<'_, Editor>,
12665) -> InlayHintSettings {
12666 let file = snapshot.file_at(location);
12667 let language = snapshot.language_at(location);
12668 let settings = all_language_settings(file, cx);
12669 settings
12670 .language(language.map(|l| l.name()).as_ref())
12671 .inlay_hints
12672}
12673
12674fn consume_contiguous_rows(
12675 contiguous_row_selections: &mut Vec<Selection<Point>>,
12676 selection: &Selection<Point>,
12677 display_map: &DisplaySnapshot,
12678 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12679) -> (MultiBufferRow, MultiBufferRow) {
12680 contiguous_row_selections.push(selection.clone());
12681 let start_row = MultiBufferRow(selection.start.row);
12682 let mut end_row = ending_row(selection, display_map);
12683
12684 while let Some(next_selection) = selections.peek() {
12685 if next_selection.start.row <= end_row.0 {
12686 end_row = ending_row(next_selection, display_map);
12687 contiguous_row_selections.push(selections.next().unwrap().clone());
12688 } else {
12689 break;
12690 }
12691 }
12692 (start_row, end_row)
12693}
12694
12695fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12696 if next_selection.end.column > 0 || next_selection.is_empty() {
12697 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12698 } else {
12699 MultiBufferRow(next_selection.end.row)
12700 }
12701}
12702
12703impl EditorSnapshot {
12704 pub fn remote_selections_in_range<'a>(
12705 &'a self,
12706 range: &'a Range<Anchor>,
12707 collaboration_hub: &dyn CollaborationHub,
12708 cx: &'a AppContext,
12709 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12710 let participant_names = collaboration_hub.user_names(cx);
12711 let participant_indices = collaboration_hub.user_participant_indices(cx);
12712 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12713 let collaborators_by_replica_id = collaborators_by_peer_id
12714 .iter()
12715 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12716 .collect::<HashMap<_, _>>();
12717 self.buffer_snapshot
12718 .selections_in_range(range, false)
12719 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12720 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12721 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12722 let user_name = participant_names.get(&collaborator.user_id).cloned();
12723 Some(RemoteSelection {
12724 replica_id,
12725 selection,
12726 cursor_shape,
12727 line_mode,
12728 participant_index,
12729 peer_id: collaborator.peer_id,
12730 user_name,
12731 })
12732 })
12733 }
12734
12735 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12736 self.display_snapshot.buffer_snapshot.language_at(position)
12737 }
12738
12739 pub fn is_focused(&self) -> bool {
12740 self.is_focused
12741 }
12742
12743 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12744 self.placeholder_text.as_ref()
12745 }
12746
12747 pub fn scroll_position(&self) -> gpui::Point<f32> {
12748 self.scroll_anchor.scroll_position(&self.display_snapshot)
12749 }
12750
12751 fn gutter_dimensions(
12752 &self,
12753 font_id: FontId,
12754 font_size: Pixels,
12755 em_width: Pixels,
12756 max_line_number_width: Pixels,
12757 cx: &AppContext,
12758 ) -> GutterDimensions {
12759 if !self.show_gutter {
12760 return GutterDimensions::default();
12761 }
12762 let descent = cx.text_system().descent(font_id, font_size);
12763
12764 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12765 matches!(
12766 ProjectSettings::get_global(cx).git.git_gutter,
12767 Some(GitGutterSetting::TrackedFiles)
12768 )
12769 });
12770 let gutter_settings = EditorSettings::get_global(cx).gutter;
12771 let show_line_numbers = self
12772 .show_line_numbers
12773 .unwrap_or(gutter_settings.line_numbers);
12774 let line_gutter_width = if show_line_numbers {
12775 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12776 let min_width_for_number_on_gutter = em_width * 4.0;
12777 max_line_number_width.max(min_width_for_number_on_gutter)
12778 } else {
12779 0.0.into()
12780 };
12781
12782 let show_code_actions = self
12783 .show_code_actions
12784 .unwrap_or(gutter_settings.code_actions);
12785
12786 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12787
12788 let git_blame_entries_width = self
12789 .render_git_blame_gutter
12790 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12791
12792 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12793 left_padding += if show_code_actions || show_runnables {
12794 em_width * 3.0
12795 } else if show_git_gutter && show_line_numbers {
12796 em_width * 2.0
12797 } else if show_git_gutter || show_line_numbers {
12798 em_width
12799 } else {
12800 px(0.)
12801 };
12802
12803 let right_padding = if gutter_settings.folds && show_line_numbers {
12804 em_width * 4.0
12805 } else if gutter_settings.folds {
12806 em_width * 3.0
12807 } else if show_line_numbers {
12808 em_width
12809 } else {
12810 px(0.)
12811 };
12812
12813 GutterDimensions {
12814 left_padding,
12815 right_padding,
12816 width: line_gutter_width + left_padding + right_padding,
12817 margin: -descent,
12818 git_blame_entries_width,
12819 }
12820 }
12821
12822 pub fn render_fold_toggle(
12823 &self,
12824 buffer_row: MultiBufferRow,
12825 row_contains_cursor: bool,
12826 editor: View<Editor>,
12827 cx: &mut WindowContext,
12828 ) -> Option<AnyElement> {
12829 let folded = self.is_line_folded(buffer_row);
12830
12831 if let Some(crease) = self
12832 .crease_snapshot
12833 .query_row(buffer_row, &self.buffer_snapshot)
12834 {
12835 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12836 if folded {
12837 editor.update(cx, |editor, cx| {
12838 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12839 });
12840 } else {
12841 editor.update(cx, |editor, cx| {
12842 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12843 });
12844 }
12845 });
12846
12847 Some((crease.render_toggle)(
12848 buffer_row,
12849 folded,
12850 toggle_callback,
12851 cx,
12852 ))
12853 } else if folded
12854 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12855 {
12856 Some(
12857 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12858 .selected(folded)
12859 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12860 if folded {
12861 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12862 } else {
12863 this.fold_at(&FoldAt { buffer_row }, cx);
12864 }
12865 }))
12866 .into_any_element(),
12867 )
12868 } else {
12869 None
12870 }
12871 }
12872
12873 pub fn render_crease_trailer(
12874 &self,
12875 buffer_row: MultiBufferRow,
12876 cx: &mut WindowContext,
12877 ) -> Option<AnyElement> {
12878 let folded = self.is_line_folded(buffer_row);
12879 let crease = self
12880 .crease_snapshot
12881 .query_row(buffer_row, &self.buffer_snapshot)?;
12882 Some((crease.render_trailer)(buffer_row, folded, cx))
12883 }
12884}
12885
12886impl Deref for EditorSnapshot {
12887 type Target = DisplaySnapshot;
12888
12889 fn deref(&self) -> &Self::Target {
12890 &self.display_snapshot
12891 }
12892}
12893
12894#[derive(Clone, Debug, PartialEq, Eq)]
12895pub enum EditorEvent {
12896 InputIgnored {
12897 text: Arc<str>,
12898 },
12899 InputHandled {
12900 utf16_range_to_replace: Option<Range<isize>>,
12901 text: Arc<str>,
12902 },
12903 ExcerptsAdded {
12904 buffer: Model<Buffer>,
12905 predecessor: ExcerptId,
12906 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12907 },
12908 ExcerptsRemoved {
12909 ids: Vec<ExcerptId>,
12910 },
12911 ExcerptsEdited {
12912 ids: Vec<ExcerptId>,
12913 },
12914 ExcerptsExpanded {
12915 ids: Vec<ExcerptId>,
12916 },
12917 BufferEdited,
12918 Edited {
12919 transaction_id: clock::Lamport,
12920 },
12921 Reparsed(BufferId),
12922 Focused,
12923 FocusedIn,
12924 Blurred,
12925 DirtyChanged,
12926 Saved,
12927 TitleChanged,
12928 DiffBaseChanged,
12929 SelectionsChanged {
12930 local: bool,
12931 },
12932 ScrollPositionChanged {
12933 local: bool,
12934 autoscroll: bool,
12935 },
12936 Closed,
12937 TransactionUndone {
12938 transaction_id: clock::Lamport,
12939 },
12940 TransactionBegun {
12941 transaction_id: clock::Lamport,
12942 },
12943}
12944
12945impl EventEmitter<EditorEvent> for Editor {}
12946
12947impl FocusableView for Editor {
12948 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12949 self.focus_handle.clone()
12950 }
12951}
12952
12953impl Render for Editor {
12954 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12955 let settings = ThemeSettings::get_global(cx);
12956
12957 let text_style = match self.mode {
12958 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12959 color: cx.theme().colors().editor_foreground,
12960 font_family: settings.ui_font.family.clone(),
12961 font_features: settings.ui_font.features.clone(),
12962 font_fallbacks: settings.ui_font.fallbacks.clone(),
12963 font_size: rems(0.875).into(),
12964 font_weight: settings.ui_font.weight,
12965 line_height: relative(settings.buffer_line_height.value()),
12966 ..Default::default()
12967 },
12968 EditorMode::Full => TextStyle {
12969 color: cx.theme().colors().editor_foreground,
12970 font_family: settings.buffer_font.family.clone(),
12971 font_features: settings.buffer_font.features.clone(),
12972 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12973 font_size: settings.buffer_font_size(cx).into(),
12974 font_weight: settings.buffer_font.weight,
12975 line_height: relative(settings.buffer_line_height.value()),
12976 ..Default::default()
12977 },
12978 };
12979
12980 let background = match self.mode {
12981 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12982 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12983 EditorMode::Full => cx.theme().colors().editor_background,
12984 };
12985
12986 EditorElement::new(
12987 cx.view(),
12988 EditorStyle {
12989 background,
12990 local_player: cx.theme().players().local(),
12991 text: text_style,
12992 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12993 syntax: cx.theme().syntax().clone(),
12994 status: cx.theme().status().clone(),
12995 inlay_hints_style: HighlightStyle {
12996 color: Some(cx.theme().status().hint),
12997 ..HighlightStyle::default()
12998 },
12999 suggestions_style: HighlightStyle {
13000 color: Some(cx.theme().status().predictive),
13001 ..HighlightStyle::default()
13002 },
13003 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13004 },
13005 )
13006 }
13007}
13008
13009impl ViewInputHandler for Editor {
13010 fn text_for_range(
13011 &mut self,
13012 range_utf16: Range<usize>,
13013 cx: &mut ViewContext<Self>,
13014 ) -> Option<String> {
13015 Some(
13016 self.buffer
13017 .read(cx)
13018 .read(cx)
13019 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13020 .collect(),
13021 )
13022 }
13023
13024 fn selected_text_range(
13025 &mut self,
13026 ignore_disabled_input: bool,
13027 cx: &mut ViewContext<Self>,
13028 ) -> Option<UTF16Selection> {
13029 // Prevent the IME menu from appearing when holding down an alphabetic key
13030 // while input is disabled.
13031 if !ignore_disabled_input && !self.input_enabled {
13032 return None;
13033 }
13034
13035 let selection = self.selections.newest::<OffsetUtf16>(cx);
13036 let range = selection.range();
13037
13038 Some(UTF16Selection {
13039 range: range.start.0..range.end.0,
13040 reversed: selection.reversed,
13041 })
13042 }
13043
13044 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13045 let snapshot = self.buffer.read(cx).read(cx);
13046 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13047 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13048 }
13049
13050 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13051 self.clear_highlights::<InputComposition>(cx);
13052 self.ime_transaction.take();
13053 }
13054
13055 fn replace_text_in_range(
13056 &mut self,
13057 range_utf16: Option<Range<usize>>,
13058 text: &str,
13059 cx: &mut ViewContext<Self>,
13060 ) {
13061 if !self.input_enabled {
13062 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13063 return;
13064 }
13065
13066 self.transact(cx, |this, cx| {
13067 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13068 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13069 Some(this.selection_replacement_ranges(range_utf16, cx))
13070 } else {
13071 this.marked_text_ranges(cx)
13072 };
13073
13074 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13075 let newest_selection_id = this.selections.newest_anchor().id;
13076 this.selections
13077 .all::<OffsetUtf16>(cx)
13078 .iter()
13079 .zip(ranges_to_replace.iter())
13080 .find_map(|(selection, range)| {
13081 if selection.id == newest_selection_id {
13082 Some(
13083 (range.start.0 as isize - selection.head().0 as isize)
13084 ..(range.end.0 as isize - selection.head().0 as isize),
13085 )
13086 } else {
13087 None
13088 }
13089 })
13090 });
13091
13092 cx.emit(EditorEvent::InputHandled {
13093 utf16_range_to_replace: range_to_replace,
13094 text: text.into(),
13095 });
13096
13097 if let Some(new_selected_ranges) = new_selected_ranges {
13098 this.change_selections(None, cx, |selections| {
13099 selections.select_ranges(new_selected_ranges)
13100 });
13101 this.backspace(&Default::default(), cx);
13102 }
13103
13104 this.handle_input(text, cx);
13105 });
13106
13107 if let Some(transaction) = self.ime_transaction {
13108 self.buffer.update(cx, |buffer, cx| {
13109 buffer.group_until_transaction(transaction, cx);
13110 });
13111 }
13112
13113 self.unmark_text(cx);
13114 }
13115
13116 fn replace_and_mark_text_in_range(
13117 &mut self,
13118 range_utf16: Option<Range<usize>>,
13119 text: &str,
13120 new_selected_range_utf16: Option<Range<usize>>,
13121 cx: &mut ViewContext<Self>,
13122 ) {
13123 if !self.input_enabled {
13124 return;
13125 }
13126
13127 let transaction = self.transact(cx, |this, cx| {
13128 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13129 let snapshot = this.buffer.read(cx).read(cx);
13130 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13131 for marked_range in &mut marked_ranges {
13132 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13133 marked_range.start.0 += relative_range_utf16.start;
13134 marked_range.start =
13135 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13136 marked_range.end =
13137 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13138 }
13139 }
13140 Some(marked_ranges)
13141 } else if let Some(range_utf16) = range_utf16 {
13142 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13143 Some(this.selection_replacement_ranges(range_utf16, cx))
13144 } else {
13145 None
13146 };
13147
13148 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13149 let newest_selection_id = this.selections.newest_anchor().id;
13150 this.selections
13151 .all::<OffsetUtf16>(cx)
13152 .iter()
13153 .zip(ranges_to_replace.iter())
13154 .find_map(|(selection, range)| {
13155 if selection.id == newest_selection_id {
13156 Some(
13157 (range.start.0 as isize - selection.head().0 as isize)
13158 ..(range.end.0 as isize - selection.head().0 as isize),
13159 )
13160 } else {
13161 None
13162 }
13163 })
13164 });
13165
13166 cx.emit(EditorEvent::InputHandled {
13167 utf16_range_to_replace: range_to_replace,
13168 text: text.into(),
13169 });
13170
13171 if let Some(ranges) = ranges_to_replace {
13172 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13173 }
13174
13175 let marked_ranges = {
13176 let snapshot = this.buffer.read(cx).read(cx);
13177 this.selections
13178 .disjoint_anchors()
13179 .iter()
13180 .map(|selection| {
13181 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13182 })
13183 .collect::<Vec<_>>()
13184 };
13185
13186 if text.is_empty() {
13187 this.unmark_text(cx);
13188 } else {
13189 this.highlight_text::<InputComposition>(
13190 marked_ranges.clone(),
13191 HighlightStyle {
13192 underline: Some(UnderlineStyle {
13193 thickness: px(1.),
13194 color: None,
13195 wavy: false,
13196 }),
13197 ..Default::default()
13198 },
13199 cx,
13200 );
13201 }
13202
13203 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13204 let use_autoclose = this.use_autoclose;
13205 let use_auto_surround = this.use_auto_surround;
13206 this.set_use_autoclose(false);
13207 this.set_use_auto_surround(false);
13208 this.handle_input(text, cx);
13209 this.set_use_autoclose(use_autoclose);
13210 this.set_use_auto_surround(use_auto_surround);
13211
13212 if let Some(new_selected_range) = new_selected_range_utf16 {
13213 let snapshot = this.buffer.read(cx).read(cx);
13214 let new_selected_ranges = marked_ranges
13215 .into_iter()
13216 .map(|marked_range| {
13217 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13218 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13219 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13220 snapshot.clip_offset_utf16(new_start, Bias::Left)
13221 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13222 })
13223 .collect::<Vec<_>>();
13224
13225 drop(snapshot);
13226 this.change_selections(None, cx, |selections| {
13227 selections.select_ranges(new_selected_ranges)
13228 });
13229 }
13230 });
13231
13232 self.ime_transaction = self.ime_transaction.or(transaction);
13233 if let Some(transaction) = self.ime_transaction {
13234 self.buffer.update(cx, |buffer, cx| {
13235 buffer.group_until_transaction(transaction, cx);
13236 });
13237 }
13238
13239 if self.text_highlights::<InputComposition>(cx).is_none() {
13240 self.ime_transaction.take();
13241 }
13242 }
13243
13244 fn bounds_for_range(
13245 &mut self,
13246 range_utf16: Range<usize>,
13247 element_bounds: gpui::Bounds<Pixels>,
13248 cx: &mut ViewContext<Self>,
13249 ) -> Option<gpui::Bounds<Pixels>> {
13250 let text_layout_details = self.text_layout_details(cx);
13251 let style = &text_layout_details.editor_style;
13252 let font_id = cx.text_system().resolve_font(&style.text.font());
13253 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13254 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13255
13256 let em_width = cx
13257 .text_system()
13258 .typographic_bounds(font_id, font_size, 'm')
13259 .unwrap()
13260 .size
13261 .width;
13262
13263 let snapshot = self.snapshot(cx);
13264 let scroll_position = snapshot.scroll_position();
13265 let scroll_left = scroll_position.x * em_width;
13266
13267 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13268 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13269 + self.gutter_dimensions.width;
13270 let y = line_height * (start.row().as_f32() - scroll_position.y);
13271
13272 Some(Bounds {
13273 origin: element_bounds.origin + point(x, y),
13274 size: size(em_width, line_height),
13275 })
13276 }
13277}
13278
13279trait SelectionExt {
13280 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13281 fn spanned_rows(
13282 &self,
13283 include_end_if_at_line_start: bool,
13284 map: &DisplaySnapshot,
13285 ) -> Range<MultiBufferRow>;
13286}
13287
13288impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13289 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13290 let start = self
13291 .start
13292 .to_point(&map.buffer_snapshot)
13293 .to_display_point(map);
13294 let end = self
13295 .end
13296 .to_point(&map.buffer_snapshot)
13297 .to_display_point(map);
13298 if self.reversed {
13299 end..start
13300 } else {
13301 start..end
13302 }
13303 }
13304
13305 fn spanned_rows(
13306 &self,
13307 include_end_if_at_line_start: bool,
13308 map: &DisplaySnapshot,
13309 ) -> Range<MultiBufferRow> {
13310 let start = self.start.to_point(&map.buffer_snapshot);
13311 let mut end = self.end.to_point(&map.buffer_snapshot);
13312 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13313 end.row -= 1;
13314 }
13315
13316 let buffer_start = map.prev_line_boundary(start).0;
13317 let buffer_end = map.next_line_boundary(end).0;
13318 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13319 }
13320}
13321
13322impl<T: InvalidationRegion> InvalidationStack<T> {
13323 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13324 where
13325 S: Clone + ToOffset,
13326 {
13327 while let Some(region) = self.last() {
13328 let all_selections_inside_invalidation_ranges =
13329 if selections.len() == region.ranges().len() {
13330 selections
13331 .iter()
13332 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13333 .all(|(selection, invalidation_range)| {
13334 let head = selection.head().to_offset(buffer);
13335 invalidation_range.start <= head && invalidation_range.end >= head
13336 })
13337 } else {
13338 false
13339 };
13340
13341 if all_selections_inside_invalidation_ranges {
13342 break;
13343 } else {
13344 self.pop();
13345 }
13346 }
13347 }
13348}
13349
13350impl<T> Default for InvalidationStack<T> {
13351 fn default() -> Self {
13352 Self(Default::default())
13353 }
13354}
13355
13356impl<T> Deref for InvalidationStack<T> {
13357 type Target = Vec<T>;
13358
13359 fn deref(&self) -> &Self::Target {
13360 &self.0
13361 }
13362}
13363
13364impl<T> DerefMut for InvalidationStack<T> {
13365 fn deref_mut(&mut self) -> &mut Self::Target {
13366 &mut self.0
13367 }
13368}
13369
13370impl InvalidationRegion for SnippetState {
13371 fn ranges(&self) -> &[Range<Anchor>] {
13372 &self.ranges[self.active_index]
13373 }
13374}
13375
13376pub fn diagnostic_block_renderer(
13377 diagnostic: Diagnostic,
13378 max_message_rows: Option<u8>,
13379 allow_closing: bool,
13380 _is_valid: bool,
13381) -> RenderBlock {
13382 let (text_without_backticks, code_ranges) =
13383 highlight_diagnostic_message(&diagnostic, max_message_rows);
13384
13385 Box::new(move |cx: &mut BlockContext| {
13386 let group_id: SharedString = cx.block_id.to_string().into();
13387
13388 let mut text_style = cx.text_style().clone();
13389 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13390 let theme_settings = ThemeSettings::get_global(cx);
13391 text_style.font_family = theme_settings.buffer_font.family.clone();
13392 text_style.font_style = theme_settings.buffer_font.style;
13393 text_style.font_features = theme_settings.buffer_font.features.clone();
13394 text_style.font_weight = theme_settings.buffer_font.weight;
13395
13396 let multi_line_diagnostic = diagnostic.message.contains('\n');
13397
13398 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13399 if multi_line_diagnostic {
13400 v_flex()
13401 } else {
13402 h_flex()
13403 }
13404 .when(allow_closing, |div| {
13405 div.children(diagnostic.is_primary.then(|| {
13406 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13407 .icon_color(Color::Muted)
13408 .size(ButtonSize::Compact)
13409 .style(ButtonStyle::Transparent)
13410 .visible_on_hover(group_id.clone())
13411 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13412 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13413 }))
13414 })
13415 .child(
13416 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13417 .icon_color(Color::Muted)
13418 .size(ButtonSize::Compact)
13419 .style(ButtonStyle::Transparent)
13420 .visible_on_hover(group_id.clone())
13421 .on_click({
13422 let message = diagnostic.message.clone();
13423 move |_click, cx| {
13424 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13425 }
13426 })
13427 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13428 )
13429 };
13430
13431 let icon_size = buttons(&diagnostic, cx.block_id)
13432 .into_any_element()
13433 .layout_as_root(AvailableSpace::min_size(), cx);
13434
13435 h_flex()
13436 .id(cx.block_id)
13437 .group(group_id.clone())
13438 .relative()
13439 .size_full()
13440 .pl(cx.gutter_dimensions.width)
13441 .w(cx.max_width + cx.gutter_dimensions.width)
13442 .child(
13443 div()
13444 .flex()
13445 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13446 .flex_shrink(),
13447 )
13448 .child(buttons(&diagnostic, cx.block_id))
13449 .child(div().flex().flex_shrink_0().child(
13450 StyledText::new(text_without_backticks.clone()).with_highlights(
13451 &text_style,
13452 code_ranges.iter().map(|range| {
13453 (
13454 range.clone(),
13455 HighlightStyle {
13456 font_weight: Some(FontWeight::BOLD),
13457 ..Default::default()
13458 },
13459 )
13460 }),
13461 ),
13462 ))
13463 .into_any_element()
13464 })
13465}
13466
13467pub fn highlight_diagnostic_message(
13468 diagnostic: &Diagnostic,
13469 mut max_message_rows: Option<u8>,
13470) -> (SharedString, Vec<Range<usize>>) {
13471 let mut text_without_backticks = String::new();
13472 let mut code_ranges = Vec::new();
13473
13474 if let Some(source) = &diagnostic.source {
13475 text_without_backticks.push_str(source);
13476 code_ranges.push(0..source.len());
13477 text_without_backticks.push_str(": ");
13478 }
13479
13480 let mut prev_offset = 0;
13481 let mut in_code_block = false;
13482 let has_row_limit = max_message_rows.is_some();
13483 let mut newline_indices = diagnostic
13484 .message
13485 .match_indices('\n')
13486 .filter(|_| has_row_limit)
13487 .map(|(ix, _)| ix)
13488 .fuse()
13489 .peekable();
13490
13491 for (quote_ix, _) in diagnostic
13492 .message
13493 .match_indices('`')
13494 .chain([(diagnostic.message.len(), "")])
13495 {
13496 let mut first_newline_ix = None;
13497 let mut last_newline_ix = None;
13498 while let Some(newline_ix) = newline_indices.peek() {
13499 if *newline_ix < quote_ix {
13500 if first_newline_ix.is_none() {
13501 first_newline_ix = Some(*newline_ix);
13502 }
13503 last_newline_ix = Some(*newline_ix);
13504
13505 if let Some(rows_left) = &mut max_message_rows {
13506 if *rows_left == 0 {
13507 break;
13508 } else {
13509 *rows_left -= 1;
13510 }
13511 }
13512 let _ = newline_indices.next();
13513 } else {
13514 break;
13515 }
13516 }
13517 let prev_len = text_without_backticks.len();
13518 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13519 text_without_backticks.push_str(new_text);
13520 if in_code_block {
13521 code_ranges.push(prev_len..text_without_backticks.len());
13522 }
13523 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13524 in_code_block = !in_code_block;
13525 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13526 text_without_backticks.push_str("...");
13527 break;
13528 }
13529 }
13530
13531 (text_without_backticks.into(), code_ranges)
13532}
13533
13534fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13535 match severity {
13536 DiagnosticSeverity::ERROR => colors.error,
13537 DiagnosticSeverity::WARNING => colors.warning,
13538 DiagnosticSeverity::INFORMATION => colors.info,
13539 DiagnosticSeverity::HINT => colors.info,
13540 _ => colors.ignored,
13541 }
13542}
13543
13544pub fn styled_runs_for_code_label<'a>(
13545 label: &'a CodeLabel,
13546 syntax_theme: &'a theme::SyntaxTheme,
13547) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13548 let fade_out = HighlightStyle {
13549 fade_out: Some(0.35),
13550 ..Default::default()
13551 };
13552
13553 let mut prev_end = label.filter_range.end;
13554 label
13555 .runs
13556 .iter()
13557 .enumerate()
13558 .flat_map(move |(ix, (range, highlight_id))| {
13559 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13560 style
13561 } else {
13562 return Default::default();
13563 };
13564 let mut muted_style = style;
13565 muted_style.highlight(fade_out);
13566
13567 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13568 if range.start >= label.filter_range.end {
13569 if range.start > prev_end {
13570 runs.push((prev_end..range.start, fade_out));
13571 }
13572 runs.push((range.clone(), muted_style));
13573 } else if range.end <= label.filter_range.end {
13574 runs.push((range.clone(), style));
13575 } else {
13576 runs.push((range.start..label.filter_range.end, style));
13577 runs.push((label.filter_range.end..range.end, muted_style));
13578 }
13579 prev_end = cmp::max(prev_end, range.end);
13580
13581 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13582 runs.push((prev_end..label.text.len(), fade_out));
13583 }
13584
13585 runs
13586 })
13587}
13588
13589pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13590 let mut prev_index = 0;
13591 let mut prev_codepoint: Option<char> = None;
13592 text.char_indices()
13593 .chain([(text.len(), '\0')])
13594 .filter_map(move |(index, codepoint)| {
13595 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13596 let is_boundary = index == text.len()
13597 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13598 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13599 if is_boundary {
13600 let chunk = &text[prev_index..index];
13601 prev_index = index;
13602 Some(chunk)
13603 } else {
13604 None
13605 }
13606 })
13607}
13608
13609pub trait RangeToAnchorExt: Sized {
13610 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13611
13612 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13613 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13614 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13615 }
13616}
13617
13618impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13619 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13620 let start_offset = self.start.to_offset(snapshot);
13621 let end_offset = self.end.to_offset(snapshot);
13622 if start_offset == end_offset {
13623 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13624 } else {
13625 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13626 }
13627 }
13628}
13629
13630pub trait RowExt {
13631 fn as_f32(&self) -> f32;
13632
13633 fn next_row(&self) -> Self;
13634
13635 fn previous_row(&self) -> Self;
13636
13637 fn minus(&self, other: Self) -> u32;
13638}
13639
13640impl RowExt for DisplayRow {
13641 fn as_f32(&self) -> f32 {
13642 self.0 as f32
13643 }
13644
13645 fn next_row(&self) -> Self {
13646 Self(self.0 + 1)
13647 }
13648
13649 fn previous_row(&self) -> Self {
13650 Self(self.0.saturating_sub(1))
13651 }
13652
13653 fn minus(&self, other: Self) -> u32 {
13654 self.0 - other.0
13655 }
13656}
13657
13658impl RowExt for MultiBufferRow {
13659 fn as_f32(&self) -> f32 {
13660 self.0 as f32
13661 }
13662
13663 fn next_row(&self) -> Self {
13664 Self(self.0 + 1)
13665 }
13666
13667 fn previous_row(&self) -> Self {
13668 Self(self.0.saturating_sub(1))
13669 }
13670
13671 fn minus(&self, other: Self) -> u32 {
13672 self.0 - other.0
13673 }
13674}
13675
13676trait RowRangeExt {
13677 type Row;
13678
13679 fn len(&self) -> usize;
13680
13681 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13682}
13683
13684impl RowRangeExt for Range<MultiBufferRow> {
13685 type Row = MultiBufferRow;
13686
13687 fn len(&self) -> usize {
13688 (self.end.0 - self.start.0) as usize
13689 }
13690
13691 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13692 (self.start.0..self.end.0).map(MultiBufferRow)
13693 }
13694}
13695
13696impl RowRangeExt for Range<DisplayRow> {
13697 type Row = DisplayRow;
13698
13699 fn len(&self) -> usize {
13700 (self.end.0 - self.start.0) as usize
13701 }
13702
13703 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13704 (self.start.0..self.end.0).map(DisplayRow)
13705 }
13706}
13707
13708fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13709 if hunk.diff_base_byte_range.is_empty() {
13710 DiffHunkStatus::Added
13711 } else if hunk.associated_range.is_empty() {
13712 DiffHunkStatus::Removed
13713 } else {
13714 DiffHunkStatus::Modified
13715 }
13716}
13717
13718/// If select range has more than one line, we
13719/// just point the cursor to range.start.
13720fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13721 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13722 range
13723 } else {
13724 range.start..range.start
13725 }
13726}