1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
52pub(crate) use actions::*;
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, 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};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, 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 proposed_changes_editor::{ProposedChangesBuffer, ProposedChangesEditor};
102use similar::{ChangeTag, TextDiff};
103use task::{ResolvedTask, TaskTemplate, TaskVariables};
104
105use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
106pub use lsp::CompletionContext;
107use lsp::{
108 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
109 LanguageServerId,
110};
111use mouse_context_menu::MouseContextMenu;
112use movement::TextLayoutDetails;
113pub use multi_buffer::{
114 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
115 ToPoint,
116};
117use multi_buffer::{
118 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
119};
120use ordered_float::OrderedFloat;
121use parking_lot::{Mutex, RwLock};
122use project::project_settings::{GitGutterSetting, ProjectSettings};
123use project::{
124 lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
125 ProjectPath, ProjectTransaction, TaskSourceKind,
126};
127use rand::prelude::*;
128use rpc::{proto::*, ErrorExt};
129use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
130use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
131use serde::{Deserialize, Serialize};
132use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
133use smallvec::SmallVec;
134use snippet::Snippet;
135use std::{
136 any::TypeId,
137 borrow::Cow,
138 cell::RefCell,
139 cmp::{self, Ordering, Reverse},
140 mem,
141 num::NonZeroU32,
142 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
143 path::{Path, PathBuf},
144 rc::Rc,
145 sync::Arc,
146 time::{Duration, Instant},
147};
148pub use sum_tree::Bias;
149use sum_tree::TreeMap;
150use text::{BufferId, OffsetUtf16, Rope};
151use theme::{
152 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
153 ThemeColors, ThemeSettings,
154};
155use ui::{
156 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
157 ListItem, Popover, Tooltip,
158};
159use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
160use workspace::item::{ItemHandle, PreviewTabsSettings};
161use workspace::notifications::{DetachAndPromptErr, NotificationId};
162use workspace::{
163 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
164};
165use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
166
167use crate::hover_links::find_url;
168use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
169
170pub const FILE_HEADER_HEIGHT: u32 = 1;
171pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
172pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
173pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
174const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
175const MAX_LINE_LEN: usize = 1024;
176const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
177const MAX_SELECTION_HISTORY_LEN: usize = 1024;
178pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
179#[doc(hidden)]
180pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
181#[doc(hidden)]
182pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
183
184pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
185pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
186
187pub fn render_parsed_markdown(
188 element_id: impl Into<ElementId>,
189 parsed: &language::ParsedMarkdown,
190 editor_style: &EditorStyle,
191 workspace: Option<WeakView<Workspace>>,
192 cx: &mut WindowContext,
193) -> InteractiveText {
194 let code_span_background_color = cx
195 .theme()
196 .colors()
197 .editor_document_highlight_read_background;
198
199 let highlights = gpui::combine_highlights(
200 parsed.highlights.iter().filter_map(|(range, highlight)| {
201 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
202 Some((range.clone(), highlight))
203 }),
204 parsed
205 .regions
206 .iter()
207 .zip(&parsed.region_ranges)
208 .filter_map(|(region, range)| {
209 if region.code {
210 Some((
211 range.clone(),
212 HighlightStyle {
213 background_color: Some(code_span_background_color),
214 ..Default::default()
215 },
216 ))
217 } else {
218 None
219 }
220 }),
221 );
222
223 let mut links = Vec::new();
224 let mut link_ranges = Vec::new();
225 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
226 if let Some(link) = region.link.clone() {
227 links.push(link);
228 link_ranges.push(range.clone());
229 }
230 }
231
232 InteractiveText::new(
233 element_id,
234 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
235 )
236 .on_click(link_ranges, move |clicked_range_ix, cx| {
237 match &links[clicked_range_ix] {
238 markdown::Link::Web { url } => cx.open_url(url),
239 markdown::Link::Path { path } => {
240 if let Some(workspace) = &workspace {
241 _ = workspace.update(cx, |workspace, cx| {
242 workspace.open_abs_path(path.clone(), false, cx).detach();
243 });
244 }
245 }
246 }
247 })
248}
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
251pub(crate) enum InlayId {
252 Suggestion(usize),
253 Hint(usize),
254}
255
256impl InlayId {
257 fn id(&self) -> usize {
258 match self {
259 Self::Suggestion(id) => *id,
260 Self::Hint(id) => *id,
261 }
262 }
263}
264
265enum DiffRowHighlight {}
266enum DocumentHighlightRead {}
267enum DocumentHighlightWrite {}
268enum InputComposition {}
269
270#[derive(Copy, Clone, PartialEq, Eq)]
271pub enum Direction {
272 Prev,
273 Next,
274}
275
276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
277pub enum Navigated {
278 Yes,
279 No,
280}
281
282impl Navigated {
283 pub fn from_bool(yes: bool) -> Navigated {
284 if yes {
285 Navigated::Yes
286 } else {
287 Navigated::No
288 }
289 }
290}
291
292pub fn init_settings(cx: &mut AppContext) {
293 EditorSettings::register(cx);
294}
295
296pub fn init(cx: &mut AppContext) {
297 init_settings(cx);
298
299 workspace::register_project_item::<Editor>(cx);
300 workspace::FollowableViewRegistry::register::<Editor>(cx);
301 workspace::register_serializable_item::<Editor>(cx);
302
303 cx.observe_new_views(
304 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
305 workspace.register_action(Editor::new_file);
306 workspace.register_action(Editor::new_file_vertical);
307 workspace.register_action(Editor::new_file_horizontal);
308 },
309 )
310 .detach();
311
312 cx.on_action(move |_: &workspace::NewFile, cx| {
313 let app_state = workspace::AppState::global(cx);
314 if let Some(app_state) = app_state.upgrade() {
315 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
316 Editor::new_file(workspace, &Default::default(), cx)
317 })
318 .detach();
319 }
320 });
321 cx.on_action(move |_: &workspace::NewWindow, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
325 Editor::new_file(workspace, &Default::default(), cx)
326 })
327 .detach();
328 }
329 });
330}
331
332pub struct SearchWithinRange;
333
334trait InvalidationRegion {
335 fn ranges(&self) -> &[Range<Anchor>];
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub enum SelectPhase {
340 Begin {
341 position: DisplayPoint,
342 add: bool,
343 click_count: usize,
344 },
345 BeginColumnar {
346 position: DisplayPoint,
347 reset: bool,
348 goal_column: u32,
349 },
350 Extend {
351 position: DisplayPoint,
352 click_count: usize,
353 },
354 Update {
355 position: DisplayPoint,
356 goal_column: u32,
357 scroll_delta: gpui::Point<f32>,
358 },
359 End,
360}
361
362#[derive(Clone, Debug)]
363pub enum SelectMode {
364 Character,
365 Word(Range<Anchor>),
366 Line(Range<Anchor>),
367 All,
368}
369
370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
371pub enum EditorMode {
372 SingleLine { auto_width: bool },
373 AutoHeight { max_lines: usize },
374 Full,
375}
376
377#[derive(Clone, Debug)]
378pub enum SoftWrap {
379 None,
380 PreferLine,
381 EditorWidth,
382 Column(u32),
383 Bounded(u32),
384}
385
386#[derive(Clone)]
387pub struct EditorStyle {
388 pub background: Hsla,
389 pub local_player: PlayerColor,
390 pub text: TextStyle,
391 pub scrollbar_width: Pixels,
392 pub syntax: Arc<SyntaxTheme>,
393 pub status: StatusColors,
394 pub inlay_hints_style: HighlightStyle,
395 pub suggestions_style: HighlightStyle,
396 pub unnecessary_code_fade: f32,
397}
398
399impl Default for EditorStyle {
400 fn default() -> Self {
401 Self {
402 background: Hsla::default(),
403 local_player: PlayerColor::default(),
404 text: TextStyle::default(),
405 scrollbar_width: Pixels::default(),
406 syntax: Default::default(),
407 // HACK: Status colors don't have a real default.
408 // We should look into removing the status colors from the editor
409 // style and retrieve them directly from the theme.
410 status: StatusColors::dark(),
411 inlay_hints_style: HighlightStyle::default(),
412 suggestions_style: HighlightStyle::default(),
413 unnecessary_code_fade: Default::default(),
414 }
415 }
416}
417
418pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
419 let show_background = all_language_settings(None, cx)
420 .language(None)
421 .inlay_hints
422 .show_background;
423
424 HighlightStyle {
425 color: Some(cx.theme().status().hint),
426 background_color: show_background.then(|| cx.theme().status().hint_background),
427 ..HighlightStyle::default()
428 }
429}
430
431type CompletionId = usize;
432
433#[derive(Clone, Debug)]
434struct CompletionState {
435 // render_inlay_ids represents the inlay hints that are inserted
436 // for rendering the inline completions. They may be discontinuous
437 // in the event that the completion provider returns some intersection
438 // with the existing content.
439 render_inlay_ids: Vec<InlayId>,
440 // text is the resulting rope that is inserted when the user accepts a completion.
441 text: Rope,
442 // position is the position of the cursor when the completion was triggered.
443 position: multi_buffer::Anchor,
444 // delete_range is the range of text that this completion state covers.
445 // if the completion is accepted, this range should be deleted.
446 delete_range: Option<Range<multi_buffer::Anchor>>,
447}
448
449#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
450struct EditorActionId(usize);
451
452impl EditorActionId {
453 pub fn post_inc(&mut self) -> Self {
454 let answer = self.0;
455
456 *self = Self(answer + 1);
457
458 Self(answer)
459 }
460}
461
462// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
463// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
464
465type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
466type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
467
468#[derive(Default)]
469struct ScrollbarMarkerState {
470 scrollbar_size: Size<Pixels>,
471 dirty: bool,
472 markers: Arc<[PaintQuad]>,
473 pending_refresh: Option<Task<Result<()>>>,
474}
475
476impl ScrollbarMarkerState {
477 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
478 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
479 }
480}
481
482#[derive(Clone, Debug)]
483struct RunnableTasks {
484 templates: Vec<(TaskSourceKind, TaskTemplate)>,
485 offset: MultiBufferOffset,
486 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
487 column: u32,
488 // Values of all named captures, including those starting with '_'
489 extra_variables: HashMap<String, String>,
490 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
491 context_range: Range<BufferOffset>,
492}
493
494#[derive(Clone)]
495struct ResolvedTasks {
496 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
497 position: Anchor,
498}
499#[derive(Copy, Clone, Debug)]
500struct MultiBufferOffset(usize);
501#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
502struct BufferOffset(usize);
503
504// Addons allow storing per-editor state in other crates (e.g. Vim)
505pub trait Addon: 'static {
506 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
507
508 fn to_any(&self) -> &dyn std::any::Any;
509}
510
511/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
512///
513/// See the [module level documentation](self) for more information.
514pub struct Editor {
515 focus_handle: FocusHandle,
516 last_focused_descendant: Option<WeakFocusHandle>,
517 /// The text buffer being edited
518 buffer: Model<MultiBuffer>,
519 /// Map of how text in the buffer should be displayed.
520 /// Handles soft wraps, folds, fake inlay text insertions, etc.
521 pub display_map: Model<DisplayMap>,
522 pub selections: SelectionsCollection,
523 pub scroll_manager: ScrollManager,
524 /// When inline assist editors are linked, they all render cursors because
525 /// typing enters text into each of them, even the ones that aren't focused.
526 pub(crate) show_cursor_when_unfocused: bool,
527 columnar_selection_tail: Option<Anchor>,
528 add_selections_state: Option<AddSelectionsState>,
529 select_next_state: Option<SelectNextState>,
530 select_prev_state: Option<SelectNextState>,
531 selection_history: SelectionHistory,
532 autoclose_regions: Vec<AutocloseRegion>,
533 snippet_stack: InvalidationStack<SnippetState>,
534 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
535 ime_transaction: Option<TransactionId>,
536 active_diagnostics: Option<ActiveDiagnosticGroup>,
537 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
538 project: Option<Model<Project>>,
539 completion_provider: Option<Box<dyn CompletionProvider>>,
540 collaboration_hub: Option<Box<dyn CollaborationHub>>,
541 blink_manager: Model<BlinkManager>,
542 show_cursor_names: bool,
543 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
544 pub show_local_selections: bool,
545 mode: EditorMode,
546 show_breadcrumbs: bool,
547 show_gutter: bool,
548 show_line_numbers: Option<bool>,
549 use_relative_line_numbers: Option<bool>,
550 show_git_diff_gutter: Option<bool>,
551 show_code_actions: Option<bool>,
552 show_runnables: Option<bool>,
553 show_wrap_guides: Option<bool>,
554 show_indent_guides: Option<bool>,
555 placeholder_text: Option<Arc<str>>,
556 highlight_order: usize,
557 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
558 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
559 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
560 scrollbar_marker_state: ScrollbarMarkerState,
561 active_indent_guides_state: ActiveIndentGuidesState,
562 nav_history: Option<ItemNavHistory>,
563 context_menu: RwLock<Option<ContextMenu>>,
564 mouse_context_menu: Option<MouseContextMenu>,
565 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
566 signature_help_state: SignatureHelpState,
567 auto_signature_help: Option<bool>,
568 find_all_references_task_sources: Vec<Anchor>,
569 next_completion_id: CompletionId,
570 completion_documentation_pre_resolve_debounce: DebouncedDelay,
571 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
572 code_actions_task: Option<Task<Result<()>>>,
573 document_highlights_task: Option<Task<()>>,
574 linked_editing_range_task: Option<Task<Option<()>>>,
575 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
576 pending_rename: Option<RenameState>,
577 searchable: bool,
578 cursor_shape: CursorShape,
579 current_line_highlight: Option<CurrentLineHighlight>,
580 collapse_matches: bool,
581 autoindent_mode: Option<AutoindentMode>,
582 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
583 input_enabled: bool,
584 use_modal_editing: bool,
585 read_only: bool,
586 leader_peer_id: Option<PeerId>,
587 remote_id: Option<ViewId>,
588 hover_state: HoverState,
589 gutter_hovered: bool,
590 hovered_link_state: Option<HoveredLinkState>,
591 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
592 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
593 active_inline_completion: Option<CompletionState>,
594 // enable_inline_completions is a switch that Vim can use to disable
595 // inline completions based on its mode.
596 enable_inline_completions: bool,
597 show_inline_completions_override: Option<bool>,
598 inlay_hint_cache: InlayHintCache,
599 expanded_hunks: ExpandedHunks,
600 next_inlay_id: usize,
601 _subscriptions: Vec<Subscription>,
602 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
603 gutter_dimensions: GutterDimensions,
604 style: Option<EditorStyle>,
605 next_editor_action_id: EditorActionId,
606 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
607 use_autoclose: bool,
608 use_auto_surround: bool,
609 auto_replace_emoji_shortcode: bool,
610 show_git_blame_gutter: bool,
611 show_git_blame_inline: bool,
612 show_git_blame_inline_delay_task: Option<Task<()>>,
613 git_blame_inline_enabled: bool,
614 serialize_dirty_buffers: bool,
615 show_selection_menu: Option<bool>,
616 blame: Option<Model<GitBlame>>,
617 blame_subscription: Option<Subscription>,
618 custom_context_menu: Option<
619 Box<
620 dyn 'static
621 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
622 >,
623 >,
624 last_bounds: Option<Bounds<Pixels>>,
625 expect_bounds_change: Option<Bounds<Pixels>>,
626 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
627 tasks_update_task: Option<Task<()>>,
628 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
629 file_header_size: u32,
630 breadcrumb_header: Option<String>,
631 focused_block: Option<FocusedBlock>,
632 next_scroll_position: NextScrollCursorCenterTopBottom,
633 addons: HashMap<TypeId, Box<dyn Addon>>,
634 _scroll_cursor_center_top_bottom_task: Task<()>,
635}
636
637#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
638enum NextScrollCursorCenterTopBottom {
639 #[default]
640 Center,
641 Top,
642 Bottom,
643}
644
645impl NextScrollCursorCenterTopBottom {
646 fn next(&self) -> Self {
647 match self {
648 Self::Center => Self::Top,
649 Self::Top => Self::Bottom,
650 Self::Bottom => Self::Center,
651 }
652 }
653}
654
655#[derive(Clone)]
656pub struct EditorSnapshot {
657 pub mode: EditorMode,
658 show_gutter: bool,
659 show_line_numbers: Option<bool>,
660 show_git_diff_gutter: Option<bool>,
661 show_code_actions: Option<bool>,
662 show_runnables: Option<bool>,
663 render_git_blame_gutter: bool,
664 pub display_snapshot: DisplaySnapshot,
665 pub placeholder_text: Option<Arc<str>>,
666 is_focused: bool,
667 scroll_anchor: ScrollAnchor,
668 ongoing_scroll: OngoingScroll,
669 current_line_highlight: CurrentLineHighlight,
670 gutter_hovered: bool,
671}
672
673const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
674
675#[derive(Default, Debug, Clone, Copy)]
676pub struct GutterDimensions {
677 pub left_padding: Pixels,
678 pub right_padding: Pixels,
679 pub width: Pixels,
680 pub margin: Pixels,
681 pub git_blame_entries_width: Option<Pixels>,
682}
683
684impl GutterDimensions {
685 /// The full width of the space taken up by the gutter.
686 pub fn full_width(&self) -> Pixels {
687 self.margin + self.width
688 }
689
690 /// The width of the space reserved for the fold indicators,
691 /// use alongside 'justify_end' and `gutter_width` to
692 /// right align content with the line numbers
693 pub fn fold_area_width(&self) -> Pixels {
694 self.margin + self.right_padding
695 }
696}
697
698#[derive(Debug)]
699pub struct RemoteSelection {
700 pub replica_id: ReplicaId,
701 pub selection: Selection<Anchor>,
702 pub cursor_shape: CursorShape,
703 pub peer_id: PeerId,
704 pub line_mode: bool,
705 pub participant_index: Option<ParticipantIndex>,
706 pub user_name: Option<SharedString>,
707}
708
709#[derive(Clone, Debug)]
710struct SelectionHistoryEntry {
711 selections: Arc<[Selection<Anchor>]>,
712 select_next_state: Option<SelectNextState>,
713 select_prev_state: Option<SelectNextState>,
714 add_selections_state: Option<AddSelectionsState>,
715}
716
717enum SelectionHistoryMode {
718 Normal,
719 Undoing,
720 Redoing,
721}
722
723#[derive(Clone, PartialEq, Eq, Hash)]
724struct HoveredCursor {
725 replica_id: u16,
726 selection_id: usize,
727}
728
729impl Default for SelectionHistoryMode {
730 fn default() -> Self {
731 Self::Normal
732 }
733}
734
735#[derive(Default)]
736struct SelectionHistory {
737 #[allow(clippy::type_complexity)]
738 selections_by_transaction:
739 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
740 mode: SelectionHistoryMode,
741 undo_stack: VecDeque<SelectionHistoryEntry>,
742 redo_stack: VecDeque<SelectionHistoryEntry>,
743}
744
745impl SelectionHistory {
746 fn insert_transaction(
747 &mut self,
748 transaction_id: TransactionId,
749 selections: Arc<[Selection<Anchor>]>,
750 ) {
751 self.selections_by_transaction
752 .insert(transaction_id, (selections, None));
753 }
754
755 #[allow(clippy::type_complexity)]
756 fn transaction(
757 &self,
758 transaction_id: TransactionId,
759 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
760 self.selections_by_transaction.get(&transaction_id)
761 }
762
763 #[allow(clippy::type_complexity)]
764 fn transaction_mut(
765 &mut self,
766 transaction_id: TransactionId,
767 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
768 self.selections_by_transaction.get_mut(&transaction_id)
769 }
770
771 fn push(&mut self, entry: SelectionHistoryEntry) {
772 if !entry.selections.is_empty() {
773 match self.mode {
774 SelectionHistoryMode::Normal => {
775 self.push_undo(entry);
776 self.redo_stack.clear();
777 }
778 SelectionHistoryMode::Undoing => self.push_redo(entry),
779 SelectionHistoryMode::Redoing => self.push_undo(entry),
780 }
781 }
782 }
783
784 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
785 if self
786 .undo_stack
787 .back()
788 .map_or(true, |e| e.selections != entry.selections)
789 {
790 self.undo_stack.push_back(entry);
791 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
792 self.undo_stack.pop_front();
793 }
794 }
795 }
796
797 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
798 if self
799 .redo_stack
800 .back()
801 .map_or(true, |e| e.selections != entry.selections)
802 {
803 self.redo_stack.push_back(entry);
804 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
805 self.redo_stack.pop_front();
806 }
807 }
808 }
809}
810
811struct RowHighlight {
812 index: usize,
813 range: RangeInclusive<Anchor>,
814 color: Option<Hsla>,
815 should_autoscroll: bool,
816}
817
818#[derive(Clone, Debug)]
819struct AddSelectionsState {
820 above: bool,
821 stack: Vec<usize>,
822}
823
824#[derive(Clone)]
825struct SelectNextState {
826 query: AhoCorasick,
827 wordwise: bool,
828 done: bool,
829}
830
831impl std::fmt::Debug for SelectNextState {
832 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
833 f.debug_struct(std::any::type_name::<Self>())
834 .field("wordwise", &self.wordwise)
835 .field("done", &self.done)
836 .finish()
837 }
838}
839
840#[derive(Debug)]
841struct AutocloseRegion {
842 selection_id: usize,
843 range: Range<Anchor>,
844 pair: BracketPair,
845}
846
847#[derive(Debug)]
848struct SnippetState {
849 ranges: Vec<Vec<Range<Anchor>>>,
850 active_index: usize,
851}
852
853#[doc(hidden)]
854pub struct RenameState {
855 pub range: Range<Anchor>,
856 pub old_name: Arc<str>,
857 pub editor: View<Editor>,
858 block_id: CustomBlockId,
859}
860
861struct InvalidationStack<T>(Vec<T>);
862
863struct RegisteredInlineCompletionProvider {
864 provider: Arc<dyn InlineCompletionProviderHandle>,
865 _subscription: Subscription,
866}
867
868enum ContextMenu {
869 Completions(CompletionsMenu),
870 CodeActions(CodeActionsMenu),
871}
872
873impl ContextMenu {
874 fn select_first(
875 &mut self,
876 project: Option<&Model<Project>>,
877 cx: &mut ViewContext<Editor>,
878 ) -> bool {
879 if self.visible() {
880 match self {
881 ContextMenu::Completions(menu) => menu.select_first(project, cx),
882 ContextMenu::CodeActions(menu) => menu.select_first(cx),
883 }
884 true
885 } else {
886 false
887 }
888 }
889
890 fn select_prev(
891 &mut self,
892 project: Option<&Model<Project>>,
893 cx: &mut ViewContext<Editor>,
894 ) -> bool {
895 if self.visible() {
896 match self {
897 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
898 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
899 }
900 true
901 } else {
902 false
903 }
904 }
905
906 fn select_next(
907 &mut self,
908 project: Option<&Model<Project>>,
909 cx: &mut ViewContext<Editor>,
910 ) -> bool {
911 if self.visible() {
912 match self {
913 ContextMenu::Completions(menu) => menu.select_next(project, cx),
914 ContextMenu::CodeActions(menu) => menu.select_next(cx),
915 }
916 true
917 } else {
918 false
919 }
920 }
921
922 fn select_last(
923 &mut self,
924 project: Option<&Model<Project>>,
925 cx: &mut ViewContext<Editor>,
926 ) -> bool {
927 if self.visible() {
928 match self {
929 ContextMenu::Completions(menu) => menu.select_last(project, cx),
930 ContextMenu::CodeActions(menu) => menu.select_last(cx),
931 }
932 true
933 } else {
934 false
935 }
936 }
937
938 fn visible(&self) -> bool {
939 match self {
940 ContextMenu::Completions(menu) => menu.visible(),
941 ContextMenu::CodeActions(menu) => menu.visible(),
942 }
943 }
944
945 fn render(
946 &self,
947 cursor_position: DisplayPoint,
948 style: &EditorStyle,
949 max_height: Pixels,
950 workspace: Option<WeakView<Workspace>>,
951 cx: &mut ViewContext<Editor>,
952 ) -> (ContextMenuOrigin, AnyElement) {
953 match self {
954 ContextMenu::Completions(menu) => (
955 ContextMenuOrigin::EditorPoint(cursor_position),
956 menu.render(style, max_height, workspace, cx),
957 ),
958 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
959 }
960 }
961}
962
963enum ContextMenuOrigin {
964 EditorPoint(DisplayPoint),
965 GutterIndicator(DisplayRow),
966}
967
968#[derive(Clone)]
969struct CompletionsMenu {
970 id: CompletionId,
971 sort_completions: bool,
972 initial_position: Anchor,
973 buffer: Model<Buffer>,
974 completions: Arc<RwLock<Box<[Completion]>>>,
975 match_candidates: Arc<[StringMatchCandidate]>,
976 matches: Arc<[StringMatch]>,
977 selected_item: usize,
978 scroll_handle: UniformListScrollHandle,
979 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
980}
981
982impl CompletionsMenu {
983 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
984 self.selected_item = 0;
985 self.scroll_handle.scroll_to_item(self.selected_item);
986 self.attempt_resolve_selected_completion_documentation(project, cx);
987 cx.notify();
988 }
989
990 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
991 if self.selected_item > 0 {
992 self.selected_item -= 1;
993 } else {
994 self.selected_item = self.matches.len() - 1;
995 }
996 self.scroll_handle.scroll_to_item(self.selected_item);
997 self.attempt_resolve_selected_completion_documentation(project, cx);
998 cx.notify();
999 }
1000
1001 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1002 if self.selected_item + 1 < self.matches.len() {
1003 self.selected_item += 1;
1004 } else {
1005 self.selected_item = 0;
1006 }
1007 self.scroll_handle.scroll_to_item(self.selected_item);
1008 self.attempt_resolve_selected_completion_documentation(project, cx);
1009 cx.notify();
1010 }
1011
1012 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1013 self.selected_item = self.matches.len() - 1;
1014 self.scroll_handle.scroll_to_item(self.selected_item);
1015 self.attempt_resolve_selected_completion_documentation(project, cx);
1016 cx.notify();
1017 }
1018
1019 fn pre_resolve_completion_documentation(
1020 buffer: Model<Buffer>,
1021 completions: Arc<RwLock<Box<[Completion]>>>,
1022 matches: Arc<[StringMatch]>,
1023 editor: &Editor,
1024 cx: &mut ViewContext<Editor>,
1025 ) -> Task<()> {
1026 let settings = EditorSettings::get_global(cx);
1027 if !settings.show_completion_documentation {
1028 return Task::ready(());
1029 }
1030
1031 let Some(provider) = editor.completion_provider.as_ref() else {
1032 return Task::ready(());
1033 };
1034
1035 let resolve_task = provider.resolve_completions(
1036 buffer,
1037 matches.iter().map(|m| m.candidate_id).collect(),
1038 completions.clone(),
1039 cx,
1040 );
1041
1042 cx.spawn(move |this, mut cx| async move {
1043 if let Some(true) = resolve_task.await.log_err() {
1044 this.update(&mut cx, |_, cx| cx.notify()).ok();
1045 }
1046 })
1047 }
1048
1049 fn attempt_resolve_selected_completion_documentation(
1050 &mut self,
1051 project: Option<&Model<Project>>,
1052 cx: &mut ViewContext<Editor>,
1053 ) {
1054 let settings = EditorSettings::get_global(cx);
1055 if !settings.show_completion_documentation {
1056 return;
1057 }
1058
1059 let completion_index = self.matches[self.selected_item].candidate_id;
1060 let Some(project) = project else {
1061 return;
1062 };
1063
1064 let resolve_task = project.update(cx, |project, cx| {
1065 project.resolve_completions(
1066 self.buffer.clone(),
1067 vec![completion_index],
1068 self.completions.clone(),
1069 cx,
1070 )
1071 });
1072
1073 let delay_ms =
1074 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1075 let delay = Duration::from_millis(delay_ms);
1076
1077 self.selected_completion_documentation_resolve_debounce
1078 .lock()
1079 .fire_new(delay, cx, |_, cx| {
1080 cx.spawn(move |this, mut cx| async move {
1081 if let Some(true) = resolve_task.await.log_err() {
1082 this.update(&mut cx, |_, cx| cx.notify()).ok();
1083 }
1084 })
1085 });
1086 }
1087
1088 fn visible(&self) -> bool {
1089 !self.matches.is_empty()
1090 }
1091
1092 fn render(
1093 &self,
1094 style: &EditorStyle,
1095 max_height: Pixels,
1096 workspace: Option<WeakView<Workspace>>,
1097 cx: &mut ViewContext<Editor>,
1098 ) -> AnyElement {
1099 let settings = EditorSettings::get_global(cx);
1100 let show_completion_documentation = settings.show_completion_documentation;
1101
1102 let widest_completion_ix = self
1103 .matches
1104 .iter()
1105 .enumerate()
1106 .max_by_key(|(_, mat)| {
1107 let completions = self.completions.read();
1108 let completion = &completions[mat.candidate_id];
1109 let documentation = &completion.documentation;
1110
1111 let mut len = completion.label.text.chars().count();
1112 if let Some(Documentation::SingleLine(text)) = documentation {
1113 if show_completion_documentation {
1114 len += text.chars().count();
1115 }
1116 }
1117
1118 len
1119 })
1120 .map(|(ix, _)| ix);
1121
1122 let completions = self.completions.clone();
1123 let matches = self.matches.clone();
1124 let selected_item = self.selected_item;
1125 let style = style.clone();
1126
1127 let multiline_docs = if show_completion_documentation {
1128 let mat = &self.matches[selected_item];
1129 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1130 Some(Documentation::MultiLinePlainText(text)) => {
1131 Some(div().child(SharedString::from(text.clone())))
1132 }
1133 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1134 Some(div().child(render_parsed_markdown(
1135 "completions_markdown",
1136 parsed,
1137 &style,
1138 workspace,
1139 cx,
1140 )))
1141 }
1142 _ => None,
1143 };
1144 multiline_docs.map(|div| {
1145 div.id("multiline_docs")
1146 .max_h(max_height)
1147 .flex_1()
1148 .px_1p5()
1149 .py_1()
1150 .min_w(px(260.))
1151 .max_w(px(640.))
1152 .w(px(500.))
1153 .overflow_y_scroll()
1154 .occlude()
1155 })
1156 } else {
1157 None
1158 };
1159
1160 let list = uniform_list(
1161 cx.view().clone(),
1162 "completions",
1163 matches.len(),
1164 move |_editor, range, cx| {
1165 let start_ix = range.start;
1166 let completions_guard = completions.read();
1167
1168 matches[range]
1169 .iter()
1170 .enumerate()
1171 .map(|(ix, mat)| {
1172 let item_ix = start_ix + ix;
1173 let candidate_id = mat.candidate_id;
1174 let completion = &completions_guard[candidate_id];
1175
1176 let documentation = if show_completion_documentation {
1177 &completion.documentation
1178 } else {
1179 &None
1180 };
1181
1182 let highlights = gpui::combine_highlights(
1183 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1184 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1185 |(range, mut highlight)| {
1186 // Ignore font weight for syntax highlighting, as we'll use it
1187 // for fuzzy matches.
1188 highlight.font_weight = None;
1189
1190 if completion.lsp_completion.deprecated.unwrap_or(false) {
1191 highlight.strikethrough = Some(StrikethroughStyle {
1192 thickness: 1.0.into(),
1193 ..Default::default()
1194 });
1195 highlight.color = Some(cx.theme().colors().text_muted);
1196 }
1197
1198 (range, highlight)
1199 },
1200 ),
1201 );
1202 let completion_label = StyledText::new(completion.label.text.clone())
1203 .with_highlights(&style.text, highlights);
1204 let documentation_label =
1205 if let Some(Documentation::SingleLine(text)) = documentation {
1206 if text.trim().is_empty() {
1207 None
1208 } else {
1209 Some(
1210 Label::new(text.clone())
1211 .ml_4()
1212 .size(LabelSize::Small)
1213 .color(Color::Muted),
1214 )
1215 }
1216 } else {
1217 None
1218 };
1219
1220 div().min_w(px(220.)).max_w(px(540.)).child(
1221 ListItem::new(mat.candidate_id)
1222 .inset(true)
1223 .selected(item_ix == selected_item)
1224 .on_click(cx.listener(move |editor, _event, cx| {
1225 cx.stop_propagation();
1226 if let Some(task) = editor.confirm_completion(
1227 &ConfirmCompletion {
1228 item_ix: Some(item_ix),
1229 },
1230 cx,
1231 ) {
1232 task.detach_and_log_err(cx)
1233 }
1234 }))
1235 .child(h_flex().overflow_hidden().child(completion_label))
1236 .end_slot::<Label>(documentation_label),
1237 )
1238 })
1239 .collect()
1240 },
1241 )
1242 .occlude()
1243 .max_h(max_height)
1244 .track_scroll(self.scroll_handle.clone())
1245 .with_width_from_item(widest_completion_ix)
1246 .with_sizing_behavior(ListSizingBehavior::Infer);
1247
1248 Popover::new()
1249 .child(list)
1250 .when_some(multiline_docs, |popover, multiline_docs| {
1251 popover.aside(multiline_docs)
1252 })
1253 .into_any_element()
1254 }
1255
1256 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1257 let mut matches = if let Some(query) = query {
1258 fuzzy::match_strings(
1259 &self.match_candidates,
1260 query,
1261 query.chars().any(|c| c.is_uppercase()),
1262 100,
1263 &Default::default(),
1264 executor,
1265 )
1266 .await
1267 } else {
1268 self.match_candidates
1269 .iter()
1270 .enumerate()
1271 .map(|(candidate_id, candidate)| StringMatch {
1272 candidate_id,
1273 score: Default::default(),
1274 positions: Default::default(),
1275 string: candidate.string.clone(),
1276 })
1277 .collect()
1278 };
1279
1280 // Remove all candidates where the query's start does not match the start of any word in the candidate
1281 if let Some(query) = query {
1282 if let Some(query_start) = query.chars().next() {
1283 matches.retain(|string_match| {
1284 split_words(&string_match.string).any(|word| {
1285 // Check that the first codepoint of the word as lowercase matches the first
1286 // codepoint of the query as lowercase
1287 word.chars()
1288 .flat_map(|codepoint| codepoint.to_lowercase())
1289 .zip(query_start.to_lowercase())
1290 .all(|(word_cp, query_cp)| word_cp == query_cp)
1291 })
1292 });
1293 }
1294 }
1295
1296 let completions = self.completions.read();
1297 if self.sort_completions {
1298 matches.sort_unstable_by_key(|mat| {
1299 // We do want to strike a balance here between what the language server tells us
1300 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1301 // `Creat` and there is a local variable called `CreateComponent`).
1302 // So what we do is: we bucket all matches into two buckets
1303 // - Strong matches
1304 // - Weak matches
1305 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1306 // and the Weak matches are the rest.
1307 //
1308 // For the strong matches, we sort by the language-servers score first and for the weak
1309 // matches, we prefer our fuzzy finder first.
1310 //
1311 // The thinking behind that: it's useless to take the sort_text the language-server gives
1312 // us into account when it's obviously a bad match.
1313
1314 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1315 enum MatchScore<'a> {
1316 Strong {
1317 sort_text: Option<&'a str>,
1318 score: Reverse<OrderedFloat<f64>>,
1319 sort_key: (usize, &'a str),
1320 },
1321 Weak {
1322 score: Reverse<OrderedFloat<f64>>,
1323 sort_text: Option<&'a str>,
1324 sort_key: (usize, &'a str),
1325 },
1326 }
1327
1328 let completion = &completions[mat.candidate_id];
1329 let sort_key = completion.sort_key();
1330 let sort_text = completion.lsp_completion.sort_text.as_deref();
1331 let score = Reverse(OrderedFloat(mat.score));
1332
1333 if mat.score >= 0.2 {
1334 MatchScore::Strong {
1335 sort_text,
1336 score,
1337 sort_key,
1338 }
1339 } else {
1340 MatchScore::Weak {
1341 score,
1342 sort_text,
1343 sort_key,
1344 }
1345 }
1346 });
1347 }
1348
1349 for mat in &mut matches {
1350 let completion = &completions[mat.candidate_id];
1351 mat.string.clone_from(&completion.label.text);
1352 for position in &mut mat.positions {
1353 *position += completion.label.filter_range.start;
1354 }
1355 }
1356 drop(completions);
1357
1358 self.matches = matches.into();
1359 self.selected_item = 0;
1360 }
1361}
1362
1363struct AvailableCodeAction {
1364 excerpt_id: ExcerptId,
1365 action: CodeAction,
1366 provider: Arc<dyn CodeActionProvider>,
1367}
1368
1369#[derive(Clone)]
1370struct CodeActionContents {
1371 tasks: Option<Arc<ResolvedTasks>>,
1372 actions: Option<Arc<[AvailableCodeAction]>>,
1373}
1374
1375impl CodeActionContents {
1376 fn len(&self) -> usize {
1377 match (&self.tasks, &self.actions) {
1378 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1379 (Some(tasks), None) => tasks.templates.len(),
1380 (None, Some(actions)) => actions.len(),
1381 (None, None) => 0,
1382 }
1383 }
1384
1385 fn is_empty(&self) -> bool {
1386 match (&self.tasks, &self.actions) {
1387 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1388 (Some(tasks), None) => tasks.templates.is_empty(),
1389 (None, Some(actions)) => actions.is_empty(),
1390 (None, None) => true,
1391 }
1392 }
1393
1394 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1395 self.tasks
1396 .iter()
1397 .flat_map(|tasks| {
1398 tasks
1399 .templates
1400 .iter()
1401 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1402 })
1403 .chain(self.actions.iter().flat_map(|actions| {
1404 actions.iter().map(|available| CodeActionsItem::CodeAction {
1405 excerpt_id: available.excerpt_id,
1406 action: available.action.clone(),
1407 provider: available.provider.clone(),
1408 })
1409 }))
1410 }
1411 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1412 match (&self.tasks, &self.actions) {
1413 (Some(tasks), Some(actions)) => {
1414 if index < tasks.templates.len() {
1415 tasks
1416 .templates
1417 .get(index)
1418 .cloned()
1419 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1420 } else {
1421 actions.get(index - tasks.templates.len()).map(|available| {
1422 CodeActionsItem::CodeAction {
1423 excerpt_id: available.excerpt_id,
1424 action: available.action.clone(),
1425 provider: available.provider.clone(),
1426 }
1427 })
1428 }
1429 }
1430 (Some(tasks), None) => tasks
1431 .templates
1432 .get(index)
1433 .cloned()
1434 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1435 (None, Some(actions)) => {
1436 actions
1437 .get(index)
1438 .map(|available| CodeActionsItem::CodeAction {
1439 excerpt_id: available.excerpt_id,
1440 action: available.action.clone(),
1441 provider: available.provider.clone(),
1442 })
1443 }
1444 (None, None) => None,
1445 }
1446 }
1447}
1448
1449#[allow(clippy::large_enum_variant)]
1450#[derive(Clone)]
1451enum CodeActionsItem {
1452 Task(TaskSourceKind, ResolvedTask),
1453 CodeAction {
1454 excerpt_id: ExcerptId,
1455 action: CodeAction,
1456 provider: Arc<dyn CodeActionProvider>,
1457 },
1458}
1459
1460impl CodeActionsItem {
1461 fn as_task(&self) -> Option<&ResolvedTask> {
1462 let Self::Task(_, task) = self else {
1463 return None;
1464 };
1465 Some(task)
1466 }
1467 fn as_code_action(&self) -> Option<&CodeAction> {
1468 let Self::CodeAction { action, .. } = self else {
1469 return None;
1470 };
1471 Some(action)
1472 }
1473 fn label(&self) -> String {
1474 match self {
1475 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1476 Self::Task(_, task) => task.resolved_label.clone(),
1477 }
1478 }
1479}
1480
1481struct CodeActionsMenu {
1482 actions: CodeActionContents,
1483 buffer: Model<Buffer>,
1484 selected_item: usize,
1485 scroll_handle: UniformListScrollHandle,
1486 deployed_from_indicator: Option<DisplayRow>,
1487}
1488
1489impl CodeActionsMenu {
1490 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1491 self.selected_item = 0;
1492 self.scroll_handle.scroll_to_item(self.selected_item);
1493 cx.notify()
1494 }
1495
1496 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1497 if self.selected_item > 0 {
1498 self.selected_item -= 1;
1499 } else {
1500 self.selected_item = self.actions.len() - 1;
1501 }
1502 self.scroll_handle.scroll_to_item(self.selected_item);
1503 cx.notify();
1504 }
1505
1506 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1507 if self.selected_item + 1 < self.actions.len() {
1508 self.selected_item += 1;
1509 } else {
1510 self.selected_item = 0;
1511 }
1512 self.scroll_handle.scroll_to_item(self.selected_item);
1513 cx.notify();
1514 }
1515
1516 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1517 self.selected_item = self.actions.len() - 1;
1518 self.scroll_handle.scroll_to_item(self.selected_item);
1519 cx.notify()
1520 }
1521
1522 fn visible(&self) -> bool {
1523 !self.actions.is_empty()
1524 }
1525
1526 fn render(
1527 &self,
1528 cursor_position: DisplayPoint,
1529 _style: &EditorStyle,
1530 max_height: Pixels,
1531 cx: &mut ViewContext<Editor>,
1532 ) -> (ContextMenuOrigin, AnyElement) {
1533 let actions = self.actions.clone();
1534 let selected_item = self.selected_item;
1535 let element = uniform_list(
1536 cx.view().clone(),
1537 "code_actions_menu",
1538 self.actions.len(),
1539 move |_this, range, cx| {
1540 actions
1541 .iter()
1542 .skip(range.start)
1543 .take(range.end - range.start)
1544 .enumerate()
1545 .map(|(ix, action)| {
1546 let item_ix = range.start + ix;
1547 let selected = selected_item == item_ix;
1548 let colors = cx.theme().colors();
1549 div()
1550 .px_1()
1551 .rounded_md()
1552 .text_color(colors.text)
1553 .when(selected, |style| {
1554 style
1555 .bg(colors.element_active)
1556 .text_color(colors.text_accent)
1557 })
1558 .hover(|style| {
1559 style
1560 .bg(colors.element_hover)
1561 .text_color(colors.text_accent)
1562 })
1563 .whitespace_nowrap()
1564 .when_some(action.as_code_action(), |this, action| {
1565 this.on_mouse_down(
1566 MouseButton::Left,
1567 cx.listener(move |editor, _, cx| {
1568 cx.stop_propagation();
1569 if let Some(task) = editor.confirm_code_action(
1570 &ConfirmCodeAction {
1571 item_ix: Some(item_ix),
1572 },
1573 cx,
1574 ) {
1575 task.detach_and_log_err(cx)
1576 }
1577 }),
1578 )
1579 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1580 .child(SharedString::from(action.lsp_action.title.clone()))
1581 })
1582 .when_some(action.as_task(), |this, task| {
1583 this.on_mouse_down(
1584 MouseButton::Left,
1585 cx.listener(move |editor, _, cx| {
1586 cx.stop_propagation();
1587 if let Some(task) = editor.confirm_code_action(
1588 &ConfirmCodeAction {
1589 item_ix: Some(item_ix),
1590 },
1591 cx,
1592 ) {
1593 task.detach_and_log_err(cx)
1594 }
1595 }),
1596 )
1597 .child(SharedString::from(task.resolved_label.clone()))
1598 })
1599 })
1600 .collect()
1601 },
1602 )
1603 .elevation_1(cx)
1604 .p_1()
1605 .max_h(max_height)
1606 .occlude()
1607 .track_scroll(self.scroll_handle.clone())
1608 .with_width_from_item(
1609 self.actions
1610 .iter()
1611 .enumerate()
1612 .max_by_key(|(_, action)| match action {
1613 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1614 CodeActionsItem::CodeAction { action, .. } => {
1615 action.lsp_action.title.chars().count()
1616 }
1617 })
1618 .map(|(ix, _)| ix),
1619 )
1620 .with_sizing_behavior(ListSizingBehavior::Infer)
1621 .into_any_element();
1622
1623 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1624 ContextMenuOrigin::GutterIndicator(row)
1625 } else {
1626 ContextMenuOrigin::EditorPoint(cursor_position)
1627 };
1628
1629 (cursor_position, element)
1630 }
1631}
1632
1633#[derive(Debug)]
1634struct ActiveDiagnosticGroup {
1635 primary_range: Range<Anchor>,
1636 primary_message: String,
1637 group_id: usize,
1638 blocks: HashMap<CustomBlockId, Diagnostic>,
1639 is_valid: bool,
1640}
1641
1642#[derive(Serialize, Deserialize, Clone, Debug)]
1643pub struct ClipboardSelection {
1644 pub len: usize,
1645 pub is_entire_line: bool,
1646 pub first_line_indent: u32,
1647}
1648
1649#[derive(Debug)]
1650pub(crate) struct NavigationData {
1651 cursor_anchor: Anchor,
1652 cursor_position: Point,
1653 scroll_anchor: ScrollAnchor,
1654 scroll_top_row: u32,
1655}
1656
1657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1658enum GotoDefinitionKind {
1659 Symbol,
1660 Declaration,
1661 Type,
1662 Implementation,
1663}
1664
1665#[derive(Debug, Clone)]
1666enum InlayHintRefreshReason {
1667 Toggle(bool),
1668 SettingsChange(InlayHintSettings),
1669 NewLinesShown,
1670 BufferEdited(HashSet<Arc<Language>>),
1671 RefreshRequested,
1672 ExcerptsRemoved(Vec<ExcerptId>),
1673}
1674
1675impl InlayHintRefreshReason {
1676 fn description(&self) -> &'static str {
1677 match self {
1678 Self::Toggle(_) => "toggle",
1679 Self::SettingsChange(_) => "settings change",
1680 Self::NewLinesShown => "new lines shown",
1681 Self::BufferEdited(_) => "buffer edited",
1682 Self::RefreshRequested => "refresh requested",
1683 Self::ExcerptsRemoved(_) => "excerpts removed",
1684 }
1685 }
1686}
1687
1688pub(crate) struct FocusedBlock {
1689 id: BlockId,
1690 focus_handle: WeakFocusHandle,
1691}
1692
1693impl Editor {
1694 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1695 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1696 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1697 Self::new(
1698 EditorMode::SingleLine { auto_width: false },
1699 buffer,
1700 None,
1701 false,
1702 cx,
1703 )
1704 }
1705
1706 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1707 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1708 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1709 Self::new(EditorMode::Full, buffer, None, false, cx)
1710 }
1711
1712 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1713 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1714 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1715 Self::new(
1716 EditorMode::SingleLine { auto_width: true },
1717 buffer,
1718 None,
1719 false,
1720 cx,
1721 )
1722 }
1723
1724 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1725 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1726 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1727 Self::new(
1728 EditorMode::AutoHeight { max_lines },
1729 buffer,
1730 None,
1731 false,
1732 cx,
1733 )
1734 }
1735
1736 pub fn for_buffer(
1737 buffer: Model<Buffer>,
1738 project: Option<Model<Project>>,
1739 cx: &mut ViewContext<Self>,
1740 ) -> Self {
1741 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1742 Self::new(EditorMode::Full, buffer, project, false, cx)
1743 }
1744
1745 pub fn for_multibuffer(
1746 buffer: Model<MultiBuffer>,
1747 project: Option<Model<Project>>,
1748 show_excerpt_controls: bool,
1749 cx: &mut ViewContext<Self>,
1750 ) -> Self {
1751 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1752 }
1753
1754 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1755 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1756 let mut clone = Self::new(
1757 self.mode,
1758 self.buffer.clone(),
1759 self.project.clone(),
1760 show_excerpt_controls,
1761 cx,
1762 );
1763 self.display_map.update(cx, |display_map, cx| {
1764 let snapshot = display_map.snapshot(cx);
1765 clone.display_map.update(cx, |display_map, cx| {
1766 display_map.set_state(&snapshot, cx);
1767 });
1768 });
1769 clone.selections.clone_state(&self.selections);
1770 clone.scroll_manager.clone_state(&self.scroll_manager);
1771 clone.searchable = self.searchable;
1772 clone
1773 }
1774
1775 pub fn new(
1776 mode: EditorMode,
1777 buffer: Model<MultiBuffer>,
1778 project: Option<Model<Project>>,
1779 show_excerpt_controls: bool,
1780 cx: &mut ViewContext<Self>,
1781 ) -> Self {
1782 let style = cx.text_style();
1783 let font_size = style.font_size.to_pixels(cx.rem_size());
1784 let editor = cx.view().downgrade();
1785 let fold_placeholder = FoldPlaceholder {
1786 constrain_width: true,
1787 render: Arc::new(move |fold_id, fold_range, cx| {
1788 let editor = editor.clone();
1789 div()
1790 .id(fold_id)
1791 .bg(cx.theme().colors().ghost_element_background)
1792 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1793 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1794 .rounded_sm()
1795 .size_full()
1796 .cursor_pointer()
1797 .child("⋯")
1798 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1799 .on_click(move |_, cx| {
1800 editor
1801 .update(cx, |editor, cx| {
1802 editor.unfold_ranges(
1803 [fold_range.start..fold_range.end],
1804 true,
1805 false,
1806 cx,
1807 );
1808 cx.stop_propagation();
1809 })
1810 .ok();
1811 })
1812 .into_any()
1813 }),
1814 merge_adjacent: true,
1815 };
1816 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1817 let display_map = cx.new_model(|cx| {
1818 DisplayMap::new(
1819 buffer.clone(),
1820 style.font(),
1821 font_size,
1822 None,
1823 show_excerpt_controls,
1824 file_header_size,
1825 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1826 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1827 fold_placeholder,
1828 cx,
1829 )
1830 });
1831
1832 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1833
1834 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1835
1836 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1837 .then(|| language_settings::SoftWrap::PreferLine);
1838
1839 let mut project_subscriptions = Vec::new();
1840 if mode == EditorMode::Full {
1841 if let Some(project) = project.as_ref() {
1842 if buffer.read(cx).is_singleton() {
1843 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1844 cx.emit(EditorEvent::TitleChanged);
1845 }));
1846 }
1847 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1848 if let project::Event::RefreshInlayHints = event {
1849 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1850 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1851 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1852 let focus_handle = editor.focus_handle(cx);
1853 if focus_handle.is_focused(cx) {
1854 let snapshot = buffer.read(cx).snapshot();
1855 for (range, snippet) in snippet_edits {
1856 let editor_range =
1857 language::range_from_lsp(*range).to_offset(&snapshot);
1858 editor
1859 .insert_snippet(&[editor_range], snippet.clone(), cx)
1860 .ok();
1861 }
1862 }
1863 }
1864 }
1865 }));
1866 let task_inventory = project.read(cx).task_inventory().clone();
1867 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1868 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1869 }));
1870 }
1871 }
1872
1873 let inlay_hint_settings = inlay_hint_settings(
1874 selections.newest_anchor().head(),
1875 &buffer.read(cx).snapshot(cx),
1876 cx,
1877 );
1878 let focus_handle = cx.focus_handle();
1879 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1880 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1881 .detach();
1882 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1883 .detach();
1884 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1885
1886 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1887 Some(false)
1888 } else {
1889 None
1890 };
1891
1892 let mut code_action_providers = Vec::new();
1893 if let Some(project) = project.clone() {
1894 code_action_providers.push(Arc::new(project) as Arc<_>);
1895 }
1896
1897 let mut this = Self {
1898 focus_handle,
1899 show_cursor_when_unfocused: false,
1900 last_focused_descendant: None,
1901 buffer: buffer.clone(),
1902 display_map: display_map.clone(),
1903 selections,
1904 scroll_manager: ScrollManager::new(cx),
1905 columnar_selection_tail: None,
1906 add_selections_state: None,
1907 select_next_state: None,
1908 select_prev_state: None,
1909 selection_history: Default::default(),
1910 autoclose_regions: Default::default(),
1911 snippet_stack: Default::default(),
1912 select_larger_syntax_node_stack: Vec::new(),
1913 ime_transaction: Default::default(),
1914 active_diagnostics: None,
1915 soft_wrap_mode_override,
1916 completion_provider: project.clone().map(|project| Box::new(project) as _),
1917 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1918 project,
1919 blink_manager: blink_manager.clone(),
1920 show_local_selections: true,
1921 mode,
1922 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1923 show_gutter: mode == EditorMode::Full,
1924 show_line_numbers: None,
1925 use_relative_line_numbers: None,
1926 show_git_diff_gutter: None,
1927 show_code_actions: None,
1928 show_runnables: None,
1929 show_wrap_guides: None,
1930 show_indent_guides,
1931 placeholder_text: None,
1932 highlight_order: 0,
1933 highlighted_rows: HashMap::default(),
1934 background_highlights: Default::default(),
1935 gutter_highlights: TreeMap::default(),
1936 scrollbar_marker_state: ScrollbarMarkerState::default(),
1937 active_indent_guides_state: ActiveIndentGuidesState::default(),
1938 nav_history: None,
1939 context_menu: RwLock::new(None),
1940 mouse_context_menu: None,
1941 completion_tasks: Default::default(),
1942 signature_help_state: SignatureHelpState::default(),
1943 auto_signature_help: None,
1944 find_all_references_task_sources: Vec::new(),
1945 next_completion_id: 0,
1946 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1947 next_inlay_id: 0,
1948 code_action_providers,
1949 available_code_actions: Default::default(),
1950 code_actions_task: Default::default(),
1951 document_highlights_task: Default::default(),
1952 linked_editing_range_task: Default::default(),
1953 pending_rename: Default::default(),
1954 searchable: true,
1955 cursor_shape: EditorSettings::get_global(cx)
1956 .cursor_shape
1957 .unwrap_or_default(),
1958 current_line_highlight: None,
1959 autoindent_mode: Some(AutoindentMode::EachLine),
1960 collapse_matches: false,
1961 workspace: None,
1962 input_enabled: true,
1963 use_modal_editing: mode == EditorMode::Full,
1964 read_only: false,
1965 use_autoclose: true,
1966 use_auto_surround: true,
1967 auto_replace_emoji_shortcode: false,
1968 leader_peer_id: None,
1969 remote_id: None,
1970 hover_state: Default::default(),
1971 hovered_link_state: Default::default(),
1972 inline_completion_provider: None,
1973 active_inline_completion: None,
1974 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1975 expanded_hunks: ExpandedHunks::default(),
1976 gutter_hovered: false,
1977 pixel_position_of_newest_cursor: None,
1978 last_bounds: None,
1979 expect_bounds_change: None,
1980 gutter_dimensions: GutterDimensions::default(),
1981 style: None,
1982 show_cursor_names: false,
1983 hovered_cursors: Default::default(),
1984 next_editor_action_id: EditorActionId::default(),
1985 editor_actions: Rc::default(),
1986 show_inline_completions_override: None,
1987 enable_inline_completions: true,
1988 custom_context_menu: None,
1989 show_git_blame_gutter: false,
1990 show_git_blame_inline: false,
1991 show_selection_menu: None,
1992 show_git_blame_inline_delay_task: None,
1993 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1994 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1995 .session
1996 .restore_unsaved_buffers,
1997 blame: None,
1998 blame_subscription: None,
1999 file_header_size,
2000 tasks: Default::default(),
2001 _subscriptions: vec![
2002 cx.observe(&buffer, Self::on_buffer_changed),
2003 cx.subscribe(&buffer, Self::on_buffer_event),
2004 cx.observe(&display_map, Self::on_display_map_changed),
2005 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2006 cx.observe_global::<SettingsStore>(Self::settings_changed),
2007 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2008 cx.observe_window_activation(|editor, cx| {
2009 let active = cx.is_window_active();
2010 editor.blink_manager.update(cx, |blink_manager, cx| {
2011 if active {
2012 blink_manager.enable(cx);
2013 } else {
2014 blink_manager.disable(cx);
2015 }
2016 });
2017 }),
2018 ],
2019 tasks_update_task: None,
2020 linked_edit_ranges: Default::default(),
2021 previous_search_ranges: None,
2022 breadcrumb_header: None,
2023 focused_block: None,
2024 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2025 addons: HashMap::default(),
2026 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2027 };
2028 this.tasks_update_task = Some(this.refresh_runnables(cx));
2029 this._subscriptions.extend(project_subscriptions);
2030
2031 this.end_selection(cx);
2032 this.scroll_manager.show_scrollbar(cx);
2033
2034 if mode == EditorMode::Full {
2035 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2036 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2037
2038 if this.git_blame_inline_enabled {
2039 this.git_blame_inline_enabled = true;
2040 this.start_git_blame_inline(false, cx);
2041 }
2042 }
2043
2044 this.report_editor_event("open", None, cx);
2045 this
2046 }
2047
2048 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2049 self.mouse_context_menu
2050 .as_ref()
2051 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2052 }
2053
2054 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2055 let mut key_context = KeyContext::new_with_defaults();
2056 key_context.add("Editor");
2057 let mode = match self.mode {
2058 EditorMode::SingleLine { .. } => "single_line",
2059 EditorMode::AutoHeight { .. } => "auto_height",
2060 EditorMode::Full => "full",
2061 };
2062
2063 if EditorSettings::jupyter_enabled(cx) {
2064 key_context.add("jupyter");
2065 }
2066
2067 key_context.set("mode", mode);
2068 if self.pending_rename.is_some() {
2069 key_context.add("renaming");
2070 }
2071 if self.context_menu_visible() {
2072 match self.context_menu.read().as_ref() {
2073 Some(ContextMenu::Completions(_)) => {
2074 key_context.add("menu");
2075 key_context.add("showing_completions")
2076 }
2077 Some(ContextMenu::CodeActions(_)) => {
2078 key_context.add("menu");
2079 key_context.add("showing_code_actions")
2080 }
2081 None => {}
2082 }
2083 }
2084
2085 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2086 if !self.focus_handle(cx).contains_focused(cx)
2087 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2088 {
2089 for addon in self.addons.values() {
2090 addon.extend_key_context(&mut key_context, cx)
2091 }
2092 }
2093
2094 if let Some(extension) = self
2095 .buffer
2096 .read(cx)
2097 .as_singleton()
2098 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2099 {
2100 key_context.set("extension", extension.to_string());
2101 }
2102
2103 if self.has_active_inline_completion(cx) {
2104 key_context.add("copilot_suggestion");
2105 key_context.add("inline_completion");
2106 }
2107
2108 key_context
2109 }
2110
2111 pub fn new_file(
2112 workspace: &mut Workspace,
2113 _: &workspace::NewFile,
2114 cx: &mut ViewContext<Workspace>,
2115 ) {
2116 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2117 "Failed to create buffer",
2118 cx,
2119 |e, _| match e.error_code() {
2120 ErrorCode::RemoteUpgradeRequired => Some(format!(
2121 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2122 e.error_tag("required").unwrap_or("the latest version")
2123 )),
2124 _ => None,
2125 },
2126 );
2127 }
2128
2129 pub fn new_in_workspace(
2130 workspace: &mut Workspace,
2131 cx: &mut ViewContext<Workspace>,
2132 ) -> Task<Result<View<Editor>>> {
2133 let project = workspace.project().clone();
2134 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2135
2136 cx.spawn(|workspace, mut cx| async move {
2137 let buffer = create.await?;
2138 workspace.update(&mut cx, |workspace, cx| {
2139 let editor =
2140 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2141 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2142 editor
2143 })
2144 })
2145 }
2146
2147 fn new_file_vertical(
2148 workspace: &mut Workspace,
2149 _: &workspace::NewFileSplitVertical,
2150 cx: &mut ViewContext<Workspace>,
2151 ) {
2152 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2153 }
2154
2155 fn new_file_horizontal(
2156 workspace: &mut Workspace,
2157 _: &workspace::NewFileSplitHorizontal,
2158 cx: &mut ViewContext<Workspace>,
2159 ) {
2160 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2161 }
2162
2163 fn new_file_in_direction(
2164 workspace: &mut Workspace,
2165 direction: SplitDirection,
2166 cx: &mut ViewContext<Workspace>,
2167 ) {
2168 let project = workspace.project().clone();
2169 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2170
2171 cx.spawn(|workspace, mut cx| async move {
2172 let buffer = create.await?;
2173 workspace.update(&mut cx, move |workspace, cx| {
2174 workspace.split_item(
2175 direction,
2176 Box::new(
2177 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2178 ),
2179 cx,
2180 )
2181 })?;
2182 anyhow::Ok(())
2183 })
2184 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2185 ErrorCode::RemoteUpgradeRequired => Some(format!(
2186 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2187 e.error_tag("required").unwrap_or("the latest version")
2188 )),
2189 _ => None,
2190 });
2191 }
2192
2193 pub fn leader_peer_id(&self) -> Option<PeerId> {
2194 self.leader_peer_id
2195 }
2196
2197 pub fn buffer(&self) -> &Model<MultiBuffer> {
2198 &self.buffer
2199 }
2200
2201 pub fn workspace(&self) -> Option<View<Workspace>> {
2202 self.workspace.as_ref()?.0.upgrade()
2203 }
2204
2205 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2206 self.buffer().read(cx).title(cx)
2207 }
2208
2209 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2210 EditorSnapshot {
2211 mode: self.mode,
2212 show_gutter: self.show_gutter,
2213 show_line_numbers: self.show_line_numbers,
2214 show_git_diff_gutter: self.show_git_diff_gutter,
2215 show_code_actions: self.show_code_actions,
2216 show_runnables: self.show_runnables,
2217 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2218 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2219 scroll_anchor: self.scroll_manager.anchor(),
2220 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2221 placeholder_text: self.placeholder_text.clone(),
2222 is_focused: self.focus_handle.is_focused(cx),
2223 current_line_highlight: self
2224 .current_line_highlight
2225 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2226 gutter_hovered: self.gutter_hovered,
2227 }
2228 }
2229
2230 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2231 self.buffer.read(cx).language_at(point, cx)
2232 }
2233
2234 pub fn file_at<T: ToOffset>(
2235 &self,
2236 point: T,
2237 cx: &AppContext,
2238 ) -> Option<Arc<dyn language::File>> {
2239 self.buffer.read(cx).read(cx).file_at(point).cloned()
2240 }
2241
2242 pub fn active_excerpt(
2243 &self,
2244 cx: &AppContext,
2245 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2246 self.buffer
2247 .read(cx)
2248 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2249 }
2250
2251 pub fn mode(&self) -> EditorMode {
2252 self.mode
2253 }
2254
2255 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2256 self.collaboration_hub.as_deref()
2257 }
2258
2259 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2260 self.collaboration_hub = Some(hub);
2261 }
2262
2263 pub fn set_custom_context_menu(
2264 &mut self,
2265 f: impl 'static
2266 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2267 ) {
2268 self.custom_context_menu = Some(Box::new(f))
2269 }
2270
2271 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2272 self.completion_provider = Some(provider);
2273 }
2274
2275 pub fn set_inline_completion_provider<T>(
2276 &mut self,
2277 provider: Option<Model<T>>,
2278 cx: &mut ViewContext<Self>,
2279 ) where
2280 T: InlineCompletionProvider,
2281 {
2282 self.inline_completion_provider =
2283 provider.map(|provider| RegisteredInlineCompletionProvider {
2284 _subscription: cx.observe(&provider, |this, _, cx| {
2285 if this.focus_handle.is_focused(cx) {
2286 this.update_visible_inline_completion(cx);
2287 }
2288 }),
2289 provider: Arc::new(provider),
2290 });
2291 self.refresh_inline_completion(false, false, cx);
2292 }
2293
2294 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2295 self.placeholder_text.as_deref()
2296 }
2297
2298 pub fn set_placeholder_text(
2299 &mut self,
2300 placeholder_text: impl Into<Arc<str>>,
2301 cx: &mut ViewContext<Self>,
2302 ) {
2303 let placeholder_text = Some(placeholder_text.into());
2304 if self.placeholder_text != placeholder_text {
2305 self.placeholder_text = placeholder_text;
2306 cx.notify();
2307 }
2308 }
2309
2310 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2311 self.cursor_shape = cursor_shape;
2312
2313 // Disrupt blink for immediate user feedback that the cursor shape has changed
2314 self.blink_manager.update(cx, BlinkManager::show_cursor);
2315
2316 cx.notify();
2317 }
2318
2319 pub fn set_current_line_highlight(
2320 &mut self,
2321 current_line_highlight: Option<CurrentLineHighlight>,
2322 ) {
2323 self.current_line_highlight = current_line_highlight;
2324 }
2325
2326 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2327 self.collapse_matches = collapse_matches;
2328 }
2329
2330 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2331 if self.collapse_matches {
2332 return range.start..range.start;
2333 }
2334 range.clone()
2335 }
2336
2337 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2338 if self.display_map.read(cx).clip_at_line_ends != clip {
2339 self.display_map
2340 .update(cx, |map, _| map.clip_at_line_ends = clip);
2341 }
2342 }
2343
2344 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2345 self.input_enabled = input_enabled;
2346 }
2347
2348 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2349 self.enable_inline_completions = enabled;
2350 }
2351
2352 pub fn set_autoindent(&mut self, autoindent: bool) {
2353 if autoindent {
2354 self.autoindent_mode = Some(AutoindentMode::EachLine);
2355 } else {
2356 self.autoindent_mode = None;
2357 }
2358 }
2359
2360 pub fn read_only(&self, cx: &AppContext) -> bool {
2361 self.read_only || self.buffer.read(cx).read_only()
2362 }
2363
2364 pub fn set_read_only(&mut self, read_only: bool) {
2365 self.read_only = read_only;
2366 }
2367
2368 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2369 self.use_autoclose = autoclose;
2370 }
2371
2372 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2373 self.use_auto_surround = auto_surround;
2374 }
2375
2376 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2377 self.auto_replace_emoji_shortcode = auto_replace;
2378 }
2379
2380 pub fn toggle_inline_completions(
2381 &mut self,
2382 _: &ToggleInlineCompletions,
2383 cx: &mut ViewContext<Self>,
2384 ) {
2385 if self.show_inline_completions_override.is_some() {
2386 self.set_show_inline_completions(None, cx);
2387 } else {
2388 let cursor = self.selections.newest_anchor().head();
2389 if let Some((buffer, cursor_buffer_position)) =
2390 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2391 {
2392 let show_inline_completions =
2393 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2394 self.set_show_inline_completions(Some(show_inline_completions), cx);
2395 }
2396 }
2397 }
2398
2399 pub fn set_show_inline_completions(
2400 &mut self,
2401 show_inline_completions: Option<bool>,
2402 cx: &mut ViewContext<Self>,
2403 ) {
2404 self.show_inline_completions_override = show_inline_completions;
2405 self.refresh_inline_completion(false, true, cx);
2406 }
2407
2408 fn should_show_inline_completions(
2409 &self,
2410 buffer: &Model<Buffer>,
2411 buffer_position: language::Anchor,
2412 cx: &AppContext,
2413 ) -> bool {
2414 if let Some(provider) = self.inline_completion_provider() {
2415 if let Some(show_inline_completions) = self.show_inline_completions_override {
2416 show_inline_completions
2417 } else {
2418 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2419 }
2420 } else {
2421 false
2422 }
2423 }
2424
2425 pub fn set_use_modal_editing(&mut self, to: bool) {
2426 self.use_modal_editing = to;
2427 }
2428
2429 pub fn use_modal_editing(&self) -> bool {
2430 self.use_modal_editing
2431 }
2432
2433 fn selections_did_change(
2434 &mut self,
2435 local: bool,
2436 old_cursor_position: &Anchor,
2437 show_completions: bool,
2438 cx: &mut ViewContext<Self>,
2439 ) {
2440 cx.invalidate_character_coordinates();
2441
2442 // Copy selections to primary selection buffer
2443 #[cfg(target_os = "linux")]
2444 if local {
2445 let selections = self.selections.all::<usize>(cx);
2446 let buffer_handle = self.buffer.read(cx).read(cx);
2447
2448 let mut text = String::new();
2449 for (index, selection) in selections.iter().enumerate() {
2450 let text_for_selection = buffer_handle
2451 .text_for_range(selection.start..selection.end)
2452 .collect::<String>();
2453
2454 text.push_str(&text_for_selection);
2455 if index != selections.len() - 1 {
2456 text.push('\n');
2457 }
2458 }
2459
2460 if !text.is_empty() {
2461 cx.write_to_primary(ClipboardItem::new_string(text));
2462 }
2463 }
2464
2465 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2466 self.buffer.update(cx, |buffer, cx| {
2467 buffer.set_active_selections(
2468 &self.selections.disjoint_anchors(),
2469 self.selections.line_mode,
2470 self.cursor_shape,
2471 cx,
2472 )
2473 });
2474 }
2475 let display_map = self
2476 .display_map
2477 .update(cx, |display_map, cx| display_map.snapshot(cx));
2478 let buffer = &display_map.buffer_snapshot;
2479 self.add_selections_state = None;
2480 self.select_next_state = None;
2481 self.select_prev_state = None;
2482 self.select_larger_syntax_node_stack.clear();
2483 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2484 self.snippet_stack
2485 .invalidate(&self.selections.disjoint_anchors(), buffer);
2486 self.take_rename(false, cx);
2487
2488 let new_cursor_position = self.selections.newest_anchor().head();
2489
2490 self.push_to_nav_history(
2491 *old_cursor_position,
2492 Some(new_cursor_position.to_point(buffer)),
2493 cx,
2494 );
2495
2496 if local {
2497 let new_cursor_position = self.selections.newest_anchor().head();
2498 let mut context_menu = self.context_menu.write();
2499 let completion_menu = match context_menu.as_ref() {
2500 Some(ContextMenu::Completions(menu)) => Some(menu),
2501
2502 _ => {
2503 *context_menu = None;
2504 None
2505 }
2506 };
2507
2508 if let Some(completion_menu) = completion_menu {
2509 let cursor_position = new_cursor_position.to_offset(buffer);
2510 let (word_range, kind) =
2511 buffer.surrounding_word(completion_menu.initial_position, true);
2512 if kind == Some(CharKind::Word)
2513 && word_range.to_inclusive().contains(&cursor_position)
2514 {
2515 let mut completion_menu = completion_menu.clone();
2516 drop(context_menu);
2517
2518 let query = Self::completion_query(buffer, cursor_position);
2519 cx.spawn(move |this, mut cx| async move {
2520 completion_menu
2521 .filter(query.as_deref(), cx.background_executor().clone())
2522 .await;
2523
2524 this.update(&mut cx, |this, cx| {
2525 let mut context_menu = this.context_menu.write();
2526 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2527 return;
2528 };
2529
2530 if menu.id > completion_menu.id {
2531 return;
2532 }
2533
2534 *context_menu = Some(ContextMenu::Completions(completion_menu));
2535 drop(context_menu);
2536 cx.notify();
2537 })
2538 })
2539 .detach();
2540
2541 if show_completions {
2542 self.show_completions(&ShowCompletions { trigger: None }, cx);
2543 }
2544 } else {
2545 drop(context_menu);
2546 self.hide_context_menu(cx);
2547 }
2548 } else {
2549 drop(context_menu);
2550 }
2551
2552 hide_hover(self, cx);
2553
2554 if old_cursor_position.to_display_point(&display_map).row()
2555 != new_cursor_position.to_display_point(&display_map).row()
2556 {
2557 self.available_code_actions.take();
2558 }
2559 self.refresh_code_actions(cx);
2560 self.refresh_document_highlights(cx);
2561 refresh_matching_bracket_highlights(self, cx);
2562 self.discard_inline_completion(false, cx);
2563 linked_editing_ranges::refresh_linked_ranges(self, cx);
2564 if self.git_blame_inline_enabled {
2565 self.start_inline_blame_timer(cx);
2566 }
2567 }
2568
2569 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2570 cx.emit(EditorEvent::SelectionsChanged { local });
2571
2572 if self.selections.disjoint_anchors().len() == 1 {
2573 cx.emit(SearchEvent::ActiveMatchChanged)
2574 }
2575 cx.notify();
2576 }
2577
2578 pub fn change_selections<R>(
2579 &mut self,
2580 autoscroll: Option<Autoscroll>,
2581 cx: &mut ViewContext<Self>,
2582 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2583 ) -> R {
2584 self.change_selections_inner(autoscroll, true, cx, change)
2585 }
2586
2587 pub fn change_selections_inner<R>(
2588 &mut self,
2589 autoscroll: Option<Autoscroll>,
2590 request_completions: bool,
2591 cx: &mut ViewContext<Self>,
2592 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2593 ) -> R {
2594 let old_cursor_position = self.selections.newest_anchor().head();
2595 self.push_to_selection_history();
2596
2597 let (changed, result) = self.selections.change_with(cx, change);
2598
2599 if changed {
2600 if let Some(autoscroll) = autoscroll {
2601 self.request_autoscroll(autoscroll, cx);
2602 }
2603 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2604
2605 if self.should_open_signature_help_automatically(
2606 &old_cursor_position,
2607 self.signature_help_state.backspace_pressed(),
2608 cx,
2609 ) {
2610 self.show_signature_help(&ShowSignatureHelp, cx);
2611 }
2612 self.signature_help_state.set_backspace_pressed(false);
2613 }
2614
2615 result
2616 }
2617
2618 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2619 where
2620 I: IntoIterator<Item = (Range<S>, T)>,
2621 S: ToOffset,
2622 T: Into<Arc<str>>,
2623 {
2624 if self.read_only(cx) {
2625 return;
2626 }
2627
2628 self.buffer
2629 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2630 }
2631
2632 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2633 where
2634 I: IntoIterator<Item = (Range<S>, T)>,
2635 S: ToOffset,
2636 T: Into<Arc<str>>,
2637 {
2638 if self.read_only(cx) {
2639 return;
2640 }
2641
2642 self.buffer.update(cx, |buffer, cx| {
2643 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2644 });
2645 }
2646
2647 pub fn edit_with_block_indent<I, S, T>(
2648 &mut self,
2649 edits: I,
2650 original_indent_columns: Vec<u32>,
2651 cx: &mut ViewContext<Self>,
2652 ) where
2653 I: IntoIterator<Item = (Range<S>, T)>,
2654 S: ToOffset,
2655 T: Into<Arc<str>>,
2656 {
2657 if self.read_only(cx) {
2658 return;
2659 }
2660
2661 self.buffer.update(cx, |buffer, cx| {
2662 buffer.edit(
2663 edits,
2664 Some(AutoindentMode::Block {
2665 original_indent_columns,
2666 }),
2667 cx,
2668 )
2669 });
2670 }
2671
2672 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2673 self.hide_context_menu(cx);
2674
2675 match phase {
2676 SelectPhase::Begin {
2677 position,
2678 add,
2679 click_count,
2680 } => self.begin_selection(position, add, click_count, cx),
2681 SelectPhase::BeginColumnar {
2682 position,
2683 goal_column,
2684 reset,
2685 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2686 SelectPhase::Extend {
2687 position,
2688 click_count,
2689 } => self.extend_selection(position, click_count, cx),
2690 SelectPhase::Update {
2691 position,
2692 goal_column,
2693 scroll_delta,
2694 } => self.update_selection(position, goal_column, scroll_delta, cx),
2695 SelectPhase::End => self.end_selection(cx),
2696 }
2697 }
2698
2699 fn extend_selection(
2700 &mut self,
2701 position: DisplayPoint,
2702 click_count: usize,
2703 cx: &mut ViewContext<Self>,
2704 ) {
2705 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2706 let tail = self.selections.newest::<usize>(cx).tail();
2707 self.begin_selection(position, false, click_count, cx);
2708
2709 let position = position.to_offset(&display_map, Bias::Left);
2710 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2711
2712 let mut pending_selection = self
2713 .selections
2714 .pending_anchor()
2715 .expect("extend_selection not called with pending selection");
2716 if position >= tail {
2717 pending_selection.start = tail_anchor;
2718 } else {
2719 pending_selection.end = tail_anchor;
2720 pending_selection.reversed = true;
2721 }
2722
2723 let mut pending_mode = self.selections.pending_mode().unwrap();
2724 match &mut pending_mode {
2725 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2726 _ => {}
2727 }
2728
2729 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2730 s.set_pending(pending_selection, pending_mode)
2731 });
2732 }
2733
2734 fn begin_selection(
2735 &mut self,
2736 position: DisplayPoint,
2737 add: bool,
2738 click_count: usize,
2739 cx: &mut ViewContext<Self>,
2740 ) {
2741 if !self.focus_handle.is_focused(cx) {
2742 self.last_focused_descendant = None;
2743 cx.focus(&self.focus_handle);
2744 }
2745
2746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2747 let buffer = &display_map.buffer_snapshot;
2748 let newest_selection = self.selections.newest_anchor().clone();
2749 let position = display_map.clip_point(position, Bias::Left);
2750
2751 let start;
2752 let end;
2753 let mode;
2754 let auto_scroll;
2755 match click_count {
2756 1 => {
2757 start = buffer.anchor_before(position.to_point(&display_map));
2758 end = start;
2759 mode = SelectMode::Character;
2760 auto_scroll = true;
2761 }
2762 2 => {
2763 let range = movement::surrounding_word(&display_map, position);
2764 start = buffer.anchor_before(range.start.to_point(&display_map));
2765 end = buffer.anchor_before(range.end.to_point(&display_map));
2766 mode = SelectMode::Word(start..end);
2767 auto_scroll = true;
2768 }
2769 3 => {
2770 let position = display_map
2771 .clip_point(position, Bias::Left)
2772 .to_point(&display_map);
2773 let line_start = display_map.prev_line_boundary(position).0;
2774 let next_line_start = buffer.clip_point(
2775 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2776 Bias::Left,
2777 );
2778 start = buffer.anchor_before(line_start);
2779 end = buffer.anchor_before(next_line_start);
2780 mode = SelectMode::Line(start..end);
2781 auto_scroll = true;
2782 }
2783 _ => {
2784 start = buffer.anchor_before(0);
2785 end = buffer.anchor_before(buffer.len());
2786 mode = SelectMode::All;
2787 auto_scroll = false;
2788 }
2789 }
2790
2791 let point_to_delete: Option<usize> = {
2792 let selected_points: Vec<Selection<Point>> =
2793 self.selections.disjoint_in_range(start..end, cx);
2794
2795 if !add || click_count > 1 {
2796 None
2797 } else if !selected_points.is_empty() {
2798 Some(selected_points[0].id)
2799 } else {
2800 let clicked_point_already_selected =
2801 self.selections.disjoint.iter().find(|selection| {
2802 selection.start.to_point(buffer) == start.to_point(buffer)
2803 || selection.end.to_point(buffer) == end.to_point(buffer)
2804 });
2805
2806 clicked_point_already_selected.map(|selection| selection.id)
2807 }
2808 };
2809
2810 let selections_count = self.selections.count();
2811
2812 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2813 if let Some(point_to_delete) = point_to_delete {
2814 s.delete(point_to_delete);
2815
2816 if selections_count == 1 {
2817 s.set_pending_anchor_range(start..end, mode);
2818 }
2819 } else {
2820 if !add {
2821 s.clear_disjoint();
2822 } else if click_count > 1 {
2823 s.delete(newest_selection.id)
2824 }
2825
2826 s.set_pending_anchor_range(start..end, mode);
2827 }
2828 });
2829 }
2830
2831 fn begin_columnar_selection(
2832 &mut self,
2833 position: DisplayPoint,
2834 goal_column: u32,
2835 reset: bool,
2836 cx: &mut ViewContext<Self>,
2837 ) {
2838 if !self.focus_handle.is_focused(cx) {
2839 self.last_focused_descendant = None;
2840 cx.focus(&self.focus_handle);
2841 }
2842
2843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2844
2845 if reset {
2846 let pointer_position = display_map
2847 .buffer_snapshot
2848 .anchor_before(position.to_point(&display_map));
2849
2850 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2851 s.clear_disjoint();
2852 s.set_pending_anchor_range(
2853 pointer_position..pointer_position,
2854 SelectMode::Character,
2855 );
2856 });
2857 }
2858
2859 let tail = self.selections.newest::<Point>(cx).tail();
2860 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2861
2862 if !reset {
2863 self.select_columns(
2864 tail.to_display_point(&display_map),
2865 position,
2866 goal_column,
2867 &display_map,
2868 cx,
2869 );
2870 }
2871 }
2872
2873 fn update_selection(
2874 &mut self,
2875 position: DisplayPoint,
2876 goal_column: u32,
2877 scroll_delta: gpui::Point<f32>,
2878 cx: &mut ViewContext<Self>,
2879 ) {
2880 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2881
2882 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2883 let tail = tail.to_display_point(&display_map);
2884 self.select_columns(tail, position, goal_column, &display_map, cx);
2885 } else if let Some(mut pending) = self.selections.pending_anchor() {
2886 let buffer = self.buffer.read(cx).snapshot(cx);
2887 let head;
2888 let tail;
2889 let mode = self.selections.pending_mode().unwrap();
2890 match &mode {
2891 SelectMode::Character => {
2892 head = position.to_point(&display_map);
2893 tail = pending.tail().to_point(&buffer);
2894 }
2895 SelectMode::Word(original_range) => {
2896 let original_display_range = original_range.start.to_display_point(&display_map)
2897 ..original_range.end.to_display_point(&display_map);
2898 let original_buffer_range = original_display_range.start.to_point(&display_map)
2899 ..original_display_range.end.to_point(&display_map);
2900 if movement::is_inside_word(&display_map, position)
2901 || original_display_range.contains(&position)
2902 {
2903 let word_range = movement::surrounding_word(&display_map, position);
2904 if word_range.start < original_display_range.start {
2905 head = word_range.start.to_point(&display_map);
2906 } else {
2907 head = word_range.end.to_point(&display_map);
2908 }
2909 } else {
2910 head = position.to_point(&display_map);
2911 }
2912
2913 if head <= original_buffer_range.start {
2914 tail = original_buffer_range.end;
2915 } else {
2916 tail = original_buffer_range.start;
2917 }
2918 }
2919 SelectMode::Line(original_range) => {
2920 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2921
2922 let position = display_map
2923 .clip_point(position, Bias::Left)
2924 .to_point(&display_map);
2925 let line_start = display_map.prev_line_boundary(position).0;
2926 let next_line_start = buffer.clip_point(
2927 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2928 Bias::Left,
2929 );
2930
2931 if line_start < original_range.start {
2932 head = line_start
2933 } else {
2934 head = next_line_start
2935 }
2936
2937 if head <= original_range.start {
2938 tail = original_range.end;
2939 } else {
2940 tail = original_range.start;
2941 }
2942 }
2943 SelectMode::All => {
2944 return;
2945 }
2946 };
2947
2948 if head < tail {
2949 pending.start = buffer.anchor_before(head);
2950 pending.end = buffer.anchor_before(tail);
2951 pending.reversed = true;
2952 } else {
2953 pending.start = buffer.anchor_before(tail);
2954 pending.end = buffer.anchor_before(head);
2955 pending.reversed = false;
2956 }
2957
2958 self.change_selections(None, cx, |s| {
2959 s.set_pending(pending, mode);
2960 });
2961 } else {
2962 log::error!("update_selection dispatched with no pending selection");
2963 return;
2964 }
2965
2966 self.apply_scroll_delta(scroll_delta, cx);
2967 cx.notify();
2968 }
2969
2970 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2971 self.columnar_selection_tail.take();
2972 if self.selections.pending_anchor().is_some() {
2973 let selections = self.selections.all::<usize>(cx);
2974 self.change_selections(None, cx, |s| {
2975 s.select(selections);
2976 s.clear_pending();
2977 });
2978 }
2979 }
2980
2981 fn select_columns(
2982 &mut self,
2983 tail: DisplayPoint,
2984 head: DisplayPoint,
2985 goal_column: u32,
2986 display_map: &DisplaySnapshot,
2987 cx: &mut ViewContext<Self>,
2988 ) {
2989 let start_row = cmp::min(tail.row(), head.row());
2990 let end_row = cmp::max(tail.row(), head.row());
2991 let start_column = cmp::min(tail.column(), goal_column);
2992 let end_column = cmp::max(tail.column(), goal_column);
2993 let reversed = start_column < tail.column();
2994
2995 let selection_ranges = (start_row.0..=end_row.0)
2996 .map(DisplayRow)
2997 .filter_map(|row| {
2998 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2999 let start = display_map
3000 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3001 .to_point(display_map);
3002 let end = display_map
3003 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3004 .to_point(display_map);
3005 if reversed {
3006 Some(end..start)
3007 } else {
3008 Some(start..end)
3009 }
3010 } else {
3011 None
3012 }
3013 })
3014 .collect::<Vec<_>>();
3015
3016 self.change_selections(None, cx, |s| {
3017 s.select_ranges(selection_ranges);
3018 });
3019 cx.notify();
3020 }
3021
3022 pub fn has_pending_nonempty_selection(&self) -> bool {
3023 let pending_nonempty_selection = match self.selections.pending_anchor() {
3024 Some(Selection { start, end, .. }) => start != end,
3025 None => false,
3026 };
3027
3028 pending_nonempty_selection
3029 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3030 }
3031
3032 pub fn has_pending_selection(&self) -> bool {
3033 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3034 }
3035
3036 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3037 if self.clear_clicked_diff_hunks(cx) {
3038 cx.notify();
3039 return;
3040 }
3041 if self.dismiss_menus_and_popups(true, cx) {
3042 return;
3043 }
3044
3045 if self.mode == EditorMode::Full
3046 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3047 {
3048 return;
3049 }
3050
3051 cx.propagate();
3052 }
3053
3054 pub fn dismiss_menus_and_popups(
3055 &mut self,
3056 should_report_inline_completion_event: bool,
3057 cx: &mut ViewContext<Self>,
3058 ) -> bool {
3059 if self.take_rename(false, cx).is_some() {
3060 return true;
3061 }
3062
3063 if hide_hover(self, cx) {
3064 return true;
3065 }
3066
3067 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3068 return true;
3069 }
3070
3071 if self.hide_context_menu(cx).is_some() {
3072 return true;
3073 }
3074
3075 if self.mouse_context_menu.take().is_some() {
3076 return true;
3077 }
3078
3079 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3080 return true;
3081 }
3082
3083 if self.snippet_stack.pop().is_some() {
3084 return true;
3085 }
3086
3087 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3088 self.dismiss_diagnostics(cx);
3089 return true;
3090 }
3091
3092 false
3093 }
3094
3095 fn linked_editing_ranges_for(
3096 &self,
3097 selection: Range<text::Anchor>,
3098 cx: &AppContext,
3099 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3100 if self.linked_edit_ranges.is_empty() {
3101 return None;
3102 }
3103 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3104 selection.end.buffer_id.and_then(|end_buffer_id| {
3105 if selection.start.buffer_id != Some(end_buffer_id) {
3106 return None;
3107 }
3108 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3109 let snapshot = buffer.read(cx).snapshot();
3110 self.linked_edit_ranges
3111 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3112 .map(|ranges| (ranges, snapshot, buffer))
3113 })?;
3114 use text::ToOffset as TO;
3115 // find offset from the start of current range to current cursor position
3116 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3117
3118 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3119 let start_difference = start_offset - start_byte_offset;
3120 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3121 let end_difference = end_offset - start_byte_offset;
3122 // Current range has associated linked ranges.
3123 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3124 for range in linked_ranges.iter() {
3125 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3126 let end_offset = start_offset + end_difference;
3127 let start_offset = start_offset + start_difference;
3128 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3129 continue;
3130 }
3131 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3132 if s.start.buffer_id != selection.start.buffer_id
3133 || s.end.buffer_id != selection.end.buffer_id
3134 {
3135 return false;
3136 }
3137 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3138 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3139 }) {
3140 continue;
3141 }
3142 let start = buffer_snapshot.anchor_after(start_offset);
3143 let end = buffer_snapshot.anchor_after(end_offset);
3144 linked_edits
3145 .entry(buffer.clone())
3146 .or_default()
3147 .push(start..end);
3148 }
3149 Some(linked_edits)
3150 }
3151
3152 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3153 let text: Arc<str> = text.into();
3154
3155 if self.read_only(cx) {
3156 return;
3157 }
3158
3159 let selections = self.selections.all_adjusted(cx);
3160 let mut bracket_inserted = false;
3161 let mut edits = Vec::new();
3162 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3163 let mut new_selections = Vec::with_capacity(selections.len());
3164 let mut new_autoclose_regions = Vec::new();
3165 let snapshot = self.buffer.read(cx).read(cx);
3166
3167 for (selection, autoclose_region) in
3168 self.selections_with_autoclose_regions(selections, &snapshot)
3169 {
3170 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3171 // Determine if the inserted text matches the opening or closing
3172 // bracket of any of this language's bracket pairs.
3173 let mut bracket_pair = None;
3174 let mut is_bracket_pair_start = false;
3175 let mut is_bracket_pair_end = false;
3176 if !text.is_empty() {
3177 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3178 // and they are removing the character that triggered IME popup.
3179 for (pair, enabled) in scope.brackets() {
3180 if !pair.close && !pair.surround {
3181 continue;
3182 }
3183
3184 if enabled && pair.start.ends_with(text.as_ref()) {
3185 bracket_pair = Some(pair.clone());
3186 is_bracket_pair_start = true;
3187 break;
3188 }
3189 if pair.end.as_str() == text.as_ref() {
3190 bracket_pair = Some(pair.clone());
3191 is_bracket_pair_end = true;
3192 break;
3193 }
3194 }
3195 }
3196
3197 if let Some(bracket_pair) = bracket_pair {
3198 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3199 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3200 let auto_surround =
3201 self.use_auto_surround && snapshot_settings.use_auto_surround;
3202 if selection.is_empty() {
3203 if is_bracket_pair_start {
3204 let prefix_len = bracket_pair.start.len() - text.len();
3205
3206 // If the inserted text is a suffix of an opening bracket and the
3207 // selection is preceded by the rest of the opening bracket, then
3208 // insert the closing bracket.
3209 let following_text_allows_autoclose = snapshot
3210 .chars_at(selection.start)
3211 .next()
3212 .map_or(true, |c| scope.should_autoclose_before(c));
3213 let preceding_text_matches_prefix = prefix_len == 0
3214 || (selection.start.column >= (prefix_len as u32)
3215 && snapshot.contains_str_at(
3216 Point::new(
3217 selection.start.row,
3218 selection.start.column - (prefix_len as u32),
3219 ),
3220 &bracket_pair.start[..prefix_len],
3221 ));
3222
3223 if autoclose
3224 && bracket_pair.close
3225 && following_text_allows_autoclose
3226 && preceding_text_matches_prefix
3227 {
3228 let anchor = snapshot.anchor_before(selection.end);
3229 new_selections.push((selection.map(|_| anchor), text.len()));
3230 new_autoclose_regions.push((
3231 anchor,
3232 text.len(),
3233 selection.id,
3234 bracket_pair.clone(),
3235 ));
3236 edits.push((
3237 selection.range(),
3238 format!("{}{}", text, bracket_pair.end).into(),
3239 ));
3240 bracket_inserted = true;
3241 continue;
3242 }
3243 }
3244
3245 if let Some(region) = autoclose_region {
3246 // If the selection is followed by an auto-inserted closing bracket,
3247 // then don't insert that closing bracket again; just move the selection
3248 // past the closing bracket.
3249 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3250 && text.as_ref() == region.pair.end.as_str();
3251 if should_skip {
3252 let anchor = snapshot.anchor_after(selection.end);
3253 new_selections
3254 .push((selection.map(|_| anchor), region.pair.end.len()));
3255 continue;
3256 }
3257 }
3258
3259 let always_treat_brackets_as_autoclosed = snapshot
3260 .settings_at(selection.start, cx)
3261 .always_treat_brackets_as_autoclosed;
3262 if always_treat_brackets_as_autoclosed
3263 && is_bracket_pair_end
3264 && snapshot.contains_str_at(selection.end, text.as_ref())
3265 {
3266 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3267 // and the inserted text is a closing bracket and the selection is followed
3268 // by the closing bracket then move the selection past the closing bracket.
3269 let anchor = snapshot.anchor_after(selection.end);
3270 new_selections.push((selection.map(|_| anchor), text.len()));
3271 continue;
3272 }
3273 }
3274 // If an opening bracket is 1 character long and is typed while
3275 // text is selected, then surround that text with the bracket pair.
3276 else if auto_surround
3277 && bracket_pair.surround
3278 && is_bracket_pair_start
3279 && bracket_pair.start.chars().count() == 1
3280 {
3281 edits.push((selection.start..selection.start, text.clone()));
3282 edits.push((
3283 selection.end..selection.end,
3284 bracket_pair.end.as_str().into(),
3285 ));
3286 bracket_inserted = true;
3287 new_selections.push((
3288 Selection {
3289 id: selection.id,
3290 start: snapshot.anchor_after(selection.start),
3291 end: snapshot.anchor_before(selection.end),
3292 reversed: selection.reversed,
3293 goal: selection.goal,
3294 },
3295 0,
3296 ));
3297 continue;
3298 }
3299 }
3300 }
3301
3302 if self.auto_replace_emoji_shortcode
3303 && selection.is_empty()
3304 && text.as_ref().ends_with(':')
3305 {
3306 if let Some(possible_emoji_short_code) =
3307 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3308 {
3309 if !possible_emoji_short_code.is_empty() {
3310 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3311 let emoji_shortcode_start = Point::new(
3312 selection.start.row,
3313 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3314 );
3315
3316 // Remove shortcode from buffer
3317 edits.push((
3318 emoji_shortcode_start..selection.start,
3319 "".to_string().into(),
3320 ));
3321 new_selections.push((
3322 Selection {
3323 id: selection.id,
3324 start: snapshot.anchor_after(emoji_shortcode_start),
3325 end: snapshot.anchor_before(selection.start),
3326 reversed: selection.reversed,
3327 goal: selection.goal,
3328 },
3329 0,
3330 ));
3331
3332 // Insert emoji
3333 let selection_start_anchor = snapshot.anchor_after(selection.start);
3334 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3335 edits.push((selection.start..selection.end, emoji.to_string().into()));
3336
3337 continue;
3338 }
3339 }
3340 }
3341 }
3342
3343 // If not handling any auto-close operation, then just replace the selected
3344 // text with the given input and move the selection to the end of the
3345 // newly inserted text.
3346 let anchor = snapshot.anchor_after(selection.end);
3347 if !self.linked_edit_ranges.is_empty() {
3348 let start_anchor = snapshot.anchor_before(selection.start);
3349
3350 let is_word_char = text.chars().next().map_or(true, |char| {
3351 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3352 classifier.is_word(char)
3353 });
3354
3355 if is_word_char {
3356 if let Some(ranges) = self
3357 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3358 {
3359 for (buffer, edits) in ranges {
3360 linked_edits
3361 .entry(buffer.clone())
3362 .or_default()
3363 .extend(edits.into_iter().map(|range| (range, text.clone())));
3364 }
3365 }
3366 }
3367 }
3368
3369 new_selections.push((selection.map(|_| anchor), 0));
3370 edits.push((selection.start..selection.end, text.clone()));
3371 }
3372
3373 drop(snapshot);
3374
3375 self.transact(cx, |this, cx| {
3376 this.buffer.update(cx, |buffer, cx| {
3377 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3378 });
3379 for (buffer, edits) in linked_edits {
3380 buffer.update(cx, |buffer, cx| {
3381 let snapshot = buffer.snapshot();
3382 let edits = edits
3383 .into_iter()
3384 .map(|(range, text)| {
3385 use text::ToPoint as TP;
3386 let end_point = TP::to_point(&range.end, &snapshot);
3387 let start_point = TP::to_point(&range.start, &snapshot);
3388 (start_point..end_point, text)
3389 })
3390 .sorted_by_key(|(range, _)| range.start)
3391 .collect::<Vec<_>>();
3392 buffer.edit(edits, None, cx);
3393 })
3394 }
3395 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3396 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3397 let snapshot = this.buffer.read(cx).read(cx);
3398 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3399 .zip(new_selection_deltas)
3400 .map(|(selection, delta)| Selection {
3401 id: selection.id,
3402 start: selection.start + delta,
3403 end: selection.end + delta,
3404 reversed: selection.reversed,
3405 goal: SelectionGoal::None,
3406 })
3407 .collect::<Vec<_>>();
3408
3409 let mut i = 0;
3410 for (position, delta, selection_id, pair) in new_autoclose_regions {
3411 let position = position.to_offset(&snapshot) + delta;
3412 let start = snapshot.anchor_before(position);
3413 let end = snapshot.anchor_after(position);
3414 while let Some(existing_state) = this.autoclose_regions.get(i) {
3415 match existing_state.range.start.cmp(&start, &snapshot) {
3416 Ordering::Less => i += 1,
3417 Ordering::Greater => break,
3418 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3419 Ordering::Less => i += 1,
3420 Ordering::Equal => break,
3421 Ordering::Greater => break,
3422 },
3423 }
3424 }
3425 this.autoclose_regions.insert(
3426 i,
3427 AutocloseRegion {
3428 selection_id,
3429 range: start..end,
3430 pair,
3431 },
3432 );
3433 }
3434
3435 drop(snapshot);
3436 let had_active_inline_completion = this.has_active_inline_completion(cx);
3437 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3438 s.select(new_selections)
3439 });
3440
3441 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3442 if let Some(on_type_format_task) =
3443 this.trigger_on_type_formatting(text.to_string(), cx)
3444 {
3445 on_type_format_task.detach_and_log_err(cx);
3446 }
3447 }
3448
3449 let editor_settings = EditorSettings::get_global(cx);
3450 if bracket_inserted
3451 && (editor_settings.auto_signature_help
3452 || editor_settings.show_signature_help_after_edits)
3453 {
3454 this.show_signature_help(&ShowSignatureHelp, cx);
3455 }
3456
3457 let trigger_in_words = !had_active_inline_completion;
3458 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3459 linked_editing_ranges::refresh_linked_ranges(this, cx);
3460 this.refresh_inline_completion(true, false, cx);
3461 });
3462 }
3463
3464 fn find_possible_emoji_shortcode_at_position(
3465 snapshot: &MultiBufferSnapshot,
3466 position: Point,
3467 ) -> Option<String> {
3468 let mut chars = Vec::new();
3469 let mut found_colon = false;
3470 for char in snapshot.reversed_chars_at(position).take(100) {
3471 // Found a possible emoji shortcode in the middle of the buffer
3472 if found_colon {
3473 if char.is_whitespace() {
3474 chars.reverse();
3475 return Some(chars.iter().collect());
3476 }
3477 // If the previous character is not a whitespace, we are in the middle of a word
3478 // and we only want to complete the shortcode if the word is made up of other emojis
3479 let mut containing_word = String::new();
3480 for ch in snapshot
3481 .reversed_chars_at(position)
3482 .skip(chars.len() + 1)
3483 .take(100)
3484 {
3485 if ch.is_whitespace() {
3486 break;
3487 }
3488 containing_word.push(ch);
3489 }
3490 let containing_word = containing_word.chars().rev().collect::<String>();
3491 if util::word_consists_of_emojis(containing_word.as_str()) {
3492 chars.reverse();
3493 return Some(chars.iter().collect());
3494 }
3495 }
3496
3497 if char.is_whitespace() || !char.is_ascii() {
3498 return None;
3499 }
3500 if char == ':' {
3501 found_colon = true;
3502 } else {
3503 chars.push(char);
3504 }
3505 }
3506 // Found a possible emoji shortcode at the beginning of the buffer
3507 chars.reverse();
3508 Some(chars.iter().collect())
3509 }
3510
3511 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3512 self.transact(cx, |this, cx| {
3513 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3514 let selections = this.selections.all::<usize>(cx);
3515 let multi_buffer = this.buffer.read(cx);
3516 let buffer = multi_buffer.snapshot(cx);
3517 selections
3518 .iter()
3519 .map(|selection| {
3520 let start_point = selection.start.to_point(&buffer);
3521 let mut indent =
3522 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3523 indent.len = cmp::min(indent.len, start_point.column);
3524 let start = selection.start;
3525 let end = selection.end;
3526 let selection_is_empty = start == end;
3527 let language_scope = buffer.language_scope_at(start);
3528 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3529 &language_scope
3530 {
3531 let leading_whitespace_len = buffer
3532 .reversed_chars_at(start)
3533 .take_while(|c| c.is_whitespace() && *c != '\n')
3534 .map(|c| c.len_utf8())
3535 .sum::<usize>();
3536
3537 let trailing_whitespace_len = buffer
3538 .chars_at(end)
3539 .take_while(|c| c.is_whitespace() && *c != '\n')
3540 .map(|c| c.len_utf8())
3541 .sum::<usize>();
3542
3543 let insert_extra_newline =
3544 language.brackets().any(|(pair, enabled)| {
3545 let pair_start = pair.start.trim_end();
3546 let pair_end = pair.end.trim_start();
3547
3548 enabled
3549 && pair.newline
3550 && buffer.contains_str_at(
3551 end + trailing_whitespace_len,
3552 pair_end,
3553 )
3554 && buffer.contains_str_at(
3555 (start - leading_whitespace_len)
3556 .saturating_sub(pair_start.len()),
3557 pair_start,
3558 )
3559 });
3560
3561 // Comment extension on newline is allowed only for cursor selections
3562 let comment_delimiter = maybe!({
3563 if !selection_is_empty {
3564 return None;
3565 }
3566
3567 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3568 return None;
3569 }
3570
3571 let delimiters = language.line_comment_prefixes();
3572 let max_len_of_delimiter =
3573 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3574 let (snapshot, range) =
3575 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3576
3577 let mut index_of_first_non_whitespace = 0;
3578 let comment_candidate = snapshot
3579 .chars_for_range(range)
3580 .skip_while(|c| {
3581 let should_skip = c.is_whitespace();
3582 if should_skip {
3583 index_of_first_non_whitespace += 1;
3584 }
3585 should_skip
3586 })
3587 .take(max_len_of_delimiter)
3588 .collect::<String>();
3589 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3590 comment_candidate.starts_with(comment_prefix.as_ref())
3591 })?;
3592 let cursor_is_placed_after_comment_marker =
3593 index_of_first_non_whitespace + comment_prefix.len()
3594 <= start_point.column as usize;
3595 if cursor_is_placed_after_comment_marker {
3596 Some(comment_prefix.clone())
3597 } else {
3598 None
3599 }
3600 });
3601 (comment_delimiter, insert_extra_newline)
3602 } else {
3603 (None, false)
3604 };
3605
3606 let capacity_for_delimiter = comment_delimiter
3607 .as_deref()
3608 .map(str::len)
3609 .unwrap_or_default();
3610 let mut new_text =
3611 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3612 new_text.push('\n');
3613 new_text.extend(indent.chars());
3614 if let Some(delimiter) = &comment_delimiter {
3615 new_text.push_str(delimiter);
3616 }
3617 if insert_extra_newline {
3618 new_text = new_text.repeat(2);
3619 }
3620
3621 let anchor = buffer.anchor_after(end);
3622 let new_selection = selection.map(|_| anchor);
3623 (
3624 (start..end, new_text),
3625 (insert_extra_newline, new_selection),
3626 )
3627 })
3628 .unzip()
3629 };
3630
3631 this.edit_with_autoindent(edits, cx);
3632 let buffer = this.buffer.read(cx).snapshot(cx);
3633 let new_selections = selection_fixup_info
3634 .into_iter()
3635 .map(|(extra_newline_inserted, new_selection)| {
3636 let mut cursor = new_selection.end.to_point(&buffer);
3637 if extra_newline_inserted {
3638 cursor.row -= 1;
3639 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3640 }
3641 new_selection.map(|_| cursor)
3642 })
3643 .collect();
3644
3645 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3646 this.refresh_inline_completion(true, false, cx);
3647 });
3648 }
3649
3650 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3651 let buffer = self.buffer.read(cx);
3652 let snapshot = buffer.snapshot(cx);
3653
3654 let mut edits = Vec::new();
3655 let mut rows = Vec::new();
3656
3657 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3658 let cursor = selection.head();
3659 let row = cursor.row;
3660
3661 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3662
3663 let newline = "\n".to_string();
3664 edits.push((start_of_line..start_of_line, newline));
3665
3666 rows.push(row + rows_inserted as u32);
3667 }
3668
3669 self.transact(cx, |editor, cx| {
3670 editor.edit(edits, cx);
3671
3672 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3673 let mut index = 0;
3674 s.move_cursors_with(|map, _, _| {
3675 let row = rows[index];
3676 index += 1;
3677
3678 let point = Point::new(row, 0);
3679 let boundary = map.next_line_boundary(point).1;
3680 let clipped = map.clip_point(boundary, Bias::Left);
3681
3682 (clipped, SelectionGoal::None)
3683 });
3684 });
3685
3686 let mut indent_edits = Vec::new();
3687 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3688 for row in rows {
3689 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3690 for (row, indent) in indents {
3691 if indent.len == 0 {
3692 continue;
3693 }
3694
3695 let text = match indent.kind {
3696 IndentKind::Space => " ".repeat(indent.len as usize),
3697 IndentKind::Tab => "\t".repeat(indent.len as usize),
3698 };
3699 let point = Point::new(row.0, 0);
3700 indent_edits.push((point..point, text));
3701 }
3702 }
3703 editor.edit(indent_edits, cx);
3704 });
3705 }
3706
3707 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3708 let buffer = self.buffer.read(cx);
3709 let snapshot = buffer.snapshot(cx);
3710
3711 let mut edits = Vec::new();
3712 let mut rows = Vec::new();
3713 let mut rows_inserted = 0;
3714
3715 for selection in self.selections.all_adjusted(cx) {
3716 let cursor = selection.head();
3717 let row = cursor.row;
3718
3719 let point = Point::new(row + 1, 0);
3720 let start_of_line = snapshot.clip_point(point, Bias::Left);
3721
3722 let newline = "\n".to_string();
3723 edits.push((start_of_line..start_of_line, newline));
3724
3725 rows_inserted += 1;
3726 rows.push(row + rows_inserted);
3727 }
3728
3729 self.transact(cx, |editor, cx| {
3730 editor.edit(edits, cx);
3731
3732 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3733 let mut index = 0;
3734 s.move_cursors_with(|map, _, _| {
3735 let row = rows[index];
3736 index += 1;
3737
3738 let point = Point::new(row, 0);
3739 let boundary = map.next_line_boundary(point).1;
3740 let clipped = map.clip_point(boundary, Bias::Left);
3741
3742 (clipped, SelectionGoal::None)
3743 });
3744 });
3745
3746 let mut indent_edits = Vec::new();
3747 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3748 for row in rows {
3749 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3750 for (row, indent) in indents {
3751 if indent.len == 0 {
3752 continue;
3753 }
3754
3755 let text = match indent.kind {
3756 IndentKind::Space => " ".repeat(indent.len as usize),
3757 IndentKind::Tab => "\t".repeat(indent.len as usize),
3758 };
3759 let point = Point::new(row.0, 0);
3760 indent_edits.push((point..point, text));
3761 }
3762 }
3763 editor.edit(indent_edits, cx);
3764 });
3765 }
3766
3767 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3768 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3769 original_indent_columns: Vec::new(),
3770 });
3771 self.insert_with_autoindent_mode(text, autoindent, cx);
3772 }
3773
3774 fn insert_with_autoindent_mode(
3775 &mut self,
3776 text: &str,
3777 autoindent_mode: Option<AutoindentMode>,
3778 cx: &mut ViewContext<Self>,
3779 ) {
3780 if self.read_only(cx) {
3781 return;
3782 }
3783
3784 let text: Arc<str> = text.into();
3785 self.transact(cx, |this, cx| {
3786 let old_selections = this.selections.all_adjusted(cx);
3787 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3788 let anchors = {
3789 let snapshot = buffer.read(cx);
3790 old_selections
3791 .iter()
3792 .map(|s| {
3793 let anchor = snapshot.anchor_after(s.head());
3794 s.map(|_| anchor)
3795 })
3796 .collect::<Vec<_>>()
3797 };
3798 buffer.edit(
3799 old_selections
3800 .iter()
3801 .map(|s| (s.start..s.end, text.clone())),
3802 autoindent_mode,
3803 cx,
3804 );
3805 anchors
3806 });
3807
3808 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3809 s.select_anchors(selection_anchors);
3810 })
3811 });
3812 }
3813
3814 fn trigger_completion_on_input(
3815 &mut self,
3816 text: &str,
3817 trigger_in_words: bool,
3818 cx: &mut ViewContext<Self>,
3819 ) {
3820 if self.is_completion_trigger(text, trigger_in_words, cx) {
3821 self.show_completions(
3822 &ShowCompletions {
3823 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3824 },
3825 cx,
3826 );
3827 } else {
3828 self.hide_context_menu(cx);
3829 }
3830 }
3831
3832 fn is_completion_trigger(
3833 &self,
3834 text: &str,
3835 trigger_in_words: bool,
3836 cx: &mut ViewContext<Self>,
3837 ) -> bool {
3838 let position = self.selections.newest_anchor().head();
3839 let multibuffer = self.buffer.read(cx);
3840 let Some(buffer) = position
3841 .buffer_id
3842 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3843 else {
3844 return false;
3845 };
3846
3847 if let Some(completion_provider) = &self.completion_provider {
3848 completion_provider.is_completion_trigger(
3849 &buffer,
3850 position.text_anchor,
3851 text,
3852 trigger_in_words,
3853 cx,
3854 )
3855 } else {
3856 false
3857 }
3858 }
3859
3860 /// If any empty selections is touching the start of its innermost containing autoclose
3861 /// region, expand it to select the brackets.
3862 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3863 let selections = self.selections.all::<usize>(cx);
3864 let buffer = self.buffer.read(cx).read(cx);
3865 let new_selections = self
3866 .selections_with_autoclose_regions(selections, &buffer)
3867 .map(|(mut selection, region)| {
3868 if !selection.is_empty() {
3869 return selection;
3870 }
3871
3872 if let Some(region) = region {
3873 let mut range = region.range.to_offset(&buffer);
3874 if selection.start == range.start && range.start >= region.pair.start.len() {
3875 range.start -= region.pair.start.len();
3876 if buffer.contains_str_at(range.start, ®ion.pair.start)
3877 && buffer.contains_str_at(range.end, ®ion.pair.end)
3878 {
3879 range.end += region.pair.end.len();
3880 selection.start = range.start;
3881 selection.end = range.end;
3882
3883 return selection;
3884 }
3885 }
3886 }
3887
3888 let always_treat_brackets_as_autoclosed = buffer
3889 .settings_at(selection.start, cx)
3890 .always_treat_brackets_as_autoclosed;
3891
3892 if !always_treat_brackets_as_autoclosed {
3893 return selection;
3894 }
3895
3896 if let Some(scope) = buffer.language_scope_at(selection.start) {
3897 for (pair, enabled) in scope.brackets() {
3898 if !enabled || !pair.close {
3899 continue;
3900 }
3901
3902 if buffer.contains_str_at(selection.start, &pair.end) {
3903 let pair_start_len = pair.start.len();
3904 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3905 {
3906 selection.start -= pair_start_len;
3907 selection.end += pair.end.len();
3908
3909 return selection;
3910 }
3911 }
3912 }
3913 }
3914
3915 selection
3916 })
3917 .collect();
3918
3919 drop(buffer);
3920 self.change_selections(None, cx, |selections| selections.select(new_selections));
3921 }
3922
3923 /// Iterate the given selections, and for each one, find the smallest surrounding
3924 /// autoclose region. This uses the ordering of the selections and the autoclose
3925 /// regions to avoid repeated comparisons.
3926 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3927 &'a self,
3928 selections: impl IntoIterator<Item = Selection<D>>,
3929 buffer: &'a MultiBufferSnapshot,
3930 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3931 let mut i = 0;
3932 let mut regions = self.autoclose_regions.as_slice();
3933 selections.into_iter().map(move |selection| {
3934 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3935
3936 let mut enclosing = None;
3937 while let Some(pair_state) = regions.get(i) {
3938 if pair_state.range.end.to_offset(buffer) < range.start {
3939 regions = ®ions[i + 1..];
3940 i = 0;
3941 } else if pair_state.range.start.to_offset(buffer) > range.end {
3942 break;
3943 } else {
3944 if pair_state.selection_id == selection.id {
3945 enclosing = Some(pair_state);
3946 }
3947 i += 1;
3948 }
3949 }
3950
3951 (selection.clone(), enclosing)
3952 })
3953 }
3954
3955 /// Remove any autoclose regions that no longer contain their selection.
3956 fn invalidate_autoclose_regions(
3957 &mut self,
3958 mut selections: &[Selection<Anchor>],
3959 buffer: &MultiBufferSnapshot,
3960 ) {
3961 self.autoclose_regions.retain(|state| {
3962 let mut i = 0;
3963 while let Some(selection) = selections.get(i) {
3964 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3965 selections = &selections[1..];
3966 continue;
3967 }
3968 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3969 break;
3970 }
3971 if selection.id == state.selection_id {
3972 return true;
3973 } else {
3974 i += 1;
3975 }
3976 }
3977 false
3978 });
3979 }
3980
3981 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3982 let offset = position.to_offset(buffer);
3983 let (word_range, kind) = buffer.surrounding_word(offset, true);
3984 if offset > word_range.start && kind == Some(CharKind::Word) {
3985 Some(
3986 buffer
3987 .text_for_range(word_range.start..offset)
3988 .collect::<String>(),
3989 )
3990 } else {
3991 None
3992 }
3993 }
3994
3995 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3996 self.refresh_inlay_hints(
3997 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3998 cx,
3999 );
4000 }
4001
4002 pub fn inlay_hints_enabled(&self) -> bool {
4003 self.inlay_hint_cache.enabled
4004 }
4005
4006 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4007 if self.project.is_none() || self.mode != EditorMode::Full {
4008 return;
4009 }
4010
4011 let reason_description = reason.description();
4012 let ignore_debounce = matches!(
4013 reason,
4014 InlayHintRefreshReason::SettingsChange(_)
4015 | InlayHintRefreshReason::Toggle(_)
4016 | InlayHintRefreshReason::ExcerptsRemoved(_)
4017 );
4018 let (invalidate_cache, required_languages) = match reason {
4019 InlayHintRefreshReason::Toggle(enabled) => {
4020 self.inlay_hint_cache.enabled = enabled;
4021 if enabled {
4022 (InvalidationStrategy::RefreshRequested, None)
4023 } else {
4024 self.inlay_hint_cache.clear();
4025 self.splice_inlays(
4026 self.visible_inlay_hints(cx)
4027 .iter()
4028 .map(|inlay| inlay.id)
4029 .collect(),
4030 Vec::new(),
4031 cx,
4032 );
4033 return;
4034 }
4035 }
4036 InlayHintRefreshReason::SettingsChange(new_settings) => {
4037 match self.inlay_hint_cache.update_settings(
4038 &self.buffer,
4039 new_settings,
4040 self.visible_inlay_hints(cx),
4041 cx,
4042 ) {
4043 ControlFlow::Break(Some(InlaySplice {
4044 to_remove,
4045 to_insert,
4046 })) => {
4047 self.splice_inlays(to_remove, to_insert, cx);
4048 return;
4049 }
4050 ControlFlow::Break(None) => return,
4051 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4052 }
4053 }
4054 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4055 if let Some(InlaySplice {
4056 to_remove,
4057 to_insert,
4058 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4059 {
4060 self.splice_inlays(to_remove, to_insert, cx);
4061 }
4062 return;
4063 }
4064 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4065 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4066 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4067 }
4068 InlayHintRefreshReason::RefreshRequested => {
4069 (InvalidationStrategy::RefreshRequested, None)
4070 }
4071 };
4072
4073 if let Some(InlaySplice {
4074 to_remove,
4075 to_insert,
4076 }) = self.inlay_hint_cache.spawn_hint_refresh(
4077 reason_description,
4078 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4079 invalidate_cache,
4080 ignore_debounce,
4081 cx,
4082 ) {
4083 self.splice_inlays(to_remove, to_insert, cx);
4084 }
4085 }
4086
4087 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4088 self.display_map
4089 .read(cx)
4090 .current_inlays()
4091 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4092 .cloned()
4093 .collect()
4094 }
4095
4096 pub fn excerpts_for_inlay_hints_query(
4097 &self,
4098 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4099 cx: &mut ViewContext<Editor>,
4100 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4101 let Some(project) = self.project.as_ref() else {
4102 return HashMap::default();
4103 };
4104 let project = project.read(cx);
4105 let multi_buffer = self.buffer().read(cx);
4106 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4107 let multi_buffer_visible_start = self
4108 .scroll_manager
4109 .anchor()
4110 .anchor
4111 .to_point(&multi_buffer_snapshot);
4112 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4113 multi_buffer_visible_start
4114 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4115 Bias::Left,
4116 );
4117 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4118 multi_buffer
4119 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4120 .into_iter()
4121 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4122 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4123 let buffer = buffer_handle.read(cx);
4124 let buffer_file = project::File::from_dyn(buffer.file())?;
4125 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4126 let worktree_entry = buffer_worktree
4127 .read(cx)
4128 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4129 if worktree_entry.is_ignored {
4130 return None;
4131 }
4132
4133 let language = buffer.language()?;
4134 if let Some(restrict_to_languages) = restrict_to_languages {
4135 if !restrict_to_languages.contains(language) {
4136 return None;
4137 }
4138 }
4139 Some((
4140 excerpt_id,
4141 (
4142 buffer_handle,
4143 buffer.version().clone(),
4144 excerpt_visible_range,
4145 ),
4146 ))
4147 })
4148 .collect()
4149 }
4150
4151 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4152 TextLayoutDetails {
4153 text_system: cx.text_system().clone(),
4154 editor_style: self.style.clone().unwrap(),
4155 rem_size: cx.rem_size(),
4156 scroll_anchor: self.scroll_manager.anchor(),
4157 visible_rows: self.visible_line_count(),
4158 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4159 }
4160 }
4161
4162 fn splice_inlays(
4163 &self,
4164 to_remove: Vec<InlayId>,
4165 to_insert: Vec<Inlay>,
4166 cx: &mut ViewContext<Self>,
4167 ) {
4168 self.display_map.update(cx, |display_map, cx| {
4169 display_map.splice_inlays(to_remove, to_insert, cx);
4170 });
4171 cx.notify();
4172 }
4173
4174 fn trigger_on_type_formatting(
4175 &self,
4176 input: String,
4177 cx: &mut ViewContext<Self>,
4178 ) -> Option<Task<Result<()>>> {
4179 if input.len() != 1 {
4180 return None;
4181 }
4182
4183 let project = self.project.as_ref()?;
4184 let position = self.selections.newest_anchor().head();
4185 let (buffer, buffer_position) = self
4186 .buffer
4187 .read(cx)
4188 .text_anchor_for_position(position, cx)?;
4189
4190 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4191 // hence we do LSP request & edit on host side only — add formats to host's history.
4192 let push_to_lsp_host_history = true;
4193 // If this is not the host, append its history with new edits.
4194 let push_to_client_history = project.read(cx).is_via_collab();
4195
4196 let on_type_formatting = project.update(cx, |project, cx| {
4197 project.on_type_format(
4198 buffer.clone(),
4199 buffer_position,
4200 input,
4201 push_to_lsp_host_history,
4202 cx,
4203 )
4204 });
4205 Some(cx.spawn(|editor, mut cx| async move {
4206 if let Some(transaction) = on_type_formatting.await? {
4207 if push_to_client_history {
4208 buffer
4209 .update(&mut cx, |buffer, _| {
4210 buffer.push_transaction(transaction, Instant::now());
4211 })
4212 .ok();
4213 }
4214 editor.update(&mut cx, |editor, cx| {
4215 editor.refresh_document_highlights(cx);
4216 })?;
4217 }
4218 Ok(())
4219 }))
4220 }
4221
4222 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4223 if self.pending_rename.is_some() {
4224 return;
4225 }
4226
4227 let Some(provider) = self.completion_provider.as_ref() else {
4228 return;
4229 };
4230
4231 let position = self.selections.newest_anchor().head();
4232 let (buffer, buffer_position) =
4233 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4234 output
4235 } else {
4236 return;
4237 };
4238
4239 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4240 let is_followup_invoke = {
4241 let context_menu_state = self.context_menu.read();
4242 matches!(
4243 context_menu_state.deref(),
4244 Some(ContextMenu::Completions(_))
4245 )
4246 };
4247 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4248 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4249 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4250 CompletionTriggerKind::TRIGGER_CHARACTER
4251 }
4252
4253 _ => CompletionTriggerKind::INVOKED,
4254 };
4255 let completion_context = CompletionContext {
4256 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4257 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4258 Some(String::from(trigger))
4259 } else {
4260 None
4261 }
4262 }),
4263 trigger_kind,
4264 };
4265 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4266 let sort_completions = provider.sort_completions();
4267
4268 let id = post_inc(&mut self.next_completion_id);
4269 let task = cx.spawn(|this, mut cx| {
4270 async move {
4271 this.update(&mut cx, |this, _| {
4272 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4273 })?;
4274 let completions = completions.await.log_err();
4275 let menu = if let Some(completions) = completions {
4276 let mut menu = CompletionsMenu {
4277 id,
4278 sort_completions,
4279 initial_position: position,
4280 match_candidates: completions
4281 .iter()
4282 .enumerate()
4283 .map(|(id, completion)| {
4284 StringMatchCandidate::new(
4285 id,
4286 completion.label.text[completion.label.filter_range.clone()]
4287 .into(),
4288 )
4289 })
4290 .collect(),
4291 buffer: buffer.clone(),
4292 completions: Arc::new(RwLock::new(completions.into())),
4293 matches: Vec::new().into(),
4294 selected_item: 0,
4295 scroll_handle: UniformListScrollHandle::new(),
4296 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4297 DebouncedDelay::new(),
4298 )),
4299 };
4300 menu.filter(query.as_deref(), cx.background_executor().clone())
4301 .await;
4302
4303 if menu.matches.is_empty() {
4304 None
4305 } else {
4306 this.update(&mut cx, |editor, cx| {
4307 let completions = menu.completions.clone();
4308 let matches = menu.matches.clone();
4309
4310 let delay_ms = EditorSettings::get_global(cx)
4311 .completion_documentation_secondary_query_debounce;
4312 let delay = Duration::from_millis(delay_ms);
4313 editor
4314 .completion_documentation_pre_resolve_debounce
4315 .fire_new(delay, cx, |editor, cx| {
4316 CompletionsMenu::pre_resolve_completion_documentation(
4317 buffer,
4318 completions,
4319 matches,
4320 editor,
4321 cx,
4322 )
4323 });
4324 })
4325 .ok();
4326 Some(menu)
4327 }
4328 } else {
4329 None
4330 };
4331
4332 this.update(&mut cx, |this, cx| {
4333 let mut context_menu = this.context_menu.write();
4334 match context_menu.as_ref() {
4335 None => {}
4336
4337 Some(ContextMenu::Completions(prev_menu)) => {
4338 if prev_menu.id > id {
4339 return;
4340 }
4341 }
4342
4343 _ => return,
4344 }
4345
4346 if this.focus_handle.is_focused(cx) && menu.is_some() {
4347 let menu = menu.unwrap();
4348 *context_menu = Some(ContextMenu::Completions(menu));
4349 drop(context_menu);
4350 this.discard_inline_completion(false, cx);
4351 cx.notify();
4352 } else if this.completion_tasks.len() <= 1 {
4353 // If there are no more completion tasks and the last menu was
4354 // empty, we should hide it. If it was already hidden, we should
4355 // also show the copilot completion when available.
4356 drop(context_menu);
4357 if this.hide_context_menu(cx).is_none() {
4358 this.update_visible_inline_completion(cx);
4359 }
4360 }
4361 })?;
4362
4363 Ok::<_, anyhow::Error>(())
4364 }
4365 .log_err()
4366 });
4367
4368 self.completion_tasks.push((id, task));
4369 }
4370
4371 pub fn confirm_completion(
4372 &mut self,
4373 action: &ConfirmCompletion,
4374 cx: &mut ViewContext<Self>,
4375 ) -> Option<Task<Result<()>>> {
4376 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4377 }
4378
4379 pub fn compose_completion(
4380 &mut self,
4381 action: &ComposeCompletion,
4382 cx: &mut ViewContext<Self>,
4383 ) -> Option<Task<Result<()>>> {
4384 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4385 }
4386
4387 fn do_completion(
4388 &mut self,
4389 item_ix: Option<usize>,
4390 intent: CompletionIntent,
4391 cx: &mut ViewContext<Editor>,
4392 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4393 use language::ToOffset as _;
4394
4395 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4396 menu
4397 } else {
4398 return None;
4399 };
4400
4401 let mat = completions_menu
4402 .matches
4403 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4404 let buffer_handle = completions_menu.buffer;
4405 let completions = completions_menu.completions.read();
4406 let completion = completions.get(mat.candidate_id)?;
4407 cx.stop_propagation();
4408
4409 let snippet;
4410 let text;
4411
4412 if completion.is_snippet() {
4413 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4414 text = snippet.as_ref().unwrap().text.clone();
4415 } else {
4416 snippet = None;
4417 text = completion.new_text.clone();
4418 };
4419 let selections = self.selections.all::<usize>(cx);
4420 let buffer = buffer_handle.read(cx);
4421 let old_range = completion.old_range.to_offset(buffer);
4422 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4423
4424 let newest_selection = self.selections.newest_anchor();
4425 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4426 return None;
4427 }
4428
4429 let lookbehind = newest_selection
4430 .start
4431 .text_anchor
4432 .to_offset(buffer)
4433 .saturating_sub(old_range.start);
4434 let lookahead = old_range
4435 .end
4436 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4437 let mut common_prefix_len = old_text
4438 .bytes()
4439 .zip(text.bytes())
4440 .take_while(|(a, b)| a == b)
4441 .count();
4442
4443 let snapshot = self.buffer.read(cx).snapshot(cx);
4444 let mut range_to_replace: Option<Range<isize>> = None;
4445 let mut ranges = Vec::new();
4446 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4447 for selection in &selections {
4448 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4449 let start = selection.start.saturating_sub(lookbehind);
4450 let end = selection.end + lookahead;
4451 if selection.id == newest_selection.id {
4452 range_to_replace = Some(
4453 ((start + common_prefix_len) as isize - selection.start as isize)
4454 ..(end as isize - selection.start as isize),
4455 );
4456 }
4457 ranges.push(start + common_prefix_len..end);
4458 } else {
4459 common_prefix_len = 0;
4460 ranges.clear();
4461 ranges.extend(selections.iter().map(|s| {
4462 if s.id == newest_selection.id {
4463 range_to_replace = Some(
4464 old_range.start.to_offset_utf16(&snapshot).0 as isize
4465 - selection.start as isize
4466 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4467 - selection.start as isize,
4468 );
4469 old_range.clone()
4470 } else {
4471 s.start..s.end
4472 }
4473 }));
4474 break;
4475 }
4476 if !self.linked_edit_ranges.is_empty() {
4477 let start_anchor = snapshot.anchor_before(selection.head());
4478 let end_anchor = snapshot.anchor_after(selection.tail());
4479 if let Some(ranges) = self
4480 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4481 {
4482 for (buffer, edits) in ranges {
4483 linked_edits.entry(buffer.clone()).or_default().extend(
4484 edits
4485 .into_iter()
4486 .map(|range| (range, text[common_prefix_len..].to_owned())),
4487 );
4488 }
4489 }
4490 }
4491 }
4492 let text = &text[common_prefix_len..];
4493
4494 cx.emit(EditorEvent::InputHandled {
4495 utf16_range_to_replace: range_to_replace,
4496 text: text.into(),
4497 });
4498
4499 self.transact(cx, |this, cx| {
4500 if let Some(mut snippet) = snippet {
4501 snippet.text = text.to_string();
4502 for tabstop in snippet.tabstops.iter_mut().flatten() {
4503 tabstop.start -= common_prefix_len as isize;
4504 tabstop.end -= common_prefix_len as isize;
4505 }
4506
4507 this.insert_snippet(&ranges, snippet, cx).log_err();
4508 } else {
4509 this.buffer.update(cx, |buffer, cx| {
4510 buffer.edit(
4511 ranges.iter().map(|range| (range.clone(), text)),
4512 this.autoindent_mode.clone(),
4513 cx,
4514 );
4515 });
4516 }
4517 for (buffer, edits) in linked_edits {
4518 buffer.update(cx, |buffer, cx| {
4519 let snapshot = buffer.snapshot();
4520 let edits = edits
4521 .into_iter()
4522 .map(|(range, text)| {
4523 use text::ToPoint as TP;
4524 let end_point = TP::to_point(&range.end, &snapshot);
4525 let start_point = TP::to_point(&range.start, &snapshot);
4526 (start_point..end_point, text)
4527 })
4528 .sorted_by_key(|(range, _)| range.start)
4529 .collect::<Vec<_>>();
4530 buffer.edit(edits, None, cx);
4531 })
4532 }
4533
4534 this.refresh_inline_completion(true, false, cx);
4535 });
4536
4537 let show_new_completions_on_confirm = completion
4538 .confirm
4539 .as_ref()
4540 .map_or(false, |confirm| confirm(intent, cx));
4541 if show_new_completions_on_confirm {
4542 self.show_completions(&ShowCompletions { trigger: None }, cx);
4543 }
4544
4545 let provider = self.completion_provider.as_ref()?;
4546 let apply_edits = provider.apply_additional_edits_for_completion(
4547 buffer_handle,
4548 completion.clone(),
4549 true,
4550 cx,
4551 );
4552
4553 let editor_settings = EditorSettings::get_global(cx);
4554 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4555 // After the code completion is finished, users often want to know what signatures are needed.
4556 // so we should automatically call signature_help
4557 self.show_signature_help(&ShowSignatureHelp, cx);
4558 }
4559
4560 Some(cx.foreground_executor().spawn(async move {
4561 apply_edits.await?;
4562 Ok(())
4563 }))
4564 }
4565
4566 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4567 let mut context_menu = self.context_menu.write();
4568 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4569 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4570 // Toggle if we're selecting the same one
4571 *context_menu = None;
4572 cx.notify();
4573 return;
4574 } else {
4575 // Otherwise, clear it and start a new one
4576 *context_menu = None;
4577 cx.notify();
4578 }
4579 }
4580 drop(context_menu);
4581 let snapshot = self.snapshot(cx);
4582 let deployed_from_indicator = action.deployed_from_indicator;
4583 let mut task = self.code_actions_task.take();
4584 let action = action.clone();
4585 cx.spawn(|editor, mut cx| async move {
4586 while let Some(prev_task) = task {
4587 prev_task.await.log_err();
4588 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4589 }
4590
4591 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4592 if editor.focus_handle.is_focused(cx) {
4593 let multibuffer_point = action
4594 .deployed_from_indicator
4595 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4596 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4597 let (buffer, buffer_row) = snapshot
4598 .buffer_snapshot
4599 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4600 .and_then(|(buffer_snapshot, range)| {
4601 editor
4602 .buffer
4603 .read(cx)
4604 .buffer(buffer_snapshot.remote_id())
4605 .map(|buffer| (buffer, range.start.row))
4606 })?;
4607 let (_, code_actions) = editor
4608 .available_code_actions
4609 .clone()
4610 .and_then(|(location, code_actions)| {
4611 let snapshot = location.buffer.read(cx).snapshot();
4612 let point_range = location.range.to_point(&snapshot);
4613 let point_range = point_range.start.row..=point_range.end.row;
4614 if point_range.contains(&buffer_row) {
4615 Some((location, code_actions))
4616 } else {
4617 None
4618 }
4619 })
4620 .unzip();
4621 let buffer_id = buffer.read(cx).remote_id();
4622 let tasks = editor
4623 .tasks
4624 .get(&(buffer_id, buffer_row))
4625 .map(|t| Arc::new(t.to_owned()));
4626 if tasks.is_none() && code_actions.is_none() {
4627 return None;
4628 }
4629
4630 editor.completion_tasks.clear();
4631 editor.discard_inline_completion(false, cx);
4632 let task_context =
4633 tasks
4634 .as_ref()
4635 .zip(editor.project.clone())
4636 .map(|(tasks, project)| {
4637 let position = Point::new(buffer_row, tasks.column);
4638 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4639 let location = Location {
4640 buffer: buffer.clone(),
4641 range: range_start..range_start,
4642 };
4643 // Fill in the environmental variables from the tree-sitter captures
4644 let mut captured_task_variables = TaskVariables::default();
4645 for (capture_name, value) in tasks.extra_variables.clone() {
4646 captured_task_variables.insert(
4647 task::VariableName::Custom(capture_name.into()),
4648 value.clone(),
4649 );
4650 }
4651 project.update(cx, |project, cx| {
4652 project.task_context_for_location(
4653 captured_task_variables,
4654 location,
4655 cx,
4656 )
4657 })
4658 });
4659
4660 Some(cx.spawn(|editor, mut cx| async move {
4661 let task_context = match task_context {
4662 Some(task_context) => task_context.await,
4663 None => None,
4664 };
4665 let resolved_tasks =
4666 tasks.zip(task_context).map(|(tasks, task_context)| {
4667 Arc::new(ResolvedTasks {
4668 templates: tasks
4669 .templates
4670 .iter()
4671 .filter_map(|(kind, template)| {
4672 template
4673 .resolve_task(&kind.to_id_base(), &task_context)
4674 .map(|task| (kind.clone(), task))
4675 })
4676 .collect(),
4677 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4678 multibuffer_point.row,
4679 tasks.column,
4680 )),
4681 })
4682 });
4683 let spawn_straight_away = resolved_tasks
4684 .as_ref()
4685 .map_or(false, |tasks| tasks.templates.len() == 1)
4686 && code_actions
4687 .as_ref()
4688 .map_or(true, |actions| actions.is_empty());
4689 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4690 *editor.context_menu.write() =
4691 Some(ContextMenu::CodeActions(CodeActionsMenu {
4692 buffer,
4693 actions: CodeActionContents {
4694 tasks: resolved_tasks,
4695 actions: code_actions,
4696 },
4697 selected_item: Default::default(),
4698 scroll_handle: UniformListScrollHandle::default(),
4699 deployed_from_indicator,
4700 }));
4701 if spawn_straight_away {
4702 if let Some(task) = editor.confirm_code_action(
4703 &ConfirmCodeAction { item_ix: Some(0) },
4704 cx,
4705 ) {
4706 cx.notify();
4707 return task;
4708 }
4709 }
4710 cx.notify();
4711 Task::ready(Ok(()))
4712 }) {
4713 task.await
4714 } else {
4715 Ok(())
4716 }
4717 }))
4718 } else {
4719 Some(Task::ready(Ok(())))
4720 }
4721 })?;
4722 if let Some(task) = spawned_test_task {
4723 task.await?;
4724 }
4725
4726 Ok::<_, anyhow::Error>(())
4727 })
4728 .detach_and_log_err(cx);
4729 }
4730
4731 pub fn confirm_code_action(
4732 &mut self,
4733 action: &ConfirmCodeAction,
4734 cx: &mut ViewContext<Self>,
4735 ) -> Option<Task<Result<()>>> {
4736 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4737 menu
4738 } else {
4739 return None;
4740 };
4741 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4742 let action = actions_menu.actions.get(action_ix)?;
4743 let title = action.label();
4744 let buffer = actions_menu.buffer;
4745 let workspace = self.workspace()?;
4746
4747 match action {
4748 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4749 workspace.update(cx, |workspace, cx| {
4750 workspace::tasks::schedule_resolved_task(
4751 workspace,
4752 task_source_kind,
4753 resolved_task,
4754 false,
4755 cx,
4756 );
4757
4758 Some(Task::ready(Ok(())))
4759 })
4760 }
4761 CodeActionsItem::CodeAction {
4762 excerpt_id,
4763 action,
4764 provider,
4765 } => {
4766 let apply_code_action =
4767 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4768 let workspace = workspace.downgrade();
4769 Some(cx.spawn(|editor, cx| async move {
4770 let project_transaction = apply_code_action.await?;
4771 Self::open_project_transaction(
4772 &editor,
4773 workspace,
4774 project_transaction,
4775 title,
4776 cx,
4777 )
4778 .await
4779 }))
4780 }
4781 }
4782 }
4783
4784 pub async fn open_project_transaction(
4785 this: &WeakView<Editor>,
4786 workspace: WeakView<Workspace>,
4787 transaction: ProjectTransaction,
4788 title: String,
4789 mut cx: AsyncWindowContext,
4790 ) -> Result<()> {
4791 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4792 cx.update(|cx| {
4793 entries.sort_unstable_by_key(|(buffer, _)| {
4794 buffer.read(cx).file().map(|f| f.path().clone())
4795 });
4796 })?;
4797
4798 // If the project transaction's edits are all contained within this editor, then
4799 // avoid opening a new editor to display them.
4800
4801 if let Some((buffer, transaction)) = entries.first() {
4802 if entries.len() == 1 {
4803 let excerpt = this.update(&mut cx, |editor, cx| {
4804 editor
4805 .buffer()
4806 .read(cx)
4807 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4808 })?;
4809 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4810 if excerpted_buffer == *buffer {
4811 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4812 let excerpt_range = excerpt_range.to_offset(buffer);
4813 buffer
4814 .edited_ranges_for_transaction::<usize>(transaction)
4815 .all(|range| {
4816 excerpt_range.start <= range.start
4817 && excerpt_range.end >= range.end
4818 })
4819 })?;
4820
4821 if all_edits_within_excerpt {
4822 return Ok(());
4823 }
4824 }
4825 }
4826 }
4827 } else {
4828 return Ok(());
4829 }
4830
4831 let mut ranges_to_highlight = Vec::new();
4832 let excerpt_buffer = cx.new_model(|cx| {
4833 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4834 for (buffer_handle, transaction) in &entries {
4835 let buffer = buffer_handle.read(cx);
4836 ranges_to_highlight.extend(
4837 multibuffer.push_excerpts_with_context_lines(
4838 buffer_handle.clone(),
4839 buffer
4840 .edited_ranges_for_transaction::<usize>(transaction)
4841 .collect(),
4842 DEFAULT_MULTIBUFFER_CONTEXT,
4843 cx,
4844 ),
4845 );
4846 }
4847 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4848 multibuffer
4849 })?;
4850
4851 workspace.update(&mut cx, |workspace, cx| {
4852 let project = workspace.project().clone();
4853 let editor =
4854 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4855 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4856 editor.update(cx, |editor, cx| {
4857 editor.highlight_background::<Self>(
4858 &ranges_to_highlight,
4859 |theme| theme.editor_highlighted_line_background,
4860 cx,
4861 );
4862 });
4863 })?;
4864
4865 Ok(())
4866 }
4867
4868 pub fn push_code_action_provider(
4869 &mut self,
4870 provider: Arc<dyn CodeActionProvider>,
4871 cx: &mut ViewContext<Self>,
4872 ) {
4873 self.code_action_providers.push(provider);
4874 self.refresh_code_actions(cx);
4875 }
4876
4877 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4878 let buffer = self.buffer.read(cx);
4879 let newest_selection = self.selections.newest_anchor().clone();
4880 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4881 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4882 if start_buffer != end_buffer {
4883 return None;
4884 }
4885
4886 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4887 cx.background_executor()
4888 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4889 .await;
4890
4891 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4892 let providers = this.code_action_providers.clone();
4893 let tasks = this
4894 .code_action_providers
4895 .iter()
4896 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4897 .collect::<Vec<_>>();
4898 (providers, tasks)
4899 })?;
4900
4901 let mut actions = Vec::new();
4902 for (provider, provider_actions) in
4903 providers.into_iter().zip(future::join_all(tasks).await)
4904 {
4905 if let Some(provider_actions) = provider_actions.log_err() {
4906 actions.extend(provider_actions.into_iter().map(|action| {
4907 AvailableCodeAction {
4908 excerpt_id: newest_selection.start.excerpt_id,
4909 action,
4910 provider: provider.clone(),
4911 }
4912 }));
4913 }
4914 }
4915
4916 this.update(&mut cx, |this, cx| {
4917 this.available_code_actions = if actions.is_empty() {
4918 None
4919 } else {
4920 Some((
4921 Location {
4922 buffer: start_buffer,
4923 range: start..end,
4924 },
4925 actions.into(),
4926 ))
4927 };
4928 cx.notify();
4929 })
4930 }));
4931 None
4932 }
4933
4934 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4935 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4936 self.show_git_blame_inline = false;
4937
4938 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4939 cx.background_executor().timer(delay).await;
4940
4941 this.update(&mut cx, |this, cx| {
4942 this.show_git_blame_inline = true;
4943 cx.notify();
4944 })
4945 .log_err();
4946 }));
4947 }
4948 }
4949
4950 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4951 if self.pending_rename.is_some() {
4952 return None;
4953 }
4954
4955 let project = self.project.clone()?;
4956 let buffer = self.buffer.read(cx);
4957 let newest_selection = self.selections.newest_anchor().clone();
4958 let cursor_position = newest_selection.head();
4959 let (cursor_buffer, cursor_buffer_position) =
4960 buffer.text_anchor_for_position(cursor_position, cx)?;
4961 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4962 if cursor_buffer != tail_buffer {
4963 return None;
4964 }
4965
4966 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4967 cx.background_executor()
4968 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4969 .await;
4970
4971 let highlights = if let Some(highlights) = project
4972 .update(&mut cx, |project, cx| {
4973 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4974 })
4975 .log_err()
4976 {
4977 highlights.await.log_err()
4978 } else {
4979 None
4980 };
4981
4982 if let Some(highlights) = highlights {
4983 this.update(&mut cx, |this, cx| {
4984 if this.pending_rename.is_some() {
4985 return;
4986 }
4987
4988 let buffer_id = cursor_position.buffer_id;
4989 let buffer = this.buffer.read(cx);
4990 if !buffer
4991 .text_anchor_for_position(cursor_position, cx)
4992 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4993 {
4994 return;
4995 }
4996
4997 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4998 let mut write_ranges = Vec::new();
4999 let mut read_ranges = Vec::new();
5000 for highlight in highlights {
5001 for (excerpt_id, excerpt_range) in
5002 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5003 {
5004 let start = highlight
5005 .range
5006 .start
5007 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5008 let end = highlight
5009 .range
5010 .end
5011 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5012 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5013 continue;
5014 }
5015
5016 let range = Anchor {
5017 buffer_id,
5018 excerpt_id,
5019 text_anchor: start,
5020 }..Anchor {
5021 buffer_id,
5022 excerpt_id,
5023 text_anchor: end,
5024 };
5025 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5026 write_ranges.push(range);
5027 } else {
5028 read_ranges.push(range);
5029 }
5030 }
5031 }
5032
5033 this.highlight_background::<DocumentHighlightRead>(
5034 &read_ranges,
5035 |theme| theme.editor_document_highlight_read_background,
5036 cx,
5037 );
5038 this.highlight_background::<DocumentHighlightWrite>(
5039 &write_ranges,
5040 |theme| theme.editor_document_highlight_write_background,
5041 cx,
5042 );
5043 cx.notify();
5044 })
5045 .log_err();
5046 }
5047 }));
5048 None
5049 }
5050
5051 pub fn refresh_inline_completion(
5052 &mut self,
5053 debounce: bool,
5054 user_requested: bool,
5055 cx: &mut ViewContext<Self>,
5056 ) -> Option<()> {
5057 let provider = self.inline_completion_provider()?;
5058 let cursor = self.selections.newest_anchor().head();
5059 let (buffer, cursor_buffer_position) =
5060 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5061
5062 if !user_requested
5063 && (!self.enable_inline_completions
5064 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5065 {
5066 self.discard_inline_completion(false, cx);
5067 return None;
5068 }
5069
5070 self.update_visible_inline_completion(cx);
5071 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5072 Some(())
5073 }
5074
5075 fn cycle_inline_completion(
5076 &mut self,
5077 direction: Direction,
5078 cx: &mut ViewContext<Self>,
5079 ) -> Option<()> {
5080 let provider = self.inline_completion_provider()?;
5081 let cursor = self.selections.newest_anchor().head();
5082 let (buffer, cursor_buffer_position) =
5083 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5084 if !self.enable_inline_completions
5085 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5086 {
5087 return None;
5088 }
5089
5090 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5091 self.update_visible_inline_completion(cx);
5092
5093 Some(())
5094 }
5095
5096 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5097 if !self.has_active_inline_completion(cx) {
5098 self.refresh_inline_completion(false, true, cx);
5099 return;
5100 }
5101
5102 self.update_visible_inline_completion(cx);
5103 }
5104
5105 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5106 self.show_cursor_names(cx);
5107 }
5108
5109 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5110 self.show_cursor_names = true;
5111 cx.notify();
5112 cx.spawn(|this, mut cx| async move {
5113 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5114 this.update(&mut cx, |this, cx| {
5115 this.show_cursor_names = false;
5116 cx.notify()
5117 })
5118 .ok()
5119 })
5120 .detach();
5121 }
5122
5123 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5124 if self.has_active_inline_completion(cx) {
5125 self.cycle_inline_completion(Direction::Next, cx);
5126 } else {
5127 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5128 if is_copilot_disabled {
5129 cx.propagate();
5130 }
5131 }
5132 }
5133
5134 pub fn previous_inline_completion(
5135 &mut self,
5136 _: &PreviousInlineCompletion,
5137 cx: &mut ViewContext<Self>,
5138 ) {
5139 if self.has_active_inline_completion(cx) {
5140 self.cycle_inline_completion(Direction::Prev, cx);
5141 } else {
5142 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5143 if is_copilot_disabled {
5144 cx.propagate();
5145 }
5146 }
5147 }
5148
5149 pub fn accept_inline_completion(
5150 &mut self,
5151 _: &AcceptInlineCompletion,
5152 cx: &mut ViewContext<Self>,
5153 ) {
5154 let Some(completion) = self.take_active_inline_completion(cx) else {
5155 return;
5156 };
5157 if let Some(provider) = self.inline_completion_provider() {
5158 provider.accept(cx);
5159 }
5160
5161 cx.emit(EditorEvent::InputHandled {
5162 utf16_range_to_replace: None,
5163 text: completion.text.to_string().into(),
5164 });
5165
5166 if let Some(range) = completion.delete_range {
5167 self.change_selections(None, cx, |s| s.select_ranges([range]))
5168 }
5169 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5170 self.refresh_inline_completion(true, true, cx);
5171 cx.notify();
5172 }
5173
5174 pub fn accept_partial_inline_completion(
5175 &mut self,
5176 _: &AcceptPartialInlineCompletion,
5177 cx: &mut ViewContext<Self>,
5178 ) {
5179 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5180 if let Some(completion) = self.take_active_inline_completion(cx) {
5181 let mut partial_completion = completion
5182 .text
5183 .chars()
5184 .by_ref()
5185 .take_while(|c| c.is_alphabetic())
5186 .collect::<String>();
5187 if partial_completion.is_empty() {
5188 partial_completion = completion
5189 .text
5190 .chars()
5191 .by_ref()
5192 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5193 .collect::<String>();
5194 }
5195
5196 cx.emit(EditorEvent::InputHandled {
5197 utf16_range_to_replace: None,
5198 text: partial_completion.clone().into(),
5199 });
5200
5201 if let Some(range) = completion.delete_range {
5202 self.change_selections(None, cx, |s| s.select_ranges([range]))
5203 }
5204 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5205
5206 self.refresh_inline_completion(true, true, cx);
5207 cx.notify();
5208 }
5209 }
5210 }
5211
5212 fn discard_inline_completion(
5213 &mut self,
5214 should_report_inline_completion_event: bool,
5215 cx: &mut ViewContext<Self>,
5216 ) -> bool {
5217 if let Some(provider) = self.inline_completion_provider() {
5218 provider.discard(should_report_inline_completion_event, cx);
5219 }
5220
5221 self.take_active_inline_completion(cx).is_some()
5222 }
5223
5224 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5225 if let Some(completion) = self.active_inline_completion.as_ref() {
5226 let buffer = self.buffer.read(cx).read(cx);
5227 completion.position.is_valid(&buffer)
5228 } else {
5229 false
5230 }
5231 }
5232
5233 fn take_active_inline_completion(
5234 &mut self,
5235 cx: &mut ViewContext<Self>,
5236 ) -> Option<CompletionState> {
5237 let completion = self.active_inline_completion.take()?;
5238 let render_inlay_ids = completion.render_inlay_ids.clone();
5239 self.display_map.update(cx, |map, cx| {
5240 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5241 });
5242 let buffer = self.buffer.read(cx).read(cx);
5243
5244 if completion.position.is_valid(&buffer) {
5245 Some(completion)
5246 } else {
5247 None
5248 }
5249 }
5250
5251 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5252 let selection = self.selections.newest_anchor();
5253 let cursor = selection.head();
5254
5255 let excerpt_id = cursor.excerpt_id;
5256
5257 if self.context_menu.read().is_none()
5258 && self.completion_tasks.is_empty()
5259 && selection.start == selection.end
5260 {
5261 if let Some(provider) = self.inline_completion_provider() {
5262 if let Some((buffer, cursor_buffer_position)) =
5263 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5264 {
5265 if let Some(proposal) =
5266 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5267 {
5268 let mut to_remove = Vec::new();
5269 if let Some(completion) = self.active_inline_completion.take() {
5270 to_remove.extend(completion.render_inlay_ids.iter());
5271 }
5272
5273 let to_add = proposal
5274 .inlays
5275 .iter()
5276 .filter_map(|inlay| {
5277 let snapshot = self.buffer.read(cx).snapshot(cx);
5278 let id = post_inc(&mut self.next_inlay_id);
5279 match inlay {
5280 InlayProposal::Hint(position, hint) => {
5281 let position =
5282 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5283 Some(Inlay::hint(id, position, hint))
5284 }
5285 InlayProposal::Suggestion(position, text) => {
5286 let position =
5287 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5288 Some(Inlay::suggestion(id, position, text.clone()))
5289 }
5290 }
5291 })
5292 .collect_vec();
5293
5294 self.active_inline_completion = Some(CompletionState {
5295 position: cursor,
5296 text: proposal.text,
5297 delete_range: proposal.delete_range.and_then(|range| {
5298 let snapshot = self.buffer.read(cx).snapshot(cx);
5299 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5300 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5301 Some(start?..end?)
5302 }),
5303 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5304 });
5305
5306 self.display_map
5307 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5308
5309 cx.notify();
5310 return;
5311 }
5312 }
5313 }
5314 }
5315
5316 self.discard_inline_completion(false, cx);
5317 }
5318
5319 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5320 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5321 }
5322
5323 fn render_code_actions_indicator(
5324 &self,
5325 _style: &EditorStyle,
5326 row: DisplayRow,
5327 is_active: bool,
5328 cx: &mut ViewContext<Self>,
5329 ) -> Option<IconButton> {
5330 if self.available_code_actions.is_some() {
5331 Some(
5332 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5333 .shape(ui::IconButtonShape::Square)
5334 .icon_size(IconSize::XSmall)
5335 .icon_color(Color::Muted)
5336 .selected(is_active)
5337 .on_click(cx.listener(move |editor, _e, cx| {
5338 editor.focus(cx);
5339 editor.toggle_code_actions(
5340 &ToggleCodeActions {
5341 deployed_from_indicator: Some(row),
5342 },
5343 cx,
5344 );
5345 })),
5346 )
5347 } else {
5348 None
5349 }
5350 }
5351
5352 fn clear_tasks(&mut self) {
5353 self.tasks.clear()
5354 }
5355
5356 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5357 if self.tasks.insert(key, value).is_some() {
5358 // This case should hopefully be rare, but just in case...
5359 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5360 }
5361 }
5362
5363 fn render_run_indicator(
5364 &self,
5365 _style: &EditorStyle,
5366 is_active: bool,
5367 row: DisplayRow,
5368 cx: &mut ViewContext<Self>,
5369 ) -> IconButton {
5370 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5371 .shape(ui::IconButtonShape::Square)
5372 .icon_size(IconSize::XSmall)
5373 .icon_color(Color::Muted)
5374 .selected(is_active)
5375 .on_click(cx.listener(move |editor, _e, cx| {
5376 editor.focus(cx);
5377 editor.toggle_code_actions(
5378 &ToggleCodeActions {
5379 deployed_from_indicator: Some(row),
5380 },
5381 cx,
5382 );
5383 }))
5384 }
5385
5386 fn close_hunk_diff_button(
5387 &self,
5388 hunk: HoveredHunk,
5389 row: DisplayRow,
5390 cx: &mut ViewContext<Self>,
5391 ) -> IconButton {
5392 IconButton::new(
5393 ("close_hunk_diff_indicator", row.0 as usize),
5394 ui::IconName::Close,
5395 )
5396 .shape(ui::IconButtonShape::Square)
5397 .icon_size(IconSize::XSmall)
5398 .icon_color(Color::Muted)
5399 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5400 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5401 }
5402
5403 pub fn context_menu_visible(&self) -> bool {
5404 self.context_menu
5405 .read()
5406 .as_ref()
5407 .map_or(false, |menu| menu.visible())
5408 }
5409
5410 fn render_context_menu(
5411 &self,
5412 cursor_position: DisplayPoint,
5413 style: &EditorStyle,
5414 max_height: Pixels,
5415 cx: &mut ViewContext<Editor>,
5416 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5417 self.context_menu.read().as_ref().map(|menu| {
5418 menu.render(
5419 cursor_position,
5420 style,
5421 max_height,
5422 self.workspace.as_ref().map(|(w, _)| w.clone()),
5423 cx,
5424 )
5425 })
5426 }
5427
5428 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5429 cx.notify();
5430 self.completion_tasks.clear();
5431 let context_menu = self.context_menu.write().take();
5432 if context_menu.is_some() {
5433 self.update_visible_inline_completion(cx);
5434 }
5435 context_menu
5436 }
5437
5438 pub fn insert_snippet(
5439 &mut self,
5440 insertion_ranges: &[Range<usize>],
5441 snippet: Snippet,
5442 cx: &mut ViewContext<Self>,
5443 ) -> Result<()> {
5444 struct Tabstop<T> {
5445 is_end_tabstop: bool,
5446 ranges: Vec<Range<T>>,
5447 }
5448
5449 let tabstops = self.buffer.update(cx, |buffer, cx| {
5450 let snippet_text: Arc<str> = snippet.text.clone().into();
5451 buffer.edit(
5452 insertion_ranges
5453 .iter()
5454 .cloned()
5455 .map(|range| (range, snippet_text.clone())),
5456 Some(AutoindentMode::EachLine),
5457 cx,
5458 );
5459
5460 let snapshot = &*buffer.read(cx);
5461 let snippet = &snippet;
5462 snippet
5463 .tabstops
5464 .iter()
5465 .map(|tabstop| {
5466 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5467 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5468 });
5469 let mut tabstop_ranges = tabstop
5470 .iter()
5471 .flat_map(|tabstop_range| {
5472 let mut delta = 0_isize;
5473 insertion_ranges.iter().map(move |insertion_range| {
5474 let insertion_start = insertion_range.start as isize + delta;
5475 delta +=
5476 snippet.text.len() as isize - insertion_range.len() as isize;
5477
5478 let start = ((insertion_start + tabstop_range.start) as usize)
5479 .min(snapshot.len());
5480 let end = ((insertion_start + tabstop_range.end) as usize)
5481 .min(snapshot.len());
5482 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5483 })
5484 })
5485 .collect::<Vec<_>>();
5486 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5487
5488 Tabstop {
5489 is_end_tabstop,
5490 ranges: tabstop_ranges,
5491 }
5492 })
5493 .collect::<Vec<_>>()
5494 });
5495 if let Some(tabstop) = tabstops.first() {
5496 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5497 s.select_ranges(tabstop.ranges.iter().cloned());
5498 });
5499
5500 // If we're already at the last tabstop and it's at the end of the snippet,
5501 // we're done, we don't need to keep the state around.
5502 if !tabstop.is_end_tabstop {
5503 let ranges = tabstops
5504 .into_iter()
5505 .map(|tabstop| tabstop.ranges)
5506 .collect::<Vec<_>>();
5507 self.snippet_stack.push(SnippetState {
5508 active_index: 0,
5509 ranges,
5510 });
5511 }
5512
5513 // Check whether the just-entered snippet ends with an auto-closable bracket.
5514 if self.autoclose_regions.is_empty() {
5515 let snapshot = self.buffer.read(cx).snapshot(cx);
5516 for selection in &mut self.selections.all::<Point>(cx) {
5517 let selection_head = selection.head();
5518 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5519 continue;
5520 };
5521
5522 let mut bracket_pair = None;
5523 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5524 let prev_chars = snapshot
5525 .reversed_chars_at(selection_head)
5526 .collect::<String>();
5527 for (pair, enabled) in scope.brackets() {
5528 if enabled
5529 && pair.close
5530 && prev_chars.starts_with(pair.start.as_str())
5531 && next_chars.starts_with(pair.end.as_str())
5532 {
5533 bracket_pair = Some(pair.clone());
5534 break;
5535 }
5536 }
5537 if let Some(pair) = bracket_pair {
5538 let start = snapshot.anchor_after(selection_head);
5539 let end = snapshot.anchor_after(selection_head);
5540 self.autoclose_regions.push(AutocloseRegion {
5541 selection_id: selection.id,
5542 range: start..end,
5543 pair,
5544 });
5545 }
5546 }
5547 }
5548 }
5549 Ok(())
5550 }
5551
5552 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5553 self.move_to_snippet_tabstop(Bias::Right, cx)
5554 }
5555
5556 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5557 self.move_to_snippet_tabstop(Bias::Left, cx)
5558 }
5559
5560 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5561 if let Some(mut snippet) = self.snippet_stack.pop() {
5562 match bias {
5563 Bias::Left => {
5564 if snippet.active_index > 0 {
5565 snippet.active_index -= 1;
5566 } else {
5567 self.snippet_stack.push(snippet);
5568 return false;
5569 }
5570 }
5571 Bias::Right => {
5572 if snippet.active_index + 1 < snippet.ranges.len() {
5573 snippet.active_index += 1;
5574 } else {
5575 self.snippet_stack.push(snippet);
5576 return false;
5577 }
5578 }
5579 }
5580 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5581 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5582 s.select_anchor_ranges(current_ranges.iter().cloned())
5583 });
5584 // If snippet state is not at the last tabstop, push it back on the stack
5585 if snippet.active_index + 1 < snippet.ranges.len() {
5586 self.snippet_stack.push(snippet);
5587 }
5588 return true;
5589 }
5590 }
5591
5592 false
5593 }
5594
5595 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5596 self.transact(cx, |this, cx| {
5597 this.select_all(&SelectAll, cx);
5598 this.insert("", cx);
5599 });
5600 }
5601
5602 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5603 self.transact(cx, |this, cx| {
5604 this.select_autoclose_pair(cx);
5605 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5606 if !this.linked_edit_ranges.is_empty() {
5607 let selections = this.selections.all::<MultiBufferPoint>(cx);
5608 let snapshot = this.buffer.read(cx).snapshot(cx);
5609
5610 for selection in selections.iter() {
5611 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5612 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5613 if selection_start.buffer_id != selection_end.buffer_id {
5614 continue;
5615 }
5616 if let Some(ranges) =
5617 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5618 {
5619 for (buffer, entries) in ranges {
5620 linked_ranges.entry(buffer).or_default().extend(entries);
5621 }
5622 }
5623 }
5624 }
5625
5626 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5627 if !this.selections.line_mode {
5628 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5629 for selection in &mut selections {
5630 if selection.is_empty() {
5631 let old_head = selection.head();
5632 let mut new_head =
5633 movement::left(&display_map, old_head.to_display_point(&display_map))
5634 .to_point(&display_map);
5635 if let Some((buffer, line_buffer_range)) = display_map
5636 .buffer_snapshot
5637 .buffer_line_for_row(MultiBufferRow(old_head.row))
5638 {
5639 let indent_size =
5640 buffer.indent_size_for_line(line_buffer_range.start.row);
5641 let indent_len = match indent_size.kind {
5642 IndentKind::Space => {
5643 buffer.settings_at(line_buffer_range.start, cx).tab_size
5644 }
5645 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5646 };
5647 if old_head.column <= indent_size.len && old_head.column > 0 {
5648 let indent_len = indent_len.get();
5649 new_head = cmp::min(
5650 new_head,
5651 MultiBufferPoint::new(
5652 old_head.row,
5653 ((old_head.column - 1) / indent_len) * indent_len,
5654 ),
5655 );
5656 }
5657 }
5658
5659 selection.set_head(new_head, SelectionGoal::None);
5660 }
5661 }
5662 }
5663
5664 this.signature_help_state.set_backspace_pressed(true);
5665 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5666 this.insert("", cx);
5667 let empty_str: Arc<str> = Arc::from("");
5668 for (buffer, edits) in linked_ranges {
5669 let snapshot = buffer.read(cx).snapshot();
5670 use text::ToPoint as TP;
5671
5672 let edits = edits
5673 .into_iter()
5674 .map(|range| {
5675 let end_point = TP::to_point(&range.end, &snapshot);
5676 let mut start_point = TP::to_point(&range.start, &snapshot);
5677
5678 if end_point == start_point {
5679 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5680 .saturating_sub(1);
5681 start_point = TP::to_point(&offset, &snapshot);
5682 };
5683
5684 (start_point..end_point, empty_str.clone())
5685 })
5686 .sorted_by_key(|(range, _)| range.start)
5687 .collect::<Vec<_>>();
5688 buffer.update(cx, |this, cx| {
5689 this.edit(edits, None, cx);
5690 })
5691 }
5692 this.refresh_inline_completion(true, false, cx);
5693 linked_editing_ranges::refresh_linked_ranges(this, cx);
5694 });
5695 }
5696
5697 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5698 self.transact(cx, |this, cx| {
5699 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5700 let line_mode = s.line_mode;
5701 s.move_with(|map, selection| {
5702 if selection.is_empty() && !line_mode {
5703 let cursor = movement::right(map, selection.head());
5704 selection.end = cursor;
5705 selection.reversed = true;
5706 selection.goal = SelectionGoal::None;
5707 }
5708 })
5709 });
5710 this.insert("", cx);
5711 this.refresh_inline_completion(true, false, cx);
5712 });
5713 }
5714
5715 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5716 if self.move_to_prev_snippet_tabstop(cx) {
5717 return;
5718 }
5719
5720 self.outdent(&Outdent, cx);
5721 }
5722
5723 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5724 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5725 return;
5726 }
5727
5728 let mut selections = self.selections.all_adjusted(cx);
5729 let buffer = self.buffer.read(cx);
5730 let snapshot = buffer.snapshot(cx);
5731 let rows_iter = selections.iter().map(|s| s.head().row);
5732 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5733
5734 let mut edits = Vec::new();
5735 let mut prev_edited_row = 0;
5736 let mut row_delta = 0;
5737 for selection in &mut selections {
5738 if selection.start.row != prev_edited_row {
5739 row_delta = 0;
5740 }
5741 prev_edited_row = selection.end.row;
5742
5743 // If the selection is non-empty, then increase the indentation of the selected lines.
5744 if !selection.is_empty() {
5745 row_delta =
5746 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5747 continue;
5748 }
5749
5750 // If the selection is empty and the cursor is in the leading whitespace before the
5751 // suggested indentation, then auto-indent the line.
5752 let cursor = selection.head();
5753 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5754 if let Some(suggested_indent) =
5755 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5756 {
5757 if cursor.column < suggested_indent.len
5758 && cursor.column <= current_indent.len
5759 && current_indent.len <= suggested_indent.len
5760 {
5761 selection.start = Point::new(cursor.row, suggested_indent.len);
5762 selection.end = selection.start;
5763 if row_delta == 0 {
5764 edits.extend(Buffer::edit_for_indent_size_adjustment(
5765 cursor.row,
5766 current_indent,
5767 suggested_indent,
5768 ));
5769 row_delta = suggested_indent.len - current_indent.len;
5770 }
5771 continue;
5772 }
5773 }
5774
5775 // Otherwise, insert a hard or soft tab.
5776 let settings = buffer.settings_at(cursor, cx);
5777 let tab_size = if settings.hard_tabs {
5778 IndentSize::tab()
5779 } else {
5780 let tab_size = settings.tab_size.get();
5781 let char_column = snapshot
5782 .text_for_range(Point::new(cursor.row, 0)..cursor)
5783 .flat_map(str::chars)
5784 .count()
5785 + row_delta as usize;
5786 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5787 IndentSize::spaces(chars_to_next_tab_stop)
5788 };
5789 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5790 selection.end = selection.start;
5791 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5792 row_delta += tab_size.len;
5793 }
5794
5795 self.transact(cx, |this, cx| {
5796 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5797 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5798 this.refresh_inline_completion(true, false, cx);
5799 });
5800 }
5801
5802 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5803 if self.read_only(cx) {
5804 return;
5805 }
5806 let mut selections = self.selections.all::<Point>(cx);
5807 let mut prev_edited_row = 0;
5808 let mut row_delta = 0;
5809 let mut edits = Vec::new();
5810 let buffer = self.buffer.read(cx);
5811 let snapshot = buffer.snapshot(cx);
5812 for selection in &mut selections {
5813 if selection.start.row != prev_edited_row {
5814 row_delta = 0;
5815 }
5816 prev_edited_row = selection.end.row;
5817
5818 row_delta =
5819 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5820 }
5821
5822 self.transact(cx, |this, cx| {
5823 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5824 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5825 });
5826 }
5827
5828 fn indent_selection(
5829 buffer: &MultiBuffer,
5830 snapshot: &MultiBufferSnapshot,
5831 selection: &mut Selection<Point>,
5832 edits: &mut Vec<(Range<Point>, String)>,
5833 delta_for_start_row: u32,
5834 cx: &AppContext,
5835 ) -> u32 {
5836 let settings = buffer.settings_at(selection.start, cx);
5837 let tab_size = settings.tab_size.get();
5838 let indent_kind = if settings.hard_tabs {
5839 IndentKind::Tab
5840 } else {
5841 IndentKind::Space
5842 };
5843 let mut start_row = selection.start.row;
5844 let mut end_row = selection.end.row + 1;
5845
5846 // If a selection ends at the beginning of a line, don't indent
5847 // that last line.
5848 if selection.end.column == 0 && selection.end.row > selection.start.row {
5849 end_row -= 1;
5850 }
5851
5852 // Avoid re-indenting a row that has already been indented by a
5853 // previous selection, but still update this selection's column
5854 // to reflect that indentation.
5855 if delta_for_start_row > 0 {
5856 start_row += 1;
5857 selection.start.column += delta_for_start_row;
5858 if selection.end.row == selection.start.row {
5859 selection.end.column += delta_for_start_row;
5860 }
5861 }
5862
5863 let mut delta_for_end_row = 0;
5864 let has_multiple_rows = start_row + 1 != end_row;
5865 for row in start_row..end_row {
5866 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5867 let indent_delta = match (current_indent.kind, indent_kind) {
5868 (IndentKind::Space, IndentKind::Space) => {
5869 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5870 IndentSize::spaces(columns_to_next_tab_stop)
5871 }
5872 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5873 (_, IndentKind::Tab) => IndentSize::tab(),
5874 };
5875
5876 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5877 0
5878 } else {
5879 selection.start.column
5880 };
5881 let row_start = Point::new(row, start);
5882 edits.push((
5883 row_start..row_start,
5884 indent_delta.chars().collect::<String>(),
5885 ));
5886
5887 // Update this selection's endpoints to reflect the indentation.
5888 if row == selection.start.row {
5889 selection.start.column += indent_delta.len;
5890 }
5891 if row == selection.end.row {
5892 selection.end.column += indent_delta.len;
5893 delta_for_end_row = indent_delta.len;
5894 }
5895 }
5896
5897 if selection.start.row == selection.end.row {
5898 delta_for_start_row + delta_for_end_row
5899 } else {
5900 delta_for_end_row
5901 }
5902 }
5903
5904 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5905 if self.read_only(cx) {
5906 return;
5907 }
5908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5909 let selections = self.selections.all::<Point>(cx);
5910 let mut deletion_ranges = Vec::new();
5911 let mut last_outdent = None;
5912 {
5913 let buffer = self.buffer.read(cx);
5914 let snapshot = buffer.snapshot(cx);
5915 for selection in &selections {
5916 let settings = buffer.settings_at(selection.start, cx);
5917 let tab_size = settings.tab_size.get();
5918 let mut rows = selection.spanned_rows(false, &display_map);
5919
5920 // Avoid re-outdenting a row that has already been outdented by a
5921 // previous selection.
5922 if let Some(last_row) = last_outdent {
5923 if last_row == rows.start {
5924 rows.start = rows.start.next_row();
5925 }
5926 }
5927 let has_multiple_rows = rows.len() > 1;
5928 for row in rows.iter_rows() {
5929 let indent_size = snapshot.indent_size_for_line(row);
5930 if indent_size.len > 0 {
5931 let deletion_len = match indent_size.kind {
5932 IndentKind::Space => {
5933 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5934 if columns_to_prev_tab_stop == 0 {
5935 tab_size
5936 } else {
5937 columns_to_prev_tab_stop
5938 }
5939 }
5940 IndentKind::Tab => 1,
5941 };
5942 let start = if has_multiple_rows
5943 || deletion_len > selection.start.column
5944 || indent_size.len < selection.start.column
5945 {
5946 0
5947 } else {
5948 selection.start.column - deletion_len
5949 };
5950 deletion_ranges.push(
5951 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5952 );
5953 last_outdent = Some(row);
5954 }
5955 }
5956 }
5957 }
5958
5959 self.transact(cx, |this, cx| {
5960 this.buffer.update(cx, |buffer, cx| {
5961 let empty_str: Arc<str> = Arc::default();
5962 buffer.edit(
5963 deletion_ranges
5964 .into_iter()
5965 .map(|range| (range, empty_str.clone())),
5966 None,
5967 cx,
5968 );
5969 });
5970 let selections = this.selections.all::<usize>(cx);
5971 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5972 });
5973 }
5974
5975 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5976 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5977 let selections = self.selections.all::<Point>(cx);
5978
5979 let mut new_cursors = Vec::new();
5980 let mut edit_ranges = Vec::new();
5981 let mut selections = selections.iter().peekable();
5982 while let Some(selection) = selections.next() {
5983 let mut rows = selection.spanned_rows(false, &display_map);
5984 let goal_display_column = selection.head().to_display_point(&display_map).column();
5985
5986 // Accumulate contiguous regions of rows that we want to delete.
5987 while let Some(next_selection) = selections.peek() {
5988 let next_rows = next_selection.spanned_rows(false, &display_map);
5989 if next_rows.start <= rows.end {
5990 rows.end = next_rows.end;
5991 selections.next().unwrap();
5992 } else {
5993 break;
5994 }
5995 }
5996
5997 let buffer = &display_map.buffer_snapshot;
5998 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5999 let edit_end;
6000 let cursor_buffer_row;
6001 if buffer.max_point().row >= rows.end.0 {
6002 // If there's a line after the range, delete the \n from the end of the row range
6003 // and position the cursor on the next line.
6004 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6005 cursor_buffer_row = rows.end;
6006 } else {
6007 // If there isn't a line after the range, delete the \n from the line before the
6008 // start of the row range and position the cursor there.
6009 edit_start = edit_start.saturating_sub(1);
6010 edit_end = buffer.len();
6011 cursor_buffer_row = rows.start.previous_row();
6012 }
6013
6014 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6015 *cursor.column_mut() =
6016 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6017
6018 new_cursors.push((
6019 selection.id,
6020 buffer.anchor_after(cursor.to_point(&display_map)),
6021 ));
6022 edit_ranges.push(edit_start..edit_end);
6023 }
6024
6025 self.transact(cx, |this, cx| {
6026 let buffer = this.buffer.update(cx, |buffer, cx| {
6027 let empty_str: Arc<str> = Arc::default();
6028 buffer.edit(
6029 edit_ranges
6030 .into_iter()
6031 .map(|range| (range, empty_str.clone())),
6032 None,
6033 cx,
6034 );
6035 buffer.snapshot(cx)
6036 });
6037 let new_selections = new_cursors
6038 .into_iter()
6039 .map(|(id, cursor)| {
6040 let cursor = cursor.to_point(&buffer);
6041 Selection {
6042 id,
6043 start: cursor,
6044 end: cursor,
6045 reversed: false,
6046 goal: SelectionGoal::None,
6047 }
6048 })
6049 .collect();
6050
6051 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6052 s.select(new_selections);
6053 });
6054 });
6055 }
6056
6057 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6058 if self.read_only(cx) {
6059 return;
6060 }
6061 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6062 for selection in self.selections.all::<Point>(cx) {
6063 let start = MultiBufferRow(selection.start.row);
6064 let end = if selection.start.row == selection.end.row {
6065 MultiBufferRow(selection.start.row + 1)
6066 } else {
6067 MultiBufferRow(selection.end.row)
6068 };
6069
6070 if let Some(last_row_range) = row_ranges.last_mut() {
6071 if start <= last_row_range.end {
6072 last_row_range.end = end;
6073 continue;
6074 }
6075 }
6076 row_ranges.push(start..end);
6077 }
6078
6079 let snapshot = self.buffer.read(cx).snapshot(cx);
6080 let mut cursor_positions = Vec::new();
6081 for row_range in &row_ranges {
6082 let anchor = snapshot.anchor_before(Point::new(
6083 row_range.end.previous_row().0,
6084 snapshot.line_len(row_range.end.previous_row()),
6085 ));
6086 cursor_positions.push(anchor..anchor);
6087 }
6088
6089 self.transact(cx, |this, cx| {
6090 for row_range in row_ranges.into_iter().rev() {
6091 for row in row_range.iter_rows().rev() {
6092 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6093 let next_line_row = row.next_row();
6094 let indent = snapshot.indent_size_for_line(next_line_row);
6095 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6096
6097 let replace = if snapshot.line_len(next_line_row) > indent.len {
6098 " "
6099 } else {
6100 ""
6101 };
6102
6103 this.buffer.update(cx, |buffer, cx| {
6104 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6105 });
6106 }
6107 }
6108
6109 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6110 s.select_anchor_ranges(cursor_positions)
6111 });
6112 });
6113 }
6114
6115 pub fn sort_lines_case_sensitive(
6116 &mut self,
6117 _: &SortLinesCaseSensitive,
6118 cx: &mut ViewContext<Self>,
6119 ) {
6120 self.manipulate_lines(cx, |lines| lines.sort())
6121 }
6122
6123 pub fn sort_lines_case_insensitive(
6124 &mut self,
6125 _: &SortLinesCaseInsensitive,
6126 cx: &mut ViewContext<Self>,
6127 ) {
6128 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6129 }
6130
6131 pub fn unique_lines_case_insensitive(
6132 &mut self,
6133 _: &UniqueLinesCaseInsensitive,
6134 cx: &mut ViewContext<Self>,
6135 ) {
6136 self.manipulate_lines(cx, |lines| {
6137 let mut seen = HashSet::default();
6138 lines.retain(|line| seen.insert(line.to_lowercase()));
6139 })
6140 }
6141
6142 pub fn unique_lines_case_sensitive(
6143 &mut self,
6144 _: &UniqueLinesCaseSensitive,
6145 cx: &mut ViewContext<Self>,
6146 ) {
6147 self.manipulate_lines(cx, |lines| {
6148 let mut seen = HashSet::default();
6149 lines.retain(|line| seen.insert(*line));
6150 })
6151 }
6152
6153 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6154 let mut revert_changes = HashMap::default();
6155 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6156 for hunk in hunks_for_rows(
6157 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6158 &multi_buffer_snapshot,
6159 ) {
6160 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6161 }
6162 if !revert_changes.is_empty() {
6163 self.transact(cx, |editor, cx| {
6164 editor.revert(revert_changes, cx);
6165 });
6166 }
6167 }
6168
6169 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6170 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6171 if !revert_changes.is_empty() {
6172 self.transact(cx, |editor, cx| {
6173 editor.revert(revert_changes, cx);
6174 });
6175 }
6176 }
6177
6178 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6179 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6180 let project_path = buffer.read(cx).project_path(cx)?;
6181 let project = self.project.as_ref()?.read(cx);
6182 let entry = project.entry_for_path(&project_path, cx)?;
6183 let abs_path = project.absolute_path(&project_path, cx)?;
6184 let parent = if entry.is_symlink {
6185 abs_path.canonicalize().ok()?
6186 } else {
6187 abs_path
6188 }
6189 .parent()?
6190 .to_path_buf();
6191 Some(parent)
6192 }) {
6193 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6194 }
6195 }
6196
6197 fn gather_revert_changes(
6198 &mut self,
6199 selections: &[Selection<Anchor>],
6200 cx: &mut ViewContext<'_, Editor>,
6201 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6202 let mut revert_changes = HashMap::default();
6203 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6204 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6205 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6206 }
6207 revert_changes
6208 }
6209
6210 pub fn prepare_revert_change(
6211 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6212 multi_buffer: &Model<MultiBuffer>,
6213 hunk: &MultiBufferDiffHunk,
6214 cx: &AppContext,
6215 ) -> Option<()> {
6216 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6217 let buffer = buffer.read(cx);
6218 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6219 let buffer_snapshot = buffer.snapshot();
6220 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6221 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6222 probe
6223 .0
6224 .start
6225 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6226 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6227 }) {
6228 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6229 Some(())
6230 } else {
6231 None
6232 }
6233 }
6234
6235 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6236 self.manipulate_lines(cx, |lines| lines.reverse())
6237 }
6238
6239 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6240 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6241 }
6242
6243 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6244 where
6245 Fn: FnMut(&mut Vec<&str>),
6246 {
6247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6248 let buffer = self.buffer.read(cx).snapshot(cx);
6249
6250 let mut edits = Vec::new();
6251
6252 let selections = self.selections.all::<Point>(cx);
6253 let mut selections = selections.iter().peekable();
6254 let mut contiguous_row_selections = Vec::new();
6255 let mut new_selections = Vec::new();
6256 let mut added_lines = 0;
6257 let mut removed_lines = 0;
6258
6259 while let Some(selection) = selections.next() {
6260 let (start_row, end_row) = consume_contiguous_rows(
6261 &mut contiguous_row_selections,
6262 selection,
6263 &display_map,
6264 &mut selections,
6265 );
6266
6267 let start_point = Point::new(start_row.0, 0);
6268 let end_point = Point::new(
6269 end_row.previous_row().0,
6270 buffer.line_len(end_row.previous_row()),
6271 );
6272 let text = buffer
6273 .text_for_range(start_point..end_point)
6274 .collect::<String>();
6275
6276 let mut lines = text.split('\n').collect_vec();
6277
6278 let lines_before = lines.len();
6279 callback(&mut lines);
6280 let lines_after = lines.len();
6281
6282 edits.push((start_point..end_point, lines.join("\n")));
6283
6284 // Selections must change based on added and removed line count
6285 let start_row =
6286 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6287 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6288 new_selections.push(Selection {
6289 id: selection.id,
6290 start: start_row,
6291 end: end_row,
6292 goal: SelectionGoal::None,
6293 reversed: selection.reversed,
6294 });
6295
6296 if lines_after > lines_before {
6297 added_lines += lines_after - lines_before;
6298 } else if lines_before > lines_after {
6299 removed_lines += lines_before - lines_after;
6300 }
6301 }
6302
6303 self.transact(cx, |this, cx| {
6304 let buffer = this.buffer.update(cx, |buffer, cx| {
6305 buffer.edit(edits, None, cx);
6306 buffer.snapshot(cx)
6307 });
6308
6309 // Recalculate offsets on newly edited buffer
6310 let new_selections = new_selections
6311 .iter()
6312 .map(|s| {
6313 let start_point = Point::new(s.start.0, 0);
6314 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6315 Selection {
6316 id: s.id,
6317 start: buffer.point_to_offset(start_point),
6318 end: buffer.point_to_offset(end_point),
6319 goal: s.goal,
6320 reversed: s.reversed,
6321 }
6322 })
6323 .collect();
6324
6325 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6326 s.select(new_selections);
6327 });
6328
6329 this.request_autoscroll(Autoscroll::fit(), cx);
6330 });
6331 }
6332
6333 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6334 self.manipulate_text(cx, |text| text.to_uppercase())
6335 }
6336
6337 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6338 self.manipulate_text(cx, |text| text.to_lowercase())
6339 }
6340
6341 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6342 self.manipulate_text(cx, |text| {
6343 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6344 // https://github.com/rutrum/convert-case/issues/16
6345 text.split('\n')
6346 .map(|line| line.to_case(Case::Title))
6347 .join("\n")
6348 })
6349 }
6350
6351 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6352 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6353 }
6354
6355 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6356 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6357 }
6358
6359 pub fn convert_to_upper_camel_case(
6360 &mut self,
6361 _: &ConvertToUpperCamelCase,
6362 cx: &mut ViewContext<Self>,
6363 ) {
6364 self.manipulate_text(cx, |text| {
6365 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6366 // https://github.com/rutrum/convert-case/issues/16
6367 text.split('\n')
6368 .map(|line| line.to_case(Case::UpperCamel))
6369 .join("\n")
6370 })
6371 }
6372
6373 pub fn convert_to_lower_camel_case(
6374 &mut self,
6375 _: &ConvertToLowerCamelCase,
6376 cx: &mut ViewContext<Self>,
6377 ) {
6378 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6379 }
6380
6381 pub fn convert_to_opposite_case(
6382 &mut self,
6383 _: &ConvertToOppositeCase,
6384 cx: &mut ViewContext<Self>,
6385 ) {
6386 self.manipulate_text(cx, |text| {
6387 text.chars()
6388 .fold(String::with_capacity(text.len()), |mut t, c| {
6389 if c.is_uppercase() {
6390 t.extend(c.to_lowercase());
6391 } else {
6392 t.extend(c.to_uppercase());
6393 }
6394 t
6395 })
6396 })
6397 }
6398
6399 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6400 where
6401 Fn: FnMut(&str) -> String,
6402 {
6403 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6404 let buffer = self.buffer.read(cx).snapshot(cx);
6405
6406 let mut new_selections = Vec::new();
6407 let mut edits = Vec::new();
6408 let mut selection_adjustment = 0i32;
6409
6410 for selection in self.selections.all::<usize>(cx) {
6411 let selection_is_empty = selection.is_empty();
6412
6413 let (start, end) = if selection_is_empty {
6414 let word_range = movement::surrounding_word(
6415 &display_map,
6416 selection.start.to_display_point(&display_map),
6417 );
6418 let start = word_range.start.to_offset(&display_map, Bias::Left);
6419 let end = word_range.end.to_offset(&display_map, Bias::Left);
6420 (start, end)
6421 } else {
6422 (selection.start, selection.end)
6423 };
6424
6425 let text = buffer.text_for_range(start..end).collect::<String>();
6426 let old_length = text.len() as i32;
6427 let text = callback(&text);
6428
6429 new_selections.push(Selection {
6430 start: (start as i32 - selection_adjustment) as usize,
6431 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6432 goal: SelectionGoal::None,
6433 ..selection
6434 });
6435
6436 selection_adjustment += old_length - text.len() as i32;
6437
6438 edits.push((start..end, text));
6439 }
6440
6441 self.transact(cx, |this, cx| {
6442 this.buffer.update(cx, |buffer, cx| {
6443 buffer.edit(edits, None, cx);
6444 });
6445
6446 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6447 s.select(new_selections);
6448 });
6449
6450 this.request_autoscroll(Autoscroll::fit(), cx);
6451 });
6452 }
6453
6454 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6455 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6456 let buffer = &display_map.buffer_snapshot;
6457 let selections = self.selections.all::<Point>(cx);
6458
6459 let mut edits = Vec::new();
6460 let mut selections_iter = selections.iter().peekable();
6461 while let Some(selection) = selections_iter.next() {
6462 // Avoid duplicating the same lines twice.
6463 let mut rows = selection.spanned_rows(false, &display_map);
6464
6465 while let Some(next_selection) = selections_iter.peek() {
6466 let next_rows = next_selection.spanned_rows(false, &display_map);
6467 if next_rows.start < rows.end {
6468 rows.end = next_rows.end;
6469 selections_iter.next().unwrap();
6470 } else {
6471 break;
6472 }
6473 }
6474
6475 // Copy the text from the selected row region and splice it either at the start
6476 // or end of the region.
6477 let start = Point::new(rows.start.0, 0);
6478 let end = Point::new(
6479 rows.end.previous_row().0,
6480 buffer.line_len(rows.end.previous_row()),
6481 );
6482 let text = buffer
6483 .text_for_range(start..end)
6484 .chain(Some("\n"))
6485 .collect::<String>();
6486 let insert_location = if upwards {
6487 Point::new(rows.end.0, 0)
6488 } else {
6489 start
6490 };
6491 edits.push((insert_location..insert_location, text));
6492 }
6493
6494 self.transact(cx, |this, cx| {
6495 this.buffer.update(cx, |buffer, cx| {
6496 buffer.edit(edits, None, cx);
6497 });
6498
6499 this.request_autoscroll(Autoscroll::fit(), cx);
6500 });
6501 }
6502
6503 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6504 self.duplicate_line(true, cx);
6505 }
6506
6507 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6508 self.duplicate_line(false, cx);
6509 }
6510
6511 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6512 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6513 let buffer = self.buffer.read(cx).snapshot(cx);
6514
6515 let mut edits = Vec::new();
6516 let mut unfold_ranges = Vec::new();
6517 let mut refold_ranges = Vec::new();
6518
6519 let selections = self.selections.all::<Point>(cx);
6520 let mut selections = selections.iter().peekable();
6521 let mut contiguous_row_selections = Vec::new();
6522 let mut new_selections = Vec::new();
6523
6524 while let Some(selection) = selections.next() {
6525 // Find all the selections that span a contiguous row range
6526 let (start_row, end_row) = consume_contiguous_rows(
6527 &mut contiguous_row_selections,
6528 selection,
6529 &display_map,
6530 &mut selections,
6531 );
6532
6533 // Move the text spanned by the row range to be before the line preceding the row range
6534 if start_row.0 > 0 {
6535 let range_to_move = Point::new(
6536 start_row.previous_row().0,
6537 buffer.line_len(start_row.previous_row()),
6538 )
6539 ..Point::new(
6540 end_row.previous_row().0,
6541 buffer.line_len(end_row.previous_row()),
6542 );
6543 let insertion_point = display_map
6544 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6545 .0;
6546
6547 // Don't move lines across excerpts
6548 if buffer
6549 .excerpt_boundaries_in_range((
6550 Bound::Excluded(insertion_point),
6551 Bound::Included(range_to_move.end),
6552 ))
6553 .next()
6554 .is_none()
6555 {
6556 let text = buffer
6557 .text_for_range(range_to_move.clone())
6558 .flat_map(|s| s.chars())
6559 .skip(1)
6560 .chain(['\n'])
6561 .collect::<String>();
6562
6563 edits.push((
6564 buffer.anchor_after(range_to_move.start)
6565 ..buffer.anchor_before(range_to_move.end),
6566 String::new(),
6567 ));
6568 let insertion_anchor = buffer.anchor_after(insertion_point);
6569 edits.push((insertion_anchor..insertion_anchor, text));
6570
6571 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6572
6573 // Move selections up
6574 new_selections.extend(contiguous_row_selections.drain(..).map(
6575 |mut selection| {
6576 selection.start.row -= row_delta;
6577 selection.end.row -= row_delta;
6578 selection
6579 },
6580 ));
6581
6582 // Move folds up
6583 unfold_ranges.push(range_to_move.clone());
6584 for fold in display_map.folds_in_range(
6585 buffer.anchor_before(range_to_move.start)
6586 ..buffer.anchor_after(range_to_move.end),
6587 ) {
6588 let mut start = fold.range.start.to_point(&buffer);
6589 let mut end = fold.range.end.to_point(&buffer);
6590 start.row -= row_delta;
6591 end.row -= row_delta;
6592 refold_ranges.push((start..end, fold.placeholder.clone()));
6593 }
6594 }
6595 }
6596
6597 // If we didn't move line(s), preserve the existing selections
6598 new_selections.append(&mut contiguous_row_selections);
6599 }
6600
6601 self.transact(cx, |this, cx| {
6602 this.unfold_ranges(unfold_ranges, true, true, cx);
6603 this.buffer.update(cx, |buffer, cx| {
6604 for (range, text) in edits {
6605 buffer.edit([(range, text)], None, cx);
6606 }
6607 });
6608 this.fold_ranges(refold_ranges, true, cx);
6609 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6610 s.select(new_selections);
6611 })
6612 });
6613 }
6614
6615 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6616 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6617 let buffer = self.buffer.read(cx).snapshot(cx);
6618
6619 let mut edits = Vec::new();
6620 let mut unfold_ranges = Vec::new();
6621 let mut refold_ranges = Vec::new();
6622
6623 let selections = self.selections.all::<Point>(cx);
6624 let mut selections = selections.iter().peekable();
6625 let mut contiguous_row_selections = Vec::new();
6626 let mut new_selections = Vec::new();
6627
6628 while let Some(selection) = selections.next() {
6629 // Find all the selections that span a contiguous row range
6630 let (start_row, end_row) = consume_contiguous_rows(
6631 &mut contiguous_row_selections,
6632 selection,
6633 &display_map,
6634 &mut selections,
6635 );
6636
6637 // Move the text spanned by the row range to be after the last line of the row range
6638 if end_row.0 <= buffer.max_point().row {
6639 let range_to_move =
6640 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6641 let insertion_point = display_map
6642 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6643 .0;
6644
6645 // Don't move lines across excerpt boundaries
6646 if buffer
6647 .excerpt_boundaries_in_range((
6648 Bound::Excluded(range_to_move.start),
6649 Bound::Included(insertion_point),
6650 ))
6651 .next()
6652 .is_none()
6653 {
6654 let mut text = String::from("\n");
6655 text.extend(buffer.text_for_range(range_to_move.clone()));
6656 text.pop(); // Drop trailing newline
6657 edits.push((
6658 buffer.anchor_after(range_to_move.start)
6659 ..buffer.anchor_before(range_to_move.end),
6660 String::new(),
6661 ));
6662 let insertion_anchor = buffer.anchor_after(insertion_point);
6663 edits.push((insertion_anchor..insertion_anchor, text));
6664
6665 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6666
6667 // Move selections down
6668 new_selections.extend(contiguous_row_selections.drain(..).map(
6669 |mut selection| {
6670 selection.start.row += row_delta;
6671 selection.end.row += row_delta;
6672 selection
6673 },
6674 ));
6675
6676 // Move folds down
6677 unfold_ranges.push(range_to_move.clone());
6678 for fold in display_map.folds_in_range(
6679 buffer.anchor_before(range_to_move.start)
6680 ..buffer.anchor_after(range_to_move.end),
6681 ) {
6682 let mut start = fold.range.start.to_point(&buffer);
6683 let mut end = fold.range.end.to_point(&buffer);
6684 start.row += row_delta;
6685 end.row += row_delta;
6686 refold_ranges.push((start..end, fold.placeholder.clone()));
6687 }
6688 }
6689 }
6690
6691 // If we didn't move line(s), preserve the existing selections
6692 new_selections.append(&mut contiguous_row_selections);
6693 }
6694
6695 self.transact(cx, |this, cx| {
6696 this.unfold_ranges(unfold_ranges, true, true, cx);
6697 this.buffer.update(cx, |buffer, cx| {
6698 for (range, text) in edits {
6699 buffer.edit([(range, text)], None, cx);
6700 }
6701 });
6702 this.fold_ranges(refold_ranges, true, cx);
6703 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6704 });
6705 }
6706
6707 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6708 let text_layout_details = &self.text_layout_details(cx);
6709 self.transact(cx, |this, cx| {
6710 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6711 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6712 let line_mode = s.line_mode;
6713 s.move_with(|display_map, selection| {
6714 if !selection.is_empty() || line_mode {
6715 return;
6716 }
6717
6718 let mut head = selection.head();
6719 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6720 if head.column() == display_map.line_len(head.row()) {
6721 transpose_offset = display_map
6722 .buffer_snapshot
6723 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6724 }
6725
6726 if transpose_offset == 0 {
6727 return;
6728 }
6729
6730 *head.column_mut() += 1;
6731 head = display_map.clip_point(head, Bias::Right);
6732 let goal = SelectionGoal::HorizontalPosition(
6733 display_map
6734 .x_for_display_point(head, text_layout_details)
6735 .into(),
6736 );
6737 selection.collapse_to(head, goal);
6738
6739 let transpose_start = display_map
6740 .buffer_snapshot
6741 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6742 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6743 let transpose_end = display_map
6744 .buffer_snapshot
6745 .clip_offset(transpose_offset + 1, Bias::Right);
6746 if let Some(ch) =
6747 display_map.buffer_snapshot.chars_at(transpose_start).next()
6748 {
6749 edits.push((transpose_start..transpose_offset, String::new()));
6750 edits.push((transpose_end..transpose_end, ch.to_string()));
6751 }
6752 }
6753 });
6754 edits
6755 });
6756 this.buffer
6757 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6758 let selections = this.selections.all::<usize>(cx);
6759 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6760 s.select(selections);
6761 });
6762 });
6763 }
6764
6765 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6766 self.rewrap_impl(true, cx)
6767 }
6768
6769 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6770 let buffer = self.buffer.read(cx).snapshot(cx);
6771 let selections = self.selections.all::<Point>(cx);
6772 let mut selections = selections.iter().peekable();
6773
6774 let mut edits = Vec::new();
6775 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6776
6777 while let Some(selection) = selections.next() {
6778 let mut start_row = selection.start.row;
6779 let mut end_row = selection.end.row;
6780
6781 // Skip selections that overlap with a range that has already been rewrapped.
6782 let selection_range = start_row..end_row;
6783 if rewrapped_row_ranges
6784 .iter()
6785 .any(|range| range.overlaps(&selection_range))
6786 {
6787 continue;
6788 }
6789
6790 let mut should_rewrap = !only_text;
6791
6792 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6793 match language_scope.language_name().0.as_ref() {
6794 "Markdown" | "Plain Text" => {
6795 should_rewrap = true;
6796 }
6797 _ => {}
6798 }
6799 }
6800
6801 // Since not all lines in the selection may be at the same indent
6802 // level, choose the indent size that is the most common between all
6803 // of the lines.
6804 //
6805 // If there is a tie, we use the deepest indent.
6806 let (indent_size, indent_end) = {
6807 let mut indent_size_occurrences = HashMap::default();
6808 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6809
6810 for row in start_row..=end_row {
6811 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6812 rows_by_indent_size.entry(indent).or_default().push(row);
6813 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6814 }
6815
6816 let indent_size = indent_size_occurrences
6817 .into_iter()
6818 .max_by_key(|(indent, count)| (*count, indent.len))
6819 .map(|(indent, _)| indent)
6820 .unwrap_or_default();
6821 let row = rows_by_indent_size[&indent_size][0];
6822 let indent_end = Point::new(row, indent_size.len);
6823
6824 (indent_size, indent_end)
6825 };
6826
6827 let mut line_prefix = indent_size.chars().collect::<String>();
6828
6829 if let Some(comment_prefix) =
6830 buffer
6831 .language_scope_at(selection.head())
6832 .and_then(|language| {
6833 language
6834 .line_comment_prefixes()
6835 .iter()
6836 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6837 .cloned()
6838 })
6839 {
6840 line_prefix.push_str(&comment_prefix);
6841 should_rewrap = true;
6842 }
6843
6844 if selection.is_empty() {
6845 'expand_upwards: while start_row > 0 {
6846 let prev_row = start_row - 1;
6847 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6848 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6849 {
6850 start_row = prev_row;
6851 } else {
6852 break 'expand_upwards;
6853 }
6854 }
6855
6856 'expand_downwards: while end_row < buffer.max_point().row {
6857 let next_row = end_row + 1;
6858 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6859 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6860 {
6861 end_row = next_row;
6862 } else {
6863 break 'expand_downwards;
6864 }
6865 }
6866 }
6867
6868 if !should_rewrap {
6869 continue;
6870 }
6871
6872 let start = Point::new(start_row, 0);
6873 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6874 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6875 let Some(lines_without_prefixes) = selection_text
6876 .lines()
6877 .map(|line| {
6878 line.strip_prefix(&line_prefix)
6879 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6880 .ok_or_else(|| {
6881 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6882 })
6883 })
6884 .collect::<Result<Vec<_>, _>>()
6885 .log_err()
6886 else {
6887 continue;
6888 };
6889
6890 let unwrapped_text = lines_without_prefixes.join(" ");
6891 let wrap_column = buffer
6892 .settings_at(Point::new(start_row, 0), cx)
6893 .preferred_line_length as usize;
6894 let mut wrapped_text = String::new();
6895 let mut current_line = line_prefix.clone();
6896 for word in unwrapped_text.split_whitespace() {
6897 if current_line.len() + word.len() >= wrap_column {
6898 wrapped_text.push_str(¤t_line);
6899 wrapped_text.push('\n');
6900 current_line.truncate(line_prefix.len());
6901 }
6902
6903 if current_line.len() > line_prefix.len() {
6904 current_line.push(' ');
6905 }
6906
6907 current_line.push_str(word);
6908 }
6909
6910 if !current_line.is_empty() {
6911 wrapped_text.push_str(¤t_line);
6912 }
6913
6914 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6915 let mut offset = start.to_offset(&buffer);
6916 let mut moved_since_edit = true;
6917
6918 for change in diff.iter_all_changes() {
6919 let value = change.value();
6920 match change.tag() {
6921 ChangeTag::Equal => {
6922 offset += value.len();
6923 moved_since_edit = true;
6924 }
6925 ChangeTag::Delete => {
6926 let start = buffer.anchor_after(offset);
6927 let end = buffer.anchor_before(offset + value.len());
6928
6929 if moved_since_edit {
6930 edits.push((start..end, String::new()));
6931 } else {
6932 edits.last_mut().unwrap().0.end = end;
6933 }
6934
6935 offset += value.len();
6936 moved_since_edit = false;
6937 }
6938 ChangeTag::Insert => {
6939 if moved_since_edit {
6940 let anchor = buffer.anchor_after(offset);
6941 edits.push((anchor..anchor, value.to_string()));
6942 } else {
6943 edits.last_mut().unwrap().1.push_str(value);
6944 }
6945
6946 moved_since_edit = false;
6947 }
6948 }
6949 }
6950
6951 rewrapped_row_ranges.push(start_row..=end_row);
6952 }
6953
6954 self.buffer
6955 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6956 }
6957
6958 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6959 let mut text = String::new();
6960 let buffer = self.buffer.read(cx).snapshot(cx);
6961 let mut selections = self.selections.all::<Point>(cx);
6962 let mut clipboard_selections = Vec::with_capacity(selections.len());
6963 {
6964 let max_point = buffer.max_point();
6965 let mut is_first = true;
6966 for selection in &mut selections {
6967 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6968 if is_entire_line {
6969 selection.start = Point::new(selection.start.row, 0);
6970 if !selection.is_empty() && selection.end.column == 0 {
6971 selection.end = cmp::min(max_point, selection.end);
6972 } else {
6973 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6974 }
6975 selection.goal = SelectionGoal::None;
6976 }
6977 if is_first {
6978 is_first = false;
6979 } else {
6980 text += "\n";
6981 }
6982 let mut len = 0;
6983 for chunk in buffer.text_for_range(selection.start..selection.end) {
6984 text.push_str(chunk);
6985 len += chunk.len();
6986 }
6987 clipboard_selections.push(ClipboardSelection {
6988 len,
6989 is_entire_line,
6990 first_line_indent: buffer
6991 .indent_size_for_line(MultiBufferRow(selection.start.row))
6992 .len,
6993 });
6994 }
6995 }
6996
6997 self.transact(cx, |this, cx| {
6998 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6999 s.select(selections);
7000 });
7001 this.insert("", cx);
7002 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7003 text,
7004 clipboard_selections,
7005 ));
7006 });
7007 }
7008
7009 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7010 let selections = self.selections.all::<Point>(cx);
7011 let buffer = self.buffer.read(cx).read(cx);
7012 let mut text = String::new();
7013
7014 let mut clipboard_selections = Vec::with_capacity(selections.len());
7015 {
7016 let max_point = buffer.max_point();
7017 let mut is_first = true;
7018 for selection in selections.iter() {
7019 let mut start = selection.start;
7020 let mut end = selection.end;
7021 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7022 if is_entire_line {
7023 start = Point::new(start.row, 0);
7024 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7025 }
7026 if is_first {
7027 is_first = false;
7028 } else {
7029 text += "\n";
7030 }
7031 let mut len = 0;
7032 for chunk in buffer.text_for_range(start..end) {
7033 text.push_str(chunk);
7034 len += chunk.len();
7035 }
7036 clipboard_selections.push(ClipboardSelection {
7037 len,
7038 is_entire_line,
7039 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7040 });
7041 }
7042 }
7043
7044 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7045 text,
7046 clipboard_selections,
7047 ));
7048 }
7049
7050 pub fn do_paste(
7051 &mut self,
7052 text: &String,
7053 clipboard_selections: Option<Vec<ClipboardSelection>>,
7054 handle_entire_lines: bool,
7055 cx: &mut ViewContext<Self>,
7056 ) {
7057 if self.read_only(cx) {
7058 return;
7059 }
7060
7061 let clipboard_text = Cow::Borrowed(text);
7062
7063 self.transact(cx, |this, cx| {
7064 if let Some(mut clipboard_selections) = clipboard_selections {
7065 let old_selections = this.selections.all::<usize>(cx);
7066 let all_selections_were_entire_line =
7067 clipboard_selections.iter().all(|s| s.is_entire_line);
7068 let first_selection_indent_column =
7069 clipboard_selections.first().map(|s| s.first_line_indent);
7070 if clipboard_selections.len() != old_selections.len() {
7071 clipboard_selections.drain(..);
7072 }
7073
7074 this.buffer.update(cx, |buffer, cx| {
7075 let snapshot = buffer.read(cx);
7076 let mut start_offset = 0;
7077 let mut edits = Vec::new();
7078 let mut original_indent_columns = Vec::new();
7079 for (ix, selection) in old_selections.iter().enumerate() {
7080 let to_insert;
7081 let entire_line;
7082 let original_indent_column;
7083 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7084 let end_offset = start_offset + clipboard_selection.len;
7085 to_insert = &clipboard_text[start_offset..end_offset];
7086 entire_line = clipboard_selection.is_entire_line;
7087 start_offset = end_offset + 1;
7088 original_indent_column = Some(clipboard_selection.first_line_indent);
7089 } else {
7090 to_insert = clipboard_text.as_str();
7091 entire_line = all_selections_were_entire_line;
7092 original_indent_column = first_selection_indent_column
7093 }
7094
7095 // If the corresponding selection was empty when this slice of the
7096 // clipboard text was written, then the entire line containing the
7097 // selection was copied. If this selection is also currently empty,
7098 // then paste the line before the current line of the buffer.
7099 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7100 let column = selection.start.to_point(&snapshot).column as usize;
7101 let line_start = selection.start - column;
7102 line_start..line_start
7103 } else {
7104 selection.range()
7105 };
7106
7107 edits.push((range, to_insert));
7108 original_indent_columns.extend(original_indent_column);
7109 }
7110 drop(snapshot);
7111
7112 buffer.edit(
7113 edits,
7114 Some(AutoindentMode::Block {
7115 original_indent_columns,
7116 }),
7117 cx,
7118 );
7119 });
7120
7121 let selections = this.selections.all::<usize>(cx);
7122 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7123 } else {
7124 this.insert(&clipboard_text, cx);
7125 }
7126 });
7127 }
7128
7129 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7130 if let Some(item) = cx.read_from_clipboard() {
7131 let entries = item.entries();
7132
7133 match entries.first() {
7134 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7135 // of all the pasted entries.
7136 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7137 .do_paste(
7138 clipboard_string.text(),
7139 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7140 true,
7141 cx,
7142 ),
7143 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7144 }
7145 }
7146 }
7147
7148 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7149 if self.read_only(cx) {
7150 return;
7151 }
7152
7153 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7154 if let Some((selections, _)) =
7155 self.selection_history.transaction(transaction_id).cloned()
7156 {
7157 self.change_selections(None, cx, |s| {
7158 s.select_anchors(selections.to_vec());
7159 });
7160 }
7161 self.request_autoscroll(Autoscroll::fit(), cx);
7162 self.unmark_text(cx);
7163 self.refresh_inline_completion(true, false, cx);
7164 cx.emit(EditorEvent::Edited { transaction_id });
7165 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7166 }
7167 }
7168
7169 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7170 if self.read_only(cx) {
7171 return;
7172 }
7173
7174 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7175 if let Some((_, Some(selections))) =
7176 self.selection_history.transaction(transaction_id).cloned()
7177 {
7178 self.change_selections(None, cx, |s| {
7179 s.select_anchors(selections.to_vec());
7180 });
7181 }
7182 self.request_autoscroll(Autoscroll::fit(), cx);
7183 self.unmark_text(cx);
7184 self.refresh_inline_completion(true, false, cx);
7185 cx.emit(EditorEvent::Edited { transaction_id });
7186 }
7187 }
7188
7189 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7190 self.buffer
7191 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7192 }
7193
7194 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7195 self.buffer
7196 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7197 }
7198
7199 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7200 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7201 let line_mode = s.line_mode;
7202 s.move_with(|map, selection| {
7203 let cursor = if selection.is_empty() && !line_mode {
7204 movement::left(map, selection.start)
7205 } else {
7206 selection.start
7207 };
7208 selection.collapse_to(cursor, SelectionGoal::None);
7209 });
7210 })
7211 }
7212
7213 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7214 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7215 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7216 })
7217 }
7218
7219 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7220 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7221 let line_mode = s.line_mode;
7222 s.move_with(|map, selection| {
7223 let cursor = if selection.is_empty() && !line_mode {
7224 movement::right(map, selection.end)
7225 } else {
7226 selection.end
7227 };
7228 selection.collapse_to(cursor, SelectionGoal::None)
7229 });
7230 })
7231 }
7232
7233 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7234 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7235 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7236 })
7237 }
7238
7239 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7240 if self.take_rename(true, cx).is_some() {
7241 return;
7242 }
7243
7244 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7245 cx.propagate();
7246 return;
7247 }
7248
7249 let text_layout_details = &self.text_layout_details(cx);
7250 let selection_count = self.selections.count();
7251 let first_selection = self.selections.first_anchor();
7252
7253 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7254 let line_mode = s.line_mode;
7255 s.move_with(|map, selection| {
7256 if !selection.is_empty() && !line_mode {
7257 selection.goal = SelectionGoal::None;
7258 }
7259 let (cursor, goal) = movement::up(
7260 map,
7261 selection.start,
7262 selection.goal,
7263 false,
7264 text_layout_details,
7265 );
7266 selection.collapse_to(cursor, goal);
7267 });
7268 });
7269
7270 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7271 {
7272 cx.propagate();
7273 }
7274 }
7275
7276 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7277 if self.take_rename(true, cx).is_some() {
7278 return;
7279 }
7280
7281 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7282 cx.propagate();
7283 return;
7284 }
7285
7286 let text_layout_details = &self.text_layout_details(cx);
7287
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 let line_mode = s.line_mode;
7290 s.move_with(|map, selection| {
7291 if !selection.is_empty() && !line_mode {
7292 selection.goal = SelectionGoal::None;
7293 }
7294 let (cursor, goal) = movement::up_by_rows(
7295 map,
7296 selection.start,
7297 action.lines,
7298 selection.goal,
7299 false,
7300 text_layout_details,
7301 );
7302 selection.collapse_to(cursor, goal);
7303 });
7304 })
7305 }
7306
7307 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7308 if self.take_rename(true, cx).is_some() {
7309 return;
7310 }
7311
7312 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7313 cx.propagate();
7314 return;
7315 }
7316
7317 let text_layout_details = &self.text_layout_details(cx);
7318
7319 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7320 let line_mode = s.line_mode;
7321 s.move_with(|map, selection| {
7322 if !selection.is_empty() && !line_mode {
7323 selection.goal = SelectionGoal::None;
7324 }
7325 let (cursor, goal) = movement::down_by_rows(
7326 map,
7327 selection.start,
7328 action.lines,
7329 selection.goal,
7330 false,
7331 text_layout_details,
7332 );
7333 selection.collapse_to(cursor, goal);
7334 });
7335 })
7336 }
7337
7338 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7339 let text_layout_details = &self.text_layout_details(cx);
7340 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7341 s.move_heads_with(|map, head, goal| {
7342 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7343 })
7344 })
7345 }
7346
7347 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7348 let text_layout_details = &self.text_layout_details(cx);
7349 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7350 s.move_heads_with(|map, head, goal| {
7351 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7352 })
7353 })
7354 }
7355
7356 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7357 let Some(row_count) = self.visible_row_count() else {
7358 return;
7359 };
7360
7361 let text_layout_details = &self.text_layout_details(cx);
7362
7363 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7364 s.move_heads_with(|map, head, goal| {
7365 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7366 })
7367 })
7368 }
7369
7370 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7371 if self.take_rename(true, cx).is_some() {
7372 return;
7373 }
7374
7375 if self
7376 .context_menu
7377 .write()
7378 .as_mut()
7379 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7380 .unwrap_or(false)
7381 {
7382 return;
7383 }
7384
7385 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7386 cx.propagate();
7387 return;
7388 }
7389
7390 let Some(row_count) = self.visible_row_count() else {
7391 return;
7392 };
7393
7394 let autoscroll = if action.center_cursor {
7395 Autoscroll::center()
7396 } else {
7397 Autoscroll::fit()
7398 };
7399
7400 let text_layout_details = &self.text_layout_details(cx);
7401
7402 self.change_selections(Some(autoscroll), cx, |s| {
7403 let line_mode = s.line_mode;
7404 s.move_with(|map, selection| {
7405 if !selection.is_empty() && !line_mode {
7406 selection.goal = SelectionGoal::None;
7407 }
7408 let (cursor, goal) = movement::up_by_rows(
7409 map,
7410 selection.end,
7411 row_count,
7412 selection.goal,
7413 false,
7414 text_layout_details,
7415 );
7416 selection.collapse_to(cursor, goal);
7417 });
7418 });
7419 }
7420
7421 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7422 let text_layout_details = &self.text_layout_details(cx);
7423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7424 s.move_heads_with(|map, head, goal| {
7425 movement::up(map, head, goal, false, text_layout_details)
7426 })
7427 })
7428 }
7429
7430 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7431 self.take_rename(true, cx);
7432
7433 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7434 cx.propagate();
7435 return;
7436 }
7437
7438 let text_layout_details = &self.text_layout_details(cx);
7439 let selection_count = self.selections.count();
7440 let first_selection = self.selections.first_anchor();
7441
7442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7443 let line_mode = s.line_mode;
7444 s.move_with(|map, selection| {
7445 if !selection.is_empty() && !line_mode {
7446 selection.goal = SelectionGoal::None;
7447 }
7448 let (cursor, goal) = movement::down(
7449 map,
7450 selection.end,
7451 selection.goal,
7452 false,
7453 text_layout_details,
7454 );
7455 selection.collapse_to(cursor, goal);
7456 });
7457 });
7458
7459 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7460 {
7461 cx.propagate();
7462 }
7463 }
7464
7465 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7466 let Some(row_count) = self.visible_row_count() else {
7467 return;
7468 };
7469
7470 let text_layout_details = &self.text_layout_details(cx);
7471
7472 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7473 s.move_heads_with(|map, head, goal| {
7474 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7475 })
7476 })
7477 }
7478
7479 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7480 if self.take_rename(true, cx).is_some() {
7481 return;
7482 }
7483
7484 if self
7485 .context_menu
7486 .write()
7487 .as_mut()
7488 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7489 .unwrap_or(false)
7490 {
7491 return;
7492 }
7493
7494 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7495 cx.propagate();
7496 return;
7497 }
7498
7499 let Some(row_count) = self.visible_row_count() else {
7500 return;
7501 };
7502
7503 let autoscroll = if action.center_cursor {
7504 Autoscroll::center()
7505 } else {
7506 Autoscroll::fit()
7507 };
7508
7509 let text_layout_details = &self.text_layout_details(cx);
7510 self.change_selections(Some(autoscroll), cx, |s| {
7511 let line_mode = s.line_mode;
7512 s.move_with(|map, selection| {
7513 if !selection.is_empty() && !line_mode {
7514 selection.goal = SelectionGoal::None;
7515 }
7516 let (cursor, goal) = movement::down_by_rows(
7517 map,
7518 selection.end,
7519 row_count,
7520 selection.goal,
7521 false,
7522 text_layout_details,
7523 );
7524 selection.collapse_to(cursor, goal);
7525 });
7526 });
7527 }
7528
7529 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7530 let text_layout_details = &self.text_layout_details(cx);
7531 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7532 s.move_heads_with(|map, head, goal| {
7533 movement::down(map, head, goal, false, text_layout_details)
7534 })
7535 });
7536 }
7537
7538 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7539 if let Some(context_menu) = self.context_menu.write().as_mut() {
7540 context_menu.select_first(self.project.as_ref(), cx);
7541 }
7542 }
7543
7544 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7545 if let Some(context_menu) = self.context_menu.write().as_mut() {
7546 context_menu.select_prev(self.project.as_ref(), cx);
7547 }
7548 }
7549
7550 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7551 if let Some(context_menu) = self.context_menu.write().as_mut() {
7552 context_menu.select_next(self.project.as_ref(), cx);
7553 }
7554 }
7555
7556 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7557 if let Some(context_menu) = self.context_menu.write().as_mut() {
7558 context_menu.select_last(self.project.as_ref(), cx);
7559 }
7560 }
7561
7562 pub fn move_to_previous_word_start(
7563 &mut self,
7564 _: &MoveToPreviousWordStart,
7565 cx: &mut ViewContext<Self>,
7566 ) {
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.move_cursors_with(|map, head, _| {
7569 (
7570 movement::previous_word_start(map, head),
7571 SelectionGoal::None,
7572 )
7573 });
7574 })
7575 }
7576
7577 pub fn move_to_previous_subword_start(
7578 &mut self,
7579 _: &MoveToPreviousSubwordStart,
7580 cx: &mut ViewContext<Self>,
7581 ) {
7582 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7583 s.move_cursors_with(|map, head, _| {
7584 (
7585 movement::previous_subword_start(map, head),
7586 SelectionGoal::None,
7587 )
7588 });
7589 })
7590 }
7591
7592 pub fn select_to_previous_word_start(
7593 &mut self,
7594 _: &SelectToPreviousWordStart,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_heads_with(|map, head, _| {
7599 (
7600 movement::previous_word_start(map, head),
7601 SelectionGoal::None,
7602 )
7603 });
7604 })
7605 }
7606
7607 pub fn select_to_previous_subword_start(
7608 &mut self,
7609 _: &SelectToPreviousSubwordStart,
7610 cx: &mut ViewContext<Self>,
7611 ) {
7612 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7613 s.move_heads_with(|map, head, _| {
7614 (
7615 movement::previous_subword_start(map, head),
7616 SelectionGoal::None,
7617 )
7618 });
7619 })
7620 }
7621
7622 pub fn delete_to_previous_word_start(
7623 &mut self,
7624 action: &DeleteToPreviousWordStart,
7625 cx: &mut ViewContext<Self>,
7626 ) {
7627 self.transact(cx, |this, cx| {
7628 this.select_autoclose_pair(cx);
7629 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 let line_mode = s.line_mode;
7631 s.move_with(|map, selection| {
7632 if selection.is_empty() && !line_mode {
7633 let cursor = if action.ignore_newlines {
7634 movement::previous_word_start(map, selection.head())
7635 } else {
7636 movement::previous_word_start_or_newline(map, selection.head())
7637 };
7638 selection.set_head(cursor, SelectionGoal::None);
7639 }
7640 });
7641 });
7642 this.insert("", cx);
7643 });
7644 }
7645
7646 pub fn delete_to_previous_subword_start(
7647 &mut self,
7648 _: &DeleteToPreviousSubwordStart,
7649 cx: &mut ViewContext<Self>,
7650 ) {
7651 self.transact(cx, |this, cx| {
7652 this.select_autoclose_pair(cx);
7653 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 let line_mode = s.line_mode;
7655 s.move_with(|map, selection| {
7656 if selection.is_empty() && !line_mode {
7657 let cursor = movement::previous_subword_start(map, selection.head());
7658 selection.set_head(cursor, SelectionGoal::None);
7659 }
7660 });
7661 });
7662 this.insert("", cx);
7663 });
7664 }
7665
7666 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7668 s.move_cursors_with(|map, head, _| {
7669 (movement::next_word_end(map, head), SelectionGoal::None)
7670 });
7671 })
7672 }
7673
7674 pub fn move_to_next_subword_end(
7675 &mut self,
7676 _: &MoveToNextSubwordEnd,
7677 cx: &mut ViewContext<Self>,
7678 ) {
7679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7680 s.move_cursors_with(|map, head, _| {
7681 (movement::next_subword_end(map, head), SelectionGoal::None)
7682 });
7683 })
7684 }
7685
7686 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7687 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7688 s.move_heads_with(|map, head, _| {
7689 (movement::next_word_end(map, head), SelectionGoal::None)
7690 });
7691 })
7692 }
7693
7694 pub fn select_to_next_subword_end(
7695 &mut self,
7696 _: &SelectToNextSubwordEnd,
7697 cx: &mut ViewContext<Self>,
7698 ) {
7699 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7700 s.move_heads_with(|map, head, _| {
7701 (movement::next_subword_end(map, head), SelectionGoal::None)
7702 });
7703 })
7704 }
7705
7706 pub fn delete_to_next_word_end(
7707 &mut self,
7708 action: &DeleteToNextWordEnd,
7709 cx: &mut ViewContext<Self>,
7710 ) {
7711 self.transact(cx, |this, cx| {
7712 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7713 let line_mode = s.line_mode;
7714 s.move_with(|map, selection| {
7715 if selection.is_empty() && !line_mode {
7716 let cursor = if action.ignore_newlines {
7717 movement::next_word_end(map, selection.head())
7718 } else {
7719 movement::next_word_end_or_newline(map, selection.head())
7720 };
7721 selection.set_head(cursor, SelectionGoal::None);
7722 }
7723 });
7724 });
7725 this.insert("", cx);
7726 });
7727 }
7728
7729 pub fn delete_to_next_subword_end(
7730 &mut self,
7731 _: &DeleteToNextSubwordEnd,
7732 cx: &mut ViewContext<Self>,
7733 ) {
7734 self.transact(cx, |this, cx| {
7735 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7736 s.move_with(|map, selection| {
7737 if selection.is_empty() {
7738 let cursor = movement::next_subword_end(map, selection.head());
7739 selection.set_head(cursor, SelectionGoal::None);
7740 }
7741 });
7742 });
7743 this.insert("", cx);
7744 });
7745 }
7746
7747 pub fn move_to_beginning_of_line(
7748 &mut self,
7749 action: &MoveToBeginningOfLine,
7750 cx: &mut ViewContext<Self>,
7751 ) {
7752 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7753 s.move_cursors_with(|map, head, _| {
7754 (
7755 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7756 SelectionGoal::None,
7757 )
7758 });
7759 })
7760 }
7761
7762 pub fn select_to_beginning_of_line(
7763 &mut self,
7764 action: &SelectToBeginningOfLine,
7765 cx: &mut ViewContext<Self>,
7766 ) {
7767 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7768 s.move_heads_with(|map, head, _| {
7769 (
7770 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7771 SelectionGoal::None,
7772 )
7773 });
7774 });
7775 }
7776
7777 pub fn delete_to_beginning_of_line(
7778 &mut self,
7779 _: &DeleteToBeginningOfLine,
7780 cx: &mut ViewContext<Self>,
7781 ) {
7782 self.transact(cx, |this, cx| {
7783 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7784 s.move_with(|_, selection| {
7785 selection.reversed = true;
7786 });
7787 });
7788
7789 this.select_to_beginning_of_line(
7790 &SelectToBeginningOfLine {
7791 stop_at_soft_wraps: false,
7792 },
7793 cx,
7794 );
7795 this.backspace(&Backspace, cx);
7796 });
7797 }
7798
7799 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7800 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7801 s.move_cursors_with(|map, head, _| {
7802 (
7803 movement::line_end(map, head, action.stop_at_soft_wraps),
7804 SelectionGoal::None,
7805 )
7806 });
7807 })
7808 }
7809
7810 pub fn select_to_end_of_line(
7811 &mut self,
7812 action: &SelectToEndOfLine,
7813 cx: &mut ViewContext<Self>,
7814 ) {
7815 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7816 s.move_heads_with(|map, head, _| {
7817 (
7818 movement::line_end(map, head, action.stop_at_soft_wraps),
7819 SelectionGoal::None,
7820 )
7821 });
7822 })
7823 }
7824
7825 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7826 self.transact(cx, |this, cx| {
7827 this.select_to_end_of_line(
7828 &SelectToEndOfLine {
7829 stop_at_soft_wraps: false,
7830 },
7831 cx,
7832 );
7833 this.delete(&Delete, cx);
7834 });
7835 }
7836
7837 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7838 self.transact(cx, |this, cx| {
7839 this.select_to_end_of_line(
7840 &SelectToEndOfLine {
7841 stop_at_soft_wraps: false,
7842 },
7843 cx,
7844 );
7845 this.cut(&Cut, cx);
7846 });
7847 }
7848
7849 pub fn move_to_start_of_paragraph(
7850 &mut self,
7851 _: &MoveToStartOfParagraph,
7852 cx: &mut ViewContext<Self>,
7853 ) {
7854 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7855 cx.propagate();
7856 return;
7857 }
7858
7859 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7860 s.move_with(|map, selection| {
7861 selection.collapse_to(
7862 movement::start_of_paragraph(map, selection.head(), 1),
7863 SelectionGoal::None,
7864 )
7865 });
7866 })
7867 }
7868
7869 pub fn move_to_end_of_paragraph(
7870 &mut self,
7871 _: &MoveToEndOfParagraph,
7872 cx: &mut ViewContext<Self>,
7873 ) {
7874 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7875 cx.propagate();
7876 return;
7877 }
7878
7879 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7880 s.move_with(|map, selection| {
7881 selection.collapse_to(
7882 movement::end_of_paragraph(map, selection.head(), 1),
7883 SelectionGoal::None,
7884 )
7885 });
7886 })
7887 }
7888
7889 pub fn select_to_start_of_paragraph(
7890 &mut self,
7891 _: &SelectToStartOfParagraph,
7892 cx: &mut ViewContext<Self>,
7893 ) {
7894 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7895 cx.propagate();
7896 return;
7897 }
7898
7899 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7900 s.move_heads_with(|map, head, _| {
7901 (
7902 movement::start_of_paragraph(map, head, 1),
7903 SelectionGoal::None,
7904 )
7905 });
7906 })
7907 }
7908
7909 pub fn select_to_end_of_paragraph(
7910 &mut self,
7911 _: &SelectToEndOfParagraph,
7912 cx: &mut ViewContext<Self>,
7913 ) {
7914 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7915 cx.propagate();
7916 return;
7917 }
7918
7919 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7920 s.move_heads_with(|map, head, _| {
7921 (
7922 movement::end_of_paragraph(map, head, 1),
7923 SelectionGoal::None,
7924 )
7925 });
7926 })
7927 }
7928
7929 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7930 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7931 cx.propagate();
7932 return;
7933 }
7934
7935 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7936 s.select_ranges(vec![0..0]);
7937 });
7938 }
7939
7940 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7941 let mut selection = self.selections.last::<Point>(cx);
7942 selection.set_head(Point::zero(), SelectionGoal::None);
7943
7944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7945 s.select(vec![selection]);
7946 });
7947 }
7948
7949 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7950 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7951 cx.propagate();
7952 return;
7953 }
7954
7955 let cursor = self.buffer.read(cx).read(cx).len();
7956 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7957 s.select_ranges(vec![cursor..cursor])
7958 });
7959 }
7960
7961 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7962 self.nav_history = nav_history;
7963 }
7964
7965 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7966 self.nav_history.as_ref()
7967 }
7968
7969 fn push_to_nav_history(
7970 &mut self,
7971 cursor_anchor: Anchor,
7972 new_position: Option<Point>,
7973 cx: &mut ViewContext<Self>,
7974 ) {
7975 if let Some(nav_history) = self.nav_history.as_mut() {
7976 let buffer = self.buffer.read(cx).read(cx);
7977 let cursor_position = cursor_anchor.to_point(&buffer);
7978 let scroll_state = self.scroll_manager.anchor();
7979 let scroll_top_row = scroll_state.top_row(&buffer);
7980 drop(buffer);
7981
7982 if let Some(new_position) = new_position {
7983 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7984 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7985 return;
7986 }
7987 }
7988
7989 nav_history.push(
7990 Some(NavigationData {
7991 cursor_anchor,
7992 cursor_position,
7993 scroll_anchor: scroll_state,
7994 scroll_top_row,
7995 }),
7996 cx,
7997 );
7998 }
7999 }
8000
8001 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8002 let buffer = self.buffer.read(cx).snapshot(cx);
8003 let mut selection = self.selections.first::<usize>(cx);
8004 selection.set_head(buffer.len(), SelectionGoal::None);
8005 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8006 s.select(vec![selection]);
8007 });
8008 }
8009
8010 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8011 let end = self.buffer.read(cx).read(cx).len();
8012 self.change_selections(None, cx, |s| {
8013 s.select_ranges(vec![0..end]);
8014 });
8015 }
8016
8017 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8018 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8019 let mut selections = self.selections.all::<Point>(cx);
8020 let max_point = display_map.buffer_snapshot.max_point();
8021 for selection in &mut selections {
8022 let rows = selection.spanned_rows(true, &display_map);
8023 selection.start = Point::new(rows.start.0, 0);
8024 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8025 selection.reversed = false;
8026 }
8027 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8028 s.select(selections);
8029 });
8030 }
8031
8032 pub fn split_selection_into_lines(
8033 &mut self,
8034 _: &SplitSelectionIntoLines,
8035 cx: &mut ViewContext<Self>,
8036 ) {
8037 let mut to_unfold = Vec::new();
8038 let mut new_selection_ranges = Vec::new();
8039 {
8040 let selections = self.selections.all::<Point>(cx);
8041 let buffer = self.buffer.read(cx).read(cx);
8042 for selection in selections {
8043 for row in selection.start.row..selection.end.row {
8044 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8045 new_selection_ranges.push(cursor..cursor);
8046 }
8047 new_selection_ranges.push(selection.end..selection.end);
8048 to_unfold.push(selection.start..selection.end);
8049 }
8050 }
8051 self.unfold_ranges(to_unfold, true, true, cx);
8052 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8053 s.select_ranges(new_selection_ranges);
8054 });
8055 }
8056
8057 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8058 self.add_selection(true, cx);
8059 }
8060
8061 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8062 self.add_selection(false, cx);
8063 }
8064
8065 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8066 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8067 let mut selections = self.selections.all::<Point>(cx);
8068 let text_layout_details = self.text_layout_details(cx);
8069 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8070 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8071 let range = oldest_selection.display_range(&display_map).sorted();
8072
8073 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8074 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8075 let positions = start_x.min(end_x)..start_x.max(end_x);
8076
8077 selections.clear();
8078 let mut stack = Vec::new();
8079 for row in range.start.row().0..=range.end.row().0 {
8080 if let Some(selection) = self.selections.build_columnar_selection(
8081 &display_map,
8082 DisplayRow(row),
8083 &positions,
8084 oldest_selection.reversed,
8085 &text_layout_details,
8086 ) {
8087 stack.push(selection.id);
8088 selections.push(selection);
8089 }
8090 }
8091
8092 if above {
8093 stack.reverse();
8094 }
8095
8096 AddSelectionsState { above, stack }
8097 });
8098
8099 let last_added_selection = *state.stack.last().unwrap();
8100 let mut new_selections = Vec::new();
8101 if above == state.above {
8102 let end_row = if above {
8103 DisplayRow(0)
8104 } else {
8105 display_map.max_point().row()
8106 };
8107
8108 'outer: for selection in selections {
8109 if selection.id == last_added_selection {
8110 let range = selection.display_range(&display_map).sorted();
8111 debug_assert_eq!(range.start.row(), range.end.row());
8112 let mut row = range.start.row();
8113 let positions =
8114 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8115 px(start)..px(end)
8116 } else {
8117 let start_x =
8118 display_map.x_for_display_point(range.start, &text_layout_details);
8119 let end_x =
8120 display_map.x_for_display_point(range.end, &text_layout_details);
8121 start_x.min(end_x)..start_x.max(end_x)
8122 };
8123
8124 while row != end_row {
8125 if above {
8126 row.0 -= 1;
8127 } else {
8128 row.0 += 1;
8129 }
8130
8131 if let Some(new_selection) = self.selections.build_columnar_selection(
8132 &display_map,
8133 row,
8134 &positions,
8135 selection.reversed,
8136 &text_layout_details,
8137 ) {
8138 state.stack.push(new_selection.id);
8139 if above {
8140 new_selections.push(new_selection);
8141 new_selections.push(selection);
8142 } else {
8143 new_selections.push(selection);
8144 new_selections.push(new_selection);
8145 }
8146
8147 continue 'outer;
8148 }
8149 }
8150 }
8151
8152 new_selections.push(selection);
8153 }
8154 } else {
8155 new_selections = selections;
8156 new_selections.retain(|s| s.id != last_added_selection);
8157 state.stack.pop();
8158 }
8159
8160 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8161 s.select(new_selections);
8162 });
8163 if state.stack.len() > 1 {
8164 self.add_selections_state = Some(state);
8165 }
8166 }
8167
8168 pub fn select_next_match_internal(
8169 &mut self,
8170 display_map: &DisplaySnapshot,
8171 replace_newest: bool,
8172 autoscroll: Option<Autoscroll>,
8173 cx: &mut ViewContext<Self>,
8174 ) -> Result<()> {
8175 fn select_next_match_ranges(
8176 this: &mut Editor,
8177 range: Range<usize>,
8178 replace_newest: bool,
8179 auto_scroll: Option<Autoscroll>,
8180 cx: &mut ViewContext<Editor>,
8181 ) {
8182 this.unfold_ranges([range.clone()], false, true, cx);
8183 this.change_selections(auto_scroll, cx, |s| {
8184 if replace_newest {
8185 s.delete(s.newest_anchor().id);
8186 }
8187 s.insert_range(range.clone());
8188 });
8189 }
8190
8191 let buffer = &display_map.buffer_snapshot;
8192 let mut selections = self.selections.all::<usize>(cx);
8193 if let Some(mut select_next_state) = self.select_next_state.take() {
8194 let query = &select_next_state.query;
8195 if !select_next_state.done {
8196 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8197 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8198 let mut next_selected_range = None;
8199
8200 let bytes_after_last_selection =
8201 buffer.bytes_in_range(last_selection.end..buffer.len());
8202 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8203 let query_matches = query
8204 .stream_find_iter(bytes_after_last_selection)
8205 .map(|result| (last_selection.end, result))
8206 .chain(
8207 query
8208 .stream_find_iter(bytes_before_first_selection)
8209 .map(|result| (0, result)),
8210 );
8211
8212 for (start_offset, query_match) in query_matches {
8213 let query_match = query_match.unwrap(); // can only fail due to I/O
8214 let offset_range =
8215 start_offset + query_match.start()..start_offset + query_match.end();
8216 let display_range = offset_range.start.to_display_point(display_map)
8217 ..offset_range.end.to_display_point(display_map);
8218
8219 if !select_next_state.wordwise
8220 || (!movement::is_inside_word(display_map, display_range.start)
8221 && !movement::is_inside_word(display_map, display_range.end))
8222 {
8223 // TODO: This is n^2, because we might check all the selections
8224 if !selections
8225 .iter()
8226 .any(|selection| selection.range().overlaps(&offset_range))
8227 {
8228 next_selected_range = Some(offset_range);
8229 break;
8230 }
8231 }
8232 }
8233
8234 if let Some(next_selected_range) = next_selected_range {
8235 select_next_match_ranges(
8236 self,
8237 next_selected_range,
8238 replace_newest,
8239 autoscroll,
8240 cx,
8241 );
8242 } else {
8243 select_next_state.done = true;
8244 }
8245 }
8246
8247 self.select_next_state = Some(select_next_state);
8248 } else {
8249 let mut only_carets = true;
8250 let mut same_text_selected = true;
8251 let mut selected_text = None;
8252
8253 let mut selections_iter = selections.iter().peekable();
8254 while let Some(selection) = selections_iter.next() {
8255 if selection.start != selection.end {
8256 only_carets = false;
8257 }
8258
8259 if same_text_selected {
8260 if selected_text.is_none() {
8261 selected_text =
8262 Some(buffer.text_for_range(selection.range()).collect::<String>());
8263 }
8264
8265 if let Some(next_selection) = selections_iter.peek() {
8266 if next_selection.range().len() == selection.range().len() {
8267 let next_selected_text = buffer
8268 .text_for_range(next_selection.range())
8269 .collect::<String>();
8270 if Some(next_selected_text) != selected_text {
8271 same_text_selected = false;
8272 selected_text = None;
8273 }
8274 } else {
8275 same_text_selected = false;
8276 selected_text = None;
8277 }
8278 }
8279 }
8280 }
8281
8282 if only_carets {
8283 for selection in &mut selections {
8284 let word_range = movement::surrounding_word(
8285 display_map,
8286 selection.start.to_display_point(display_map),
8287 );
8288 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8289 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8290 selection.goal = SelectionGoal::None;
8291 selection.reversed = false;
8292 select_next_match_ranges(
8293 self,
8294 selection.start..selection.end,
8295 replace_newest,
8296 autoscroll,
8297 cx,
8298 );
8299 }
8300
8301 if selections.len() == 1 {
8302 let selection = selections
8303 .last()
8304 .expect("ensured that there's only one selection");
8305 let query = buffer
8306 .text_for_range(selection.start..selection.end)
8307 .collect::<String>();
8308 let is_empty = query.is_empty();
8309 let select_state = SelectNextState {
8310 query: AhoCorasick::new(&[query])?,
8311 wordwise: true,
8312 done: is_empty,
8313 };
8314 self.select_next_state = Some(select_state);
8315 } else {
8316 self.select_next_state = None;
8317 }
8318 } else if let Some(selected_text) = selected_text {
8319 self.select_next_state = Some(SelectNextState {
8320 query: AhoCorasick::new(&[selected_text])?,
8321 wordwise: false,
8322 done: false,
8323 });
8324 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8325 }
8326 }
8327 Ok(())
8328 }
8329
8330 pub fn select_all_matches(
8331 &mut self,
8332 _action: &SelectAllMatches,
8333 cx: &mut ViewContext<Self>,
8334 ) -> Result<()> {
8335 self.push_to_selection_history();
8336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8337
8338 self.select_next_match_internal(&display_map, false, None, cx)?;
8339 let Some(select_next_state) = self.select_next_state.as_mut() else {
8340 return Ok(());
8341 };
8342 if select_next_state.done {
8343 return Ok(());
8344 }
8345
8346 let mut new_selections = self.selections.all::<usize>(cx);
8347
8348 let buffer = &display_map.buffer_snapshot;
8349 let query_matches = select_next_state
8350 .query
8351 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8352
8353 for query_match in query_matches {
8354 let query_match = query_match.unwrap(); // can only fail due to I/O
8355 let offset_range = query_match.start()..query_match.end();
8356 let display_range = offset_range.start.to_display_point(&display_map)
8357 ..offset_range.end.to_display_point(&display_map);
8358
8359 if !select_next_state.wordwise
8360 || (!movement::is_inside_word(&display_map, display_range.start)
8361 && !movement::is_inside_word(&display_map, display_range.end))
8362 {
8363 self.selections.change_with(cx, |selections| {
8364 new_selections.push(Selection {
8365 id: selections.new_selection_id(),
8366 start: offset_range.start,
8367 end: offset_range.end,
8368 reversed: false,
8369 goal: SelectionGoal::None,
8370 });
8371 });
8372 }
8373 }
8374
8375 new_selections.sort_by_key(|selection| selection.start);
8376 let mut ix = 0;
8377 while ix + 1 < new_selections.len() {
8378 let current_selection = &new_selections[ix];
8379 let next_selection = &new_selections[ix + 1];
8380 if current_selection.range().overlaps(&next_selection.range()) {
8381 if current_selection.id < next_selection.id {
8382 new_selections.remove(ix + 1);
8383 } else {
8384 new_selections.remove(ix);
8385 }
8386 } else {
8387 ix += 1;
8388 }
8389 }
8390
8391 select_next_state.done = true;
8392 self.unfold_ranges(
8393 new_selections.iter().map(|selection| selection.range()),
8394 false,
8395 false,
8396 cx,
8397 );
8398 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8399 selections.select(new_selections)
8400 });
8401
8402 Ok(())
8403 }
8404
8405 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8406 self.push_to_selection_history();
8407 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8408 self.select_next_match_internal(
8409 &display_map,
8410 action.replace_newest,
8411 Some(Autoscroll::newest()),
8412 cx,
8413 )?;
8414 Ok(())
8415 }
8416
8417 pub fn select_previous(
8418 &mut self,
8419 action: &SelectPrevious,
8420 cx: &mut ViewContext<Self>,
8421 ) -> Result<()> {
8422 self.push_to_selection_history();
8423 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8424 let buffer = &display_map.buffer_snapshot;
8425 let mut selections = self.selections.all::<usize>(cx);
8426 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8427 let query = &select_prev_state.query;
8428 if !select_prev_state.done {
8429 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8430 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8431 let mut next_selected_range = None;
8432 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8433 let bytes_before_last_selection =
8434 buffer.reversed_bytes_in_range(0..last_selection.start);
8435 let bytes_after_first_selection =
8436 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8437 let query_matches = query
8438 .stream_find_iter(bytes_before_last_selection)
8439 .map(|result| (last_selection.start, result))
8440 .chain(
8441 query
8442 .stream_find_iter(bytes_after_first_selection)
8443 .map(|result| (buffer.len(), result)),
8444 );
8445 for (end_offset, query_match) in query_matches {
8446 let query_match = query_match.unwrap(); // can only fail due to I/O
8447 let offset_range =
8448 end_offset - query_match.end()..end_offset - query_match.start();
8449 let display_range = offset_range.start.to_display_point(&display_map)
8450 ..offset_range.end.to_display_point(&display_map);
8451
8452 if !select_prev_state.wordwise
8453 || (!movement::is_inside_word(&display_map, display_range.start)
8454 && !movement::is_inside_word(&display_map, display_range.end))
8455 {
8456 next_selected_range = Some(offset_range);
8457 break;
8458 }
8459 }
8460
8461 if let Some(next_selected_range) = next_selected_range {
8462 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8463 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8464 if action.replace_newest {
8465 s.delete(s.newest_anchor().id);
8466 }
8467 s.insert_range(next_selected_range);
8468 });
8469 } else {
8470 select_prev_state.done = true;
8471 }
8472 }
8473
8474 self.select_prev_state = Some(select_prev_state);
8475 } else {
8476 let mut only_carets = true;
8477 let mut same_text_selected = true;
8478 let mut selected_text = None;
8479
8480 let mut selections_iter = selections.iter().peekable();
8481 while let Some(selection) = selections_iter.next() {
8482 if selection.start != selection.end {
8483 only_carets = false;
8484 }
8485
8486 if same_text_selected {
8487 if selected_text.is_none() {
8488 selected_text =
8489 Some(buffer.text_for_range(selection.range()).collect::<String>());
8490 }
8491
8492 if let Some(next_selection) = selections_iter.peek() {
8493 if next_selection.range().len() == selection.range().len() {
8494 let next_selected_text = buffer
8495 .text_for_range(next_selection.range())
8496 .collect::<String>();
8497 if Some(next_selected_text) != selected_text {
8498 same_text_selected = false;
8499 selected_text = None;
8500 }
8501 } else {
8502 same_text_selected = false;
8503 selected_text = None;
8504 }
8505 }
8506 }
8507 }
8508
8509 if only_carets {
8510 for selection in &mut selections {
8511 let word_range = movement::surrounding_word(
8512 &display_map,
8513 selection.start.to_display_point(&display_map),
8514 );
8515 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8516 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8517 selection.goal = SelectionGoal::None;
8518 selection.reversed = false;
8519 }
8520 if selections.len() == 1 {
8521 let selection = selections
8522 .last()
8523 .expect("ensured that there's only one selection");
8524 let query = buffer
8525 .text_for_range(selection.start..selection.end)
8526 .collect::<String>();
8527 let is_empty = query.is_empty();
8528 let select_state = SelectNextState {
8529 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8530 wordwise: true,
8531 done: is_empty,
8532 };
8533 self.select_prev_state = Some(select_state);
8534 } else {
8535 self.select_prev_state = None;
8536 }
8537
8538 self.unfold_ranges(
8539 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8540 false,
8541 true,
8542 cx,
8543 );
8544 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8545 s.select(selections);
8546 });
8547 } else if let Some(selected_text) = selected_text {
8548 self.select_prev_state = Some(SelectNextState {
8549 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8550 wordwise: false,
8551 done: false,
8552 });
8553 self.select_previous(action, cx)?;
8554 }
8555 }
8556 Ok(())
8557 }
8558
8559 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8560 let text_layout_details = &self.text_layout_details(cx);
8561 self.transact(cx, |this, cx| {
8562 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8563 let mut edits = Vec::new();
8564 let mut selection_edit_ranges = Vec::new();
8565 let mut last_toggled_row = None;
8566 let snapshot = this.buffer.read(cx).read(cx);
8567 let empty_str: Arc<str> = Arc::default();
8568 let mut suffixes_inserted = Vec::new();
8569
8570 fn comment_prefix_range(
8571 snapshot: &MultiBufferSnapshot,
8572 row: MultiBufferRow,
8573 comment_prefix: &str,
8574 comment_prefix_whitespace: &str,
8575 ) -> Range<Point> {
8576 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8577
8578 let mut line_bytes = snapshot
8579 .bytes_in_range(start..snapshot.max_point())
8580 .flatten()
8581 .copied();
8582
8583 // If this line currently begins with the line comment prefix, then record
8584 // the range containing the prefix.
8585 if line_bytes
8586 .by_ref()
8587 .take(comment_prefix.len())
8588 .eq(comment_prefix.bytes())
8589 {
8590 // Include any whitespace that matches the comment prefix.
8591 let matching_whitespace_len = line_bytes
8592 .zip(comment_prefix_whitespace.bytes())
8593 .take_while(|(a, b)| a == b)
8594 .count() as u32;
8595 let end = Point::new(
8596 start.row,
8597 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8598 );
8599 start..end
8600 } else {
8601 start..start
8602 }
8603 }
8604
8605 fn comment_suffix_range(
8606 snapshot: &MultiBufferSnapshot,
8607 row: MultiBufferRow,
8608 comment_suffix: &str,
8609 comment_suffix_has_leading_space: bool,
8610 ) -> Range<Point> {
8611 let end = Point::new(row.0, snapshot.line_len(row));
8612 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8613
8614 let mut line_end_bytes = snapshot
8615 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8616 .flatten()
8617 .copied();
8618
8619 let leading_space_len = if suffix_start_column > 0
8620 && line_end_bytes.next() == Some(b' ')
8621 && comment_suffix_has_leading_space
8622 {
8623 1
8624 } else {
8625 0
8626 };
8627
8628 // If this line currently begins with the line comment prefix, then record
8629 // the range containing the prefix.
8630 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8631 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8632 start..end
8633 } else {
8634 end..end
8635 }
8636 }
8637
8638 // TODO: Handle selections that cross excerpts
8639 for selection in &mut selections {
8640 let start_column = snapshot
8641 .indent_size_for_line(MultiBufferRow(selection.start.row))
8642 .len;
8643 let language = if let Some(language) =
8644 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8645 {
8646 language
8647 } else {
8648 continue;
8649 };
8650
8651 selection_edit_ranges.clear();
8652
8653 // If multiple selections contain a given row, avoid processing that
8654 // row more than once.
8655 let mut start_row = MultiBufferRow(selection.start.row);
8656 if last_toggled_row == Some(start_row) {
8657 start_row = start_row.next_row();
8658 }
8659 let end_row =
8660 if selection.end.row > selection.start.row && selection.end.column == 0 {
8661 MultiBufferRow(selection.end.row - 1)
8662 } else {
8663 MultiBufferRow(selection.end.row)
8664 };
8665 last_toggled_row = Some(end_row);
8666
8667 if start_row > end_row {
8668 continue;
8669 }
8670
8671 // If the language has line comments, toggle those.
8672 let full_comment_prefixes = language.line_comment_prefixes();
8673 if !full_comment_prefixes.is_empty() {
8674 let first_prefix = full_comment_prefixes
8675 .first()
8676 .expect("prefixes is non-empty");
8677 let prefix_trimmed_lengths = full_comment_prefixes
8678 .iter()
8679 .map(|p| p.trim_end_matches(' ').len())
8680 .collect::<SmallVec<[usize; 4]>>();
8681
8682 let mut all_selection_lines_are_comments = true;
8683
8684 for row in start_row.0..=end_row.0 {
8685 let row = MultiBufferRow(row);
8686 if start_row < end_row && snapshot.is_line_blank(row) {
8687 continue;
8688 }
8689
8690 let prefix_range = full_comment_prefixes
8691 .iter()
8692 .zip(prefix_trimmed_lengths.iter().copied())
8693 .map(|(prefix, trimmed_prefix_len)| {
8694 comment_prefix_range(
8695 snapshot.deref(),
8696 row,
8697 &prefix[..trimmed_prefix_len],
8698 &prefix[trimmed_prefix_len..],
8699 )
8700 })
8701 .max_by_key(|range| range.end.column - range.start.column)
8702 .expect("prefixes is non-empty");
8703
8704 if prefix_range.is_empty() {
8705 all_selection_lines_are_comments = false;
8706 }
8707
8708 selection_edit_ranges.push(prefix_range);
8709 }
8710
8711 if all_selection_lines_are_comments {
8712 edits.extend(
8713 selection_edit_ranges
8714 .iter()
8715 .cloned()
8716 .map(|range| (range, empty_str.clone())),
8717 );
8718 } else {
8719 let min_column = selection_edit_ranges
8720 .iter()
8721 .map(|range| range.start.column)
8722 .min()
8723 .unwrap_or(0);
8724 edits.extend(selection_edit_ranges.iter().map(|range| {
8725 let position = Point::new(range.start.row, min_column);
8726 (position..position, first_prefix.clone())
8727 }));
8728 }
8729 } else if let Some((full_comment_prefix, comment_suffix)) =
8730 language.block_comment_delimiters()
8731 {
8732 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8733 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8734 let prefix_range = comment_prefix_range(
8735 snapshot.deref(),
8736 start_row,
8737 comment_prefix,
8738 comment_prefix_whitespace,
8739 );
8740 let suffix_range = comment_suffix_range(
8741 snapshot.deref(),
8742 end_row,
8743 comment_suffix.trim_start_matches(' '),
8744 comment_suffix.starts_with(' '),
8745 );
8746
8747 if prefix_range.is_empty() || suffix_range.is_empty() {
8748 edits.push((
8749 prefix_range.start..prefix_range.start,
8750 full_comment_prefix.clone(),
8751 ));
8752 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8753 suffixes_inserted.push((end_row, comment_suffix.len()));
8754 } else {
8755 edits.push((prefix_range, empty_str.clone()));
8756 edits.push((suffix_range, empty_str.clone()));
8757 }
8758 } else {
8759 continue;
8760 }
8761 }
8762
8763 drop(snapshot);
8764 this.buffer.update(cx, |buffer, cx| {
8765 buffer.edit(edits, None, cx);
8766 });
8767
8768 // Adjust selections so that they end before any comment suffixes that
8769 // were inserted.
8770 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8771 let mut selections = this.selections.all::<Point>(cx);
8772 let snapshot = this.buffer.read(cx).read(cx);
8773 for selection in &mut selections {
8774 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8775 match row.cmp(&MultiBufferRow(selection.end.row)) {
8776 Ordering::Less => {
8777 suffixes_inserted.next();
8778 continue;
8779 }
8780 Ordering::Greater => break,
8781 Ordering::Equal => {
8782 if selection.end.column == snapshot.line_len(row) {
8783 if selection.is_empty() {
8784 selection.start.column -= suffix_len as u32;
8785 }
8786 selection.end.column -= suffix_len as u32;
8787 }
8788 break;
8789 }
8790 }
8791 }
8792 }
8793
8794 drop(snapshot);
8795 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8796
8797 let selections = this.selections.all::<Point>(cx);
8798 let selections_on_single_row = selections.windows(2).all(|selections| {
8799 selections[0].start.row == selections[1].start.row
8800 && selections[0].end.row == selections[1].end.row
8801 && selections[0].start.row == selections[0].end.row
8802 });
8803 let selections_selecting = selections
8804 .iter()
8805 .any(|selection| selection.start != selection.end);
8806 let advance_downwards = action.advance_downwards
8807 && selections_on_single_row
8808 && !selections_selecting
8809 && !matches!(this.mode, EditorMode::SingleLine { .. });
8810
8811 if advance_downwards {
8812 let snapshot = this.buffer.read(cx).snapshot(cx);
8813
8814 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8815 s.move_cursors_with(|display_snapshot, display_point, _| {
8816 let mut point = display_point.to_point(display_snapshot);
8817 point.row += 1;
8818 point = snapshot.clip_point(point, Bias::Left);
8819 let display_point = point.to_display_point(display_snapshot);
8820 let goal = SelectionGoal::HorizontalPosition(
8821 display_snapshot
8822 .x_for_display_point(display_point, text_layout_details)
8823 .into(),
8824 );
8825 (display_point, goal)
8826 })
8827 });
8828 }
8829 });
8830 }
8831
8832 pub fn select_enclosing_symbol(
8833 &mut self,
8834 _: &SelectEnclosingSymbol,
8835 cx: &mut ViewContext<Self>,
8836 ) {
8837 let buffer = self.buffer.read(cx).snapshot(cx);
8838 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8839
8840 fn update_selection(
8841 selection: &Selection<usize>,
8842 buffer_snap: &MultiBufferSnapshot,
8843 ) -> Option<Selection<usize>> {
8844 let cursor = selection.head();
8845 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8846 for symbol in symbols.iter().rev() {
8847 let start = symbol.range.start.to_offset(buffer_snap);
8848 let end = symbol.range.end.to_offset(buffer_snap);
8849 let new_range = start..end;
8850 if start < selection.start || end > selection.end {
8851 return Some(Selection {
8852 id: selection.id,
8853 start: new_range.start,
8854 end: new_range.end,
8855 goal: SelectionGoal::None,
8856 reversed: selection.reversed,
8857 });
8858 }
8859 }
8860 None
8861 }
8862
8863 let mut selected_larger_symbol = false;
8864 let new_selections = old_selections
8865 .iter()
8866 .map(|selection| match update_selection(selection, &buffer) {
8867 Some(new_selection) => {
8868 if new_selection.range() != selection.range() {
8869 selected_larger_symbol = true;
8870 }
8871 new_selection
8872 }
8873 None => selection.clone(),
8874 })
8875 .collect::<Vec<_>>();
8876
8877 if selected_larger_symbol {
8878 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8879 s.select(new_selections);
8880 });
8881 }
8882 }
8883
8884 pub fn select_larger_syntax_node(
8885 &mut self,
8886 _: &SelectLargerSyntaxNode,
8887 cx: &mut ViewContext<Self>,
8888 ) {
8889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8890 let buffer = self.buffer.read(cx).snapshot(cx);
8891 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8892
8893 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8894 let mut selected_larger_node = false;
8895 let new_selections = old_selections
8896 .iter()
8897 .map(|selection| {
8898 let old_range = selection.start..selection.end;
8899 let mut new_range = old_range.clone();
8900 while let Some(containing_range) =
8901 buffer.range_for_syntax_ancestor(new_range.clone())
8902 {
8903 new_range = containing_range;
8904 if !display_map.intersects_fold(new_range.start)
8905 && !display_map.intersects_fold(new_range.end)
8906 {
8907 break;
8908 }
8909 }
8910
8911 selected_larger_node |= new_range != old_range;
8912 Selection {
8913 id: selection.id,
8914 start: new_range.start,
8915 end: new_range.end,
8916 goal: SelectionGoal::None,
8917 reversed: selection.reversed,
8918 }
8919 })
8920 .collect::<Vec<_>>();
8921
8922 if selected_larger_node {
8923 stack.push(old_selections);
8924 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8925 s.select(new_selections);
8926 });
8927 }
8928 self.select_larger_syntax_node_stack = stack;
8929 }
8930
8931 pub fn select_smaller_syntax_node(
8932 &mut self,
8933 _: &SelectSmallerSyntaxNode,
8934 cx: &mut ViewContext<Self>,
8935 ) {
8936 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8937 if let Some(selections) = stack.pop() {
8938 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8939 s.select(selections.to_vec());
8940 });
8941 }
8942 self.select_larger_syntax_node_stack = stack;
8943 }
8944
8945 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8946 if !EditorSettings::get_global(cx).gutter.runnables {
8947 self.clear_tasks();
8948 return Task::ready(());
8949 }
8950 let project = self.project.clone();
8951 cx.spawn(|this, mut cx| async move {
8952 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8953 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8954 }) else {
8955 return;
8956 };
8957
8958 let Some(project) = project else {
8959 return;
8960 };
8961
8962 let hide_runnables = project
8963 .update(&mut cx, |project, cx| {
8964 // Do not display any test indicators in non-dev server remote projects.
8965 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8966 })
8967 .unwrap_or(true);
8968 if hide_runnables {
8969 return;
8970 }
8971 let new_rows =
8972 cx.background_executor()
8973 .spawn({
8974 let snapshot = display_snapshot.clone();
8975 async move {
8976 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8977 }
8978 })
8979 .await;
8980 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8981
8982 this.update(&mut cx, |this, _| {
8983 this.clear_tasks();
8984 for (key, value) in rows {
8985 this.insert_tasks(key, value);
8986 }
8987 })
8988 .ok();
8989 })
8990 }
8991 fn fetch_runnable_ranges(
8992 snapshot: &DisplaySnapshot,
8993 range: Range<Anchor>,
8994 ) -> Vec<language::RunnableRange> {
8995 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8996 }
8997
8998 fn runnable_rows(
8999 project: Model<Project>,
9000 snapshot: DisplaySnapshot,
9001 runnable_ranges: Vec<RunnableRange>,
9002 mut cx: AsyncWindowContext,
9003 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9004 runnable_ranges
9005 .into_iter()
9006 .filter_map(|mut runnable| {
9007 let tasks = cx
9008 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9009 .ok()?;
9010 if tasks.is_empty() {
9011 return None;
9012 }
9013
9014 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9015
9016 let row = snapshot
9017 .buffer_snapshot
9018 .buffer_line_for_row(MultiBufferRow(point.row))?
9019 .1
9020 .start
9021 .row;
9022
9023 let context_range =
9024 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9025 Some((
9026 (runnable.buffer_id, row),
9027 RunnableTasks {
9028 templates: tasks,
9029 offset: MultiBufferOffset(runnable.run_range.start),
9030 context_range,
9031 column: point.column,
9032 extra_variables: runnable.extra_captures,
9033 },
9034 ))
9035 })
9036 .collect()
9037 }
9038
9039 fn templates_with_tags(
9040 project: &Model<Project>,
9041 runnable: &mut Runnable,
9042 cx: &WindowContext<'_>,
9043 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9044 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9045 let (worktree_id, file) = project
9046 .buffer_for_id(runnable.buffer, cx)
9047 .and_then(|buffer| buffer.read(cx).file())
9048 .map(|file| (file.worktree_id(cx), file.clone()))
9049 .unzip();
9050
9051 (project.task_inventory().clone(), worktree_id, file)
9052 });
9053
9054 let inventory = inventory.read(cx);
9055 let tags = mem::take(&mut runnable.tags);
9056 let mut tags: Vec<_> = tags
9057 .into_iter()
9058 .flat_map(|tag| {
9059 let tag = tag.0.clone();
9060 inventory
9061 .list_tasks(
9062 file.clone(),
9063 Some(runnable.language.clone()),
9064 worktree_id,
9065 cx,
9066 )
9067 .into_iter()
9068 .filter(move |(_, template)| {
9069 template.tags.iter().any(|source_tag| source_tag == &tag)
9070 })
9071 })
9072 .sorted_by_key(|(kind, _)| kind.to_owned())
9073 .collect();
9074 if let Some((leading_tag_source, _)) = tags.first() {
9075 // Strongest source wins; if we have worktree tag binding, prefer that to
9076 // global and language bindings;
9077 // if we have a global binding, prefer that to language binding.
9078 let first_mismatch = tags
9079 .iter()
9080 .position(|(tag_source, _)| tag_source != leading_tag_source);
9081 if let Some(index) = first_mismatch {
9082 tags.truncate(index);
9083 }
9084 }
9085
9086 tags
9087 }
9088
9089 pub fn move_to_enclosing_bracket(
9090 &mut self,
9091 _: &MoveToEnclosingBracket,
9092 cx: &mut ViewContext<Self>,
9093 ) {
9094 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9095 s.move_offsets_with(|snapshot, selection| {
9096 let Some(enclosing_bracket_ranges) =
9097 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9098 else {
9099 return;
9100 };
9101
9102 let mut best_length = usize::MAX;
9103 let mut best_inside = false;
9104 let mut best_in_bracket_range = false;
9105 let mut best_destination = None;
9106 for (open, close) in enclosing_bracket_ranges {
9107 let close = close.to_inclusive();
9108 let length = close.end() - open.start;
9109 let inside = selection.start >= open.end && selection.end <= *close.start();
9110 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9111 || close.contains(&selection.head());
9112
9113 // If best is next to a bracket and current isn't, skip
9114 if !in_bracket_range && best_in_bracket_range {
9115 continue;
9116 }
9117
9118 // Prefer smaller lengths unless best is inside and current isn't
9119 if length > best_length && (best_inside || !inside) {
9120 continue;
9121 }
9122
9123 best_length = length;
9124 best_inside = inside;
9125 best_in_bracket_range = in_bracket_range;
9126 best_destination = Some(
9127 if close.contains(&selection.start) && close.contains(&selection.end) {
9128 if inside {
9129 open.end
9130 } else {
9131 open.start
9132 }
9133 } else if inside {
9134 *close.start()
9135 } else {
9136 *close.end()
9137 },
9138 );
9139 }
9140
9141 if let Some(destination) = best_destination {
9142 selection.collapse_to(destination, SelectionGoal::None);
9143 }
9144 })
9145 });
9146 }
9147
9148 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9149 self.end_selection(cx);
9150 self.selection_history.mode = SelectionHistoryMode::Undoing;
9151 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9152 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9153 self.select_next_state = entry.select_next_state;
9154 self.select_prev_state = entry.select_prev_state;
9155 self.add_selections_state = entry.add_selections_state;
9156 self.request_autoscroll(Autoscroll::newest(), cx);
9157 }
9158 self.selection_history.mode = SelectionHistoryMode::Normal;
9159 }
9160
9161 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9162 self.end_selection(cx);
9163 self.selection_history.mode = SelectionHistoryMode::Redoing;
9164 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9165 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9166 self.select_next_state = entry.select_next_state;
9167 self.select_prev_state = entry.select_prev_state;
9168 self.add_selections_state = entry.add_selections_state;
9169 self.request_autoscroll(Autoscroll::newest(), cx);
9170 }
9171 self.selection_history.mode = SelectionHistoryMode::Normal;
9172 }
9173
9174 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9175 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9176 }
9177
9178 pub fn expand_excerpts_down(
9179 &mut self,
9180 action: &ExpandExcerptsDown,
9181 cx: &mut ViewContext<Self>,
9182 ) {
9183 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9184 }
9185
9186 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9187 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9188 }
9189
9190 pub fn expand_excerpts_for_direction(
9191 &mut self,
9192 lines: u32,
9193 direction: ExpandExcerptDirection,
9194 cx: &mut ViewContext<Self>,
9195 ) {
9196 let selections = self.selections.disjoint_anchors();
9197
9198 let lines = if lines == 0 {
9199 EditorSettings::get_global(cx).expand_excerpt_lines
9200 } else {
9201 lines
9202 };
9203
9204 self.buffer.update(cx, |buffer, cx| {
9205 buffer.expand_excerpts(
9206 selections
9207 .iter()
9208 .map(|selection| selection.head().excerpt_id)
9209 .dedup(),
9210 lines,
9211 direction,
9212 cx,
9213 )
9214 })
9215 }
9216
9217 pub fn expand_excerpt(
9218 &mut self,
9219 excerpt: ExcerptId,
9220 direction: ExpandExcerptDirection,
9221 cx: &mut ViewContext<Self>,
9222 ) {
9223 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9224 self.buffer.update(cx, |buffer, cx| {
9225 buffer.expand_excerpts([excerpt], lines, direction, cx)
9226 })
9227 }
9228
9229 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9230 self.go_to_diagnostic_impl(Direction::Next, cx)
9231 }
9232
9233 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9234 self.go_to_diagnostic_impl(Direction::Prev, cx)
9235 }
9236
9237 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9238 let buffer = self.buffer.read(cx).snapshot(cx);
9239 let selection = self.selections.newest::<usize>(cx);
9240
9241 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9242 if direction == Direction::Next {
9243 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9244 let (group_id, jump_to) = popover.activation_info();
9245 if self.activate_diagnostics(group_id, cx) {
9246 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9247 let mut new_selection = s.newest_anchor().clone();
9248 new_selection.collapse_to(jump_to, SelectionGoal::None);
9249 s.select_anchors(vec![new_selection.clone()]);
9250 });
9251 }
9252 return;
9253 }
9254 }
9255
9256 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9257 active_diagnostics
9258 .primary_range
9259 .to_offset(&buffer)
9260 .to_inclusive()
9261 });
9262 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9263 if active_primary_range.contains(&selection.head()) {
9264 *active_primary_range.start()
9265 } else {
9266 selection.head()
9267 }
9268 } else {
9269 selection.head()
9270 };
9271 let snapshot = self.snapshot(cx);
9272 loop {
9273 let diagnostics = if direction == Direction::Prev {
9274 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9275 } else {
9276 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9277 }
9278 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9279 let group = diagnostics
9280 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9281 // be sorted in a stable way
9282 // skip until we are at current active diagnostic, if it exists
9283 .skip_while(|entry| {
9284 (match direction {
9285 Direction::Prev => entry.range.start >= search_start,
9286 Direction::Next => entry.range.start <= search_start,
9287 }) && self
9288 .active_diagnostics
9289 .as_ref()
9290 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9291 })
9292 .find_map(|entry| {
9293 if entry.diagnostic.is_primary
9294 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9295 && !entry.range.is_empty()
9296 // if we match with the active diagnostic, skip it
9297 && Some(entry.diagnostic.group_id)
9298 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9299 {
9300 Some((entry.range, entry.diagnostic.group_id))
9301 } else {
9302 None
9303 }
9304 });
9305
9306 if let Some((primary_range, group_id)) = group {
9307 if self.activate_diagnostics(group_id, cx) {
9308 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9309 s.select(vec![Selection {
9310 id: selection.id,
9311 start: primary_range.start,
9312 end: primary_range.start,
9313 reversed: false,
9314 goal: SelectionGoal::None,
9315 }]);
9316 });
9317 }
9318 break;
9319 } else {
9320 // Cycle around to the start of the buffer, potentially moving back to the start of
9321 // the currently active diagnostic.
9322 active_primary_range.take();
9323 if direction == Direction::Prev {
9324 if search_start == buffer.len() {
9325 break;
9326 } else {
9327 search_start = buffer.len();
9328 }
9329 } else if search_start == 0 {
9330 break;
9331 } else {
9332 search_start = 0;
9333 }
9334 }
9335 }
9336 }
9337
9338 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9339 let snapshot = self
9340 .display_map
9341 .update(cx, |display_map, cx| display_map.snapshot(cx));
9342 let selection = self.selections.newest::<Point>(cx);
9343
9344 if !self.seek_in_direction(
9345 &snapshot,
9346 selection.head(),
9347 false,
9348 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9349 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9350 ),
9351 cx,
9352 ) {
9353 let wrapped_point = Point::zero();
9354 self.seek_in_direction(
9355 &snapshot,
9356 wrapped_point,
9357 true,
9358 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9359 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9360 ),
9361 cx,
9362 );
9363 }
9364 }
9365
9366 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9367 let snapshot = self
9368 .display_map
9369 .update(cx, |display_map, cx| display_map.snapshot(cx));
9370 let selection = self.selections.newest::<Point>(cx);
9371
9372 if !self.seek_in_direction(
9373 &snapshot,
9374 selection.head(),
9375 false,
9376 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9377 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9378 ),
9379 cx,
9380 ) {
9381 let wrapped_point = snapshot.buffer_snapshot.max_point();
9382 self.seek_in_direction(
9383 &snapshot,
9384 wrapped_point,
9385 true,
9386 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9387 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9388 ),
9389 cx,
9390 );
9391 }
9392 }
9393
9394 fn seek_in_direction(
9395 &mut self,
9396 snapshot: &DisplaySnapshot,
9397 initial_point: Point,
9398 is_wrapped: bool,
9399 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9400 cx: &mut ViewContext<Editor>,
9401 ) -> bool {
9402 let display_point = initial_point.to_display_point(snapshot);
9403 let mut hunks = hunks
9404 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9405 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9406 .dedup();
9407
9408 if let Some(hunk) = hunks.next() {
9409 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9410 let row = hunk.start_display_row();
9411 let point = DisplayPoint::new(row, 0);
9412 s.select_display_ranges([point..point]);
9413 });
9414
9415 true
9416 } else {
9417 false
9418 }
9419 }
9420
9421 pub fn go_to_definition(
9422 &mut self,
9423 _: &GoToDefinition,
9424 cx: &mut ViewContext<Self>,
9425 ) -> Task<Result<Navigated>> {
9426 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9427 cx.spawn(|editor, mut cx| async move {
9428 if definition.await? == Navigated::Yes {
9429 return Ok(Navigated::Yes);
9430 }
9431 match editor.update(&mut cx, |editor, cx| {
9432 editor.find_all_references(&FindAllReferences, cx)
9433 })? {
9434 Some(references) => references.await,
9435 None => Ok(Navigated::No),
9436 }
9437 })
9438 }
9439
9440 pub fn go_to_declaration(
9441 &mut self,
9442 _: &GoToDeclaration,
9443 cx: &mut ViewContext<Self>,
9444 ) -> Task<Result<Navigated>> {
9445 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9446 }
9447
9448 pub fn go_to_declaration_split(
9449 &mut self,
9450 _: &GoToDeclaration,
9451 cx: &mut ViewContext<Self>,
9452 ) -> Task<Result<Navigated>> {
9453 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9454 }
9455
9456 pub fn go_to_implementation(
9457 &mut self,
9458 _: &GoToImplementation,
9459 cx: &mut ViewContext<Self>,
9460 ) -> Task<Result<Navigated>> {
9461 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9462 }
9463
9464 pub fn go_to_implementation_split(
9465 &mut self,
9466 _: &GoToImplementationSplit,
9467 cx: &mut ViewContext<Self>,
9468 ) -> Task<Result<Navigated>> {
9469 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9470 }
9471
9472 pub fn go_to_type_definition(
9473 &mut self,
9474 _: &GoToTypeDefinition,
9475 cx: &mut ViewContext<Self>,
9476 ) -> Task<Result<Navigated>> {
9477 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9478 }
9479
9480 pub fn go_to_definition_split(
9481 &mut self,
9482 _: &GoToDefinitionSplit,
9483 cx: &mut ViewContext<Self>,
9484 ) -> Task<Result<Navigated>> {
9485 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9486 }
9487
9488 pub fn go_to_type_definition_split(
9489 &mut self,
9490 _: &GoToTypeDefinitionSplit,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9494 }
9495
9496 fn go_to_definition_of_kind(
9497 &mut self,
9498 kind: GotoDefinitionKind,
9499 split: bool,
9500 cx: &mut ViewContext<Self>,
9501 ) -> Task<Result<Navigated>> {
9502 let Some(workspace) = self.workspace() else {
9503 return Task::ready(Ok(Navigated::No));
9504 };
9505 let buffer = self.buffer.read(cx);
9506 let head = self.selections.newest::<usize>(cx).head();
9507 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9508 text_anchor
9509 } else {
9510 return Task::ready(Ok(Navigated::No));
9511 };
9512
9513 let project = workspace.read(cx).project().clone();
9514 let definitions = project.update(cx, |project, cx| match kind {
9515 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9516 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9517 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9518 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9519 });
9520
9521 cx.spawn(|editor, mut cx| async move {
9522 let definitions = definitions.await?;
9523 let navigated = editor
9524 .update(&mut cx, |editor, cx| {
9525 editor.navigate_to_hover_links(
9526 Some(kind),
9527 definitions
9528 .into_iter()
9529 .filter(|location| {
9530 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9531 })
9532 .map(HoverLink::Text)
9533 .collect::<Vec<_>>(),
9534 split,
9535 cx,
9536 )
9537 })?
9538 .await?;
9539 anyhow::Ok(navigated)
9540 })
9541 }
9542
9543 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9544 let position = self.selections.newest_anchor().head();
9545 let Some((buffer, buffer_position)) =
9546 self.buffer.read(cx).text_anchor_for_position(position, cx)
9547 else {
9548 return;
9549 };
9550
9551 cx.spawn(|editor, mut cx| async move {
9552 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9553 editor.update(&mut cx, |_, cx| {
9554 cx.open_url(&url);
9555 })
9556 } else {
9557 Ok(())
9558 }
9559 })
9560 .detach();
9561 }
9562
9563 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9564 let Some(workspace) = self.workspace() else {
9565 return;
9566 };
9567
9568 let position = self.selections.newest_anchor().head();
9569
9570 let Some((buffer, buffer_position)) =
9571 self.buffer.read(cx).text_anchor_for_position(position, cx)
9572 else {
9573 return;
9574 };
9575
9576 let Some(project) = self.project.clone() else {
9577 return;
9578 };
9579
9580 cx.spawn(|_, mut cx| async move {
9581 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9582
9583 if let Some((_, path)) = result {
9584 workspace
9585 .update(&mut cx, |workspace, cx| {
9586 workspace.open_resolved_path(path, cx)
9587 })?
9588 .await?;
9589 }
9590 anyhow::Ok(())
9591 })
9592 .detach();
9593 }
9594
9595 pub(crate) fn navigate_to_hover_links(
9596 &mut self,
9597 kind: Option<GotoDefinitionKind>,
9598 mut definitions: Vec<HoverLink>,
9599 split: bool,
9600 cx: &mut ViewContext<Editor>,
9601 ) -> Task<Result<Navigated>> {
9602 // If there is one definition, just open it directly
9603 if definitions.len() == 1 {
9604 let definition = definitions.pop().unwrap();
9605
9606 enum TargetTaskResult {
9607 Location(Option<Location>),
9608 AlreadyNavigated,
9609 }
9610
9611 let target_task = match definition {
9612 HoverLink::Text(link) => {
9613 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9614 }
9615 HoverLink::InlayHint(lsp_location, server_id) => {
9616 let computation = self.compute_target_location(lsp_location, server_id, cx);
9617 cx.background_executor().spawn(async move {
9618 let location = computation.await?;
9619 Ok(TargetTaskResult::Location(location))
9620 })
9621 }
9622 HoverLink::Url(url) => {
9623 cx.open_url(&url);
9624 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9625 }
9626 HoverLink::File(path) => {
9627 if let Some(workspace) = self.workspace() {
9628 cx.spawn(|_, mut cx| async move {
9629 workspace
9630 .update(&mut cx, |workspace, cx| {
9631 workspace.open_resolved_path(path, cx)
9632 })?
9633 .await
9634 .map(|_| TargetTaskResult::AlreadyNavigated)
9635 })
9636 } else {
9637 Task::ready(Ok(TargetTaskResult::Location(None)))
9638 }
9639 }
9640 };
9641 cx.spawn(|editor, mut cx| async move {
9642 let target = match target_task.await.context("target resolution task")? {
9643 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9644 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9645 TargetTaskResult::Location(Some(target)) => target,
9646 };
9647
9648 editor.update(&mut cx, |editor, cx| {
9649 let Some(workspace) = editor.workspace() else {
9650 return Navigated::No;
9651 };
9652 let pane = workspace.read(cx).active_pane().clone();
9653
9654 let range = target.range.to_offset(target.buffer.read(cx));
9655 let range = editor.range_for_match(&range);
9656
9657 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9658 let buffer = target.buffer.read(cx);
9659 let range = check_multiline_range(buffer, range);
9660 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9661 s.select_ranges([range]);
9662 });
9663 } else {
9664 cx.window_context().defer(move |cx| {
9665 let target_editor: View<Self> =
9666 workspace.update(cx, |workspace, cx| {
9667 let pane = if split {
9668 workspace.adjacent_pane(cx)
9669 } else {
9670 workspace.active_pane().clone()
9671 };
9672
9673 workspace.open_project_item(
9674 pane,
9675 target.buffer.clone(),
9676 true,
9677 true,
9678 cx,
9679 )
9680 });
9681 target_editor.update(cx, |target_editor, cx| {
9682 // When selecting a definition in a different buffer, disable the nav history
9683 // to avoid creating a history entry at the previous cursor location.
9684 pane.update(cx, |pane, _| pane.disable_history());
9685 let buffer = target.buffer.read(cx);
9686 let range = check_multiline_range(buffer, range);
9687 target_editor.change_selections(
9688 Some(Autoscroll::focused()),
9689 cx,
9690 |s| {
9691 s.select_ranges([range]);
9692 },
9693 );
9694 pane.update(cx, |pane, _| pane.enable_history());
9695 });
9696 });
9697 }
9698 Navigated::Yes
9699 })
9700 })
9701 } else if !definitions.is_empty() {
9702 cx.spawn(|editor, mut cx| async move {
9703 let (title, location_tasks, workspace) = editor
9704 .update(&mut cx, |editor, cx| {
9705 let tab_kind = match kind {
9706 Some(GotoDefinitionKind::Implementation) => "Implementations",
9707 _ => "Definitions",
9708 };
9709 let title = definitions
9710 .iter()
9711 .find_map(|definition| match definition {
9712 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9713 let buffer = origin.buffer.read(cx);
9714 format!(
9715 "{} for {}",
9716 tab_kind,
9717 buffer
9718 .text_for_range(origin.range.clone())
9719 .collect::<String>()
9720 )
9721 }),
9722 HoverLink::InlayHint(_, _) => None,
9723 HoverLink::Url(_) => None,
9724 HoverLink::File(_) => None,
9725 })
9726 .unwrap_or(tab_kind.to_string());
9727 let location_tasks = definitions
9728 .into_iter()
9729 .map(|definition| match definition {
9730 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9731 HoverLink::InlayHint(lsp_location, server_id) => {
9732 editor.compute_target_location(lsp_location, server_id, cx)
9733 }
9734 HoverLink::Url(_) => Task::ready(Ok(None)),
9735 HoverLink::File(_) => Task::ready(Ok(None)),
9736 })
9737 .collect::<Vec<_>>();
9738 (title, location_tasks, editor.workspace().clone())
9739 })
9740 .context("location tasks preparation")?;
9741
9742 let locations = future::join_all(location_tasks)
9743 .await
9744 .into_iter()
9745 .filter_map(|location| location.transpose())
9746 .collect::<Result<_>>()
9747 .context("location tasks")?;
9748
9749 let Some(workspace) = workspace else {
9750 return Ok(Navigated::No);
9751 };
9752 let opened = workspace
9753 .update(&mut cx, |workspace, cx| {
9754 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9755 })
9756 .ok();
9757
9758 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9759 })
9760 } else {
9761 Task::ready(Ok(Navigated::No))
9762 }
9763 }
9764
9765 fn compute_target_location(
9766 &self,
9767 lsp_location: lsp::Location,
9768 server_id: LanguageServerId,
9769 cx: &mut ViewContext<Editor>,
9770 ) -> Task<anyhow::Result<Option<Location>>> {
9771 let Some(project) = self.project.clone() else {
9772 return Task::Ready(Some(Ok(None)));
9773 };
9774
9775 cx.spawn(move |editor, mut cx| async move {
9776 let location_task = editor.update(&mut cx, |editor, cx| {
9777 project.update(cx, |project, cx| {
9778 let language_server_name =
9779 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9780 project
9781 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9782 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9783 });
9784 language_server_name.map(|language_server_name| {
9785 project.open_local_buffer_via_lsp(
9786 lsp_location.uri.clone(),
9787 server_id,
9788 language_server_name,
9789 cx,
9790 )
9791 })
9792 })
9793 })?;
9794 let location = match location_task {
9795 Some(task) => Some({
9796 let target_buffer_handle = task.await.context("open local buffer")?;
9797 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9798 let target_start = target_buffer
9799 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9800 let target_end = target_buffer
9801 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9802 target_buffer.anchor_after(target_start)
9803 ..target_buffer.anchor_before(target_end)
9804 })?;
9805 Location {
9806 buffer: target_buffer_handle,
9807 range,
9808 }
9809 }),
9810 None => None,
9811 };
9812 Ok(location)
9813 })
9814 }
9815
9816 pub fn find_all_references(
9817 &mut self,
9818 _: &FindAllReferences,
9819 cx: &mut ViewContext<Self>,
9820 ) -> Option<Task<Result<Navigated>>> {
9821 let multi_buffer = self.buffer.read(cx);
9822 let selection = self.selections.newest::<usize>(cx);
9823 let head = selection.head();
9824
9825 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9826 let head_anchor = multi_buffer_snapshot.anchor_at(
9827 head,
9828 if head < selection.tail() {
9829 Bias::Right
9830 } else {
9831 Bias::Left
9832 },
9833 );
9834
9835 match self
9836 .find_all_references_task_sources
9837 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9838 {
9839 Ok(_) => {
9840 log::info!(
9841 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9842 );
9843 return None;
9844 }
9845 Err(i) => {
9846 self.find_all_references_task_sources.insert(i, head_anchor);
9847 }
9848 }
9849
9850 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9851 let workspace = self.workspace()?;
9852 let project = workspace.read(cx).project().clone();
9853 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9854 Some(cx.spawn(|editor, mut cx| async move {
9855 let _cleanup = defer({
9856 let mut cx = cx.clone();
9857 move || {
9858 let _ = editor.update(&mut cx, |editor, _| {
9859 if let Ok(i) =
9860 editor
9861 .find_all_references_task_sources
9862 .binary_search_by(|anchor| {
9863 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9864 })
9865 {
9866 editor.find_all_references_task_sources.remove(i);
9867 }
9868 });
9869 }
9870 });
9871
9872 let locations = references.await?;
9873 if locations.is_empty() {
9874 return anyhow::Ok(Navigated::No);
9875 }
9876
9877 workspace.update(&mut cx, |workspace, cx| {
9878 let title = locations
9879 .first()
9880 .as_ref()
9881 .map(|location| {
9882 let buffer = location.buffer.read(cx);
9883 format!(
9884 "References to `{}`",
9885 buffer
9886 .text_for_range(location.range.clone())
9887 .collect::<String>()
9888 )
9889 })
9890 .unwrap();
9891 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9892 Navigated::Yes
9893 })
9894 }))
9895 }
9896
9897 /// Opens a multibuffer with the given project locations in it
9898 pub fn open_locations_in_multibuffer(
9899 workspace: &mut Workspace,
9900 mut locations: Vec<Location>,
9901 title: String,
9902 split: bool,
9903 cx: &mut ViewContext<Workspace>,
9904 ) {
9905 // If there are multiple definitions, open them in a multibuffer
9906 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9907 let mut locations = locations.into_iter().peekable();
9908 let mut ranges_to_highlight = Vec::new();
9909 let capability = workspace.project().read(cx).capability();
9910
9911 let excerpt_buffer = cx.new_model(|cx| {
9912 let mut multibuffer = MultiBuffer::new(capability);
9913 while let Some(location) = locations.next() {
9914 let buffer = location.buffer.read(cx);
9915 let mut ranges_for_buffer = Vec::new();
9916 let range = location.range.to_offset(buffer);
9917 ranges_for_buffer.push(range.clone());
9918
9919 while let Some(next_location) = locations.peek() {
9920 if next_location.buffer == location.buffer {
9921 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9922 locations.next();
9923 } else {
9924 break;
9925 }
9926 }
9927
9928 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9929 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9930 location.buffer.clone(),
9931 ranges_for_buffer,
9932 DEFAULT_MULTIBUFFER_CONTEXT,
9933 cx,
9934 ))
9935 }
9936
9937 multibuffer.with_title(title)
9938 });
9939
9940 let editor = cx.new_view(|cx| {
9941 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9942 });
9943 editor.update(cx, |editor, cx| {
9944 if let Some(first_range) = ranges_to_highlight.first() {
9945 editor.change_selections(None, cx, |selections| {
9946 selections.clear_disjoint();
9947 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9948 });
9949 }
9950 editor.highlight_background::<Self>(
9951 &ranges_to_highlight,
9952 |theme| theme.editor_highlighted_line_background,
9953 cx,
9954 );
9955 });
9956
9957 let item = Box::new(editor);
9958 let item_id = item.item_id();
9959
9960 if split {
9961 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9962 } else {
9963 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9964 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9965 pane.close_current_preview_item(cx)
9966 } else {
9967 None
9968 }
9969 });
9970 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9971 }
9972 workspace.active_pane().update(cx, |pane, cx| {
9973 pane.set_preview_item_id(Some(item_id), cx);
9974 });
9975 }
9976
9977 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9978 use language::ToOffset as _;
9979
9980 let project = self.project.clone()?;
9981 let selection = self.selections.newest_anchor().clone();
9982 let (cursor_buffer, cursor_buffer_position) = self
9983 .buffer
9984 .read(cx)
9985 .text_anchor_for_position(selection.head(), cx)?;
9986 let (tail_buffer, cursor_buffer_position_end) = self
9987 .buffer
9988 .read(cx)
9989 .text_anchor_for_position(selection.tail(), cx)?;
9990 if tail_buffer != cursor_buffer {
9991 return None;
9992 }
9993
9994 let snapshot = cursor_buffer.read(cx).snapshot();
9995 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9996 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9997 let prepare_rename = project.update(cx, |project, cx| {
9998 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9999 });
10000 drop(snapshot);
10001
10002 Some(cx.spawn(|this, mut cx| async move {
10003 let rename_range = if let Some(range) = prepare_rename.await? {
10004 Some(range)
10005 } else {
10006 this.update(&mut cx, |this, cx| {
10007 let buffer = this.buffer.read(cx).snapshot(cx);
10008 let mut buffer_highlights = this
10009 .document_highlights_for_position(selection.head(), &buffer)
10010 .filter(|highlight| {
10011 highlight.start.excerpt_id == selection.head().excerpt_id
10012 && highlight.end.excerpt_id == selection.head().excerpt_id
10013 });
10014 buffer_highlights
10015 .next()
10016 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10017 })?
10018 };
10019 if let Some(rename_range) = rename_range {
10020 this.update(&mut cx, |this, cx| {
10021 let snapshot = cursor_buffer.read(cx).snapshot();
10022 let rename_buffer_range = rename_range.to_offset(&snapshot);
10023 let cursor_offset_in_rename_range =
10024 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10025 let cursor_offset_in_rename_range_end =
10026 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10027
10028 this.take_rename(false, cx);
10029 let buffer = this.buffer.read(cx).read(cx);
10030 let cursor_offset = selection.head().to_offset(&buffer);
10031 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10032 let rename_end = rename_start + rename_buffer_range.len();
10033 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10034 let mut old_highlight_id = None;
10035 let old_name: Arc<str> = buffer
10036 .chunks(rename_start..rename_end, true)
10037 .map(|chunk| {
10038 if old_highlight_id.is_none() {
10039 old_highlight_id = chunk.syntax_highlight_id;
10040 }
10041 chunk.text
10042 })
10043 .collect::<String>()
10044 .into();
10045
10046 drop(buffer);
10047
10048 // Position the selection in the rename editor so that it matches the current selection.
10049 this.show_local_selections = false;
10050 let rename_editor = cx.new_view(|cx| {
10051 let mut editor = Editor::single_line(cx);
10052 editor.buffer.update(cx, |buffer, cx| {
10053 buffer.edit([(0..0, old_name.clone())], None, cx)
10054 });
10055 let rename_selection_range = match cursor_offset_in_rename_range
10056 .cmp(&cursor_offset_in_rename_range_end)
10057 {
10058 Ordering::Equal => {
10059 editor.select_all(&SelectAll, cx);
10060 return editor;
10061 }
10062 Ordering::Less => {
10063 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10064 }
10065 Ordering::Greater => {
10066 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10067 }
10068 };
10069 if rename_selection_range.end > old_name.len() {
10070 editor.select_all(&SelectAll, cx);
10071 } else {
10072 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10073 s.select_ranges([rename_selection_range]);
10074 });
10075 }
10076 editor
10077 });
10078 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10079 if e == &EditorEvent::Focused {
10080 cx.emit(EditorEvent::FocusedIn)
10081 }
10082 })
10083 .detach();
10084
10085 let write_highlights =
10086 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10087 let read_highlights =
10088 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10089 let ranges = write_highlights
10090 .iter()
10091 .flat_map(|(_, ranges)| ranges.iter())
10092 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10093 .cloned()
10094 .collect();
10095
10096 this.highlight_text::<Rename>(
10097 ranges,
10098 HighlightStyle {
10099 fade_out: Some(0.6),
10100 ..Default::default()
10101 },
10102 cx,
10103 );
10104 let rename_focus_handle = rename_editor.focus_handle(cx);
10105 cx.focus(&rename_focus_handle);
10106 let block_id = this.insert_blocks(
10107 [BlockProperties {
10108 style: BlockStyle::Flex,
10109 position: range.start,
10110 height: 1,
10111 render: Box::new({
10112 let rename_editor = rename_editor.clone();
10113 move |cx: &mut BlockContext| {
10114 let mut text_style = cx.editor_style.text.clone();
10115 if let Some(highlight_style) = old_highlight_id
10116 .and_then(|h| h.style(&cx.editor_style.syntax))
10117 {
10118 text_style = text_style.highlight(highlight_style);
10119 }
10120 div()
10121 .pl(cx.anchor_x)
10122 .child(EditorElement::new(
10123 &rename_editor,
10124 EditorStyle {
10125 background: cx.theme().system().transparent,
10126 local_player: cx.editor_style.local_player,
10127 text: text_style,
10128 scrollbar_width: cx.editor_style.scrollbar_width,
10129 syntax: cx.editor_style.syntax.clone(),
10130 status: cx.editor_style.status.clone(),
10131 inlay_hints_style: HighlightStyle {
10132 font_weight: Some(FontWeight::BOLD),
10133 ..make_inlay_hints_style(cx)
10134 },
10135 suggestions_style: HighlightStyle {
10136 color: Some(cx.theme().status().predictive),
10137 ..HighlightStyle::default()
10138 },
10139 ..EditorStyle::default()
10140 },
10141 ))
10142 .into_any_element()
10143 }
10144 }),
10145 disposition: BlockDisposition::Below,
10146 priority: 0,
10147 }],
10148 Some(Autoscroll::fit()),
10149 cx,
10150 )[0];
10151 this.pending_rename = Some(RenameState {
10152 range,
10153 old_name,
10154 editor: rename_editor,
10155 block_id,
10156 });
10157 })?;
10158 }
10159
10160 Ok(())
10161 }))
10162 }
10163
10164 pub fn confirm_rename(
10165 &mut self,
10166 _: &ConfirmRename,
10167 cx: &mut ViewContext<Self>,
10168 ) -> Option<Task<Result<()>>> {
10169 let rename = self.take_rename(false, cx)?;
10170 let workspace = self.workspace()?;
10171 let (start_buffer, start) = self
10172 .buffer
10173 .read(cx)
10174 .text_anchor_for_position(rename.range.start, cx)?;
10175 let (end_buffer, end) = self
10176 .buffer
10177 .read(cx)
10178 .text_anchor_for_position(rename.range.end, cx)?;
10179 if start_buffer != end_buffer {
10180 return None;
10181 }
10182
10183 let buffer = start_buffer;
10184 let range = start..end;
10185 let old_name = rename.old_name;
10186 let new_name = rename.editor.read(cx).text(cx);
10187
10188 let rename = workspace
10189 .read(cx)
10190 .project()
10191 .clone()
10192 .update(cx, |project, cx| {
10193 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10194 });
10195 let workspace = workspace.downgrade();
10196
10197 Some(cx.spawn(|editor, mut cx| async move {
10198 let project_transaction = rename.await?;
10199 Self::open_project_transaction(
10200 &editor,
10201 workspace,
10202 project_transaction,
10203 format!("Rename: {} → {}", old_name, new_name),
10204 cx.clone(),
10205 )
10206 .await?;
10207
10208 editor.update(&mut cx, |editor, cx| {
10209 editor.refresh_document_highlights(cx);
10210 })?;
10211 Ok(())
10212 }))
10213 }
10214
10215 fn take_rename(
10216 &mut self,
10217 moving_cursor: bool,
10218 cx: &mut ViewContext<Self>,
10219 ) -> Option<RenameState> {
10220 let rename = self.pending_rename.take()?;
10221 if rename.editor.focus_handle(cx).is_focused(cx) {
10222 cx.focus(&self.focus_handle);
10223 }
10224
10225 self.remove_blocks(
10226 [rename.block_id].into_iter().collect(),
10227 Some(Autoscroll::fit()),
10228 cx,
10229 );
10230 self.clear_highlights::<Rename>(cx);
10231 self.show_local_selections = true;
10232
10233 if moving_cursor {
10234 let rename_editor = rename.editor.read(cx);
10235 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10236
10237 // Update the selection to match the position of the selection inside
10238 // the rename editor.
10239 let snapshot = self.buffer.read(cx).read(cx);
10240 let rename_range = rename.range.to_offset(&snapshot);
10241 let cursor_in_editor = snapshot
10242 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10243 .min(rename_range.end);
10244 drop(snapshot);
10245
10246 self.change_selections(None, cx, |s| {
10247 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10248 });
10249 } else {
10250 self.refresh_document_highlights(cx);
10251 }
10252
10253 Some(rename)
10254 }
10255
10256 pub fn pending_rename(&self) -> Option<&RenameState> {
10257 self.pending_rename.as_ref()
10258 }
10259
10260 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10261 let project = match &self.project {
10262 Some(project) => project.clone(),
10263 None => return None,
10264 };
10265
10266 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10267 }
10268
10269 fn perform_format(
10270 &mut self,
10271 project: Model<Project>,
10272 trigger: FormatTrigger,
10273 cx: &mut ViewContext<Self>,
10274 ) -> Task<Result<()>> {
10275 let buffer = self.buffer().clone();
10276 let mut buffers = buffer.read(cx).all_buffers();
10277 if trigger == FormatTrigger::Save {
10278 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10279 }
10280
10281 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10282 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10283
10284 cx.spawn(|_, mut cx| async move {
10285 let transaction = futures::select_biased! {
10286 () = timeout => {
10287 log::warn!("timed out waiting for formatting");
10288 None
10289 }
10290 transaction = format.log_err().fuse() => transaction,
10291 };
10292
10293 buffer
10294 .update(&mut cx, |buffer, cx| {
10295 if let Some(transaction) = transaction {
10296 if !buffer.is_singleton() {
10297 buffer.push_transaction(&transaction.0, cx);
10298 }
10299 }
10300
10301 cx.notify();
10302 })
10303 .ok();
10304
10305 Ok(())
10306 })
10307 }
10308
10309 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10310 if let Some(project) = self.project.clone() {
10311 self.buffer.update(cx, |multi_buffer, cx| {
10312 project.update(cx, |project, cx| {
10313 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10314 });
10315 })
10316 }
10317 }
10318
10319 fn cancel_language_server_work(
10320 &mut self,
10321 _: &CancelLanguageServerWork,
10322 cx: &mut ViewContext<Self>,
10323 ) {
10324 if let Some(project) = self.project.clone() {
10325 self.buffer.update(cx, |multi_buffer, cx| {
10326 project.update(cx, |project, cx| {
10327 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10328 });
10329 })
10330 }
10331 }
10332
10333 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10334 cx.show_character_palette();
10335 }
10336
10337 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10338 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10339 let buffer = self.buffer.read(cx).snapshot(cx);
10340 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10341 let is_valid = buffer
10342 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10343 .any(|entry| {
10344 entry.diagnostic.is_primary
10345 && !entry.range.is_empty()
10346 && entry.range.start == primary_range_start
10347 && entry.diagnostic.message == active_diagnostics.primary_message
10348 });
10349
10350 if is_valid != active_diagnostics.is_valid {
10351 active_diagnostics.is_valid = is_valid;
10352 let mut new_styles = HashMap::default();
10353 for (block_id, diagnostic) in &active_diagnostics.blocks {
10354 new_styles.insert(
10355 *block_id,
10356 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10357 );
10358 }
10359 self.display_map.update(cx, |display_map, _cx| {
10360 display_map.replace_blocks(new_styles)
10361 });
10362 }
10363 }
10364 }
10365
10366 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10367 self.dismiss_diagnostics(cx);
10368 let snapshot = self.snapshot(cx);
10369 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10370 let buffer = self.buffer.read(cx).snapshot(cx);
10371
10372 let mut primary_range = None;
10373 let mut primary_message = None;
10374 let mut group_end = Point::zero();
10375 let diagnostic_group = buffer
10376 .diagnostic_group::<MultiBufferPoint>(group_id)
10377 .filter_map(|entry| {
10378 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10379 && (entry.range.start.row == entry.range.end.row
10380 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10381 {
10382 return None;
10383 }
10384 if entry.range.end > group_end {
10385 group_end = entry.range.end;
10386 }
10387 if entry.diagnostic.is_primary {
10388 primary_range = Some(entry.range.clone());
10389 primary_message = Some(entry.diagnostic.message.clone());
10390 }
10391 Some(entry)
10392 })
10393 .collect::<Vec<_>>();
10394 let primary_range = primary_range?;
10395 let primary_message = primary_message?;
10396 let primary_range =
10397 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10398
10399 let blocks = display_map
10400 .insert_blocks(
10401 diagnostic_group.iter().map(|entry| {
10402 let diagnostic = entry.diagnostic.clone();
10403 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10404 BlockProperties {
10405 style: BlockStyle::Fixed,
10406 position: buffer.anchor_after(entry.range.start),
10407 height: message_height,
10408 render: diagnostic_block_renderer(diagnostic, None, true, true),
10409 disposition: BlockDisposition::Below,
10410 priority: 0,
10411 }
10412 }),
10413 cx,
10414 )
10415 .into_iter()
10416 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10417 .collect();
10418
10419 Some(ActiveDiagnosticGroup {
10420 primary_range,
10421 primary_message,
10422 group_id,
10423 blocks,
10424 is_valid: true,
10425 })
10426 });
10427 self.active_diagnostics.is_some()
10428 }
10429
10430 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10431 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10432 self.display_map.update(cx, |display_map, cx| {
10433 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10434 });
10435 cx.notify();
10436 }
10437 }
10438
10439 pub fn set_selections_from_remote(
10440 &mut self,
10441 selections: Vec<Selection<Anchor>>,
10442 pending_selection: Option<Selection<Anchor>>,
10443 cx: &mut ViewContext<Self>,
10444 ) {
10445 let old_cursor_position = self.selections.newest_anchor().head();
10446 self.selections.change_with(cx, |s| {
10447 s.select_anchors(selections);
10448 if let Some(pending_selection) = pending_selection {
10449 s.set_pending(pending_selection, SelectMode::Character);
10450 } else {
10451 s.clear_pending();
10452 }
10453 });
10454 self.selections_did_change(false, &old_cursor_position, true, cx);
10455 }
10456
10457 fn push_to_selection_history(&mut self) {
10458 self.selection_history.push(SelectionHistoryEntry {
10459 selections: self.selections.disjoint_anchors(),
10460 select_next_state: self.select_next_state.clone(),
10461 select_prev_state: self.select_prev_state.clone(),
10462 add_selections_state: self.add_selections_state.clone(),
10463 });
10464 }
10465
10466 pub fn transact(
10467 &mut self,
10468 cx: &mut ViewContext<Self>,
10469 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10470 ) -> Option<TransactionId> {
10471 self.start_transaction_at(Instant::now(), cx);
10472 update(self, cx);
10473 self.end_transaction_at(Instant::now(), cx)
10474 }
10475
10476 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10477 self.end_selection(cx);
10478 if let Some(tx_id) = self
10479 .buffer
10480 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10481 {
10482 self.selection_history
10483 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10484 cx.emit(EditorEvent::TransactionBegun {
10485 transaction_id: tx_id,
10486 })
10487 }
10488 }
10489
10490 fn end_transaction_at(
10491 &mut self,
10492 now: Instant,
10493 cx: &mut ViewContext<Self>,
10494 ) -> Option<TransactionId> {
10495 if let Some(transaction_id) = self
10496 .buffer
10497 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10498 {
10499 if let Some((_, end_selections)) =
10500 self.selection_history.transaction_mut(transaction_id)
10501 {
10502 *end_selections = Some(self.selections.disjoint_anchors());
10503 } else {
10504 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10505 }
10506
10507 cx.emit(EditorEvent::Edited { transaction_id });
10508 Some(transaction_id)
10509 } else {
10510 None
10511 }
10512 }
10513
10514 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10515 let mut fold_ranges = Vec::new();
10516
10517 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10518
10519 let selections = self.selections.all_adjusted(cx);
10520 for selection in selections {
10521 let range = selection.range().sorted();
10522 let buffer_start_row = range.start.row;
10523
10524 for row in (0..=range.end.row).rev() {
10525 if let Some((foldable_range, fold_text)) =
10526 display_map.foldable_range(MultiBufferRow(row))
10527 {
10528 if foldable_range.end.row >= buffer_start_row {
10529 fold_ranges.push((foldable_range, fold_text));
10530 if row <= range.start.row {
10531 break;
10532 }
10533 }
10534 }
10535 }
10536 }
10537
10538 self.fold_ranges(fold_ranges, true, cx);
10539 }
10540
10541 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10542 let buffer_row = fold_at.buffer_row;
10543 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10544
10545 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10546 let autoscroll = self
10547 .selections
10548 .all::<Point>(cx)
10549 .iter()
10550 .any(|selection| fold_range.overlaps(&selection.range()));
10551
10552 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10553 }
10554 }
10555
10556 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10557 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10558 let buffer = &display_map.buffer_snapshot;
10559 let selections = self.selections.all::<Point>(cx);
10560 let ranges = selections
10561 .iter()
10562 .map(|s| {
10563 let range = s.display_range(&display_map).sorted();
10564 let mut start = range.start.to_point(&display_map);
10565 let mut end = range.end.to_point(&display_map);
10566 start.column = 0;
10567 end.column = buffer.line_len(MultiBufferRow(end.row));
10568 start..end
10569 })
10570 .collect::<Vec<_>>();
10571
10572 self.unfold_ranges(ranges, true, true, cx);
10573 }
10574
10575 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10576 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10577
10578 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10579 ..Point::new(
10580 unfold_at.buffer_row.0,
10581 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10582 );
10583
10584 let autoscroll = self
10585 .selections
10586 .all::<Point>(cx)
10587 .iter()
10588 .any(|selection| selection.range().overlaps(&intersection_range));
10589
10590 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10591 }
10592
10593 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10594 let selections = self.selections.all::<Point>(cx);
10595 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10596 let line_mode = self.selections.line_mode;
10597 let ranges = selections.into_iter().map(|s| {
10598 if line_mode {
10599 let start = Point::new(s.start.row, 0);
10600 let end = Point::new(
10601 s.end.row,
10602 display_map
10603 .buffer_snapshot
10604 .line_len(MultiBufferRow(s.end.row)),
10605 );
10606 (start..end, display_map.fold_placeholder.clone())
10607 } else {
10608 (s.start..s.end, display_map.fold_placeholder.clone())
10609 }
10610 });
10611 self.fold_ranges(ranges, true, cx);
10612 }
10613
10614 pub fn fold_ranges<T: ToOffset + Clone>(
10615 &mut self,
10616 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10617 auto_scroll: bool,
10618 cx: &mut ViewContext<Self>,
10619 ) {
10620 let mut fold_ranges = Vec::new();
10621 let mut buffers_affected = HashMap::default();
10622 let multi_buffer = self.buffer().read(cx);
10623 for (fold_range, fold_text) in ranges {
10624 if let Some((_, buffer, _)) =
10625 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10626 {
10627 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10628 };
10629 fold_ranges.push((fold_range, fold_text));
10630 }
10631
10632 let mut ranges = fold_ranges.into_iter().peekable();
10633 if ranges.peek().is_some() {
10634 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10635
10636 if auto_scroll {
10637 self.request_autoscroll(Autoscroll::fit(), cx);
10638 }
10639
10640 for buffer in buffers_affected.into_values() {
10641 self.sync_expanded_diff_hunks(buffer, cx);
10642 }
10643
10644 cx.notify();
10645
10646 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10647 // Clear diagnostics block when folding a range that contains it.
10648 let snapshot = self.snapshot(cx);
10649 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10650 drop(snapshot);
10651 self.active_diagnostics = Some(active_diagnostics);
10652 self.dismiss_diagnostics(cx);
10653 } else {
10654 self.active_diagnostics = Some(active_diagnostics);
10655 }
10656 }
10657
10658 self.scrollbar_marker_state.dirty = true;
10659 }
10660 }
10661
10662 pub fn unfold_ranges<T: ToOffset + Clone>(
10663 &mut self,
10664 ranges: impl IntoIterator<Item = Range<T>>,
10665 inclusive: bool,
10666 auto_scroll: bool,
10667 cx: &mut ViewContext<Self>,
10668 ) {
10669 let mut unfold_ranges = Vec::new();
10670 let mut buffers_affected = HashMap::default();
10671 let multi_buffer = self.buffer().read(cx);
10672 for range in ranges {
10673 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10674 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10675 };
10676 unfold_ranges.push(range);
10677 }
10678
10679 let mut ranges = unfold_ranges.into_iter().peekable();
10680 if ranges.peek().is_some() {
10681 self.display_map
10682 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10683 if auto_scroll {
10684 self.request_autoscroll(Autoscroll::fit(), cx);
10685 }
10686
10687 for buffer in buffers_affected.into_values() {
10688 self.sync_expanded_diff_hunks(buffer, cx);
10689 }
10690
10691 cx.notify();
10692 self.scrollbar_marker_state.dirty = true;
10693 self.active_indent_guides_state.dirty = true;
10694 }
10695 }
10696
10697 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10698 self.display_map.read(cx).fold_placeholder.clone()
10699 }
10700
10701 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10702 if hovered != self.gutter_hovered {
10703 self.gutter_hovered = hovered;
10704 cx.notify();
10705 }
10706 }
10707
10708 pub fn insert_blocks(
10709 &mut self,
10710 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10711 autoscroll: Option<Autoscroll>,
10712 cx: &mut ViewContext<Self>,
10713 ) -> Vec<CustomBlockId> {
10714 let blocks = self
10715 .display_map
10716 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10717 if let Some(autoscroll) = autoscroll {
10718 self.request_autoscroll(autoscroll, cx);
10719 }
10720 cx.notify();
10721 blocks
10722 }
10723
10724 pub fn resize_blocks(
10725 &mut self,
10726 heights: HashMap<CustomBlockId, u32>,
10727 autoscroll: Option<Autoscroll>,
10728 cx: &mut ViewContext<Self>,
10729 ) {
10730 self.display_map
10731 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10732 if let Some(autoscroll) = autoscroll {
10733 self.request_autoscroll(autoscroll, cx);
10734 }
10735 cx.notify();
10736 }
10737
10738 pub fn replace_blocks(
10739 &mut self,
10740 renderers: HashMap<CustomBlockId, RenderBlock>,
10741 autoscroll: Option<Autoscroll>,
10742 cx: &mut ViewContext<Self>,
10743 ) {
10744 self.display_map
10745 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10746 if let Some(autoscroll) = autoscroll {
10747 self.request_autoscroll(autoscroll, cx);
10748 }
10749 cx.notify();
10750 }
10751
10752 pub fn remove_blocks(
10753 &mut self,
10754 block_ids: HashSet<CustomBlockId>,
10755 autoscroll: Option<Autoscroll>,
10756 cx: &mut ViewContext<Self>,
10757 ) {
10758 self.display_map.update(cx, |display_map, cx| {
10759 display_map.remove_blocks(block_ids, cx)
10760 });
10761 if let Some(autoscroll) = autoscroll {
10762 self.request_autoscroll(autoscroll, cx);
10763 }
10764 cx.notify();
10765 }
10766
10767 pub fn row_for_block(
10768 &self,
10769 block_id: CustomBlockId,
10770 cx: &mut ViewContext<Self>,
10771 ) -> Option<DisplayRow> {
10772 self.display_map
10773 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10774 }
10775
10776 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10777 self.focused_block = Some(focused_block);
10778 }
10779
10780 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10781 self.focused_block.take()
10782 }
10783
10784 pub fn insert_creases(
10785 &mut self,
10786 creases: impl IntoIterator<Item = Crease>,
10787 cx: &mut ViewContext<Self>,
10788 ) -> Vec<CreaseId> {
10789 self.display_map
10790 .update(cx, |map, cx| map.insert_creases(creases, cx))
10791 }
10792
10793 pub fn remove_creases(
10794 &mut self,
10795 ids: impl IntoIterator<Item = CreaseId>,
10796 cx: &mut ViewContext<Self>,
10797 ) {
10798 self.display_map
10799 .update(cx, |map, cx| map.remove_creases(ids, cx));
10800 }
10801
10802 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10803 self.display_map
10804 .update(cx, |map, cx| map.snapshot(cx))
10805 .longest_row()
10806 }
10807
10808 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10809 self.display_map
10810 .update(cx, |map, cx| map.snapshot(cx))
10811 .max_point()
10812 }
10813
10814 pub fn text(&self, cx: &AppContext) -> String {
10815 self.buffer.read(cx).read(cx).text()
10816 }
10817
10818 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10819 let text = self.text(cx);
10820 let text = text.trim();
10821
10822 if text.is_empty() {
10823 return None;
10824 }
10825
10826 Some(text.to_string())
10827 }
10828
10829 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10830 self.transact(cx, |this, cx| {
10831 this.buffer
10832 .read(cx)
10833 .as_singleton()
10834 .expect("you can only call set_text on editors for singleton buffers")
10835 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10836 });
10837 }
10838
10839 pub fn display_text(&self, cx: &mut AppContext) -> String {
10840 self.display_map
10841 .update(cx, |map, cx| map.snapshot(cx))
10842 .text()
10843 }
10844
10845 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10846 let mut wrap_guides = smallvec::smallvec![];
10847
10848 if self.show_wrap_guides == Some(false) {
10849 return wrap_guides;
10850 }
10851
10852 let settings = self.buffer.read(cx).settings_at(0, cx);
10853 if settings.show_wrap_guides {
10854 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10855 wrap_guides.push((soft_wrap as usize, true));
10856 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10857 wrap_guides.push((soft_wrap as usize, true));
10858 }
10859 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10860 }
10861
10862 wrap_guides
10863 }
10864
10865 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10866 let settings = self.buffer.read(cx).settings_at(0, cx);
10867 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10868 match mode {
10869 language_settings::SoftWrap::None => SoftWrap::None,
10870 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10871 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10872 language_settings::SoftWrap::PreferredLineLength => {
10873 SoftWrap::Column(settings.preferred_line_length)
10874 }
10875 language_settings::SoftWrap::Bounded => {
10876 SoftWrap::Bounded(settings.preferred_line_length)
10877 }
10878 }
10879 }
10880
10881 pub fn set_soft_wrap_mode(
10882 &mut self,
10883 mode: language_settings::SoftWrap,
10884 cx: &mut ViewContext<Self>,
10885 ) {
10886 self.soft_wrap_mode_override = Some(mode);
10887 cx.notify();
10888 }
10889
10890 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10891 let rem_size = cx.rem_size();
10892 self.display_map.update(cx, |map, cx| {
10893 map.set_font(
10894 style.text.font(),
10895 style.text.font_size.to_pixels(rem_size),
10896 cx,
10897 )
10898 });
10899 self.style = Some(style);
10900 }
10901
10902 pub fn style(&self) -> Option<&EditorStyle> {
10903 self.style.as_ref()
10904 }
10905
10906 // Called by the element. This method is not designed to be called outside of the editor
10907 // element's layout code because it does not notify when rewrapping is computed synchronously.
10908 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10909 self.display_map
10910 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10911 }
10912
10913 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10914 if self.soft_wrap_mode_override.is_some() {
10915 self.soft_wrap_mode_override.take();
10916 } else {
10917 let soft_wrap = match self.soft_wrap_mode(cx) {
10918 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10919 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10920 language_settings::SoftWrap::PreferLine
10921 }
10922 };
10923 self.soft_wrap_mode_override = Some(soft_wrap);
10924 }
10925 cx.notify();
10926 }
10927
10928 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10929 let Some(workspace) = self.workspace() else {
10930 return;
10931 };
10932 let fs = workspace.read(cx).app_state().fs.clone();
10933 let current_show = TabBarSettings::get_global(cx).show;
10934 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10935 setting.show = Some(!current_show);
10936 });
10937 }
10938
10939 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10940 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10941 self.buffer
10942 .read(cx)
10943 .settings_at(0, cx)
10944 .indent_guides
10945 .enabled
10946 });
10947 self.show_indent_guides = Some(!currently_enabled);
10948 cx.notify();
10949 }
10950
10951 fn should_show_indent_guides(&self) -> Option<bool> {
10952 self.show_indent_guides
10953 }
10954
10955 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10956 let mut editor_settings = EditorSettings::get_global(cx).clone();
10957 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10958 EditorSettings::override_global(editor_settings, cx);
10959 }
10960
10961 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10962 self.use_relative_line_numbers
10963 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10964 }
10965
10966 pub fn toggle_relative_line_numbers(
10967 &mut self,
10968 _: &ToggleRelativeLineNumbers,
10969 cx: &mut ViewContext<Self>,
10970 ) {
10971 let is_relative = self.should_use_relative_line_numbers(cx);
10972 self.set_relative_line_number(Some(!is_relative), cx)
10973 }
10974
10975 pub fn set_relative_line_number(
10976 &mut self,
10977 is_relative: Option<bool>,
10978 cx: &mut ViewContext<Self>,
10979 ) {
10980 self.use_relative_line_numbers = is_relative;
10981 cx.notify();
10982 }
10983
10984 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10985 self.show_gutter = show_gutter;
10986 cx.notify();
10987 }
10988
10989 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10990 self.show_line_numbers = Some(show_line_numbers);
10991 cx.notify();
10992 }
10993
10994 pub fn set_show_git_diff_gutter(
10995 &mut self,
10996 show_git_diff_gutter: bool,
10997 cx: &mut ViewContext<Self>,
10998 ) {
10999 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11000 cx.notify();
11001 }
11002
11003 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11004 self.show_code_actions = Some(show_code_actions);
11005 cx.notify();
11006 }
11007
11008 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11009 self.show_runnables = Some(show_runnables);
11010 cx.notify();
11011 }
11012
11013 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11014 if self.display_map.read(cx).masked != masked {
11015 self.display_map.update(cx, |map, _| map.masked = masked);
11016 }
11017 cx.notify()
11018 }
11019
11020 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11021 self.show_wrap_guides = Some(show_wrap_guides);
11022 cx.notify();
11023 }
11024
11025 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11026 self.show_indent_guides = Some(show_indent_guides);
11027 cx.notify();
11028 }
11029
11030 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11031 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11032 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11033 if let Some(dir) = file.abs_path(cx).parent() {
11034 return Some(dir.to_owned());
11035 }
11036 }
11037
11038 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11039 return Some(project_path.path.to_path_buf());
11040 }
11041 }
11042
11043 None
11044 }
11045
11046 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11047 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11048 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11049 cx.reveal_path(&file.abs_path(cx));
11050 }
11051 }
11052 }
11053
11054 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11055 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11056 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11057 if let Some(path) = file.abs_path(cx).to_str() {
11058 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11059 }
11060 }
11061 }
11062 }
11063
11064 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11065 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11066 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11067 if let Some(path) = file.path().to_str() {
11068 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11069 }
11070 }
11071 }
11072 }
11073
11074 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11075 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11076
11077 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11078 self.start_git_blame(true, cx);
11079 }
11080
11081 cx.notify();
11082 }
11083
11084 pub fn toggle_git_blame_inline(
11085 &mut self,
11086 _: &ToggleGitBlameInline,
11087 cx: &mut ViewContext<Self>,
11088 ) {
11089 self.toggle_git_blame_inline_internal(true, cx);
11090 cx.notify();
11091 }
11092
11093 pub fn git_blame_inline_enabled(&self) -> bool {
11094 self.git_blame_inline_enabled
11095 }
11096
11097 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11098 self.show_selection_menu = self
11099 .show_selection_menu
11100 .map(|show_selections_menu| !show_selections_menu)
11101 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11102
11103 cx.notify();
11104 }
11105
11106 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11107 self.show_selection_menu
11108 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11109 }
11110
11111 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11112 if let Some(project) = self.project.as_ref() {
11113 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11114 return;
11115 };
11116
11117 if buffer.read(cx).file().is_none() {
11118 return;
11119 }
11120
11121 let focused = self.focus_handle(cx).contains_focused(cx);
11122
11123 let project = project.clone();
11124 let blame =
11125 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11126 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11127 self.blame = Some(blame);
11128 }
11129 }
11130
11131 fn toggle_git_blame_inline_internal(
11132 &mut self,
11133 user_triggered: bool,
11134 cx: &mut ViewContext<Self>,
11135 ) {
11136 if self.git_blame_inline_enabled {
11137 self.git_blame_inline_enabled = false;
11138 self.show_git_blame_inline = false;
11139 self.show_git_blame_inline_delay_task.take();
11140 } else {
11141 self.git_blame_inline_enabled = true;
11142 self.start_git_blame_inline(user_triggered, cx);
11143 }
11144
11145 cx.notify();
11146 }
11147
11148 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11149 self.start_git_blame(user_triggered, cx);
11150
11151 if ProjectSettings::get_global(cx)
11152 .git
11153 .inline_blame_delay()
11154 .is_some()
11155 {
11156 self.start_inline_blame_timer(cx);
11157 } else {
11158 self.show_git_blame_inline = true
11159 }
11160 }
11161
11162 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11163 self.blame.as_ref()
11164 }
11165
11166 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11167 self.show_git_blame_gutter && self.has_blame_entries(cx)
11168 }
11169
11170 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11171 self.show_git_blame_inline
11172 && self.focus_handle.is_focused(cx)
11173 && !self.newest_selection_head_on_empty_line(cx)
11174 && self.has_blame_entries(cx)
11175 }
11176
11177 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11178 self.blame()
11179 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11180 }
11181
11182 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11183 let cursor_anchor = self.selections.newest_anchor().head();
11184
11185 let snapshot = self.buffer.read(cx).snapshot(cx);
11186 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11187
11188 snapshot.line_len(buffer_row) == 0
11189 }
11190
11191 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11192 let (path, selection, repo) = maybe!({
11193 let project_handle = self.project.as_ref()?.clone();
11194 let project = project_handle.read(cx);
11195
11196 let selection = self.selections.newest::<Point>(cx);
11197 let selection_range = selection.range();
11198
11199 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11200 (buffer, selection_range.start.row..selection_range.end.row)
11201 } else {
11202 let buffer_ranges = self
11203 .buffer()
11204 .read(cx)
11205 .range_to_buffer_ranges(selection_range, cx);
11206
11207 let (buffer, range, _) = if selection.reversed {
11208 buffer_ranges.first()
11209 } else {
11210 buffer_ranges.last()
11211 }?;
11212
11213 let snapshot = buffer.read(cx).snapshot();
11214 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11215 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11216 (buffer.clone(), selection)
11217 };
11218
11219 let path = buffer
11220 .read(cx)
11221 .file()?
11222 .as_local()?
11223 .path()
11224 .to_str()?
11225 .to_string();
11226 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11227 Some((path, selection, repo))
11228 })
11229 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11230
11231 const REMOTE_NAME: &str = "origin";
11232 let origin_url = repo
11233 .remote_url(REMOTE_NAME)
11234 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11235 let sha = repo
11236 .head_sha()
11237 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11238
11239 let (provider, remote) =
11240 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11241 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11242
11243 Ok(provider.build_permalink(
11244 remote,
11245 BuildPermalinkParams {
11246 sha: &sha,
11247 path: &path,
11248 selection: Some(selection),
11249 },
11250 ))
11251 }
11252
11253 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11254 let permalink = self.get_permalink_to_line(cx);
11255
11256 match permalink {
11257 Ok(permalink) => {
11258 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11259 }
11260 Err(err) => {
11261 let message = format!("Failed to copy permalink: {err}");
11262
11263 Err::<(), anyhow::Error>(err).log_err();
11264
11265 if let Some(workspace) = self.workspace() {
11266 workspace.update(cx, |workspace, cx| {
11267 struct CopyPermalinkToLine;
11268
11269 workspace.show_toast(
11270 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11271 cx,
11272 )
11273 })
11274 }
11275 }
11276 }
11277 }
11278
11279 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11280 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11281 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11282 if let Some(path) = file.path().to_str() {
11283 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11284 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11285 }
11286 }
11287 }
11288 }
11289
11290 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11291 let permalink = self.get_permalink_to_line(cx);
11292
11293 match permalink {
11294 Ok(permalink) => {
11295 cx.open_url(permalink.as_ref());
11296 }
11297 Err(err) => {
11298 let message = format!("Failed to open permalink: {err}");
11299
11300 Err::<(), anyhow::Error>(err).log_err();
11301
11302 if let Some(workspace) = self.workspace() {
11303 workspace.update(cx, |workspace, cx| {
11304 struct OpenPermalinkToLine;
11305
11306 workspace.show_toast(
11307 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11308 cx,
11309 )
11310 })
11311 }
11312 }
11313 }
11314 }
11315
11316 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11317 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11318 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11319 pub fn highlight_rows<T: 'static>(
11320 &mut self,
11321 rows: RangeInclusive<Anchor>,
11322 color: Option<Hsla>,
11323 should_autoscroll: bool,
11324 cx: &mut ViewContext<Self>,
11325 ) {
11326 let snapshot = self.buffer().read(cx).snapshot(cx);
11327 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11328 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11329 highlight
11330 .range
11331 .start()
11332 .cmp(rows.start(), &snapshot)
11333 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11334 });
11335 match (color, existing_highlight_index) {
11336 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11337 ix,
11338 RowHighlight {
11339 index: post_inc(&mut self.highlight_order),
11340 range: rows,
11341 should_autoscroll,
11342 color,
11343 },
11344 ),
11345 (None, Ok(i)) => {
11346 row_highlights.remove(i);
11347 }
11348 }
11349 }
11350
11351 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11352 pub fn clear_row_highlights<T: 'static>(&mut self) {
11353 self.highlighted_rows.remove(&TypeId::of::<T>());
11354 }
11355
11356 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11357 pub fn highlighted_rows<T: 'static>(
11358 &self,
11359 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11360 Some(
11361 self.highlighted_rows
11362 .get(&TypeId::of::<T>())?
11363 .iter()
11364 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11365 )
11366 }
11367
11368 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11369 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11370 /// Allows to ignore certain kinds of highlights.
11371 pub fn highlighted_display_rows(
11372 &mut self,
11373 cx: &mut WindowContext,
11374 ) -> BTreeMap<DisplayRow, Hsla> {
11375 let snapshot = self.snapshot(cx);
11376 let mut used_highlight_orders = HashMap::default();
11377 self.highlighted_rows
11378 .iter()
11379 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11380 .fold(
11381 BTreeMap::<DisplayRow, Hsla>::new(),
11382 |mut unique_rows, highlight| {
11383 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11384 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11385 for row in start_row.0..=end_row.0 {
11386 let used_index =
11387 used_highlight_orders.entry(row).or_insert(highlight.index);
11388 if highlight.index >= *used_index {
11389 *used_index = highlight.index;
11390 match highlight.color {
11391 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11392 None => unique_rows.remove(&DisplayRow(row)),
11393 };
11394 }
11395 }
11396 unique_rows
11397 },
11398 )
11399 }
11400
11401 pub fn highlighted_display_row_for_autoscroll(
11402 &self,
11403 snapshot: &DisplaySnapshot,
11404 ) -> Option<DisplayRow> {
11405 self.highlighted_rows
11406 .values()
11407 .flat_map(|highlighted_rows| highlighted_rows.iter())
11408 .filter_map(|highlight| {
11409 if highlight.color.is_none() || !highlight.should_autoscroll {
11410 return None;
11411 }
11412 Some(highlight.range.start().to_display_point(snapshot).row())
11413 })
11414 .min()
11415 }
11416
11417 pub fn set_search_within_ranges(
11418 &mut self,
11419 ranges: &[Range<Anchor>],
11420 cx: &mut ViewContext<Self>,
11421 ) {
11422 self.highlight_background::<SearchWithinRange>(
11423 ranges,
11424 |colors| colors.editor_document_highlight_read_background,
11425 cx,
11426 )
11427 }
11428
11429 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11430 self.breadcrumb_header = Some(new_header);
11431 }
11432
11433 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11434 self.clear_background_highlights::<SearchWithinRange>(cx);
11435 }
11436
11437 pub fn highlight_background<T: 'static>(
11438 &mut self,
11439 ranges: &[Range<Anchor>],
11440 color_fetcher: fn(&ThemeColors) -> Hsla,
11441 cx: &mut ViewContext<Self>,
11442 ) {
11443 self.background_highlights
11444 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11445 self.scrollbar_marker_state.dirty = true;
11446 cx.notify();
11447 }
11448
11449 pub fn clear_background_highlights<T: 'static>(
11450 &mut self,
11451 cx: &mut ViewContext<Self>,
11452 ) -> Option<BackgroundHighlight> {
11453 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11454 if !text_highlights.1.is_empty() {
11455 self.scrollbar_marker_state.dirty = true;
11456 cx.notify();
11457 }
11458 Some(text_highlights)
11459 }
11460
11461 pub fn highlight_gutter<T: 'static>(
11462 &mut self,
11463 ranges: &[Range<Anchor>],
11464 color_fetcher: fn(&AppContext) -> Hsla,
11465 cx: &mut ViewContext<Self>,
11466 ) {
11467 self.gutter_highlights
11468 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11469 cx.notify();
11470 }
11471
11472 pub fn clear_gutter_highlights<T: 'static>(
11473 &mut self,
11474 cx: &mut ViewContext<Self>,
11475 ) -> Option<GutterHighlight> {
11476 cx.notify();
11477 self.gutter_highlights.remove(&TypeId::of::<T>())
11478 }
11479
11480 #[cfg(feature = "test-support")]
11481 pub fn all_text_background_highlights(
11482 &mut self,
11483 cx: &mut ViewContext<Self>,
11484 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11485 let snapshot = self.snapshot(cx);
11486 let buffer = &snapshot.buffer_snapshot;
11487 let start = buffer.anchor_before(0);
11488 let end = buffer.anchor_after(buffer.len());
11489 let theme = cx.theme().colors();
11490 self.background_highlights_in_range(start..end, &snapshot, theme)
11491 }
11492
11493 #[cfg(feature = "test-support")]
11494 pub fn search_background_highlights(
11495 &mut self,
11496 cx: &mut ViewContext<Self>,
11497 ) -> Vec<Range<Point>> {
11498 let snapshot = self.buffer().read(cx).snapshot(cx);
11499
11500 let highlights = self
11501 .background_highlights
11502 .get(&TypeId::of::<items::BufferSearchHighlights>());
11503
11504 if let Some((_color, ranges)) = highlights {
11505 ranges
11506 .iter()
11507 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11508 .collect_vec()
11509 } else {
11510 vec![]
11511 }
11512 }
11513
11514 fn document_highlights_for_position<'a>(
11515 &'a self,
11516 position: Anchor,
11517 buffer: &'a MultiBufferSnapshot,
11518 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11519 let read_highlights = self
11520 .background_highlights
11521 .get(&TypeId::of::<DocumentHighlightRead>())
11522 .map(|h| &h.1);
11523 let write_highlights = self
11524 .background_highlights
11525 .get(&TypeId::of::<DocumentHighlightWrite>())
11526 .map(|h| &h.1);
11527 let left_position = position.bias_left(buffer);
11528 let right_position = position.bias_right(buffer);
11529 read_highlights
11530 .into_iter()
11531 .chain(write_highlights)
11532 .flat_map(move |ranges| {
11533 let start_ix = match ranges.binary_search_by(|probe| {
11534 let cmp = probe.end.cmp(&left_position, buffer);
11535 if cmp.is_ge() {
11536 Ordering::Greater
11537 } else {
11538 Ordering::Less
11539 }
11540 }) {
11541 Ok(i) | Err(i) => i,
11542 };
11543
11544 ranges[start_ix..]
11545 .iter()
11546 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11547 })
11548 }
11549
11550 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11551 self.background_highlights
11552 .get(&TypeId::of::<T>())
11553 .map_or(false, |(_, highlights)| !highlights.is_empty())
11554 }
11555
11556 pub fn background_highlights_in_range(
11557 &self,
11558 search_range: Range<Anchor>,
11559 display_snapshot: &DisplaySnapshot,
11560 theme: &ThemeColors,
11561 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11562 let mut results = Vec::new();
11563 for (color_fetcher, ranges) in self.background_highlights.values() {
11564 let color = color_fetcher(theme);
11565 let start_ix = match ranges.binary_search_by(|probe| {
11566 let cmp = probe
11567 .end
11568 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11569 if cmp.is_gt() {
11570 Ordering::Greater
11571 } else {
11572 Ordering::Less
11573 }
11574 }) {
11575 Ok(i) | Err(i) => i,
11576 };
11577 for range in &ranges[start_ix..] {
11578 if range
11579 .start
11580 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11581 .is_ge()
11582 {
11583 break;
11584 }
11585
11586 let start = range.start.to_display_point(display_snapshot);
11587 let end = range.end.to_display_point(display_snapshot);
11588 results.push((start..end, color))
11589 }
11590 }
11591 results
11592 }
11593
11594 pub fn background_highlight_row_ranges<T: 'static>(
11595 &self,
11596 search_range: Range<Anchor>,
11597 display_snapshot: &DisplaySnapshot,
11598 count: usize,
11599 ) -> Vec<RangeInclusive<DisplayPoint>> {
11600 let mut results = Vec::new();
11601 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11602 return vec![];
11603 };
11604
11605 let start_ix = match ranges.binary_search_by(|probe| {
11606 let cmp = probe
11607 .end
11608 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11609 if cmp.is_gt() {
11610 Ordering::Greater
11611 } else {
11612 Ordering::Less
11613 }
11614 }) {
11615 Ok(i) | Err(i) => i,
11616 };
11617 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11618 if let (Some(start_display), Some(end_display)) = (start, end) {
11619 results.push(
11620 start_display.to_display_point(display_snapshot)
11621 ..=end_display.to_display_point(display_snapshot),
11622 );
11623 }
11624 };
11625 let mut start_row: Option<Point> = None;
11626 let mut end_row: Option<Point> = None;
11627 if ranges.len() > count {
11628 return Vec::new();
11629 }
11630 for range in &ranges[start_ix..] {
11631 if range
11632 .start
11633 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11634 .is_ge()
11635 {
11636 break;
11637 }
11638 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11639 if let Some(current_row) = &end_row {
11640 if end.row == current_row.row {
11641 continue;
11642 }
11643 }
11644 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11645 if start_row.is_none() {
11646 assert_eq!(end_row, None);
11647 start_row = Some(start);
11648 end_row = Some(end);
11649 continue;
11650 }
11651 if let Some(current_end) = end_row.as_mut() {
11652 if start.row > current_end.row + 1 {
11653 push_region(start_row, end_row);
11654 start_row = Some(start);
11655 end_row = Some(end);
11656 } else {
11657 // Merge two hunks.
11658 *current_end = end;
11659 }
11660 } else {
11661 unreachable!();
11662 }
11663 }
11664 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11665 push_region(start_row, end_row);
11666 results
11667 }
11668
11669 pub fn gutter_highlights_in_range(
11670 &self,
11671 search_range: Range<Anchor>,
11672 display_snapshot: &DisplaySnapshot,
11673 cx: &AppContext,
11674 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11675 let mut results = Vec::new();
11676 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11677 let color = color_fetcher(cx);
11678 let start_ix = match ranges.binary_search_by(|probe| {
11679 let cmp = probe
11680 .end
11681 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11682 if cmp.is_gt() {
11683 Ordering::Greater
11684 } else {
11685 Ordering::Less
11686 }
11687 }) {
11688 Ok(i) | Err(i) => i,
11689 };
11690 for range in &ranges[start_ix..] {
11691 if range
11692 .start
11693 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11694 .is_ge()
11695 {
11696 break;
11697 }
11698
11699 let start = range.start.to_display_point(display_snapshot);
11700 let end = range.end.to_display_point(display_snapshot);
11701 results.push((start..end, color))
11702 }
11703 }
11704 results
11705 }
11706
11707 /// Get the text ranges corresponding to the redaction query
11708 pub fn redacted_ranges(
11709 &self,
11710 search_range: Range<Anchor>,
11711 display_snapshot: &DisplaySnapshot,
11712 cx: &WindowContext,
11713 ) -> Vec<Range<DisplayPoint>> {
11714 display_snapshot
11715 .buffer_snapshot
11716 .redacted_ranges(search_range, |file| {
11717 if let Some(file) = file {
11718 file.is_private()
11719 && EditorSettings::get(
11720 Some(SettingsLocation {
11721 worktree_id: file.worktree_id(cx),
11722 path: file.path().as_ref(),
11723 }),
11724 cx,
11725 )
11726 .redact_private_values
11727 } else {
11728 false
11729 }
11730 })
11731 .map(|range| {
11732 range.start.to_display_point(display_snapshot)
11733 ..range.end.to_display_point(display_snapshot)
11734 })
11735 .collect()
11736 }
11737
11738 pub fn highlight_text<T: 'static>(
11739 &mut self,
11740 ranges: Vec<Range<Anchor>>,
11741 style: HighlightStyle,
11742 cx: &mut ViewContext<Self>,
11743 ) {
11744 self.display_map.update(cx, |map, _| {
11745 map.highlight_text(TypeId::of::<T>(), ranges, style)
11746 });
11747 cx.notify();
11748 }
11749
11750 pub(crate) fn highlight_inlays<T: 'static>(
11751 &mut self,
11752 highlights: Vec<InlayHighlight>,
11753 style: HighlightStyle,
11754 cx: &mut ViewContext<Self>,
11755 ) {
11756 self.display_map.update(cx, |map, _| {
11757 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11758 });
11759 cx.notify();
11760 }
11761
11762 pub fn text_highlights<'a, T: 'static>(
11763 &'a self,
11764 cx: &'a AppContext,
11765 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11766 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11767 }
11768
11769 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11770 let cleared = self
11771 .display_map
11772 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11773 if cleared {
11774 cx.notify();
11775 }
11776 }
11777
11778 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11779 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11780 && self.focus_handle.is_focused(cx)
11781 }
11782
11783 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11784 self.show_cursor_when_unfocused = is_enabled;
11785 cx.notify();
11786 }
11787
11788 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11789 cx.notify();
11790 }
11791
11792 fn on_buffer_event(
11793 &mut self,
11794 multibuffer: Model<MultiBuffer>,
11795 event: &multi_buffer::Event,
11796 cx: &mut ViewContext<Self>,
11797 ) {
11798 match event {
11799 multi_buffer::Event::Edited {
11800 singleton_buffer_edited,
11801 } => {
11802 self.scrollbar_marker_state.dirty = true;
11803 self.active_indent_guides_state.dirty = true;
11804 self.refresh_active_diagnostics(cx);
11805 self.refresh_code_actions(cx);
11806 if self.has_active_inline_completion(cx) {
11807 self.update_visible_inline_completion(cx);
11808 }
11809 cx.emit(EditorEvent::BufferEdited);
11810 cx.emit(SearchEvent::MatchesInvalidated);
11811 if *singleton_buffer_edited {
11812 if let Some(project) = &self.project {
11813 let project = project.read(cx);
11814 #[allow(clippy::mutable_key_type)]
11815 let languages_affected = multibuffer
11816 .read(cx)
11817 .all_buffers()
11818 .into_iter()
11819 .filter_map(|buffer| {
11820 let buffer = buffer.read(cx);
11821 let language = buffer.language()?;
11822 if project.is_local()
11823 && project.language_servers_for_buffer(buffer, cx).count() == 0
11824 {
11825 None
11826 } else {
11827 Some(language)
11828 }
11829 })
11830 .cloned()
11831 .collect::<HashSet<_>>();
11832 if !languages_affected.is_empty() {
11833 self.refresh_inlay_hints(
11834 InlayHintRefreshReason::BufferEdited(languages_affected),
11835 cx,
11836 );
11837 }
11838 }
11839 }
11840
11841 let Some(project) = &self.project else { return };
11842 let telemetry = project.read(cx).client().telemetry().clone();
11843 refresh_linked_ranges(self, cx);
11844 telemetry.log_edit_event("editor");
11845 }
11846 multi_buffer::Event::ExcerptsAdded {
11847 buffer,
11848 predecessor,
11849 excerpts,
11850 } => {
11851 self.tasks_update_task = Some(self.refresh_runnables(cx));
11852 cx.emit(EditorEvent::ExcerptsAdded {
11853 buffer: buffer.clone(),
11854 predecessor: *predecessor,
11855 excerpts: excerpts.clone(),
11856 });
11857 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11858 }
11859 multi_buffer::Event::ExcerptsRemoved { ids } => {
11860 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11861 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11862 }
11863 multi_buffer::Event::ExcerptsEdited { ids } => {
11864 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11865 }
11866 multi_buffer::Event::ExcerptsExpanded { ids } => {
11867 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11868 }
11869 multi_buffer::Event::Reparsed(buffer_id) => {
11870 self.tasks_update_task = Some(self.refresh_runnables(cx));
11871
11872 cx.emit(EditorEvent::Reparsed(*buffer_id));
11873 }
11874 multi_buffer::Event::LanguageChanged(buffer_id) => {
11875 linked_editing_ranges::refresh_linked_ranges(self, cx);
11876 cx.emit(EditorEvent::Reparsed(*buffer_id));
11877 cx.notify();
11878 }
11879 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11880 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11881 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11882 cx.emit(EditorEvent::TitleChanged)
11883 }
11884 multi_buffer::Event::DiffBaseChanged => {
11885 self.scrollbar_marker_state.dirty = true;
11886 cx.emit(EditorEvent::DiffBaseChanged);
11887 cx.notify();
11888 }
11889 multi_buffer::Event::DiffUpdated { buffer } => {
11890 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11891 cx.notify();
11892 }
11893 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11894 multi_buffer::Event::DiagnosticsUpdated => {
11895 self.refresh_active_diagnostics(cx);
11896 self.scrollbar_marker_state.dirty = true;
11897 cx.notify();
11898 }
11899 _ => {}
11900 };
11901 }
11902
11903 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11904 cx.notify();
11905 }
11906
11907 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11908 self.tasks_update_task = Some(self.refresh_runnables(cx));
11909 self.refresh_inline_completion(true, false, cx);
11910 self.refresh_inlay_hints(
11911 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11912 self.selections.newest_anchor().head(),
11913 &self.buffer.read(cx).snapshot(cx),
11914 cx,
11915 )),
11916 cx,
11917 );
11918 let editor_settings = EditorSettings::get_global(cx);
11919 if let Some(cursor_shape) = editor_settings.cursor_shape {
11920 self.cursor_shape = cursor_shape;
11921 }
11922 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11923 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11924
11925 let project_settings = ProjectSettings::get_global(cx);
11926 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11927
11928 if self.mode == EditorMode::Full {
11929 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11930 if self.git_blame_inline_enabled != inline_blame_enabled {
11931 self.toggle_git_blame_inline_internal(false, cx);
11932 }
11933 }
11934
11935 cx.notify();
11936 }
11937
11938 pub fn set_searchable(&mut self, searchable: bool) {
11939 self.searchable = searchable;
11940 }
11941
11942 pub fn searchable(&self) -> bool {
11943 self.searchable
11944 }
11945
11946 fn open_proposed_changes_editor(
11947 &mut self,
11948 _: &OpenProposedChangesEditor,
11949 cx: &mut ViewContext<Self>,
11950 ) {
11951 let Some(workspace) = self.workspace() else {
11952 cx.propagate();
11953 return;
11954 };
11955
11956 let buffer = self.buffer.read(cx);
11957 let mut new_selections_by_buffer = HashMap::default();
11958 for selection in self.selections.all::<usize>(cx) {
11959 for (buffer, mut range, _) in
11960 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11961 {
11962 if selection.reversed {
11963 mem::swap(&mut range.start, &mut range.end);
11964 }
11965 let mut range = range.to_point(buffer.read(cx));
11966 range.start.column = 0;
11967 range.end.column = buffer.read(cx).line_len(range.end.row);
11968 new_selections_by_buffer
11969 .entry(buffer)
11970 .or_insert(Vec::new())
11971 .push(range)
11972 }
11973 }
11974
11975 let proposed_changes_buffers = new_selections_by_buffer
11976 .into_iter()
11977 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
11978 .collect::<Vec<_>>();
11979 let proposed_changes_editor = cx.new_view(|cx| {
11980 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
11981 });
11982
11983 cx.window_context().defer(move |cx| {
11984 workspace.update(cx, |workspace, cx| {
11985 workspace.active_pane().update(cx, |pane, cx| {
11986 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
11987 });
11988 });
11989 });
11990 }
11991
11992 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11993 self.open_excerpts_common(true, cx)
11994 }
11995
11996 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11997 self.open_excerpts_common(false, cx)
11998 }
11999
12000 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12001 let buffer = self.buffer.read(cx);
12002 if buffer.is_singleton() {
12003 cx.propagate();
12004 return;
12005 }
12006
12007 let Some(workspace) = self.workspace() else {
12008 cx.propagate();
12009 return;
12010 };
12011
12012 let mut new_selections_by_buffer = HashMap::default();
12013 for selection in self.selections.all::<usize>(cx) {
12014 for (buffer, mut range, _) in
12015 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12016 {
12017 if selection.reversed {
12018 mem::swap(&mut range.start, &mut range.end);
12019 }
12020 new_selections_by_buffer
12021 .entry(buffer)
12022 .or_insert(Vec::new())
12023 .push(range)
12024 }
12025 }
12026
12027 // We defer the pane interaction because we ourselves are a workspace item
12028 // and activating a new item causes the pane to call a method on us reentrantly,
12029 // which panics if we're on the stack.
12030 cx.window_context().defer(move |cx| {
12031 workspace.update(cx, |workspace, cx| {
12032 let pane = if split {
12033 workspace.adjacent_pane(cx)
12034 } else {
12035 workspace.active_pane().clone()
12036 };
12037
12038 for (buffer, ranges) in new_selections_by_buffer {
12039 let editor =
12040 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12041 editor.update(cx, |editor, cx| {
12042 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12043 s.select_ranges(ranges);
12044 });
12045 });
12046 }
12047 })
12048 });
12049 }
12050
12051 fn jump(
12052 &mut self,
12053 path: ProjectPath,
12054 position: Point,
12055 anchor: language::Anchor,
12056 offset_from_top: u32,
12057 cx: &mut ViewContext<Self>,
12058 ) {
12059 let workspace = self.workspace();
12060 cx.spawn(|_, mut cx| async move {
12061 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12062 let editor = workspace.update(&mut cx, |workspace, cx| {
12063 // Reset the preview item id before opening the new item
12064 workspace.active_pane().update(cx, |pane, cx| {
12065 pane.set_preview_item_id(None, cx);
12066 });
12067 workspace.open_path_preview(path, None, true, true, cx)
12068 })?;
12069 let editor = editor
12070 .await?
12071 .downcast::<Editor>()
12072 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12073 .downgrade();
12074 editor.update(&mut cx, |editor, cx| {
12075 let buffer = editor
12076 .buffer()
12077 .read(cx)
12078 .as_singleton()
12079 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12080 let buffer = buffer.read(cx);
12081 let cursor = if buffer.can_resolve(&anchor) {
12082 language::ToPoint::to_point(&anchor, buffer)
12083 } else {
12084 buffer.clip_point(position, Bias::Left)
12085 };
12086
12087 let nav_history = editor.nav_history.take();
12088 editor.change_selections(
12089 Some(Autoscroll::top_relative(offset_from_top as usize)),
12090 cx,
12091 |s| {
12092 s.select_ranges([cursor..cursor]);
12093 },
12094 );
12095 editor.nav_history = nav_history;
12096
12097 anyhow::Ok(())
12098 })??;
12099
12100 anyhow::Ok(())
12101 })
12102 .detach_and_log_err(cx);
12103 }
12104
12105 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12106 let snapshot = self.buffer.read(cx).read(cx);
12107 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12108 Some(
12109 ranges
12110 .iter()
12111 .map(move |range| {
12112 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12113 })
12114 .collect(),
12115 )
12116 }
12117
12118 fn selection_replacement_ranges(
12119 &self,
12120 range: Range<OffsetUtf16>,
12121 cx: &AppContext,
12122 ) -> Vec<Range<OffsetUtf16>> {
12123 let selections = self.selections.all::<OffsetUtf16>(cx);
12124 let newest_selection = selections
12125 .iter()
12126 .max_by_key(|selection| selection.id)
12127 .unwrap();
12128 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12129 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12130 let snapshot = self.buffer.read(cx).read(cx);
12131 selections
12132 .into_iter()
12133 .map(|mut selection| {
12134 selection.start.0 =
12135 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12136 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12137 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12138 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12139 })
12140 .collect()
12141 }
12142
12143 fn report_editor_event(
12144 &self,
12145 operation: &'static str,
12146 file_extension: Option<String>,
12147 cx: &AppContext,
12148 ) {
12149 if cfg!(any(test, feature = "test-support")) {
12150 return;
12151 }
12152
12153 let Some(project) = &self.project else { return };
12154
12155 // If None, we are in a file without an extension
12156 let file = self
12157 .buffer
12158 .read(cx)
12159 .as_singleton()
12160 .and_then(|b| b.read(cx).file());
12161 let file_extension = file_extension.or(file
12162 .as_ref()
12163 .and_then(|file| Path::new(file.file_name(cx)).extension())
12164 .and_then(|e| e.to_str())
12165 .map(|a| a.to_string()));
12166
12167 let vim_mode = cx
12168 .global::<SettingsStore>()
12169 .raw_user_settings()
12170 .get("vim_mode")
12171 == Some(&serde_json::Value::Bool(true));
12172
12173 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12174 == language::language_settings::InlineCompletionProvider::Copilot;
12175 let copilot_enabled_for_language = self
12176 .buffer
12177 .read(cx)
12178 .settings_at(0, cx)
12179 .show_inline_completions;
12180
12181 let telemetry = project.read(cx).client().telemetry().clone();
12182 telemetry.report_editor_event(
12183 file_extension,
12184 vim_mode,
12185 operation,
12186 copilot_enabled,
12187 copilot_enabled_for_language,
12188 )
12189 }
12190
12191 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12192 /// with each line being an array of {text, highlight} objects.
12193 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12194 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12195 return;
12196 };
12197
12198 #[derive(Serialize)]
12199 struct Chunk<'a> {
12200 text: String,
12201 highlight: Option<&'a str>,
12202 }
12203
12204 let snapshot = buffer.read(cx).snapshot();
12205 let range = self
12206 .selected_text_range(false, cx)
12207 .and_then(|selection| {
12208 if selection.range.is_empty() {
12209 None
12210 } else {
12211 Some(selection.range)
12212 }
12213 })
12214 .unwrap_or_else(|| 0..snapshot.len());
12215
12216 let chunks = snapshot.chunks(range, true);
12217 let mut lines = Vec::new();
12218 let mut line: VecDeque<Chunk> = VecDeque::new();
12219
12220 let Some(style) = self.style.as_ref() else {
12221 return;
12222 };
12223
12224 for chunk in chunks {
12225 let highlight = chunk
12226 .syntax_highlight_id
12227 .and_then(|id| id.name(&style.syntax));
12228 let mut chunk_lines = chunk.text.split('\n').peekable();
12229 while let Some(text) = chunk_lines.next() {
12230 let mut merged_with_last_token = false;
12231 if let Some(last_token) = line.back_mut() {
12232 if last_token.highlight == highlight {
12233 last_token.text.push_str(text);
12234 merged_with_last_token = true;
12235 }
12236 }
12237
12238 if !merged_with_last_token {
12239 line.push_back(Chunk {
12240 text: text.into(),
12241 highlight,
12242 });
12243 }
12244
12245 if chunk_lines.peek().is_some() {
12246 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12247 line.pop_front();
12248 }
12249 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12250 line.pop_back();
12251 }
12252
12253 lines.push(mem::take(&mut line));
12254 }
12255 }
12256 }
12257
12258 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12259 return;
12260 };
12261 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12262 }
12263
12264 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12265 &self.inlay_hint_cache
12266 }
12267
12268 pub fn replay_insert_event(
12269 &mut self,
12270 text: &str,
12271 relative_utf16_range: Option<Range<isize>>,
12272 cx: &mut ViewContext<Self>,
12273 ) {
12274 if !self.input_enabled {
12275 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12276 return;
12277 }
12278 if let Some(relative_utf16_range) = relative_utf16_range {
12279 let selections = self.selections.all::<OffsetUtf16>(cx);
12280 self.change_selections(None, cx, |s| {
12281 let new_ranges = selections.into_iter().map(|range| {
12282 let start = OffsetUtf16(
12283 range
12284 .head()
12285 .0
12286 .saturating_add_signed(relative_utf16_range.start),
12287 );
12288 let end = OffsetUtf16(
12289 range
12290 .head()
12291 .0
12292 .saturating_add_signed(relative_utf16_range.end),
12293 );
12294 start..end
12295 });
12296 s.select_ranges(new_ranges);
12297 });
12298 }
12299
12300 self.handle_input(text, cx);
12301 }
12302
12303 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12304 let Some(project) = self.project.as_ref() else {
12305 return false;
12306 };
12307 let project = project.read(cx);
12308
12309 let mut supports = false;
12310 self.buffer().read(cx).for_each_buffer(|buffer| {
12311 if !supports {
12312 supports = project
12313 .language_servers_for_buffer(buffer.read(cx), cx)
12314 .any(
12315 |(_, server)| match server.capabilities().inlay_hint_provider {
12316 Some(lsp::OneOf::Left(enabled)) => enabled,
12317 Some(lsp::OneOf::Right(_)) => true,
12318 None => false,
12319 },
12320 )
12321 }
12322 });
12323 supports
12324 }
12325
12326 pub fn focus(&self, cx: &mut WindowContext) {
12327 cx.focus(&self.focus_handle)
12328 }
12329
12330 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12331 self.focus_handle.is_focused(cx)
12332 }
12333
12334 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12335 cx.emit(EditorEvent::Focused);
12336
12337 if let Some(descendant) = self
12338 .last_focused_descendant
12339 .take()
12340 .and_then(|descendant| descendant.upgrade())
12341 {
12342 cx.focus(&descendant);
12343 } else {
12344 if let Some(blame) = self.blame.as_ref() {
12345 blame.update(cx, GitBlame::focus)
12346 }
12347
12348 self.blink_manager.update(cx, BlinkManager::enable);
12349 self.show_cursor_names(cx);
12350 self.buffer.update(cx, |buffer, cx| {
12351 buffer.finalize_last_transaction(cx);
12352 if self.leader_peer_id.is_none() {
12353 buffer.set_active_selections(
12354 &self.selections.disjoint_anchors(),
12355 self.selections.line_mode,
12356 self.cursor_shape,
12357 cx,
12358 );
12359 }
12360 });
12361 }
12362 }
12363
12364 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12365 cx.emit(EditorEvent::FocusedIn)
12366 }
12367
12368 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12369 if event.blurred != self.focus_handle {
12370 self.last_focused_descendant = Some(event.blurred);
12371 }
12372 }
12373
12374 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12375 self.blink_manager.update(cx, BlinkManager::disable);
12376 self.buffer
12377 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12378
12379 if let Some(blame) = self.blame.as_ref() {
12380 blame.update(cx, GitBlame::blur)
12381 }
12382 if !self.hover_state.focused(cx) {
12383 hide_hover(self, cx);
12384 }
12385
12386 self.hide_context_menu(cx);
12387 cx.emit(EditorEvent::Blurred);
12388 cx.notify();
12389 }
12390
12391 pub fn register_action<A: Action>(
12392 &mut self,
12393 listener: impl Fn(&A, &mut WindowContext) + 'static,
12394 ) -> Subscription {
12395 let id = self.next_editor_action_id.post_inc();
12396 let listener = Arc::new(listener);
12397 self.editor_actions.borrow_mut().insert(
12398 id,
12399 Box::new(move |cx| {
12400 let cx = cx.window_context();
12401 let listener = listener.clone();
12402 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12403 let action = action.downcast_ref().unwrap();
12404 if phase == DispatchPhase::Bubble {
12405 listener(action, cx)
12406 }
12407 })
12408 }),
12409 );
12410
12411 let editor_actions = self.editor_actions.clone();
12412 Subscription::new(move || {
12413 editor_actions.borrow_mut().remove(&id);
12414 })
12415 }
12416
12417 pub fn file_header_size(&self) -> u32 {
12418 self.file_header_size
12419 }
12420
12421 pub fn revert(
12422 &mut self,
12423 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12424 cx: &mut ViewContext<Self>,
12425 ) {
12426 self.buffer().update(cx, |multi_buffer, cx| {
12427 for (buffer_id, changes) in revert_changes {
12428 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12429 buffer.update(cx, |buffer, cx| {
12430 buffer.edit(
12431 changes.into_iter().map(|(range, text)| {
12432 (range, text.to_string().map(Arc::<str>::from))
12433 }),
12434 None,
12435 cx,
12436 );
12437 });
12438 }
12439 }
12440 });
12441 self.change_selections(None, cx, |selections| selections.refresh());
12442 }
12443
12444 pub fn to_pixel_point(
12445 &mut self,
12446 source: multi_buffer::Anchor,
12447 editor_snapshot: &EditorSnapshot,
12448 cx: &mut ViewContext<Self>,
12449 ) -> Option<gpui::Point<Pixels>> {
12450 let source_point = source.to_display_point(editor_snapshot);
12451 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12452 }
12453
12454 pub fn display_to_pixel_point(
12455 &mut self,
12456 source: DisplayPoint,
12457 editor_snapshot: &EditorSnapshot,
12458 cx: &mut ViewContext<Self>,
12459 ) -> Option<gpui::Point<Pixels>> {
12460 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12461 let text_layout_details = self.text_layout_details(cx);
12462 let scroll_top = text_layout_details
12463 .scroll_anchor
12464 .scroll_position(editor_snapshot)
12465 .y;
12466
12467 if source.row().as_f32() < scroll_top.floor() {
12468 return None;
12469 }
12470 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12471 let source_y = line_height * (source.row().as_f32() - scroll_top);
12472 Some(gpui::Point::new(source_x, source_y))
12473 }
12474
12475 pub fn has_active_completions_menu(&self) -> bool {
12476 self.context_menu.read().as_ref().map_or(false, |menu| {
12477 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12478 })
12479 }
12480
12481 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12482 self.addons
12483 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12484 }
12485
12486 pub fn unregister_addon<T: Addon>(&mut self) {
12487 self.addons.remove(&std::any::TypeId::of::<T>());
12488 }
12489
12490 pub fn addon<T: Addon>(&self) -> Option<&T> {
12491 let type_id = std::any::TypeId::of::<T>();
12492 self.addons
12493 .get(&type_id)
12494 .and_then(|item| item.to_any().downcast_ref::<T>())
12495 }
12496}
12497
12498fn hunks_for_selections(
12499 multi_buffer_snapshot: &MultiBufferSnapshot,
12500 selections: &[Selection<Anchor>],
12501) -> Vec<MultiBufferDiffHunk> {
12502 let buffer_rows_for_selections = selections.iter().map(|selection| {
12503 let head = selection.head();
12504 let tail = selection.tail();
12505 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12506 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12507 if start > end {
12508 end..start
12509 } else {
12510 start..end
12511 }
12512 });
12513
12514 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12515}
12516
12517pub fn hunks_for_rows(
12518 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12519 multi_buffer_snapshot: &MultiBufferSnapshot,
12520) -> Vec<MultiBufferDiffHunk> {
12521 let mut hunks = Vec::new();
12522 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12523 HashMap::default();
12524 for selected_multi_buffer_rows in rows {
12525 let query_rows =
12526 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12527 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12528 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12529 // when the caret is just above or just below the deleted hunk.
12530 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12531 let related_to_selection = if allow_adjacent {
12532 hunk.row_range.overlaps(&query_rows)
12533 || hunk.row_range.start == query_rows.end
12534 || hunk.row_range.end == query_rows.start
12535 } else {
12536 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12537 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12538 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12539 || selected_multi_buffer_rows.end == hunk.row_range.start
12540 };
12541 if related_to_selection {
12542 if !processed_buffer_rows
12543 .entry(hunk.buffer_id)
12544 .or_default()
12545 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12546 {
12547 continue;
12548 }
12549 hunks.push(hunk);
12550 }
12551 }
12552 }
12553
12554 hunks
12555}
12556
12557pub trait CollaborationHub {
12558 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12559 fn user_participant_indices<'a>(
12560 &self,
12561 cx: &'a AppContext,
12562 ) -> &'a HashMap<u64, ParticipantIndex>;
12563 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12564}
12565
12566impl CollaborationHub for Model<Project> {
12567 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12568 self.read(cx).collaborators()
12569 }
12570
12571 fn user_participant_indices<'a>(
12572 &self,
12573 cx: &'a AppContext,
12574 ) -> &'a HashMap<u64, ParticipantIndex> {
12575 self.read(cx).user_store().read(cx).participant_indices()
12576 }
12577
12578 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12579 let this = self.read(cx);
12580 let user_ids = this.collaborators().values().map(|c| c.user_id);
12581 this.user_store().read_with(cx, |user_store, cx| {
12582 user_store.participant_names(user_ids, cx)
12583 })
12584 }
12585}
12586
12587pub trait CompletionProvider {
12588 fn completions(
12589 &self,
12590 buffer: &Model<Buffer>,
12591 buffer_position: text::Anchor,
12592 trigger: CompletionContext,
12593 cx: &mut ViewContext<Editor>,
12594 ) -> Task<Result<Vec<Completion>>>;
12595
12596 fn resolve_completions(
12597 &self,
12598 buffer: Model<Buffer>,
12599 completion_indices: Vec<usize>,
12600 completions: Arc<RwLock<Box<[Completion]>>>,
12601 cx: &mut ViewContext<Editor>,
12602 ) -> Task<Result<bool>>;
12603
12604 fn apply_additional_edits_for_completion(
12605 &self,
12606 buffer: Model<Buffer>,
12607 completion: Completion,
12608 push_to_history: bool,
12609 cx: &mut ViewContext<Editor>,
12610 ) -> Task<Result<Option<language::Transaction>>>;
12611
12612 fn is_completion_trigger(
12613 &self,
12614 buffer: &Model<Buffer>,
12615 position: language::Anchor,
12616 text: &str,
12617 trigger_in_words: bool,
12618 cx: &mut ViewContext<Editor>,
12619 ) -> bool;
12620
12621 fn sort_completions(&self) -> bool {
12622 true
12623 }
12624}
12625
12626pub trait CodeActionProvider {
12627 fn code_actions(
12628 &self,
12629 buffer: &Model<Buffer>,
12630 range: Range<text::Anchor>,
12631 cx: &mut WindowContext,
12632 ) -> Task<Result<Vec<CodeAction>>>;
12633
12634 fn apply_code_action(
12635 &self,
12636 buffer_handle: Model<Buffer>,
12637 action: CodeAction,
12638 excerpt_id: ExcerptId,
12639 push_to_history: bool,
12640 cx: &mut WindowContext,
12641 ) -> Task<Result<ProjectTransaction>>;
12642}
12643
12644impl CodeActionProvider for Model<Project> {
12645 fn code_actions(
12646 &self,
12647 buffer: &Model<Buffer>,
12648 range: Range<text::Anchor>,
12649 cx: &mut WindowContext,
12650 ) -> Task<Result<Vec<CodeAction>>> {
12651 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12652 }
12653
12654 fn apply_code_action(
12655 &self,
12656 buffer_handle: Model<Buffer>,
12657 action: CodeAction,
12658 _excerpt_id: ExcerptId,
12659 push_to_history: bool,
12660 cx: &mut WindowContext,
12661 ) -> Task<Result<ProjectTransaction>> {
12662 self.update(cx, |project, cx| {
12663 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12664 })
12665 }
12666}
12667
12668fn snippet_completions(
12669 project: &Project,
12670 buffer: &Model<Buffer>,
12671 buffer_position: text::Anchor,
12672 cx: &mut AppContext,
12673) -> Vec<Completion> {
12674 let language = buffer.read(cx).language_at(buffer_position);
12675 let language_name = language.as_ref().map(|language| language.lsp_id());
12676 let snippet_store = project.snippets().read(cx);
12677 let snippets = snippet_store.snippets_for(language_name, cx);
12678
12679 if snippets.is_empty() {
12680 return vec![];
12681 }
12682 let snapshot = buffer.read(cx).text_snapshot();
12683 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12684
12685 let mut lines = chunks.lines();
12686 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12687 return vec![];
12688 };
12689
12690 let scope = language.map(|language| language.default_scope());
12691 let classifier = CharClassifier::new(scope).for_completion(true);
12692 let mut last_word = line_at
12693 .chars()
12694 .rev()
12695 .take_while(|c| classifier.is_word(*c))
12696 .collect::<String>();
12697 last_word = last_word.chars().rev().collect();
12698 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12699 let to_lsp = |point: &text::Anchor| {
12700 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12701 point_to_lsp(end)
12702 };
12703 let lsp_end = to_lsp(&buffer_position);
12704 snippets
12705 .into_iter()
12706 .filter_map(|snippet| {
12707 let matching_prefix = snippet
12708 .prefix
12709 .iter()
12710 .find(|prefix| prefix.starts_with(&last_word))?;
12711 let start = as_offset - last_word.len();
12712 let start = snapshot.anchor_before(start);
12713 let range = start..buffer_position;
12714 let lsp_start = to_lsp(&start);
12715 let lsp_range = lsp::Range {
12716 start: lsp_start,
12717 end: lsp_end,
12718 };
12719 Some(Completion {
12720 old_range: range,
12721 new_text: snippet.body.clone(),
12722 label: CodeLabel {
12723 text: matching_prefix.clone(),
12724 runs: vec![],
12725 filter_range: 0..matching_prefix.len(),
12726 },
12727 server_id: LanguageServerId(usize::MAX),
12728 documentation: snippet.description.clone().map(Documentation::SingleLine),
12729 lsp_completion: lsp::CompletionItem {
12730 label: snippet.prefix.first().unwrap().clone(),
12731 kind: Some(CompletionItemKind::SNIPPET),
12732 label_details: snippet.description.as_ref().map(|description| {
12733 lsp::CompletionItemLabelDetails {
12734 detail: Some(description.clone()),
12735 description: None,
12736 }
12737 }),
12738 insert_text_format: Some(InsertTextFormat::SNIPPET),
12739 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12740 lsp::InsertReplaceEdit {
12741 new_text: snippet.body.clone(),
12742 insert: lsp_range,
12743 replace: lsp_range,
12744 },
12745 )),
12746 filter_text: Some(snippet.body.clone()),
12747 sort_text: Some(char::MAX.to_string()),
12748 ..Default::default()
12749 },
12750 confirm: None,
12751 })
12752 })
12753 .collect()
12754}
12755
12756impl CompletionProvider for Model<Project> {
12757 fn completions(
12758 &self,
12759 buffer: &Model<Buffer>,
12760 buffer_position: text::Anchor,
12761 options: CompletionContext,
12762 cx: &mut ViewContext<Editor>,
12763 ) -> Task<Result<Vec<Completion>>> {
12764 self.update(cx, |project, cx| {
12765 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12766 let project_completions = project.completions(buffer, buffer_position, options, cx);
12767 cx.background_executor().spawn(async move {
12768 let mut completions = project_completions.await?;
12769 //let snippets = snippets.into_iter().;
12770 completions.extend(snippets);
12771 Ok(completions)
12772 })
12773 })
12774 }
12775
12776 fn resolve_completions(
12777 &self,
12778 buffer: Model<Buffer>,
12779 completion_indices: Vec<usize>,
12780 completions: Arc<RwLock<Box<[Completion]>>>,
12781 cx: &mut ViewContext<Editor>,
12782 ) -> Task<Result<bool>> {
12783 self.update(cx, |project, cx| {
12784 project.resolve_completions(buffer, completion_indices, completions, cx)
12785 })
12786 }
12787
12788 fn apply_additional_edits_for_completion(
12789 &self,
12790 buffer: Model<Buffer>,
12791 completion: Completion,
12792 push_to_history: bool,
12793 cx: &mut ViewContext<Editor>,
12794 ) -> Task<Result<Option<language::Transaction>>> {
12795 self.update(cx, |project, cx| {
12796 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12797 })
12798 }
12799
12800 fn is_completion_trigger(
12801 &self,
12802 buffer: &Model<Buffer>,
12803 position: language::Anchor,
12804 text: &str,
12805 trigger_in_words: bool,
12806 cx: &mut ViewContext<Editor>,
12807 ) -> bool {
12808 if !EditorSettings::get_global(cx).show_completions_on_input {
12809 return false;
12810 }
12811
12812 let mut chars = text.chars();
12813 let char = if let Some(char) = chars.next() {
12814 char
12815 } else {
12816 return false;
12817 };
12818 if chars.next().is_some() {
12819 return false;
12820 }
12821
12822 let buffer = buffer.read(cx);
12823 let classifier = buffer
12824 .snapshot()
12825 .char_classifier_at(position)
12826 .for_completion(true);
12827 if trigger_in_words && classifier.is_word(char) {
12828 return true;
12829 }
12830
12831 buffer
12832 .completion_triggers()
12833 .iter()
12834 .any(|string| string == text)
12835 }
12836}
12837
12838fn inlay_hint_settings(
12839 location: Anchor,
12840 snapshot: &MultiBufferSnapshot,
12841 cx: &mut ViewContext<'_, Editor>,
12842) -> InlayHintSettings {
12843 let file = snapshot.file_at(location);
12844 let language = snapshot.language_at(location);
12845 let settings = all_language_settings(file, cx);
12846 settings
12847 .language(language.map(|l| l.name()).as_ref())
12848 .inlay_hints
12849}
12850
12851fn consume_contiguous_rows(
12852 contiguous_row_selections: &mut Vec<Selection<Point>>,
12853 selection: &Selection<Point>,
12854 display_map: &DisplaySnapshot,
12855 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12856) -> (MultiBufferRow, MultiBufferRow) {
12857 contiguous_row_selections.push(selection.clone());
12858 let start_row = MultiBufferRow(selection.start.row);
12859 let mut end_row = ending_row(selection, display_map);
12860
12861 while let Some(next_selection) = selections.peek() {
12862 if next_selection.start.row <= end_row.0 {
12863 end_row = ending_row(next_selection, display_map);
12864 contiguous_row_selections.push(selections.next().unwrap().clone());
12865 } else {
12866 break;
12867 }
12868 }
12869 (start_row, end_row)
12870}
12871
12872fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12873 if next_selection.end.column > 0 || next_selection.is_empty() {
12874 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12875 } else {
12876 MultiBufferRow(next_selection.end.row)
12877 }
12878}
12879
12880impl EditorSnapshot {
12881 pub fn remote_selections_in_range<'a>(
12882 &'a self,
12883 range: &'a Range<Anchor>,
12884 collaboration_hub: &dyn CollaborationHub,
12885 cx: &'a AppContext,
12886 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12887 let participant_names = collaboration_hub.user_names(cx);
12888 let participant_indices = collaboration_hub.user_participant_indices(cx);
12889 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12890 let collaborators_by_replica_id = collaborators_by_peer_id
12891 .iter()
12892 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12893 .collect::<HashMap<_, _>>();
12894 self.buffer_snapshot
12895 .selections_in_range(range, false)
12896 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12897 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12898 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12899 let user_name = participant_names.get(&collaborator.user_id).cloned();
12900 Some(RemoteSelection {
12901 replica_id,
12902 selection,
12903 cursor_shape,
12904 line_mode,
12905 participant_index,
12906 peer_id: collaborator.peer_id,
12907 user_name,
12908 })
12909 })
12910 }
12911
12912 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12913 self.display_snapshot.buffer_snapshot.language_at(position)
12914 }
12915
12916 pub fn is_focused(&self) -> bool {
12917 self.is_focused
12918 }
12919
12920 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12921 self.placeholder_text.as_ref()
12922 }
12923
12924 pub fn scroll_position(&self) -> gpui::Point<f32> {
12925 self.scroll_anchor.scroll_position(&self.display_snapshot)
12926 }
12927
12928 fn gutter_dimensions(
12929 &self,
12930 font_id: FontId,
12931 font_size: Pixels,
12932 em_width: Pixels,
12933 max_line_number_width: Pixels,
12934 cx: &AppContext,
12935 ) -> GutterDimensions {
12936 if !self.show_gutter {
12937 return GutterDimensions::default();
12938 }
12939 let descent = cx.text_system().descent(font_id, font_size);
12940
12941 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12942 matches!(
12943 ProjectSettings::get_global(cx).git.git_gutter,
12944 Some(GitGutterSetting::TrackedFiles)
12945 )
12946 });
12947 let gutter_settings = EditorSettings::get_global(cx).gutter;
12948 let show_line_numbers = self
12949 .show_line_numbers
12950 .unwrap_or(gutter_settings.line_numbers);
12951 let line_gutter_width = if show_line_numbers {
12952 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12953 let min_width_for_number_on_gutter = em_width * 4.0;
12954 max_line_number_width.max(min_width_for_number_on_gutter)
12955 } else {
12956 0.0.into()
12957 };
12958
12959 let show_code_actions = self
12960 .show_code_actions
12961 .unwrap_or(gutter_settings.code_actions);
12962
12963 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12964
12965 let git_blame_entries_width = self
12966 .render_git_blame_gutter
12967 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12968
12969 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12970 left_padding += if show_code_actions || show_runnables {
12971 em_width * 3.0
12972 } else if show_git_gutter && show_line_numbers {
12973 em_width * 2.0
12974 } else if show_git_gutter || show_line_numbers {
12975 em_width
12976 } else {
12977 px(0.)
12978 };
12979
12980 let right_padding = if gutter_settings.folds && show_line_numbers {
12981 em_width * 4.0
12982 } else if gutter_settings.folds {
12983 em_width * 3.0
12984 } else if show_line_numbers {
12985 em_width
12986 } else {
12987 px(0.)
12988 };
12989
12990 GutterDimensions {
12991 left_padding,
12992 right_padding,
12993 width: line_gutter_width + left_padding + right_padding,
12994 margin: -descent,
12995 git_blame_entries_width,
12996 }
12997 }
12998
12999 pub fn render_fold_toggle(
13000 &self,
13001 buffer_row: MultiBufferRow,
13002 row_contains_cursor: bool,
13003 editor: View<Editor>,
13004 cx: &mut WindowContext,
13005 ) -> Option<AnyElement> {
13006 let folded = self.is_line_folded(buffer_row);
13007
13008 if let Some(crease) = self
13009 .crease_snapshot
13010 .query_row(buffer_row, &self.buffer_snapshot)
13011 {
13012 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13013 if folded {
13014 editor.update(cx, |editor, cx| {
13015 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13016 });
13017 } else {
13018 editor.update(cx, |editor, cx| {
13019 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13020 });
13021 }
13022 });
13023
13024 Some((crease.render_toggle)(
13025 buffer_row,
13026 folded,
13027 toggle_callback,
13028 cx,
13029 ))
13030 } else if folded
13031 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13032 {
13033 Some(
13034 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13035 .selected(folded)
13036 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13037 if folded {
13038 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13039 } else {
13040 this.fold_at(&FoldAt { buffer_row }, cx);
13041 }
13042 }))
13043 .into_any_element(),
13044 )
13045 } else {
13046 None
13047 }
13048 }
13049
13050 pub fn render_crease_trailer(
13051 &self,
13052 buffer_row: MultiBufferRow,
13053 cx: &mut WindowContext,
13054 ) -> Option<AnyElement> {
13055 let folded = self.is_line_folded(buffer_row);
13056 let crease = self
13057 .crease_snapshot
13058 .query_row(buffer_row, &self.buffer_snapshot)?;
13059 Some((crease.render_trailer)(buffer_row, folded, cx))
13060 }
13061}
13062
13063impl Deref for EditorSnapshot {
13064 type Target = DisplaySnapshot;
13065
13066 fn deref(&self) -> &Self::Target {
13067 &self.display_snapshot
13068 }
13069}
13070
13071#[derive(Clone, Debug, PartialEq, Eq)]
13072pub enum EditorEvent {
13073 InputIgnored {
13074 text: Arc<str>,
13075 },
13076 InputHandled {
13077 utf16_range_to_replace: Option<Range<isize>>,
13078 text: Arc<str>,
13079 },
13080 ExcerptsAdded {
13081 buffer: Model<Buffer>,
13082 predecessor: ExcerptId,
13083 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13084 },
13085 ExcerptsRemoved {
13086 ids: Vec<ExcerptId>,
13087 },
13088 ExcerptsEdited {
13089 ids: Vec<ExcerptId>,
13090 },
13091 ExcerptsExpanded {
13092 ids: Vec<ExcerptId>,
13093 },
13094 BufferEdited,
13095 Edited {
13096 transaction_id: clock::Lamport,
13097 },
13098 Reparsed(BufferId),
13099 Focused,
13100 FocusedIn,
13101 Blurred,
13102 DirtyChanged,
13103 Saved,
13104 TitleChanged,
13105 DiffBaseChanged,
13106 SelectionsChanged {
13107 local: bool,
13108 },
13109 ScrollPositionChanged {
13110 local: bool,
13111 autoscroll: bool,
13112 },
13113 Closed,
13114 TransactionUndone {
13115 transaction_id: clock::Lamport,
13116 },
13117 TransactionBegun {
13118 transaction_id: clock::Lamport,
13119 },
13120}
13121
13122impl EventEmitter<EditorEvent> for Editor {}
13123
13124impl FocusableView for Editor {
13125 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13126 self.focus_handle.clone()
13127 }
13128}
13129
13130impl Render for Editor {
13131 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13132 let settings = ThemeSettings::get_global(cx);
13133
13134 let text_style = match self.mode {
13135 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13136 color: cx.theme().colors().editor_foreground,
13137 font_family: settings.ui_font.family.clone(),
13138 font_features: settings.ui_font.features.clone(),
13139 font_fallbacks: settings.ui_font.fallbacks.clone(),
13140 font_size: rems(0.875).into(),
13141 font_weight: settings.ui_font.weight,
13142 line_height: relative(settings.buffer_line_height.value()),
13143 ..Default::default()
13144 },
13145 EditorMode::Full => TextStyle {
13146 color: cx.theme().colors().editor_foreground,
13147 font_family: settings.buffer_font.family.clone(),
13148 font_features: settings.buffer_font.features.clone(),
13149 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13150 font_size: settings.buffer_font_size(cx).into(),
13151 font_weight: settings.buffer_font.weight,
13152 line_height: relative(settings.buffer_line_height.value()),
13153 ..Default::default()
13154 },
13155 };
13156
13157 let background = match self.mode {
13158 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13159 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13160 EditorMode::Full => cx.theme().colors().editor_background,
13161 };
13162
13163 EditorElement::new(
13164 cx.view(),
13165 EditorStyle {
13166 background,
13167 local_player: cx.theme().players().local(),
13168 text: text_style,
13169 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13170 syntax: cx.theme().syntax().clone(),
13171 status: cx.theme().status().clone(),
13172 inlay_hints_style: make_inlay_hints_style(cx),
13173 suggestions_style: HighlightStyle {
13174 color: Some(cx.theme().status().predictive),
13175 ..HighlightStyle::default()
13176 },
13177 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13178 },
13179 )
13180 }
13181}
13182
13183impl ViewInputHandler for Editor {
13184 fn text_for_range(
13185 &mut self,
13186 range_utf16: Range<usize>,
13187 cx: &mut ViewContext<Self>,
13188 ) -> Option<String> {
13189 Some(
13190 self.buffer
13191 .read(cx)
13192 .read(cx)
13193 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13194 .collect(),
13195 )
13196 }
13197
13198 fn selected_text_range(
13199 &mut self,
13200 ignore_disabled_input: bool,
13201 cx: &mut ViewContext<Self>,
13202 ) -> Option<UTF16Selection> {
13203 // Prevent the IME menu from appearing when holding down an alphabetic key
13204 // while input is disabled.
13205 if !ignore_disabled_input && !self.input_enabled {
13206 return None;
13207 }
13208
13209 let selection = self.selections.newest::<OffsetUtf16>(cx);
13210 let range = selection.range();
13211
13212 Some(UTF16Selection {
13213 range: range.start.0..range.end.0,
13214 reversed: selection.reversed,
13215 })
13216 }
13217
13218 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13219 let snapshot = self.buffer.read(cx).read(cx);
13220 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13221 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13222 }
13223
13224 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13225 self.clear_highlights::<InputComposition>(cx);
13226 self.ime_transaction.take();
13227 }
13228
13229 fn replace_text_in_range(
13230 &mut self,
13231 range_utf16: Option<Range<usize>>,
13232 text: &str,
13233 cx: &mut ViewContext<Self>,
13234 ) {
13235 if !self.input_enabled {
13236 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13237 return;
13238 }
13239
13240 self.transact(cx, |this, cx| {
13241 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13242 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13243 Some(this.selection_replacement_ranges(range_utf16, cx))
13244 } else {
13245 this.marked_text_ranges(cx)
13246 };
13247
13248 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13249 let newest_selection_id = this.selections.newest_anchor().id;
13250 this.selections
13251 .all::<OffsetUtf16>(cx)
13252 .iter()
13253 .zip(ranges_to_replace.iter())
13254 .find_map(|(selection, range)| {
13255 if selection.id == newest_selection_id {
13256 Some(
13257 (range.start.0 as isize - selection.head().0 as isize)
13258 ..(range.end.0 as isize - selection.head().0 as isize),
13259 )
13260 } else {
13261 None
13262 }
13263 })
13264 });
13265
13266 cx.emit(EditorEvent::InputHandled {
13267 utf16_range_to_replace: range_to_replace,
13268 text: text.into(),
13269 });
13270
13271 if let Some(new_selected_ranges) = new_selected_ranges {
13272 this.change_selections(None, cx, |selections| {
13273 selections.select_ranges(new_selected_ranges)
13274 });
13275 this.backspace(&Default::default(), cx);
13276 }
13277
13278 this.handle_input(text, cx);
13279 });
13280
13281 if let Some(transaction) = self.ime_transaction {
13282 self.buffer.update(cx, |buffer, cx| {
13283 buffer.group_until_transaction(transaction, cx);
13284 });
13285 }
13286
13287 self.unmark_text(cx);
13288 }
13289
13290 fn replace_and_mark_text_in_range(
13291 &mut self,
13292 range_utf16: Option<Range<usize>>,
13293 text: &str,
13294 new_selected_range_utf16: Option<Range<usize>>,
13295 cx: &mut ViewContext<Self>,
13296 ) {
13297 if !self.input_enabled {
13298 return;
13299 }
13300
13301 let transaction = self.transact(cx, |this, cx| {
13302 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13303 let snapshot = this.buffer.read(cx).read(cx);
13304 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13305 for marked_range in &mut marked_ranges {
13306 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13307 marked_range.start.0 += relative_range_utf16.start;
13308 marked_range.start =
13309 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13310 marked_range.end =
13311 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13312 }
13313 }
13314 Some(marked_ranges)
13315 } else if let Some(range_utf16) = range_utf16 {
13316 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13317 Some(this.selection_replacement_ranges(range_utf16, cx))
13318 } else {
13319 None
13320 };
13321
13322 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13323 let newest_selection_id = this.selections.newest_anchor().id;
13324 this.selections
13325 .all::<OffsetUtf16>(cx)
13326 .iter()
13327 .zip(ranges_to_replace.iter())
13328 .find_map(|(selection, range)| {
13329 if selection.id == newest_selection_id {
13330 Some(
13331 (range.start.0 as isize - selection.head().0 as isize)
13332 ..(range.end.0 as isize - selection.head().0 as isize),
13333 )
13334 } else {
13335 None
13336 }
13337 })
13338 });
13339
13340 cx.emit(EditorEvent::InputHandled {
13341 utf16_range_to_replace: range_to_replace,
13342 text: text.into(),
13343 });
13344
13345 if let Some(ranges) = ranges_to_replace {
13346 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13347 }
13348
13349 let marked_ranges = {
13350 let snapshot = this.buffer.read(cx).read(cx);
13351 this.selections
13352 .disjoint_anchors()
13353 .iter()
13354 .map(|selection| {
13355 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13356 })
13357 .collect::<Vec<_>>()
13358 };
13359
13360 if text.is_empty() {
13361 this.unmark_text(cx);
13362 } else {
13363 this.highlight_text::<InputComposition>(
13364 marked_ranges.clone(),
13365 HighlightStyle {
13366 underline: Some(UnderlineStyle {
13367 thickness: px(1.),
13368 color: None,
13369 wavy: false,
13370 }),
13371 ..Default::default()
13372 },
13373 cx,
13374 );
13375 }
13376
13377 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13378 let use_autoclose = this.use_autoclose;
13379 let use_auto_surround = this.use_auto_surround;
13380 this.set_use_autoclose(false);
13381 this.set_use_auto_surround(false);
13382 this.handle_input(text, cx);
13383 this.set_use_autoclose(use_autoclose);
13384 this.set_use_auto_surround(use_auto_surround);
13385
13386 if let Some(new_selected_range) = new_selected_range_utf16 {
13387 let snapshot = this.buffer.read(cx).read(cx);
13388 let new_selected_ranges = marked_ranges
13389 .into_iter()
13390 .map(|marked_range| {
13391 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13392 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13393 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13394 snapshot.clip_offset_utf16(new_start, Bias::Left)
13395 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13396 })
13397 .collect::<Vec<_>>();
13398
13399 drop(snapshot);
13400 this.change_selections(None, cx, |selections| {
13401 selections.select_ranges(new_selected_ranges)
13402 });
13403 }
13404 });
13405
13406 self.ime_transaction = self.ime_transaction.or(transaction);
13407 if let Some(transaction) = self.ime_transaction {
13408 self.buffer.update(cx, |buffer, cx| {
13409 buffer.group_until_transaction(transaction, cx);
13410 });
13411 }
13412
13413 if self.text_highlights::<InputComposition>(cx).is_none() {
13414 self.ime_transaction.take();
13415 }
13416 }
13417
13418 fn bounds_for_range(
13419 &mut self,
13420 range_utf16: Range<usize>,
13421 element_bounds: gpui::Bounds<Pixels>,
13422 cx: &mut ViewContext<Self>,
13423 ) -> Option<gpui::Bounds<Pixels>> {
13424 let text_layout_details = self.text_layout_details(cx);
13425 let style = &text_layout_details.editor_style;
13426 let font_id = cx.text_system().resolve_font(&style.text.font());
13427 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13428 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13429
13430 let em_width = cx
13431 .text_system()
13432 .typographic_bounds(font_id, font_size, 'm')
13433 .unwrap()
13434 .size
13435 .width;
13436
13437 let snapshot = self.snapshot(cx);
13438 let scroll_position = snapshot.scroll_position();
13439 let scroll_left = scroll_position.x * em_width;
13440
13441 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13442 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13443 + self.gutter_dimensions.width;
13444 let y = line_height * (start.row().as_f32() - scroll_position.y);
13445
13446 Some(Bounds {
13447 origin: element_bounds.origin + point(x, y),
13448 size: size(em_width, line_height),
13449 })
13450 }
13451}
13452
13453trait SelectionExt {
13454 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13455 fn spanned_rows(
13456 &self,
13457 include_end_if_at_line_start: bool,
13458 map: &DisplaySnapshot,
13459 ) -> Range<MultiBufferRow>;
13460}
13461
13462impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13463 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13464 let start = self
13465 .start
13466 .to_point(&map.buffer_snapshot)
13467 .to_display_point(map);
13468 let end = self
13469 .end
13470 .to_point(&map.buffer_snapshot)
13471 .to_display_point(map);
13472 if self.reversed {
13473 end..start
13474 } else {
13475 start..end
13476 }
13477 }
13478
13479 fn spanned_rows(
13480 &self,
13481 include_end_if_at_line_start: bool,
13482 map: &DisplaySnapshot,
13483 ) -> Range<MultiBufferRow> {
13484 let start = self.start.to_point(&map.buffer_snapshot);
13485 let mut end = self.end.to_point(&map.buffer_snapshot);
13486 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13487 end.row -= 1;
13488 }
13489
13490 let buffer_start = map.prev_line_boundary(start).0;
13491 let buffer_end = map.next_line_boundary(end).0;
13492 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13493 }
13494}
13495
13496impl<T: InvalidationRegion> InvalidationStack<T> {
13497 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13498 where
13499 S: Clone + ToOffset,
13500 {
13501 while let Some(region) = self.last() {
13502 let all_selections_inside_invalidation_ranges =
13503 if selections.len() == region.ranges().len() {
13504 selections
13505 .iter()
13506 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13507 .all(|(selection, invalidation_range)| {
13508 let head = selection.head().to_offset(buffer);
13509 invalidation_range.start <= head && invalidation_range.end >= head
13510 })
13511 } else {
13512 false
13513 };
13514
13515 if all_selections_inside_invalidation_ranges {
13516 break;
13517 } else {
13518 self.pop();
13519 }
13520 }
13521 }
13522}
13523
13524impl<T> Default for InvalidationStack<T> {
13525 fn default() -> Self {
13526 Self(Default::default())
13527 }
13528}
13529
13530impl<T> Deref for InvalidationStack<T> {
13531 type Target = Vec<T>;
13532
13533 fn deref(&self) -> &Self::Target {
13534 &self.0
13535 }
13536}
13537
13538impl<T> DerefMut for InvalidationStack<T> {
13539 fn deref_mut(&mut self) -> &mut Self::Target {
13540 &mut self.0
13541 }
13542}
13543
13544impl InvalidationRegion for SnippetState {
13545 fn ranges(&self) -> &[Range<Anchor>] {
13546 &self.ranges[self.active_index]
13547 }
13548}
13549
13550pub fn diagnostic_block_renderer(
13551 diagnostic: Diagnostic,
13552 max_message_rows: Option<u8>,
13553 allow_closing: bool,
13554 _is_valid: bool,
13555) -> RenderBlock {
13556 let (text_without_backticks, code_ranges) =
13557 highlight_diagnostic_message(&diagnostic, max_message_rows);
13558
13559 Box::new(move |cx: &mut BlockContext| {
13560 let group_id: SharedString = cx.block_id.to_string().into();
13561
13562 let mut text_style = cx.text_style().clone();
13563 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13564 let theme_settings = ThemeSettings::get_global(cx);
13565 text_style.font_family = theme_settings.buffer_font.family.clone();
13566 text_style.font_style = theme_settings.buffer_font.style;
13567 text_style.font_features = theme_settings.buffer_font.features.clone();
13568 text_style.font_weight = theme_settings.buffer_font.weight;
13569
13570 let multi_line_diagnostic = diagnostic.message.contains('\n');
13571
13572 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13573 if multi_line_diagnostic {
13574 v_flex()
13575 } else {
13576 h_flex()
13577 }
13578 .when(allow_closing, |div| {
13579 div.children(diagnostic.is_primary.then(|| {
13580 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13581 .icon_color(Color::Muted)
13582 .size(ButtonSize::Compact)
13583 .style(ButtonStyle::Transparent)
13584 .visible_on_hover(group_id.clone())
13585 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13586 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13587 }))
13588 })
13589 .child(
13590 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13591 .icon_color(Color::Muted)
13592 .size(ButtonSize::Compact)
13593 .style(ButtonStyle::Transparent)
13594 .visible_on_hover(group_id.clone())
13595 .on_click({
13596 let message = diagnostic.message.clone();
13597 move |_click, cx| {
13598 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13599 }
13600 })
13601 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13602 )
13603 };
13604
13605 let icon_size = buttons(&diagnostic, cx.block_id)
13606 .into_any_element()
13607 .layout_as_root(AvailableSpace::min_size(), cx);
13608
13609 h_flex()
13610 .id(cx.block_id)
13611 .group(group_id.clone())
13612 .relative()
13613 .size_full()
13614 .pl(cx.gutter_dimensions.width)
13615 .w(cx.max_width + cx.gutter_dimensions.width)
13616 .child(
13617 div()
13618 .flex()
13619 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13620 .flex_shrink(),
13621 )
13622 .child(buttons(&diagnostic, cx.block_id))
13623 .child(div().flex().flex_shrink_0().child(
13624 StyledText::new(text_without_backticks.clone()).with_highlights(
13625 &text_style,
13626 code_ranges.iter().map(|range| {
13627 (
13628 range.clone(),
13629 HighlightStyle {
13630 font_weight: Some(FontWeight::BOLD),
13631 ..Default::default()
13632 },
13633 )
13634 }),
13635 ),
13636 ))
13637 .into_any_element()
13638 })
13639}
13640
13641pub fn highlight_diagnostic_message(
13642 diagnostic: &Diagnostic,
13643 mut max_message_rows: Option<u8>,
13644) -> (SharedString, Vec<Range<usize>>) {
13645 let mut text_without_backticks = String::new();
13646 let mut code_ranges = Vec::new();
13647
13648 if let Some(source) = &diagnostic.source {
13649 text_without_backticks.push_str(source);
13650 code_ranges.push(0..source.len());
13651 text_without_backticks.push_str(": ");
13652 }
13653
13654 let mut prev_offset = 0;
13655 let mut in_code_block = false;
13656 let has_row_limit = max_message_rows.is_some();
13657 let mut newline_indices = diagnostic
13658 .message
13659 .match_indices('\n')
13660 .filter(|_| has_row_limit)
13661 .map(|(ix, _)| ix)
13662 .fuse()
13663 .peekable();
13664
13665 for (quote_ix, _) in diagnostic
13666 .message
13667 .match_indices('`')
13668 .chain([(diagnostic.message.len(), "")])
13669 {
13670 let mut first_newline_ix = None;
13671 let mut last_newline_ix = None;
13672 while let Some(newline_ix) = newline_indices.peek() {
13673 if *newline_ix < quote_ix {
13674 if first_newline_ix.is_none() {
13675 first_newline_ix = Some(*newline_ix);
13676 }
13677 last_newline_ix = Some(*newline_ix);
13678
13679 if let Some(rows_left) = &mut max_message_rows {
13680 if *rows_left == 0 {
13681 break;
13682 } else {
13683 *rows_left -= 1;
13684 }
13685 }
13686 let _ = newline_indices.next();
13687 } else {
13688 break;
13689 }
13690 }
13691 let prev_len = text_without_backticks.len();
13692 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13693 text_without_backticks.push_str(new_text);
13694 if in_code_block {
13695 code_ranges.push(prev_len..text_without_backticks.len());
13696 }
13697 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13698 in_code_block = !in_code_block;
13699 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13700 text_without_backticks.push_str("...");
13701 break;
13702 }
13703 }
13704
13705 (text_without_backticks.into(), code_ranges)
13706}
13707
13708fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13709 match severity {
13710 DiagnosticSeverity::ERROR => colors.error,
13711 DiagnosticSeverity::WARNING => colors.warning,
13712 DiagnosticSeverity::INFORMATION => colors.info,
13713 DiagnosticSeverity::HINT => colors.info,
13714 _ => colors.ignored,
13715 }
13716}
13717
13718pub fn styled_runs_for_code_label<'a>(
13719 label: &'a CodeLabel,
13720 syntax_theme: &'a theme::SyntaxTheme,
13721) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13722 let fade_out = HighlightStyle {
13723 fade_out: Some(0.35),
13724 ..Default::default()
13725 };
13726
13727 let mut prev_end = label.filter_range.end;
13728 label
13729 .runs
13730 .iter()
13731 .enumerate()
13732 .flat_map(move |(ix, (range, highlight_id))| {
13733 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13734 style
13735 } else {
13736 return Default::default();
13737 };
13738 let mut muted_style = style;
13739 muted_style.highlight(fade_out);
13740
13741 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13742 if range.start >= label.filter_range.end {
13743 if range.start > prev_end {
13744 runs.push((prev_end..range.start, fade_out));
13745 }
13746 runs.push((range.clone(), muted_style));
13747 } else if range.end <= label.filter_range.end {
13748 runs.push((range.clone(), style));
13749 } else {
13750 runs.push((range.start..label.filter_range.end, style));
13751 runs.push((label.filter_range.end..range.end, muted_style));
13752 }
13753 prev_end = cmp::max(prev_end, range.end);
13754
13755 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13756 runs.push((prev_end..label.text.len(), fade_out));
13757 }
13758
13759 runs
13760 })
13761}
13762
13763pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13764 let mut prev_index = 0;
13765 let mut prev_codepoint: Option<char> = None;
13766 text.char_indices()
13767 .chain([(text.len(), '\0')])
13768 .filter_map(move |(index, codepoint)| {
13769 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13770 let is_boundary = index == text.len()
13771 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13772 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13773 if is_boundary {
13774 let chunk = &text[prev_index..index];
13775 prev_index = index;
13776 Some(chunk)
13777 } else {
13778 None
13779 }
13780 })
13781}
13782
13783pub trait RangeToAnchorExt: Sized {
13784 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13785
13786 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13787 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13788 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13789 }
13790}
13791
13792impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13793 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13794 let start_offset = self.start.to_offset(snapshot);
13795 let end_offset = self.end.to_offset(snapshot);
13796 if start_offset == end_offset {
13797 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13798 } else {
13799 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13800 }
13801 }
13802}
13803
13804pub trait RowExt {
13805 fn as_f32(&self) -> f32;
13806
13807 fn next_row(&self) -> Self;
13808
13809 fn previous_row(&self) -> Self;
13810
13811 fn minus(&self, other: Self) -> u32;
13812}
13813
13814impl RowExt for DisplayRow {
13815 fn as_f32(&self) -> f32 {
13816 self.0 as f32
13817 }
13818
13819 fn next_row(&self) -> Self {
13820 Self(self.0 + 1)
13821 }
13822
13823 fn previous_row(&self) -> Self {
13824 Self(self.0.saturating_sub(1))
13825 }
13826
13827 fn minus(&self, other: Self) -> u32 {
13828 self.0 - other.0
13829 }
13830}
13831
13832impl RowExt for MultiBufferRow {
13833 fn as_f32(&self) -> f32 {
13834 self.0 as f32
13835 }
13836
13837 fn next_row(&self) -> Self {
13838 Self(self.0 + 1)
13839 }
13840
13841 fn previous_row(&self) -> Self {
13842 Self(self.0.saturating_sub(1))
13843 }
13844
13845 fn minus(&self, other: Self) -> u32 {
13846 self.0 - other.0
13847 }
13848}
13849
13850trait RowRangeExt {
13851 type Row;
13852
13853 fn len(&self) -> usize;
13854
13855 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13856}
13857
13858impl RowRangeExt for Range<MultiBufferRow> {
13859 type Row = MultiBufferRow;
13860
13861 fn len(&self) -> usize {
13862 (self.end.0 - self.start.0) as usize
13863 }
13864
13865 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13866 (self.start.0..self.end.0).map(MultiBufferRow)
13867 }
13868}
13869
13870impl RowRangeExt for Range<DisplayRow> {
13871 type Row = DisplayRow;
13872
13873 fn len(&self) -> usize {
13874 (self.end.0 - self.start.0) as usize
13875 }
13876
13877 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13878 (self.start.0..self.end.0).map(DisplayRow)
13879 }
13880}
13881
13882fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
13883 if hunk.diff_base_byte_range.is_empty() {
13884 DiffHunkStatus::Added
13885 } else if hunk.row_range.is_empty() {
13886 DiffHunkStatus::Removed
13887 } else {
13888 DiffHunkStatus::Modified
13889 }
13890}
13891
13892/// If select range has more than one line, we
13893/// just point the cursor to range.start.
13894fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13895 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13896 range
13897 } else {
13898 range.start..range.start
13899 }
13900}