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;
101pub use proposed_changes_editor::{
102 ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use task::{ResolvedTask, TaskTemplate, TaskVariables};
106
107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
108pub use lsp::CompletionContext;
109use lsp::{
110 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
111 LanguageServerId,
112};
113use mouse_context_menu::MouseContextMenu;
114use movement::TextLayoutDetails;
115pub use multi_buffer::{
116 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
117 ToPoint,
118};
119use multi_buffer::{
120 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
121};
122use ordered_float::OrderedFloat;
123use parking_lot::{Mutex, RwLock};
124use project::project_settings::{GitGutterSetting, ProjectSettings};
125use project::{
126 lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
127 ProjectPath, ProjectTransaction, TaskSourceKind,
128};
129use rand::prelude::*;
130use rpc::{proto::*, ErrorExt};
131use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
132use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
133use serde::{Deserialize, Serialize};
134use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
135use smallvec::SmallVec;
136use snippet::Snippet;
137use std::{
138 any::TypeId,
139 borrow::Cow,
140 cell::RefCell,
141 cmp::{self, Ordering, Reverse},
142 mem,
143 num::NonZeroU32,
144 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
145 path::{Path, PathBuf},
146 rc::Rc,
147 sync::Arc,
148 time::{Duration, Instant},
149};
150pub use sum_tree::Bias;
151use sum_tree::TreeMap;
152use text::{BufferId, OffsetUtf16, Rope};
153use theme::{
154 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
155 ThemeColors, ThemeSettings,
156};
157use ui::{
158 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
159 ListItem, Popover, PopoverMenuHandle, Tooltip,
160};
161use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
162use workspace::item::{ItemHandle, PreviewTabsSettings};
163use workspace::notifications::{DetachAndPromptErr, NotificationId};
164use workspace::{
165 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
166};
167use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
168
169use crate::hover_links::find_url;
170use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
171
172pub const FILE_HEADER_HEIGHT: u32 = 1;
173pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
174pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
175pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
176const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
177const MAX_LINE_LEN: usize = 1024;
178const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
179const MAX_SELECTION_HISTORY_LEN: usize = 1024;
180pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
181#[doc(hidden)]
182pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
183#[doc(hidden)]
184pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
185
186pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
187pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
188
189pub fn render_parsed_markdown(
190 element_id: impl Into<ElementId>,
191 parsed: &language::ParsedMarkdown,
192 editor_style: &EditorStyle,
193 workspace: Option<WeakView<Workspace>>,
194 cx: &mut WindowContext,
195) -> InteractiveText {
196 let code_span_background_color = cx
197 .theme()
198 .colors()
199 .editor_document_highlight_read_background;
200
201 let highlights = gpui::combine_highlights(
202 parsed.highlights.iter().filter_map(|(range, highlight)| {
203 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
204 Some((range.clone(), highlight))
205 }),
206 parsed
207 .regions
208 .iter()
209 .zip(&parsed.region_ranges)
210 .filter_map(|(region, range)| {
211 if region.code {
212 Some((
213 range.clone(),
214 HighlightStyle {
215 background_color: Some(code_span_background_color),
216 ..Default::default()
217 },
218 ))
219 } else {
220 None
221 }
222 }),
223 );
224
225 let mut links = Vec::new();
226 let mut link_ranges = Vec::new();
227 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
228 if let Some(link) = region.link.clone() {
229 links.push(link);
230 link_ranges.push(range.clone());
231 }
232 }
233
234 InteractiveText::new(
235 element_id,
236 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
237 )
238 .on_click(link_ranges, move |clicked_range_ix, cx| {
239 match &links[clicked_range_ix] {
240 markdown::Link::Web { url } => cx.open_url(url),
241 markdown::Link::Path { path } => {
242 if let Some(workspace) = &workspace {
243 _ = workspace.update(cx, |workspace, cx| {
244 workspace.open_abs_path(path.clone(), false, cx).detach();
245 });
246 }
247 }
248 }
249 })
250}
251
252#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
253pub(crate) enum InlayId {
254 Suggestion(usize),
255 Hint(usize),
256}
257
258impl InlayId {
259 fn id(&self) -> usize {
260 match self {
261 Self::Suggestion(id) => *id,
262 Self::Hint(id) => *id,
263 }
264 }
265}
266
267enum DiffRowHighlight {}
268enum DocumentHighlightRead {}
269enum DocumentHighlightWrite {}
270enum InputComposition {}
271
272#[derive(Copy, Clone, PartialEq, Eq)]
273pub enum Direction {
274 Prev,
275 Next,
276}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut AppContext) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut AppContext) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new_views(
306 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
318 Editor::new_file(workspace, &Default::default(), cx)
319 })
320 .detach();
321 }
322 });
323 cx.on_action(move |_: &workspace::NewWindow, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
327 Editor::new_file(workspace, &Default::default(), cx)
328 })
329 .detach();
330 }
331 });
332}
333
334pub struct SearchWithinRange;
335
336trait InvalidationRegion {
337 fn ranges(&self) -> &[Range<Anchor>];
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum SelectPhase {
342 Begin {
343 position: DisplayPoint,
344 add: bool,
345 click_count: usize,
346 },
347 BeginColumnar {
348 position: DisplayPoint,
349 reset: bool,
350 goal_column: u32,
351 },
352 Extend {
353 position: DisplayPoint,
354 click_count: usize,
355 },
356 Update {
357 position: DisplayPoint,
358 goal_column: u32,
359 scroll_delta: gpui::Point<f32>,
360 },
361 End,
362}
363
364#[derive(Clone, Debug)]
365pub enum SelectMode {
366 Character,
367 Word(Range<Anchor>),
368 Line(Range<Anchor>),
369 All,
370}
371
372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
373pub enum EditorMode {
374 SingleLine { auto_width: bool },
375 AutoHeight { max_lines: usize },
376 Full,
377}
378
379#[derive(Clone, Debug)]
380pub enum SoftWrap {
381 None,
382 PreferLine,
383 EditorWidth,
384 Column(u32),
385 Bounded(u32),
386}
387
388#[derive(Clone)]
389pub struct EditorStyle {
390 pub background: Hsla,
391 pub local_player: PlayerColor,
392 pub text: TextStyle,
393 pub scrollbar_width: Pixels,
394 pub syntax: Arc<SyntaxTheme>,
395 pub status: StatusColors,
396 pub inlay_hints_style: HighlightStyle,
397 pub suggestions_style: HighlightStyle,
398 pub unnecessary_code_fade: f32,
399}
400
401impl Default for EditorStyle {
402 fn default() -> Self {
403 Self {
404 background: Hsla::default(),
405 local_player: PlayerColor::default(),
406 text: TextStyle::default(),
407 scrollbar_width: Pixels::default(),
408 syntax: Default::default(),
409 // HACK: Status colors don't have a real default.
410 // We should look into removing the status colors from the editor
411 // style and retrieve them directly from the theme.
412 status: StatusColors::dark(),
413 inlay_hints_style: HighlightStyle::default(),
414 suggestions_style: HighlightStyle::default(),
415 unnecessary_code_fade: Default::default(),
416 }
417 }
418}
419
420pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
421 let show_background = all_language_settings(None, cx)
422 .language(None)
423 .inlay_hints
424 .show_background;
425
426 HighlightStyle {
427 color: Some(cx.theme().status().hint),
428 background_color: show_background.then(|| cx.theme().status().hint_background),
429 ..HighlightStyle::default()
430 }
431}
432
433type CompletionId = usize;
434
435#[derive(Clone, Debug)]
436struct CompletionState {
437 // render_inlay_ids represents the inlay hints that are inserted
438 // for rendering the inline completions. They may be discontinuous
439 // in the event that the completion provider returns some intersection
440 // with the existing content.
441 render_inlay_ids: Vec<InlayId>,
442 // text is the resulting rope that is inserted when the user accepts a completion.
443 text: Rope,
444 // position is the position of the cursor when the completion was triggered.
445 position: multi_buffer::Anchor,
446 // delete_range is the range of text that this completion state covers.
447 // if the completion is accepted, this range should be deleted.
448 delete_range: Option<Range<multi_buffer::Anchor>>,
449}
450
451#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
452struct EditorActionId(usize);
453
454impl EditorActionId {
455 pub fn post_inc(&mut self) -> Self {
456 let answer = self.0;
457
458 *self = Self(answer + 1);
459
460 Self(answer)
461 }
462}
463
464// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
465// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
466
467type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
468type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
469
470#[derive(Default)]
471struct ScrollbarMarkerState {
472 scrollbar_size: Size<Pixels>,
473 dirty: bool,
474 markers: Arc<[PaintQuad]>,
475 pending_refresh: Option<Task<Result<()>>>,
476}
477
478impl ScrollbarMarkerState {
479 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
480 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
481 }
482}
483
484#[derive(Clone, Debug)]
485struct RunnableTasks {
486 templates: Vec<(TaskSourceKind, TaskTemplate)>,
487 offset: MultiBufferOffset,
488 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
489 column: u32,
490 // Values of all named captures, including those starting with '_'
491 extra_variables: HashMap<String, String>,
492 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
493 context_range: Range<BufferOffset>,
494}
495
496#[derive(Clone)]
497struct ResolvedTasks {
498 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
499 position: Anchor,
500}
501#[derive(Copy, Clone, Debug)]
502struct MultiBufferOffset(usize);
503#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
504struct BufferOffset(usize);
505
506// Addons allow storing per-editor state in other crates (e.g. Vim)
507pub trait Addon: 'static {
508 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
509
510 fn to_any(&self) -> &dyn std::any::Any;
511}
512
513/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
514///
515/// See the [module level documentation](self) for more information.
516pub struct Editor {
517 focus_handle: FocusHandle,
518 last_focused_descendant: Option<WeakFocusHandle>,
519 /// The text buffer being edited
520 buffer: Model<MultiBuffer>,
521 /// Map of how text in the buffer should be displayed.
522 /// Handles soft wraps, folds, fake inlay text insertions, etc.
523 pub display_map: Model<DisplayMap>,
524 pub selections: SelectionsCollection,
525 pub scroll_manager: ScrollManager,
526 /// When inline assist editors are linked, they all render cursors because
527 /// typing enters text into each of them, even the ones that aren't focused.
528 pub(crate) show_cursor_when_unfocused: bool,
529 columnar_selection_tail: Option<Anchor>,
530 add_selections_state: Option<AddSelectionsState>,
531 select_next_state: Option<SelectNextState>,
532 select_prev_state: Option<SelectNextState>,
533 selection_history: SelectionHistory,
534 autoclose_regions: Vec<AutocloseRegion>,
535 snippet_stack: InvalidationStack<SnippetState>,
536 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
537 ime_transaction: Option<TransactionId>,
538 active_diagnostics: Option<ActiveDiagnosticGroup>,
539 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
540 project: Option<Model<Project>>,
541 completion_provider: Option<Box<dyn CompletionProvider>>,
542 collaboration_hub: Option<Box<dyn CollaborationHub>>,
543 blink_manager: Model<BlinkManager>,
544 show_cursor_names: bool,
545 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
546 pub show_local_selections: bool,
547 mode: EditorMode,
548 show_breadcrumbs: bool,
549 show_gutter: bool,
550 show_line_numbers: Option<bool>,
551 use_relative_line_numbers: Option<bool>,
552 show_git_diff_gutter: Option<bool>,
553 show_code_actions: Option<bool>,
554 show_runnables: Option<bool>,
555 show_wrap_guides: Option<bool>,
556 show_indent_guides: Option<bool>,
557 placeholder_text: Option<Arc<str>>,
558 highlight_order: usize,
559 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
560 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
561 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
562 scrollbar_marker_state: ScrollbarMarkerState,
563 active_indent_guides_state: ActiveIndentGuidesState,
564 nav_history: Option<ItemNavHistory>,
565 context_menu: RwLock<Option<ContextMenu>>,
566 mouse_context_menu: Option<MouseContextMenu>,
567 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
568 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
569 signature_help_state: SignatureHelpState,
570 auto_signature_help: Option<bool>,
571 find_all_references_task_sources: Vec<Anchor>,
572 next_completion_id: CompletionId,
573 completion_documentation_pre_resolve_debounce: DebouncedDelay,
574 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
575 code_actions_task: Option<Task<Result<()>>>,
576 document_highlights_task: Option<Task<()>>,
577 linked_editing_range_task: Option<Task<Option<()>>>,
578 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
579 pending_rename: Option<RenameState>,
580 searchable: bool,
581 cursor_shape: CursorShape,
582 current_line_highlight: Option<CurrentLineHighlight>,
583 collapse_matches: bool,
584 autoindent_mode: Option<AutoindentMode>,
585 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
586 input_enabled: bool,
587 use_modal_editing: bool,
588 read_only: bool,
589 leader_peer_id: Option<PeerId>,
590 remote_id: Option<ViewId>,
591 hover_state: HoverState,
592 gutter_hovered: bool,
593 hovered_link_state: Option<HoveredLinkState>,
594 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
595 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
596 active_inline_completion: Option<CompletionState>,
597 // enable_inline_completions is a switch that Vim can use to disable
598 // inline completions based on its mode.
599 enable_inline_completions: bool,
600 show_inline_completions_override: Option<bool>,
601 inlay_hint_cache: InlayHintCache,
602 expanded_hunks: ExpandedHunks,
603 next_inlay_id: usize,
604 _subscriptions: Vec<Subscription>,
605 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
606 gutter_dimensions: GutterDimensions,
607 style: Option<EditorStyle>,
608 next_editor_action_id: EditorActionId,
609 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
610 use_autoclose: bool,
611 use_auto_surround: bool,
612 auto_replace_emoji_shortcode: bool,
613 show_git_blame_gutter: bool,
614 show_git_blame_inline: bool,
615 show_git_blame_inline_delay_task: Option<Task<()>>,
616 git_blame_inline_enabled: bool,
617 serialize_dirty_buffers: bool,
618 show_selection_menu: Option<bool>,
619 blame: Option<Model<GitBlame>>,
620 blame_subscription: Option<Subscription>,
621 custom_context_menu: Option<
622 Box<
623 dyn 'static
624 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
625 >,
626 >,
627 last_bounds: Option<Bounds<Pixels>>,
628 expect_bounds_change: Option<Bounds<Pixels>>,
629 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
630 tasks_update_task: Option<Task<()>>,
631 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
632 file_header_size: u32,
633 breadcrumb_header: Option<String>,
634 focused_block: Option<FocusedBlock>,
635 next_scroll_position: NextScrollCursorCenterTopBottom,
636 addons: HashMap<TypeId, Box<dyn Addon>>,
637 _scroll_cursor_center_top_bottom_task: Task<()>,
638}
639
640#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
641enum NextScrollCursorCenterTopBottom {
642 #[default]
643 Center,
644 Top,
645 Bottom,
646}
647
648impl NextScrollCursorCenterTopBottom {
649 fn next(&self) -> Self {
650 match self {
651 Self::Center => Self::Top,
652 Self::Top => Self::Bottom,
653 Self::Bottom => Self::Center,
654 }
655 }
656}
657
658#[derive(Clone)]
659pub struct EditorSnapshot {
660 pub mode: EditorMode,
661 show_gutter: bool,
662 show_line_numbers: Option<bool>,
663 show_git_diff_gutter: Option<bool>,
664 show_code_actions: Option<bool>,
665 show_runnables: Option<bool>,
666 git_blame_gutter_max_author_length: Option<usize>,
667 pub display_snapshot: DisplaySnapshot,
668 pub placeholder_text: Option<Arc<str>>,
669 is_focused: bool,
670 scroll_anchor: ScrollAnchor,
671 ongoing_scroll: OngoingScroll,
672 current_line_highlight: CurrentLineHighlight,
673 gutter_hovered: bool,
674}
675
676const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
677
678#[derive(Default, Debug, Clone, Copy)]
679pub struct GutterDimensions {
680 pub left_padding: Pixels,
681 pub right_padding: Pixels,
682 pub width: Pixels,
683 pub margin: Pixels,
684 pub git_blame_entries_width: Option<Pixels>,
685}
686
687impl GutterDimensions {
688 /// The full width of the space taken up by the gutter.
689 pub fn full_width(&self) -> Pixels {
690 self.margin + self.width
691 }
692
693 /// The width of the space reserved for the fold indicators,
694 /// use alongside 'justify_end' and `gutter_width` to
695 /// right align content with the line numbers
696 pub fn fold_area_width(&self) -> Pixels {
697 self.margin + self.right_padding
698 }
699}
700
701#[derive(Debug)]
702pub struct RemoteSelection {
703 pub replica_id: ReplicaId,
704 pub selection: Selection<Anchor>,
705 pub cursor_shape: CursorShape,
706 pub peer_id: PeerId,
707 pub line_mode: bool,
708 pub participant_index: Option<ParticipantIndex>,
709 pub user_name: Option<SharedString>,
710}
711
712#[derive(Clone, Debug)]
713struct SelectionHistoryEntry {
714 selections: Arc<[Selection<Anchor>]>,
715 select_next_state: Option<SelectNextState>,
716 select_prev_state: Option<SelectNextState>,
717 add_selections_state: Option<AddSelectionsState>,
718}
719
720enum SelectionHistoryMode {
721 Normal,
722 Undoing,
723 Redoing,
724}
725
726#[derive(Clone, PartialEq, Eq, Hash)]
727struct HoveredCursor {
728 replica_id: u16,
729 selection_id: usize,
730}
731
732impl Default for SelectionHistoryMode {
733 fn default() -> Self {
734 Self::Normal
735 }
736}
737
738#[derive(Default)]
739struct SelectionHistory {
740 #[allow(clippy::type_complexity)]
741 selections_by_transaction:
742 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
743 mode: SelectionHistoryMode,
744 undo_stack: VecDeque<SelectionHistoryEntry>,
745 redo_stack: VecDeque<SelectionHistoryEntry>,
746}
747
748impl SelectionHistory {
749 fn insert_transaction(
750 &mut self,
751 transaction_id: TransactionId,
752 selections: Arc<[Selection<Anchor>]>,
753 ) {
754 self.selections_by_transaction
755 .insert(transaction_id, (selections, None));
756 }
757
758 #[allow(clippy::type_complexity)]
759 fn transaction(
760 &self,
761 transaction_id: TransactionId,
762 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
763 self.selections_by_transaction.get(&transaction_id)
764 }
765
766 #[allow(clippy::type_complexity)]
767 fn transaction_mut(
768 &mut self,
769 transaction_id: TransactionId,
770 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
771 self.selections_by_transaction.get_mut(&transaction_id)
772 }
773
774 fn push(&mut self, entry: SelectionHistoryEntry) {
775 if !entry.selections.is_empty() {
776 match self.mode {
777 SelectionHistoryMode::Normal => {
778 self.push_undo(entry);
779 self.redo_stack.clear();
780 }
781 SelectionHistoryMode::Undoing => self.push_redo(entry),
782 SelectionHistoryMode::Redoing => self.push_undo(entry),
783 }
784 }
785 }
786
787 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
788 if self
789 .undo_stack
790 .back()
791 .map_or(true, |e| e.selections != entry.selections)
792 {
793 self.undo_stack.push_back(entry);
794 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
795 self.undo_stack.pop_front();
796 }
797 }
798 }
799
800 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
801 if self
802 .redo_stack
803 .back()
804 .map_or(true, |e| e.selections != entry.selections)
805 {
806 self.redo_stack.push_back(entry);
807 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
808 self.redo_stack.pop_front();
809 }
810 }
811 }
812}
813
814struct RowHighlight {
815 index: usize,
816 range: RangeInclusive<Anchor>,
817 color: Option<Hsla>,
818 should_autoscroll: bool,
819}
820
821#[derive(Clone, Debug)]
822struct AddSelectionsState {
823 above: bool,
824 stack: Vec<usize>,
825}
826
827#[derive(Clone)]
828struct SelectNextState {
829 query: AhoCorasick,
830 wordwise: bool,
831 done: bool,
832}
833
834impl std::fmt::Debug for SelectNextState {
835 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836 f.debug_struct(std::any::type_name::<Self>())
837 .field("wordwise", &self.wordwise)
838 .field("done", &self.done)
839 .finish()
840 }
841}
842
843#[derive(Debug)]
844struct AutocloseRegion {
845 selection_id: usize,
846 range: Range<Anchor>,
847 pair: BracketPair,
848}
849
850#[derive(Debug)]
851struct SnippetState {
852 ranges: Vec<Vec<Range<Anchor>>>,
853 active_index: usize,
854}
855
856#[doc(hidden)]
857pub struct RenameState {
858 pub range: Range<Anchor>,
859 pub old_name: Arc<str>,
860 pub editor: View<Editor>,
861 block_id: CustomBlockId,
862}
863
864struct InvalidationStack<T>(Vec<T>);
865
866struct RegisteredInlineCompletionProvider {
867 provider: Arc<dyn InlineCompletionProviderHandle>,
868 _subscription: Subscription,
869}
870
871enum ContextMenu {
872 Completions(CompletionsMenu),
873 CodeActions(CodeActionsMenu),
874}
875
876impl ContextMenu {
877 fn select_first(
878 &mut self,
879 project: Option<&Model<Project>>,
880 cx: &mut ViewContext<Editor>,
881 ) -> bool {
882 if self.visible() {
883 match self {
884 ContextMenu::Completions(menu) => menu.select_first(project, cx),
885 ContextMenu::CodeActions(menu) => menu.select_first(cx),
886 }
887 true
888 } else {
889 false
890 }
891 }
892
893 fn select_prev(
894 &mut self,
895 project: Option<&Model<Project>>,
896 cx: &mut ViewContext<Editor>,
897 ) -> bool {
898 if self.visible() {
899 match self {
900 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
901 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
902 }
903 true
904 } else {
905 false
906 }
907 }
908
909 fn select_next(
910 &mut self,
911 project: Option<&Model<Project>>,
912 cx: &mut ViewContext<Editor>,
913 ) -> bool {
914 if self.visible() {
915 match self {
916 ContextMenu::Completions(menu) => menu.select_next(project, cx),
917 ContextMenu::CodeActions(menu) => menu.select_next(cx),
918 }
919 true
920 } else {
921 false
922 }
923 }
924
925 fn select_last(
926 &mut self,
927 project: Option<&Model<Project>>,
928 cx: &mut ViewContext<Editor>,
929 ) -> bool {
930 if self.visible() {
931 match self {
932 ContextMenu::Completions(menu) => menu.select_last(project, cx),
933 ContextMenu::CodeActions(menu) => menu.select_last(cx),
934 }
935 true
936 } else {
937 false
938 }
939 }
940
941 fn visible(&self) -> bool {
942 match self {
943 ContextMenu::Completions(menu) => menu.visible(),
944 ContextMenu::CodeActions(menu) => menu.visible(),
945 }
946 }
947
948 fn render(
949 &self,
950 cursor_position: DisplayPoint,
951 style: &EditorStyle,
952 max_height: Pixels,
953 workspace: Option<WeakView<Workspace>>,
954 cx: &mut ViewContext<Editor>,
955 ) -> (ContextMenuOrigin, AnyElement) {
956 match self {
957 ContextMenu::Completions(menu) => (
958 ContextMenuOrigin::EditorPoint(cursor_position),
959 menu.render(style, max_height, workspace, cx),
960 ),
961 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
962 }
963 }
964}
965
966enum ContextMenuOrigin {
967 EditorPoint(DisplayPoint),
968 GutterIndicator(DisplayRow),
969}
970
971#[derive(Clone)]
972struct CompletionsMenu {
973 id: CompletionId,
974 sort_completions: bool,
975 initial_position: Anchor,
976 buffer: Model<Buffer>,
977 completions: Arc<RwLock<Box<[Completion]>>>,
978 match_candidates: Arc<[StringMatchCandidate]>,
979 matches: Arc<[StringMatch]>,
980 selected_item: usize,
981 scroll_handle: UniformListScrollHandle,
982 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
983}
984
985impl CompletionsMenu {
986 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
987 self.selected_item = 0;
988 self.scroll_handle.scroll_to_item(self.selected_item);
989 self.attempt_resolve_selected_completion_documentation(project, cx);
990 cx.notify();
991 }
992
993 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
994 if self.selected_item > 0 {
995 self.selected_item -= 1;
996 } else {
997 self.selected_item = self.matches.len() - 1;
998 }
999 self.scroll_handle.scroll_to_item(self.selected_item);
1000 self.attempt_resolve_selected_completion_documentation(project, cx);
1001 cx.notify();
1002 }
1003
1004 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1005 if self.selected_item + 1 < self.matches.len() {
1006 self.selected_item += 1;
1007 } else {
1008 self.selected_item = 0;
1009 }
1010 self.scroll_handle.scroll_to_item(self.selected_item);
1011 self.attempt_resolve_selected_completion_documentation(project, cx);
1012 cx.notify();
1013 }
1014
1015 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1016 self.selected_item = self.matches.len() - 1;
1017 self.scroll_handle.scroll_to_item(self.selected_item);
1018 self.attempt_resolve_selected_completion_documentation(project, cx);
1019 cx.notify();
1020 }
1021
1022 fn pre_resolve_completion_documentation(
1023 buffer: Model<Buffer>,
1024 completions: Arc<RwLock<Box<[Completion]>>>,
1025 matches: Arc<[StringMatch]>,
1026 editor: &Editor,
1027 cx: &mut ViewContext<Editor>,
1028 ) -> Task<()> {
1029 let settings = EditorSettings::get_global(cx);
1030 if !settings.show_completion_documentation {
1031 return Task::ready(());
1032 }
1033
1034 let Some(provider) = editor.completion_provider.as_ref() else {
1035 return Task::ready(());
1036 };
1037
1038 let resolve_task = provider.resolve_completions(
1039 buffer,
1040 matches.iter().map(|m| m.candidate_id).collect(),
1041 completions.clone(),
1042 cx,
1043 );
1044
1045 cx.spawn(move |this, mut cx| async move {
1046 if let Some(true) = resolve_task.await.log_err() {
1047 this.update(&mut cx, |_, cx| cx.notify()).ok();
1048 }
1049 })
1050 }
1051
1052 fn attempt_resolve_selected_completion_documentation(
1053 &mut self,
1054 project: Option<&Model<Project>>,
1055 cx: &mut ViewContext<Editor>,
1056 ) {
1057 let settings = EditorSettings::get_global(cx);
1058 if !settings.show_completion_documentation {
1059 return;
1060 }
1061
1062 let completion_index = self.matches[self.selected_item].candidate_id;
1063 let Some(project) = project else {
1064 return;
1065 };
1066
1067 let resolve_task = project.update(cx, |project, cx| {
1068 project.resolve_completions(
1069 self.buffer.clone(),
1070 vec![completion_index],
1071 self.completions.clone(),
1072 cx,
1073 )
1074 });
1075
1076 let delay_ms =
1077 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1078 let delay = Duration::from_millis(delay_ms);
1079
1080 self.selected_completion_documentation_resolve_debounce
1081 .lock()
1082 .fire_new(delay, cx, |_, cx| {
1083 cx.spawn(move |this, mut cx| async move {
1084 if let Some(true) = resolve_task.await.log_err() {
1085 this.update(&mut cx, |_, cx| cx.notify()).ok();
1086 }
1087 })
1088 });
1089 }
1090
1091 fn visible(&self) -> bool {
1092 !self.matches.is_empty()
1093 }
1094
1095 fn render(
1096 &self,
1097 style: &EditorStyle,
1098 max_height: Pixels,
1099 workspace: Option<WeakView<Workspace>>,
1100 cx: &mut ViewContext<Editor>,
1101 ) -> AnyElement {
1102 let settings = EditorSettings::get_global(cx);
1103 let show_completion_documentation = settings.show_completion_documentation;
1104
1105 let widest_completion_ix = self
1106 .matches
1107 .iter()
1108 .enumerate()
1109 .max_by_key(|(_, mat)| {
1110 let completions = self.completions.read();
1111 let completion = &completions[mat.candidate_id];
1112 let documentation = &completion.documentation;
1113
1114 let mut len = completion.label.text.chars().count();
1115 if let Some(Documentation::SingleLine(text)) = documentation {
1116 if show_completion_documentation {
1117 len += text.chars().count();
1118 }
1119 }
1120
1121 len
1122 })
1123 .map(|(ix, _)| ix);
1124
1125 let completions = self.completions.clone();
1126 let matches = self.matches.clone();
1127 let selected_item = self.selected_item;
1128 let style = style.clone();
1129
1130 let multiline_docs = if show_completion_documentation {
1131 let mat = &self.matches[selected_item];
1132 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1133 Some(Documentation::MultiLinePlainText(text)) => {
1134 Some(div().child(SharedString::from(text.clone())))
1135 }
1136 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1137 Some(div().child(render_parsed_markdown(
1138 "completions_markdown",
1139 parsed,
1140 &style,
1141 workspace,
1142 cx,
1143 )))
1144 }
1145 _ => None,
1146 };
1147 multiline_docs.map(|div| {
1148 div.id("multiline_docs")
1149 .max_h(max_height)
1150 .flex_1()
1151 .px_1p5()
1152 .py_1()
1153 .min_w(px(260.))
1154 .max_w(px(640.))
1155 .w(px(500.))
1156 .overflow_y_scroll()
1157 .occlude()
1158 })
1159 } else {
1160 None
1161 };
1162
1163 let list = uniform_list(
1164 cx.view().clone(),
1165 "completions",
1166 matches.len(),
1167 move |_editor, range, cx| {
1168 let start_ix = range.start;
1169 let completions_guard = completions.read();
1170
1171 matches[range]
1172 .iter()
1173 .enumerate()
1174 .map(|(ix, mat)| {
1175 let item_ix = start_ix + ix;
1176 let candidate_id = mat.candidate_id;
1177 let completion = &completions_guard[candidate_id];
1178
1179 let documentation = if show_completion_documentation {
1180 &completion.documentation
1181 } else {
1182 &None
1183 };
1184
1185 let highlights = gpui::combine_highlights(
1186 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1187 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1188 |(range, mut highlight)| {
1189 // Ignore font weight for syntax highlighting, as we'll use it
1190 // for fuzzy matches.
1191 highlight.font_weight = None;
1192
1193 if completion.lsp_completion.deprecated.unwrap_or(false) {
1194 highlight.strikethrough = Some(StrikethroughStyle {
1195 thickness: 1.0.into(),
1196 ..Default::default()
1197 });
1198 highlight.color = Some(cx.theme().colors().text_muted);
1199 }
1200
1201 (range, highlight)
1202 },
1203 ),
1204 );
1205 let completion_label = StyledText::new(completion.label.text.clone())
1206 .with_highlights(&style.text, highlights);
1207 let documentation_label =
1208 if let Some(Documentation::SingleLine(text)) = documentation {
1209 if text.trim().is_empty() {
1210 None
1211 } else {
1212 Some(
1213 Label::new(text.clone())
1214 .ml_4()
1215 .size(LabelSize::Small)
1216 .color(Color::Muted),
1217 )
1218 }
1219 } else {
1220 None
1221 };
1222
1223 div().min_w(px(220.)).max_w(px(540.)).child(
1224 ListItem::new(mat.candidate_id)
1225 .inset(true)
1226 .selected(item_ix == selected_item)
1227 .on_click(cx.listener(move |editor, _event, cx| {
1228 cx.stop_propagation();
1229 if let Some(task) = editor.confirm_completion(
1230 &ConfirmCompletion {
1231 item_ix: Some(item_ix),
1232 },
1233 cx,
1234 ) {
1235 task.detach_and_log_err(cx)
1236 }
1237 }))
1238 .child(h_flex().overflow_hidden().child(completion_label))
1239 .end_slot::<Label>(documentation_label),
1240 )
1241 })
1242 .collect()
1243 },
1244 )
1245 .occlude()
1246 .max_h(max_height)
1247 .track_scroll(self.scroll_handle.clone())
1248 .with_width_from_item(widest_completion_ix)
1249 .with_sizing_behavior(ListSizingBehavior::Infer);
1250
1251 Popover::new()
1252 .child(list)
1253 .when_some(multiline_docs, |popover, multiline_docs| {
1254 popover.aside(multiline_docs)
1255 })
1256 .into_any_element()
1257 }
1258
1259 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1260 let mut matches = if let Some(query) = query {
1261 fuzzy::match_strings(
1262 &self.match_candidates,
1263 query,
1264 query.chars().any(|c| c.is_uppercase()),
1265 100,
1266 &Default::default(),
1267 executor,
1268 )
1269 .await
1270 } else {
1271 self.match_candidates
1272 .iter()
1273 .enumerate()
1274 .map(|(candidate_id, candidate)| StringMatch {
1275 candidate_id,
1276 score: Default::default(),
1277 positions: Default::default(),
1278 string: candidate.string.clone(),
1279 })
1280 .collect()
1281 };
1282
1283 // Remove all candidates where the query's start does not match the start of any word in the candidate
1284 if let Some(query) = query {
1285 if let Some(query_start) = query.chars().next() {
1286 matches.retain(|string_match| {
1287 split_words(&string_match.string).any(|word| {
1288 // Check that the first codepoint of the word as lowercase matches the first
1289 // codepoint of the query as lowercase
1290 word.chars()
1291 .flat_map(|codepoint| codepoint.to_lowercase())
1292 .zip(query_start.to_lowercase())
1293 .all(|(word_cp, query_cp)| word_cp == query_cp)
1294 })
1295 });
1296 }
1297 }
1298
1299 let completions = self.completions.read();
1300 if self.sort_completions {
1301 matches.sort_unstable_by_key(|mat| {
1302 // We do want to strike a balance here between what the language server tells us
1303 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1304 // `Creat` and there is a local variable called `CreateComponent`).
1305 // So what we do is: we bucket all matches into two buckets
1306 // - Strong matches
1307 // - Weak matches
1308 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1309 // and the Weak matches are the rest.
1310 //
1311 // For the strong matches, we sort by the language-servers score first and for the weak
1312 // matches, we prefer our fuzzy finder first.
1313 //
1314 // The thinking behind that: it's useless to take the sort_text the language-server gives
1315 // us into account when it's obviously a bad match.
1316
1317 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1318 enum MatchScore<'a> {
1319 Strong {
1320 sort_text: Option<&'a str>,
1321 score: Reverse<OrderedFloat<f64>>,
1322 sort_key: (usize, &'a str),
1323 },
1324 Weak {
1325 score: Reverse<OrderedFloat<f64>>,
1326 sort_text: Option<&'a str>,
1327 sort_key: (usize, &'a str),
1328 },
1329 }
1330
1331 let completion = &completions[mat.candidate_id];
1332 let sort_key = completion.sort_key();
1333 let sort_text = completion.lsp_completion.sort_text.as_deref();
1334 let score = Reverse(OrderedFloat(mat.score));
1335
1336 if mat.score >= 0.2 {
1337 MatchScore::Strong {
1338 sort_text,
1339 score,
1340 sort_key,
1341 }
1342 } else {
1343 MatchScore::Weak {
1344 score,
1345 sort_text,
1346 sort_key,
1347 }
1348 }
1349 });
1350 }
1351
1352 for mat in &mut matches {
1353 let completion = &completions[mat.candidate_id];
1354 mat.string.clone_from(&completion.label.text);
1355 for position in &mut mat.positions {
1356 *position += completion.label.filter_range.start;
1357 }
1358 }
1359 drop(completions);
1360
1361 self.matches = matches.into();
1362 self.selected_item = 0;
1363 }
1364}
1365
1366struct AvailableCodeAction {
1367 excerpt_id: ExcerptId,
1368 action: CodeAction,
1369 provider: Arc<dyn CodeActionProvider>,
1370}
1371
1372#[derive(Clone)]
1373struct CodeActionContents {
1374 tasks: Option<Arc<ResolvedTasks>>,
1375 actions: Option<Arc<[AvailableCodeAction]>>,
1376}
1377
1378impl CodeActionContents {
1379 fn len(&self) -> usize {
1380 match (&self.tasks, &self.actions) {
1381 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1382 (Some(tasks), None) => tasks.templates.len(),
1383 (None, Some(actions)) => actions.len(),
1384 (None, None) => 0,
1385 }
1386 }
1387
1388 fn is_empty(&self) -> bool {
1389 match (&self.tasks, &self.actions) {
1390 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1391 (Some(tasks), None) => tasks.templates.is_empty(),
1392 (None, Some(actions)) => actions.is_empty(),
1393 (None, None) => true,
1394 }
1395 }
1396
1397 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1398 self.tasks
1399 .iter()
1400 .flat_map(|tasks| {
1401 tasks
1402 .templates
1403 .iter()
1404 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1405 })
1406 .chain(self.actions.iter().flat_map(|actions| {
1407 actions.iter().map(|available| CodeActionsItem::CodeAction {
1408 excerpt_id: available.excerpt_id,
1409 action: available.action.clone(),
1410 provider: available.provider.clone(),
1411 })
1412 }))
1413 }
1414 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1415 match (&self.tasks, &self.actions) {
1416 (Some(tasks), Some(actions)) => {
1417 if index < tasks.templates.len() {
1418 tasks
1419 .templates
1420 .get(index)
1421 .cloned()
1422 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1423 } else {
1424 actions.get(index - tasks.templates.len()).map(|available| {
1425 CodeActionsItem::CodeAction {
1426 excerpt_id: available.excerpt_id,
1427 action: available.action.clone(),
1428 provider: available.provider.clone(),
1429 }
1430 })
1431 }
1432 }
1433 (Some(tasks), None) => tasks
1434 .templates
1435 .get(index)
1436 .cloned()
1437 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1438 (None, Some(actions)) => {
1439 actions
1440 .get(index)
1441 .map(|available| CodeActionsItem::CodeAction {
1442 excerpt_id: available.excerpt_id,
1443 action: available.action.clone(),
1444 provider: available.provider.clone(),
1445 })
1446 }
1447 (None, None) => None,
1448 }
1449 }
1450}
1451
1452#[allow(clippy::large_enum_variant)]
1453#[derive(Clone)]
1454enum CodeActionsItem {
1455 Task(TaskSourceKind, ResolvedTask),
1456 CodeAction {
1457 excerpt_id: ExcerptId,
1458 action: CodeAction,
1459 provider: Arc<dyn CodeActionProvider>,
1460 },
1461}
1462
1463impl CodeActionsItem {
1464 fn as_task(&self) -> Option<&ResolvedTask> {
1465 let Self::Task(_, task) = self else {
1466 return None;
1467 };
1468 Some(task)
1469 }
1470 fn as_code_action(&self) -> Option<&CodeAction> {
1471 let Self::CodeAction { action, .. } = self else {
1472 return None;
1473 };
1474 Some(action)
1475 }
1476 fn label(&self) -> String {
1477 match self {
1478 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1479 Self::Task(_, task) => task.resolved_label.clone(),
1480 }
1481 }
1482}
1483
1484struct CodeActionsMenu {
1485 actions: CodeActionContents,
1486 buffer: Model<Buffer>,
1487 selected_item: usize,
1488 scroll_handle: UniformListScrollHandle,
1489 deployed_from_indicator: Option<DisplayRow>,
1490}
1491
1492impl CodeActionsMenu {
1493 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1494 self.selected_item = 0;
1495 self.scroll_handle.scroll_to_item(self.selected_item);
1496 cx.notify()
1497 }
1498
1499 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1500 if self.selected_item > 0 {
1501 self.selected_item -= 1;
1502 } else {
1503 self.selected_item = self.actions.len() - 1;
1504 }
1505 self.scroll_handle.scroll_to_item(self.selected_item);
1506 cx.notify();
1507 }
1508
1509 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1510 if self.selected_item + 1 < self.actions.len() {
1511 self.selected_item += 1;
1512 } else {
1513 self.selected_item = 0;
1514 }
1515 self.scroll_handle.scroll_to_item(self.selected_item);
1516 cx.notify();
1517 }
1518
1519 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1520 self.selected_item = self.actions.len() - 1;
1521 self.scroll_handle.scroll_to_item(self.selected_item);
1522 cx.notify()
1523 }
1524
1525 fn visible(&self) -> bool {
1526 !self.actions.is_empty()
1527 }
1528
1529 fn render(
1530 &self,
1531 cursor_position: DisplayPoint,
1532 _style: &EditorStyle,
1533 max_height: Pixels,
1534 cx: &mut ViewContext<Editor>,
1535 ) -> (ContextMenuOrigin, AnyElement) {
1536 let actions = self.actions.clone();
1537 let selected_item = self.selected_item;
1538 let element = uniform_list(
1539 cx.view().clone(),
1540 "code_actions_menu",
1541 self.actions.len(),
1542 move |_this, range, cx| {
1543 actions
1544 .iter()
1545 .skip(range.start)
1546 .take(range.end - range.start)
1547 .enumerate()
1548 .map(|(ix, action)| {
1549 let item_ix = range.start + ix;
1550 let selected = selected_item == item_ix;
1551 let colors = cx.theme().colors();
1552 div()
1553 .px_1()
1554 .rounded_md()
1555 .text_color(colors.text)
1556 .when(selected, |style| {
1557 style
1558 .bg(colors.element_active)
1559 .text_color(colors.text_accent)
1560 })
1561 .hover(|style| {
1562 style
1563 .bg(colors.element_hover)
1564 .text_color(colors.text_accent)
1565 })
1566 .whitespace_nowrap()
1567 .when_some(action.as_code_action(), |this, action| {
1568 this.on_mouse_down(
1569 MouseButton::Left,
1570 cx.listener(move |editor, _, cx| {
1571 cx.stop_propagation();
1572 if let Some(task) = editor.confirm_code_action(
1573 &ConfirmCodeAction {
1574 item_ix: Some(item_ix),
1575 },
1576 cx,
1577 ) {
1578 task.detach_and_log_err(cx)
1579 }
1580 }),
1581 )
1582 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1583 .child(SharedString::from(action.lsp_action.title.clone()))
1584 })
1585 .when_some(action.as_task(), |this, task| {
1586 this.on_mouse_down(
1587 MouseButton::Left,
1588 cx.listener(move |editor, _, cx| {
1589 cx.stop_propagation();
1590 if let Some(task) = editor.confirm_code_action(
1591 &ConfirmCodeAction {
1592 item_ix: Some(item_ix),
1593 },
1594 cx,
1595 ) {
1596 task.detach_and_log_err(cx)
1597 }
1598 }),
1599 )
1600 .child(SharedString::from(task.resolved_label.clone()))
1601 })
1602 })
1603 .collect()
1604 },
1605 )
1606 .elevation_1(cx)
1607 .p_1()
1608 .max_h(max_height)
1609 .occlude()
1610 .track_scroll(self.scroll_handle.clone())
1611 .with_width_from_item(
1612 self.actions
1613 .iter()
1614 .enumerate()
1615 .max_by_key(|(_, action)| match action {
1616 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1617 CodeActionsItem::CodeAction { action, .. } => {
1618 action.lsp_action.title.chars().count()
1619 }
1620 })
1621 .map(|(ix, _)| ix),
1622 )
1623 .with_sizing_behavior(ListSizingBehavior::Infer)
1624 .into_any_element();
1625
1626 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1627 ContextMenuOrigin::GutterIndicator(row)
1628 } else {
1629 ContextMenuOrigin::EditorPoint(cursor_position)
1630 };
1631
1632 (cursor_position, element)
1633 }
1634}
1635
1636#[derive(Debug)]
1637struct ActiveDiagnosticGroup {
1638 primary_range: Range<Anchor>,
1639 primary_message: String,
1640 group_id: usize,
1641 blocks: HashMap<CustomBlockId, Diagnostic>,
1642 is_valid: bool,
1643}
1644
1645#[derive(Serialize, Deserialize, Clone, Debug)]
1646pub struct ClipboardSelection {
1647 pub len: usize,
1648 pub is_entire_line: bool,
1649 pub first_line_indent: u32,
1650}
1651
1652#[derive(Debug)]
1653pub(crate) struct NavigationData {
1654 cursor_anchor: Anchor,
1655 cursor_position: Point,
1656 scroll_anchor: ScrollAnchor,
1657 scroll_top_row: u32,
1658}
1659
1660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1661enum GotoDefinitionKind {
1662 Symbol,
1663 Declaration,
1664 Type,
1665 Implementation,
1666}
1667
1668#[derive(Debug, Clone)]
1669enum InlayHintRefreshReason {
1670 Toggle(bool),
1671 SettingsChange(InlayHintSettings),
1672 NewLinesShown,
1673 BufferEdited(HashSet<Arc<Language>>),
1674 RefreshRequested,
1675 ExcerptsRemoved(Vec<ExcerptId>),
1676}
1677
1678impl InlayHintRefreshReason {
1679 fn description(&self) -> &'static str {
1680 match self {
1681 Self::Toggle(_) => "toggle",
1682 Self::SettingsChange(_) => "settings change",
1683 Self::NewLinesShown => "new lines shown",
1684 Self::BufferEdited(_) => "buffer edited",
1685 Self::RefreshRequested => "refresh requested",
1686 Self::ExcerptsRemoved(_) => "excerpts removed",
1687 }
1688 }
1689}
1690
1691pub(crate) struct FocusedBlock {
1692 id: BlockId,
1693 focus_handle: WeakFocusHandle,
1694}
1695
1696impl Editor {
1697 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1698 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1699 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1700 Self::new(
1701 EditorMode::SingleLine { auto_width: false },
1702 buffer,
1703 None,
1704 false,
1705 cx,
1706 )
1707 }
1708
1709 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1710 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1711 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1712 Self::new(EditorMode::Full, buffer, None, false, cx)
1713 }
1714
1715 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1716 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1717 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1718 Self::new(
1719 EditorMode::SingleLine { auto_width: true },
1720 buffer,
1721 None,
1722 false,
1723 cx,
1724 )
1725 }
1726
1727 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1728 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1729 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1730 Self::new(
1731 EditorMode::AutoHeight { max_lines },
1732 buffer,
1733 None,
1734 false,
1735 cx,
1736 )
1737 }
1738
1739 pub fn for_buffer(
1740 buffer: Model<Buffer>,
1741 project: Option<Model<Project>>,
1742 cx: &mut ViewContext<Self>,
1743 ) -> Self {
1744 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1745 Self::new(EditorMode::Full, buffer, project, false, cx)
1746 }
1747
1748 pub fn for_multibuffer(
1749 buffer: Model<MultiBuffer>,
1750 project: Option<Model<Project>>,
1751 show_excerpt_controls: bool,
1752 cx: &mut ViewContext<Self>,
1753 ) -> Self {
1754 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1755 }
1756
1757 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1758 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1759 let mut clone = Self::new(
1760 self.mode,
1761 self.buffer.clone(),
1762 self.project.clone(),
1763 show_excerpt_controls,
1764 cx,
1765 );
1766 self.display_map.update(cx, |display_map, cx| {
1767 let snapshot = display_map.snapshot(cx);
1768 clone.display_map.update(cx, |display_map, cx| {
1769 display_map.set_state(&snapshot, cx);
1770 });
1771 });
1772 clone.selections.clone_state(&self.selections);
1773 clone.scroll_manager.clone_state(&self.scroll_manager);
1774 clone.searchable = self.searchable;
1775 clone
1776 }
1777
1778 pub fn new(
1779 mode: EditorMode,
1780 buffer: Model<MultiBuffer>,
1781 project: Option<Model<Project>>,
1782 show_excerpt_controls: bool,
1783 cx: &mut ViewContext<Self>,
1784 ) -> Self {
1785 let style = cx.text_style();
1786 let font_size = style.font_size.to_pixels(cx.rem_size());
1787 let editor = cx.view().downgrade();
1788 let fold_placeholder = FoldPlaceholder {
1789 constrain_width: true,
1790 render: Arc::new(move |fold_id, fold_range, cx| {
1791 let editor = editor.clone();
1792 div()
1793 .id(fold_id)
1794 .bg(cx.theme().colors().ghost_element_background)
1795 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1796 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1797 .rounded_sm()
1798 .size_full()
1799 .cursor_pointer()
1800 .child("⋯")
1801 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1802 .on_click(move |_, cx| {
1803 editor
1804 .update(cx, |editor, cx| {
1805 editor.unfold_ranges(
1806 [fold_range.start..fold_range.end],
1807 true,
1808 false,
1809 cx,
1810 );
1811 cx.stop_propagation();
1812 })
1813 .ok();
1814 })
1815 .into_any()
1816 }),
1817 merge_adjacent: true,
1818 };
1819 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1820 let display_map = cx.new_model(|cx| {
1821 DisplayMap::new(
1822 buffer.clone(),
1823 style.font(),
1824 font_size,
1825 None,
1826 show_excerpt_controls,
1827 file_header_size,
1828 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1829 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1830 fold_placeholder,
1831 cx,
1832 )
1833 });
1834
1835 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1836
1837 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1838
1839 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1840 .then(|| language_settings::SoftWrap::PreferLine);
1841
1842 let mut project_subscriptions = Vec::new();
1843 if mode == EditorMode::Full {
1844 if let Some(project) = project.as_ref() {
1845 if buffer.read(cx).is_singleton() {
1846 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1847 cx.emit(EditorEvent::TitleChanged);
1848 }));
1849 }
1850 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1851 if let project::Event::RefreshInlayHints = event {
1852 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1853 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1854 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1855 let focus_handle = editor.focus_handle(cx);
1856 if focus_handle.is_focused(cx) {
1857 let snapshot = buffer.read(cx).snapshot();
1858 for (range, snippet) in snippet_edits {
1859 let editor_range =
1860 language::range_from_lsp(*range).to_offset(&snapshot);
1861 editor
1862 .insert_snippet(&[editor_range], snippet.clone(), cx)
1863 .ok();
1864 }
1865 }
1866 }
1867 }
1868 }));
1869 let task_inventory = project.read(cx).task_inventory().clone();
1870 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1871 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1872 }));
1873 }
1874 }
1875
1876 let inlay_hint_settings = inlay_hint_settings(
1877 selections.newest_anchor().head(),
1878 &buffer.read(cx).snapshot(cx),
1879 cx,
1880 );
1881 let focus_handle = cx.focus_handle();
1882 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1883 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1884 .detach();
1885 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1886 .detach();
1887 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1888
1889 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1890 Some(false)
1891 } else {
1892 None
1893 };
1894
1895 let mut code_action_providers = Vec::new();
1896 if let Some(project) = project.clone() {
1897 code_action_providers.push(Arc::new(project) as Arc<_>);
1898 }
1899
1900 let mut this = Self {
1901 focus_handle,
1902 show_cursor_when_unfocused: false,
1903 last_focused_descendant: None,
1904 buffer: buffer.clone(),
1905 display_map: display_map.clone(),
1906 selections,
1907 scroll_manager: ScrollManager::new(cx),
1908 columnar_selection_tail: None,
1909 add_selections_state: None,
1910 select_next_state: None,
1911 select_prev_state: None,
1912 selection_history: Default::default(),
1913 autoclose_regions: Default::default(),
1914 snippet_stack: Default::default(),
1915 select_larger_syntax_node_stack: Vec::new(),
1916 ime_transaction: Default::default(),
1917 active_diagnostics: None,
1918 soft_wrap_mode_override,
1919 completion_provider: project.clone().map(|project| Box::new(project) as _),
1920 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1921 project,
1922 blink_manager: blink_manager.clone(),
1923 show_local_selections: true,
1924 mode,
1925 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1926 show_gutter: mode == EditorMode::Full,
1927 show_line_numbers: None,
1928 use_relative_line_numbers: None,
1929 show_git_diff_gutter: None,
1930 show_code_actions: None,
1931 show_runnables: None,
1932 show_wrap_guides: None,
1933 show_indent_guides,
1934 placeholder_text: None,
1935 highlight_order: 0,
1936 highlighted_rows: HashMap::default(),
1937 background_highlights: Default::default(),
1938 gutter_highlights: TreeMap::default(),
1939 scrollbar_marker_state: ScrollbarMarkerState::default(),
1940 active_indent_guides_state: ActiveIndentGuidesState::default(),
1941 nav_history: None,
1942 context_menu: RwLock::new(None),
1943 mouse_context_menu: None,
1944 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1945 completion_tasks: Default::default(),
1946 signature_help_state: SignatureHelpState::default(),
1947 auto_signature_help: None,
1948 find_all_references_task_sources: Vec::new(),
1949 next_completion_id: 0,
1950 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1951 next_inlay_id: 0,
1952 code_action_providers,
1953 available_code_actions: Default::default(),
1954 code_actions_task: Default::default(),
1955 document_highlights_task: Default::default(),
1956 linked_editing_range_task: Default::default(),
1957 pending_rename: Default::default(),
1958 searchable: true,
1959 cursor_shape: EditorSettings::get_global(cx)
1960 .cursor_shape
1961 .unwrap_or_default(),
1962 current_line_highlight: None,
1963 autoindent_mode: Some(AutoindentMode::EachLine),
1964 collapse_matches: false,
1965 workspace: None,
1966 input_enabled: true,
1967 use_modal_editing: mode == EditorMode::Full,
1968 read_only: false,
1969 use_autoclose: true,
1970 use_auto_surround: true,
1971 auto_replace_emoji_shortcode: false,
1972 leader_peer_id: None,
1973 remote_id: None,
1974 hover_state: Default::default(),
1975 hovered_link_state: Default::default(),
1976 inline_completion_provider: None,
1977 active_inline_completion: None,
1978 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1979 expanded_hunks: ExpandedHunks::default(),
1980 gutter_hovered: false,
1981 pixel_position_of_newest_cursor: None,
1982 last_bounds: None,
1983 expect_bounds_change: None,
1984 gutter_dimensions: GutterDimensions::default(),
1985 style: None,
1986 show_cursor_names: false,
1987 hovered_cursors: Default::default(),
1988 next_editor_action_id: EditorActionId::default(),
1989 editor_actions: Rc::default(),
1990 show_inline_completions_override: None,
1991 enable_inline_completions: true,
1992 custom_context_menu: None,
1993 show_git_blame_gutter: false,
1994 show_git_blame_inline: false,
1995 show_selection_menu: None,
1996 show_git_blame_inline_delay_task: None,
1997 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1998 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1999 .session
2000 .restore_unsaved_buffers,
2001 blame: None,
2002 blame_subscription: None,
2003 file_header_size,
2004 tasks: Default::default(),
2005 _subscriptions: vec![
2006 cx.observe(&buffer, Self::on_buffer_changed),
2007 cx.subscribe(&buffer, Self::on_buffer_event),
2008 cx.observe(&display_map, Self::on_display_map_changed),
2009 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2010 cx.observe_global::<SettingsStore>(Self::settings_changed),
2011 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2012 cx.observe_window_activation(|editor, cx| {
2013 let active = cx.is_window_active();
2014 editor.blink_manager.update(cx, |blink_manager, cx| {
2015 if active {
2016 blink_manager.enable(cx);
2017 } else {
2018 blink_manager.disable(cx);
2019 }
2020 });
2021 }),
2022 ],
2023 tasks_update_task: None,
2024 linked_edit_ranges: Default::default(),
2025 previous_search_ranges: None,
2026 breadcrumb_header: None,
2027 focused_block: None,
2028 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2029 addons: HashMap::default(),
2030 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2031 };
2032 this.tasks_update_task = Some(this.refresh_runnables(cx));
2033 this._subscriptions.extend(project_subscriptions);
2034
2035 this.end_selection(cx);
2036 this.scroll_manager.show_scrollbar(cx);
2037
2038 if mode == EditorMode::Full {
2039 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2040 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2041
2042 if this.git_blame_inline_enabled {
2043 this.git_blame_inline_enabled = true;
2044 this.start_git_blame_inline(false, cx);
2045 }
2046 }
2047
2048 this.report_editor_event("open", None, cx);
2049 this
2050 }
2051
2052 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2053 self.mouse_context_menu
2054 .as_ref()
2055 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2056 }
2057
2058 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2059 let mut key_context = KeyContext::new_with_defaults();
2060 key_context.add("Editor");
2061 let mode = match self.mode {
2062 EditorMode::SingleLine { .. } => "single_line",
2063 EditorMode::AutoHeight { .. } => "auto_height",
2064 EditorMode::Full => "full",
2065 };
2066
2067 if EditorSettings::jupyter_enabled(cx) {
2068 key_context.add("jupyter");
2069 }
2070
2071 key_context.set("mode", mode);
2072 if self.pending_rename.is_some() {
2073 key_context.add("renaming");
2074 }
2075 if self.context_menu_visible() {
2076 match self.context_menu.read().as_ref() {
2077 Some(ContextMenu::Completions(_)) => {
2078 key_context.add("menu");
2079 key_context.add("showing_completions")
2080 }
2081 Some(ContextMenu::CodeActions(_)) => {
2082 key_context.add("menu");
2083 key_context.add("showing_code_actions")
2084 }
2085 None => {}
2086 }
2087 }
2088
2089 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2090 if !self.focus_handle(cx).contains_focused(cx)
2091 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2092 {
2093 for addon in self.addons.values() {
2094 addon.extend_key_context(&mut key_context, cx)
2095 }
2096 }
2097
2098 if let Some(extension) = self
2099 .buffer
2100 .read(cx)
2101 .as_singleton()
2102 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2103 {
2104 key_context.set("extension", extension.to_string());
2105 }
2106
2107 if self.has_active_inline_completion(cx) {
2108 key_context.add("copilot_suggestion");
2109 key_context.add("inline_completion");
2110 }
2111
2112 key_context
2113 }
2114
2115 pub fn new_file(
2116 workspace: &mut Workspace,
2117 _: &workspace::NewFile,
2118 cx: &mut ViewContext<Workspace>,
2119 ) {
2120 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2121 "Failed to create buffer",
2122 cx,
2123 |e, _| match e.error_code() {
2124 ErrorCode::RemoteUpgradeRequired => Some(format!(
2125 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2126 e.error_tag("required").unwrap_or("the latest version")
2127 )),
2128 _ => None,
2129 },
2130 );
2131 }
2132
2133 pub fn new_in_workspace(
2134 workspace: &mut Workspace,
2135 cx: &mut ViewContext<Workspace>,
2136 ) -> Task<Result<View<Editor>>> {
2137 let project = workspace.project().clone();
2138 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2139
2140 cx.spawn(|workspace, mut cx| async move {
2141 let buffer = create.await?;
2142 workspace.update(&mut cx, |workspace, cx| {
2143 let editor =
2144 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2145 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2146 editor
2147 })
2148 })
2149 }
2150
2151 fn new_file_vertical(
2152 workspace: &mut Workspace,
2153 _: &workspace::NewFileSplitVertical,
2154 cx: &mut ViewContext<Workspace>,
2155 ) {
2156 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2157 }
2158
2159 fn new_file_horizontal(
2160 workspace: &mut Workspace,
2161 _: &workspace::NewFileSplitHorizontal,
2162 cx: &mut ViewContext<Workspace>,
2163 ) {
2164 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2165 }
2166
2167 fn new_file_in_direction(
2168 workspace: &mut Workspace,
2169 direction: SplitDirection,
2170 cx: &mut ViewContext<Workspace>,
2171 ) {
2172 let project = workspace.project().clone();
2173 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2174
2175 cx.spawn(|workspace, mut cx| async move {
2176 let buffer = create.await?;
2177 workspace.update(&mut cx, move |workspace, cx| {
2178 workspace.split_item(
2179 direction,
2180 Box::new(
2181 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2182 ),
2183 cx,
2184 )
2185 })?;
2186 anyhow::Ok(())
2187 })
2188 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2189 ErrorCode::RemoteUpgradeRequired => Some(format!(
2190 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2191 e.error_tag("required").unwrap_or("the latest version")
2192 )),
2193 _ => None,
2194 });
2195 }
2196
2197 pub fn leader_peer_id(&self) -> Option<PeerId> {
2198 self.leader_peer_id
2199 }
2200
2201 pub fn buffer(&self) -> &Model<MultiBuffer> {
2202 &self.buffer
2203 }
2204
2205 pub fn workspace(&self) -> Option<View<Workspace>> {
2206 self.workspace.as_ref()?.0.upgrade()
2207 }
2208
2209 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2210 self.buffer().read(cx).title(cx)
2211 }
2212
2213 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2214 let git_blame_gutter_max_author_length = self
2215 .render_git_blame_gutter(cx)
2216 .then(|| {
2217 if let Some(blame) = self.blame.as_ref() {
2218 let max_author_length =
2219 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2220 Some(max_author_length)
2221 } else {
2222 None
2223 }
2224 })
2225 .flatten();
2226
2227 EditorSnapshot {
2228 mode: self.mode,
2229 show_gutter: self.show_gutter,
2230 show_line_numbers: self.show_line_numbers,
2231 show_git_diff_gutter: self.show_git_diff_gutter,
2232 show_code_actions: self.show_code_actions,
2233 show_runnables: self.show_runnables,
2234 git_blame_gutter_max_author_length,
2235 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2236 scroll_anchor: self.scroll_manager.anchor(),
2237 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2238 placeholder_text: self.placeholder_text.clone(),
2239 is_focused: self.focus_handle.is_focused(cx),
2240 current_line_highlight: self
2241 .current_line_highlight
2242 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2243 gutter_hovered: self.gutter_hovered,
2244 }
2245 }
2246
2247 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2248 self.buffer.read(cx).language_at(point, cx)
2249 }
2250
2251 pub fn file_at<T: ToOffset>(
2252 &self,
2253 point: T,
2254 cx: &AppContext,
2255 ) -> Option<Arc<dyn language::File>> {
2256 self.buffer.read(cx).read(cx).file_at(point).cloned()
2257 }
2258
2259 pub fn active_excerpt(
2260 &self,
2261 cx: &AppContext,
2262 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2263 self.buffer
2264 .read(cx)
2265 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2266 }
2267
2268 pub fn mode(&self) -> EditorMode {
2269 self.mode
2270 }
2271
2272 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2273 self.collaboration_hub.as_deref()
2274 }
2275
2276 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2277 self.collaboration_hub = Some(hub);
2278 }
2279
2280 pub fn set_custom_context_menu(
2281 &mut self,
2282 f: impl 'static
2283 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2284 ) {
2285 self.custom_context_menu = Some(Box::new(f))
2286 }
2287
2288 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2289 self.completion_provider = Some(provider);
2290 }
2291
2292 pub fn set_inline_completion_provider<T>(
2293 &mut self,
2294 provider: Option<Model<T>>,
2295 cx: &mut ViewContext<Self>,
2296 ) where
2297 T: InlineCompletionProvider,
2298 {
2299 self.inline_completion_provider =
2300 provider.map(|provider| RegisteredInlineCompletionProvider {
2301 _subscription: cx.observe(&provider, |this, _, cx| {
2302 if this.focus_handle.is_focused(cx) {
2303 this.update_visible_inline_completion(cx);
2304 }
2305 }),
2306 provider: Arc::new(provider),
2307 });
2308 self.refresh_inline_completion(false, false, cx);
2309 }
2310
2311 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2312 self.placeholder_text.as_deref()
2313 }
2314
2315 pub fn set_placeholder_text(
2316 &mut self,
2317 placeholder_text: impl Into<Arc<str>>,
2318 cx: &mut ViewContext<Self>,
2319 ) {
2320 let placeholder_text = Some(placeholder_text.into());
2321 if self.placeholder_text != placeholder_text {
2322 self.placeholder_text = placeholder_text;
2323 cx.notify();
2324 }
2325 }
2326
2327 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2328 self.cursor_shape = cursor_shape;
2329
2330 // Disrupt blink for immediate user feedback that the cursor shape has changed
2331 self.blink_manager.update(cx, BlinkManager::show_cursor);
2332
2333 cx.notify();
2334 }
2335
2336 pub fn set_current_line_highlight(
2337 &mut self,
2338 current_line_highlight: Option<CurrentLineHighlight>,
2339 ) {
2340 self.current_line_highlight = current_line_highlight;
2341 }
2342
2343 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2344 self.collapse_matches = collapse_matches;
2345 }
2346
2347 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2348 if self.collapse_matches {
2349 return range.start..range.start;
2350 }
2351 range.clone()
2352 }
2353
2354 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2355 if self.display_map.read(cx).clip_at_line_ends != clip {
2356 self.display_map
2357 .update(cx, |map, _| map.clip_at_line_ends = clip);
2358 }
2359 }
2360
2361 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2362 self.input_enabled = input_enabled;
2363 }
2364
2365 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2366 self.enable_inline_completions = enabled;
2367 }
2368
2369 pub fn set_autoindent(&mut self, autoindent: bool) {
2370 if autoindent {
2371 self.autoindent_mode = Some(AutoindentMode::EachLine);
2372 } else {
2373 self.autoindent_mode = None;
2374 }
2375 }
2376
2377 pub fn read_only(&self, cx: &AppContext) -> bool {
2378 self.read_only || self.buffer.read(cx).read_only()
2379 }
2380
2381 pub fn set_read_only(&mut self, read_only: bool) {
2382 self.read_only = read_only;
2383 }
2384
2385 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2386 self.use_autoclose = autoclose;
2387 }
2388
2389 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2390 self.use_auto_surround = auto_surround;
2391 }
2392
2393 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2394 self.auto_replace_emoji_shortcode = auto_replace;
2395 }
2396
2397 pub fn toggle_inline_completions(
2398 &mut self,
2399 _: &ToggleInlineCompletions,
2400 cx: &mut ViewContext<Self>,
2401 ) {
2402 if self.show_inline_completions_override.is_some() {
2403 self.set_show_inline_completions(None, cx);
2404 } else {
2405 let cursor = self.selections.newest_anchor().head();
2406 if let Some((buffer, cursor_buffer_position)) =
2407 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2408 {
2409 let show_inline_completions =
2410 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2411 self.set_show_inline_completions(Some(show_inline_completions), cx);
2412 }
2413 }
2414 }
2415
2416 pub fn set_show_inline_completions(
2417 &mut self,
2418 show_inline_completions: Option<bool>,
2419 cx: &mut ViewContext<Self>,
2420 ) {
2421 self.show_inline_completions_override = show_inline_completions;
2422 self.refresh_inline_completion(false, true, cx);
2423 }
2424
2425 fn should_show_inline_completions(
2426 &self,
2427 buffer: &Model<Buffer>,
2428 buffer_position: language::Anchor,
2429 cx: &AppContext,
2430 ) -> bool {
2431 if let Some(provider) = self.inline_completion_provider() {
2432 if let Some(show_inline_completions) = self.show_inline_completions_override {
2433 show_inline_completions
2434 } else {
2435 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2436 }
2437 } else {
2438 false
2439 }
2440 }
2441
2442 pub fn set_use_modal_editing(&mut self, to: bool) {
2443 self.use_modal_editing = to;
2444 }
2445
2446 pub fn use_modal_editing(&self) -> bool {
2447 self.use_modal_editing
2448 }
2449
2450 fn selections_did_change(
2451 &mut self,
2452 local: bool,
2453 old_cursor_position: &Anchor,
2454 show_completions: bool,
2455 cx: &mut ViewContext<Self>,
2456 ) {
2457 cx.invalidate_character_coordinates();
2458
2459 // Copy selections to primary selection buffer
2460 #[cfg(target_os = "linux")]
2461 if local {
2462 let selections = self.selections.all::<usize>(cx);
2463 let buffer_handle = self.buffer.read(cx).read(cx);
2464
2465 let mut text = String::new();
2466 for (index, selection) in selections.iter().enumerate() {
2467 let text_for_selection = buffer_handle
2468 .text_for_range(selection.start..selection.end)
2469 .collect::<String>();
2470
2471 text.push_str(&text_for_selection);
2472 if index != selections.len() - 1 {
2473 text.push('\n');
2474 }
2475 }
2476
2477 if !text.is_empty() {
2478 cx.write_to_primary(ClipboardItem::new_string(text));
2479 }
2480 }
2481
2482 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2483 self.buffer.update(cx, |buffer, cx| {
2484 buffer.set_active_selections(
2485 &self.selections.disjoint_anchors(),
2486 self.selections.line_mode,
2487 self.cursor_shape,
2488 cx,
2489 )
2490 });
2491 }
2492 let display_map = self
2493 .display_map
2494 .update(cx, |display_map, cx| display_map.snapshot(cx));
2495 let buffer = &display_map.buffer_snapshot;
2496 self.add_selections_state = None;
2497 self.select_next_state = None;
2498 self.select_prev_state = None;
2499 self.select_larger_syntax_node_stack.clear();
2500 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2501 self.snippet_stack
2502 .invalidate(&self.selections.disjoint_anchors(), buffer);
2503 self.take_rename(false, cx);
2504
2505 let new_cursor_position = self.selections.newest_anchor().head();
2506
2507 self.push_to_nav_history(
2508 *old_cursor_position,
2509 Some(new_cursor_position.to_point(buffer)),
2510 cx,
2511 );
2512
2513 if local {
2514 let new_cursor_position = self.selections.newest_anchor().head();
2515 let mut context_menu = self.context_menu.write();
2516 let completion_menu = match context_menu.as_ref() {
2517 Some(ContextMenu::Completions(menu)) => Some(menu),
2518
2519 _ => {
2520 *context_menu = None;
2521 None
2522 }
2523 };
2524
2525 if let Some(completion_menu) = completion_menu {
2526 let cursor_position = new_cursor_position.to_offset(buffer);
2527 let (word_range, kind) =
2528 buffer.surrounding_word(completion_menu.initial_position, true);
2529 if kind == Some(CharKind::Word)
2530 && word_range.to_inclusive().contains(&cursor_position)
2531 {
2532 let mut completion_menu = completion_menu.clone();
2533 drop(context_menu);
2534
2535 let query = Self::completion_query(buffer, cursor_position);
2536 cx.spawn(move |this, mut cx| async move {
2537 completion_menu
2538 .filter(query.as_deref(), cx.background_executor().clone())
2539 .await;
2540
2541 this.update(&mut cx, |this, cx| {
2542 let mut context_menu = this.context_menu.write();
2543 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2544 return;
2545 };
2546
2547 if menu.id > completion_menu.id {
2548 return;
2549 }
2550
2551 *context_menu = Some(ContextMenu::Completions(completion_menu));
2552 drop(context_menu);
2553 cx.notify();
2554 })
2555 })
2556 .detach();
2557
2558 if show_completions {
2559 self.show_completions(&ShowCompletions { trigger: None }, cx);
2560 }
2561 } else {
2562 drop(context_menu);
2563 self.hide_context_menu(cx);
2564 }
2565 } else {
2566 drop(context_menu);
2567 }
2568
2569 hide_hover(self, cx);
2570
2571 if old_cursor_position.to_display_point(&display_map).row()
2572 != new_cursor_position.to_display_point(&display_map).row()
2573 {
2574 self.available_code_actions.take();
2575 }
2576 self.refresh_code_actions(cx);
2577 self.refresh_document_highlights(cx);
2578 refresh_matching_bracket_highlights(self, cx);
2579 self.discard_inline_completion(false, cx);
2580 linked_editing_ranges::refresh_linked_ranges(self, cx);
2581 if self.git_blame_inline_enabled {
2582 self.start_inline_blame_timer(cx);
2583 }
2584 }
2585
2586 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2587 cx.emit(EditorEvent::SelectionsChanged { local });
2588
2589 if self.selections.disjoint_anchors().len() == 1 {
2590 cx.emit(SearchEvent::ActiveMatchChanged)
2591 }
2592 cx.notify();
2593 }
2594
2595 pub fn change_selections<R>(
2596 &mut self,
2597 autoscroll: Option<Autoscroll>,
2598 cx: &mut ViewContext<Self>,
2599 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2600 ) -> R {
2601 self.change_selections_inner(autoscroll, true, cx, change)
2602 }
2603
2604 pub fn change_selections_inner<R>(
2605 &mut self,
2606 autoscroll: Option<Autoscroll>,
2607 request_completions: bool,
2608 cx: &mut ViewContext<Self>,
2609 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2610 ) -> R {
2611 let old_cursor_position = self.selections.newest_anchor().head();
2612 self.push_to_selection_history();
2613
2614 let (changed, result) = self.selections.change_with(cx, change);
2615
2616 if changed {
2617 if let Some(autoscroll) = autoscroll {
2618 self.request_autoscroll(autoscroll, cx);
2619 }
2620 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2621
2622 if self.should_open_signature_help_automatically(
2623 &old_cursor_position,
2624 self.signature_help_state.backspace_pressed(),
2625 cx,
2626 ) {
2627 self.show_signature_help(&ShowSignatureHelp, cx);
2628 }
2629 self.signature_help_state.set_backspace_pressed(false);
2630 }
2631
2632 result
2633 }
2634
2635 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2636 where
2637 I: IntoIterator<Item = (Range<S>, T)>,
2638 S: ToOffset,
2639 T: Into<Arc<str>>,
2640 {
2641 if self.read_only(cx) {
2642 return;
2643 }
2644
2645 self.buffer
2646 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2647 }
2648
2649 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2650 where
2651 I: IntoIterator<Item = (Range<S>, T)>,
2652 S: ToOffset,
2653 T: Into<Arc<str>>,
2654 {
2655 if self.read_only(cx) {
2656 return;
2657 }
2658
2659 self.buffer.update(cx, |buffer, cx| {
2660 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2661 });
2662 }
2663
2664 pub fn edit_with_block_indent<I, S, T>(
2665 &mut self,
2666 edits: I,
2667 original_indent_columns: Vec<u32>,
2668 cx: &mut ViewContext<Self>,
2669 ) where
2670 I: IntoIterator<Item = (Range<S>, T)>,
2671 S: ToOffset,
2672 T: Into<Arc<str>>,
2673 {
2674 if self.read_only(cx) {
2675 return;
2676 }
2677
2678 self.buffer.update(cx, |buffer, cx| {
2679 buffer.edit(
2680 edits,
2681 Some(AutoindentMode::Block {
2682 original_indent_columns,
2683 }),
2684 cx,
2685 )
2686 });
2687 }
2688
2689 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2690 self.hide_context_menu(cx);
2691
2692 match phase {
2693 SelectPhase::Begin {
2694 position,
2695 add,
2696 click_count,
2697 } => self.begin_selection(position, add, click_count, cx),
2698 SelectPhase::BeginColumnar {
2699 position,
2700 goal_column,
2701 reset,
2702 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2703 SelectPhase::Extend {
2704 position,
2705 click_count,
2706 } => self.extend_selection(position, click_count, cx),
2707 SelectPhase::Update {
2708 position,
2709 goal_column,
2710 scroll_delta,
2711 } => self.update_selection(position, goal_column, scroll_delta, cx),
2712 SelectPhase::End => self.end_selection(cx),
2713 }
2714 }
2715
2716 fn extend_selection(
2717 &mut self,
2718 position: DisplayPoint,
2719 click_count: usize,
2720 cx: &mut ViewContext<Self>,
2721 ) {
2722 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2723 let tail = self.selections.newest::<usize>(cx).tail();
2724 self.begin_selection(position, false, click_count, cx);
2725
2726 let position = position.to_offset(&display_map, Bias::Left);
2727 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2728
2729 let mut pending_selection = self
2730 .selections
2731 .pending_anchor()
2732 .expect("extend_selection not called with pending selection");
2733 if position >= tail {
2734 pending_selection.start = tail_anchor;
2735 } else {
2736 pending_selection.end = tail_anchor;
2737 pending_selection.reversed = true;
2738 }
2739
2740 let mut pending_mode = self.selections.pending_mode().unwrap();
2741 match &mut pending_mode {
2742 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2743 _ => {}
2744 }
2745
2746 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2747 s.set_pending(pending_selection, pending_mode)
2748 });
2749 }
2750
2751 fn begin_selection(
2752 &mut self,
2753 position: DisplayPoint,
2754 add: bool,
2755 click_count: usize,
2756 cx: &mut ViewContext<Self>,
2757 ) {
2758 if !self.focus_handle.is_focused(cx) {
2759 self.last_focused_descendant = None;
2760 cx.focus(&self.focus_handle);
2761 }
2762
2763 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2764 let buffer = &display_map.buffer_snapshot;
2765 let newest_selection = self.selections.newest_anchor().clone();
2766 let position = display_map.clip_point(position, Bias::Left);
2767
2768 let start;
2769 let end;
2770 let mode;
2771 let auto_scroll;
2772 match click_count {
2773 1 => {
2774 start = buffer.anchor_before(position.to_point(&display_map));
2775 end = start;
2776 mode = SelectMode::Character;
2777 auto_scroll = true;
2778 }
2779 2 => {
2780 let range = movement::surrounding_word(&display_map, position);
2781 start = buffer.anchor_before(range.start.to_point(&display_map));
2782 end = buffer.anchor_before(range.end.to_point(&display_map));
2783 mode = SelectMode::Word(start..end);
2784 auto_scroll = true;
2785 }
2786 3 => {
2787 let position = display_map
2788 .clip_point(position, Bias::Left)
2789 .to_point(&display_map);
2790 let line_start = display_map.prev_line_boundary(position).0;
2791 let next_line_start = buffer.clip_point(
2792 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2793 Bias::Left,
2794 );
2795 start = buffer.anchor_before(line_start);
2796 end = buffer.anchor_before(next_line_start);
2797 mode = SelectMode::Line(start..end);
2798 auto_scroll = true;
2799 }
2800 _ => {
2801 start = buffer.anchor_before(0);
2802 end = buffer.anchor_before(buffer.len());
2803 mode = SelectMode::All;
2804 auto_scroll = false;
2805 }
2806 }
2807
2808 let point_to_delete: Option<usize> = {
2809 let selected_points: Vec<Selection<Point>> =
2810 self.selections.disjoint_in_range(start..end, cx);
2811
2812 if !add || click_count > 1 {
2813 None
2814 } else if !selected_points.is_empty() {
2815 Some(selected_points[0].id)
2816 } else {
2817 let clicked_point_already_selected =
2818 self.selections.disjoint.iter().find(|selection| {
2819 selection.start.to_point(buffer) == start.to_point(buffer)
2820 || selection.end.to_point(buffer) == end.to_point(buffer)
2821 });
2822
2823 clicked_point_already_selected.map(|selection| selection.id)
2824 }
2825 };
2826
2827 let selections_count = self.selections.count();
2828
2829 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2830 if let Some(point_to_delete) = point_to_delete {
2831 s.delete(point_to_delete);
2832
2833 if selections_count == 1 {
2834 s.set_pending_anchor_range(start..end, mode);
2835 }
2836 } else {
2837 if !add {
2838 s.clear_disjoint();
2839 } else if click_count > 1 {
2840 s.delete(newest_selection.id)
2841 }
2842
2843 s.set_pending_anchor_range(start..end, mode);
2844 }
2845 });
2846 }
2847
2848 fn begin_columnar_selection(
2849 &mut self,
2850 position: DisplayPoint,
2851 goal_column: u32,
2852 reset: bool,
2853 cx: &mut ViewContext<Self>,
2854 ) {
2855 if !self.focus_handle.is_focused(cx) {
2856 self.last_focused_descendant = None;
2857 cx.focus(&self.focus_handle);
2858 }
2859
2860 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2861
2862 if reset {
2863 let pointer_position = display_map
2864 .buffer_snapshot
2865 .anchor_before(position.to_point(&display_map));
2866
2867 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2868 s.clear_disjoint();
2869 s.set_pending_anchor_range(
2870 pointer_position..pointer_position,
2871 SelectMode::Character,
2872 );
2873 });
2874 }
2875
2876 let tail = self.selections.newest::<Point>(cx).tail();
2877 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2878
2879 if !reset {
2880 self.select_columns(
2881 tail.to_display_point(&display_map),
2882 position,
2883 goal_column,
2884 &display_map,
2885 cx,
2886 );
2887 }
2888 }
2889
2890 fn update_selection(
2891 &mut self,
2892 position: DisplayPoint,
2893 goal_column: u32,
2894 scroll_delta: gpui::Point<f32>,
2895 cx: &mut ViewContext<Self>,
2896 ) {
2897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2898
2899 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2900 let tail = tail.to_display_point(&display_map);
2901 self.select_columns(tail, position, goal_column, &display_map, cx);
2902 } else if let Some(mut pending) = self.selections.pending_anchor() {
2903 let buffer = self.buffer.read(cx).snapshot(cx);
2904 let head;
2905 let tail;
2906 let mode = self.selections.pending_mode().unwrap();
2907 match &mode {
2908 SelectMode::Character => {
2909 head = position.to_point(&display_map);
2910 tail = pending.tail().to_point(&buffer);
2911 }
2912 SelectMode::Word(original_range) => {
2913 let original_display_range = original_range.start.to_display_point(&display_map)
2914 ..original_range.end.to_display_point(&display_map);
2915 let original_buffer_range = original_display_range.start.to_point(&display_map)
2916 ..original_display_range.end.to_point(&display_map);
2917 if movement::is_inside_word(&display_map, position)
2918 || original_display_range.contains(&position)
2919 {
2920 let word_range = movement::surrounding_word(&display_map, position);
2921 if word_range.start < original_display_range.start {
2922 head = word_range.start.to_point(&display_map);
2923 } else {
2924 head = word_range.end.to_point(&display_map);
2925 }
2926 } else {
2927 head = position.to_point(&display_map);
2928 }
2929
2930 if head <= original_buffer_range.start {
2931 tail = original_buffer_range.end;
2932 } else {
2933 tail = original_buffer_range.start;
2934 }
2935 }
2936 SelectMode::Line(original_range) => {
2937 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2938
2939 let position = display_map
2940 .clip_point(position, Bias::Left)
2941 .to_point(&display_map);
2942 let line_start = display_map.prev_line_boundary(position).0;
2943 let next_line_start = buffer.clip_point(
2944 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2945 Bias::Left,
2946 );
2947
2948 if line_start < original_range.start {
2949 head = line_start
2950 } else {
2951 head = next_line_start
2952 }
2953
2954 if head <= original_range.start {
2955 tail = original_range.end;
2956 } else {
2957 tail = original_range.start;
2958 }
2959 }
2960 SelectMode::All => {
2961 return;
2962 }
2963 };
2964
2965 if head < tail {
2966 pending.start = buffer.anchor_before(head);
2967 pending.end = buffer.anchor_before(tail);
2968 pending.reversed = true;
2969 } else {
2970 pending.start = buffer.anchor_before(tail);
2971 pending.end = buffer.anchor_before(head);
2972 pending.reversed = false;
2973 }
2974
2975 self.change_selections(None, cx, |s| {
2976 s.set_pending(pending, mode);
2977 });
2978 } else {
2979 log::error!("update_selection dispatched with no pending selection");
2980 return;
2981 }
2982
2983 self.apply_scroll_delta(scroll_delta, cx);
2984 cx.notify();
2985 }
2986
2987 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2988 self.columnar_selection_tail.take();
2989 if self.selections.pending_anchor().is_some() {
2990 let selections = self.selections.all::<usize>(cx);
2991 self.change_selections(None, cx, |s| {
2992 s.select(selections);
2993 s.clear_pending();
2994 });
2995 }
2996 }
2997
2998 fn select_columns(
2999 &mut self,
3000 tail: DisplayPoint,
3001 head: DisplayPoint,
3002 goal_column: u32,
3003 display_map: &DisplaySnapshot,
3004 cx: &mut ViewContext<Self>,
3005 ) {
3006 let start_row = cmp::min(tail.row(), head.row());
3007 let end_row = cmp::max(tail.row(), head.row());
3008 let start_column = cmp::min(tail.column(), goal_column);
3009 let end_column = cmp::max(tail.column(), goal_column);
3010 let reversed = start_column < tail.column();
3011
3012 let selection_ranges = (start_row.0..=end_row.0)
3013 .map(DisplayRow)
3014 .filter_map(|row| {
3015 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3016 let start = display_map
3017 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3018 .to_point(display_map);
3019 let end = display_map
3020 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3021 .to_point(display_map);
3022 if reversed {
3023 Some(end..start)
3024 } else {
3025 Some(start..end)
3026 }
3027 } else {
3028 None
3029 }
3030 })
3031 .collect::<Vec<_>>();
3032
3033 self.change_selections(None, cx, |s| {
3034 s.select_ranges(selection_ranges);
3035 });
3036 cx.notify();
3037 }
3038
3039 pub fn has_pending_nonempty_selection(&self) -> bool {
3040 let pending_nonempty_selection = match self.selections.pending_anchor() {
3041 Some(Selection { start, end, .. }) => start != end,
3042 None => false,
3043 };
3044
3045 pending_nonempty_selection
3046 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3047 }
3048
3049 pub fn has_pending_selection(&self) -> bool {
3050 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3051 }
3052
3053 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3054 if self.clear_clicked_diff_hunks(cx) {
3055 cx.notify();
3056 return;
3057 }
3058 if self.dismiss_menus_and_popups(true, cx) {
3059 return;
3060 }
3061
3062 if self.mode == EditorMode::Full
3063 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3064 {
3065 return;
3066 }
3067
3068 cx.propagate();
3069 }
3070
3071 pub fn dismiss_menus_and_popups(
3072 &mut self,
3073 should_report_inline_completion_event: bool,
3074 cx: &mut ViewContext<Self>,
3075 ) -> bool {
3076 if self.take_rename(false, cx).is_some() {
3077 return true;
3078 }
3079
3080 if hide_hover(self, cx) {
3081 return true;
3082 }
3083
3084 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3085 return true;
3086 }
3087
3088 if self.hide_context_menu(cx).is_some() {
3089 return true;
3090 }
3091
3092 if self.mouse_context_menu.take().is_some() {
3093 return true;
3094 }
3095
3096 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3097 return true;
3098 }
3099
3100 if self.snippet_stack.pop().is_some() {
3101 return true;
3102 }
3103
3104 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3105 self.dismiss_diagnostics(cx);
3106 return true;
3107 }
3108
3109 false
3110 }
3111
3112 fn linked_editing_ranges_for(
3113 &self,
3114 selection: Range<text::Anchor>,
3115 cx: &AppContext,
3116 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3117 if self.linked_edit_ranges.is_empty() {
3118 return None;
3119 }
3120 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3121 selection.end.buffer_id.and_then(|end_buffer_id| {
3122 if selection.start.buffer_id != Some(end_buffer_id) {
3123 return None;
3124 }
3125 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3126 let snapshot = buffer.read(cx).snapshot();
3127 self.linked_edit_ranges
3128 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3129 .map(|ranges| (ranges, snapshot, buffer))
3130 })?;
3131 use text::ToOffset as TO;
3132 // find offset from the start of current range to current cursor position
3133 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3134
3135 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3136 let start_difference = start_offset - start_byte_offset;
3137 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3138 let end_difference = end_offset - start_byte_offset;
3139 // Current range has associated linked ranges.
3140 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3141 for range in linked_ranges.iter() {
3142 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3143 let end_offset = start_offset + end_difference;
3144 let start_offset = start_offset + start_difference;
3145 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3146 continue;
3147 }
3148 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3149 if s.start.buffer_id != selection.start.buffer_id
3150 || s.end.buffer_id != selection.end.buffer_id
3151 {
3152 return false;
3153 }
3154 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3155 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3156 }) {
3157 continue;
3158 }
3159 let start = buffer_snapshot.anchor_after(start_offset);
3160 let end = buffer_snapshot.anchor_after(end_offset);
3161 linked_edits
3162 .entry(buffer.clone())
3163 .or_default()
3164 .push(start..end);
3165 }
3166 Some(linked_edits)
3167 }
3168
3169 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3170 let text: Arc<str> = text.into();
3171
3172 if self.read_only(cx) {
3173 return;
3174 }
3175
3176 let selections = self.selections.all_adjusted(cx);
3177 let mut bracket_inserted = false;
3178 let mut edits = Vec::new();
3179 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3180 let mut new_selections = Vec::with_capacity(selections.len());
3181 let mut new_autoclose_regions = Vec::new();
3182 let snapshot = self.buffer.read(cx).read(cx);
3183
3184 for (selection, autoclose_region) in
3185 self.selections_with_autoclose_regions(selections, &snapshot)
3186 {
3187 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3188 // Determine if the inserted text matches the opening or closing
3189 // bracket of any of this language's bracket pairs.
3190 let mut bracket_pair = None;
3191 let mut is_bracket_pair_start = false;
3192 let mut is_bracket_pair_end = false;
3193 if !text.is_empty() {
3194 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3195 // and they are removing the character that triggered IME popup.
3196 for (pair, enabled) in scope.brackets() {
3197 if !pair.close && !pair.surround {
3198 continue;
3199 }
3200
3201 if enabled && pair.start.ends_with(text.as_ref()) {
3202 bracket_pair = Some(pair.clone());
3203 is_bracket_pair_start = true;
3204 break;
3205 }
3206 if pair.end.as_str() == text.as_ref() {
3207 bracket_pair = Some(pair.clone());
3208 is_bracket_pair_end = true;
3209 break;
3210 }
3211 }
3212 }
3213
3214 if let Some(bracket_pair) = bracket_pair {
3215 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3216 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3217 let auto_surround =
3218 self.use_auto_surround && snapshot_settings.use_auto_surround;
3219 if selection.is_empty() {
3220 if is_bracket_pair_start {
3221 let prefix_len = bracket_pair.start.len() - text.len();
3222
3223 // If the inserted text is a suffix of an opening bracket and the
3224 // selection is preceded by the rest of the opening bracket, then
3225 // insert the closing bracket.
3226 let following_text_allows_autoclose = snapshot
3227 .chars_at(selection.start)
3228 .next()
3229 .map_or(true, |c| scope.should_autoclose_before(c));
3230 let preceding_text_matches_prefix = prefix_len == 0
3231 || (selection.start.column >= (prefix_len as u32)
3232 && snapshot.contains_str_at(
3233 Point::new(
3234 selection.start.row,
3235 selection.start.column - (prefix_len as u32),
3236 ),
3237 &bracket_pair.start[..prefix_len],
3238 ));
3239
3240 if autoclose
3241 && bracket_pair.close
3242 && following_text_allows_autoclose
3243 && preceding_text_matches_prefix
3244 {
3245 let anchor = snapshot.anchor_before(selection.end);
3246 new_selections.push((selection.map(|_| anchor), text.len()));
3247 new_autoclose_regions.push((
3248 anchor,
3249 text.len(),
3250 selection.id,
3251 bracket_pair.clone(),
3252 ));
3253 edits.push((
3254 selection.range(),
3255 format!("{}{}", text, bracket_pair.end).into(),
3256 ));
3257 bracket_inserted = true;
3258 continue;
3259 }
3260 }
3261
3262 if let Some(region) = autoclose_region {
3263 // If the selection is followed by an auto-inserted closing bracket,
3264 // then don't insert that closing bracket again; just move the selection
3265 // past the closing bracket.
3266 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3267 && text.as_ref() == region.pair.end.as_str();
3268 if should_skip {
3269 let anchor = snapshot.anchor_after(selection.end);
3270 new_selections
3271 .push((selection.map(|_| anchor), region.pair.end.len()));
3272 continue;
3273 }
3274 }
3275
3276 let always_treat_brackets_as_autoclosed = snapshot
3277 .settings_at(selection.start, cx)
3278 .always_treat_brackets_as_autoclosed;
3279 if always_treat_brackets_as_autoclosed
3280 && is_bracket_pair_end
3281 && snapshot.contains_str_at(selection.end, text.as_ref())
3282 {
3283 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3284 // and the inserted text is a closing bracket and the selection is followed
3285 // by the closing bracket then move the selection past the closing bracket.
3286 let anchor = snapshot.anchor_after(selection.end);
3287 new_selections.push((selection.map(|_| anchor), text.len()));
3288 continue;
3289 }
3290 }
3291 // If an opening bracket is 1 character long and is typed while
3292 // text is selected, then surround that text with the bracket pair.
3293 else if auto_surround
3294 && bracket_pair.surround
3295 && is_bracket_pair_start
3296 && bracket_pair.start.chars().count() == 1
3297 {
3298 edits.push((selection.start..selection.start, text.clone()));
3299 edits.push((
3300 selection.end..selection.end,
3301 bracket_pair.end.as_str().into(),
3302 ));
3303 bracket_inserted = true;
3304 new_selections.push((
3305 Selection {
3306 id: selection.id,
3307 start: snapshot.anchor_after(selection.start),
3308 end: snapshot.anchor_before(selection.end),
3309 reversed: selection.reversed,
3310 goal: selection.goal,
3311 },
3312 0,
3313 ));
3314 continue;
3315 }
3316 }
3317 }
3318
3319 if self.auto_replace_emoji_shortcode
3320 && selection.is_empty()
3321 && text.as_ref().ends_with(':')
3322 {
3323 if let Some(possible_emoji_short_code) =
3324 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3325 {
3326 if !possible_emoji_short_code.is_empty() {
3327 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3328 let emoji_shortcode_start = Point::new(
3329 selection.start.row,
3330 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3331 );
3332
3333 // Remove shortcode from buffer
3334 edits.push((
3335 emoji_shortcode_start..selection.start,
3336 "".to_string().into(),
3337 ));
3338 new_selections.push((
3339 Selection {
3340 id: selection.id,
3341 start: snapshot.anchor_after(emoji_shortcode_start),
3342 end: snapshot.anchor_before(selection.start),
3343 reversed: selection.reversed,
3344 goal: selection.goal,
3345 },
3346 0,
3347 ));
3348
3349 // Insert emoji
3350 let selection_start_anchor = snapshot.anchor_after(selection.start);
3351 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3352 edits.push((selection.start..selection.end, emoji.to_string().into()));
3353
3354 continue;
3355 }
3356 }
3357 }
3358 }
3359
3360 // If not handling any auto-close operation, then just replace the selected
3361 // text with the given input and move the selection to the end of the
3362 // newly inserted text.
3363 let anchor = snapshot.anchor_after(selection.end);
3364 if !self.linked_edit_ranges.is_empty() {
3365 let start_anchor = snapshot.anchor_before(selection.start);
3366
3367 let is_word_char = text.chars().next().map_or(true, |char| {
3368 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3369 classifier.is_word(char)
3370 });
3371
3372 if is_word_char {
3373 if let Some(ranges) = self
3374 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3375 {
3376 for (buffer, edits) in ranges {
3377 linked_edits
3378 .entry(buffer.clone())
3379 .or_default()
3380 .extend(edits.into_iter().map(|range| (range, text.clone())));
3381 }
3382 }
3383 }
3384 }
3385
3386 new_selections.push((selection.map(|_| anchor), 0));
3387 edits.push((selection.start..selection.end, text.clone()));
3388 }
3389
3390 drop(snapshot);
3391
3392 self.transact(cx, |this, cx| {
3393 this.buffer.update(cx, |buffer, cx| {
3394 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3395 });
3396 for (buffer, edits) in linked_edits {
3397 buffer.update(cx, |buffer, cx| {
3398 let snapshot = buffer.snapshot();
3399 let edits = edits
3400 .into_iter()
3401 .map(|(range, text)| {
3402 use text::ToPoint as TP;
3403 let end_point = TP::to_point(&range.end, &snapshot);
3404 let start_point = TP::to_point(&range.start, &snapshot);
3405 (start_point..end_point, text)
3406 })
3407 .sorted_by_key(|(range, _)| range.start)
3408 .collect::<Vec<_>>();
3409 buffer.edit(edits, None, cx);
3410 })
3411 }
3412 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3413 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3414 let snapshot = this.buffer.read(cx).read(cx);
3415 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3416 .zip(new_selection_deltas)
3417 .map(|(selection, delta)| Selection {
3418 id: selection.id,
3419 start: selection.start + delta,
3420 end: selection.end + delta,
3421 reversed: selection.reversed,
3422 goal: SelectionGoal::None,
3423 })
3424 .collect::<Vec<_>>();
3425
3426 let mut i = 0;
3427 for (position, delta, selection_id, pair) in new_autoclose_regions {
3428 let position = position.to_offset(&snapshot) + delta;
3429 let start = snapshot.anchor_before(position);
3430 let end = snapshot.anchor_after(position);
3431 while let Some(existing_state) = this.autoclose_regions.get(i) {
3432 match existing_state.range.start.cmp(&start, &snapshot) {
3433 Ordering::Less => i += 1,
3434 Ordering::Greater => break,
3435 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3436 Ordering::Less => i += 1,
3437 Ordering::Equal => break,
3438 Ordering::Greater => break,
3439 },
3440 }
3441 }
3442 this.autoclose_regions.insert(
3443 i,
3444 AutocloseRegion {
3445 selection_id,
3446 range: start..end,
3447 pair,
3448 },
3449 );
3450 }
3451
3452 drop(snapshot);
3453 let had_active_inline_completion = this.has_active_inline_completion(cx);
3454 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3455 s.select(new_selections)
3456 });
3457
3458 if !bracket_inserted {
3459 if let Some(on_type_format_task) =
3460 this.trigger_on_type_formatting(text.to_string(), cx)
3461 {
3462 on_type_format_task.detach_and_log_err(cx);
3463 }
3464 }
3465
3466 let editor_settings = EditorSettings::get_global(cx);
3467 if bracket_inserted
3468 && (editor_settings.auto_signature_help
3469 || editor_settings.show_signature_help_after_edits)
3470 {
3471 this.show_signature_help(&ShowSignatureHelp, cx);
3472 }
3473
3474 let trigger_in_words = !had_active_inline_completion;
3475 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3476 linked_editing_ranges::refresh_linked_ranges(this, cx);
3477 this.refresh_inline_completion(true, false, cx);
3478 });
3479 }
3480
3481 fn find_possible_emoji_shortcode_at_position(
3482 snapshot: &MultiBufferSnapshot,
3483 position: Point,
3484 ) -> Option<String> {
3485 let mut chars = Vec::new();
3486 let mut found_colon = false;
3487 for char in snapshot.reversed_chars_at(position).take(100) {
3488 // Found a possible emoji shortcode in the middle of the buffer
3489 if found_colon {
3490 if char.is_whitespace() {
3491 chars.reverse();
3492 return Some(chars.iter().collect());
3493 }
3494 // If the previous character is not a whitespace, we are in the middle of a word
3495 // and we only want to complete the shortcode if the word is made up of other emojis
3496 let mut containing_word = String::new();
3497 for ch in snapshot
3498 .reversed_chars_at(position)
3499 .skip(chars.len() + 1)
3500 .take(100)
3501 {
3502 if ch.is_whitespace() {
3503 break;
3504 }
3505 containing_word.push(ch);
3506 }
3507 let containing_word = containing_word.chars().rev().collect::<String>();
3508 if util::word_consists_of_emojis(containing_word.as_str()) {
3509 chars.reverse();
3510 return Some(chars.iter().collect());
3511 }
3512 }
3513
3514 if char.is_whitespace() || !char.is_ascii() {
3515 return None;
3516 }
3517 if char == ':' {
3518 found_colon = true;
3519 } else {
3520 chars.push(char);
3521 }
3522 }
3523 // Found a possible emoji shortcode at the beginning of the buffer
3524 chars.reverse();
3525 Some(chars.iter().collect())
3526 }
3527
3528 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3529 self.transact(cx, |this, cx| {
3530 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3531 let selections = this.selections.all::<usize>(cx);
3532 let multi_buffer = this.buffer.read(cx);
3533 let buffer = multi_buffer.snapshot(cx);
3534 selections
3535 .iter()
3536 .map(|selection| {
3537 let start_point = selection.start.to_point(&buffer);
3538 let mut indent =
3539 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3540 indent.len = cmp::min(indent.len, start_point.column);
3541 let start = selection.start;
3542 let end = selection.end;
3543 let selection_is_empty = start == end;
3544 let language_scope = buffer.language_scope_at(start);
3545 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3546 &language_scope
3547 {
3548 let leading_whitespace_len = buffer
3549 .reversed_chars_at(start)
3550 .take_while(|c| c.is_whitespace() && *c != '\n')
3551 .map(|c| c.len_utf8())
3552 .sum::<usize>();
3553
3554 let trailing_whitespace_len = buffer
3555 .chars_at(end)
3556 .take_while(|c| c.is_whitespace() && *c != '\n')
3557 .map(|c| c.len_utf8())
3558 .sum::<usize>();
3559
3560 let insert_extra_newline =
3561 language.brackets().any(|(pair, enabled)| {
3562 let pair_start = pair.start.trim_end();
3563 let pair_end = pair.end.trim_start();
3564
3565 enabled
3566 && pair.newline
3567 && buffer.contains_str_at(
3568 end + trailing_whitespace_len,
3569 pair_end,
3570 )
3571 && buffer.contains_str_at(
3572 (start - leading_whitespace_len)
3573 .saturating_sub(pair_start.len()),
3574 pair_start,
3575 )
3576 });
3577
3578 // Comment extension on newline is allowed only for cursor selections
3579 let comment_delimiter = maybe!({
3580 if !selection_is_empty {
3581 return None;
3582 }
3583
3584 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3585 return None;
3586 }
3587
3588 let delimiters = language.line_comment_prefixes();
3589 let max_len_of_delimiter =
3590 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3591 let (snapshot, range) =
3592 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3593
3594 let mut index_of_first_non_whitespace = 0;
3595 let comment_candidate = snapshot
3596 .chars_for_range(range)
3597 .skip_while(|c| {
3598 let should_skip = c.is_whitespace();
3599 if should_skip {
3600 index_of_first_non_whitespace += 1;
3601 }
3602 should_skip
3603 })
3604 .take(max_len_of_delimiter)
3605 .collect::<String>();
3606 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3607 comment_candidate.starts_with(comment_prefix.as_ref())
3608 })?;
3609 let cursor_is_placed_after_comment_marker =
3610 index_of_first_non_whitespace + comment_prefix.len()
3611 <= start_point.column as usize;
3612 if cursor_is_placed_after_comment_marker {
3613 Some(comment_prefix.clone())
3614 } else {
3615 None
3616 }
3617 });
3618 (comment_delimiter, insert_extra_newline)
3619 } else {
3620 (None, false)
3621 };
3622
3623 let capacity_for_delimiter = comment_delimiter
3624 .as_deref()
3625 .map(str::len)
3626 .unwrap_or_default();
3627 let mut new_text =
3628 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3629 new_text.push('\n');
3630 new_text.extend(indent.chars());
3631 if let Some(delimiter) = &comment_delimiter {
3632 new_text.push_str(delimiter);
3633 }
3634 if insert_extra_newline {
3635 new_text = new_text.repeat(2);
3636 }
3637
3638 let anchor = buffer.anchor_after(end);
3639 let new_selection = selection.map(|_| anchor);
3640 (
3641 (start..end, new_text),
3642 (insert_extra_newline, new_selection),
3643 )
3644 })
3645 .unzip()
3646 };
3647
3648 this.edit_with_autoindent(edits, cx);
3649 let buffer = this.buffer.read(cx).snapshot(cx);
3650 let new_selections = selection_fixup_info
3651 .into_iter()
3652 .map(|(extra_newline_inserted, new_selection)| {
3653 let mut cursor = new_selection.end.to_point(&buffer);
3654 if extra_newline_inserted {
3655 cursor.row -= 1;
3656 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3657 }
3658 new_selection.map(|_| cursor)
3659 })
3660 .collect();
3661
3662 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3663 this.refresh_inline_completion(true, false, cx);
3664 });
3665 }
3666
3667 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3668 let buffer = self.buffer.read(cx);
3669 let snapshot = buffer.snapshot(cx);
3670
3671 let mut edits = Vec::new();
3672 let mut rows = Vec::new();
3673
3674 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3675 let cursor = selection.head();
3676 let row = cursor.row;
3677
3678 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3679
3680 let newline = "\n".to_string();
3681 edits.push((start_of_line..start_of_line, newline));
3682
3683 rows.push(row + rows_inserted as u32);
3684 }
3685
3686 self.transact(cx, |editor, cx| {
3687 editor.edit(edits, cx);
3688
3689 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3690 let mut index = 0;
3691 s.move_cursors_with(|map, _, _| {
3692 let row = rows[index];
3693 index += 1;
3694
3695 let point = Point::new(row, 0);
3696 let boundary = map.next_line_boundary(point).1;
3697 let clipped = map.clip_point(boundary, Bias::Left);
3698
3699 (clipped, SelectionGoal::None)
3700 });
3701 });
3702
3703 let mut indent_edits = Vec::new();
3704 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3705 for row in rows {
3706 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3707 for (row, indent) in indents {
3708 if indent.len == 0 {
3709 continue;
3710 }
3711
3712 let text = match indent.kind {
3713 IndentKind::Space => " ".repeat(indent.len as usize),
3714 IndentKind::Tab => "\t".repeat(indent.len as usize),
3715 };
3716 let point = Point::new(row.0, 0);
3717 indent_edits.push((point..point, text));
3718 }
3719 }
3720 editor.edit(indent_edits, cx);
3721 });
3722 }
3723
3724 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3725 let buffer = self.buffer.read(cx);
3726 let snapshot = buffer.snapshot(cx);
3727
3728 let mut edits = Vec::new();
3729 let mut rows = Vec::new();
3730 let mut rows_inserted = 0;
3731
3732 for selection in self.selections.all_adjusted(cx) {
3733 let cursor = selection.head();
3734 let row = cursor.row;
3735
3736 let point = Point::new(row + 1, 0);
3737 let start_of_line = snapshot.clip_point(point, Bias::Left);
3738
3739 let newline = "\n".to_string();
3740 edits.push((start_of_line..start_of_line, newline));
3741
3742 rows_inserted += 1;
3743 rows.push(row + rows_inserted);
3744 }
3745
3746 self.transact(cx, |editor, cx| {
3747 editor.edit(edits, cx);
3748
3749 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3750 let mut index = 0;
3751 s.move_cursors_with(|map, _, _| {
3752 let row = rows[index];
3753 index += 1;
3754
3755 let point = Point::new(row, 0);
3756 let boundary = map.next_line_boundary(point).1;
3757 let clipped = map.clip_point(boundary, Bias::Left);
3758
3759 (clipped, SelectionGoal::None)
3760 });
3761 });
3762
3763 let mut indent_edits = Vec::new();
3764 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3765 for row in rows {
3766 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3767 for (row, indent) in indents {
3768 if indent.len == 0 {
3769 continue;
3770 }
3771
3772 let text = match indent.kind {
3773 IndentKind::Space => " ".repeat(indent.len as usize),
3774 IndentKind::Tab => "\t".repeat(indent.len as usize),
3775 };
3776 let point = Point::new(row.0, 0);
3777 indent_edits.push((point..point, text));
3778 }
3779 }
3780 editor.edit(indent_edits, cx);
3781 });
3782 }
3783
3784 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3785 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3786 original_indent_columns: Vec::new(),
3787 });
3788 self.insert_with_autoindent_mode(text, autoindent, cx);
3789 }
3790
3791 fn insert_with_autoindent_mode(
3792 &mut self,
3793 text: &str,
3794 autoindent_mode: Option<AutoindentMode>,
3795 cx: &mut ViewContext<Self>,
3796 ) {
3797 if self.read_only(cx) {
3798 return;
3799 }
3800
3801 let text: Arc<str> = text.into();
3802 self.transact(cx, |this, cx| {
3803 let old_selections = this.selections.all_adjusted(cx);
3804 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3805 let anchors = {
3806 let snapshot = buffer.read(cx);
3807 old_selections
3808 .iter()
3809 .map(|s| {
3810 let anchor = snapshot.anchor_after(s.head());
3811 s.map(|_| anchor)
3812 })
3813 .collect::<Vec<_>>()
3814 };
3815 buffer.edit(
3816 old_selections
3817 .iter()
3818 .map(|s| (s.start..s.end, text.clone())),
3819 autoindent_mode,
3820 cx,
3821 );
3822 anchors
3823 });
3824
3825 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3826 s.select_anchors(selection_anchors);
3827 })
3828 });
3829 }
3830
3831 fn trigger_completion_on_input(
3832 &mut self,
3833 text: &str,
3834 trigger_in_words: bool,
3835 cx: &mut ViewContext<Self>,
3836 ) {
3837 if self.is_completion_trigger(text, trigger_in_words, cx) {
3838 self.show_completions(
3839 &ShowCompletions {
3840 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3841 },
3842 cx,
3843 );
3844 } else {
3845 self.hide_context_menu(cx);
3846 }
3847 }
3848
3849 fn is_completion_trigger(
3850 &self,
3851 text: &str,
3852 trigger_in_words: bool,
3853 cx: &mut ViewContext<Self>,
3854 ) -> bool {
3855 let position = self.selections.newest_anchor().head();
3856 let multibuffer = self.buffer.read(cx);
3857 let Some(buffer) = position
3858 .buffer_id
3859 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3860 else {
3861 return false;
3862 };
3863
3864 if let Some(completion_provider) = &self.completion_provider {
3865 completion_provider.is_completion_trigger(
3866 &buffer,
3867 position.text_anchor,
3868 text,
3869 trigger_in_words,
3870 cx,
3871 )
3872 } else {
3873 false
3874 }
3875 }
3876
3877 /// If any empty selections is touching the start of its innermost containing autoclose
3878 /// region, expand it to select the brackets.
3879 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3880 let selections = self.selections.all::<usize>(cx);
3881 let buffer = self.buffer.read(cx).read(cx);
3882 let new_selections = self
3883 .selections_with_autoclose_regions(selections, &buffer)
3884 .map(|(mut selection, region)| {
3885 if !selection.is_empty() {
3886 return selection;
3887 }
3888
3889 if let Some(region) = region {
3890 let mut range = region.range.to_offset(&buffer);
3891 if selection.start == range.start && range.start >= region.pair.start.len() {
3892 range.start -= region.pair.start.len();
3893 if buffer.contains_str_at(range.start, ®ion.pair.start)
3894 && buffer.contains_str_at(range.end, ®ion.pair.end)
3895 {
3896 range.end += region.pair.end.len();
3897 selection.start = range.start;
3898 selection.end = range.end;
3899
3900 return selection;
3901 }
3902 }
3903 }
3904
3905 let always_treat_brackets_as_autoclosed = buffer
3906 .settings_at(selection.start, cx)
3907 .always_treat_brackets_as_autoclosed;
3908
3909 if !always_treat_brackets_as_autoclosed {
3910 return selection;
3911 }
3912
3913 if let Some(scope) = buffer.language_scope_at(selection.start) {
3914 for (pair, enabled) in scope.brackets() {
3915 if !enabled || !pair.close {
3916 continue;
3917 }
3918
3919 if buffer.contains_str_at(selection.start, &pair.end) {
3920 let pair_start_len = pair.start.len();
3921 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3922 {
3923 selection.start -= pair_start_len;
3924 selection.end += pair.end.len();
3925
3926 return selection;
3927 }
3928 }
3929 }
3930 }
3931
3932 selection
3933 })
3934 .collect();
3935
3936 drop(buffer);
3937 self.change_selections(None, cx, |selections| selections.select(new_selections));
3938 }
3939
3940 /// Iterate the given selections, and for each one, find the smallest surrounding
3941 /// autoclose region. This uses the ordering of the selections and the autoclose
3942 /// regions to avoid repeated comparisons.
3943 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3944 &'a self,
3945 selections: impl IntoIterator<Item = Selection<D>>,
3946 buffer: &'a MultiBufferSnapshot,
3947 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3948 let mut i = 0;
3949 let mut regions = self.autoclose_regions.as_slice();
3950 selections.into_iter().map(move |selection| {
3951 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3952
3953 let mut enclosing = None;
3954 while let Some(pair_state) = regions.get(i) {
3955 if pair_state.range.end.to_offset(buffer) < range.start {
3956 regions = ®ions[i + 1..];
3957 i = 0;
3958 } else if pair_state.range.start.to_offset(buffer) > range.end {
3959 break;
3960 } else {
3961 if pair_state.selection_id == selection.id {
3962 enclosing = Some(pair_state);
3963 }
3964 i += 1;
3965 }
3966 }
3967
3968 (selection.clone(), enclosing)
3969 })
3970 }
3971
3972 /// Remove any autoclose regions that no longer contain their selection.
3973 fn invalidate_autoclose_regions(
3974 &mut self,
3975 mut selections: &[Selection<Anchor>],
3976 buffer: &MultiBufferSnapshot,
3977 ) {
3978 self.autoclose_regions.retain(|state| {
3979 let mut i = 0;
3980 while let Some(selection) = selections.get(i) {
3981 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3982 selections = &selections[1..];
3983 continue;
3984 }
3985 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3986 break;
3987 }
3988 if selection.id == state.selection_id {
3989 return true;
3990 } else {
3991 i += 1;
3992 }
3993 }
3994 false
3995 });
3996 }
3997
3998 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3999 let offset = position.to_offset(buffer);
4000 let (word_range, kind) = buffer.surrounding_word(offset, true);
4001 if offset > word_range.start && kind == Some(CharKind::Word) {
4002 Some(
4003 buffer
4004 .text_for_range(word_range.start..offset)
4005 .collect::<String>(),
4006 )
4007 } else {
4008 None
4009 }
4010 }
4011
4012 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4013 self.refresh_inlay_hints(
4014 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4015 cx,
4016 );
4017 }
4018
4019 pub fn inlay_hints_enabled(&self) -> bool {
4020 self.inlay_hint_cache.enabled
4021 }
4022
4023 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4024 if self.project.is_none() || self.mode != EditorMode::Full {
4025 return;
4026 }
4027
4028 let reason_description = reason.description();
4029 let ignore_debounce = matches!(
4030 reason,
4031 InlayHintRefreshReason::SettingsChange(_)
4032 | InlayHintRefreshReason::Toggle(_)
4033 | InlayHintRefreshReason::ExcerptsRemoved(_)
4034 );
4035 let (invalidate_cache, required_languages) = match reason {
4036 InlayHintRefreshReason::Toggle(enabled) => {
4037 self.inlay_hint_cache.enabled = enabled;
4038 if enabled {
4039 (InvalidationStrategy::RefreshRequested, None)
4040 } else {
4041 self.inlay_hint_cache.clear();
4042 self.splice_inlays(
4043 self.visible_inlay_hints(cx)
4044 .iter()
4045 .map(|inlay| inlay.id)
4046 .collect(),
4047 Vec::new(),
4048 cx,
4049 );
4050 return;
4051 }
4052 }
4053 InlayHintRefreshReason::SettingsChange(new_settings) => {
4054 match self.inlay_hint_cache.update_settings(
4055 &self.buffer,
4056 new_settings,
4057 self.visible_inlay_hints(cx),
4058 cx,
4059 ) {
4060 ControlFlow::Break(Some(InlaySplice {
4061 to_remove,
4062 to_insert,
4063 })) => {
4064 self.splice_inlays(to_remove, to_insert, cx);
4065 return;
4066 }
4067 ControlFlow::Break(None) => return,
4068 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4069 }
4070 }
4071 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4072 if let Some(InlaySplice {
4073 to_remove,
4074 to_insert,
4075 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4076 {
4077 self.splice_inlays(to_remove, to_insert, cx);
4078 }
4079 return;
4080 }
4081 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4082 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4083 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4084 }
4085 InlayHintRefreshReason::RefreshRequested => {
4086 (InvalidationStrategy::RefreshRequested, None)
4087 }
4088 };
4089
4090 if let Some(InlaySplice {
4091 to_remove,
4092 to_insert,
4093 }) = self.inlay_hint_cache.spawn_hint_refresh(
4094 reason_description,
4095 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4096 invalidate_cache,
4097 ignore_debounce,
4098 cx,
4099 ) {
4100 self.splice_inlays(to_remove, to_insert, cx);
4101 }
4102 }
4103
4104 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4105 self.display_map
4106 .read(cx)
4107 .current_inlays()
4108 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4109 .cloned()
4110 .collect()
4111 }
4112
4113 pub fn excerpts_for_inlay_hints_query(
4114 &self,
4115 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4116 cx: &mut ViewContext<Editor>,
4117 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4118 let Some(project) = self.project.as_ref() else {
4119 return HashMap::default();
4120 };
4121 let project = project.read(cx);
4122 let multi_buffer = self.buffer().read(cx);
4123 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4124 let multi_buffer_visible_start = self
4125 .scroll_manager
4126 .anchor()
4127 .anchor
4128 .to_point(&multi_buffer_snapshot);
4129 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4130 multi_buffer_visible_start
4131 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4132 Bias::Left,
4133 );
4134 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4135 multi_buffer
4136 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4137 .into_iter()
4138 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4139 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4140 let buffer = buffer_handle.read(cx);
4141 let buffer_file = project::File::from_dyn(buffer.file())?;
4142 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4143 let worktree_entry = buffer_worktree
4144 .read(cx)
4145 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4146 if worktree_entry.is_ignored {
4147 return None;
4148 }
4149
4150 let language = buffer.language()?;
4151 if let Some(restrict_to_languages) = restrict_to_languages {
4152 if !restrict_to_languages.contains(language) {
4153 return None;
4154 }
4155 }
4156 Some((
4157 excerpt_id,
4158 (
4159 buffer_handle,
4160 buffer.version().clone(),
4161 excerpt_visible_range,
4162 ),
4163 ))
4164 })
4165 .collect()
4166 }
4167
4168 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4169 TextLayoutDetails {
4170 text_system: cx.text_system().clone(),
4171 editor_style: self.style.clone().unwrap(),
4172 rem_size: cx.rem_size(),
4173 scroll_anchor: self.scroll_manager.anchor(),
4174 visible_rows: self.visible_line_count(),
4175 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4176 }
4177 }
4178
4179 fn splice_inlays(
4180 &self,
4181 to_remove: Vec<InlayId>,
4182 to_insert: Vec<Inlay>,
4183 cx: &mut ViewContext<Self>,
4184 ) {
4185 self.display_map.update(cx, |display_map, cx| {
4186 display_map.splice_inlays(to_remove, to_insert, cx);
4187 });
4188 cx.notify();
4189 }
4190
4191 fn trigger_on_type_formatting(
4192 &self,
4193 input: String,
4194 cx: &mut ViewContext<Self>,
4195 ) -> Option<Task<Result<()>>> {
4196 if input.len() != 1 {
4197 return None;
4198 }
4199
4200 let project = self.project.as_ref()?;
4201 let position = self.selections.newest_anchor().head();
4202 let (buffer, buffer_position) = self
4203 .buffer
4204 .read(cx)
4205 .text_anchor_for_position(position, cx)?;
4206
4207 let settings = language_settings::language_settings(
4208 buffer.read(cx).language_at(buffer_position).as_ref(),
4209 buffer.read(cx).file(),
4210 cx,
4211 );
4212 if !settings.use_on_type_format {
4213 return None;
4214 }
4215
4216 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4217 // hence we do LSP request & edit on host side only — add formats to host's history.
4218 let push_to_lsp_host_history = true;
4219 // If this is not the host, append its history with new edits.
4220 let push_to_client_history = project.read(cx).is_via_collab();
4221
4222 let on_type_formatting = project.update(cx, |project, cx| {
4223 project.on_type_format(
4224 buffer.clone(),
4225 buffer_position,
4226 input,
4227 push_to_lsp_host_history,
4228 cx,
4229 )
4230 });
4231 Some(cx.spawn(|editor, mut cx| async move {
4232 if let Some(transaction) = on_type_formatting.await? {
4233 if push_to_client_history {
4234 buffer
4235 .update(&mut cx, |buffer, _| {
4236 buffer.push_transaction(transaction, Instant::now());
4237 })
4238 .ok();
4239 }
4240 editor.update(&mut cx, |editor, cx| {
4241 editor.refresh_document_highlights(cx);
4242 })?;
4243 }
4244 Ok(())
4245 }))
4246 }
4247
4248 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4249 if self.pending_rename.is_some() {
4250 return;
4251 }
4252
4253 let Some(provider) = self.completion_provider.as_ref() else {
4254 return;
4255 };
4256
4257 let position = self.selections.newest_anchor().head();
4258 let (buffer, buffer_position) =
4259 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4260 output
4261 } else {
4262 return;
4263 };
4264
4265 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4266 let is_followup_invoke = {
4267 let context_menu_state = self.context_menu.read();
4268 matches!(
4269 context_menu_state.deref(),
4270 Some(ContextMenu::Completions(_))
4271 )
4272 };
4273 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4274 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4275 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4276 CompletionTriggerKind::TRIGGER_CHARACTER
4277 }
4278
4279 _ => CompletionTriggerKind::INVOKED,
4280 };
4281 let completion_context = CompletionContext {
4282 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4283 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4284 Some(String::from(trigger))
4285 } else {
4286 None
4287 }
4288 }),
4289 trigger_kind,
4290 };
4291 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4292 let sort_completions = provider.sort_completions();
4293
4294 let id = post_inc(&mut self.next_completion_id);
4295 let task = cx.spawn(|this, mut cx| {
4296 async move {
4297 this.update(&mut cx, |this, _| {
4298 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4299 })?;
4300 let completions = completions.await.log_err();
4301 let menu = if let Some(completions) = completions {
4302 let mut menu = CompletionsMenu {
4303 id,
4304 sort_completions,
4305 initial_position: position,
4306 match_candidates: completions
4307 .iter()
4308 .enumerate()
4309 .map(|(id, completion)| {
4310 StringMatchCandidate::new(
4311 id,
4312 completion.label.text[completion.label.filter_range.clone()]
4313 .into(),
4314 )
4315 })
4316 .collect(),
4317 buffer: buffer.clone(),
4318 completions: Arc::new(RwLock::new(completions.into())),
4319 matches: Vec::new().into(),
4320 selected_item: 0,
4321 scroll_handle: UniformListScrollHandle::new(),
4322 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4323 DebouncedDelay::new(),
4324 )),
4325 };
4326 menu.filter(query.as_deref(), cx.background_executor().clone())
4327 .await;
4328
4329 if menu.matches.is_empty() {
4330 None
4331 } else {
4332 this.update(&mut cx, |editor, cx| {
4333 let completions = menu.completions.clone();
4334 let matches = menu.matches.clone();
4335
4336 let delay_ms = EditorSettings::get_global(cx)
4337 .completion_documentation_secondary_query_debounce;
4338 let delay = Duration::from_millis(delay_ms);
4339 editor
4340 .completion_documentation_pre_resolve_debounce
4341 .fire_new(delay, cx, |editor, cx| {
4342 CompletionsMenu::pre_resolve_completion_documentation(
4343 buffer,
4344 completions,
4345 matches,
4346 editor,
4347 cx,
4348 )
4349 });
4350 })
4351 .ok();
4352 Some(menu)
4353 }
4354 } else {
4355 None
4356 };
4357
4358 this.update(&mut cx, |this, cx| {
4359 let mut context_menu = this.context_menu.write();
4360 match context_menu.as_ref() {
4361 None => {}
4362
4363 Some(ContextMenu::Completions(prev_menu)) => {
4364 if prev_menu.id > id {
4365 return;
4366 }
4367 }
4368
4369 _ => return,
4370 }
4371
4372 if this.focus_handle.is_focused(cx) && menu.is_some() {
4373 let menu = menu.unwrap();
4374 *context_menu = Some(ContextMenu::Completions(menu));
4375 drop(context_menu);
4376 this.discard_inline_completion(false, cx);
4377 cx.notify();
4378 } else if this.completion_tasks.len() <= 1 {
4379 // If there are no more completion tasks and the last menu was
4380 // empty, we should hide it. If it was already hidden, we should
4381 // also show the copilot completion when available.
4382 drop(context_menu);
4383 if this.hide_context_menu(cx).is_none() {
4384 this.update_visible_inline_completion(cx);
4385 }
4386 }
4387 })?;
4388
4389 Ok::<_, anyhow::Error>(())
4390 }
4391 .log_err()
4392 });
4393
4394 self.completion_tasks.push((id, task));
4395 }
4396
4397 pub fn confirm_completion(
4398 &mut self,
4399 action: &ConfirmCompletion,
4400 cx: &mut ViewContext<Self>,
4401 ) -> Option<Task<Result<()>>> {
4402 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4403 }
4404
4405 pub fn compose_completion(
4406 &mut self,
4407 action: &ComposeCompletion,
4408 cx: &mut ViewContext<Self>,
4409 ) -> Option<Task<Result<()>>> {
4410 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4411 }
4412
4413 fn do_completion(
4414 &mut self,
4415 item_ix: Option<usize>,
4416 intent: CompletionIntent,
4417 cx: &mut ViewContext<Editor>,
4418 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4419 use language::ToOffset as _;
4420
4421 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4422 menu
4423 } else {
4424 return None;
4425 };
4426
4427 let mat = completions_menu
4428 .matches
4429 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4430 let buffer_handle = completions_menu.buffer;
4431 let completions = completions_menu.completions.read();
4432 let completion = completions.get(mat.candidate_id)?;
4433 cx.stop_propagation();
4434
4435 let snippet;
4436 let text;
4437
4438 if completion.is_snippet() {
4439 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4440 text = snippet.as_ref().unwrap().text.clone();
4441 } else {
4442 snippet = None;
4443 text = completion.new_text.clone();
4444 };
4445 let selections = self.selections.all::<usize>(cx);
4446 let buffer = buffer_handle.read(cx);
4447 let old_range = completion.old_range.to_offset(buffer);
4448 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4449
4450 let newest_selection = self.selections.newest_anchor();
4451 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4452 return None;
4453 }
4454
4455 let lookbehind = newest_selection
4456 .start
4457 .text_anchor
4458 .to_offset(buffer)
4459 .saturating_sub(old_range.start);
4460 let lookahead = old_range
4461 .end
4462 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4463 let mut common_prefix_len = old_text
4464 .bytes()
4465 .zip(text.bytes())
4466 .take_while(|(a, b)| a == b)
4467 .count();
4468
4469 let snapshot = self.buffer.read(cx).snapshot(cx);
4470 let mut range_to_replace: Option<Range<isize>> = None;
4471 let mut ranges = Vec::new();
4472 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4473 for selection in &selections {
4474 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4475 let start = selection.start.saturating_sub(lookbehind);
4476 let end = selection.end + lookahead;
4477 if selection.id == newest_selection.id {
4478 range_to_replace = Some(
4479 ((start + common_prefix_len) as isize - selection.start as isize)
4480 ..(end as isize - selection.start as isize),
4481 );
4482 }
4483 ranges.push(start + common_prefix_len..end);
4484 } else {
4485 common_prefix_len = 0;
4486 ranges.clear();
4487 ranges.extend(selections.iter().map(|s| {
4488 if s.id == newest_selection.id {
4489 range_to_replace = Some(
4490 old_range.start.to_offset_utf16(&snapshot).0 as isize
4491 - selection.start as isize
4492 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4493 - selection.start as isize,
4494 );
4495 old_range.clone()
4496 } else {
4497 s.start..s.end
4498 }
4499 }));
4500 break;
4501 }
4502 if !self.linked_edit_ranges.is_empty() {
4503 let start_anchor = snapshot.anchor_before(selection.head());
4504 let end_anchor = snapshot.anchor_after(selection.tail());
4505 if let Some(ranges) = self
4506 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4507 {
4508 for (buffer, edits) in ranges {
4509 linked_edits.entry(buffer.clone()).or_default().extend(
4510 edits
4511 .into_iter()
4512 .map(|range| (range, text[common_prefix_len..].to_owned())),
4513 );
4514 }
4515 }
4516 }
4517 }
4518 let text = &text[common_prefix_len..];
4519
4520 cx.emit(EditorEvent::InputHandled {
4521 utf16_range_to_replace: range_to_replace,
4522 text: text.into(),
4523 });
4524
4525 self.transact(cx, |this, cx| {
4526 if let Some(mut snippet) = snippet {
4527 snippet.text = text.to_string();
4528 for tabstop in snippet.tabstops.iter_mut().flatten() {
4529 tabstop.start -= common_prefix_len as isize;
4530 tabstop.end -= common_prefix_len as isize;
4531 }
4532
4533 this.insert_snippet(&ranges, snippet, cx).log_err();
4534 } else {
4535 this.buffer.update(cx, |buffer, cx| {
4536 buffer.edit(
4537 ranges.iter().map(|range| (range.clone(), text)),
4538 this.autoindent_mode.clone(),
4539 cx,
4540 );
4541 });
4542 }
4543 for (buffer, edits) in linked_edits {
4544 buffer.update(cx, |buffer, cx| {
4545 let snapshot = buffer.snapshot();
4546 let edits = edits
4547 .into_iter()
4548 .map(|(range, text)| {
4549 use text::ToPoint as TP;
4550 let end_point = TP::to_point(&range.end, &snapshot);
4551 let start_point = TP::to_point(&range.start, &snapshot);
4552 (start_point..end_point, text)
4553 })
4554 .sorted_by_key(|(range, _)| range.start)
4555 .collect::<Vec<_>>();
4556 buffer.edit(edits, None, cx);
4557 })
4558 }
4559
4560 this.refresh_inline_completion(true, false, cx);
4561 });
4562
4563 let show_new_completions_on_confirm = completion
4564 .confirm
4565 .as_ref()
4566 .map_or(false, |confirm| confirm(intent, cx));
4567 if show_new_completions_on_confirm {
4568 self.show_completions(&ShowCompletions { trigger: None }, cx);
4569 }
4570
4571 let provider = self.completion_provider.as_ref()?;
4572 let apply_edits = provider.apply_additional_edits_for_completion(
4573 buffer_handle,
4574 completion.clone(),
4575 true,
4576 cx,
4577 );
4578
4579 let editor_settings = EditorSettings::get_global(cx);
4580 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4581 // After the code completion is finished, users often want to know what signatures are needed.
4582 // so we should automatically call signature_help
4583 self.show_signature_help(&ShowSignatureHelp, cx);
4584 }
4585
4586 Some(cx.foreground_executor().spawn(async move {
4587 apply_edits.await?;
4588 Ok(())
4589 }))
4590 }
4591
4592 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4593 let mut context_menu = self.context_menu.write();
4594 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4595 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4596 // Toggle if we're selecting the same one
4597 *context_menu = None;
4598 cx.notify();
4599 return;
4600 } else {
4601 // Otherwise, clear it and start a new one
4602 *context_menu = None;
4603 cx.notify();
4604 }
4605 }
4606 drop(context_menu);
4607 let snapshot = self.snapshot(cx);
4608 let deployed_from_indicator = action.deployed_from_indicator;
4609 let mut task = self.code_actions_task.take();
4610 let action = action.clone();
4611 cx.spawn(|editor, mut cx| async move {
4612 while let Some(prev_task) = task {
4613 prev_task.await.log_err();
4614 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4615 }
4616
4617 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4618 if editor.focus_handle.is_focused(cx) {
4619 let multibuffer_point = action
4620 .deployed_from_indicator
4621 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4622 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4623 let (buffer, buffer_row) = snapshot
4624 .buffer_snapshot
4625 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4626 .and_then(|(buffer_snapshot, range)| {
4627 editor
4628 .buffer
4629 .read(cx)
4630 .buffer(buffer_snapshot.remote_id())
4631 .map(|buffer| (buffer, range.start.row))
4632 })?;
4633 let (_, code_actions) = editor
4634 .available_code_actions
4635 .clone()
4636 .and_then(|(location, code_actions)| {
4637 let snapshot = location.buffer.read(cx).snapshot();
4638 let point_range = location.range.to_point(&snapshot);
4639 let point_range = point_range.start.row..=point_range.end.row;
4640 if point_range.contains(&buffer_row) {
4641 Some((location, code_actions))
4642 } else {
4643 None
4644 }
4645 })
4646 .unzip();
4647 let buffer_id = buffer.read(cx).remote_id();
4648 let tasks = editor
4649 .tasks
4650 .get(&(buffer_id, buffer_row))
4651 .map(|t| Arc::new(t.to_owned()));
4652 if tasks.is_none() && code_actions.is_none() {
4653 return None;
4654 }
4655
4656 editor.completion_tasks.clear();
4657 editor.discard_inline_completion(false, cx);
4658 let task_context =
4659 tasks
4660 .as_ref()
4661 .zip(editor.project.clone())
4662 .map(|(tasks, project)| {
4663 let position = Point::new(buffer_row, tasks.column);
4664 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4665 let location = Location {
4666 buffer: buffer.clone(),
4667 range: range_start..range_start,
4668 };
4669 // Fill in the environmental variables from the tree-sitter captures
4670 let mut captured_task_variables = TaskVariables::default();
4671 for (capture_name, value) in tasks.extra_variables.clone() {
4672 captured_task_variables.insert(
4673 task::VariableName::Custom(capture_name.into()),
4674 value.clone(),
4675 );
4676 }
4677 project.update(cx, |project, cx| {
4678 project.task_context_for_location(
4679 captured_task_variables,
4680 location,
4681 cx,
4682 )
4683 })
4684 });
4685
4686 Some(cx.spawn(|editor, mut cx| async move {
4687 let task_context = match task_context {
4688 Some(task_context) => task_context.await,
4689 None => None,
4690 };
4691 let resolved_tasks =
4692 tasks.zip(task_context).map(|(tasks, task_context)| {
4693 Arc::new(ResolvedTasks {
4694 templates: tasks
4695 .templates
4696 .iter()
4697 .filter_map(|(kind, template)| {
4698 template
4699 .resolve_task(&kind.to_id_base(), &task_context)
4700 .map(|task| (kind.clone(), task))
4701 })
4702 .collect(),
4703 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4704 multibuffer_point.row,
4705 tasks.column,
4706 )),
4707 })
4708 });
4709 let spawn_straight_away = resolved_tasks
4710 .as_ref()
4711 .map_or(false, |tasks| tasks.templates.len() == 1)
4712 && code_actions
4713 .as_ref()
4714 .map_or(true, |actions| actions.is_empty());
4715 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4716 *editor.context_menu.write() =
4717 Some(ContextMenu::CodeActions(CodeActionsMenu {
4718 buffer,
4719 actions: CodeActionContents {
4720 tasks: resolved_tasks,
4721 actions: code_actions,
4722 },
4723 selected_item: Default::default(),
4724 scroll_handle: UniformListScrollHandle::default(),
4725 deployed_from_indicator,
4726 }));
4727 if spawn_straight_away {
4728 if let Some(task) = editor.confirm_code_action(
4729 &ConfirmCodeAction { item_ix: Some(0) },
4730 cx,
4731 ) {
4732 cx.notify();
4733 return task;
4734 }
4735 }
4736 cx.notify();
4737 Task::ready(Ok(()))
4738 }) {
4739 task.await
4740 } else {
4741 Ok(())
4742 }
4743 }))
4744 } else {
4745 Some(Task::ready(Ok(())))
4746 }
4747 })?;
4748 if let Some(task) = spawned_test_task {
4749 task.await?;
4750 }
4751
4752 Ok::<_, anyhow::Error>(())
4753 })
4754 .detach_and_log_err(cx);
4755 }
4756
4757 pub fn confirm_code_action(
4758 &mut self,
4759 action: &ConfirmCodeAction,
4760 cx: &mut ViewContext<Self>,
4761 ) -> Option<Task<Result<()>>> {
4762 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4763 menu
4764 } else {
4765 return None;
4766 };
4767 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4768 let action = actions_menu.actions.get(action_ix)?;
4769 let title = action.label();
4770 let buffer = actions_menu.buffer;
4771 let workspace = self.workspace()?;
4772
4773 match action {
4774 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4775 workspace.update(cx, |workspace, cx| {
4776 workspace::tasks::schedule_resolved_task(
4777 workspace,
4778 task_source_kind,
4779 resolved_task,
4780 false,
4781 cx,
4782 );
4783
4784 Some(Task::ready(Ok(())))
4785 })
4786 }
4787 CodeActionsItem::CodeAction {
4788 excerpt_id,
4789 action,
4790 provider,
4791 } => {
4792 let apply_code_action =
4793 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4794 let workspace = workspace.downgrade();
4795 Some(cx.spawn(|editor, cx| async move {
4796 let project_transaction = apply_code_action.await?;
4797 Self::open_project_transaction(
4798 &editor,
4799 workspace,
4800 project_transaction,
4801 title,
4802 cx,
4803 )
4804 .await
4805 }))
4806 }
4807 }
4808 }
4809
4810 pub async fn open_project_transaction(
4811 this: &WeakView<Editor>,
4812 workspace: WeakView<Workspace>,
4813 transaction: ProjectTransaction,
4814 title: String,
4815 mut cx: AsyncWindowContext,
4816 ) -> Result<()> {
4817 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4818 cx.update(|cx| {
4819 entries.sort_unstable_by_key(|(buffer, _)| {
4820 buffer.read(cx).file().map(|f| f.path().clone())
4821 });
4822 })?;
4823
4824 // If the project transaction's edits are all contained within this editor, then
4825 // avoid opening a new editor to display them.
4826
4827 if let Some((buffer, transaction)) = entries.first() {
4828 if entries.len() == 1 {
4829 let excerpt = this.update(&mut cx, |editor, cx| {
4830 editor
4831 .buffer()
4832 .read(cx)
4833 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4834 })?;
4835 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4836 if excerpted_buffer == *buffer {
4837 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4838 let excerpt_range = excerpt_range.to_offset(buffer);
4839 buffer
4840 .edited_ranges_for_transaction::<usize>(transaction)
4841 .all(|range| {
4842 excerpt_range.start <= range.start
4843 && excerpt_range.end >= range.end
4844 })
4845 })?;
4846
4847 if all_edits_within_excerpt {
4848 return Ok(());
4849 }
4850 }
4851 }
4852 }
4853 } else {
4854 return Ok(());
4855 }
4856
4857 let mut ranges_to_highlight = Vec::new();
4858 let excerpt_buffer = cx.new_model(|cx| {
4859 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4860 for (buffer_handle, transaction) in &entries {
4861 let buffer = buffer_handle.read(cx);
4862 ranges_to_highlight.extend(
4863 multibuffer.push_excerpts_with_context_lines(
4864 buffer_handle.clone(),
4865 buffer
4866 .edited_ranges_for_transaction::<usize>(transaction)
4867 .collect(),
4868 DEFAULT_MULTIBUFFER_CONTEXT,
4869 cx,
4870 ),
4871 );
4872 }
4873 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4874 multibuffer
4875 })?;
4876
4877 workspace.update(&mut cx, |workspace, cx| {
4878 let project = workspace.project().clone();
4879 let editor =
4880 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4881 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4882 editor.update(cx, |editor, cx| {
4883 editor.highlight_background::<Self>(
4884 &ranges_to_highlight,
4885 |theme| theme.editor_highlighted_line_background,
4886 cx,
4887 );
4888 });
4889 })?;
4890
4891 Ok(())
4892 }
4893
4894 pub fn push_code_action_provider(
4895 &mut self,
4896 provider: Arc<dyn CodeActionProvider>,
4897 cx: &mut ViewContext<Self>,
4898 ) {
4899 self.code_action_providers.push(provider);
4900 self.refresh_code_actions(cx);
4901 }
4902
4903 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4904 let buffer = self.buffer.read(cx);
4905 let newest_selection = self.selections.newest_anchor().clone();
4906 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4907 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4908 if start_buffer != end_buffer {
4909 return None;
4910 }
4911
4912 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4913 cx.background_executor()
4914 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4915 .await;
4916
4917 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4918 let providers = this.code_action_providers.clone();
4919 let tasks = this
4920 .code_action_providers
4921 .iter()
4922 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4923 .collect::<Vec<_>>();
4924 (providers, tasks)
4925 })?;
4926
4927 let mut actions = Vec::new();
4928 for (provider, provider_actions) in
4929 providers.into_iter().zip(future::join_all(tasks).await)
4930 {
4931 if let Some(provider_actions) = provider_actions.log_err() {
4932 actions.extend(provider_actions.into_iter().map(|action| {
4933 AvailableCodeAction {
4934 excerpt_id: newest_selection.start.excerpt_id,
4935 action,
4936 provider: provider.clone(),
4937 }
4938 }));
4939 }
4940 }
4941
4942 this.update(&mut cx, |this, cx| {
4943 this.available_code_actions = if actions.is_empty() {
4944 None
4945 } else {
4946 Some((
4947 Location {
4948 buffer: start_buffer,
4949 range: start..end,
4950 },
4951 actions.into(),
4952 ))
4953 };
4954 cx.notify();
4955 })
4956 }));
4957 None
4958 }
4959
4960 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4961 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4962 self.show_git_blame_inline = false;
4963
4964 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4965 cx.background_executor().timer(delay).await;
4966
4967 this.update(&mut cx, |this, cx| {
4968 this.show_git_blame_inline = true;
4969 cx.notify();
4970 })
4971 .log_err();
4972 }));
4973 }
4974 }
4975
4976 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4977 if self.pending_rename.is_some() {
4978 return None;
4979 }
4980
4981 let project = self.project.clone()?;
4982 let buffer = self.buffer.read(cx);
4983 let newest_selection = self.selections.newest_anchor().clone();
4984 let cursor_position = newest_selection.head();
4985 let (cursor_buffer, cursor_buffer_position) =
4986 buffer.text_anchor_for_position(cursor_position, cx)?;
4987 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4988 if cursor_buffer != tail_buffer {
4989 return None;
4990 }
4991
4992 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4993 cx.background_executor()
4994 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4995 .await;
4996
4997 let highlights = if let Some(highlights) = project
4998 .update(&mut cx, |project, cx| {
4999 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5000 })
5001 .log_err()
5002 {
5003 highlights.await.log_err()
5004 } else {
5005 None
5006 };
5007
5008 if let Some(highlights) = highlights {
5009 this.update(&mut cx, |this, cx| {
5010 if this.pending_rename.is_some() {
5011 return;
5012 }
5013
5014 let buffer_id = cursor_position.buffer_id;
5015 let buffer = this.buffer.read(cx);
5016 if !buffer
5017 .text_anchor_for_position(cursor_position, cx)
5018 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5019 {
5020 return;
5021 }
5022
5023 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5024 let mut write_ranges = Vec::new();
5025 let mut read_ranges = Vec::new();
5026 for highlight in highlights {
5027 for (excerpt_id, excerpt_range) in
5028 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5029 {
5030 let start = highlight
5031 .range
5032 .start
5033 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5034 let end = highlight
5035 .range
5036 .end
5037 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5038 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5039 continue;
5040 }
5041
5042 let range = Anchor {
5043 buffer_id,
5044 excerpt_id,
5045 text_anchor: start,
5046 }..Anchor {
5047 buffer_id,
5048 excerpt_id,
5049 text_anchor: end,
5050 };
5051 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5052 write_ranges.push(range);
5053 } else {
5054 read_ranges.push(range);
5055 }
5056 }
5057 }
5058
5059 this.highlight_background::<DocumentHighlightRead>(
5060 &read_ranges,
5061 |theme| theme.editor_document_highlight_read_background,
5062 cx,
5063 );
5064 this.highlight_background::<DocumentHighlightWrite>(
5065 &write_ranges,
5066 |theme| theme.editor_document_highlight_write_background,
5067 cx,
5068 );
5069 cx.notify();
5070 })
5071 .log_err();
5072 }
5073 }));
5074 None
5075 }
5076
5077 pub fn refresh_inline_completion(
5078 &mut self,
5079 debounce: bool,
5080 user_requested: bool,
5081 cx: &mut ViewContext<Self>,
5082 ) -> Option<()> {
5083 let provider = self.inline_completion_provider()?;
5084 let cursor = self.selections.newest_anchor().head();
5085 let (buffer, cursor_buffer_position) =
5086 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5087
5088 if !user_requested
5089 && (!self.enable_inline_completions
5090 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5091 {
5092 self.discard_inline_completion(false, cx);
5093 return None;
5094 }
5095
5096 self.update_visible_inline_completion(cx);
5097 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5098 Some(())
5099 }
5100
5101 fn cycle_inline_completion(
5102 &mut self,
5103 direction: Direction,
5104 cx: &mut ViewContext<Self>,
5105 ) -> Option<()> {
5106 let provider = self.inline_completion_provider()?;
5107 let cursor = self.selections.newest_anchor().head();
5108 let (buffer, cursor_buffer_position) =
5109 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5110 if !self.enable_inline_completions
5111 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5112 {
5113 return None;
5114 }
5115
5116 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5117 self.update_visible_inline_completion(cx);
5118
5119 Some(())
5120 }
5121
5122 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5123 if !self.has_active_inline_completion(cx) {
5124 self.refresh_inline_completion(false, true, cx);
5125 return;
5126 }
5127
5128 self.update_visible_inline_completion(cx);
5129 }
5130
5131 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5132 self.show_cursor_names(cx);
5133 }
5134
5135 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5136 self.show_cursor_names = true;
5137 cx.notify();
5138 cx.spawn(|this, mut cx| async move {
5139 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5140 this.update(&mut cx, |this, cx| {
5141 this.show_cursor_names = false;
5142 cx.notify()
5143 })
5144 .ok()
5145 })
5146 .detach();
5147 }
5148
5149 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5150 if self.has_active_inline_completion(cx) {
5151 self.cycle_inline_completion(Direction::Next, cx);
5152 } else {
5153 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5154 if is_copilot_disabled {
5155 cx.propagate();
5156 }
5157 }
5158 }
5159
5160 pub fn previous_inline_completion(
5161 &mut self,
5162 _: &PreviousInlineCompletion,
5163 cx: &mut ViewContext<Self>,
5164 ) {
5165 if self.has_active_inline_completion(cx) {
5166 self.cycle_inline_completion(Direction::Prev, cx);
5167 } else {
5168 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5169 if is_copilot_disabled {
5170 cx.propagate();
5171 }
5172 }
5173 }
5174
5175 pub fn accept_inline_completion(
5176 &mut self,
5177 _: &AcceptInlineCompletion,
5178 cx: &mut ViewContext<Self>,
5179 ) {
5180 let Some(completion) = self.take_active_inline_completion(cx) else {
5181 return;
5182 };
5183 if let Some(provider) = self.inline_completion_provider() {
5184 provider.accept(cx);
5185 }
5186
5187 cx.emit(EditorEvent::InputHandled {
5188 utf16_range_to_replace: None,
5189 text: completion.text.to_string().into(),
5190 });
5191
5192 if let Some(range) = completion.delete_range {
5193 self.change_selections(None, cx, |s| s.select_ranges([range]))
5194 }
5195 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5196 self.refresh_inline_completion(true, true, cx);
5197 cx.notify();
5198 }
5199
5200 pub fn accept_partial_inline_completion(
5201 &mut self,
5202 _: &AcceptPartialInlineCompletion,
5203 cx: &mut ViewContext<Self>,
5204 ) {
5205 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5206 if let Some(completion) = self.take_active_inline_completion(cx) {
5207 let mut partial_completion = completion
5208 .text
5209 .chars()
5210 .by_ref()
5211 .take_while(|c| c.is_alphabetic())
5212 .collect::<String>();
5213 if partial_completion.is_empty() {
5214 partial_completion = completion
5215 .text
5216 .chars()
5217 .by_ref()
5218 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5219 .collect::<String>();
5220 }
5221
5222 cx.emit(EditorEvent::InputHandled {
5223 utf16_range_to_replace: None,
5224 text: partial_completion.clone().into(),
5225 });
5226
5227 if let Some(range) = completion.delete_range {
5228 self.change_selections(None, cx, |s| s.select_ranges([range]))
5229 }
5230 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5231
5232 self.refresh_inline_completion(true, true, cx);
5233 cx.notify();
5234 }
5235 }
5236 }
5237
5238 fn discard_inline_completion(
5239 &mut self,
5240 should_report_inline_completion_event: bool,
5241 cx: &mut ViewContext<Self>,
5242 ) -> bool {
5243 if let Some(provider) = self.inline_completion_provider() {
5244 provider.discard(should_report_inline_completion_event, cx);
5245 }
5246
5247 self.take_active_inline_completion(cx).is_some()
5248 }
5249
5250 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5251 if let Some(completion) = self.active_inline_completion.as_ref() {
5252 let buffer = self.buffer.read(cx).read(cx);
5253 completion.position.is_valid(&buffer)
5254 } else {
5255 false
5256 }
5257 }
5258
5259 fn take_active_inline_completion(
5260 &mut self,
5261 cx: &mut ViewContext<Self>,
5262 ) -> Option<CompletionState> {
5263 let completion = self.active_inline_completion.take()?;
5264 let render_inlay_ids = completion.render_inlay_ids.clone();
5265 self.display_map.update(cx, |map, cx| {
5266 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5267 });
5268 let buffer = self.buffer.read(cx).read(cx);
5269
5270 if completion.position.is_valid(&buffer) {
5271 Some(completion)
5272 } else {
5273 None
5274 }
5275 }
5276
5277 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5278 let selection = self.selections.newest_anchor();
5279 let cursor = selection.head();
5280
5281 let excerpt_id = cursor.excerpt_id;
5282
5283 if self.context_menu.read().is_none()
5284 && self.completion_tasks.is_empty()
5285 && selection.start == selection.end
5286 {
5287 if let Some(provider) = self.inline_completion_provider() {
5288 if let Some((buffer, cursor_buffer_position)) =
5289 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5290 {
5291 if let Some(proposal) =
5292 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5293 {
5294 let mut to_remove = Vec::new();
5295 if let Some(completion) = self.active_inline_completion.take() {
5296 to_remove.extend(completion.render_inlay_ids.iter());
5297 }
5298
5299 let to_add = proposal
5300 .inlays
5301 .iter()
5302 .filter_map(|inlay| {
5303 let snapshot = self.buffer.read(cx).snapshot(cx);
5304 let id = post_inc(&mut self.next_inlay_id);
5305 match inlay {
5306 InlayProposal::Hint(position, hint) => {
5307 let position =
5308 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5309 Some(Inlay::hint(id, position, hint))
5310 }
5311 InlayProposal::Suggestion(position, text) => {
5312 let position =
5313 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5314 Some(Inlay::suggestion(id, position, text.clone()))
5315 }
5316 }
5317 })
5318 .collect_vec();
5319
5320 self.active_inline_completion = Some(CompletionState {
5321 position: cursor,
5322 text: proposal.text,
5323 delete_range: proposal.delete_range.and_then(|range| {
5324 let snapshot = self.buffer.read(cx).snapshot(cx);
5325 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5326 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5327 Some(start?..end?)
5328 }),
5329 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5330 });
5331
5332 self.display_map
5333 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5334
5335 cx.notify();
5336 return;
5337 }
5338 }
5339 }
5340 }
5341
5342 self.discard_inline_completion(false, cx);
5343 }
5344
5345 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5346 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5347 }
5348
5349 fn render_code_actions_indicator(
5350 &self,
5351 _style: &EditorStyle,
5352 row: DisplayRow,
5353 is_active: bool,
5354 cx: &mut ViewContext<Self>,
5355 ) -> Option<IconButton> {
5356 if self.available_code_actions.is_some() {
5357 Some(
5358 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5359 .shape(ui::IconButtonShape::Square)
5360 .icon_size(IconSize::XSmall)
5361 .icon_color(Color::Muted)
5362 .selected(is_active)
5363 .on_click(cx.listener(move |editor, _e, cx| {
5364 editor.focus(cx);
5365 editor.toggle_code_actions(
5366 &ToggleCodeActions {
5367 deployed_from_indicator: Some(row),
5368 },
5369 cx,
5370 );
5371 })),
5372 )
5373 } else {
5374 None
5375 }
5376 }
5377
5378 fn clear_tasks(&mut self) {
5379 self.tasks.clear()
5380 }
5381
5382 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5383 if self.tasks.insert(key, value).is_some() {
5384 // This case should hopefully be rare, but just in case...
5385 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5386 }
5387 }
5388
5389 fn render_run_indicator(
5390 &self,
5391 _style: &EditorStyle,
5392 is_active: bool,
5393 row: DisplayRow,
5394 cx: &mut ViewContext<Self>,
5395 ) -> IconButton {
5396 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5397 .shape(ui::IconButtonShape::Square)
5398 .icon_size(IconSize::XSmall)
5399 .icon_color(Color::Muted)
5400 .selected(is_active)
5401 .on_click(cx.listener(move |editor, _e, cx| {
5402 editor.focus(cx);
5403 editor.toggle_code_actions(
5404 &ToggleCodeActions {
5405 deployed_from_indicator: Some(row),
5406 },
5407 cx,
5408 );
5409 }))
5410 }
5411
5412 pub fn context_menu_visible(&self) -> bool {
5413 self.context_menu
5414 .read()
5415 .as_ref()
5416 .map_or(false, |menu| menu.visible())
5417 }
5418
5419 fn render_context_menu(
5420 &self,
5421 cursor_position: DisplayPoint,
5422 style: &EditorStyle,
5423 max_height: Pixels,
5424 cx: &mut ViewContext<Editor>,
5425 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5426 self.context_menu.read().as_ref().map(|menu| {
5427 menu.render(
5428 cursor_position,
5429 style,
5430 max_height,
5431 self.workspace.as_ref().map(|(w, _)| w.clone()),
5432 cx,
5433 )
5434 })
5435 }
5436
5437 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5438 cx.notify();
5439 self.completion_tasks.clear();
5440 let context_menu = self.context_menu.write().take();
5441 if context_menu.is_some() {
5442 self.update_visible_inline_completion(cx);
5443 }
5444 context_menu
5445 }
5446
5447 pub fn insert_snippet(
5448 &mut self,
5449 insertion_ranges: &[Range<usize>],
5450 snippet: Snippet,
5451 cx: &mut ViewContext<Self>,
5452 ) -> Result<()> {
5453 struct Tabstop<T> {
5454 is_end_tabstop: bool,
5455 ranges: Vec<Range<T>>,
5456 }
5457
5458 let tabstops = self.buffer.update(cx, |buffer, cx| {
5459 let snippet_text: Arc<str> = snippet.text.clone().into();
5460 buffer.edit(
5461 insertion_ranges
5462 .iter()
5463 .cloned()
5464 .map(|range| (range, snippet_text.clone())),
5465 Some(AutoindentMode::EachLine),
5466 cx,
5467 );
5468
5469 let snapshot = &*buffer.read(cx);
5470 let snippet = &snippet;
5471 snippet
5472 .tabstops
5473 .iter()
5474 .map(|tabstop| {
5475 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5476 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5477 });
5478 let mut tabstop_ranges = tabstop
5479 .iter()
5480 .flat_map(|tabstop_range| {
5481 let mut delta = 0_isize;
5482 insertion_ranges.iter().map(move |insertion_range| {
5483 let insertion_start = insertion_range.start as isize + delta;
5484 delta +=
5485 snippet.text.len() as isize - insertion_range.len() as isize;
5486
5487 let start = ((insertion_start + tabstop_range.start) as usize)
5488 .min(snapshot.len());
5489 let end = ((insertion_start + tabstop_range.end) as usize)
5490 .min(snapshot.len());
5491 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5492 })
5493 })
5494 .collect::<Vec<_>>();
5495 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5496
5497 Tabstop {
5498 is_end_tabstop,
5499 ranges: tabstop_ranges,
5500 }
5501 })
5502 .collect::<Vec<_>>()
5503 });
5504 if let Some(tabstop) = tabstops.first() {
5505 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5506 s.select_ranges(tabstop.ranges.iter().cloned());
5507 });
5508
5509 // If we're already at the last tabstop and it's at the end of the snippet,
5510 // we're done, we don't need to keep the state around.
5511 if !tabstop.is_end_tabstop {
5512 let ranges = tabstops
5513 .into_iter()
5514 .map(|tabstop| tabstop.ranges)
5515 .collect::<Vec<_>>();
5516 self.snippet_stack.push(SnippetState {
5517 active_index: 0,
5518 ranges,
5519 });
5520 }
5521
5522 // Check whether the just-entered snippet ends with an auto-closable bracket.
5523 if self.autoclose_regions.is_empty() {
5524 let snapshot = self.buffer.read(cx).snapshot(cx);
5525 for selection in &mut self.selections.all::<Point>(cx) {
5526 let selection_head = selection.head();
5527 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5528 continue;
5529 };
5530
5531 let mut bracket_pair = None;
5532 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5533 let prev_chars = snapshot
5534 .reversed_chars_at(selection_head)
5535 .collect::<String>();
5536 for (pair, enabled) in scope.brackets() {
5537 if enabled
5538 && pair.close
5539 && prev_chars.starts_with(pair.start.as_str())
5540 && next_chars.starts_with(pair.end.as_str())
5541 {
5542 bracket_pair = Some(pair.clone());
5543 break;
5544 }
5545 }
5546 if let Some(pair) = bracket_pair {
5547 let start = snapshot.anchor_after(selection_head);
5548 let end = snapshot.anchor_after(selection_head);
5549 self.autoclose_regions.push(AutocloseRegion {
5550 selection_id: selection.id,
5551 range: start..end,
5552 pair,
5553 });
5554 }
5555 }
5556 }
5557 }
5558 Ok(())
5559 }
5560
5561 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5562 self.move_to_snippet_tabstop(Bias::Right, cx)
5563 }
5564
5565 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5566 self.move_to_snippet_tabstop(Bias::Left, cx)
5567 }
5568
5569 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5570 if let Some(mut snippet) = self.snippet_stack.pop() {
5571 match bias {
5572 Bias::Left => {
5573 if snippet.active_index > 0 {
5574 snippet.active_index -= 1;
5575 } else {
5576 self.snippet_stack.push(snippet);
5577 return false;
5578 }
5579 }
5580 Bias::Right => {
5581 if snippet.active_index + 1 < snippet.ranges.len() {
5582 snippet.active_index += 1;
5583 } else {
5584 self.snippet_stack.push(snippet);
5585 return false;
5586 }
5587 }
5588 }
5589 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5590 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5591 s.select_anchor_ranges(current_ranges.iter().cloned())
5592 });
5593 // If snippet state is not at the last tabstop, push it back on the stack
5594 if snippet.active_index + 1 < snippet.ranges.len() {
5595 self.snippet_stack.push(snippet);
5596 }
5597 return true;
5598 }
5599 }
5600
5601 false
5602 }
5603
5604 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5605 self.transact(cx, |this, cx| {
5606 this.select_all(&SelectAll, cx);
5607 this.insert("", cx);
5608 });
5609 }
5610
5611 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5612 self.transact(cx, |this, cx| {
5613 this.select_autoclose_pair(cx);
5614 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5615 if !this.linked_edit_ranges.is_empty() {
5616 let selections = this.selections.all::<MultiBufferPoint>(cx);
5617 let snapshot = this.buffer.read(cx).snapshot(cx);
5618
5619 for selection in selections.iter() {
5620 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5621 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5622 if selection_start.buffer_id != selection_end.buffer_id {
5623 continue;
5624 }
5625 if let Some(ranges) =
5626 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5627 {
5628 for (buffer, entries) in ranges {
5629 linked_ranges.entry(buffer).or_default().extend(entries);
5630 }
5631 }
5632 }
5633 }
5634
5635 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5636 if !this.selections.line_mode {
5637 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5638 for selection in &mut selections {
5639 if selection.is_empty() {
5640 let old_head = selection.head();
5641 let mut new_head =
5642 movement::left(&display_map, old_head.to_display_point(&display_map))
5643 .to_point(&display_map);
5644 if let Some((buffer, line_buffer_range)) = display_map
5645 .buffer_snapshot
5646 .buffer_line_for_row(MultiBufferRow(old_head.row))
5647 {
5648 let indent_size =
5649 buffer.indent_size_for_line(line_buffer_range.start.row);
5650 let indent_len = match indent_size.kind {
5651 IndentKind::Space => {
5652 buffer.settings_at(line_buffer_range.start, cx).tab_size
5653 }
5654 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5655 };
5656 if old_head.column <= indent_size.len && old_head.column > 0 {
5657 let indent_len = indent_len.get();
5658 new_head = cmp::min(
5659 new_head,
5660 MultiBufferPoint::new(
5661 old_head.row,
5662 ((old_head.column - 1) / indent_len) * indent_len,
5663 ),
5664 );
5665 }
5666 }
5667
5668 selection.set_head(new_head, SelectionGoal::None);
5669 }
5670 }
5671 }
5672
5673 this.signature_help_state.set_backspace_pressed(true);
5674 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5675 this.insert("", cx);
5676 let empty_str: Arc<str> = Arc::from("");
5677 for (buffer, edits) in linked_ranges {
5678 let snapshot = buffer.read(cx).snapshot();
5679 use text::ToPoint as TP;
5680
5681 let edits = edits
5682 .into_iter()
5683 .map(|range| {
5684 let end_point = TP::to_point(&range.end, &snapshot);
5685 let mut start_point = TP::to_point(&range.start, &snapshot);
5686
5687 if end_point == start_point {
5688 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5689 .saturating_sub(1);
5690 start_point = TP::to_point(&offset, &snapshot);
5691 };
5692
5693 (start_point..end_point, empty_str.clone())
5694 })
5695 .sorted_by_key(|(range, _)| range.start)
5696 .collect::<Vec<_>>();
5697 buffer.update(cx, |this, cx| {
5698 this.edit(edits, None, cx);
5699 })
5700 }
5701 this.refresh_inline_completion(true, false, cx);
5702 linked_editing_ranges::refresh_linked_ranges(this, cx);
5703 });
5704 }
5705
5706 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5707 self.transact(cx, |this, cx| {
5708 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5709 let line_mode = s.line_mode;
5710 s.move_with(|map, selection| {
5711 if selection.is_empty() && !line_mode {
5712 let cursor = movement::right(map, selection.head());
5713 selection.end = cursor;
5714 selection.reversed = true;
5715 selection.goal = SelectionGoal::None;
5716 }
5717 })
5718 });
5719 this.insert("", cx);
5720 this.refresh_inline_completion(true, false, cx);
5721 });
5722 }
5723
5724 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5725 if self.move_to_prev_snippet_tabstop(cx) {
5726 return;
5727 }
5728
5729 self.outdent(&Outdent, cx);
5730 }
5731
5732 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5733 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5734 return;
5735 }
5736
5737 let mut selections = self.selections.all_adjusted(cx);
5738 let buffer = self.buffer.read(cx);
5739 let snapshot = buffer.snapshot(cx);
5740 let rows_iter = selections.iter().map(|s| s.head().row);
5741 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5742
5743 let mut edits = Vec::new();
5744 let mut prev_edited_row = 0;
5745 let mut row_delta = 0;
5746 for selection in &mut selections {
5747 if selection.start.row != prev_edited_row {
5748 row_delta = 0;
5749 }
5750 prev_edited_row = selection.end.row;
5751
5752 // If the selection is non-empty, then increase the indentation of the selected lines.
5753 if !selection.is_empty() {
5754 row_delta =
5755 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5756 continue;
5757 }
5758
5759 // If the selection is empty and the cursor is in the leading whitespace before the
5760 // suggested indentation, then auto-indent the line.
5761 let cursor = selection.head();
5762 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5763 if let Some(suggested_indent) =
5764 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5765 {
5766 if cursor.column < suggested_indent.len
5767 && cursor.column <= current_indent.len
5768 && current_indent.len <= suggested_indent.len
5769 {
5770 selection.start = Point::new(cursor.row, suggested_indent.len);
5771 selection.end = selection.start;
5772 if row_delta == 0 {
5773 edits.extend(Buffer::edit_for_indent_size_adjustment(
5774 cursor.row,
5775 current_indent,
5776 suggested_indent,
5777 ));
5778 row_delta = suggested_indent.len - current_indent.len;
5779 }
5780 continue;
5781 }
5782 }
5783
5784 // Otherwise, insert a hard or soft tab.
5785 let settings = buffer.settings_at(cursor, cx);
5786 let tab_size = if settings.hard_tabs {
5787 IndentSize::tab()
5788 } else {
5789 let tab_size = settings.tab_size.get();
5790 let char_column = snapshot
5791 .text_for_range(Point::new(cursor.row, 0)..cursor)
5792 .flat_map(str::chars)
5793 .count()
5794 + row_delta as usize;
5795 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5796 IndentSize::spaces(chars_to_next_tab_stop)
5797 };
5798 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5799 selection.end = selection.start;
5800 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5801 row_delta += tab_size.len;
5802 }
5803
5804 self.transact(cx, |this, cx| {
5805 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5806 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5807 this.refresh_inline_completion(true, false, cx);
5808 });
5809 }
5810
5811 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5812 if self.read_only(cx) {
5813 return;
5814 }
5815 let mut selections = self.selections.all::<Point>(cx);
5816 let mut prev_edited_row = 0;
5817 let mut row_delta = 0;
5818 let mut edits = Vec::new();
5819 let buffer = self.buffer.read(cx);
5820 let snapshot = buffer.snapshot(cx);
5821 for selection in &mut selections {
5822 if selection.start.row != prev_edited_row {
5823 row_delta = 0;
5824 }
5825 prev_edited_row = selection.end.row;
5826
5827 row_delta =
5828 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5829 }
5830
5831 self.transact(cx, |this, cx| {
5832 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5833 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5834 });
5835 }
5836
5837 fn indent_selection(
5838 buffer: &MultiBuffer,
5839 snapshot: &MultiBufferSnapshot,
5840 selection: &mut Selection<Point>,
5841 edits: &mut Vec<(Range<Point>, String)>,
5842 delta_for_start_row: u32,
5843 cx: &AppContext,
5844 ) -> u32 {
5845 let settings = buffer.settings_at(selection.start, cx);
5846 let tab_size = settings.tab_size.get();
5847 let indent_kind = if settings.hard_tabs {
5848 IndentKind::Tab
5849 } else {
5850 IndentKind::Space
5851 };
5852 let mut start_row = selection.start.row;
5853 let mut end_row = selection.end.row + 1;
5854
5855 // If a selection ends at the beginning of a line, don't indent
5856 // that last line.
5857 if selection.end.column == 0 && selection.end.row > selection.start.row {
5858 end_row -= 1;
5859 }
5860
5861 // Avoid re-indenting a row that has already been indented by a
5862 // previous selection, but still update this selection's column
5863 // to reflect that indentation.
5864 if delta_for_start_row > 0 {
5865 start_row += 1;
5866 selection.start.column += delta_for_start_row;
5867 if selection.end.row == selection.start.row {
5868 selection.end.column += delta_for_start_row;
5869 }
5870 }
5871
5872 let mut delta_for_end_row = 0;
5873 let has_multiple_rows = start_row + 1 != end_row;
5874 for row in start_row..end_row {
5875 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5876 let indent_delta = match (current_indent.kind, indent_kind) {
5877 (IndentKind::Space, IndentKind::Space) => {
5878 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5879 IndentSize::spaces(columns_to_next_tab_stop)
5880 }
5881 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5882 (_, IndentKind::Tab) => IndentSize::tab(),
5883 };
5884
5885 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5886 0
5887 } else {
5888 selection.start.column
5889 };
5890 let row_start = Point::new(row, start);
5891 edits.push((
5892 row_start..row_start,
5893 indent_delta.chars().collect::<String>(),
5894 ));
5895
5896 // Update this selection's endpoints to reflect the indentation.
5897 if row == selection.start.row {
5898 selection.start.column += indent_delta.len;
5899 }
5900 if row == selection.end.row {
5901 selection.end.column += indent_delta.len;
5902 delta_for_end_row = indent_delta.len;
5903 }
5904 }
5905
5906 if selection.start.row == selection.end.row {
5907 delta_for_start_row + delta_for_end_row
5908 } else {
5909 delta_for_end_row
5910 }
5911 }
5912
5913 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5914 if self.read_only(cx) {
5915 return;
5916 }
5917 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5918 let selections = self.selections.all::<Point>(cx);
5919 let mut deletion_ranges = Vec::new();
5920 let mut last_outdent = None;
5921 {
5922 let buffer = self.buffer.read(cx);
5923 let snapshot = buffer.snapshot(cx);
5924 for selection in &selections {
5925 let settings = buffer.settings_at(selection.start, cx);
5926 let tab_size = settings.tab_size.get();
5927 let mut rows = selection.spanned_rows(false, &display_map);
5928
5929 // Avoid re-outdenting a row that has already been outdented by a
5930 // previous selection.
5931 if let Some(last_row) = last_outdent {
5932 if last_row == rows.start {
5933 rows.start = rows.start.next_row();
5934 }
5935 }
5936 let has_multiple_rows = rows.len() > 1;
5937 for row in rows.iter_rows() {
5938 let indent_size = snapshot.indent_size_for_line(row);
5939 if indent_size.len > 0 {
5940 let deletion_len = match indent_size.kind {
5941 IndentKind::Space => {
5942 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5943 if columns_to_prev_tab_stop == 0 {
5944 tab_size
5945 } else {
5946 columns_to_prev_tab_stop
5947 }
5948 }
5949 IndentKind::Tab => 1,
5950 };
5951 let start = if has_multiple_rows
5952 || deletion_len > selection.start.column
5953 || indent_size.len < selection.start.column
5954 {
5955 0
5956 } else {
5957 selection.start.column - deletion_len
5958 };
5959 deletion_ranges.push(
5960 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5961 );
5962 last_outdent = Some(row);
5963 }
5964 }
5965 }
5966 }
5967
5968 self.transact(cx, |this, cx| {
5969 this.buffer.update(cx, |buffer, cx| {
5970 let empty_str: Arc<str> = Arc::default();
5971 buffer.edit(
5972 deletion_ranges
5973 .into_iter()
5974 .map(|range| (range, empty_str.clone())),
5975 None,
5976 cx,
5977 );
5978 });
5979 let selections = this.selections.all::<usize>(cx);
5980 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5981 });
5982 }
5983
5984 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5986 let selections = self.selections.all::<Point>(cx);
5987
5988 let mut new_cursors = Vec::new();
5989 let mut edit_ranges = Vec::new();
5990 let mut selections = selections.iter().peekable();
5991 while let Some(selection) = selections.next() {
5992 let mut rows = selection.spanned_rows(false, &display_map);
5993 let goal_display_column = selection.head().to_display_point(&display_map).column();
5994
5995 // Accumulate contiguous regions of rows that we want to delete.
5996 while let Some(next_selection) = selections.peek() {
5997 let next_rows = next_selection.spanned_rows(false, &display_map);
5998 if next_rows.start <= rows.end {
5999 rows.end = next_rows.end;
6000 selections.next().unwrap();
6001 } else {
6002 break;
6003 }
6004 }
6005
6006 let buffer = &display_map.buffer_snapshot;
6007 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6008 let edit_end;
6009 let cursor_buffer_row;
6010 if buffer.max_point().row >= rows.end.0 {
6011 // If there's a line after the range, delete the \n from the end of the row range
6012 // and position the cursor on the next line.
6013 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6014 cursor_buffer_row = rows.end;
6015 } else {
6016 // If there isn't a line after the range, delete the \n from the line before the
6017 // start of the row range and position the cursor there.
6018 edit_start = edit_start.saturating_sub(1);
6019 edit_end = buffer.len();
6020 cursor_buffer_row = rows.start.previous_row();
6021 }
6022
6023 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6024 *cursor.column_mut() =
6025 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6026
6027 new_cursors.push((
6028 selection.id,
6029 buffer.anchor_after(cursor.to_point(&display_map)),
6030 ));
6031 edit_ranges.push(edit_start..edit_end);
6032 }
6033
6034 self.transact(cx, |this, cx| {
6035 let buffer = this.buffer.update(cx, |buffer, cx| {
6036 let empty_str: Arc<str> = Arc::default();
6037 buffer.edit(
6038 edit_ranges
6039 .into_iter()
6040 .map(|range| (range, empty_str.clone())),
6041 None,
6042 cx,
6043 );
6044 buffer.snapshot(cx)
6045 });
6046 let new_selections = new_cursors
6047 .into_iter()
6048 .map(|(id, cursor)| {
6049 let cursor = cursor.to_point(&buffer);
6050 Selection {
6051 id,
6052 start: cursor,
6053 end: cursor,
6054 reversed: false,
6055 goal: SelectionGoal::None,
6056 }
6057 })
6058 .collect();
6059
6060 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6061 s.select(new_selections);
6062 });
6063 });
6064 }
6065
6066 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6067 if self.read_only(cx) {
6068 return;
6069 }
6070 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6071 for selection in self.selections.all::<Point>(cx) {
6072 let start = MultiBufferRow(selection.start.row);
6073 let end = if selection.start.row == selection.end.row {
6074 MultiBufferRow(selection.start.row + 1)
6075 } else {
6076 MultiBufferRow(selection.end.row)
6077 };
6078
6079 if let Some(last_row_range) = row_ranges.last_mut() {
6080 if start <= last_row_range.end {
6081 last_row_range.end = end;
6082 continue;
6083 }
6084 }
6085 row_ranges.push(start..end);
6086 }
6087
6088 let snapshot = self.buffer.read(cx).snapshot(cx);
6089 let mut cursor_positions = Vec::new();
6090 for row_range in &row_ranges {
6091 let anchor = snapshot.anchor_before(Point::new(
6092 row_range.end.previous_row().0,
6093 snapshot.line_len(row_range.end.previous_row()),
6094 ));
6095 cursor_positions.push(anchor..anchor);
6096 }
6097
6098 self.transact(cx, |this, cx| {
6099 for row_range in row_ranges.into_iter().rev() {
6100 for row in row_range.iter_rows().rev() {
6101 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6102 let next_line_row = row.next_row();
6103 let indent = snapshot.indent_size_for_line(next_line_row);
6104 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6105
6106 let replace = if snapshot.line_len(next_line_row) > indent.len {
6107 " "
6108 } else {
6109 ""
6110 };
6111
6112 this.buffer.update(cx, |buffer, cx| {
6113 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6114 });
6115 }
6116 }
6117
6118 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6119 s.select_anchor_ranges(cursor_positions)
6120 });
6121 });
6122 }
6123
6124 pub fn sort_lines_case_sensitive(
6125 &mut self,
6126 _: &SortLinesCaseSensitive,
6127 cx: &mut ViewContext<Self>,
6128 ) {
6129 self.manipulate_lines(cx, |lines| lines.sort())
6130 }
6131
6132 pub fn sort_lines_case_insensitive(
6133 &mut self,
6134 _: &SortLinesCaseInsensitive,
6135 cx: &mut ViewContext<Self>,
6136 ) {
6137 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6138 }
6139
6140 pub fn unique_lines_case_insensitive(
6141 &mut self,
6142 _: &UniqueLinesCaseInsensitive,
6143 cx: &mut ViewContext<Self>,
6144 ) {
6145 self.manipulate_lines(cx, |lines| {
6146 let mut seen = HashSet::default();
6147 lines.retain(|line| seen.insert(line.to_lowercase()));
6148 })
6149 }
6150
6151 pub fn unique_lines_case_sensitive(
6152 &mut self,
6153 _: &UniqueLinesCaseSensitive,
6154 cx: &mut ViewContext<Self>,
6155 ) {
6156 self.manipulate_lines(cx, |lines| {
6157 let mut seen = HashSet::default();
6158 lines.retain(|line| seen.insert(*line));
6159 })
6160 }
6161
6162 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6163 let mut revert_changes = HashMap::default();
6164 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6165 for hunk in hunks_for_rows(
6166 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6167 &multi_buffer_snapshot,
6168 ) {
6169 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6170 }
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 revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6179 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6180 if !revert_changes.is_empty() {
6181 self.transact(cx, |editor, cx| {
6182 editor.revert(revert_changes, cx);
6183 });
6184 }
6185 }
6186
6187 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6188 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6189 let project_path = buffer.read(cx).project_path(cx)?;
6190 let project = self.project.as_ref()?.read(cx);
6191 let entry = project.entry_for_path(&project_path, cx)?;
6192 let abs_path = project.absolute_path(&project_path, cx)?;
6193 let parent = if entry.is_symlink {
6194 abs_path.canonicalize().ok()?
6195 } else {
6196 abs_path
6197 }
6198 .parent()?
6199 .to_path_buf();
6200 Some(parent)
6201 }) {
6202 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6203 }
6204 }
6205
6206 fn gather_revert_changes(
6207 &mut self,
6208 selections: &[Selection<Anchor>],
6209 cx: &mut ViewContext<'_, Editor>,
6210 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6211 let mut revert_changes = HashMap::default();
6212 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6213 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6214 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6215 }
6216 revert_changes
6217 }
6218
6219 pub fn prepare_revert_change(
6220 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6221 multi_buffer: &Model<MultiBuffer>,
6222 hunk: &MultiBufferDiffHunk,
6223 cx: &AppContext,
6224 ) -> Option<()> {
6225 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6226 let buffer = buffer.read(cx);
6227 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6228 let buffer_snapshot = buffer.snapshot();
6229 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6230 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6231 probe
6232 .0
6233 .start
6234 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6235 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6236 }) {
6237 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6238 Some(())
6239 } else {
6240 None
6241 }
6242 }
6243
6244 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6245 self.manipulate_lines(cx, |lines| lines.reverse())
6246 }
6247
6248 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6249 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6250 }
6251
6252 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6253 where
6254 Fn: FnMut(&mut Vec<&str>),
6255 {
6256 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6257 let buffer = self.buffer.read(cx).snapshot(cx);
6258
6259 let mut edits = Vec::new();
6260
6261 let selections = self.selections.all::<Point>(cx);
6262 let mut selections = selections.iter().peekable();
6263 let mut contiguous_row_selections = Vec::new();
6264 let mut new_selections = Vec::new();
6265 let mut added_lines = 0;
6266 let mut removed_lines = 0;
6267
6268 while let Some(selection) = selections.next() {
6269 let (start_row, end_row) = consume_contiguous_rows(
6270 &mut contiguous_row_selections,
6271 selection,
6272 &display_map,
6273 &mut selections,
6274 );
6275
6276 let start_point = Point::new(start_row.0, 0);
6277 let end_point = Point::new(
6278 end_row.previous_row().0,
6279 buffer.line_len(end_row.previous_row()),
6280 );
6281 let text = buffer
6282 .text_for_range(start_point..end_point)
6283 .collect::<String>();
6284
6285 let mut lines = text.split('\n').collect_vec();
6286
6287 let lines_before = lines.len();
6288 callback(&mut lines);
6289 let lines_after = lines.len();
6290
6291 edits.push((start_point..end_point, lines.join("\n")));
6292
6293 // Selections must change based on added and removed line count
6294 let start_row =
6295 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6296 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6297 new_selections.push(Selection {
6298 id: selection.id,
6299 start: start_row,
6300 end: end_row,
6301 goal: SelectionGoal::None,
6302 reversed: selection.reversed,
6303 });
6304
6305 if lines_after > lines_before {
6306 added_lines += lines_after - lines_before;
6307 } else if lines_before > lines_after {
6308 removed_lines += lines_before - lines_after;
6309 }
6310 }
6311
6312 self.transact(cx, |this, cx| {
6313 let buffer = this.buffer.update(cx, |buffer, cx| {
6314 buffer.edit(edits, None, cx);
6315 buffer.snapshot(cx)
6316 });
6317
6318 // Recalculate offsets on newly edited buffer
6319 let new_selections = new_selections
6320 .iter()
6321 .map(|s| {
6322 let start_point = Point::new(s.start.0, 0);
6323 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6324 Selection {
6325 id: s.id,
6326 start: buffer.point_to_offset(start_point),
6327 end: buffer.point_to_offset(end_point),
6328 goal: s.goal,
6329 reversed: s.reversed,
6330 }
6331 })
6332 .collect();
6333
6334 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6335 s.select(new_selections);
6336 });
6337
6338 this.request_autoscroll(Autoscroll::fit(), cx);
6339 });
6340 }
6341
6342 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6343 self.manipulate_text(cx, |text| text.to_uppercase())
6344 }
6345
6346 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6347 self.manipulate_text(cx, |text| text.to_lowercase())
6348 }
6349
6350 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6351 self.manipulate_text(cx, |text| {
6352 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6353 // https://github.com/rutrum/convert-case/issues/16
6354 text.split('\n')
6355 .map(|line| line.to_case(Case::Title))
6356 .join("\n")
6357 })
6358 }
6359
6360 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6361 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6362 }
6363
6364 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6365 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6366 }
6367
6368 pub fn convert_to_upper_camel_case(
6369 &mut self,
6370 _: &ConvertToUpperCamelCase,
6371 cx: &mut ViewContext<Self>,
6372 ) {
6373 self.manipulate_text(cx, |text| {
6374 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6375 // https://github.com/rutrum/convert-case/issues/16
6376 text.split('\n')
6377 .map(|line| line.to_case(Case::UpperCamel))
6378 .join("\n")
6379 })
6380 }
6381
6382 pub fn convert_to_lower_camel_case(
6383 &mut self,
6384 _: &ConvertToLowerCamelCase,
6385 cx: &mut ViewContext<Self>,
6386 ) {
6387 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6388 }
6389
6390 pub fn convert_to_opposite_case(
6391 &mut self,
6392 _: &ConvertToOppositeCase,
6393 cx: &mut ViewContext<Self>,
6394 ) {
6395 self.manipulate_text(cx, |text| {
6396 text.chars()
6397 .fold(String::with_capacity(text.len()), |mut t, c| {
6398 if c.is_uppercase() {
6399 t.extend(c.to_lowercase());
6400 } else {
6401 t.extend(c.to_uppercase());
6402 }
6403 t
6404 })
6405 })
6406 }
6407
6408 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6409 where
6410 Fn: FnMut(&str) -> String,
6411 {
6412 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6413 let buffer = self.buffer.read(cx).snapshot(cx);
6414
6415 let mut new_selections = Vec::new();
6416 let mut edits = Vec::new();
6417 let mut selection_adjustment = 0i32;
6418
6419 for selection in self.selections.all::<usize>(cx) {
6420 let selection_is_empty = selection.is_empty();
6421
6422 let (start, end) = if selection_is_empty {
6423 let word_range = movement::surrounding_word(
6424 &display_map,
6425 selection.start.to_display_point(&display_map),
6426 );
6427 let start = word_range.start.to_offset(&display_map, Bias::Left);
6428 let end = word_range.end.to_offset(&display_map, Bias::Left);
6429 (start, end)
6430 } else {
6431 (selection.start, selection.end)
6432 };
6433
6434 let text = buffer.text_for_range(start..end).collect::<String>();
6435 let old_length = text.len() as i32;
6436 let text = callback(&text);
6437
6438 new_selections.push(Selection {
6439 start: (start as i32 - selection_adjustment) as usize,
6440 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6441 goal: SelectionGoal::None,
6442 ..selection
6443 });
6444
6445 selection_adjustment += old_length - text.len() as i32;
6446
6447 edits.push((start..end, text));
6448 }
6449
6450 self.transact(cx, |this, cx| {
6451 this.buffer.update(cx, |buffer, cx| {
6452 buffer.edit(edits, None, cx);
6453 });
6454
6455 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6456 s.select(new_selections);
6457 });
6458
6459 this.request_autoscroll(Autoscroll::fit(), cx);
6460 });
6461 }
6462
6463 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6464 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6465 let buffer = &display_map.buffer_snapshot;
6466 let selections = self.selections.all::<Point>(cx);
6467
6468 let mut edits = Vec::new();
6469 let mut selections_iter = selections.iter().peekable();
6470 while let Some(selection) = selections_iter.next() {
6471 // Avoid duplicating the same lines twice.
6472 let mut rows = selection.spanned_rows(false, &display_map);
6473
6474 while let Some(next_selection) = selections_iter.peek() {
6475 let next_rows = next_selection.spanned_rows(false, &display_map);
6476 if next_rows.start < rows.end {
6477 rows.end = next_rows.end;
6478 selections_iter.next().unwrap();
6479 } else {
6480 break;
6481 }
6482 }
6483
6484 // Copy the text from the selected row region and splice it either at the start
6485 // or end of the region.
6486 let start = Point::new(rows.start.0, 0);
6487 let end = Point::new(
6488 rows.end.previous_row().0,
6489 buffer.line_len(rows.end.previous_row()),
6490 );
6491 let text = buffer
6492 .text_for_range(start..end)
6493 .chain(Some("\n"))
6494 .collect::<String>();
6495 let insert_location = if upwards {
6496 Point::new(rows.end.0, 0)
6497 } else {
6498 start
6499 };
6500 edits.push((insert_location..insert_location, text));
6501 }
6502
6503 self.transact(cx, |this, cx| {
6504 this.buffer.update(cx, |buffer, cx| {
6505 buffer.edit(edits, None, cx);
6506 });
6507
6508 this.request_autoscroll(Autoscroll::fit(), cx);
6509 });
6510 }
6511
6512 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6513 self.duplicate_line(true, cx);
6514 }
6515
6516 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6517 self.duplicate_line(false, cx);
6518 }
6519
6520 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6521 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6522 let buffer = self.buffer.read(cx).snapshot(cx);
6523
6524 let mut edits = Vec::new();
6525 let mut unfold_ranges = Vec::new();
6526 let mut refold_ranges = Vec::new();
6527
6528 let selections = self.selections.all::<Point>(cx);
6529 let mut selections = selections.iter().peekable();
6530 let mut contiguous_row_selections = Vec::new();
6531 let mut new_selections = Vec::new();
6532
6533 while let Some(selection) = selections.next() {
6534 // Find all the selections that span a contiguous row range
6535 let (start_row, end_row) = consume_contiguous_rows(
6536 &mut contiguous_row_selections,
6537 selection,
6538 &display_map,
6539 &mut selections,
6540 );
6541
6542 // Move the text spanned by the row range to be before the line preceding the row range
6543 if start_row.0 > 0 {
6544 let range_to_move = Point::new(
6545 start_row.previous_row().0,
6546 buffer.line_len(start_row.previous_row()),
6547 )
6548 ..Point::new(
6549 end_row.previous_row().0,
6550 buffer.line_len(end_row.previous_row()),
6551 );
6552 let insertion_point = display_map
6553 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6554 .0;
6555
6556 // Don't move lines across excerpts
6557 if buffer
6558 .excerpt_boundaries_in_range((
6559 Bound::Excluded(insertion_point),
6560 Bound::Included(range_to_move.end),
6561 ))
6562 .next()
6563 .is_none()
6564 {
6565 let text = buffer
6566 .text_for_range(range_to_move.clone())
6567 .flat_map(|s| s.chars())
6568 .skip(1)
6569 .chain(['\n'])
6570 .collect::<String>();
6571
6572 edits.push((
6573 buffer.anchor_after(range_to_move.start)
6574 ..buffer.anchor_before(range_to_move.end),
6575 String::new(),
6576 ));
6577 let insertion_anchor = buffer.anchor_after(insertion_point);
6578 edits.push((insertion_anchor..insertion_anchor, text));
6579
6580 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6581
6582 // Move selections up
6583 new_selections.extend(contiguous_row_selections.drain(..).map(
6584 |mut selection| {
6585 selection.start.row -= row_delta;
6586 selection.end.row -= row_delta;
6587 selection
6588 },
6589 ));
6590
6591 // Move folds up
6592 unfold_ranges.push(range_to_move.clone());
6593 for fold in display_map.folds_in_range(
6594 buffer.anchor_before(range_to_move.start)
6595 ..buffer.anchor_after(range_to_move.end),
6596 ) {
6597 let mut start = fold.range.start.to_point(&buffer);
6598 let mut end = fold.range.end.to_point(&buffer);
6599 start.row -= row_delta;
6600 end.row -= row_delta;
6601 refold_ranges.push((start..end, fold.placeholder.clone()));
6602 }
6603 }
6604 }
6605
6606 // If we didn't move line(s), preserve the existing selections
6607 new_selections.append(&mut contiguous_row_selections);
6608 }
6609
6610 self.transact(cx, |this, cx| {
6611 this.unfold_ranges(unfold_ranges, true, true, cx);
6612 this.buffer.update(cx, |buffer, cx| {
6613 for (range, text) in edits {
6614 buffer.edit([(range, text)], None, cx);
6615 }
6616 });
6617 this.fold_ranges(refold_ranges, true, cx);
6618 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6619 s.select(new_selections);
6620 })
6621 });
6622 }
6623
6624 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6625 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6626 let buffer = self.buffer.read(cx).snapshot(cx);
6627
6628 let mut edits = Vec::new();
6629 let mut unfold_ranges = Vec::new();
6630 let mut refold_ranges = Vec::new();
6631
6632 let selections = self.selections.all::<Point>(cx);
6633 let mut selections = selections.iter().peekable();
6634 let mut contiguous_row_selections = Vec::new();
6635 let mut new_selections = Vec::new();
6636
6637 while let Some(selection) = selections.next() {
6638 // Find all the selections that span a contiguous row range
6639 let (start_row, end_row) = consume_contiguous_rows(
6640 &mut contiguous_row_selections,
6641 selection,
6642 &display_map,
6643 &mut selections,
6644 );
6645
6646 // Move the text spanned by the row range to be after the last line of the row range
6647 if end_row.0 <= buffer.max_point().row {
6648 let range_to_move =
6649 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6650 let insertion_point = display_map
6651 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6652 .0;
6653
6654 // Don't move lines across excerpt boundaries
6655 if buffer
6656 .excerpt_boundaries_in_range((
6657 Bound::Excluded(range_to_move.start),
6658 Bound::Included(insertion_point),
6659 ))
6660 .next()
6661 .is_none()
6662 {
6663 let mut text = String::from("\n");
6664 text.extend(buffer.text_for_range(range_to_move.clone()));
6665 text.pop(); // Drop trailing newline
6666 edits.push((
6667 buffer.anchor_after(range_to_move.start)
6668 ..buffer.anchor_before(range_to_move.end),
6669 String::new(),
6670 ));
6671 let insertion_anchor = buffer.anchor_after(insertion_point);
6672 edits.push((insertion_anchor..insertion_anchor, text));
6673
6674 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6675
6676 // Move selections down
6677 new_selections.extend(contiguous_row_selections.drain(..).map(
6678 |mut selection| {
6679 selection.start.row += row_delta;
6680 selection.end.row += row_delta;
6681 selection
6682 },
6683 ));
6684
6685 // Move folds down
6686 unfold_ranges.push(range_to_move.clone());
6687 for fold in display_map.folds_in_range(
6688 buffer.anchor_before(range_to_move.start)
6689 ..buffer.anchor_after(range_to_move.end),
6690 ) {
6691 let mut start = fold.range.start.to_point(&buffer);
6692 let mut end = fold.range.end.to_point(&buffer);
6693 start.row += row_delta;
6694 end.row += row_delta;
6695 refold_ranges.push((start..end, fold.placeholder.clone()));
6696 }
6697 }
6698 }
6699
6700 // If we didn't move line(s), preserve the existing selections
6701 new_selections.append(&mut contiguous_row_selections);
6702 }
6703
6704 self.transact(cx, |this, cx| {
6705 this.unfold_ranges(unfold_ranges, true, true, cx);
6706 this.buffer.update(cx, |buffer, cx| {
6707 for (range, text) in edits {
6708 buffer.edit([(range, text)], None, cx);
6709 }
6710 });
6711 this.fold_ranges(refold_ranges, true, cx);
6712 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6713 });
6714 }
6715
6716 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6717 let text_layout_details = &self.text_layout_details(cx);
6718 self.transact(cx, |this, cx| {
6719 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6720 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6721 let line_mode = s.line_mode;
6722 s.move_with(|display_map, selection| {
6723 if !selection.is_empty() || line_mode {
6724 return;
6725 }
6726
6727 let mut head = selection.head();
6728 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6729 if head.column() == display_map.line_len(head.row()) {
6730 transpose_offset = display_map
6731 .buffer_snapshot
6732 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6733 }
6734
6735 if transpose_offset == 0 {
6736 return;
6737 }
6738
6739 *head.column_mut() += 1;
6740 head = display_map.clip_point(head, Bias::Right);
6741 let goal = SelectionGoal::HorizontalPosition(
6742 display_map
6743 .x_for_display_point(head, text_layout_details)
6744 .into(),
6745 );
6746 selection.collapse_to(head, goal);
6747
6748 let transpose_start = display_map
6749 .buffer_snapshot
6750 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6751 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6752 let transpose_end = display_map
6753 .buffer_snapshot
6754 .clip_offset(transpose_offset + 1, Bias::Right);
6755 if let Some(ch) =
6756 display_map.buffer_snapshot.chars_at(transpose_start).next()
6757 {
6758 edits.push((transpose_start..transpose_offset, String::new()));
6759 edits.push((transpose_end..transpose_end, ch.to_string()));
6760 }
6761 }
6762 });
6763 edits
6764 });
6765 this.buffer
6766 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6767 let selections = this.selections.all::<usize>(cx);
6768 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6769 s.select(selections);
6770 });
6771 });
6772 }
6773
6774 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6775 self.rewrap_impl(true, cx)
6776 }
6777
6778 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6779 let buffer = self.buffer.read(cx).snapshot(cx);
6780 let selections = self.selections.all::<Point>(cx);
6781 let mut selections = selections.iter().peekable();
6782
6783 let mut edits = Vec::new();
6784 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6785
6786 while let Some(selection) = selections.next() {
6787 let mut start_row = selection.start.row;
6788 let mut end_row = selection.end.row;
6789
6790 // Skip selections that overlap with a range that has already been rewrapped.
6791 let selection_range = start_row..end_row;
6792 if rewrapped_row_ranges
6793 .iter()
6794 .any(|range| range.overlaps(&selection_range))
6795 {
6796 continue;
6797 }
6798
6799 let mut should_rewrap = !only_text;
6800
6801 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6802 match language_scope.language_name().0.as_ref() {
6803 "Markdown" | "Plain Text" => {
6804 should_rewrap = true;
6805 }
6806 _ => {}
6807 }
6808 }
6809
6810 // Since not all lines in the selection may be at the same indent
6811 // level, choose the indent size that is the most common between all
6812 // of the lines.
6813 //
6814 // If there is a tie, we use the deepest indent.
6815 let (indent_size, indent_end) = {
6816 let mut indent_size_occurrences = HashMap::default();
6817 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6818
6819 for row in start_row..=end_row {
6820 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6821 rows_by_indent_size.entry(indent).or_default().push(row);
6822 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6823 }
6824
6825 let indent_size = indent_size_occurrences
6826 .into_iter()
6827 .max_by_key(|(indent, count)| (*count, indent.len))
6828 .map(|(indent, _)| indent)
6829 .unwrap_or_default();
6830 let row = rows_by_indent_size[&indent_size][0];
6831 let indent_end = Point::new(row, indent_size.len);
6832
6833 (indent_size, indent_end)
6834 };
6835
6836 let mut line_prefix = indent_size.chars().collect::<String>();
6837
6838 if let Some(comment_prefix) =
6839 buffer
6840 .language_scope_at(selection.head())
6841 .and_then(|language| {
6842 language
6843 .line_comment_prefixes()
6844 .iter()
6845 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6846 .cloned()
6847 })
6848 {
6849 line_prefix.push_str(&comment_prefix);
6850 should_rewrap = true;
6851 }
6852
6853 if selection.is_empty() {
6854 'expand_upwards: while start_row > 0 {
6855 let prev_row = start_row - 1;
6856 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6857 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6858 {
6859 start_row = prev_row;
6860 } else {
6861 break 'expand_upwards;
6862 }
6863 }
6864
6865 'expand_downwards: while end_row < buffer.max_point().row {
6866 let next_row = end_row + 1;
6867 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6868 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6869 {
6870 end_row = next_row;
6871 } else {
6872 break 'expand_downwards;
6873 }
6874 }
6875 }
6876
6877 if !should_rewrap {
6878 continue;
6879 }
6880
6881 let start = Point::new(start_row, 0);
6882 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6883 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6884 let Some(lines_without_prefixes) = selection_text
6885 .lines()
6886 .map(|line| {
6887 line.strip_prefix(&line_prefix)
6888 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6889 .ok_or_else(|| {
6890 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6891 })
6892 })
6893 .collect::<Result<Vec<_>, _>>()
6894 .log_err()
6895 else {
6896 continue;
6897 };
6898
6899 let unwrapped_text = lines_without_prefixes.join(" ");
6900 let wrap_column = buffer
6901 .settings_at(Point::new(start_row, 0), cx)
6902 .preferred_line_length as usize;
6903 let mut wrapped_text = String::new();
6904 let mut current_line = line_prefix.clone();
6905 for word in unwrapped_text.split_whitespace() {
6906 if current_line.len() + word.len() >= wrap_column {
6907 wrapped_text.push_str(¤t_line);
6908 wrapped_text.push('\n');
6909 current_line.truncate(line_prefix.len());
6910 }
6911
6912 if current_line.len() > line_prefix.len() {
6913 current_line.push(' ');
6914 }
6915
6916 current_line.push_str(word);
6917 }
6918
6919 if !current_line.is_empty() {
6920 wrapped_text.push_str(¤t_line);
6921 }
6922
6923 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6924 let mut offset = start.to_offset(&buffer);
6925 let mut moved_since_edit = true;
6926
6927 for change in diff.iter_all_changes() {
6928 let value = change.value();
6929 match change.tag() {
6930 ChangeTag::Equal => {
6931 offset += value.len();
6932 moved_since_edit = true;
6933 }
6934 ChangeTag::Delete => {
6935 let start = buffer.anchor_after(offset);
6936 let end = buffer.anchor_before(offset + value.len());
6937
6938 if moved_since_edit {
6939 edits.push((start..end, String::new()));
6940 } else {
6941 edits.last_mut().unwrap().0.end = end;
6942 }
6943
6944 offset += value.len();
6945 moved_since_edit = false;
6946 }
6947 ChangeTag::Insert => {
6948 if moved_since_edit {
6949 let anchor = buffer.anchor_after(offset);
6950 edits.push((anchor..anchor, value.to_string()));
6951 } else {
6952 edits.last_mut().unwrap().1.push_str(value);
6953 }
6954
6955 moved_since_edit = false;
6956 }
6957 }
6958 }
6959
6960 rewrapped_row_ranges.push(start_row..=end_row);
6961 }
6962
6963 self.buffer
6964 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6965 }
6966
6967 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6968 let mut text = String::new();
6969 let buffer = self.buffer.read(cx).snapshot(cx);
6970 let mut selections = self.selections.all::<Point>(cx);
6971 let mut clipboard_selections = Vec::with_capacity(selections.len());
6972 {
6973 let max_point = buffer.max_point();
6974 let mut is_first = true;
6975 for selection in &mut selections {
6976 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6977 if is_entire_line {
6978 selection.start = Point::new(selection.start.row, 0);
6979 if !selection.is_empty() && selection.end.column == 0 {
6980 selection.end = cmp::min(max_point, selection.end);
6981 } else {
6982 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6983 }
6984 selection.goal = SelectionGoal::None;
6985 }
6986 if is_first {
6987 is_first = false;
6988 } else {
6989 text += "\n";
6990 }
6991 let mut len = 0;
6992 for chunk in buffer.text_for_range(selection.start..selection.end) {
6993 text.push_str(chunk);
6994 len += chunk.len();
6995 }
6996 clipboard_selections.push(ClipboardSelection {
6997 len,
6998 is_entire_line,
6999 first_line_indent: buffer
7000 .indent_size_for_line(MultiBufferRow(selection.start.row))
7001 .len,
7002 });
7003 }
7004 }
7005
7006 self.transact(cx, |this, cx| {
7007 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7008 s.select(selections);
7009 });
7010 this.insert("", cx);
7011 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7012 text,
7013 clipboard_selections,
7014 ));
7015 });
7016 }
7017
7018 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7019 let selections = self.selections.all::<Point>(cx);
7020 let buffer = self.buffer.read(cx).read(cx);
7021 let mut text = String::new();
7022
7023 let mut clipboard_selections = Vec::with_capacity(selections.len());
7024 {
7025 let max_point = buffer.max_point();
7026 let mut is_first = true;
7027 for selection in selections.iter() {
7028 let mut start = selection.start;
7029 let mut end = selection.end;
7030 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7031 if is_entire_line {
7032 start = Point::new(start.row, 0);
7033 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7034 }
7035 if is_first {
7036 is_first = false;
7037 } else {
7038 text += "\n";
7039 }
7040 let mut len = 0;
7041 for chunk in buffer.text_for_range(start..end) {
7042 text.push_str(chunk);
7043 len += chunk.len();
7044 }
7045 clipboard_selections.push(ClipboardSelection {
7046 len,
7047 is_entire_line,
7048 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7049 });
7050 }
7051 }
7052
7053 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7054 text,
7055 clipboard_selections,
7056 ));
7057 }
7058
7059 pub fn do_paste(
7060 &mut self,
7061 text: &String,
7062 clipboard_selections: Option<Vec<ClipboardSelection>>,
7063 handle_entire_lines: bool,
7064 cx: &mut ViewContext<Self>,
7065 ) {
7066 if self.read_only(cx) {
7067 return;
7068 }
7069
7070 let clipboard_text = Cow::Borrowed(text);
7071
7072 self.transact(cx, |this, cx| {
7073 if let Some(mut clipboard_selections) = clipboard_selections {
7074 let old_selections = this.selections.all::<usize>(cx);
7075 let all_selections_were_entire_line =
7076 clipboard_selections.iter().all(|s| s.is_entire_line);
7077 let first_selection_indent_column =
7078 clipboard_selections.first().map(|s| s.first_line_indent);
7079 if clipboard_selections.len() != old_selections.len() {
7080 clipboard_selections.drain(..);
7081 }
7082
7083 this.buffer.update(cx, |buffer, cx| {
7084 let snapshot = buffer.read(cx);
7085 let mut start_offset = 0;
7086 let mut edits = Vec::new();
7087 let mut original_indent_columns = Vec::new();
7088 for (ix, selection) in old_selections.iter().enumerate() {
7089 let to_insert;
7090 let entire_line;
7091 let original_indent_column;
7092 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7093 let end_offset = start_offset + clipboard_selection.len;
7094 to_insert = &clipboard_text[start_offset..end_offset];
7095 entire_line = clipboard_selection.is_entire_line;
7096 start_offset = end_offset + 1;
7097 original_indent_column = Some(clipboard_selection.first_line_indent);
7098 } else {
7099 to_insert = clipboard_text.as_str();
7100 entire_line = all_selections_were_entire_line;
7101 original_indent_column = first_selection_indent_column
7102 }
7103
7104 // If the corresponding selection was empty when this slice of the
7105 // clipboard text was written, then the entire line containing the
7106 // selection was copied. If this selection is also currently empty,
7107 // then paste the line before the current line of the buffer.
7108 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7109 let column = selection.start.to_point(&snapshot).column as usize;
7110 let line_start = selection.start - column;
7111 line_start..line_start
7112 } else {
7113 selection.range()
7114 };
7115
7116 edits.push((range, to_insert));
7117 original_indent_columns.extend(original_indent_column);
7118 }
7119 drop(snapshot);
7120
7121 buffer.edit(
7122 edits,
7123 Some(AutoindentMode::Block {
7124 original_indent_columns,
7125 }),
7126 cx,
7127 );
7128 });
7129
7130 let selections = this.selections.all::<usize>(cx);
7131 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7132 } else {
7133 this.insert(&clipboard_text, cx);
7134 }
7135 });
7136 }
7137
7138 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7139 if let Some(item) = cx.read_from_clipboard() {
7140 let entries = item.entries();
7141
7142 match entries.first() {
7143 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7144 // of all the pasted entries.
7145 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7146 .do_paste(
7147 clipboard_string.text(),
7148 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7149 true,
7150 cx,
7151 ),
7152 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7153 }
7154 }
7155 }
7156
7157 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7158 if self.read_only(cx) {
7159 return;
7160 }
7161
7162 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7163 if let Some((selections, _)) =
7164 self.selection_history.transaction(transaction_id).cloned()
7165 {
7166 self.change_selections(None, cx, |s| {
7167 s.select_anchors(selections.to_vec());
7168 });
7169 }
7170 self.request_autoscroll(Autoscroll::fit(), cx);
7171 self.unmark_text(cx);
7172 self.refresh_inline_completion(true, false, cx);
7173 cx.emit(EditorEvent::Edited { transaction_id });
7174 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7175 }
7176 }
7177
7178 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7179 if self.read_only(cx) {
7180 return;
7181 }
7182
7183 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7184 if let Some((_, Some(selections))) =
7185 self.selection_history.transaction(transaction_id).cloned()
7186 {
7187 self.change_selections(None, cx, |s| {
7188 s.select_anchors(selections.to_vec());
7189 });
7190 }
7191 self.request_autoscroll(Autoscroll::fit(), cx);
7192 self.unmark_text(cx);
7193 self.refresh_inline_completion(true, false, cx);
7194 cx.emit(EditorEvent::Edited { transaction_id });
7195 }
7196 }
7197
7198 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7199 self.buffer
7200 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7201 }
7202
7203 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7204 self.buffer
7205 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7206 }
7207
7208 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7209 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7210 let line_mode = s.line_mode;
7211 s.move_with(|map, selection| {
7212 let cursor = if selection.is_empty() && !line_mode {
7213 movement::left(map, selection.start)
7214 } else {
7215 selection.start
7216 };
7217 selection.collapse_to(cursor, SelectionGoal::None);
7218 });
7219 })
7220 }
7221
7222 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7223 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7224 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7225 })
7226 }
7227
7228 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7229 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7230 let line_mode = s.line_mode;
7231 s.move_with(|map, selection| {
7232 let cursor = if selection.is_empty() && !line_mode {
7233 movement::right(map, selection.end)
7234 } else {
7235 selection.end
7236 };
7237 selection.collapse_to(cursor, SelectionGoal::None)
7238 });
7239 })
7240 }
7241
7242 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7243 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7244 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7245 })
7246 }
7247
7248 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7249 if self.take_rename(true, cx).is_some() {
7250 return;
7251 }
7252
7253 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7254 cx.propagate();
7255 return;
7256 }
7257
7258 let text_layout_details = &self.text_layout_details(cx);
7259 let selection_count = self.selections.count();
7260 let first_selection = self.selections.first_anchor();
7261
7262 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7263 let line_mode = s.line_mode;
7264 s.move_with(|map, selection| {
7265 if !selection.is_empty() && !line_mode {
7266 selection.goal = SelectionGoal::None;
7267 }
7268 let (cursor, goal) = movement::up(
7269 map,
7270 selection.start,
7271 selection.goal,
7272 false,
7273 text_layout_details,
7274 );
7275 selection.collapse_to(cursor, goal);
7276 });
7277 });
7278
7279 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7280 {
7281 cx.propagate();
7282 }
7283 }
7284
7285 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7286 if self.take_rename(true, cx).is_some() {
7287 return;
7288 }
7289
7290 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7291 cx.propagate();
7292 return;
7293 }
7294
7295 let text_layout_details = &self.text_layout_details(cx);
7296
7297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7298 let line_mode = s.line_mode;
7299 s.move_with(|map, selection| {
7300 if !selection.is_empty() && !line_mode {
7301 selection.goal = SelectionGoal::None;
7302 }
7303 let (cursor, goal) = movement::up_by_rows(
7304 map,
7305 selection.start,
7306 action.lines,
7307 selection.goal,
7308 false,
7309 text_layout_details,
7310 );
7311 selection.collapse_to(cursor, goal);
7312 });
7313 })
7314 }
7315
7316 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7317 if self.take_rename(true, cx).is_some() {
7318 return;
7319 }
7320
7321 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7322 cx.propagate();
7323 return;
7324 }
7325
7326 let text_layout_details = &self.text_layout_details(cx);
7327
7328 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7329 let line_mode = s.line_mode;
7330 s.move_with(|map, selection| {
7331 if !selection.is_empty() && !line_mode {
7332 selection.goal = SelectionGoal::None;
7333 }
7334 let (cursor, goal) = movement::down_by_rows(
7335 map,
7336 selection.start,
7337 action.lines,
7338 selection.goal,
7339 false,
7340 text_layout_details,
7341 );
7342 selection.collapse_to(cursor, goal);
7343 });
7344 })
7345 }
7346
7347 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, 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::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7352 })
7353 })
7354 }
7355
7356 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7357 let text_layout_details = &self.text_layout_details(cx);
7358 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7359 s.move_heads_with(|map, head, goal| {
7360 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7361 })
7362 })
7363 }
7364
7365 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7366 let Some(row_count) = self.visible_row_count() else {
7367 return;
7368 };
7369
7370 let text_layout_details = &self.text_layout_details(cx);
7371
7372 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7373 s.move_heads_with(|map, head, goal| {
7374 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7375 })
7376 })
7377 }
7378
7379 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7380 if self.take_rename(true, cx).is_some() {
7381 return;
7382 }
7383
7384 if self
7385 .context_menu
7386 .write()
7387 .as_mut()
7388 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7389 .unwrap_or(false)
7390 {
7391 return;
7392 }
7393
7394 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7395 cx.propagate();
7396 return;
7397 }
7398
7399 let Some(row_count) = self.visible_row_count() else {
7400 return;
7401 };
7402
7403 let autoscroll = if action.center_cursor {
7404 Autoscroll::center()
7405 } else {
7406 Autoscroll::fit()
7407 };
7408
7409 let text_layout_details = &self.text_layout_details(cx);
7410
7411 self.change_selections(Some(autoscroll), cx, |s| {
7412 let line_mode = s.line_mode;
7413 s.move_with(|map, selection| {
7414 if !selection.is_empty() && !line_mode {
7415 selection.goal = SelectionGoal::None;
7416 }
7417 let (cursor, goal) = movement::up_by_rows(
7418 map,
7419 selection.end,
7420 row_count,
7421 selection.goal,
7422 false,
7423 text_layout_details,
7424 );
7425 selection.collapse_to(cursor, goal);
7426 });
7427 });
7428 }
7429
7430 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7431 let text_layout_details = &self.text_layout_details(cx);
7432 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7433 s.move_heads_with(|map, head, goal| {
7434 movement::up(map, head, goal, false, text_layout_details)
7435 })
7436 })
7437 }
7438
7439 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7440 self.take_rename(true, cx);
7441
7442 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7443 cx.propagate();
7444 return;
7445 }
7446
7447 let text_layout_details = &self.text_layout_details(cx);
7448 let selection_count = self.selections.count();
7449 let first_selection = self.selections.first_anchor();
7450
7451 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7452 let line_mode = s.line_mode;
7453 s.move_with(|map, selection| {
7454 if !selection.is_empty() && !line_mode {
7455 selection.goal = SelectionGoal::None;
7456 }
7457 let (cursor, goal) = movement::down(
7458 map,
7459 selection.end,
7460 selection.goal,
7461 false,
7462 text_layout_details,
7463 );
7464 selection.collapse_to(cursor, goal);
7465 });
7466 });
7467
7468 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7469 {
7470 cx.propagate();
7471 }
7472 }
7473
7474 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7475 let Some(row_count) = self.visible_row_count() else {
7476 return;
7477 };
7478
7479 let text_layout_details = &self.text_layout_details(cx);
7480
7481 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7482 s.move_heads_with(|map, head, goal| {
7483 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7484 })
7485 })
7486 }
7487
7488 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7489 if self.take_rename(true, cx).is_some() {
7490 return;
7491 }
7492
7493 if self
7494 .context_menu
7495 .write()
7496 .as_mut()
7497 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7498 .unwrap_or(false)
7499 {
7500 return;
7501 }
7502
7503 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7504 cx.propagate();
7505 return;
7506 }
7507
7508 let Some(row_count) = self.visible_row_count() else {
7509 return;
7510 };
7511
7512 let autoscroll = if action.center_cursor {
7513 Autoscroll::center()
7514 } else {
7515 Autoscroll::fit()
7516 };
7517
7518 let text_layout_details = &self.text_layout_details(cx);
7519 self.change_selections(Some(autoscroll), cx, |s| {
7520 let line_mode = s.line_mode;
7521 s.move_with(|map, selection| {
7522 if !selection.is_empty() && !line_mode {
7523 selection.goal = SelectionGoal::None;
7524 }
7525 let (cursor, goal) = movement::down_by_rows(
7526 map,
7527 selection.end,
7528 row_count,
7529 selection.goal,
7530 false,
7531 text_layout_details,
7532 );
7533 selection.collapse_to(cursor, goal);
7534 });
7535 });
7536 }
7537
7538 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7539 let text_layout_details = &self.text_layout_details(cx);
7540 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7541 s.move_heads_with(|map, head, goal| {
7542 movement::down(map, head, goal, false, text_layout_details)
7543 })
7544 });
7545 }
7546
7547 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7548 if let Some(context_menu) = self.context_menu.write().as_mut() {
7549 context_menu.select_first(self.project.as_ref(), cx);
7550 }
7551 }
7552
7553 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7554 if let Some(context_menu) = self.context_menu.write().as_mut() {
7555 context_menu.select_prev(self.project.as_ref(), cx);
7556 }
7557 }
7558
7559 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7560 if let Some(context_menu) = self.context_menu.write().as_mut() {
7561 context_menu.select_next(self.project.as_ref(), cx);
7562 }
7563 }
7564
7565 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7566 if let Some(context_menu) = self.context_menu.write().as_mut() {
7567 context_menu.select_last(self.project.as_ref(), cx);
7568 }
7569 }
7570
7571 pub fn move_to_previous_word_start(
7572 &mut self,
7573 _: &MoveToPreviousWordStart,
7574 cx: &mut ViewContext<Self>,
7575 ) {
7576 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7577 s.move_cursors_with(|map, head, _| {
7578 (
7579 movement::previous_word_start(map, head),
7580 SelectionGoal::None,
7581 )
7582 });
7583 })
7584 }
7585
7586 pub fn move_to_previous_subword_start(
7587 &mut self,
7588 _: &MoveToPreviousSubwordStart,
7589 cx: &mut ViewContext<Self>,
7590 ) {
7591 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7592 s.move_cursors_with(|map, head, _| {
7593 (
7594 movement::previous_subword_start(map, head),
7595 SelectionGoal::None,
7596 )
7597 });
7598 })
7599 }
7600
7601 pub fn select_to_previous_word_start(
7602 &mut self,
7603 _: &SelectToPreviousWordStart,
7604 cx: &mut ViewContext<Self>,
7605 ) {
7606 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7607 s.move_heads_with(|map, head, _| {
7608 (
7609 movement::previous_word_start(map, head),
7610 SelectionGoal::None,
7611 )
7612 });
7613 })
7614 }
7615
7616 pub fn select_to_previous_subword_start(
7617 &mut self,
7618 _: &SelectToPreviousSubwordStart,
7619 cx: &mut ViewContext<Self>,
7620 ) {
7621 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7622 s.move_heads_with(|map, head, _| {
7623 (
7624 movement::previous_subword_start(map, head),
7625 SelectionGoal::None,
7626 )
7627 });
7628 })
7629 }
7630
7631 pub fn delete_to_previous_word_start(
7632 &mut self,
7633 action: &DeleteToPreviousWordStart,
7634 cx: &mut ViewContext<Self>,
7635 ) {
7636 self.transact(cx, |this, cx| {
7637 this.select_autoclose_pair(cx);
7638 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7639 let line_mode = s.line_mode;
7640 s.move_with(|map, selection| {
7641 if selection.is_empty() && !line_mode {
7642 let cursor = if action.ignore_newlines {
7643 movement::previous_word_start(map, selection.head())
7644 } else {
7645 movement::previous_word_start_or_newline(map, selection.head())
7646 };
7647 selection.set_head(cursor, SelectionGoal::None);
7648 }
7649 });
7650 });
7651 this.insert("", cx);
7652 });
7653 }
7654
7655 pub fn delete_to_previous_subword_start(
7656 &mut self,
7657 _: &DeleteToPreviousSubwordStart,
7658 cx: &mut ViewContext<Self>,
7659 ) {
7660 self.transact(cx, |this, cx| {
7661 this.select_autoclose_pair(cx);
7662 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 let line_mode = s.line_mode;
7664 s.move_with(|map, selection| {
7665 if selection.is_empty() && !line_mode {
7666 let cursor = movement::previous_subword_start(map, selection.head());
7667 selection.set_head(cursor, SelectionGoal::None);
7668 }
7669 });
7670 });
7671 this.insert("", cx);
7672 });
7673 }
7674
7675 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7676 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7677 s.move_cursors_with(|map, head, _| {
7678 (movement::next_word_end(map, head), SelectionGoal::None)
7679 });
7680 })
7681 }
7682
7683 pub fn move_to_next_subword_end(
7684 &mut self,
7685 _: &MoveToNextSubwordEnd,
7686 cx: &mut ViewContext<Self>,
7687 ) {
7688 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7689 s.move_cursors_with(|map, head, _| {
7690 (movement::next_subword_end(map, head), SelectionGoal::None)
7691 });
7692 })
7693 }
7694
7695 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7696 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7697 s.move_heads_with(|map, head, _| {
7698 (movement::next_word_end(map, head), SelectionGoal::None)
7699 });
7700 })
7701 }
7702
7703 pub fn select_to_next_subword_end(
7704 &mut self,
7705 _: &SelectToNextSubwordEnd,
7706 cx: &mut ViewContext<Self>,
7707 ) {
7708 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7709 s.move_heads_with(|map, head, _| {
7710 (movement::next_subword_end(map, head), SelectionGoal::None)
7711 });
7712 })
7713 }
7714
7715 pub fn delete_to_next_word_end(
7716 &mut self,
7717 action: &DeleteToNextWordEnd,
7718 cx: &mut ViewContext<Self>,
7719 ) {
7720 self.transact(cx, |this, cx| {
7721 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7722 let line_mode = s.line_mode;
7723 s.move_with(|map, selection| {
7724 if selection.is_empty() && !line_mode {
7725 let cursor = if action.ignore_newlines {
7726 movement::next_word_end(map, selection.head())
7727 } else {
7728 movement::next_word_end_or_newline(map, selection.head())
7729 };
7730 selection.set_head(cursor, SelectionGoal::None);
7731 }
7732 });
7733 });
7734 this.insert("", cx);
7735 });
7736 }
7737
7738 pub fn delete_to_next_subword_end(
7739 &mut self,
7740 _: &DeleteToNextSubwordEnd,
7741 cx: &mut ViewContext<Self>,
7742 ) {
7743 self.transact(cx, |this, cx| {
7744 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7745 s.move_with(|map, selection| {
7746 if selection.is_empty() {
7747 let cursor = movement::next_subword_end(map, selection.head());
7748 selection.set_head(cursor, SelectionGoal::None);
7749 }
7750 });
7751 });
7752 this.insert("", cx);
7753 });
7754 }
7755
7756 pub fn move_to_beginning_of_line(
7757 &mut self,
7758 action: &MoveToBeginningOfLine,
7759 cx: &mut ViewContext<Self>,
7760 ) {
7761 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7762 s.move_cursors_with(|map, head, _| {
7763 (
7764 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7765 SelectionGoal::None,
7766 )
7767 });
7768 })
7769 }
7770
7771 pub fn select_to_beginning_of_line(
7772 &mut self,
7773 action: &SelectToBeginningOfLine,
7774 cx: &mut ViewContext<Self>,
7775 ) {
7776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7777 s.move_heads_with(|map, head, _| {
7778 (
7779 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7780 SelectionGoal::None,
7781 )
7782 });
7783 });
7784 }
7785
7786 pub fn delete_to_beginning_of_line(
7787 &mut self,
7788 _: &DeleteToBeginningOfLine,
7789 cx: &mut ViewContext<Self>,
7790 ) {
7791 self.transact(cx, |this, cx| {
7792 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7793 s.move_with(|_, selection| {
7794 selection.reversed = true;
7795 });
7796 });
7797
7798 this.select_to_beginning_of_line(
7799 &SelectToBeginningOfLine {
7800 stop_at_soft_wraps: false,
7801 },
7802 cx,
7803 );
7804 this.backspace(&Backspace, cx);
7805 });
7806 }
7807
7808 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7809 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7810 s.move_cursors_with(|map, head, _| {
7811 (
7812 movement::line_end(map, head, action.stop_at_soft_wraps),
7813 SelectionGoal::None,
7814 )
7815 });
7816 })
7817 }
7818
7819 pub fn select_to_end_of_line(
7820 &mut self,
7821 action: &SelectToEndOfLine,
7822 cx: &mut ViewContext<Self>,
7823 ) {
7824 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7825 s.move_heads_with(|map, head, _| {
7826 (
7827 movement::line_end(map, head, action.stop_at_soft_wraps),
7828 SelectionGoal::None,
7829 )
7830 });
7831 })
7832 }
7833
7834 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7835 self.transact(cx, |this, cx| {
7836 this.select_to_end_of_line(
7837 &SelectToEndOfLine {
7838 stop_at_soft_wraps: false,
7839 },
7840 cx,
7841 );
7842 this.delete(&Delete, cx);
7843 });
7844 }
7845
7846 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7847 self.transact(cx, |this, cx| {
7848 this.select_to_end_of_line(
7849 &SelectToEndOfLine {
7850 stop_at_soft_wraps: false,
7851 },
7852 cx,
7853 );
7854 this.cut(&Cut, cx);
7855 });
7856 }
7857
7858 pub fn move_to_start_of_paragraph(
7859 &mut self,
7860 _: &MoveToStartOfParagraph,
7861 cx: &mut ViewContext<Self>,
7862 ) {
7863 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7864 cx.propagate();
7865 return;
7866 }
7867
7868 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7869 s.move_with(|map, selection| {
7870 selection.collapse_to(
7871 movement::start_of_paragraph(map, selection.head(), 1),
7872 SelectionGoal::None,
7873 )
7874 });
7875 })
7876 }
7877
7878 pub fn move_to_end_of_paragraph(
7879 &mut self,
7880 _: &MoveToEndOfParagraph,
7881 cx: &mut ViewContext<Self>,
7882 ) {
7883 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7884 cx.propagate();
7885 return;
7886 }
7887
7888 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7889 s.move_with(|map, selection| {
7890 selection.collapse_to(
7891 movement::end_of_paragraph(map, selection.head(), 1),
7892 SelectionGoal::None,
7893 )
7894 });
7895 })
7896 }
7897
7898 pub fn select_to_start_of_paragraph(
7899 &mut self,
7900 _: &SelectToStartOfParagraph,
7901 cx: &mut ViewContext<Self>,
7902 ) {
7903 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7904 cx.propagate();
7905 return;
7906 }
7907
7908 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7909 s.move_heads_with(|map, head, _| {
7910 (
7911 movement::start_of_paragraph(map, head, 1),
7912 SelectionGoal::None,
7913 )
7914 });
7915 })
7916 }
7917
7918 pub fn select_to_end_of_paragraph(
7919 &mut self,
7920 _: &SelectToEndOfParagraph,
7921 cx: &mut ViewContext<Self>,
7922 ) {
7923 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7924 cx.propagate();
7925 return;
7926 }
7927
7928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7929 s.move_heads_with(|map, head, _| {
7930 (
7931 movement::end_of_paragraph(map, head, 1),
7932 SelectionGoal::None,
7933 )
7934 });
7935 })
7936 }
7937
7938 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7939 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7940 cx.propagate();
7941 return;
7942 }
7943
7944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7945 s.select_ranges(vec![0..0]);
7946 });
7947 }
7948
7949 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7950 let mut selection = self.selections.last::<Point>(cx);
7951 selection.set_head(Point::zero(), SelectionGoal::None);
7952
7953 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7954 s.select(vec![selection]);
7955 });
7956 }
7957
7958 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7959 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7960 cx.propagate();
7961 return;
7962 }
7963
7964 let cursor = self.buffer.read(cx).read(cx).len();
7965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7966 s.select_ranges(vec![cursor..cursor])
7967 });
7968 }
7969
7970 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7971 self.nav_history = nav_history;
7972 }
7973
7974 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7975 self.nav_history.as_ref()
7976 }
7977
7978 fn push_to_nav_history(
7979 &mut self,
7980 cursor_anchor: Anchor,
7981 new_position: Option<Point>,
7982 cx: &mut ViewContext<Self>,
7983 ) {
7984 if let Some(nav_history) = self.nav_history.as_mut() {
7985 let buffer = self.buffer.read(cx).read(cx);
7986 let cursor_position = cursor_anchor.to_point(&buffer);
7987 let scroll_state = self.scroll_manager.anchor();
7988 let scroll_top_row = scroll_state.top_row(&buffer);
7989 drop(buffer);
7990
7991 if let Some(new_position) = new_position {
7992 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7993 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7994 return;
7995 }
7996 }
7997
7998 nav_history.push(
7999 Some(NavigationData {
8000 cursor_anchor,
8001 cursor_position,
8002 scroll_anchor: scroll_state,
8003 scroll_top_row,
8004 }),
8005 cx,
8006 );
8007 }
8008 }
8009
8010 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8011 let buffer = self.buffer.read(cx).snapshot(cx);
8012 let mut selection = self.selections.first::<usize>(cx);
8013 selection.set_head(buffer.len(), SelectionGoal::None);
8014 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8015 s.select(vec![selection]);
8016 });
8017 }
8018
8019 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8020 let end = self.buffer.read(cx).read(cx).len();
8021 self.change_selections(None, cx, |s| {
8022 s.select_ranges(vec![0..end]);
8023 });
8024 }
8025
8026 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8027 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8028 let mut selections = self.selections.all::<Point>(cx);
8029 let max_point = display_map.buffer_snapshot.max_point();
8030 for selection in &mut selections {
8031 let rows = selection.spanned_rows(true, &display_map);
8032 selection.start = Point::new(rows.start.0, 0);
8033 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8034 selection.reversed = false;
8035 }
8036 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8037 s.select(selections);
8038 });
8039 }
8040
8041 pub fn split_selection_into_lines(
8042 &mut self,
8043 _: &SplitSelectionIntoLines,
8044 cx: &mut ViewContext<Self>,
8045 ) {
8046 let mut to_unfold = Vec::new();
8047 let mut new_selection_ranges = Vec::new();
8048 {
8049 let selections = self.selections.all::<Point>(cx);
8050 let buffer = self.buffer.read(cx).read(cx);
8051 for selection in selections {
8052 for row in selection.start.row..selection.end.row {
8053 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8054 new_selection_ranges.push(cursor..cursor);
8055 }
8056 new_selection_ranges.push(selection.end..selection.end);
8057 to_unfold.push(selection.start..selection.end);
8058 }
8059 }
8060 self.unfold_ranges(to_unfold, true, true, cx);
8061 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8062 s.select_ranges(new_selection_ranges);
8063 });
8064 }
8065
8066 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8067 self.add_selection(true, cx);
8068 }
8069
8070 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8071 self.add_selection(false, cx);
8072 }
8073
8074 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8075 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8076 let mut selections = self.selections.all::<Point>(cx);
8077 let text_layout_details = self.text_layout_details(cx);
8078 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8079 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8080 let range = oldest_selection.display_range(&display_map).sorted();
8081
8082 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8083 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8084 let positions = start_x.min(end_x)..start_x.max(end_x);
8085
8086 selections.clear();
8087 let mut stack = Vec::new();
8088 for row in range.start.row().0..=range.end.row().0 {
8089 if let Some(selection) = self.selections.build_columnar_selection(
8090 &display_map,
8091 DisplayRow(row),
8092 &positions,
8093 oldest_selection.reversed,
8094 &text_layout_details,
8095 ) {
8096 stack.push(selection.id);
8097 selections.push(selection);
8098 }
8099 }
8100
8101 if above {
8102 stack.reverse();
8103 }
8104
8105 AddSelectionsState { above, stack }
8106 });
8107
8108 let last_added_selection = *state.stack.last().unwrap();
8109 let mut new_selections = Vec::new();
8110 if above == state.above {
8111 let end_row = if above {
8112 DisplayRow(0)
8113 } else {
8114 display_map.max_point().row()
8115 };
8116
8117 'outer: for selection in selections {
8118 if selection.id == last_added_selection {
8119 let range = selection.display_range(&display_map).sorted();
8120 debug_assert_eq!(range.start.row(), range.end.row());
8121 let mut row = range.start.row();
8122 let positions =
8123 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8124 px(start)..px(end)
8125 } else {
8126 let start_x =
8127 display_map.x_for_display_point(range.start, &text_layout_details);
8128 let end_x =
8129 display_map.x_for_display_point(range.end, &text_layout_details);
8130 start_x.min(end_x)..start_x.max(end_x)
8131 };
8132
8133 while row != end_row {
8134 if above {
8135 row.0 -= 1;
8136 } else {
8137 row.0 += 1;
8138 }
8139
8140 if let Some(new_selection) = self.selections.build_columnar_selection(
8141 &display_map,
8142 row,
8143 &positions,
8144 selection.reversed,
8145 &text_layout_details,
8146 ) {
8147 state.stack.push(new_selection.id);
8148 if above {
8149 new_selections.push(new_selection);
8150 new_selections.push(selection);
8151 } else {
8152 new_selections.push(selection);
8153 new_selections.push(new_selection);
8154 }
8155
8156 continue 'outer;
8157 }
8158 }
8159 }
8160
8161 new_selections.push(selection);
8162 }
8163 } else {
8164 new_selections = selections;
8165 new_selections.retain(|s| s.id != last_added_selection);
8166 state.stack.pop();
8167 }
8168
8169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8170 s.select(new_selections);
8171 });
8172 if state.stack.len() > 1 {
8173 self.add_selections_state = Some(state);
8174 }
8175 }
8176
8177 pub fn select_next_match_internal(
8178 &mut self,
8179 display_map: &DisplaySnapshot,
8180 replace_newest: bool,
8181 autoscroll: Option<Autoscroll>,
8182 cx: &mut ViewContext<Self>,
8183 ) -> Result<()> {
8184 fn select_next_match_ranges(
8185 this: &mut Editor,
8186 range: Range<usize>,
8187 replace_newest: bool,
8188 auto_scroll: Option<Autoscroll>,
8189 cx: &mut ViewContext<Editor>,
8190 ) {
8191 this.unfold_ranges([range.clone()], false, true, cx);
8192 this.change_selections(auto_scroll, cx, |s| {
8193 if replace_newest {
8194 s.delete(s.newest_anchor().id);
8195 }
8196 s.insert_range(range.clone());
8197 });
8198 }
8199
8200 let buffer = &display_map.buffer_snapshot;
8201 let mut selections = self.selections.all::<usize>(cx);
8202 if let Some(mut select_next_state) = self.select_next_state.take() {
8203 let query = &select_next_state.query;
8204 if !select_next_state.done {
8205 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8206 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8207 let mut next_selected_range = None;
8208
8209 let bytes_after_last_selection =
8210 buffer.bytes_in_range(last_selection.end..buffer.len());
8211 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8212 let query_matches = query
8213 .stream_find_iter(bytes_after_last_selection)
8214 .map(|result| (last_selection.end, result))
8215 .chain(
8216 query
8217 .stream_find_iter(bytes_before_first_selection)
8218 .map(|result| (0, result)),
8219 );
8220
8221 for (start_offset, query_match) in query_matches {
8222 let query_match = query_match.unwrap(); // can only fail due to I/O
8223 let offset_range =
8224 start_offset + query_match.start()..start_offset + query_match.end();
8225 let display_range = offset_range.start.to_display_point(display_map)
8226 ..offset_range.end.to_display_point(display_map);
8227
8228 if !select_next_state.wordwise
8229 || (!movement::is_inside_word(display_map, display_range.start)
8230 && !movement::is_inside_word(display_map, display_range.end))
8231 {
8232 // TODO: This is n^2, because we might check all the selections
8233 if !selections
8234 .iter()
8235 .any(|selection| selection.range().overlaps(&offset_range))
8236 {
8237 next_selected_range = Some(offset_range);
8238 break;
8239 }
8240 }
8241 }
8242
8243 if let Some(next_selected_range) = next_selected_range {
8244 select_next_match_ranges(
8245 self,
8246 next_selected_range,
8247 replace_newest,
8248 autoscroll,
8249 cx,
8250 );
8251 } else {
8252 select_next_state.done = true;
8253 }
8254 }
8255
8256 self.select_next_state = Some(select_next_state);
8257 } else {
8258 let mut only_carets = true;
8259 let mut same_text_selected = true;
8260 let mut selected_text = None;
8261
8262 let mut selections_iter = selections.iter().peekable();
8263 while let Some(selection) = selections_iter.next() {
8264 if selection.start != selection.end {
8265 only_carets = false;
8266 }
8267
8268 if same_text_selected {
8269 if selected_text.is_none() {
8270 selected_text =
8271 Some(buffer.text_for_range(selection.range()).collect::<String>());
8272 }
8273
8274 if let Some(next_selection) = selections_iter.peek() {
8275 if next_selection.range().len() == selection.range().len() {
8276 let next_selected_text = buffer
8277 .text_for_range(next_selection.range())
8278 .collect::<String>();
8279 if Some(next_selected_text) != selected_text {
8280 same_text_selected = false;
8281 selected_text = None;
8282 }
8283 } else {
8284 same_text_selected = false;
8285 selected_text = None;
8286 }
8287 }
8288 }
8289 }
8290
8291 if only_carets {
8292 for selection in &mut selections {
8293 let word_range = movement::surrounding_word(
8294 display_map,
8295 selection.start.to_display_point(display_map),
8296 );
8297 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8298 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8299 selection.goal = SelectionGoal::None;
8300 selection.reversed = false;
8301 select_next_match_ranges(
8302 self,
8303 selection.start..selection.end,
8304 replace_newest,
8305 autoscroll,
8306 cx,
8307 );
8308 }
8309
8310 if selections.len() == 1 {
8311 let selection = selections
8312 .last()
8313 .expect("ensured that there's only one selection");
8314 let query = buffer
8315 .text_for_range(selection.start..selection.end)
8316 .collect::<String>();
8317 let is_empty = query.is_empty();
8318 let select_state = SelectNextState {
8319 query: AhoCorasick::new(&[query])?,
8320 wordwise: true,
8321 done: is_empty,
8322 };
8323 self.select_next_state = Some(select_state);
8324 } else {
8325 self.select_next_state = None;
8326 }
8327 } else if let Some(selected_text) = selected_text {
8328 self.select_next_state = Some(SelectNextState {
8329 query: AhoCorasick::new(&[selected_text])?,
8330 wordwise: false,
8331 done: false,
8332 });
8333 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8334 }
8335 }
8336 Ok(())
8337 }
8338
8339 pub fn select_all_matches(
8340 &mut self,
8341 _action: &SelectAllMatches,
8342 cx: &mut ViewContext<Self>,
8343 ) -> Result<()> {
8344 self.push_to_selection_history();
8345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8346
8347 self.select_next_match_internal(&display_map, false, None, cx)?;
8348 let Some(select_next_state) = self.select_next_state.as_mut() else {
8349 return Ok(());
8350 };
8351 if select_next_state.done {
8352 return Ok(());
8353 }
8354
8355 let mut new_selections = self.selections.all::<usize>(cx);
8356
8357 let buffer = &display_map.buffer_snapshot;
8358 let query_matches = select_next_state
8359 .query
8360 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8361
8362 for query_match in query_matches {
8363 let query_match = query_match.unwrap(); // can only fail due to I/O
8364 let offset_range = query_match.start()..query_match.end();
8365 let display_range = offset_range.start.to_display_point(&display_map)
8366 ..offset_range.end.to_display_point(&display_map);
8367
8368 if !select_next_state.wordwise
8369 || (!movement::is_inside_word(&display_map, display_range.start)
8370 && !movement::is_inside_word(&display_map, display_range.end))
8371 {
8372 self.selections.change_with(cx, |selections| {
8373 new_selections.push(Selection {
8374 id: selections.new_selection_id(),
8375 start: offset_range.start,
8376 end: offset_range.end,
8377 reversed: false,
8378 goal: SelectionGoal::None,
8379 });
8380 });
8381 }
8382 }
8383
8384 new_selections.sort_by_key(|selection| selection.start);
8385 let mut ix = 0;
8386 while ix + 1 < new_selections.len() {
8387 let current_selection = &new_selections[ix];
8388 let next_selection = &new_selections[ix + 1];
8389 if current_selection.range().overlaps(&next_selection.range()) {
8390 if current_selection.id < next_selection.id {
8391 new_selections.remove(ix + 1);
8392 } else {
8393 new_selections.remove(ix);
8394 }
8395 } else {
8396 ix += 1;
8397 }
8398 }
8399
8400 select_next_state.done = true;
8401 self.unfold_ranges(
8402 new_selections.iter().map(|selection| selection.range()),
8403 false,
8404 false,
8405 cx,
8406 );
8407 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8408 selections.select(new_selections)
8409 });
8410
8411 Ok(())
8412 }
8413
8414 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8415 self.push_to_selection_history();
8416 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8417 self.select_next_match_internal(
8418 &display_map,
8419 action.replace_newest,
8420 Some(Autoscroll::newest()),
8421 cx,
8422 )?;
8423 Ok(())
8424 }
8425
8426 pub fn select_previous(
8427 &mut self,
8428 action: &SelectPrevious,
8429 cx: &mut ViewContext<Self>,
8430 ) -> Result<()> {
8431 self.push_to_selection_history();
8432 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8433 let buffer = &display_map.buffer_snapshot;
8434 let mut selections = self.selections.all::<usize>(cx);
8435 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8436 let query = &select_prev_state.query;
8437 if !select_prev_state.done {
8438 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8439 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8440 let mut next_selected_range = None;
8441 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8442 let bytes_before_last_selection =
8443 buffer.reversed_bytes_in_range(0..last_selection.start);
8444 let bytes_after_first_selection =
8445 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8446 let query_matches = query
8447 .stream_find_iter(bytes_before_last_selection)
8448 .map(|result| (last_selection.start, result))
8449 .chain(
8450 query
8451 .stream_find_iter(bytes_after_first_selection)
8452 .map(|result| (buffer.len(), result)),
8453 );
8454 for (end_offset, query_match) in query_matches {
8455 let query_match = query_match.unwrap(); // can only fail due to I/O
8456 let offset_range =
8457 end_offset - query_match.end()..end_offset - query_match.start();
8458 let display_range = offset_range.start.to_display_point(&display_map)
8459 ..offset_range.end.to_display_point(&display_map);
8460
8461 if !select_prev_state.wordwise
8462 || (!movement::is_inside_word(&display_map, display_range.start)
8463 && !movement::is_inside_word(&display_map, display_range.end))
8464 {
8465 next_selected_range = Some(offset_range);
8466 break;
8467 }
8468 }
8469
8470 if let Some(next_selected_range) = next_selected_range {
8471 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8472 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8473 if action.replace_newest {
8474 s.delete(s.newest_anchor().id);
8475 }
8476 s.insert_range(next_selected_range);
8477 });
8478 } else {
8479 select_prev_state.done = true;
8480 }
8481 }
8482
8483 self.select_prev_state = Some(select_prev_state);
8484 } else {
8485 let mut only_carets = true;
8486 let mut same_text_selected = true;
8487 let mut selected_text = None;
8488
8489 let mut selections_iter = selections.iter().peekable();
8490 while let Some(selection) = selections_iter.next() {
8491 if selection.start != selection.end {
8492 only_carets = false;
8493 }
8494
8495 if same_text_selected {
8496 if selected_text.is_none() {
8497 selected_text =
8498 Some(buffer.text_for_range(selection.range()).collect::<String>());
8499 }
8500
8501 if let Some(next_selection) = selections_iter.peek() {
8502 if next_selection.range().len() == selection.range().len() {
8503 let next_selected_text = buffer
8504 .text_for_range(next_selection.range())
8505 .collect::<String>();
8506 if Some(next_selected_text) != selected_text {
8507 same_text_selected = false;
8508 selected_text = None;
8509 }
8510 } else {
8511 same_text_selected = false;
8512 selected_text = None;
8513 }
8514 }
8515 }
8516 }
8517
8518 if only_carets {
8519 for selection in &mut selections {
8520 let word_range = movement::surrounding_word(
8521 &display_map,
8522 selection.start.to_display_point(&display_map),
8523 );
8524 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8525 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8526 selection.goal = SelectionGoal::None;
8527 selection.reversed = false;
8528 }
8529 if selections.len() == 1 {
8530 let selection = selections
8531 .last()
8532 .expect("ensured that there's only one selection");
8533 let query = buffer
8534 .text_for_range(selection.start..selection.end)
8535 .collect::<String>();
8536 let is_empty = query.is_empty();
8537 let select_state = SelectNextState {
8538 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8539 wordwise: true,
8540 done: is_empty,
8541 };
8542 self.select_prev_state = Some(select_state);
8543 } else {
8544 self.select_prev_state = None;
8545 }
8546
8547 self.unfold_ranges(
8548 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8549 false,
8550 true,
8551 cx,
8552 );
8553 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8554 s.select(selections);
8555 });
8556 } else if let Some(selected_text) = selected_text {
8557 self.select_prev_state = Some(SelectNextState {
8558 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8559 wordwise: false,
8560 done: false,
8561 });
8562 self.select_previous(action, cx)?;
8563 }
8564 }
8565 Ok(())
8566 }
8567
8568 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8569 let text_layout_details = &self.text_layout_details(cx);
8570 self.transact(cx, |this, cx| {
8571 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8572 let mut edits = Vec::new();
8573 let mut selection_edit_ranges = Vec::new();
8574 let mut last_toggled_row = None;
8575 let snapshot = this.buffer.read(cx).read(cx);
8576 let empty_str: Arc<str> = Arc::default();
8577 let mut suffixes_inserted = Vec::new();
8578
8579 fn comment_prefix_range(
8580 snapshot: &MultiBufferSnapshot,
8581 row: MultiBufferRow,
8582 comment_prefix: &str,
8583 comment_prefix_whitespace: &str,
8584 ) -> Range<Point> {
8585 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8586
8587 let mut line_bytes = snapshot
8588 .bytes_in_range(start..snapshot.max_point())
8589 .flatten()
8590 .copied();
8591
8592 // If this line currently begins with the line comment prefix, then record
8593 // the range containing the prefix.
8594 if line_bytes
8595 .by_ref()
8596 .take(comment_prefix.len())
8597 .eq(comment_prefix.bytes())
8598 {
8599 // Include any whitespace that matches the comment prefix.
8600 let matching_whitespace_len = line_bytes
8601 .zip(comment_prefix_whitespace.bytes())
8602 .take_while(|(a, b)| a == b)
8603 .count() as u32;
8604 let end = Point::new(
8605 start.row,
8606 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8607 );
8608 start..end
8609 } else {
8610 start..start
8611 }
8612 }
8613
8614 fn comment_suffix_range(
8615 snapshot: &MultiBufferSnapshot,
8616 row: MultiBufferRow,
8617 comment_suffix: &str,
8618 comment_suffix_has_leading_space: bool,
8619 ) -> Range<Point> {
8620 let end = Point::new(row.0, snapshot.line_len(row));
8621 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8622
8623 let mut line_end_bytes = snapshot
8624 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8625 .flatten()
8626 .copied();
8627
8628 let leading_space_len = if suffix_start_column > 0
8629 && line_end_bytes.next() == Some(b' ')
8630 && comment_suffix_has_leading_space
8631 {
8632 1
8633 } else {
8634 0
8635 };
8636
8637 // If this line currently begins with the line comment prefix, then record
8638 // the range containing the prefix.
8639 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8640 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8641 start..end
8642 } else {
8643 end..end
8644 }
8645 }
8646
8647 // TODO: Handle selections that cross excerpts
8648 for selection in &mut selections {
8649 let start_column = snapshot
8650 .indent_size_for_line(MultiBufferRow(selection.start.row))
8651 .len;
8652 let language = if let Some(language) =
8653 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8654 {
8655 language
8656 } else {
8657 continue;
8658 };
8659
8660 selection_edit_ranges.clear();
8661
8662 // If multiple selections contain a given row, avoid processing that
8663 // row more than once.
8664 let mut start_row = MultiBufferRow(selection.start.row);
8665 if last_toggled_row == Some(start_row) {
8666 start_row = start_row.next_row();
8667 }
8668 let end_row =
8669 if selection.end.row > selection.start.row && selection.end.column == 0 {
8670 MultiBufferRow(selection.end.row - 1)
8671 } else {
8672 MultiBufferRow(selection.end.row)
8673 };
8674 last_toggled_row = Some(end_row);
8675
8676 if start_row > end_row {
8677 continue;
8678 }
8679
8680 // If the language has line comments, toggle those.
8681 let full_comment_prefixes = language.line_comment_prefixes();
8682 if !full_comment_prefixes.is_empty() {
8683 let first_prefix = full_comment_prefixes
8684 .first()
8685 .expect("prefixes is non-empty");
8686 let prefix_trimmed_lengths = full_comment_prefixes
8687 .iter()
8688 .map(|p| p.trim_end_matches(' ').len())
8689 .collect::<SmallVec<[usize; 4]>>();
8690
8691 let mut all_selection_lines_are_comments = true;
8692
8693 for row in start_row.0..=end_row.0 {
8694 let row = MultiBufferRow(row);
8695 if start_row < end_row && snapshot.is_line_blank(row) {
8696 continue;
8697 }
8698
8699 let prefix_range = full_comment_prefixes
8700 .iter()
8701 .zip(prefix_trimmed_lengths.iter().copied())
8702 .map(|(prefix, trimmed_prefix_len)| {
8703 comment_prefix_range(
8704 snapshot.deref(),
8705 row,
8706 &prefix[..trimmed_prefix_len],
8707 &prefix[trimmed_prefix_len..],
8708 )
8709 })
8710 .max_by_key(|range| range.end.column - range.start.column)
8711 .expect("prefixes is non-empty");
8712
8713 if prefix_range.is_empty() {
8714 all_selection_lines_are_comments = false;
8715 }
8716
8717 selection_edit_ranges.push(prefix_range);
8718 }
8719
8720 if all_selection_lines_are_comments {
8721 edits.extend(
8722 selection_edit_ranges
8723 .iter()
8724 .cloned()
8725 .map(|range| (range, empty_str.clone())),
8726 );
8727 } else {
8728 let min_column = selection_edit_ranges
8729 .iter()
8730 .map(|range| range.start.column)
8731 .min()
8732 .unwrap_or(0);
8733 edits.extend(selection_edit_ranges.iter().map(|range| {
8734 let position = Point::new(range.start.row, min_column);
8735 (position..position, first_prefix.clone())
8736 }));
8737 }
8738 } else if let Some((full_comment_prefix, comment_suffix)) =
8739 language.block_comment_delimiters()
8740 {
8741 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8742 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8743 let prefix_range = comment_prefix_range(
8744 snapshot.deref(),
8745 start_row,
8746 comment_prefix,
8747 comment_prefix_whitespace,
8748 );
8749 let suffix_range = comment_suffix_range(
8750 snapshot.deref(),
8751 end_row,
8752 comment_suffix.trim_start_matches(' '),
8753 comment_suffix.starts_with(' '),
8754 );
8755
8756 if prefix_range.is_empty() || suffix_range.is_empty() {
8757 edits.push((
8758 prefix_range.start..prefix_range.start,
8759 full_comment_prefix.clone(),
8760 ));
8761 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8762 suffixes_inserted.push((end_row, comment_suffix.len()));
8763 } else {
8764 edits.push((prefix_range, empty_str.clone()));
8765 edits.push((suffix_range, empty_str.clone()));
8766 }
8767 } else {
8768 continue;
8769 }
8770 }
8771
8772 drop(snapshot);
8773 this.buffer.update(cx, |buffer, cx| {
8774 buffer.edit(edits, None, cx);
8775 });
8776
8777 // Adjust selections so that they end before any comment suffixes that
8778 // were inserted.
8779 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8780 let mut selections = this.selections.all::<Point>(cx);
8781 let snapshot = this.buffer.read(cx).read(cx);
8782 for selection in &mut selections {
8783 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8784 match row.cmp(&MultiBufferRow(selection.end.row)) {
8785 Ordering::Less => {
8786 suffixes_inserted.next();
8787 continue;
8788 }
8789 Ordering::Greater => break,
8790 Ordering::Equal => {
8791 if selection.end.column == snapshot.line_len(row) {
8792 if selection.is_empty() {
8793 selection.start.column -= suffix_len as u32;
8794 }
8795 selection.end.column -= suffix_len as u32;
8796 }
8797 break;
8798 }
8799 }
8800 }
8801 }
8802
8803 drop(snapshot);
8804 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8805
8806 let selections = this.selections.all::<Point>(cx);
8807 let selections_on_single_row = selections.windows(2).all(|selections| {
8808 selections[0].start.row == selections[1].start.row
8809 && selections[0].end.row == selections[1].end.row
8810 && selections[0].start.row == selections[0].end.row
8811 });
8812 let selections_selecting = selections
8813 .iter()
8814 .any(|selection| selection.start != selection.end);
8815 let advance_downwards = action.advance_downwards
8816 && selections_on_single_row
8817 && !selections_selecting
8818 && !matches!(this.mode, EditorMode::SingleLine { .. });
8819
8820 if advance_downwards {
8821 let snapshot = this.buffer.read(cx).snapshot(cx);
8822
8823 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8824 s.move_cursors_with(|display_snapshot, display_point, _| {
8825 let mut point = display_point.to_point(display_snapshot);
8826 point.row += 1;
8827 point = snapshot.clip_point(point, Bias::Left);
8828 let display_point = point.to_display_point(display_snapshot);
8829 let goal = SelectionGoal::HorizontalPosition(
8830 display_snapshot
8831 .x_for_display_point(display_point, text_layout_details)
8832 .into(),
8833 );
8834 (display_point, goal)
8835 })
8836 });
8837 }
8838 });
8839 }
8840
8841 pub fn select_enclosing_symbol(
8842 &mut self,
8843 _: &SelectEnclosingSymbol,
8844 cx: &mut ViewContext<Self>,
8845 ) {
8846 let buffer = self.buffer.read(cx).snapshot(cx);
8847 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8848
8849 fn update_selection(
8850 selection: &Selection<usize>,
8851 buffer_snap: &MultiBufferSnapshot,
8852 ) -> Option<Selection<usize>> {
8853 let cursor = selection.head();
8854 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8855 for symbol in symbols.iter().rev() {
8856 let start = symbol.range.start.to_offset(buffer_snap);
8857 let end = symbol.range.end.to_offset(buffer_snap);
8858 let new_range = start..end;
8859 if start < selection.start || end > selection.end {
8860 return Some(Selection {
8861 id: selection.id,
8862 start: new_range.start,
8863 end: new_range.end,
8864 goal: SelectionGoal::None,
8865 reversed: selection.reversed,
8866 });
8867 }
8868 }
8869 None
8870 }
8871
8872 let mut selected_larger_symbol = false;
8873 let new_selections = old_selections
8874 .iter()
8875 .map(|selection| match update_selection(selection, &buffer) {
8876 Some(new_selection) => {
8877 if new_selection.range() != selection.range() {
8878 selected_larger_symbol = true;
8879 }
8880 new_selection
8881 }
8882 None => selection.clone(),
8883 })
8884 .collect::<Vec<_>>();
8885
8886 if selected_larger_symbol {
8887 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8888 s.select(new_selections);
8889 });
8890 }
8891 }
8892
8893 pub fn select_larger_syntax_node(
8894 &mut self,
8895 _: &SelectLargerSyntaxNode,
8896 cx: &mut ViewContext<Self>,
8897 ) {
8898 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8899 let buffer = self.buffer.read(cx).snapshot(cx);
8900 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8901
8902 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8903 let mut selected_larger_node = false;
8904 let new_selections = old_selections
8905 .iter()
8906 .map(|selection| {
8907 let old_range = selection.start..selection.end;
8908 let mut new_range = old_range.clone();
8909 while let Some(containing_range) =
8910 buffer.range_for_syntax_ancestor(new_range.clone())
8911 {
8912 new_range = containing_range;
8913 if !display_map.intersects_fold(new_range.start)
8914 && !display_map.intersects_fold(new_range.end)
8915 {
8916 break;
8917 }
8918 }
8919
8920 selected_larger_node |= new_range != old_range;
8921 Selection {
8922 id: selection.id,
8923 start: new_range.start,
8924 end: new_range.end,
8925 goal: SelectionGoal::None,
8926 reversed: selection.reversed,
8927 }
8928 })
8929 .collect::<Vec<_>>();
8930
8931 if selected_larger_node {
8932 stack.push(old_selections);
8933 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8934 s.select(new_selections);
8935 });
8936 }
8937 self.select_larger_syntax_node_stack = stack;
8938 }
8939
8940 pub fn select_smaller_syntax_node(
8941 &mut self,
8942 _: &SelectSmallerSyntaxNode,
8943 cx: &mut ViewContext<Self>,
8944 ) {
8945 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8946 if let Some(selections) = stack.pop() {
8947 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8948 s.select(selections.to_vec());
8949 });
8950 }
8951 self.select_larger_syntax_node_stack = stack;
8952 }
8953
8954 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8955 if !EditorSettings::get_global(cx).gutter.runnables {
8956 self.clear_tasks();
8957 return Task::ready(());
8958 }
8959 let project = self.project.clone();
8960 cx.spawn(|this, mut cx| async move {
8961 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8962 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8963 }) else {
8964 return;
8965 };
8966
8967 let Some(project) = project else {
8968 return;
8969 };
8970
8971 let hide_runnables = project
8972 .update(&mut cx, |project, cx| {
8973 // Do not display any test indicators in non-dev server remote projects.
8974 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8975 })
8976 .unwrap_or(true);
8977 if hide_runnables {
8978 return;
8979 }
8980 let new_rows =
8981 cx.background_executor()
8982 .spawn({
8983 let snapshot = display_snapshot.clone();
8984 async move {
8985 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8986 }
8987 })
8988 .await;
8989 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8990
8991 this.update(&mut cx, |this, _| {
8992 this.clear_tasks();
8993 for (key, value) in rows {
8994 this.insert_tasks(key, value);
8995 }
8996 })
8997 .ok();
8998 })
8999 }
9000 fn fetch_runnable_ranges(
9001 snapshot: &DisplaySnapshot,
9002 range: Range<Anchor>,
9003 ) -> Vec<language::RunnableRange> {
9004 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9005 }
9006
9007 fn runnable_rows(
9008 project: Model<Project>,
9009 snapshot: DisplaySnapshot,
9010 runnable_ranges: Vec<RunnableRange>,
9011 mut cx: AsyncWindowContext,
9012 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9013 runnable_ranges
9014 .into_iter()
9015 .filter_map(|mut runnable| {
9016 let tasks = cx
9017 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9018 .ok()?;
9019 if tasks.is_empty() {
9020 return None;
9021 }
9022
9023 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9024
9025 let row = snapshot
9026 .buffer_snapshot
9027 .buffer_line_for_row(MultiBufferRow(point.row))?
9028 .1
9029 .start
9030 .row;
9031
9032 let context_range =
9033 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9034 Some((
9035 (runnable.buffer_id, row),
9036 RunnableTasks {
9037 templates: tasks,
9038 offset: MultiBufferOffset(runnable.run_range.start),
9039 context_range,
9040 column: point.column,
9041 extra_variables: runnable.extra_captures,
9042 },
9043 ))
9044 })
9045 .collect()
9046 }
9047
9048 fn templates_with_tags(
9049 project: &Model<Project>,
9050 runnable: &mut Runnable,
9051 cx: &WindowContext<'_>,
9052 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9053 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9054 let (worktree_id, file) = project
9055 .buffer_for_id(runnable.buffer, cx)
9056 .and_then(|buffer| buffer.read(cx).file())
9057 .map(|file| (file.worktree_id(cx), file.clone()))
9058 .unzip();
9059
9060 (project.task_inventory().clone(), worktree_id, file)
9061 });
9062
9063 let inventory = inventory.read(cx);
9064 let tags = mem::take(&mut runnable.tags);
9065 let mut tags: Vec<_> = tags
9066 .into_iter()
9067 .flat_map(|tag| {
9068 let tag = tag.0.clone();
9069 inventory
9070 .list_tasks(
9071 file.clone(),
9072 Some(runnable.language.clone()),
9073 worktree_id,
9074 cx,
9075 )
9076 .into_iter()
9077 .filter(move |(_, template)| {
9078 template.tags.iter().any(|source_tag| source_tag == &tag)
9079 })
9080 })
9081 .sorted_by_key(|(kind, _)| kind.to_owned())
9082 .collect();
9083 if let Some((leading_tag_source, _)) = tags.first() {
9084 // Strongest source wins; if we have worktree tag binding, prefer that to
9085 // global and language bindings;
9086 // if we have a global binding, prefer that to language binding.
9087 let first_mismatch = tags
9088 .iter()
9089 .position(|(tag_source, _)| tag_source != leading_tag_source);
9090 if let Some(index) = first_mismatch {
9091 tags.truncate(index);
9092 }
9093 }
9094
9095 tags
9096 }
9097
9098 pub fn move_to_enclosing_bracket(
9099 &mut self,
9100 _: &MoveToEnclosingBracket,
9101 cx: &mut ViewContext<Self>,
9102 ) {
9103 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9104 s.move_offsets_with(|snapshot, selection| {
9105 let Some(enclosing_bracket_ranges) =
9106 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9107 else {
9108 return;
9109 };
9110
9111 let mut best_length = usize::MAX;
9112 let mut best_inside = false;
9113 let mut best_in_bracket_range = false;
9114 let mut best_destination = None;
9115 for (open, close) in enclosing_bracket_ranges {
9116 let close = close.to_inclusive();
9117 let length = close.end() - open.start;
9118 let inside = selection.start >= open.end && selection.end <= *close.start();
9119 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9120 || close.contains(&selection.head());
9121
9122 // If best is next to a bracket and current isn't, skip
9123 if !in_bracket_range && best_in_bracket_range {
9124 continue;
9125 }
9126
9127 // Prefer smaller lengths unless best is inside and current isn't
9128 if length > best_length && (best_inside || !inside) {
9129 continue;
9130 }
9131
9132 best_length = length;
9133 best_inside = inside;
9134 best_in_bracket_range = in_bracket_range;
9135 best_destination = Some(
9136 if close.contains(&selection.start) && close.contains(&selection.end) {
9137 if inside {
9138 open.end
9139 } else {
9140 open.start
9141 }
9142 } else if inside {
9143 *close.start()
9144 } else {
9145 *close.end()
9146 },
9147 );
9148 }
9149
9150 if let Some(destination) = best_destination {
9151 selection.collapse_to(destination, SelectionGoal::None);
9152 }
9153 })
9154 });
9155 }
9156
9157 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9158 self.end_selection(cx);
9159 self.selection_history.mode = SelectionHistoryMode::Undoing;
9160 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9161 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9162 self.select_next_state = entry.select_next_state;
9163 self.select_prev_state = entry.select_prev_state;
9164 self.add_selections_state = entry.add_selections_state;
9165 self.request_autoscroll(Autoscroll::newest(), cx);
9166 }
9167 self.selection_history.mode = SelectionHistoryMode::Normal;
9168 }
9169
9170 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9171 self.end_selection(cx);
9172 self.selection_history.mode = SelectionHistoryMode::Redoing;
9173 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9174 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9175 self.select_next_state = entry.select_next_state;
9176 self.select_prev_state = entry.select_prev_state;
9177 self.add_selections_state = entry.add_selections_state;
9178 self.request_autoscroll(Autoscroll::newest(), cx);
9179 }
9180 self.selection_history.mode = SelectionHistoryMode::Normal;
9181 }
9182
9183 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9184 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9185 }
9186
9187 pub fn expand_excerpts_down(
9188 &mut self,
9189 action: &ExpandExcerptsDown,
9190 cx: &mut ViewContext<Self>,
9191 ) {
9192 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9193 }
9194
9195 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9196 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9197 }
9198
9199 pub fn expand_excerpts_for_direction(
9200 &mut self,
9201 lines: u32,
9202 direction: ExpandExcerptDirection,
9203 cx: &mut ViewContext<Self>,
9204 ) {
9205 let selections = self.selections.disjoint_anchors();
9206
9207 let lines = if lines == 0 {
9208 EditorSettings::get_global(cx).expand_excerpt_lines
9209 } else {
9210 lines
9211 };
9212
9213 self.buffer.update(cx, |buffer, cx| {
9214 buffer.expand_excerpts(
9215 selections
9216 .iter()
9217 .map(|selection| selection.head().excerpt_id)
9218 .dedup(),
9219 lines,
9220 direction,
9221 cx,
9222 )
9223 })
9224 }
9225
9226 pub fn expand_excerpt(
9227 &mut self,
9228 excerpt: ExcerptId,
9229 direction: ExpandExcerptDirection,
9230 cx: &mut ViewContext<Self>,
9231 ) {
9232 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9233 self.buffer.update(cx, |buffer, cx| {
9234 buffer.expand_excerpts([excerpt], lines, direction, cx)
9235 })
9236 }
9237
9238 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9239 self.go_to_diagnostic_impl(Direction::Next, cx)
9240 }
9241
9242 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9243 self.go_to_diagnostic_impl(Direction::Prev, cx)
9244 }
9245
9246 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9247 let buffer = self.buffer.read(cx).snapshot(cx);
9248 let selection = self.selections.newest::<usize>(cx);
9249
9250 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9251 if direction == Direction::Next {
9252 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9253 let (group_id, jump_to) = popover.activation_info();
9254 if self.activate_diagnostics(group_id, cx) {
9255 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9256 let mut new_selection = s.newest_anchor().clone();
9257 new_selection.collapse_to(jump_to, SelectionGoal::None);
9258 s.select_anchors(vec![new_selection.clone()]);
9259 });
9260 }
9261 return;
9262 }
9263 }
9264
9265 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9266 active_diagnostics
9267 .primary_range
9268 .to_offset(&buffer)
9269 .to_inclusive()
9270 });
9271 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9272 if active_primary_range.contains(&selection.head()) {
9273 *active_primary_range.start()
9274 } else {
9275 selection.head()
9276 }
9277 } else {
9278 selection.head()
9279 };
9280 let snapshot = self.snapshot(cx);
9281 loop {
9282 let diagnostics = if direction == Direction::Prev {
9283 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9284 } else {
9285 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9286 }
9287 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9288 let group = diagnostics
9289 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9290 // be sorted in a stable way
9291 // skip until we are at current active diagnostic, if it exists
9292 .skip_while(|entry| {
9293 (match direction {
9294 Direction::Prev => entry.range.start >= search_start,
9295 Direction::Next => entry.range.start <= search_start,
9296 }) && self
9297 .active_diagnostics
9298 .as_ref()
9299 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9300 })
9301 .find_map(|entry| {
9302 if entry.diagnostic.is_primary
9303 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9304 && !entry.range.is_empty()
9305 // if we match with the active diagnostic, skip it
9306 && Some(entry.diagnostic.group_id)
9307 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9308 {
9309 Some((entry.range, entry.diagnostic.group_id))
9310 } else {
9311 None
9312 }
9313 });
9314
9315 if let Some((primary_range, group_id)) = group {
9316 if self.activate_diagnostics(group_id, cx) {
9317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9318 s.select(vec![Selection {
9319 id: selection.id,
9320 start: primary_range.start,
9321 end: primary_range.start,
9322 reversed: false,
9323 goal: SelectionGoal::None,
9324 }]);
9325 });
9326 }
9327 break;
9328 } else {
9329 // Cycle around to the start of the buffer, potentially moving back to the start of
9330 // the currently active diagnostic.
9331 active_primary_range.take();
9332 if direction == Direction::Prev {
9333 if search_start == buffer.len() {
9334 break;
9335 } else {
9336 search_start = buffer.len();
9337 }
9338 } else if search_start == 0 {
9339 break;
9340 } else {
9341 search_start = 0;
9342 }
9343 }
9344 }
9345 }
9346
9347 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9348 let snapshot = self
9349 .display_map
9350 .update(cx, |display_map, cx| display_map.snapshot(cx));
9351 let selection = self.selections.newest::<Point>(cx);
9352 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9353 }
9354
9355 fn go_to_hunk_after_position(
9356 &mut self,
9357 snapshot: &DisplaySnapshot,
9358 position: Point,
9359 cx: &mut ViewContext<'_, Editor>,
9360 ) -> Option<MultiBufferDiffHunk> {
9361 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9362 snapshot,
9363 position,
9364 false,
9365 snapshot
9366 .buffer_snapshot
9367 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9368 cx,
9369 ) {
9370 return Some(hunk);
9371 }
9372
9373 let wrapped_point = Point::zero();
9374 self.go_to_next_hunk_in_direction(
9375 snapshot,
9376 wrapped_point,
9377 true,
9378 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9379 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9380 ),
9381 cx,
9382 )
9383 }
9384
9385 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9386 let snapshot = self
9387 .display_map
9388 .update(cx, |display_map, cx| display_map.snapshot(cx));
9389 let selection = self.selections.newest::<Point>(cx);
9390
9391 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9392 }
9393
9394 fn go_to_hunk_before_position(
9395 &mut self,
9396 snapshot: &DisplaySnapshot,
9397 position: Point,
9398 cx: &mut ViewContext<'_, Editor>,
9399 ) -> Option<MultiBufferDiffHunk> {
9400 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9401 snapshot,
9402 position,
9403 false,
9404 snapshot
9405 .buffer_snapshot
9406 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9407 cx,
9408 ) {
9409 return Some(hunk);
9410 }
9411
9412 let wrapped_point = snapshot.buffer_snapshot.max_point();
9413 self.go_to_next_hunk_in_direction(
9414 snapshot,
9415 wrapped_point,
9416 true,
9417 snapshot
9418 .buffer_snapshot
9419 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9420 cx,
9421 )
9422 }
9423
9424 fn go_to_next_hunk_in_direction(
9425 &mut self,
9426 snapshot: &DisplaySnapshot,
9427 initial_point: Point,
9428 is_wrapped: bool,
9429 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9430 cx: &mut ViewContext<Editor>,
9431 ) -> Option<MultiBufferDiffHunk> {
9432 let display_point = initial_point.to_display_point(snapshot);
9433 let mut hunks = hunks
9434 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9435 .filter(|(display_hunk, _)| {
9436 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9437 })
9438 .dedup();
9439
9440 if let Some((display_hunk, hunk)) = hunks.next() {
9441 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9442 let row = display_hunk.start_display_row();
9443 let point = DisplayPoint::new(row, 0);
9444 s.select_display_ranges([point..point]);
9445 });
9446
9447 Some(hunk)
9448 } else {
9449 None
9450 }
9451 }
9452
9453 pub fn go_to_definition(
9454 &mut self,
9455 _: &GoToDefinition,
9456 cx: &mut ViewContext<Self>,
9457 ) -> Task<Result<Navigated>> {
9458 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9459 cx.spawn(|editor, mut cx| async move {
9460 if definition.await? == Navigated::Yes {
9461 return Ok(Navigated::Yes);
9462 }
9463 match editor.update(&mut cx, |editor, cx| {
9464 editor.find_all_references(&FindAllReferences, cx)
9465 })? {
9466 Some(references) => references.await,
9467 None => Ok(Navigated::No),
9468 }
9469 })
9470 }
9471
9472 pub fn go_to_declaration(
9473 &mut self,
9474 _: &GoToDeclaration,
9475 cx: &mut ViewContext<Self>,
9476 ) -> Task<Result<Navigated>> {
9477 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9478 }
9479
9480 pub fn go_to_declaration_split(
9481 &mut self,
9482 _: &GoToDeclaration,
9483 cx: &mut ViewContext<Self>,
9484 ) -> Task<Result<Navigated>> {
9485 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9486 }
9487
9488 pub fn go_to_implementation(
9489 &mut self,
9490 _: &GoToImplementation,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9494 }
9495
9496 pub fn go_to_implementation_split(
9497 &mut self,
9498 _: &GoToImplementationSplit,
9499 cx: &mut ViewContext<Self>,
9500 ) -> Task<Result<Navigated>> {
9501 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9502 }
9503
9504 pub fn go_to_type_definition(
9505 &mut self,
9506 _: &GoToTypeDefinition,
9507 cx: &mut ViewContext<Self>,
9508 ) -> Task<Result<Navigated>> {
9509 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9510 }
9511
9512 pub fn go_to_definition_split(
9513 &mut self,
9514 _: &GoToDefinitionSplit,
9515 cx: &mut ViewContext<Self>,
9516 ) -> Task<Result<Navigated>> {
9517 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9518 }
9519
9520 pub fn go_to_type_definition_split(
9521 &mut self,
9522 _: &GoToTypeDefinitionSplit,
9523 cx: &mut ViewContext<Self>,
9524 ) -> Task<Result<Navigated>> {
9525 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9526 }
9527
9528 fn go_to_definition_of_kind(
9529 &mut self,
9530 kind: GotoDefinitionKind,
9531 split: bool,
9532 cx: &mut ViewContext<Self>,
9533 ) -> Task<Result<Navigated>> {
9534 let Some(workspace) = self.workspace() else {
9535 return Task::ready(Ok(Navigated::No));
9536 };
9537 let buffer = self.buffer.read(cx);
9538 let head = self.selections.newest::<usize>(cx).head();
9539 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9540 text_anchor
9541 } else {
9542 return Task::ready(Ok(Navigated::No));
9543 };
9544
9545 let project = workspace.read(cx).project().clone();
9546 let definitions = project.update(cx, |project, cx| match kind {
9547 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9548 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9549 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9550 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9551 });
9552
9553 cx.spawn(|editor, mut cx| async move {
9554 let definitions = definitions.await?;
9555 let navigated = editor
9556 .update(&mut cx, |editor, cx| {
9557 editor.navigate_to_hover_links(
9558 Some(kind),
9559 definitions
9560 .into_iter()
9561 .filter(|location| {
9562 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9563 })
9564 .map(HoverLink::Text)
9565 .collect::<Vec<_>>(),
9566 split,
9567 cx,
9568 )
9569 })?
9570 .await?;
9571 anyhow::Ok(navigated)
9572 })
9573 }
9574
9575 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9576 let position = self.selections.newest_anchor().head();
9577 let Some((buffer, buffer_position)) =
9578 self.buffer.read(cx).text_anchor_for_position(position, cx)
9579 else {
9580 return;
9581 };
9582
9583 cx.spawn(|editor, mut cx| async move {
9584 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9585 editor.update(&mut cx, |_, cx| {
9586 cx.open_url(&url);
9587 })
9588 } else {
9589 Ok(())
9590 }
9591 })
9592 .detach();
9593 }
9594
9595 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9596 let Some(workspace) = self.workspace() else {
9597 return;
9598 };
9599
9600 let position = self.selections.newest_anchor().head();
9601
9602 let Some((buffer, buffer_position)) =
9603 self.buffer.read(cx).text_anchor_for_position(position, cx)
9604 else {
9605 return;
9606 };
9607
9608 let Some(project) = self.project.clone() else {
9609 return;
9610 };
9611
9612 cx.spawn(|_, mut cx| async move {
9613 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9614
9615 if let Some((_, path)) = result {
9616 workspace
9617 .update(&mut cx, |workspace, cx| {
9618 workspace.open_resolved_path(path, cx)
9619 })?
9620 .await?;
9621 }
9622 anyhow::Ok(())
9623 })
9624 .detach();
9625 }
9626
9627 pub(crate) fn navigate_to_hover_links(
9628 &mut self,
9629 kind: Option<GotoDefinitionKind>,
9630 mut definitions: Vec<HoverLink>,
9631 split: bool,
9632 cx: &mut ViewContext<Editor>,
9633 ) -> Task<Result<Navigated>> {
9634 // If there is one definition, just open it directly
9635 if definitions.len() == 1 {
9636 let definition = definitions.pop().unwrap();
9637
9638 enum TargetTaskResult {
9639 Location(Option<Location>),
9640 AlreadyNavigated,
9641 }
9642
9643 let target_task = match definition {
9644 HoverLink::Text(link) => {
9645 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9646 }
9647 HoverLink::InlayHint(lsp_location, server_id) => {
9648 let computation = self.compute_target_location(lsp_location, server_id, cx);
9649 cx.background_executor().spawn(async move {
9650 let location = computation.await?;
9651 Ok(TargetTaskResult::Location(location))
9652 })
9653 }
9654 HoverLink::Url(url) => {
9655 cx.open_url(&url);
9656 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9657 }
9658 HoverLink::File(path) => {
9659 if let Some(workspace) = self.workspace() {
9660 cx.spawn(|_, mut cx| async move {
9661 workspace
9662 .update(&mut cx, |workspace, cx| {
9663 workspace.open_resolved_path(path, cx)
9664 })?
9665 .await
9666 .map(|_| TargetTaskResult::AlreadyNavigated)
9667 })
9668 } else {
9669 Task::ready(Ok(TargetTaskResult::Location(None)))
9670 }
9671 }
9672 };
9673 cx.spawn(|editor, mut cx| async move {
9674 let target = match target_task.await.context("target resolution task")? {
9675 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9676 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9677 TargetTaskResult::Location(Some(target)) => target,
9678 };
9679
9680 editor.update(&mut cx, |editor, cx| {
9681 let Some(workspace) = editor.workspace() else {
9682 return Navigated::No;
9683 };
9684 let pane = workspace.read(cx).active_pane().clone();
9685
9686 let range = target.range.to_offset(target.buffer.read(cx));
9687 let range = editor.range_for_match(&range);
9688
9689 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9690 let buffer = target.buffer.read(cx);
9691 let range = check_multiline_range(buffer, range);
9692 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9693 s.select_ranges([range]);
9694 });
9695 } else {
9696 cx.window_context().defer(move |cx| {
9697 let target_editor: View<Self> =
9698 workspace.update(cx, |workspace, cx| {
9699 let pane = if split {
9700 workspace.adjacent_pane(cx)
9701 } else {
9702 workspace.active_pane().clone()
9703 };
9704
9705 workspace.open_project_item(
9706 pane,
9707 target.buffer.clone(),
9708 true,
9709 true,
9710 cx,
9711 )
9712 });
9713 target_editor.update(cx, |target_editor, cx| {
9714 // When selecting a definition in a different buffer, disable the nav history
9715 // to avoid creating a history entry at the previous cursor location.
9716 pane.update(cx, |pane, _| pane.disable_history());
9717 let buffer = target.buffer.read(cx);
9718 let range = check_multiline_range(buffer, range);
9719 target_editor.change_selections(
9720 Some(Autoscroll::focused()),
9721 cx,
9722 |s| {
9723 s.select_ranges([range]);
9724 },
9725 );
9726 pane.update(cx, |pane, _| pane.enable_history());
9727 });
9728 });
9729 }
9730 Navigated::Yes
9731 })
9732 })
9733 } else if !definitions.is_empty() {
9734 cx.spawn(|editor, mut cx| async move {
9735 let (title, location_tasks, workspace) = editor
9736 .update(&mut cx, |editor, cx| {
9737 let tab_kind = match kind {
9738 Some(GotoDefinitionKind::Implementation) => "Implementations",
9739 _ => "Definitions",
9740 };
9741 let title = definitions
9742 .iter()
9743 .find_map(|definition| match definition {
9744 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9745 let buffer = origin.buffer.read(cx);
9746 format!(
9747 "{} for {}",
9748 tab_kind,
9749 buffer
9750 .text_for_range(origin.range.clone())
9751 .collect::<String>()
9752 )
9753 }),
9754 HoverLink::InlayHint(_, _) => None,
9755 HoverLink::Url(_) => None,
9756 HoverLink::File(_) => None,
9757 })
9758 .unwrap_or(tab_kind.to_string());
9759 let location_tasks = definitions
9760 .into_iter()
9761 .map(|definition| match definition {
9762 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9763 HoverLink::InlayHint(lsp_location, server_id) => {
9764 editor.compute_target_location(lsp_location, server_id, cx)
9765 }
9766 HoverLink::Url(_) => Task::ready(Ok(None)),
9767 HoverLink::File(_) => Task::ready(Ok(None)),
9768 })
9769 .collect::<Vec<_>>();
9770 (title, location_tasks, editor.workspace().clone())
9771 })
9772 .context("location tasks preparation")?;
9773
9774 let locations = future::join_all(location_tasks)
9775 .await
9776 .into_iter()
9777 .filter_map(|location| location.transpose())
9778 .collect::<Result<_>>()
9779 .context("location tasks")?;
9780
9781 let Some(workspace) = workspace else {
9782 return Ok(Navigated::No);
9783 };
9784 let opened = workspace
9785 .update(&mut cx, |workspace, cx| {
9786 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9787 })
9788 .ok();
9789
9790 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9791 })
9792 } else {
9793 Task::ready(Ok(Navigated::No))
9794 }
9795 }
9796
9797 fn compute_target_location(
9798 &self,
9799 lsp_location: lsp::Location,
9800 server_id: LanguageServerId,
9801 cx: &mut ViewContext<Editor>,
9802 ) -> Task<anyhow::Result<Option<Location>>> {
9803 let Some(project) = self.project.clone() else {
9804 return Task::Ready(Some(Ok(None)));
9805 };
9806
9807 cx.spawn(move |editor, mut cx| async move {
9808 let location_task = editor.update(&mut cx, |editor, cx| {
9809 project.update(cx, |project, cx| {
9810 let language_server_name =
9811 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9812 project
9813 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9814 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9815 });
9816 language_server_name.map(|language_server_name| {
9817 project.open_local_buffer_via_lsp(
9818 lsp_location.uri.clone(),
9819 server_id,
9820 language_server_name,
9821 cx,
9822 )
9823 })
9824 })
9825 })?;
9826 let location = match location_task {
9827 Some(task) => Some({
9828 let target_buffer_handle = task.await.context("open local buffer")?;
9829 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9830 let target_start = target_buffer
9831 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9832 let target_end = target_buffer
9833 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9834 target_buffer.anchor_after(target_start)
9835 ..target_buffer.anchor_before(target_end)
9836 })?;
9837 Location {
9838 buffer: target_buffer_handle,
9839 range,
9840 }
9841 }),
9842 None => None,
9843 };
9844 Ok(location)
9845 })
9846 }
9847
9848 pub fn find_all_references(
9849 &mut self,
9850 _: &FindAllReferences,
9851 cx: &mut ViewContext<Self>,
9852 ) -> Option<Task<Result<Navigated>>> {
9853 let multi_buffer = self.buffer.read(cx);
9854 let selection = self.selections.newest::<usize>(cx);
9855 let head = selection.head();
9856
9857 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9858 let head_anchor = multi_buffer_snapshot.anchor_at(
9859 head,
9860 if head < selection.tail() {
9861 Bias::Right
9862 } else {
9863 Bias::Left
9864 },
9865 );
9866
9867 match self
9868 .find_all_references_task_sources
9869 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9870 {
9871 Ok(_) => {
9872 log::info!(
9873 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9874 );
9875 return None;
9876 }
9877 Err(i) => {
9878 self.find_all_references_task_sources.insert(i, head_anchor);
9879 }
9880 }
9881
9882 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9883 let workspace = self.workspace()?;
9884 let project = workspace.read(cx).project().clone();
9885 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9886 Some(cx.spawn(|editor, mut cx| async move {
9887 let _cleanup = defer({
9888 let mut cx = cx.clone();
9889 move || {
9890 let _ = editor.update(&mut cx, |editor, _| {
9891 if let Ok(i) =
9892 editor
9893 .find_all_references_task_sources
9894 .binary_search_by(|anchor| {
9895 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9896 })
9897 {
9898 editor.find_all_references_task_sources.remove(i);
9899 }
9900 });
9901 }
9902 });
9903
9904 let locations = references.await?;
9905 if locations.is_empty() {
9906 return anyhow::Ok(Navigated::No);
9907 }
9908
9909 workspace.update(&mut cx, |workspace, cx| {
9910 let title = locations
9911 .first()
9912 .as_ref()
9913 .map(|location| {
9914 let buffer = location.buffer.read(cx);
9915 format!(
9916 "References to `{}`",
9917 buffer
9918 .text_for_range(location.range.clone())
9919 .collect::<String>()
9920 )
9921 })
9922 .unwrap();
9923 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9924 Navigated::Yes
9925 })
9926 }))
9927 }
9928
9929 /// Opens a multibuffer with the given project locations in it
9930 pub fn open_locations_in_multibuffer(
9931 workspace: &mut Workspace,
9932 mut locations: Vec<Location>,
9933 title: String,
9934 split: bool,
9935 cx: &mut ViewContext<Workspace>,
9936 ) {
9937 // If there are multiple definitions, open them in a multibuffer
9938 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9939 let mut locations = locations.into_iter().peekable();
9940 let mut ranges_to_highlight = Vec::new();
9941 let capability = workspace.project().read(cx).capability();
9942
9943 let excerpt_buffer = cx.new_model(|cx| {
9944 let mut multibuffer = MultiBuffer::new(capability);
9945 while let Some(location) = locations.next() {
9946 let buffer = location.buffer.read(cx);
9947 let mut ranges_for_buffer = Vec::new();
9948 let range = location.range.to_offset(buffer);
9949 ranges_for_buffer.push(range.clone());
9950
9951 while let Some(next_location) = locations.peek() {
9952 if next_location.buffer == location.buffer {
9953 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9954 locations.next();
9955 } else {
9956 break;
9957 }
9958 }
9959
9960 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9961 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9962 location.buffer.clone(),
9963 ranges_for_buffer,
9964 DEFAULT_MULTIBUFFER_CONTEXT,
9965 cx,
9966 ))
9967 }
9968
9969 multibuffer.with_title(title)
9970 });
9971
9972 let editor = cx.new_view(|cx| {
9973 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9974 });
9975 editor.update(cx, |editor, cx| {
9976 if let Some(first_range) = ranges_to_highlight.first() {
9977 editor.change_selections(None, cx, |selections| {
9978 selections.clear_disjoint();
9979 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9980 });
9981 }
9982 editor.highlight_background::<Self>(
9983 &ranges_to_highlight,
9984 |theme| theme.editor_highlighted_line_background,
9985 cx,
9986 );
9987 });
9988
9989 let item = Box::new(editor);
9990 let item_id = item.item_id();
9991
9992 if split {
9993 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9994 } else {
9995 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9996 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9997 pane.close_current_preview_item(cx)
9998 } else {
9999 None
10000 }
10001 });
10002 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10003 }
10004 workspace.active_pane().update(cx, |pane, cx| {
10005 pane.set_preview_item_id(Some(item_id), cx);
10006 });
10007 }
10008
10009 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10010 use language::ToOffset as _;
10011
10012 let project = self.project.clone()?;
10013 let selection = self.selections.newest_anchor().clone();
10014 let (cursor_buffer, cursor_buffer_position) = self
10015 .buffer
10016 .read(cx)
10017 .text_anchor_for_position(selection.head(), cx)?;
10018 let (tail_buffer, cursor_buffer_position_end) = self
10019 .buffer
10020 .read(cx)
10021 .text_anchor_for_position(selection.tail(), cx)?;
10022 if tail_buffer != cursor_buffer {
10023 return None;
10024 }
10025
10026 let snapshot = cursor_buffer.read(cx).snapshot();
10027 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10028 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10029 let prepare_rename = project.update(cx, |project, cx| {
10030 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10031 });
10032 drop(snapshot);
10033
10034 Some(cx.spawn(|this, mut cx| async move {
10035 let rename_range = if let Some(range) = prepare_rename.await? {
10036 Some(range)
10037 } else {
10038 this.update(&mut cx, |this, cx| {
10039 let buffer = this.buffer.read(cx).snapshot(cx);
10040 let mut buffer_highlights = this
10041 .document_highlights_for_position(selection.head(), &buffer)
10042 .filter(|highlight| {
10043 highlight.start.excerpt_id == selection.head().excerpt_id
10044 && highlight.end.excerpt_id == selection.head().excerpt_id
10045 });
10046 buffer_highlights
10047 .next()
10048 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10049 })?
10050 };
10051 if let Some(rename_range) = rename_range {
10052 this.update(&mut cx, |this, cx| {
10053 let snapshot = cursor_buffer.read(cx).snapshot();
10054 let rename_buffer_range = rename_range.to_offset(&snapshot);
10055 let cursor_offset_in_rename_range =
10056 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10057 let cursor_offset_in_rename_range_end =
10058 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10059
10060 this.take_rename(false, cx);
10061 let buffer = this.buffer.read(cx).read(cx);
10062 let cursor_offset = selection.head().to_offset(&buffer);
10063 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10064 let rename_end = rename_start + rename_buffer_range.len();
10065 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10066 let mut old_highlight_id = None;
10067 let old_name: Arc<str> = buffer
10068 .chunks(rename_start..rename_end, true)
10069 .map(|chunk| {
10070 if old_highlight_id.is_none() {
10071 old_highlight_id = chunk.syntax_highlight_id;
10072 }
10073 chunk.text
10074 })
10075 .collect::<String>()
10076 .into();
10077
10078 drop(buffer);
10079
10080 // Position the selection in the rename editor so that it matches the current selection.
10081 this.show_local_selections = false;
10082 let rename_editor = cx.new_view(|cx| {
10083 let mut editor = Editor::single_line(cx);
10084 editor.buffer.update(cx, |buffer, cx| {
10085 buffer.edit([(0..0, old_name.clone())], None, cx)
10086 });
10087 let rename_selection_range = match cursor_offset_in_rename_range
10088 .cmp(&cursor_offset_in_rename_range_end)
10089 {
10090 Ordering::Equal => {
10091 editor.select_all(&SelectAll, cx);
10092 return editor;
10093 }
10094 Ordering::Less => {
10095 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10096 }
10097 Ordering::Greater => {
10098 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10099 }
10100 };
10101 if rename_selection_range.end > old_name.len() {
10102 editor.select_all(&SelectAll, cx);
10103 } else {
10104 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10105 s.select_ranges([rename_selection_range]);
10106 });
10107 }
10108 editor
10109 });
10110 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10111 if e == &EditorEvent::Focused {
10112 cx.emit(EditorEvent::FocusedIn)
10113 }
10114 })
10115 .detach();
10116
10117 let write_highlights =
10118 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10119 let read_highlights =
10120 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10121 let ranges = write_highlights
10122 .iter()
10123 .flat_map(|(_, ranges)| ranges.iter())
10124 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10125 .cloned()
10126 .collect();
10127
10128 this.highlight_text::<Rename>(
10129 ranges,
10130 HighlightStyle {
10131 fade_out: Some(0.6),
10132 ..Default::default()
10133 },
10134 cx,
10135 );
10136 let rename_focus_handle = rename_editor.focus_handle(cx);
10137 cx.focus(&rename_focus_handle);
10138 let block_id = this.insert_blocks(
10139 [BlockProperties {
10140 style: BlockStyle::Flex,
10141 position: range.start,
10142 height: 1,
10143 render: Box::new({
10144 let rename_editor = rename_editor.clone();
10145 move |cx: &mut BlockContext| {
10146 let mut text_style = cx.editor_style.text.clone();
10147 if let Some(highlight_style) = old_highlight_id
10148 .and_then(|h| h.style(&cx.editor_style.syntax))
10149 {
10150 text_style = text_style.highlight(highlight_style);
10151 }
10152 div()
10153 .pl(cx.anchor_x)
10154 .child(EditorElement::new(
10155 &rename_editor,
10156 EditorStyle {
10157 background: cx.theme().system().transparent,
10158 local_player: cx.editor_style.local_player,
10159 text: text_style,
10160 scrollbar_width: cx.editor_style.scrollbar_width,
10161 syntax: cx.editor_style.syntax.clone(),
10162 status: cx.editor_style.status.clone(),
10163 inlay_hints_style: HighlightStyle {
10164 font_weight: Some(FontWeight::BOLD),
10165 ..make_inlay_hints_style(cx)
10166 },
10167 suggestions_style: HighlightStyle {
10168 color: Some(cx.theme().status().predictive),
10169 ..HighlightStyle::default()
10170 },
10171 ..EditorStyle::default()
10172 },
10173 ))
10174 .into_any_element()
10175 }
10176 }),
10177 disposition: BlockDisposition::Below,
10178 priority: 0,
10179 }],
10180 Some(Autoscroll::fit()),
10181 cx,
10182 )[0];
10183 this.pending_rename = Some(RenameState {
10184 range,
10185 old_name,
10186 editor: rename_editor,
10187 block_id,
10188 });
10189 })?;
10190 }
10191
10192 Ok(())
10193 }))
10194 }
10195
10196 pub fn confirm_rename(
10197 &mut self,
10198 _: &ConfirmRename,
10199 cx: &mut ViewContext<Self>,
10200 ) -> Option<Task<Result<()>>> {
10201 let rename = self.take_rename(false, cx)?;
10202 let workspace = self.workspace()?;
10203 let (start_buffer, start) = self
10204 .buffer
10205 .read(cx)
10206 .text_anchor_for_position(rename.range.start, cx)?;
10207 let (end_buffer, end) = self
10208 .buffer
10209 .read(cx)
10210 .text_anchor_for_position(rename.range.end, cx)?;
10211 if start_buffer != end_buffer {
10212 return None;
10213 }
10214
10215 let buffer = start_buffer;
10216 let range = start..end;
10217 let old_name = rename.old_name;
10218 let new_name = rename.editor.read(cx).text(cx);
10219
10220 let rename = workspace
10221 .read(cx)
10222 .project()
10223 .clone()
10224 .update(cx, |project, cx| {
10225 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10226 });
10227 let workspace = workspace.downgrade();
10228
10229 Some(cx.spawn(|editor, mut cx| async move {
10230 let project_transaction = rename.await?;
10231 Self::open_project_transaction(
10232 &editor,
10233 workspace,
10234 project_transaction,
10235 format!("Rename: {} → {}", old_name, new_name),
10236 cx.clone(),
10237 )
10238 .await?;
10239
10240 editor.update(&mut cx, |editor, cx| {
10241 editor.refresh_document_highlights(cx);
10242 })?;
10243 Ok(())
10244 }))
10245 }
10246
10247 fn take_rename(
10248 &mut self,
10249 moving_cursor: bool,
10250 cx: &mut ViewContext<Self>,
10251 ) -> Option<RenameState> {
10252 let rename = self.pending_rename.take()?;
10253 if rename.editor.focus_handle(cx).is_focused(cx) {
10254 cx.focus(&self.focus_handle);
10255 }
10256
10257 self.remove_blocks(
10258 [rename.block_id].into_iter().collect(),
10259 Some(Autoscroll::fit()),
10260 cx,
10261 );
10262 self.clear_highlights::<Rename>(cx);
10263 self.show_local_selections = true;
10264
10265 if moving_cursor {
10266 let rename_editor = rename.editor.read(cx);
10267 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10268
10269 // Update the selection to match the position of the selection inside
10270 // the rename editor.
10271 let snapshot = self.buffer.read(cx).read(cx);
10272 let rename_range = rename.range.to_offset(&snapshot);
10273 let cursor_in_editor = snapshot
10274 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10275 .min(rename_range.end);
10276 drop(snapshot);
10277
10278 self.change_selections(None, cx, |s| {
10279 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10280 });
10281 } else {
10282 self.refresh_document_highlights(cx);
10283 }
10284
10285 Some(rename)
10286 }
10287
10288 pub fn pending_rename(&self) -> Option<&RenameState> {
10289 self.pending_rename.as_ref()
10290 }
10291
10292 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10293 let project = match &self.project {
10294 Some(project) => project.clone(),
10295 None => return None,
10296 };
10297
10298 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10299 }
10300
10301 fn perform_format(
10302 &mut self,
10303 project: Model<Project>,
10304 trigger: FormatTrigger,
10305 cx: &mut ViewContext<Self>,
10306 ) -> Task<Result<()>> {
10307 let buffer = self.buffer().clone();
10308 let mut buffers = buffer.read(cx).all_buffers();
10309 if trigger == FormatTrigger::Save {
10310 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10311 }
10312
10313 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10314 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10315
10316 cx.spawn(|_, mut cx| async move {
10317 let transaction = futures::select_biased! {
10318 () = timeout => {
10319 log::warn!("timed out waiting for formatting");
10320 None
10321 }
10322 transaction = format.log_err().fuse() => transaction,
10323 };
10324
10325 buffer
10326 .update(&mut cx, |buffer, cx| {
10327 if let Some(transaction) = transaction {
10328 if !buffer.is_singleton() {
10329 buffer.push_transaction(&transaction.0, cx);
10330 }
10331 }
10332
10333 cx.notify();
10334 })
10335 .ok();
10336
10337 Ok(())
10338 })
10339 }
10340
10341 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10342 if let Some(project) = self.project.clone() {
10343 self.buffer.update(cx, |multi_buffer, cx| {
10344 project.update(cx, |project, cx| {
10345 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10346 });
10347 })
10348 }
10349 }
10350
10351 fn cancel_language_server_work(
10352 &mut self,
10353 _: &CancelLanguageServerWork,
10354 cx: &mut ViewContext<Self>,
10355 ) {
10356 if let Some(project) = self.project.clone() {
10357 self.buffer.update(cx, |multi_buffer, cx| {
10358 project.update(cx, |project, cx| {
10359 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10360 });
10361 })
10362 }
10363 }
10364
10365 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10366 cx.show_character_palette();
10367 }
10368
10369 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10370 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10371 let buffer = self.buffer.read(cx).snapshot(cx);
10372 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10373 let is_valid = buffer
10374 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10375 .any(|entry| {
10376 entry.diagnostic.is_primary
10377 && !entry.range.is_empty()
10378 && entry.range.start == primary_range_start
10379 && entry.diagnostic.message == active_diagnostics.primary_message
10380 });
10381
10382 if is_valid != active_diagnostics.is_valid {
10383 active_diagnostics.is_valid = is_valid;
10384 let mut new_styles = HashMap::default();
10385 for (block_id, diagnostic) in &active_diagnostics.blocks {
10386 new_styles.insert(
10387 *block_id,
10388 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10389 );
10390 }
10391 self.display_map.update(cx, |display_map, _cx| {
10392 display_map.replace_blocks(new_styles)
10393 });
10394 }
10395 }
10396 }
10397
10398 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10399 self.dismiss_diagnostics(cx);
10400 let snapshot = self.snapshot(cx);
10401 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10402 let buffer = self.buffer.read(cx).snapshot(cx);
10403
10404 let mut primary_range = None;
10405 let mut primary_message = None;
10406 let mut group_end = Point::zero();
10407 let diagnostic_group = buffer
10408 .diagnostic_group::<MultiBufferPoint>(group_id)
10409 .filter_map(|entry| {
10410 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10411 && (entry.range.start.row == entry.range.end.row
10412 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10413 {
10414 return None;
10415 }
10416 if entry.range.end > group_end {
10417 group_end = entry.range.end;
10418 }
10419 if entry.diagnostic.is_primary {
10420 primary_range = Some(entry.range.clone());
10421 primary_message = Some(entry.diagnostic.message.clone());
10422 }
10423 Some(entry)
10424 })
10425 .collect::<Vec<_>>();
10426 let primary_range = primary_range?;
10427 let primary_message = primary_message?;
10428 let primary_range =
10429 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10430
10431 let blocks = display_map
10432 .insert_blocks(
10433 diagnostic_group.iter().map(|entry| {
10434 let diagnostic = entry.diagnostic.clone();
10435 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10436 BlockProperties {
10437 style: BlockStyle::Fixed,
10438 position: buffer.anchor_after(entry.range.start),
10439 height: message_height,
10440 render: diagnostic_block_renderer(diagnostic, None, true, true),
10441 disposition: BlockDisposition::Below,
10442 priority: 0,
10443 }
10444 }),
10445 cx,
10446 )
10447 .into_iter()
10448 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10449 .collect();
10450
10451 Some(ActiveDiagnosticGroup {
10452 primary_range,
10453 primary_message,
10454 group_id,
10455 blocks,
10456 is_valid: true,
10457 })
10458 });
10459 self.active_diagnostics.is_some()
10460 }
10461
10462 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10463 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10464 self.display_map.update(cx, |display_map, cx| {
10465 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10466 });
10467 cx.notify();
10468 }
10469 }
10470
10471 pub fn set_selections_from_remote(
10472 &mut self,
10473 selections: Vec<Selection<Anchor>>,
10474 pending_selection: Option<Selection<Anchor>>,
10475 cx: &mut ViewContext<Self>,
10476 ) {
10477 let old_cursor_position = self.selections.newest_anchor().head();
10478 self.selections.change_with(cx, |s| {
10479 s.select_anchors(selections);
10480 if let Some(pending_selection) = pending_selection {
10481 s.set_pending(pending_selection, SelectMode::Character);
10482 } else {
10483 s.clear_pending();
10484 }
10485 });
10486 self.selections_did_change(false, &old_cursor_position, true, cx);
10487 }
10488
10489 fn push_to_selection_history(&mut self) {
10490 self.selection_history.push(SelectionHistoryEntry {
10491 selections: self.selections.disjoint_anchors(),
10492 select_next_state: self.select_next_state.clone(),
10493 select_prev_state: self.select_prev_state.clone(),
10494 add_selections_state: self.add_selections_state.clone(),
10495 });
10496 }
10497
10498 pub fn transact(
10499 &mut self,
10500 cx: &mut ViewContext<Self>,
10501 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10502 ) -> Option<TransactionId> {
10503 self.start_transaction_at(Instant::now(), cx);
10504 update(self, cx);
10505 self.end_transaction_at(Instant::now(), cx)
10506 }
10507
10508 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10509 self.end_selection(cx);
10510 if let Some(tx_id) = self
10511 .buffer
10512 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10513 {
10514 self.selection_history
10515 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10516 cx.emit(EditorEvent::TransactionBegun {
10517 transaction_id: tx_id,
10518 })
10519 }
10520 }
10521
10522 fn end_transaction_at(
10523 &mut self,
10524 now: Instant,
10525 cx: &mut ViewContext<Self>,
10526 ) -> Option<TransactionId> {
10527 if let Some(transaction_id) = self
10528 .buffer
10529 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10530 {
10531 if let Some((_, end_selections)) =
10532 self.selection_history.transaction_mut(transaction_id)
10533 {
10534 *end_selections = Some(self.selections.disjoint_anchors());
10535 } else {
10536 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10537 }
10538
10539 cx.emit(EditorEvent::Edited { transaction_id });
10540 Some(transaction_id)
10541 } else {
10542 None
10543 }
10544 }
10545
10546 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10547 let mut fold_ranges = Vec::new();
10548
10549 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10550
10551 let selections = self.selections.all_adjusted(cx);
10552 for selection in selections {
10553 let range = selection.range().sorted();
10554 let buffer_start_row = range.start.row;
10555
10556 for row in (0..=range.end.row).rev() {
10557 if let Some((foldable_range, fold_text)) =
10558 display_map.foldable_range(MultiBufferRow(row))
10559 {
10560 if foldable_range.end.row >= buffer_start_row {
10561 fold_ranges.push((foldable_range, fold_text));
10562 if row <= range.start.row {
10563 break;
10564 }
10565 }
10566 }
10567 }
10568 }
10569
10570 self.fold_ranges(fold_ranges, true, cx);
10571 }
10572
10573 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10574 let buffer_row = fold_at.buffer_row;
10575 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10576
10577 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10578 let autoscroll = self
10579 .selections
10580 .all::<Point>(cx)
10581 .iter()
10582 .any(|selection| fold_range.overlaps(&selection.range()));
10583
10584 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10585 }
10586 }
10587
10588 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10590 let buffer = &display_map.buffer_snapshot;
10591 let selections = self.selections.all::<Point>(cx);
10592 let ranges = selections
10593 .iter()
10594 .map(|s| {
10595 let range = s.display_range(&display_map).sorted();
10596 let mut start = range.start.to_point(&display_map);
10597 let mut end = range.end.to_point(&display_map);
10598 start.column = 0;
10599 end.column = buffer.line_len(MultiBufferRow(end.row));
10600 start..end
10601 })
10602 .collect::<Vec<_>>();
10603
10604 self.unfold_ranges(ranges, true, true, cx);
10605 }
10606
10607 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10609
10610 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10611 ..Point::new(
10612 unfold_at.buffer_row.0,
10613 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10614 );
10615
10616 let autoscroll = self
10617 .selections
10618 .all::<Point>(cx)
10619 .iter()
10620 .any(|selection| selection.range().overlaps(&intersection_range));
10621
10622 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10623 }
10624
10625 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10626 let selections = self.selections.all::<Point>(cx);
10627 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10628 let line_mode = self.selections.line_mode;
10629 let ranges = selections.into_iter().map(|s| {
10630 if line_mode {
10631 let start = Point::new(s.start.row, 0);
10632 let end = Point::new(
10633 s.end.row,
10634 display_map
10635 .buffer_snapshot
10636 .line_len(MultiBufferRow(s.end.row)),
10637 );
10638 (start..end, display_map.fold_placeholder.clone())
10639 } else {
10640 (s.start..s.end, display_map.fold_placeholder.clone())
10641 }
10642 });
10643 self.fold_ranges(ranges, true, cx);
10644 }
10645
10646 pub fn fold_ranges<T: ToOffset + Clone>(
10647 &mut self,
10648 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10649 auto_scroll: bool,
10650 cx: &mut ViewContext<Self>,
10651 ) {
10652 let mut fold_ranges = Vec::new();
10653 let mut buffers_affected = HashMap::default();
10654 let multi_buffer = self.buffer().read(cx);
10655 for (fold_range, fold_text) in ranges {
10656 if let Some((_, buffer, _)) =
10657 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10658 {
10659 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10660 };
10661 fold_ranges.push((fold_range, fold_text));
10662 }
10663
10664 let mut ranges = fold_ranges.into_iter().peekable();
10665 if ranges.peek().is_some() {
10666 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10667
10668 if auto_scroll {
10669 self.request_autoscroll(Autoscroll::fit(), cx);
10670 }
10671
10672 for buffer in buffers_affected.into_values() {
10673 self.sync_expanded_diff_hunks(buffer, cx);
10674 }
10675
10676 cx.notify();
10677
10678 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10679 // Clear diagnostics block when folding a range that contains it.
10680 let snapshot = self.snapshot(cx);
10681 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10682 drop(snapshot);
10683 self.active_diagnostics = Some(active_diagnostics);
10684 self.dismiss_diagnostics(cx);
10685 } else {
10686 self.active_diagnostics = Some(active_diagnostics);
10687 }
10688 }
10689
10690 self.scrollbar_marker_state.dirty = true;
10691 }
10692 }
10693
10694 pub fn unfold_ranges<T: ToOffset + Clone>(
10695 &mut self,
10696 ranges: impl IntoIterator<Item = Range<T>>,
10697 inclusive: bool,
10698 auto_scroll: bool,
10699 cx: &mut ViewContext<Self>,
10700 ) {
10701 let mut unfold_ranges = Vec::new();
10702 let mut buffers_affected = HashMap::default();
10703 let multi_buffer = self.buffer().read(cx);
10704 for range in ranges {
10705 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10706 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10707 };
10708 unfold_ranges.push(range);
10709 }
10710
10711 let mut ranges = unfold_ranges.into_iter().peekable();
10712 if ranges.peek().is_some() {
10713 self.display_map
10714 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10715 if auto_scroll {
10716 self.request_autoscroll(Autoscroll::fit(), cx);
10717 }
10718
10719 for buffer in buffers_affected.into_values() {
10720 self.sync_expanded_diff_hunks(buffer, cx);
10721 }
10722
10723 cx.notify();
10724 self.scrollbar_marker_state.dirty = true;
10725 self.active_indent_guides_state.dirty = true;
10726 }
10727 }
10728
10729 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10730 self.display_map.read(cx).fold_placeholder.clone()
10731 }
10732
10733 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10734 if hovered != self.gutter_hovered {
10735 self.gutter_hovered = hovered;
10736 cx.notify();
10737 }
10738 }
10739
10740 pub fn insert_blocks(
10741 &mut self,
10742 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10743 autoscroll: Option<Autoscroll>,
10744 cx: &mut ViewContext<Self>,
10745 ) -> Vec<CustomBlockId> {
10746 let blocks = self
10747 .display_map
10748 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10749 if let Some(autoscroll) = autoscroll {
10750 self.request_autoscroll(autoscroll, cx);
10751 }
10752 cx.notify();
10753 blocks
10754 }
10755
10756 pub fn resize_blocks(
10757 &mut self,
10758 heights: HashMap<CustomBlockId, u32>,
10759 autoscroll: Option<Autoscroll>,
10760 cx: &mut ViewContext<Self>,
10761 ) {
10762 self.display_map
10763 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10764 if let Some(autoscroll) = autoscroll {
10765 self.request_autoscroll(autoscroll, cx);
10766 }
10767 cx.notify();
10768 }
10769
10770 pub fn replace_blocks(
10771 &mut self,
10772 renderers: HashMap<CustomBlockId, RenderBlock>,
10773 autoscroll: Option<Autoscroll>,
10774 cx: &mut ViewContext<Self>,
10775 ) {
10776 self.display_map
10777 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10778 if let Some(autoscroll) = autoscroll {
10779 self.request_autoscroll(autoscroll, cx);
10780 }
10781 cx.notify();
10782 }
10783
10784 pub fn remove_blocks(
10785 &mut self,
10786 block_ids: HashSet<CustomBlockId>,
10787 autoscroll: Option<Autoscroll>,
10788 cx: &mut ViewContext<Self>,
10789 ) {
10790 self.display_map.update(cx, |display_map, cx| {
10791 display_map.remove_blocks(block_ids, cx)
10792 });
10793 if let Some(autoscroll) = autoscroll {
10794 self.request_autoscroll(autoscroll, cx);
10795 }
10796 cx.notify();
10797 }
10798
10799 pub fn row_for_block(
10800 &self,
10801 block_id: CustomBlockId,
10802 cx: &mut ViewContext<Self>,
10803 ) -> Option<DisplayRow> {
10804 self.display_map
10805 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10806 }
10807
10808 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10809 self.focused_block = Some(focused_block);
10810 }
10811
10812 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10813 self.focused_block.take()
10814 }
10815
10816 pub fn insert_creases(
10817 &mut self,
10818 creases: impl IntoIterator<Item = Crease>,
10819 cx: &mut ViewContext<Self>,
10820 ) -> Vec<CreaseId> {
10821 self.display_map
10822 .update(cx, |map, cx| map.insert_creases(creases, cx))
10823 }
10824
10825 pub fn remove_creases(
10826 &mut self,
10827 ids: impl IntoIterator<Item = CreaseId>,
10828 cx: &mut ViewContext<Self>,
10829 ) {
10830 self.display_map
10831 .update(cx, |map, cx| map.remove_creases(ids, cx));
10832 }
10833
10834 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10835 self.display_map
10836 .update(cx, |map, cx| map.snapshot(cx))
10837 .longest_row()
10838 }
10839
10840 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10841 self.display_map
10842 .update(cx, |map, cx| map.snapshot(cx))
10843 .max_point()
10844 }
10845
10846 pub fn text(&self, cx: &AppContext) -> String {
10847 self.buffer.read(cx).read(cx).text()
10848 }
10849
10850 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10851 let text = self.text(cx);
10852 let text = text.trim();
10853
10854 if text.is_empty() {
10855 return None;
10856 }
10857
10858 Some(text.to_string())
10859 }
10860
10861 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10862 self.transact(cx, |this, cx| {
10863 this.buffer
10864 .read(cx)
10865 .as_singleton()
10866 .expect("you can only call set_text on editors for singleton buffers")
10867 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10868 });
10869 }
10870
10871 pub fn display_text(&self, cx: &mut AppContext) -> String {
10872 self.display_map
10873 .update(cx, |map, cx| map.snapshot(cx))
10874 .text()
10875 }
10876
10877 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10878 let mut wrap_guides = smallvec::smallvec![];
10879
10880 if self.show_wrap_guides == Some(false) {
10881 return wrap_guides;
10882 }
10883
10884 let settings = self.buffer.read(cx).settings_at(0, cx);
10885 if settings.show_wrap_guides {
10886 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10887 wrap_guides.push((soft_wrap as usize, true));
10888 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10889 wrap_guides.push((soft_wrap as usize, true));
10890 }
10891 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10892 }
10893
10894 wrap_guides
10895 }
10896
10897 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10898 let settings = self.buffer.read(cx).settings_at(0, cx);
10899 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10900 match mode {
10901 language_settings::SoftWrap::None => SoftWrap::None,
10902 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10903 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10904 language_settings::SoftWrap::PreferredLineLength => {
10905 SoftWrap::Column(settings.preferred_line_length)
10906 }
10907 language_settings::SoftWrap::Bounded => {
10908 SoftWrap::Bounded(settings.preferred_line_length)
10909 }
10910 }
10911 }
10912
10913 pub fn set_soft_wrap_mode(
10914 &mut self,
10915 mode: language_settings::SoftWrap,
10916 cx: &mut ViewContext<Self>,
10917 ) {
10918 self.soft_wrap_mode_override = Some(mode);
10919 cx.notify();
10920 }
10921
10922 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10923 let rem_size = cx.rem_size();
10924 self.display_map.update(cx, |map, cx| {
10925 map.set_font(
10926 style.text.font(),
10927 style.text.font_size.to_pixels(rem_size),
10928 cx,
10929 )
10930 });
10931 self.style = Some(style);
10932 }
10933
10934 pub fn style(&self) -> Option<&EditorStyle> {
10935 self.style.as_ref()
10936 }
10937
10938 // Called by the element. This method is not designed to be called outside of the editor
10939 // element's layout code because it does not notify when rewrapping is computed synchronously.
10940 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10941 self.display_map
10942 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10943 }
10944
10945 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10946 if self.soft_wrap_mode_override.is_some() {
10947 self.soft_wrap_mode_override.take();
10948 } else {
10949 let soft_wrap = match self.soft_wrap_mode(cx) {
10950 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10951 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10952 language_settings::SoftWrap::PreferLine
10953 }
10954 };
10955 self.soft_wrap_mode_override = Some(soft_wrap);
10956 }
10957 cx.notify();
10958 }
10959
10960 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10961 let Some(workspace) = self.workspace() else {
10962 return;
10963 };
10964 let fs = workspace.read(cx).app_state().fs.clone();
10965 let current_show = TabBarSettings::get_global(cx).show;
10966 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10967 setting.show = Some(!current_show);
10968 });
10969 }
10970
10971 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10972 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10973 self.buffer
10974 .read(cx)
10975 .settings_at(0, cx)
10976 .indent_guides
10977 .enabled
10978 });
10979 self.show_indent_guides = Some(!currently_enabled);
10980 cx.notify();
10981 }
10982
10983 fn should_show_indent_guides(&self) -> Option<bool> {
10984 self.show_indent_guides
10985 }
10986
10987 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10988 let mut editor_settings = EditorSettings::get_global(cx).clone();
10989 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10990 EditorSettings::override_global(editor_settings, cx);
10991 }
10992
10993 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10994 self.use_relative_line_numbers
10995 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10996 }
10997
10998 pub fn toggle_relative_line_numbers(
10999 &mut self,
11000 _: &ToggleRelativeLineNumbers,
11001 cx: &mut ViewContext<Self>,
11002 ) {
11003 let is_relative = self.should_use_relative_line_numbers(cx);
11004 self.set_relative_line_number(Some(!is_relative), cx)
11005 }
11006
11007 pub fn set_relative_line_number(
11008 &mut self,
11009 is_relative: Option<bool>,
11010 cx: &mut ViewContext<Self>,
11011 ) {
11012 self.use_relative_line_numbers = is_relative;
11013 cx.notify();
11014 }
11015
11016 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11017 self.show_gutter = show_gutter;
11018 cx.notify();
11019 }
11020
11021 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11022 self.show_line_numbers = Some(show_line_numbers);
11023 cx.notify();
11024 }
11025
11026 pub fn set_show_git_diff_gutter(
11027 &mut self,
11028 show_git_diff_gutter: bool,
11029 cx: &mut ViewContext<Self>,
11030 ) {
11031 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11032 cx.notify();
11033 }
11034
11035 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11036 self.show_code_actions = Some(show_code_actions);
11037 cx.notify();
11038 }
11039
11040 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11041 self.show_runnables = Some(show_runnables);
11042 cx.notify();
11043 }
11044
11045 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11046 if self.display_map.read(cx).masked != masked {
11047 self.display_map.update(cx, |map, _| map.masked = masked);
11048 }
11049 cx.notify()
11050 }
11051
11052 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11053 self.show_wrap_guides = Some(show_wrap_guides);
11054 cx.notify();
11055 }
11056
11057 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11058 self.show_indent_guides = Some(show_indent_guides);
11059 cx.notify();
11060 }
11061
11062 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11063 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11064 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11065 if let Some(dir) = file.abs_path(cx).parent() {
11066 return Some(dir.to_owned());
11067 }
11068 }
11069
11070 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11071 return Some(project_path.path.to_path_buf());
11072 }
11073 }
11074
11075 None
11076 }
11077
11078 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11079 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11080 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11081 cx.reveal_path(&file.abs_path(cx));
11082 }
11083 }
11084 }
11085
11086 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11087 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11088 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11089 if let Some(path) = file.abs_path(cx).to_str() {
11090 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11091 }
11092 }
11093 }
11094 }
11095
11096 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11097 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11098 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11099 if let Some(path) = file.path().to_str() {
11100 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11101 }
11102 }
11103 }
11104 }
11105
11106 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11107 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11108
11109 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11110 self.start_git_blame(true, cx);
11111 }
11112
11113 cx.notify();
11114 }
11115
11116 pub fn toggle_git_blame_inline(
11117 &mut self,
11118 _: &ToggleGitBlameInline,
11119 cx: &mut ViewContext<Self>,
11120 ) {
11121 self.toggle_git_blame_inline_internal(true, cx);
11122 cx.notify();
11123 }
11124
11125 pub fn git_blame_inline_enabled(&self) -> bool {
11126 self.git_blame_inline_enabled
11127 }
11128
11129 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11130 self.show_selection_menu = self
11131 .show_selection_menu
11132 .map(|show_selections_menu| !show_selections_menu)
11133 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11134
11135 cx.notify();
11136 }
11137
11138 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11139 self.show_selection_menu
11140 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11141 }
11142
11143 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11144 if let Some(project) = self.project.as_ref() {
11145 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11146 return;
11147 };
11148
11149 if buffer.read(cx).file().is_none() {
11150 return;
11151 }
11152
11153 let focused = self.focus_handle(cx).contains_focused(cx);
11154
11155 let project = project.clone();
11156 let blame =
11157 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11158 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11159 self.blame = Some(blame);
11160 }
11161 }
11162
11163 fn toggle_git_blame_inline_internal(
11164 &mut self,
11165 user_triggered: bool,
11166 cx: &mut ViewContext<Self>,
11167 ) {
11168 if self.git_blame_inline_enabled {
11169 self.git_blame_inline_enabled = false;
11170 self.show_git_blame_inline = false;
11171 self.show_git_blame_inline_delay_task.take();
11172 } else {
11173 self.git_blame_inline_enabled = true;
11174 self.start_git_blame_inline(user_triggered, cx);
11175 }
11176
11177 cx.notify();
11178 }
11179
11180 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11181 self.start_git_blame(user_triggered, cx);
11182
11183 if ProjectSettings::get_global(cx)
11184 .git
11185 .inline_blame_delay()
11186 .is_some()
11187 {
11188 self.start_inline_blame_timer(cx);
11189 } else {
11190 self.show_git_blame_inline = true
11191 }
11192 }
11193
11194 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11195 self.blame.as_ref()
11196 }
11197
11198 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11199 self.show_git_blame_gutter && self.has_blame_entries(cx)
11200 }
11201
11202 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11203 self.show_git_blame_inline
11204 && self.focus_handle.is_focused(cx)
11205 && !self.newest_selection_head_on_empty_line(cx)
11206 && self.has_blame_entries(cx)
11207 }
11208
11209 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11210 self.blame()
11211 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11212 }
11213
11214 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11215 let cursor_anchor = self.selections.newest_anchor().head();
11216
11217 let snapshot = self.buffer.read(cx).snapshot(cx);
11218 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11219
11220 snapshot.line_len(buffer_row) == 0
11221 }
11222
11223 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11224 let (path, selection, repo) = maybe!({
11225 let project_handle = self.project.as_ref()?.clone();
11226 let project = project_handle.read(cx);
11227
11228 let selection = self.selections.newest::<Point>(cx);
11229 let selection_range = selection.range();
11230
11231 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11232 (buffer, selection_range.start.row..selection_range.end.row)
11233 } else {
11234 let buffer_ranges = self
11235 .buffer()
11236 .read(cx)
11237 .range_to_buffer_ranges(selection_range, cx);
11238
11239 let (buffer, range, _) = if selection.reversed {
11240 buffer_ranges.first()
11241 } else {
11242 buffer_ranges.last()
11243 }?;
11244
11245 let snapshot = buffer.read(cx).snapshot();
11246 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11247 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11248 (buffer.clone(), selection)
11249 };
11250
11251 let path = buffer
11252 .read(cx)
11253 .file()?
11254 .as_local()?
11255 .path()
11256 .to_str()?
11257 .to_string();
11258 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11259 Some((path, selection, repo))
11260 })
11261 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11262
11263 const REMOTE_NAME: &str = "origin";
11264 let origin_url = repo
11265 .remote_url(REMOTE_NAME)
11266 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11267 let sha = repo
11268 .head_sha()
11269 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11270
11271 let (provider, remote) =
11272 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11273 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11274
11275 Ok(provider.build_permalink(
11276 remote,
11277 BuildPermalinkParams {
11278 sha: &sha,
11279 path: &path,
11280 selection: Some(selection),
11281 },
11282 ))
11283 }
11284
11285 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11286 let permalink = self.get_permalink_to_line(cx);
11287
11288 match permalink {
11289 Ok(permalink) => {
11290 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11291 }
11292 Err(err) => {
11293 let message = format!("Failed to copy permalink: {err}");
11294
11295 Err::<(), anyhow::Error>(err).log_err();
11296
11297 if let Some(workspace) = self.workspace() {
11298 workspace.update(cx, |workspace, cx| {
11299 struct CopyPermalinkToLine;
11300
11301 workspace.show_toast(
11302 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11303 cx,
11304 )
11305 })
11306 }
11307 }
11308 }
11309 }
11310
11311 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11312 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11313 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11314 if let Some(path) = file.path().to_str() {
11315 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11316 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11317 }
11318 }
11319 }
11320 }
11321
11322 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11323 let permalink = self.get_permalink_to_line(cx);
11324
11325 match permalink {
11326 Ok(permalink) => {
11327 cx.open_url(permalink.as_ref());
11328 }
11329 Err(err) => {
11330 let message = format!("Failed to open permalink: {err}");
11331
11332 Err::<(), anyhow::Error>(err).log_err();
11333
11334 if let Some(workspace) = self.workspace() {
11335 workspace.update(cx, |workspace, cx| {
11336 struct OpenPermalinkToLine;
11337
11338 workspace.show_toast(
11339 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11340 cx,
11341 )
11342 })
11343 }
11344 }
11345 }
11346 }
11347
11348 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11349 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11350 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11351 pub fn highlight_rows<T: 'static>(
11352 &mut self,
11353 rows: RangeInclusive<Anchor>,
11354 color: Option<Hsla>,
11355 should_autoscroll: bool,
11356 cx: &mut ViewContext<Self>,
11357 ) {
11358 let snapshot = self.buffer().read(cx).snapshot(cx);
11359 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11360 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11361 highlight
11362 .range
11363 .start()
11364 .cmp(rows.start(), &snapshot)
11365 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11366 });
11367 match (color, existing_highlight_index) {
11368 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11369 ix,
11370 RowHighlight {
11371 index: post_inc(&mut self.highlight_order),
11372 range: rows,
11373 should_autoscroll,
11374 color,
11375 },
11376 ),
11377 (None, Ok(i)) => {
11378 row_highlights.remove(i);
11379 }
11380 }
11381 }
11382
11383 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11384 pub fn clear_row_highlights<T: 'static>(&mut self) {
11385 self.highlighted_rows.remove(&TypeId::of::<T>());
11386 }
11387
11388 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11389 pub fn highlighted_rows<T: 'static>(
11390 &self,
11391 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11392 Some(
11393 self.highlighted_rows
11394 .get(&TypeId::of::<T>())?
11395 .iter()
11396 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11397 )
11398 }
11399
11400 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11401 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11402 /// Allows to ignore certain kinds of highlights.
11403 pub fn highlighted_display_rows(
11404 &mut self,
11405 cx: &mut WindowContext,
11406 ) -> BTreeMap<DisplayRow, Hsla> {
11407 let snapshot = self.snapshot(cx);
11408 let mut used_highlight_orders = HashMap::default();
11409 self.highlighted_rows
11410 .iter()
11411 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11412 .fold(
11413 BTreeMap::<DisplayRow, Hsla>::new(),
11414 |mut unique_rows, highlight| {
11415 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11416 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11417 for row in start_row.0..=end_row.0 {
11418 let used_index =
11419 used_highlight_orders.entry(row).or_insert(highlight.index);
11420 if highlight.index >= *used_index {
11421 *used_index = highlight.index;
11422 match highlight.color {
11423 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11424 None => unique_rows.remove(&DisplayRow(row)),
11425 };
11426 }
11427 }
11428 unique_rows
11429 },
11430 )
11431 }
11432
11433 pub fn highlighted_display_row_for_autoscroll(
11434 &self,
11435 snapshot: &DisplaySnapshot,
11436 ) -> Option<DisplayRow> {
11437 self.highlighted_rows
11438 .values()
11439 .flat_map(|highlighted_rows| highlighted_rows.iter())
11440 .filter_map(|highlight| {
11441 if highlight.color.is_none() || !highlight.should_autoscroll {
11442 return None;
11443 }
11444 Some(highlight.range.start().to_display_point(snapshot).row())
11445 })
11446 .min()
11447 }
11448
11449 pub fn set_search_within_ranges(
11450 &mut self,
11451 ranges: &[Range<Anchor>],
11452 cx: &mut ViewContext<Self>,
11453 ) {
11454 self.highlight_background::<SearchWithinRange>(
11455 ranges,
11456 |colors| colors.editor_document_highlight_read_background,
11457 cx,
11458 )
11459 }
11460
11461 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11462 self.breadcrumb_header = Some(new_header);
11463 }
11464
11465 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11466 self.clear_background_highlights::<SearchWithinRange>(cx);
11467 }
11468
11469 pub fn highlight_background<T: 'static>(
11470 &mut self,
11471 ranges: &[Range<Anchor>],
11472 color_fetcher: fn(&ThemeColors) -> Hsla,
11473 cx: &mut ViewContext<Self>,
11474 ) {
11475 self.background_highlights
11476 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11477 self.scrollbar_marker_state.dirty = true;
11478 cx.notify();
11479 }
11480
11481 pub fn clear_background_highlights<T: 'static>(
11482 &mut self,
11483 cx: &mut ViewContext<Self>,
11484 ) -> Option<BackgroundHighlight> {
11485 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11486 if !text_highlights.1.is_empty() {
11487 self.scrollbar_marker_state.dirty = true;
11488 cx.notify();
11489 }
11490 Some(text_highlights)
11491 }
11492
11493 pub fn highlight_gutter<T: 'static>(
11494 &mut self,
11495 ranges: &[Range<Anchor>],
11496 color_fetcher: fn(&AppContext) -> Hsla,
11497 cx: &mut ViewContext<Self>,
11498 ) {
11499 self.gutter_highlights
11500 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11501 cx.notify();
11502 }
11503
11504 pub fn clear_gutter_highlights<T: 'static>(
11505 &mut self,
11506 cx: &mut ViewContext<Self>,
11507 ) -> Option<GutterHighlight> {
11508 cx.notify();
11509 self.gutter_highlights.remove(&TypeId::of::<T>())
11510 }
11511
11512 #[cfg(feature = "test-support")]
11513 pub fn all_text_background_highlights(
11514 &mut self,
11515 cx: &mut ViewContext<Self>,
11516 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11517 let snapshot = self.snapshot(cx);
11518 let buffer = &snapshot.buffer_snapshot;
11519 let start = buffer.anchor_before(0);
11520 let end = buffer.anchor_after(buffer.len());
11521 let theme = cx.theme().colors();
11522 self.background_highlights_in_range(start..end, &snapshot, theme)
11523 }
11524
11525 #[cfg(feature = "test-support")]
11526 pub fn search_background_highlights(
11527 &mut self,
11528 cx: &mut ViewContext<Self>,
11529 ) -> Vec<Range<Point>> {
11530 let snapshot = self.buffer().read(cx).snapshot(cx);
11531
11532 let highlights = self
11533 .background_highlights
11534 .get(&TypeId::of::<items::BufferSearchHighlights>());
11535
11536 if let Some((_color, ranges)) = highlights {
11537 ranges
11538 .iter()
11539 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11540 .collect_vec()
11541 } else {
11542 vec![]
11543 }
11544 }
11545
11546 fn document_highlights_for_position<'a>(
11547 &'a self,
11548 position: Anchor,
11549 buffer: &'a MultiBufferSnapshot,
11550 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11551 let read_highlights = self
11552 .background_highlights
11553 .get(&TypeId::of::<DocumentHighlightRead>())
11554 .map(|h| &h.1);
11555 let write_highlights = self
11556 .background_highlights
11557 .get(&TypeId::of::<DocumentHighlightWrite>())
11558 .map(|h| &h.1);
11559 let left_position = position.bias_left(buffer);
11560 let right_position = position.bias_right(buffer);
11561 read_highlights
11562 .into_iter()
11563 .chain(write_highlights)
11564 .flat_map(move |ranges| {
11565 let start_ix = match ranges.binary_search_by(|probe| {
11566 let cmp = probe.end.cmp(&left_position, buffer);
11567 if cmp.is_ge() {
11568 Ordering::Greater
11569 } else {
11570 Ordering::Less
11571 }
11572 }) {
11573 Ok(i) | Err(i) => i,
11574 };
11575
11576 ranges[start_ix..]
11577 .iter()
11578 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11579 })
11580 }
11581
11582 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11583 self.background_highlights
11584 .get(&TypeId::of::<T>())
11585 .map_or(false, |(_, highlights)| !highlights.is_empty())
11586 }
11587
11588 pub fn background_highlights_in_range(
11589 &self,
11590 search_range: Range<Anchor>,
11591 display_snapshot: &DisplaySnapshot,
11592 theme: &ThemeColors,
11593 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11594 let mut results = Vec::new();
11595 for (color_fetcher, ranges) in self.background_highlights.values() {
11596 let color = color_fetcher(theme);
11597 let start_ix = match ranges.binary_search_by(|probe| {
11598 let cmp = probe
11599 .end
11600 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11601 if cmp.is_gt() {
11602 Ordering::Greater
11603 } else {
11604 Ordering::Less
11605 }
11606 }) {
11607 Ok(i) | Err(i) => i,
11608 };
11609 for range in &ranges[start_ix..] {
11610 if range
11611 .start
11612 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11613 .is_ge()
11614 {
11615 break;
11616 }
11617
11618 let start = range.start.to_display_point(display_snapshot);
11619 let end = range.end.to_display_point(display_snapshot);
11620 results.push((start..end, color))
11621 }
11622 }
11623 results
11624 }
11625
11626 pub fn background_highlight_row_ranges<T: 'static>(
11627 &self,
11628 search_range: Range<Anchor>,
11629 display_snapshot: &DisplaySnapshot,
11630 count: usize,
11631 ) -> Vec<RangeInclusive<DisplayPoint>> {
11632 let mut results = Vec::new();
11633 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11634 return vec![];
11635 };
11636
11637 let start_ix = match ranges.binary_search_by(|probe| {
11638 let cmp = probe
11639 .end
11640 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11641 if cmp.is_gt() {
11642 Ordering::Greater
11643 } else {
11644 Ordering::Less
11645 }
11646 }) {
11647 Ok(i) | Err(i) => i,
11648 };
11649 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11650 if let (Some(start_display), Some(end_display)) = (start, end) {
11651 results.push(
11652 start_display.to_display_point(display_snapshot)
11653 ..=end_display.to_display_point(display_snapshot),
11654 );
11655 }
11656 };
11657 let mut start_row: Option<Point> = None;
11658 let mut end_row: Option<Point> = None;
11659 if ranges.len() > count {
11660 return Vec::new();
11661 }
11662 for range in &ranges[start_ix..] {
11663 if range
11664 .start
11665 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11666 .is_ge()
11667 {
11668 break;
11669 }
11670 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11671 if let Some(current_row) = &end_row {
11672 if end.row == current_row.row {
11673 continue;
11674 }
11675 }
11676 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11677 if start_row.is_none() {
11678 assert_eq!(end_row, None);
11679 start_row = Some(start);
11680 end_row = Some(end);
11681 continue;
11682 }
11683 if let Some(current_end) = end_row.as_mut() {
11684 if start.row > current_end.row + 1 {
11685 push_region(start_row, end_row);
11686 start_row = Some(start);
11687 end_row = Some(end);
11688 } else {
11689 // Merge two hunks.
11690 *current_end = end;
11691 }
11692 } else {
11693 unreachable!();
11694 }
11695 }
11696 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11697 push_region(start_row, end_row);
11698 results
11699 }
11700
11701 pub fn gutter_highlights_in_range(
11702 &self,
11703 search_range: Range<Anchor>,
11704 display_snapshot: &DisplaySnapshot,
11705 cx: &AppContext,
11706 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11707 let mut results = Vec::new();
11708 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11709 let color = color_fetcher(cx);
11710 let start_ix = match ranges.binary_search_by(|probe| {
11711 let cmp = probe
11712 .end
11713 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11714 if cmp.is_gt() {
11715 Ordering::Greater
11716 } else {
11717 Ordering::Less
11718 }
11719 }) {
11720 Ok(i) | Err(i) => i,
11721 };
11722 for range in &ranges[start_ix..] {
11723 if range
11724 .start
11725 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11726 .is_ge()
11727 {
11728 break;
11729 }
11730
11731 let start = range.start.to_display_point(display_snapshot);
11732 let end = range.end.to_display_point(display_snapshot);
11733 results.push((start..end, color))
11734 }
11735 }
11736 results
11737 }
11738
11739 /// Get the text ranges corresponding to the redaction query
11740 pub fn redacted_ranges(
11741 &self,
11742 search_range: Range<Anchor>,
11743 display_snapshot: &DisplaySnapshot,
11744 cx: &WindowContext,
11745 ) -> Vec<Range<DisplayPoint>> {
11746 display_snapshot
11747 .buffer_snapshot
11748 .redacted_ranges(search_range, |file| {
11749 if let Some(file) = file {
11750 file.is_private()
11751 && EditorSettings::get(
11752 Some(SettingsLocation {
11753 worktree_id: file.worktree_id(cx),
11754 path: file.path().as_ref(),
11755 }),
11756 cx,
11757 )
11758 .redact_private_values
11759 } else {
11760 false
11761 }
11762 })
11763 .map(|range| {
11764 range.start.to_display_point(display_snapshot)
11765 ..range.end.to_display_point(display_snapshot)
11766 })
11767 .collect()
11768 }
11769
11770 pub fn highlight_text<T: 'static>(
11771 &mut self,
11772 ranges: Vec<Range<Anchor>>,
11773 style: HighlightStyle,
11774 cx: &mut ViewContext<Self>,
11775 ) {
11776 self.display_map.update(cx, |map, _| {
11777 map.highlight_text(TypeId::of::<T>(), ranges, style)
11778 });
11779 cx.notify();
11780 }
11781
11782 pub(crate) fn highlight_inlays<T: 'static>(
11783 &mut self,
11784 highlights: Vec<InlayHighlight>,
11785 style: HighlightStyle,
11786 cx: &mut ViewContext<Self>,
11787 ) {
11788 self.display_map.update(cx, |map, _| {
11789 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11790 });
11791 cx.notify();
11792 }
11793
11794 pub fn text_highlights<'a, T: 'static>(
11795 &'a self,
11796 cx: &'a AppContext,
11797 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11798 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11799 }
11800
11801 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11802 let cleared = self
11803 .display_map
11804 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11805 if cleared {
11806 cx.notify();
11807 }
11808 }
11809
11810 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11811 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11812 && self.focus_handle.is_focused(cx)
11813 }
11814
11815 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11816 self.show_cursor_when_unfocused = is_enabled;
11817 cx.notify();
11818 }
11819
11820 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11821 cx.notify();
11822 }
11823
11824 fn on_buffer_event(
11825 &mut self,
11826 multibuffer: Model<MultiBuffer>,
11827 event: &multi_buffer::Event,
11828 cx: &mut ViewContext<Self>,
11829 ) {
11830 match event {
11831 multi_buffer::Event::Edited {
11832 singleton_buffer_edited,
11833 } => {
11834 self.scrollbar_marker_state.dirty = true;
11835 self.active_indent_guides_state.dirty = true;
11836 self.refresh_active_diagnostics(cx);
11837 self.refresh_code_actions(cx);
11838 if self.has_active_inline_completion(cx) {
11839 self.update_visible_inline_completion(cx);
11840 }
11841 cx.emit(EditorEvent::BufferEdited);
11842 cx.emit(SearchEvent::MatchesInvalidated);
11843 if *singleton_buffer_edited {
11844 if let Some(project) = &self.project {
11845 let project = project.read(cx);
11846 #[allow(clippy::mutable_key_type)]
11847 let languages_affected = multibuffer
11848 .read(cx)
11849 .all_buffers()
11850 .into_iter()
11851 .filter_map(|buffer| {
11852 let buffer = buffer.read(cx);
11853 let language = buffer.language()?;
11854 if project.is_local()
11855 && project.language_servers_for_buffer(buffer, cx).count() == 0
11856 {
11857 None
11858 } else {
11859 Some(language)
11860 }
11861 })
11862 .cloned()
11863 .collect::<HashSet<_>>();
11864 if !languages_affected.is_empty() {
11865 self.refresh_inlay_hints(
11866 InlayHintRefreshReason::BufferEdited(languages_affected),
11867 cx,
11868 );
11869 }
11870 }
11871 }
11872
11873 let Some(project) = &self.project else { return };
11874 let telemetry = project.read(cx).client().telemetry().clone();
11875 refresh_linked_ranges(self, cx);
11876 telemetry.log_edit_event("editor");
11877 }
11878 multi_buffer::Event::ExcerptsAdded {
11879 buffer,
11880 predecessor,
11881 excerpts,
11882 } => {
11883 self.tasks_update_task = Some(self.refresh_runnables(cx));
11884 cx.emit(EditorEvent::ExcerptsAdded {
11885 buffer: buffer.clone(),
11886 predecessor: *predecessor,
11887 excerpts: excerpts.clone(),
11888 });
11889 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11890 }
11891 multi_buffer::Event::ExcerptsRemoved { ids } => {
11892 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11893 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11894 }
11895 multi_buffer::Event::ExcerptsEdited { ids } => {
11896 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11897 }
11898 multi_buffer::Event::ExcerptsExpanded { ids } => {
11899 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11900 }
11901 multi_buffer::Event::Reparsed(buffer_id) => {
11902 self.tasks_update_task = Some(self.refresh_runnables(cx));
11903
11904 cx.emit(EditorEvent::Reparsed(*buffer_id));
11905 }
11906 multi_buffer::Event::LanguageChanged(buffer_id) => {
11907 linked_editing_ranges::refresh_linked_ranges(self, cx);
11908 cx.emit(EditorEvent::Reparsed(*buffer_id));
11909 cx.notify();
11910 }
11911 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11912 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11913 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11914 cx.emit(EditorEvent::TitleChanged)
11915 }
11916 multi_buffer::Event::DiffBaseChanged => {
11917 self.scrollbar_marker_state.dirty = true;
11918 cx.emit(EditorEvent::DiffBaseChanged);
11919 cx.notify();
11920 }
11921 multi_buffer::Event::DiffUpdated { buffer } => {
11922 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11923 cx.notify();
11924 }
11925 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11926 multi_buffer::Event::DiagnosticsUpdated => {
11927 self.refresh_active_diagnostics(cx);
11928 self.scrollbar_marker_state.dirty = true;
11929 cx.notify();
11930 }
11931 _ => {}
11932 };
11933 }
11934
11935 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11936 cx.notify();
11937 }
11938
11939 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11940 self.tasks_update_task = Some(self.refresh_runnables(cx));
11941 self.refresh_inline_completion(true, false, cx);
11942 self.refresh_inlay_hints(
11943 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11944 self.selections.newest_anchor().head(),
11945 &self.buffer.read(cx).snapshot(cx),
11946 cx,
11947 )),
11948 cx,
11949 );
11950
11951 let old_cursor_shape = self.cursor_shape;
11952
11953 {
11954 let editor_settings = EditorSettings::get_global(cx);
11955 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11956 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11957 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
11958 }
11959
11960 if old_cursor_shape != self.cursor_shape {
11961 cx.emit(EditorEvent::CursorShapeChanged);
11962 }
11963
11964 let project_settings = ProjectSettings::get_global(cx);
11965 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11966
11967 if self.mode == EditorMode::Full {
11968 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11969 if self.git_blame_inline_enabled != inline_blame_enabled {
11970 self.toggle_git_blame_inline_internal(false, cx);
11971 }
11972 }
11973
11974 cx.notify();
11975 }
11976
11977 pub fn set_searchable(&mut self, searchable: bool) {
11978 self.searchable = searchable;
11979 }
11980
11981 pub fn searchable(&self) -> bool {
11982 self.searchable
11983 }
11984
11985 fn open_proposed_changes_editor(
11986 &mut self,
11987 _: &OpenProposedChangesEditor,
11988 cx: &mut ViewContext<Self>,
11989 ) {
11990 let Some(workspace) = self.workspace() else {
11991 cx.propagate();
11992 return;
11993 };
11994
11995 let buffer = self.buffer.read(cx);
11996 let mut new_selections_by_buffer = HashMap::default();
11997 for selection in self.selections.all::<usize>(cx) {
11998 for (buffer, mut range, _) in
11999 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12000 {
12001 if selection.reversed {
12002 mem::swap(&mut range.start, &mut range.end);
12003 }
12004 let mut range = range.to_point(buffer.read(cx));
12005 range.start.column = 0;
12006 range.end.column = buffer.read(cx).line_len(range.end.row);
12007 new_selections_by_buffer
12008 .entry(buffer)
12009 .or_insert(Vec::new())
12010 .push(range)
12011 }
12012 }
12013
12014 let proposed_changes_buffers = new_selections_by_buffer
12015 .into_iter()
12016 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12017 .collect::<Vec<_>>();
12018 let proposed_changes_editor = cx.new_view(|cx| {
12019 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12020 });
12021
12022 cx.window_context().defer(move |cx| {
12023 workspace.update(cx, |workspace, cx| {
12024 workspace.active_pane().update(cx, |pane, cx| {
12025 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12026 });
12027 });
12028 });
12029 }
12030
12031 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12032 self.open_excerpts_common(true, cx)
12033 }
12034
12035 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12036 self.open_excerpts_common(false, cx)
12037 }
12038
12039 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12040 let buffer = self.buffer.read(cx);
12041 if buffer.is_singleton() {
12042 cx.propagate();
12043 return;
12044 }
12045
12046 let Some(workspace) = self.workspace() else {
12047 cx.propagate();
12048 return;
12049 };
12050
12051 let mut new_selections_by_buffer = HashMap::default();
12052 for selection in self.selections.all::<usize>(cx) {
12053 for (buffer, mut range, _) in
12054 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12055 {
12056 if selection.reversed {
12057 mem::swap(&mut range.start, &mut range.end);
12058 }
12059 new_selections_by_buffer
12060 .entry(buffer)
12061 .or_insert(Vec::new())
12062 .push(range)
12063 }
12064 }
12065
12066 // We defer the pane interaction because we ourselves are a workspace item
12067 // and activating a new item causes the pane to call a method on us reentrantly,
12068 // which panics if we're on the stack.
12069 cx.window_context().defer(move |cx| {
12070 workspace.update(cx, |workspace, cx| {
12071 let pane = if split {
12072 workspace.adjacent_pane(cx)
12073 } else {
12074 workspace.active_pane().clone()
12075 };
12076
12077 for (buffer, ranges) in new_selections_by_buffer {
12078 let editor =
12079 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12080 editor.update(cx, |editor, cx| {
12081 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12082 s.select_ranges(ranges);
12083 });
12084 });
12085 }
12086 })
12087 });
12088 }
12089
12090 fn jump(
12091 &mut self,
12092 path: ProjectPath,
12093 position: Point,
12094 anchor: language::Anchor,
12095 offset_from_top: u32,
12096 cx: &mut ViewContext<Self>,
12097 ) {
12098 let workspace = self.workspace();
12099 cx.spawn(|_, mut cx| async move {
12100 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12101 let editor = workspace.update(&mut cx, |workspace, cx| {
12102 // Reset the preview item id before opening the new item
12103 workspace.active_pane().update(cx, |pane, cx| {
12104 pane.set_preview_item_id(None, cx);
12105 });
12106 workspace.open_path_preview(path, None, true, true, cx)
12107 })?;
12108 let editor = editor
12109 .await?
12110 .downcast::<Editor>()
12111 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12112 .downgrade();
12113 editor.update(&mut cx, |editor, cx| {
12114 let buffer = editor
12115 .buffer()
12116 .read(cx)
12117 .as_singleton()
12118 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12119 let buffer = buffer.read(cx);
12120 let cursor = if buffer.can_resolve(&anchor) {
12121 language::ToPoint::to_point(&anchor, buffer)
12122 } else {
12123 buffer.clip_point(position, Bias::Left)
12124 };
12125
12126 let nav_history = editor.nav_history.take();
12127 editor.change_selections(
12128 Some(Autoscroll::top_relative(offset_from_top as usize)),
12129 cx,
12130 |s| {
12131 s.select_ranges([cursor..cursor]);
12132 },
12133 );
12134 editor.nav_history = nav_history;
12135
12136 anyhow::Ok(())
12137 })??;
12138
12139 anyhow::Ok(())
12140 })
12141 .detach_and_log_err(cx);
12142 }
12143
12144 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12145 let snapshot = self.buffer.read(cx).read(cx);
12146 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12147 Some(
12148 ranges
12149 .iter()
12150 .map(move |range| {
12151 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12152 })
12153 .collect(),
12154 )
12155 }
12156
12157 fn selection_replacement_ranges(
12158 &self,
12159 range: Range<OffsetUtf16>,
12160 cx: &AppContext,
12161 ) -> Vec<Range<OffsetUtf16>> {
12162 let selections = self.selections.all::<OffsetUtf16>(cx);
12163 let newest_selection = selections
12164 .iter()
12165 .max_by_key(|selection| selection.id)
12166 .unwrap();
12167 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12168 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12169 let snapshot = self.buffer.read(cx).read(cx);
12170 selections
12171 .into_iter()
12172 .map(|mut selection| {
12173 selection.start.0 =
12174 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12175 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12176 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12177 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12178 })
12179 .collect()
12180 }
12181
12182 fn report_editor_event(
12183 &self,
12184 operation: &'static str,
12185 file_extension: Option<String>,
12186 cx: &AppContext,
12187 ) {
12188 if cfg!(any(test, feature = "test-support")) {
12189 return;
12190 }
12191
12192 let Some(project) = &self.project else { return };
12193
12194 // If None, we are in a file without an extension
12195 let file = self
12196 .buffer
12197 .read(cx)
12198 .as_singleton()
12199 .and_then(|b| b.read(cx).file());
12200 let file_extension = file_extension.or(file
12201 .as_ref()
12202 .and_then(|file| Path::new(file.file_name(cx)).extension())
12203 .and_then(|e| e.to_str())
12204 .map(|a| a.to_string()));
12205
12206 let vim_mode = cx
12207 .global::<SettingsStore>()
12208 .raw_user_settings()
12209 .get("vim_mode")
12210 == Some(&serde_json::Value::Bool(true));
12211
12212 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12213 == language::language_settings::InlineCompletionProvider::Copilot;
12214 let copilot_enabled_for_language = self
12215 .buffer
12216 .read(cx)
12217 .settings_at(0, cx)
12218 .show_inline_completions;
12219
12220 let telemetry = project.read(cx).client().telemetry().clone();
12221 telemetry.report_editor_event(
12222 file_extension,
12223 vim_mode,
12224 operation,
12225 copilot_enabled,
12226 copilot_enabled_for_language,
12227 )
12228 }
12229
12230 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12231 /// with each line being an array of {text, highlight} objects.
12232 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12233 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12234 return;
12235 };
12236
12237 #[derive(Serialize)]
12238 struct Chunk<'a> {
12239 text: String,
12240 highlight: Option<&'a str>,
12241 }
12242
12243 let snapshot = buffer.read(cx).snapshot();
12244 let range = self
12245 .selected_text_range(false, cx)
12246 .and_then(|selection| {
12247 if selection.range.is_empty() {
12248 None
12249 } else {
12250 Some(selection.range)
12251 }
12252 })
12253 .unwrap_or_else(|| 0..snapshot.len());
12254
12255 let chunks = snapshot.chunks(range, true);
12256 let mut lines = Vec::new();
12257 let mut line: VecDeque<Chunk> = VecDeque::new();
12258
12259 let Some(style) = self.style.as_ref() else {
12260 return;
12261 };
12262
12263 for chunk in chunks {
12264 let highlight = chunk
12265 .syntax_highlight_id
12266 .and_then(|id| id.name(&style.syntax));
12267 let mut chunk_lines = chunk.text.split('\n').peekable();
12268 while let Some(text) = chunk_lines.next() {
12269 let mut merged_with_last_token = false;
12270 if let Some(last_token) = line.back_mut() {
12271 if last_token.highlight == highlight {
12272 last_token.text.push_str(text);
12273 merged_with_last_token = true;
12274 }
12275 }
12276
12277 if !merged_with_last_token {
12278 line.push_back(Chunk {
12279 text: text.into(),
12280 highlight,
12281 });
12282 }
12283
12284 if chunk_lines.peek().is_some() {
12285 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12286 line.pop_front();
12287 }
12288 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12289 line.pop_back();
12290 }
12291
12292 lines.push(mem::take(&mut line));
12293 }
12294 }
12295 }
12296
12297 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12298 return;
12299 };
12300 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12301 }
12302
12303 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12304 &self.inlay_hint_cache
12305 }
12306
12307 pub fn replay_insert_event(
12308 &mut self,
12309 text: &str,
12310 relative_utf16_range: Option<Range<isize>>,
12311 cx: &mut ViewContext<Self>,
12312 ) {
12313 if !self.input_enabled {
12314 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12315 return;
12316 }
12317 if let Some(relative_utf16_range) = relative_utf16_range {
12318 let selections = self.selections.all::<OffsetUtf16>(cx);
12319 self.change_selections(None, cx, |s| {
12320 let new_ranges = selections.into_iter().map(|range| {
12321 let start = OffsetUtf16(
12322 range
12323 .head()
12324 .0
12325 .saturating_add_signed(relative_utf16_range.start),
12326 );
12327 let end = OffsetUtf16(
12328 range
12329 .head()
12330 .0
12331 .saturating_add_signed(relative_utf16_range.end),
12332 );
12333 start..end
12334 });
12335 s.select_ranges(new_ranges);
12336 });
12337 }
12338
12339 self.handle_input(text, cx);
12340 }
12341
12342 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12343 let Some(project) = self.project.as_ref() else {
12344 return false;
12345 };
12346 let project = project.read(cx);
12347
12348 let mut supports = false;
12349 self.buffer().read(cx).for_each_buffer(|buffer| {
12350 if !supports {
12351 supports = project
12352 .language_servers_for_buffer(buffer.read(cx), cx)
12353 .any(
12354 |(_, server)| match server.capabilities().inlay_hint_provider {
12355 Some(lsp::OneOf::Left(enabled)) => enabled,
12356 Some(lsp::OneOf::Right(_)) => true,
12357 None => false,
12358 },
12359 )
12360 }
12361 });
12362 supports
12363 }
12364
12365 pub fn focus(&self, cx: &mut WindowContext) {
12366 cx.focus(&self.focus_handle)
12367 }
12368
12369 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12370 self.focus_handle.is_focused(cx)
12371 }
12372
12373 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12374 cx.emit(EditorEvent::Focused);
12375
12376 if let Some(descendant) = self
12377 .last_focused_descendant
12378 .take()
12379 .and_then(|descendant| descendant.upgrade())
12380 {
12381 cx.focus(&descendant);
12382 } else {
12383 if let Some(blame) = self.blame.as_ref() {
12384 blame.update(cx, GitBlame::focus)
12385 }
12386
12387 self.blink_manager.update(cx, BlinkManager::enable);
12388 self.show_cursor_names(cx);
12389 self.buffer.update(cx, |buffer, cx| {
12390 buffer.finalize_last_transaction(cx);
12391 if self.leader_peer_id.is_none() {
12392 buffer.set_active_selections(
12393 &self.selections.disjoint_anchors(),
12394 self.selections.line_mode,
12395 self.cursor_shape,
12396 cx,
12397 );
12398 }
12399 });
12400 }
12401 }
12402
12403 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12404 cx.emit(EditorEvent::FocusedIn)
12405 }
12406
12407 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12408 if event.blurred != self.focus_handle {
12409 self.last_focused_descendant = Some(event.blurred);
12410 }
12411 }
12412
12413 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12414 self.blink_manager.update(cx, BlinkManager::disable);
12415 self.buffer
12416 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12417
12418 if let Some(blame) = self.blame.as_ref() {
12419 blame.update(cx, GitBlame::blur)
12420 }
12421 if !self.hover_state.focused(cx) {
12422 hide_hover(self, cx);
12423 }
12424
12425 self.hide_context_menu(cx);
12426 cx.emit(EditorEvent::Blurred);
12427 cx.notify();
12428 }
12429
12430 pub fn register_action<A: Action>(
12431 &mut self,
12432 listener: impl Fn(&A, &mut WindowContext) + 'static,
12433 ) -> Subscription {
12434 let id = self.next_editor_action_id.post_inc();
12435 let listener = Arc::new(listener);
12436 self.editor_actions.borrow_mut().insert(
12437 id,
12438 Box::new(move |cx| {
12439 let cx = cx.window_context();
12440 let listener = listener.clone();
12441 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12442 let action = action.downcast_ref().unwrap();
12443 if phase == DispatchPhase::Bubble {
12444 listener(action, cx)
12445 }
12446 })
12447 }),
12448 );
12449
12450 let editor_actions = self.editor_actions.clone();
12451 Subscription::new(move || {
12452 editor_actions.borrow_mut().remove(&id);
12453 })
12454 }
12455
12456 pub fn file_header_size(&self) -> u32 {
12457 self.file_header_size
12458 }
12459
12460 pub fn revert(
12461 &mut self,
12462 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12463 cx: &mut ViewContext<Self>,
12464 ) {
12465 self.buffer().update(cx, |multi_buffer, cx| {
12466 for (buffer_id, changes) in revert_changes {
12467 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12468 buffer.update(cx, |buffer, cx| {
12469 buffer.edit(
12470 changes.into_iter().map(|(range, text)| {
12471 (range, text.to_string().map(Arc::<str>::from))
12472 }),
12473 None,
12474 cx,
12475 );
12476 });
12477 }
12478 }
12479 });
12480 self.change_selections(None, cx, |selections| selections.refresh());
12481 }
12482
12483 pub fn to_pixel_point(
12484 &mut self,
12485 source: multi_buffer::Anchor,
12486 editor_snapshot: &EditorSnapshot,
12487 cx: &mut ViewContext<Self>,
12488 ) -> Option<gpui::Point<Pixels>> {
12489 let source_point = source.to_display_point(editor_snapshot);
12490 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12491 }
12492
12493 pub fn display_to_pixel_point(
12494 &mut self,
12495 source: DisplayPoint,
12496 editor_snapshot: &EditorSnapshot,
12497 cx: &mut ViewContext<Self>,
12498 ) -> Option<gpui::Point<Pixels>> {
12499 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12500 let text_layout_details = self.text_layout_details(cx);
12501 let scroll_top = text_layout_details
12502 .scroll_anchor
12503 .scroll_position(editor_snapshot)
12504 .y;
12505
12506 if source.row().as_f32() < scroll_top.floor() {
12507 return None;
12508 }
12509 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12510 let source_y = line_height * (source.row().as_f32() - scroll_top);
12511 Some(gpui::Point::new(source_x, source_y))
12512 }
12513
12514 pub fn has_active_completions_menu(&self) -> bool {
12515 self.context_menu.read().as_ref().map_or(false, |menu| {
12516 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12517 })
12518 }
12519
12520 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12521 self.addons
12522 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12523 }
12524
12525 pub fn unregister_addon<T: Addon>(&mut self) {
12526 self.addons.remove(&std::any::TypeId::of::<T>());
12527 }
12528
12529 pub fn addon<T: Addon>(&self) -> Option<&T> {
12530 let type_id = std::any::TypeId::of::<T>();
12531 self.addons
12532 .get(&type_id)
12533 .and_then(|item| item.to_any().downcast_ref::<T>())
12534 }
12535}
12536
12537fn hunks_for_selections(
12538 multi_buffer_snapshot: &MultiBufferSnapshot,
12539 selections: &[Selection<Anchor>],
12540) -> Vec<MultiBufferDiffHunk> {
12541 let buffer_rows_for_selections = selections.iter().map(|selection| {
12542 let head = selection.head();
12543 let tail = selection.tail();
12544 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12545 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12546 if start > end {
12547 end..start
12548 } else {
12549 start..end
12550 }
12551 });
12552
12553 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12554}
12555
12556pub fn hunks_for_rows(
12557 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12558 multi_buffer_snapshot: &MultiBufferSnapshot,
12559) -> Vec<MultiBufferDiffHunk> {
12560 let mut hunks = Vec::new();
12561 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12562 HashMap::default();
12563 for selected_multi_buffer_rows in rows {
12564 let query_rows =
12565 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12566 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12567 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12568 // when the caret is just above or just below the deleted hunk.
12569 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12570 let related_to_selection = if allow_adjacent {
12571 hunk.row_range.overlaps(&query_rows)
12572 || hunk.row_range.start == query_rows.end
12573 || hunk.row_range.end == query_rows.start
12574 } else {
12575 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12576 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12577 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12578 || selected_multi_buffer_rows.end == hunk.row_range.start
12579 };
12580 if related_to_selection {
12581 if !processed_buffer_rows
12582 .entry(hunk.buffer_id)
12583 .or_default()
12584 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12585 {
12586 continue;
12587 }
12588 hunks.push(hunk);
12589 }
12590 }
12591 }
12592
12593 hunks
12594}
12595
12596pub trait CollaborationHub {
12597 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12598 fn user_participant_indices<'a>(
12599 &self,
12600 cx: &'a AppContext,
12601 ) -> &'a HashMap<u64, ParticipantIndex>;
12602 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12603}
12604
12605impl CollaborationHub for Model<Project> {
12606 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12607 self.read(cx).collaborators()
12608 }
12609
12610 fn user_participant_indices<'a>(
12611 &self,
12612 cx: &'a AppContext,
12613 ) -> &'a HashMap<u64, ParticipantIndex> {
12614 self.read(cx).user_store().read(cx).participant_indices()
12615 }
12616
12617 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12618 let this = self.read(cx);
12619 let user_ids = this.collaborators().values().map(|c| c.user_id);
12620 this.user_store().read_with(cx, |user_store, cx| {
12621 user_store.participant_names(user_ids, cx)
12622 })
12623 }
12624}
12625
12626pub trait CompletionProvider {
12627 fn completions(
12628 &self,
12629 buffer: &Model<Buffer>,
12630 buffer_position: text::Anchor,
12631 trigger: CompletionContext,
12632 cx: &mut ViewContext<Editor>,
12633 ) -> Task<Result<Vec<Completion>>>;
12634
12635 fn resolve_completions(
12636 &self,
12637 buffer: Model<Buffer>,
12638 completion_indices: Vec<usize>,
12639 completions: Arc<RwLock<Box<[Completion]>>>,
12640 cx: &mut ViewContext<Editor>,
12641 ) -> Task<Result<bool>>;
12642
12643 fn apply_additional_edits_for_completion(
12644 &self,
12645 buffer: Model<Buffer>,
12646 completion: Completion,
12647 push_to_history: bool,
12648 cx: &mut ViewContext<Editor>,
12649 ) -> Task<Result<Option<language::Transaction>>>;
12650
12651 fn is_completion_trigger(
12652 &self,
12653 buffer: &Model<Buffer>,
12654 position: language::Anchor,
12655 text: &str,
12656 trigger_in_words: bool,
12657 cx: &mut ViewContext<Editor>,
12658 ) -> bool;
12659
12660 fn sort_completions(&self) -> bool {
12661 true
12662 }
12663}
12664
12665pub trait CodeActionProvider {
12666 fn code_actions(
12667 &self,
12668 buffer: &Model<Buffer>,
12669 range: Range<text::Anchor>,
12670 cx: &mut WindowContext,
12671 ) -> Task<Result<Vec<CodeAction>>>;
12672
12673 fn apply_code_action(
12674 &self,
12675 buffer_handle: Model<Buffer>,
12676 action: CodeAction,
12677 excerpt_id: ExcerptId,
12678 push_to_history: bool,
12679 cx: &mut WindowContext,
12680 ) -> Task<Result<ProjectTransaction>>;
12681}
12682
12683impl CodeActionProvider for Model<Project> {
12684 fn code_actions(
12685 &self,
12686 buffer: &Model<Buffer>,
12687 range: Range<text::Anchor>,
12688 cx: &mut WindowContext,
12689 ) -> Task<Result<Vec<CodeAction>>> {
12690 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12691 }
12692
12693 fn apply_code_action(
12694 &self,
12695 buffer_handle: Model<Buffer>,
12696 action: CodeAction,
12697 _excerpt_id: ExcerptId,
12698 push_to_history: bool,
12699 cx: &mut WindowContext,
12700 ) -> Task<Result<ProjectTransaction>> {
12701 self.update(cx, |project, cx| {
12702 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12703 })
12704 }
12705}
12706
12707fn snippet_completions(
12708 project: &Project,
12709 buffer: &Model<Buffer>,
12710 buffer_position: text::Anchor,
12711 cx: &mut AppContext,
12712) -> Vec<Completion> {
12713 let language = buffer.read(cx).language_at(buffer_position);
12714 let language_name = language.as_ref().map(|language| language.lsp_id());
12715 let snippet_store = project.snippets().read(cx);
12716 let snippets = snippet_store.snippets_for(language_name, cx);
12717
12718 if snippets.is_empty() {
12719 return vec![];
12720 }
12721 let snapshot = buffer.read(cx).text_snapshot();
12722 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12723
12724 let mut lines = chunks.lines();
12725 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12726 return vec![];
12727 };
12728
12729 let scope = language.map(|language| language.default_scope());
12730 let classifier = CharClassifier::new(scope).for_completion(true);
12731 let mut last_word = line_at
12732 .chars()
12733 .rev()
12734 .take_while(|c| classifier.is_word(*c))
12735 .collect::<String>();
12736 last_word = last_word.chars().rev().collect();
12737 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12738 let to_lsp = |point: &text::Anchor| {
12739 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12740 point_to_lsp(end)
12741 };
12742 let lsp_end = to_lsp(&buffer_position);
12743 snippets
12744 .into_iter()
12745 .filter_map(|snippet| {
12746 let matching_prefix = snippet
12747 .prefix
12748 .iter()
12749 .find(|prefix| prefix.starts_with(&last_word))?;
12750 let start = as_offset - last_word.len();
12751 let start = snapshot.anchor_before(start);
12752 let range = start..buffer_position;
12753 let lsp_start = to_lsp(&start);
12754 let lsp_range = lsp::Range {
12755 start: lsp_start,
12756 end: lsp_end,
12757 };
12758 Some(Completion {
12759 old_range: range,
12760 new_text: snippet.body.clone(),
12761 label: CodeLabel {
12762 text: matching_prefix.clone(),
12763 runs: vec![],
12764 filter_range: 0..matching_prefix.len(),
12765 },
12766 server_id: LanguageServerId(usize::MAX),
12767 documentation: snippet.description.clone().map(Documentation::SingleLine),
12768 lsp_completion: lsp::CompletionItem {
12769 label: snippet.prefix.first().unwrap().clone(),
12770 kind: Some(CompletionItemKind::SNIPPET),
12771 label_details: snippet.description.as_ref().map(|description| {
12772 lsp::CompletionItemLabelDetails {
12773 detail: Some(description.clone()),
12774 description: None,
12775 }
12776 }),
12777 insert_text_format: Some(InsertTextFormat::SNIPPET),
12778 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12779 lsp::InsertReplaceEdit {
12780 new_text: snippet.body.clone(),
12781 insert: lsp_range,
12782 replace: lsp_range,
12783 },
12784 )),
12785 filter_text: Some(snippet.body.clone()),
12786 sort_text: Some(char::MAX.to_string()),
12787 ..Default::default()
12788 },
12789 confirm: None,
12790 })
12791 })
12792 .collect()
12793}
12794
12795impl CompletionProvider for Model<Project> {
12796 fn completions(
12797 &self,
12798 buffer: &Model<Buffer>,
12799 buffer_position: text::Anchor,
12800 options: CompletionContext,
12801 cx: &mut ViewContext<Editor>,
12802 ) -> Task<Result<Vec<Completion>>> {
12803 self.update(cx, |project, cx| {
12804 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12805 let project_completions = project.completions(buffer, buffer_position, options, cx);
12806 cx.background_executor().spawn(async move {
12807 let mut completions = project_completions.await?;
12808 //let snippets = snippets.into_iter().;
12809 completions.extend(snippets);
12810 Ok(completions)
12811 })
12812 })
12813 }
12814
12815 fn resolve_completions(
12816 &self,
12817 buffer: Model<Buffer>,
12818 completion_indices: Vec<usize>,
12819 completions: Arc<RwLock<Box<[Completion]>>>,
12820 cx: &mut ViewContext<Editor>,
12821 ) -> Task<Result<bool>> {
12822 self.update(cx, |project, cx| {
12823 project.resolve_completions(buffer, completion_indices, completions, cx)
12824 })
12825 }
12826
12827 fn apply_additional_edits_for_completion(
12828 &self,
12829 buffer: Model<Buffer>,
12830 completion: Completion,
12831 push_to_history: bool,
12832 cx: &mut ViewContext<Editor>,
12833 ) -> Task<Result<Option<language::Transaction>>> {
12834 self.update(cx, |project, cx| {
12835 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12836 })
12837 }
12838
12839 fn is_completion_trigger(
12840 &self,
12841 buffer: &Model<Buffer>,
12842 position: language::Anchor,
12843 text: &str,
12844 trigger_in_words: bool,
12845 cx: &mut ViewContext<Editor>,
12846 ) -> bool {
12847 if !EditorSettings::get_global(cx).show_completions_on_input {
12848 return false;
12849 }
12850
12851 let mut chars = text.chars();
12852 let char = if let Some(char) = chars.next() {
12853 char
12854 } else {
12855 return false;
12856 };
12857 if chars.next().is_some() {
12858 return false;
12859 }
12860
12861 let buffer = buffer.read(cx);
12862 let classifier = buffer
12863 .snapshot()
12864 .char_classifier_at(position)
12865 .for_completion(true);
12866 if trigger_in_words && classifier.is_word(char) {
12867 return true;
12868 }
12869
12870 buffer
12871 .completion_triggers()
12872 .iter()
12873 .any(|string| string == text)
12874 }
12875}
12876
12877fn inlay_hint_settings(
12878 location: Anchor,
12879 snapshot: &MultiBufferSnapshot,
12880 cx: &mut ViewContext<'_, Editor>,
12881) -> InlayHintSettings {
12882 let file = snapshot.file_at(location);
12883 let language = snapshot.language_at(location);
12884 let settings = all_language_settings(file, cx);
12885 settings
12886 .language(language.map(|l| l.name()).as_ref())
12887 .inlay_hints
12888}
12889
12890fn consume_contiguous_rows(
12891 contiguous_row_selections: &mut Vec<Selection<Point>>,
12892 selection: &Selection<Point>,
12893 display_map: &DisplaySnapshot,
12894 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12895) -> (MultiBufferRow, MultiBufferRow) {
12896 contiguous_row_selections.push(selection.clone());
12897 let start_row = MultiBufferRow(selection.start.row);
12898 let mut end_row = ending_row(selection, display_map);
12899
12900 while let Some(next_selection) = selections.peek() {
12901 if next_selection.start.row <= end_row.0 {
12902 end_row = ending_row(next_selection, display_map);
12903 contiguous_row_selections.push(selections.next().unwrap().clone());
12904 } else {
12905 break;
12906 }
12907 }
12908 (start_row, end_row)
12909}
12910
12911fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12912 if next_selection.end.column > 0 || next_selection.is_empty() {
12913 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12914 } else {
12915 MultiBufferRow(next_selection.end.row)
12916 }
12917}
12918
12919impl EditorSnapshot {
12920 pub fn remote_selections_in_range<'a>(
12921 &'a self,
12922 range: &'a Range<Anchor>,
12923 collaboration_hub: &dyn CollaborationHub,
12924 cx: &'a AppContext,
12925 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12926 let participant_names = collaboration_hub.user_names(cx);
12927 let participant_indices = collaboration_hub.user_participant_indices(cx);
12928 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12929 let collaborators_by_replica_id = collaborators_by_peer_id
12930 .iter()
12931 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12932 .collect::<HashMap<_, _>>();
12933 self.buffer_snapshot
12934 .selections_in_range(range, false)
12935 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12936 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12937 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12938 let user_name = participant_names.get(&collaborator.user_id).cloned();
12939 Some(RemoteSelection {
12940 replica_id,
12941 selection,
12942 cursor_shape,
12943 line_mode,
12944 participant_index,
12945 peer_id: collaborator.peer_id,
12946 user_name,
12947 })
12948 })
12949 }
12950
12951 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12952 self.display_snapshot.buffer_snapshot.language_at(position)
12953 }
12954
12955 pub fn is_focused(&self) -> bool {
12956 self.is_focused
12957 }
12958
12959 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12960 self.placeholder_text.as_ref()
12961 }
12962
12963 pub fn scroll_position(&self) -> gpui::Point<f32> {
12964 self.scroll_anchor.scroll_position(&self.display_snapshot)
12965 }
12966
12967 fn gutter_dimensions(
12968 &self,
12969 font_id: FontId,
12970 font_size: Pixels,
12971 em_width: Pixels,
12972 em_advance: Pixels,
12973 max_line_number_width: Pixels,
12974 cx: &AppContext,
12975 ) -> GutterDimensions {
12976 if !self.show_gutter {
12977 return GutterDimensions::default();
12978 }
12979 let descent = cx.text_system().descent(font_id, font_size);
12980
12981 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12982 matches!(
12983 ProjectSettings::get_global(cx).git.git_gutter,
12984 Some(GitGutterSetting::TrackedFiles)
12985 )
12986 });
12987 let gutter_settings = EditorSettings::get_global(cx).gutter;
12988 let show_line_numbers = self
12989 .show_line_numbers
12990 .unwrap_or(gutter_settings.line_numbers);
12991 let line_gutter_width = if show_line_numbers {
12992 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12993 let min_width_for_number_on_gutter = em_advance * 4.0;
12994 max_line_number_width.max(min_width_for_number_on_gutter)
12995 } else {
12996 0.0.into()
12997 };
12998
12999 let show_code_actions = self
13000 .show_code_actions
13001 .unwrap_or(gutter_settings.code_actions);
13002
13003 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13004
13005 let git_blame_entries_width =
13006 self.git_blame_gutter_max_author_length
13007 .map(|max_author_length| {
13008 // Length of the author name, but also space for the commit hash,
13009 // the spacing and the timestamp.
13010 let max_char_count = max_author_length
13011 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13012 + 7 // length of commit sha
13013 + 14 // length of max relative timestamp ("60 minutes ago")
13014 + 4; // gaps and margins
13015
13016 em_advance * max_char_count
13017 });
13018
13019 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13020 left_padding += if show_code_actions || show_runnables {
13021 em_width * 3.0
13022 } else if show_git_gutter && show_line_numbers {
13023 em_width * 2.0
13024 } else if show_git_gutter || show_line_numbers {
13025 em_width
13026 } else {
13027 px(0.)
13028 };
13029
13030 let right_padding = if gutter_settings.folds && show_line_numbers {
13031 em_width * 4.0
13032 } else if gutter_settings.folds {
13033 em_width * 3.0
13034 } else if show_line_numbers {
13035 em_width
13036 } else {
13037 px(0.)
13038 };
13039
13040 GutterDimensions {
13041 left_padding,
13042 right_padding,
13043 width: line_gutter_width + left_padding + right_padding,
13044 margin: -descent,
13045 git_blame_entries_width,
13046 }
13047 }
13048
13049 pub fn render_fold_toggle(
13050 &self,
13051 buffer_row: MultiBufferRow,
13052 row_contains_cursor: bool,
13053 editor: View<Editor>,
13054 cx: &mut WindowContext,
13055 ) -> Option<AnyElement> {
13056 let folded = self.is_line_folded(buffer_row);
13057
13058 if let Some(crease) = self
13059 .crease_snapshot
13060 .query_row(buffer_row, &self.buffer_snapshot)
13061 {
13062 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13063 if folded {
13064 editor.update(cx, |editor, cx| {
13065 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13066 });
13067 } else {
13068 editor.update(cx, |editor, cx| {
13069 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13070 });
13071 }
13072 });
13073
13074 Some((crease.render_toggle)(
13075 buffer_row,
13076 folded,
13077 toggle_callback,
13078 cx,
13079 ))
13080 } else if folded
13081 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13082 {
13083 Some(
13084 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13085 .selected(folded)
13086 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13087 if folded {
13088 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13089 } else {
13090 this.fold_at(&FoldAt { buffer_row }, cx);
13091 }
13092 }))
13093 .into_any_element(),
13094 )
13095 } else {
13096 None
13097 }
13098 }
13099
13100 pub fn render_crease_trailer(
13101 &self,
13102 buffer_row: MultiBufferRow,
13103 cx: &mut WindowContext,
13104 ) -> Option<AnyElement> {
13105 let folded = self.is_line_folded(buffer_row);
13106 let crease = self
13107 .crease_snapshot
13108 .query_row(buffer_row, &self.buffer_snapshot)?;
13109 Some((crease.render_trailer)(buffer_row, folded, cx))
13110 }
13111}
13112
13113impl Deref for EditorSnapshot {
13114 type Target = DisplaySnapshot;
13115
13116 fn deref(&self) -> &Self::Target {
13117 &self.display_snapshot
13118 }
13119}
13120
13121#[derive(Clone, Debug, PartialEq, Eq)]
13122pub enum EditorEvent {
13123 InputIgnored {
13124 text: Arc<str>,
13125 },
13126 InputHandled {
13127 utf16_range_to_replace: Option<Range<isize>>,
13128 text: Arc<str>,
13129 },
13130 ExcerptsAdded {
13131 buffer: Model<Buffer>,
13132 predecessor: ExcerptId,
13133 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13134 },
13135 ExcerptsRemoved {
13136 ids: Vec<ExcerptId>,
13137 },
13138 ExcerptsEdited {
13139 ids: Vec<ExcerptId>,
13140 },
13141 ExcerptsExpanded {
13142 ids: Vec<ExcerptId>,
13143 },
13144 BufferEdited,
13145 Edited {
13146 transaction_id: clock::Lamport,
13147 },
13148 Reparsed(BufferId),
13149 Focused,
13150 FocusedIn,
13151 Blurred,
13152 DirtyChanged,
13153 Saved,
13154 TitleChanged,
13155 DiffBaseChanged,
13156 SelectionsChanged {
13157 local: bool,
13158 },
13159 ScrollPositionChanged {
13160 local: bool,
13161 autoscroll: bool,
13162 },
13163 Closed,
13164 TransactionUndone {
13165 transaction_id: clock::Lamport,
13166 },
13167 TransactionBegun {
13168 transaction_id: clock::Lamport,
13169 },
13170 CursorShapeChanged,
13171}
13172
13173impl EventEmitter<EditorEvent> for Editor {}
13174
13175impl FocusableView for Editor {
13176 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13177 self.focus_handle.clone()
13178 }
13179}
13180
13181impl Render for Editor {
13182 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13183 let settings = ThemeSettings::get_global(cx);
13184
13185 let text_style = match self.mode {
13186 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13187 color: cx.theme().colors().editor_foreground,
13188 font_family: settings.ui_font.family.clone(),
13189 font_features: settings.ui_font.features.clone(),
13190 font_fallbacks: settings.ui_font.fallbacks.clone(),
13191 font_size: rems(0.875).into(),
13192 font_weight: settings.ui_font.weight,
13193 line_height: relative(settings.buffer_line_height.value()),
13194 ..Default::default()
13195 },
13196 EditorMode::Full => TextStyle {
13197 color: cx.theme().colors().editor_foreground,
13198 font_family: settings.buffer_font.family.clone(),
13199 font_features: settings.buffer_font.features.clone(),
13200 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13201 font_size: settings.buffer_font_size(cx).into(),
13202 font_weight: settings.buffer_font.weight,
13203 line_height: relative(settings.buffer_line_height.value()),
13204 ..Default::default()
13205 },
13206 };
13207
13208 let background = match self.mode {
13209 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13210 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13211 EditorMode::Full => cx.theme().colors().editor_background,
13212 };
13213
13214 EditorElement::new(
13215 cx.view(),
13216 EditorStyle {
13217 background,
13218 local_player: cx.theme().players().local(),
13219 text: text_style,
13220 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13221 syntax: cx.theme().syntax().clone(),
13222 status: cx.theme().status().clone(),
13223 inlay_hints_style: make_inlay_hints_style(cx),
13224 suggestions_style: HighlightStyle {
13225 color: Some(cx.theme().status().predictive),
13226 ..HighlightStyle::default()
13227 },
13228 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13229 },
13230 )
13231 }
13232}
13233
13234impl ViewInputHandler for Editor {
13235 fn text_for_range(
13236 &mut self,
13237 range_utf16: Range<usize>,
13238 cx: &mut ViewContext<Self>,
13239 ) -> Option<String> {
13240 Some(
13241 self.buffer
13242 .read(cx)
13243 .read(cx)
13244 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13245 .collect(),
13246 )
13247 }
13248
13249 fn selected_text_range(
13250 &mut self,
13251 ignore_disabled_input: bool,
13252 cx: &mut ViewContext<Self>,
13253 ) -> Option<UTF16Selection> {
13254 // Prevent the IME menu from appearing when holding down an alphabetic key
13255 // while input is disabled.
13256 if !ignore_disabled_input && !self.input_enabled {
13257 return None;
13258 }
13259
13260 let selection = self.selections.newest::<OffsetUtf16>(cx);
13261 let range = selection.range();
13262
13263 Some(UTF16Selection {
13264 range: range.start.0..range.end.0,
13265 reversed: selection.reversed,
13266 })
13267 }
13268
13269 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13270 let snapshot = self.buffer.read(cx).read(cx);
13271 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13272 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13273 }
13274
13275 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13276 self.clear_highlights::<InputComposition>(cx);
13277 self.ime_transaction.take();
13278 }
13279
13280 fn replace_text_in_range(
13281 &mut self,
13282 range_utf16: Option<Range<usize>>,
13283 text: &str,
13284 cx: &mut ViewContext<Self>,
13285 ) {
13286 if !self.input_enabled {
13287 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13288 return;
13289 }
13290
13291 self.transact(cx, |this, cx| {
13292 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13293 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13294 Some(this.selection_replacement_ranges(range_utf16, cx))
13295 } else {
13296 this.marked_text_ranges(cx)
13297 };
13298
13299 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13300 let newest_selection_id = this.selections.newest_anchor().id;
13301 this.selections
13302 .all::<OffsetUtf16>(cx)
13303 .iter()
13304 .zip(ranges_to_replace.iter())
13305 .find_map(|(selection, range)| {
13306 if selection.id == newest_selection_id {
13307 Some(
13308 (range.start.0 as isize - selection.head().0 as isize)
13309 ..(range.end.0 as isize - selection.head().0 as isize),
13310 )
13311 } else {
13312 None
13313 }
13314 })
13315 });
13316
13317 cx.emit(EditorEvent::InputHandled {
13318 utf16_range_to_replace: range_to_replace,
13319 text: text.into(),
13320 });
13321
13322 if let Some(new_selected_ranges) = new_selected_ranges {
13323 this.change_selections(None, cx, |selections| {
13324 selections.select_ranges(new_selected_ranges)
13325 });
13326 this.backspace(&Default::default(), cx);
13327 }
13328
13329 this.handle_input(text, cx);
13330 });
13331
13332 if let Some(transaction) = self.ime_transaction {
13333 self.buffer.update(cx, |buffer, cx| {
13334 buffer.group_until_transaction(transaction, cx);
13335 });
13336 }
13337
13338 self.unmark_text(cx);
13339 }
13340
13341 fn replace_and_mark_text_in_range(
13342 &mut self,
13343 range_utf16: Option<Range<usize>>,
13344 text: &str,
13345 new_selected_range_utf16: Option<Range<usize>>,
13346 cx: &mut ViewContext<Self>,
13347 ) {
13348 if !self.input_enabled {
13349 return;
13350 }
13351
13352 let transaction = self.transact(cx, |this, cx| {
13353 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13354 let snapshot = this.buffer.read(cx).read(cx);
13355 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13356 for marked_range in &mut marked_ranges {
13357 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13358 marked_range.start.0 += relative_range_utf16.start;
13359 marked_range.start =
13360 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13361 marked_range.end =
13362 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13363 }
13364 }
13365 Some(marked_ranges)
13366 } else if let Some(range_utf16) = range_utf16 {
13367 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13368 Some(this.selection_replacement_ranges(range_utf16, cx))
13369 } else {
13370 None
13371 };
13372
13373 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13374 let newest_selection_id = this.selections.newest_anchor().id;
13375 this.selections
13376 .all::<OffsetUtf16>(cx)
13377 .iter()
13378 .zip(ranges_to_replace.iter())
13379 .find_map(|(selection, range)| {
13380 if selection.id == newest_selection_id {
13381 Some(
13382 (range.start.0 as isize - selection.head().0 as isize)
13383 ..(range.end.0 as isize - selection.head().0 as isize),
13384 )
13385 } else {
13386 None
13387 }
13388 })
13389 });
13390
13391 cx.emit(EditorEvent::InputHandled {
13392 utf16_range_to_replace: range_to_replace,
13393 text: text.into(),
13394 });
13395
13396 if let Some(ranges) = ranges_to_replace {
13397 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13398 }
13399
13400 let marked_ranges = {
13401 let snapshot = this.buffer.read(cx).read(cx);
13402 this.selections
13403 .disjoint_anchors()
13404 .iter()
13405 .map(|selection| {
13406 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13407 })
13408 .collect::<Vec<_>>()
13409 };
13410
13411 if text.is_empty() {
13412 this.unmark_text(cx);
13413 } else {
13414 this.highlight_text::<InputComposition>(
13415 marked_ranges.clone(),
13416 HighlightStyle {
13417 underline: Some(UnderlineStyle {
13418 thickness: px(1.),
13419 color: None,
13420 wavy: false,
13421 }),
13422 ..Default::default()
13423 },
13424 cx,
13425 );
13426 }
13427
13428 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13429 let use_autoclose = this.use_autoclose;
13430 let use_auto_surround = this.use_auto_surround;
13431 this.set_use_autoclose(false);
13432 this.set_use_auto_surround(false);
13433 this.handle_input(text, cx);
13434 this.set_use_autoclose(use_autoclose);
13435 this.set_use_auto_surround(use_auto_surround);
13436
13437 if let Some(new_selected_range) = new_selected_range_utf16 {
13438 let snapshot = this.buffer.read(cx).read(cx);
13439 let new_selected_ranges = marked_ranges
13440 .into_iter()
13441 .map(|marked_range| {
13442 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13443 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13444 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13445 snapshot.clip_offset_utf16(new_start, Bias::Left)
13446 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13447 })
13448 .collect::<Vec<_>>();
13449
13450 drop(snapshot);
13451 this.change_selections(None, cx, |selections| {
13452 selections.select_ranges(new_selected_ranges)
13453 });
13454 }
13455 });
13456
13457 self.ime_transaction = self.ime_transaction.or(transaction);
13458 if let Some(transaction) = self.ime_transaction {
13459 self.buffer.update(cx, |buffer, cx| {
13460 buffer.group_until_transaction(transaction, cx);
13461 });
13462 }
13463
13464 if self.text_highlights::<InputComposition>(cx).is_none() {
13465 self.ime_transaction.take();
13466 }
13467 }
13468
13469 fn bounds_for_range(
13470 &mut self,
13471 range_utf16: Range<usize>,
13472 element_bounds: gpui::Bounds<Pixels>,
13473 cx: &mut ViewContext<Self>,
13474 ) -> Option<gpui::Bounds<Pixels>> {
13475 let text_layout_details = self.text_layout_details(cx);
13476 let style = &text_layout_details.editor_style;
13477 let font_id = cx.text_system().resolve_font(&style.text.font());
13478 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13479 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13480
13481 let em_width = cx
13482 .text_system()
13483 .typographic_bounds(font_id, font_size, 'm')
13484 .unwrap()
13485 .size
13486 .width;
13487
13488 let snapshot = self.snapshot(cx);
13489 let scroll_position = snapshot.scroll_position();
13490 let scroll_left = scroll_position.x * em_width;
13491
13492 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13493 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13494 + self.gutter_dimensions.width;
13495 let y = line_height * (start.row().as_f32() - scroll_position.y);
13496
13497 Some(Bounds {
13498 origin: element_bounds.origin + point(x, y),
13499 size: size(em_width, line_height),
13500 })
13501 }
13502}
13503
13504trait SelectionExt {
13505 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13506 fn spanned_rows(
13507 &self,
13508 include_end_if_at_line_start: bool,
13509 map: &DisplaySnapshot,
13510 ) -> Range<MultiBufferRow>;
13511}
13512
13513impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13514 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13515 let start = self
13516 .start
13517 .to_point(&map.buffer_snapshot)
13518 .to_display_point(map);
13519 let end = self
13520 .end
13521 .to_point(&map.buffer_snapshot)
13522 .to_display_point(map);
13523 if self.reversed {
13524 end..start
13525 } else {
13526 start..end
13527 }
13528 }
13529
13530 fn spanned_rows(
13531 &self,
13532 include_end_if_at_line_start: bool,
13533 map: &DisplaySnapshot,
13534 ) -> Range<MultiBufferRow> {
13535 let start = self.start.to_point(&map.buffer_snapshot);
13536 let mut end = self.end.to_point(&map.buffer_snapshot);
13537 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13538 end.row -= 1;
13539 }
13540
13541 let buffer_start = map.prev_line_boundary(start).0;
13542 let buffer_end = map.next_line_boundary(end).0;
13543 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13544 }
13545}
13546
13547impl<T: InvalidationRegion> InvalidationStack<T> {
13548 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13549 where
13550 S: Clone + ToOffset,
13551 {
13552 while let Some(region) = self.last() {
13553 let all_selections_inside_invalidation_ranges =
13554 if selections.len() == region.ranges().len() {
13555 selections
13556 .iter()
13557 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13558 .all(|(selection, invalidation_range)| {
13559 let head = selection.head().to_offset(buffer);
13560 invalidation_range.start <= head && invalidation_range.end >= head
13561 })
13562 } else {
13563 false
13564 };
13565
13566 if all_selections_inside_invalidation_ranges {
13567 break;
13568 } else {
13569 self.pop();
13570 }
13571 }
13572 }
13573}
13574
13575impl<T> Default for InvalidationStack<T> {
13576 fn default() -> Self {
13577 Self(Default::default())
13578 }
13579}
13580
13581impl<T> Deref for InvalidationStack<T> {
13582 type Target = Vec<T>;
13583
13584 fn deref(&self) -> &Self::Target {
13585 &self.0
13586 }
13587}
13588
13589impl<T> DerefMut for InvalidationStack<T> {
13590 fn deref_mut(&mut self) -> &mut Self::Target {
13591 &mut self.0
13592 }
13593}
13594
13595impl InvalidationRegion for SnippetState {
13596 fn ranges(&self) -> &[Range<Anchor>] {
13597 &self.ranges[self.active_index]
13598 }
13599}
13600
13601pub fn diagnostic_block_renderer(
13602 diagnostic: Diagnostic,
13603 max_message_rows: Option<u8>,
13604 allow_closing: bool,
13605 _is_valid: bool,
13606) -> RenderBlock {
13607 let (text_without_backticks, code_ranges) =
13608 highlight_diagnostic_message(&diagnostic, max_message_rows);
13609
13610 Box::new(move |cx: &mut BlockContext| {
13611 let group_id: SharedString = cx.block_id.to_string().into();
13612
13613 let mut text_style = cx.text_style().clone();
13614 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13615 let theme_settings = ThemeSettings::get_global(cx);
13616 text_style.font_family = theme_settings.buffer_font.family.clone();
13617 text_style.font_style = theme_settings.buffer_font.style;
13618 text_style.font_features = theme_settings.buffer_font.features.clone();
13619 text_style.font_weight = theme_settings.buffer_font.weight;
13620
13621 let multi_line_diagnostic = diagnostic.message.contains('\n');
13622
13623 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13624 if multi_line_diagnostic {
13625 v_flex()
13626 } else {
13627 h_flex()
13628 }
13629 .when(allow_closing, |div| {
13630 div.children(diagnostic.is_primary.then(|| {
13631 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13632 .icon_color(Color::Muted)
13633 .size(ButtonSize::Compact)
13634 .style(ButtonStyle::Transparent)
13635 .visible_on_hover(group_id.clone())
13636 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13637 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13638 }))
13639 })
13640 .child(
13641 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13642 .icon_color(Color::Muted)
13643 .size(ButtonSize::Compact)
13644 .style(ButtonStyle::Transparent)
13645 .visible_on_hover(group_id.clone())
13646 .on_click({
13647 let message = diagnostic.message.clone();
13648 move |_click, cx| {
13649 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13650 }
13651 })
13652 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13653 )
13654 };
13655
13656 let icon_size = buttons(&diagnostic, cx.block_id)
13657 .into_any_element()
13658 .layout_as_root(AvailableSpace::min_size(), cx);
13659
13660 h_flex()
13661 .id(cx.block_id)
13662 .group(group_id.clone())
13663 .relative()
13664 .size_full()
13665 .pl(cx.gutter_dimensions.width)
13666 .w(cx.max_width + cx.gutter_dimensions.width)
13667 .child(
13668 div()
13669 .flex()
13670 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13671 .flex_shrink(),
13672 )
13673 .child(buttons(&diagnostic, cx.block_id))
13674 .child(div().flex().flex_shrink_0().child(
13675 StyledText::new(text_without_backticks.clone()).with_highlights(
13676 &text_style,
13677 code_ranges.iter().map(|range| {
13678 (
13679 range.clone(),
13680 HighlightStyle {
13681 font_weight: Some(FontWeight::BOLD),
13682 ..Default::default()
13683 },
13684 )
13685 }),
13686 ),
13687 ))
13688 .into_any_element()
13689 })
13690}
13691
13692pub fn highlight_diagnostic_message(
13693 diagnostic: &Diagnostic,
13694 mut max_message_rows: Option<u8>,
13695) -> (SharedString, Vec<Range<usize>>) {
13696 let mut text_without_backticks = String::new();
13697 let mut code_ranges = Vec::new();
13698
13699 if let Some(source) = &diagnostic.source {
13700 text_without_backticks.push_str(source);
13701 code_ranges.push(0..source.len());
13702 text_without_backticks.push_str(": ");
13703 }
13704
13705 let mut prev_offset = 0;
13706 let mut in_code_block = false;
13707 let has_row_limit = max_message_rows.is_some();
13708 let mut newline_indices = diagnostic
13709 .message
13710 .match_indices('\n')
13711 .filter(|_| has_row_limit)
13712 .map(|(ix, _)| ix)
13713 .fuse()
13714 .peekable();
13715
13716 for (quote_ix, _) in diagnostic
13717 .message
13718 .match_indices('`')
13719 .chain([(diagnostic.message.len(), "")])
13720 {
13721 let mut first_newline_ix = None;
13722 let mut last_newline_ix = None;
13723 while let Some(newline_ix) = newline_indices.peek() {
13724 if *newline_ix < quote_ix {
13725 if first_newline_ix.is_none() {
13726 first_newline_ix = Some(*newline_ix);
13727 }
13728 last_newline_ix = Some(*newline_ix);
13729
13730 if let Some(rows_left) = &mut max_message_rows {
13731 if *rows_left == 0 {
13732 break;
13733 } else {
13734 *rows_left -= 1;
13735 }
13736 }
13737 let _ = newline_indices.next();
13738 } else {
13739 break;
13740 }
13741 }
13742 let prev_len = text_without_backticks.len();
13743 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13744 text_without_backticks.push_str(new_text);
13745 if in_code_block {
13746 code_ranges.push(prev_len..text_without_backticks.len());
13747 }
13748 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13749 in_code_block = !in_code_block;
13750 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13751 text_without_backticks.push_str("...");
13752 break;
13753 }
13754 }
13755
13756 (text_without_backticks.into(), code_ranges)
13757}
13758
13759fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13760 match severity {
13761 DiagnosticSeverity::ERROR => colors.error,
13762 DiagnosticSeverity::WARNING => colors.warning,
13763 DiagnosticSeverity::INFORMATION => colors.info,
13764 DiagnosticSeverity::HINT => colors.info,
13765 _ => colors.ignored,
13766 }
13767}
13768
13769pub fn styled_runs_for_code_label<'a>(
13770 label: &'a CodeLabel,
13771 syntax_theme: &'a theme::SyntaxTheme,
13772) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13773 let fade_out = HighlightStyle {
13774 fade_out: Some(0.35),
13775 ..Default::default()
13776 };
13777
13778 let mut prev_end = label.filter_range.end;
13779 label
13780 .runs
13781 .iter()
13782 .enumerate()
13783 .flat_map(move |(ix, (range, highlight_id))| {
13784 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13785 style
13786 } else {
13787 return Default::default();
13788 };
13789 let mut muted_style = style;
13790 muted_style.highlight(fade_out);
13791
13792 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13793 if range.start >= label.filter_range.end {
13794 if range.start > prev_end {
13795 runs.push((prev_end..range.start, fade_out));
13796 }
13797 runs.push((range.clone(), muted_style));
13798 } else if range.end <= label.filter_range.end {
13799 runs.push((range.clone(), style));
13800 } else {
13801 runs.push((range.start..label.filter_range.end, style));
13802 runs.push((label.filter_range.end..range.end, muted_style));
13803 }
13804 prev_end = cmp::max(prev_end, range.end);
13805
13806 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13807 runs.push((prev_end..label.text.len(), fade_out));
13808 }
13809
13810 runs
13811 })
13812}
13813
13814pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13815 let mut prev_index = 0;
13816 let mut prev_codepoint: Option<char> = None;
13817 text.char_indices()
13818 .chain([(text.len(), '\0')])
13819 .filter_map(move |(index, codepoint)| {
13820 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13821 let is_boundary = index == text.len()
13822 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13823 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13824 if is_boundary {
13825 let chunk = &text[prev_index..index];
13826 prev_index = index;
13827 Some(chunk)
13828 } else {
13829 None
13830 }
13831 })
13832}
13833
13834pub trait RangeToAnchorExt: Sized {
13835 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13836
13837 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13838 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13839 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13840 }
13841}
13842
13843impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13844 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13845 let start_offset = self.start.to_offset(snapshot);
13846 let end_offset = self.end.to_offset(snapshot);
13847 if start_offset == end_offset {
13848 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13849 } else {
13850 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13851 }
13852 }
13853}
13854
13855pub trait RowExt {
13856 fn as_f32(&self) -> f32;
13857
13858 fn next_row(&self) -> Self;
13859
13860 fn previous_row(&self) -> Self;
13861
13862 fn minus(&self, other: Self) -> u32;
13863}
13864
13865impl RowExt for DisplayRow {
13866 fn as_f32(&self) -> f32 {
13867 self.0 as f32
13868 }
13869
13870 fn next_row(&self) -> Self {
13871 Self(self.0 + 1)
13872 }
13873
13874 fn previous_row(&self) -> Self {
13875 Self(self.0.saturating_sub(1))
13876 }
13877
13878 fn minus(&self, other: Self) -> u32 {
13879 self.0 - other.0
13880 }
13881}
13882
13883impl RowExt for MultiBufferRow {
13884 fn as_f32(&self) -> f32 {
13885 self.0 as f32
13886 }
13887
13888 fn next_row(&self) -> Self {
13889 Self(self.0 + 1)
13890 }
13891
13892 fn previous_row(&self) -> Self {
13893 Self(self.0.saturating_sub(1))
13894 }
13895
13896 fn minus(&self, other: Self) -> u32 {
13897 self.0 - other.0
13898 }
13899}
13900
13901trait RowRangeExt {
13902 type Row;
13903
13904 fn len(&self) -> usize;
13905
13906 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13907}
13908
13909impl RowRangeExt for Range<MultiBufferRow> {
13910 type Row = MultiBufferRow;
13911
13912 fn len(&self) -> usize {
13913 (self.end.0 - self.start.0) as usize
13914 }
13915
13916 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13917 (self.start.0..self.end.0).map(MultiBufferRow)
13918 }
13919}
13920
13921impl RowRangeExt for Range<DisplayRow> {
13922 type Row = DisplayRow;
13923
13924 fn len(&self) -> usize {
13925 (self.end.0 - self.start.0) as usize
13926 }
13927
13928 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13929 (self.start.0..self.end.0).map(DisplayRow)
13930 }
13931}
13932
13933fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
13934 if hunk.diff_base_byte_range.is_empty() {
13935 DiffHunkStatus::Added
13936 } else if hunk.row_range.is_empty() {
13937 DiffHunkStatus::Removed
13938 } else {
13939 DiffHunkStatus::Modified
13940 }
13941}
13942
13943/// If select range has more than one line, we
13944/// just point the cursor to range.start.
13945fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13946 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13947 range
13948 } else {
13949 range.start..range.start
13950 }
13951}