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 git::diff_hunk_to_display;
75use gpui::{
76 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
77 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
78 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
79 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
80 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
81 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
82 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
83 VisualContext, WeakFocusHandle, WeakView, WindowContext,
84};
85use highlight_matching_bracket::refresh_matching_bracket_highlights;
86use hover_popover::{hide_hover, HoverState};
87use hunk_diff::ExpandedHunks;
88pub(crate) use hunk_diff::HoveredHunk;
89use indent_guides::ActiveIndentGuidesState;
90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
91pub use inline_completion_provider::*;
92pub use items::MAX_TAB_TITLE_LEN;
93use itertools::Itertools;
94use language::{
95 language_settings::{self, all_language_settings, InlayHintSettings},
96 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
97 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
98 Point, Selection, SelectionGoal, TransactionId,
99};
100use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
101use linked_editing_ranges::refresh_linked_ranges;
102use proposed_changes_editor::{ProposedChangesBuffer, ProposedChangesEditor};
103use similar::{ChangeTag, TextDiff};
104use task::{ResolvedTask, TaskTemplate, TaskVariables};
105
106use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
107pub use lsp::CompletionContext;
108use lsp::{
109 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
110 LanguageServerId,
111};
112use mouse_context_menu::MouseContextMenu;
113use movement::TextLayoutDetails;
114pub use multi_buffer::{
115 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
116 ToPoint,
117};
118use multi_buffer::{
119 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
120};
121use ordered_float::OrderedFloat;
122use parking_lot::{Mutex, RwLock};
123use project::project_settings::{GitGutterSetting, ProjectSettings};
124use project::{
125 lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
126 ProjectPath, ProjectTransaction, TaskSourceKind,
127};
128use rand::prelude::*;
129use rpc::{proto::*, ErrorExt};
130use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
131use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
132use serde::{Deserialize, Serialize};
133use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
134use smallvec::SmallVec;
135use snippet::Snippet;
136use std::{
137 any::TypeId,
138 borrow::Cow,
139 cell::RefCell,
140 cmp::{self, Ordering, Reverse},
141 mem,
142 num::NonZeroU32,
143 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
144 path::{Path, PathBuf},
145 rc::Rc,
146 sync::Arc,
147 time::{Duration, Instant},
148};
149pub use sum_tree::Bias;
150use sum_tree::TreeMap;
151use text::{BufferId, OffsetUtf16, Rope};
152use theme::{
153 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
154 ThemeColors, ThemeSettings,
155};
156use ui::{
157 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
158 ListItem, Popover, Tooltip,
159};
160use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
161use workspace::item::{ItemHandle, PreviewTabsSettings};
162use workspace::notifications::{DetachAndPromptErr, NotificationId};
163use workspace::{
164 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
165};
166use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
167
168use crate::hover_links::find_url;
169use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
170
171pub const FILE_HEADER_HEIGHT: u32 = 1;
172pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
173pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
174pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
175const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
176const MAX_LINE_LEN: usize = 1024;
177const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
178const MAX_SELECTION_HISTORY_LEN: usize = 1024;
179pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
180#[doc(hidden)]
181pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
182#[doc(hidden)]
183pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
184
185pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
186pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
187
188pub fn render_parsed_markdown(
189 element_id: impl Into<ElementId>,
190 parsed: &language::ParsedMarkdown,
191 editor_style: &EditorStyle,
192 workspace: Option<WeakView<Workspace>>,
193 cx: &mut WindowContext,
194) -> InteractiveText {
195 let code_span_background_color = cx
196 .theme()
197 .colors()
198 .editor_document_highlight_read_background;
199
200 let highlights = gpui::combine_highlights(
201 parsed.highlights.iter().filter_map(|(range, highlight)| {
202 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
203 Some((range.clone(), highlight))
204 }),
205 parsed
206 .regions
207 .iter()
208 .zip(&parsed.region_ranges)
209 .filter_map(|(region, range)| {
210 if region.code {
211 Some((
212 range.clone(),
213 HighlightStyle {
214 background_color: Some(code_span_background_color),
215 ..Default::default()
216 },
217 ))
218 } else {
219 None
220 }
221 }),
222 );
223
224 let mut links = Vec::new();
225 let mut link_ranges = Vec::new();
226 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
227 if let Some(link) = region.link.clone() {
228 links.push(link);
229 link_ranges.push(range.clone());
230 }
231 }
232
233 InteractiveText::new(
234 element_id,
235 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
236 )
237 .on_click(link_ranges, move |clicked_range_ix, cx| {
238 match &links[clicked_range_ix] {
239 markdown::Link::Web { url } => cx.open_url(url),
240 markdown::Link::Path { path } => {
241 if let Some(workspace) = &workspace {
242 _ = workspace.update(cx, |workspace, cx| {
243 workspace.open_abs_path(path.clone(), false, cx).detach();
244 });
245 }
246 }
247 }
248 })
249}
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
252pub(crate) enum InlayId {
253 Suggestion(usize),
254 Hint(usize),
255}
256
257impl InlayId {
258 fn id(&self) -> usize {
259 match self {
260 Self::Suggestion(id) => *id,
261 Self::Hint(id) => *id,
262 }
263 }
264}
265
266enum DiffRowHighlight {}
267enum DocumentHighlightRead {}
268enum DocumentHighlightWrite {}
269enum InputComposition {}
270
271#[derive(Copy, Clone, PartialEq, Eq)]
272pub enum Direction {
273 Prev,
274 Next,
275}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut AppContext) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut AppContext) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new_views(
305 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 },
310 )
311 .detach();
312
313 cx.on_action(move |_: &workspace::NewFile, cx| {
314 let app_state = workspace::AppState::global(cx);
315 if let Some(app_state) = app_state.upgrade() {
316 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
317 Editor::new_file(workspace, &Default::default(), cx)
318 })
319 .detach();
320 }
321 });
322 cx.on_action(move |_: &workspace::NewWindow, cx| {
323 let app_state = workspace::AppState::global(cx);
324 if let Some(app_state) = app_state.upgrade() {
325 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
326 Editor::new_file(workspace, &Default::default(), cx)
327 })
328 .detach();
329 }
330 });
331}
332
333pub struct SearchWithinRange;
334
335trait InvalidationRegion {
336 fn ranges(&self) -> &[Range<Anchor>];
337}
338
339#[derive(Clone, Debug, PartialEq)]
340pub enum SelectPhase {
341 Begin {
342 position: DisplayPoint,
343 add: bool,
344 click_count: usize,
345 },
346 BeginColumnar {
347 position: DisplayPoint,
348 reset: bool,
349 goal_column: u32,
350 },
351 Extend {
352 position: DisplayPoint,
353 click_count: usize,
354 },
355 Update {
356 position: DisplayPoint,
357 goal_column: u32,
358 scroll_delta: gpui::Point<f32>,
359 },
360 End,
361}
362
363#[derive(Clone, Debug)]
364pub enum SelectMode {
365 Character,
366 Word(Range<Anchor>),
367 Line(Range<Anchor>),
368 All,
369}
370
371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
372pub enum EditorMode {
373 SingleLine { auto_width: bool },
374 AutoHeight { max_lines: usize },
375 Full,
376}
377
378#[derive(Clone, Debug)]
379pub enum SoftWrap {
380 None,
381 PreferLine,
382 EditorWidth,
383 Column(u32),
384 Bounded(u32),
385}
386
387#[derive(Clone)]
388pub struct EditorStyle {
389 pub background: Hsla,
390 pub local_player: PlayerColor,
391 pub text: TextStyle,
392 pub scrollbar_width: Pixels,
393 pub syntax: Arc<SyntaxTheme>,
394 pub status: StatusColors,
395 pub inlay_hints_style: HighlightStyle,
396 pub suggestions_style: HighlightStyle,
397 pub unnecessary_code_fade: f32,
398}
399
400impl Default for EditorStyle {
401 fn default() -> Self {
402 Self {
403 background: Hsla::default(),
404 local_player: PlayerColor::default(),
405 text: TextStyle::default(),
406 scrollbar_width: Pixels::default(),
407 syntax: Default::default(),
408 // HACK: Status colors don't have a real default.
409 // We should look into removing the status colors from the editor
410 // style and retrieve them directly from the theme.
411 status: StatusColors::dark(),
412 inlay_hints_style: HighlightStyle::default(),
413 suggestions_style: HighlightStyle::default(),
414 unnecessary_code_fade: Default::default(),
415 }
416 }
417}
418
419pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
420 let show_background = all_language_settings(None, cx)
421 .language(None)
422 .inlay_hints
423 .show_background;
424
425 HighlightStyle {
426 color: Some(cx.theme().status().hint),
427 background_color: show_background.then(|| cx.theme().status().hint_background),
428 ..HighlightStyle::default()
429 }
430}
431
432type CompletionId = usize;
433
434#[derive(Clone, Debug)]
435struct CompletionState {
436 // render_inlay_ids represents the inlay hints that are inserted
437 // for rendering the inline completions. They may be discontinuous
438 // in the event that the completion provider returns some intersection
439 // with the existing content.
440 render_inlay_ids: Vec<InlayId>,
441 // text is the resulting rope that is inserted when the user accepts a completion.
442 text: Rope,
443 // position is the position of the cursor when the completion was triggered.
444 position: multi_buffer::Anchor,
445 // delete_range is the range of text that this completion state covers.
446 // if the completion is accepted, this range should be deleted.
447 delete_range: Option<Range<multi_buffer::Anchor>>,
448}
449
450#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
451struct EditorActionId(usize);
452
453impl EditorActionId {
454 pub fn post_inc(&mut self) -> Self {
455 let answer = self.0;
456
457 *self = Self(answer + 1);
458
459 Self(answer)
460 }
461}
462
463// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
464// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
465
466type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
467type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
468
469#[derive(Default)]
470struct ScrollbarMarkerState {
471 scrollbar_size: Size<Pixels>,
472 dirty: bool,
473 markers: Arc<[PaintQuad]>,
474 pending_refresh: Option<Task<Result<()>>>,
475}
476
477impl ScrollbarMarkerState {
478 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
479 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
480 }
481}
482
483#[derive(Clone, Debug)]
484struct RunnableTasks {
485 templates: Vec<(TaskSourceKind, TaskTemplate)>,
486 offset: MultiBufferOffset,
487 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
488 column: u32,
489 // Values of all named captures, including those starting with '_'
490 extra_variables: HashMap<String, String>,
491 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
492 context_range: Range<BufferOffset>,
493}
494
495#[derive(Clone)]
496struct ResolvedTasks {
497 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
498 position: Anchor,
499}
500#[derive(Copy, Clone, Debug)]
501struct MultiBufferOffset(usize);
502#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
503struct BufferOffset(usize);
504
505// Addons allow storing per-editor state in other crates (e.g. Vim)
506pub trait Addon: 'static {
507 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
508
509 fn to_any(&self) -> &dyn std::any::Any;
510}
511
512/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
513///
514/// See the [module level documentation](self) for more information.
515pub struct Editor {
516 focus_handle: FocusHandle,
517 last_focused_descendant: Option<WeakFocusHandle>,
518 /// The text buffer being edited
519 buffer: Model<MultiBuffer>,
520 /// Map of how text in the buffer should be displayed.
521 /// Handles soft wraps, folds, fake inlay text insertions, etc.
522 pub display_map: Model<DisplayMap>,
523 pub selections: SelectionsCollection,
524 pub scroll_manager: ScrollManager,
525 /// When inline assist editors are linked, they all render cursors because
526 /// typing enters text into each of them, even the ones that aren't focused.
527 pub(crate) show_cursor_when_unfocused: bool,
528 columnar_selection_tail: Option<Anchor>,
529 add_selections_state: Option<AddSelectionsState>,
530 select_next_state: Option<SelectNextState>,
531 select_prev_state: Option<SelectNextState>,
532 selection_history: SelectionHistory,
533 autoclose_regions: Vec<AutocloseRegion>,
534 snippet_stack: InvalidationStack<SnippetState>,
535 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
536 ime_transaction: Option<TransactionId>,
537 active_diagnostics: Option<ActiveDiagnosticGroup>,
538 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
539 project: Option<Model<Project>>,
540 completion_provider: Option<Box<dyn CompletionProvider>>,
541 collaboration_hub: Option<Box<dyn CollaborationHub>>,
542 blink_manager: Model<BlinkManager>,
543 show_cursor_names: bool,
544 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
545 pub show_local_selections: bool,
546 mode: EditorMode,
547 show_breadcrumbs: bool,
548 show_gutter: bool,
549 show_line_numbers: Option<bool>,
550 use_relative_line_numbers: Option<bool>,
551 show_git_diff_gutter: Option<bool>,
552 show_code_actions: Option<bool>,
553 show_runnables: Option<bool>,
554 show_wrap_guides: Option<bool>,
555 show_indent_guides: Option<bool>,
556 placeholder_text: Option<Arc<str>>,
557 highlight_order: usize,
558 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
559 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
560 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
561 scrollbar_marker_state: ScrollbarMarkerState,
562 active_indent_guides_state: ActiveIndentGuidesState,
563 nav_history: Option<ItemNavHistory>,
564 context_menu: RwLock<Option<ContextMenu>>,
565 mouse_context_menu: Option<MouseContextMenu>,
566 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
567 signature_help_state: SignatureHelpState,
568 auto_signature_help: Option<bool>,
569 find_all_references_task_sources: Vec<Anchor>,
570 next_completion_id: CompletionId,
571 completion_documentation_pre_resolve_debounce: DebouncedDelay,
572 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
573 code_actions_task: Option<Task<Result<()>>>,
574 document_highlights_task: Option<Task<()>>,
575 linked_editing_range_task: Option<Task<Option<()>>>,
576 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
577 pending_rename: Option<RenameState>,
578 searchable: bool,
579 cursor_shape: CursorShape,
580 current_line_highlight: Option<CurrentLineHighlight>,
581 collapse_matches: bool,
582 autoindent_mode: Option<AutoindentMode>,
583 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
584 input_enabled: bool,
585 use_modal_editing: bool,
586 read_only: bool,
587 leader_peer_id: Option<PeerId>,
588 remote_id: Option<ViewId>,
589 hover_state: HoverState,
590 gutter_hovered: bool,
591 hovered_link_state: Option<HoveredLinkState>,
592 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
593 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
594 active_inline_completion: Option<CompletionState>,
595 // enable_inline_completions is a switch that Vim can use to disable
596 // inline completions based on its mode.
597 enable_inline_completions: bool,
598 show_inline_completions_override: Option<bool>,
599 inlay_hint_cache: InlayHintCache,
600 expanded_hunks: ExpandedHunks,
601 next_inlay_id: usize,
602 _subscriptions: Vec<Subscription>,
603 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
604 gutter_dimensions: GutterDimensions,
605 style: Option<EditorStyle>,
606 next_editor_action_id: EditorActionId,
607 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
608 use_autoclose: bool,
609 use_auto_surround: bool,
610 auto_replace_emoji_shortcode: bool,
611 show_git_blame_gutter: bool,
612 show_git_blame_inline: bool,
613 show_git_blame_inline_delay_task: Option<Task<()>>,
614 git_blame_inline_enabled: bool,
615 serialize_dirty_buffers: bool,
616 show_selection_menu: Option<bool>,
617 blame: Option<Model<GitBlame>>,
618 blame_subscription: Option<Subscription>,
619 custom_context_menu: Option<
620 Box<
621 dyn 'static
622 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
623 >,
624 >,
625 last_bounds: Option<Bounds<Pixels>>,
626 expect_bounds_change: Option<Bounds<Pixels>>,
627 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
628 tasks_update_task: Option<Task<()>>,
629 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
630 file_header_size: u32,
631 breadcrumb_header: Option<String>,
632 focused_block: Option<FocusedBlock>,
633 next_scroll_position: NextScrollCursorCenterTopBottom,
634 addons: HashMap<TypeId, Box<dyn Addon>>,
635 _scroll_cursor_center_top_bottom_task: Task<()>,
636}
637
638#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
639enum NextScrollCursorCenterTopBottom {
640 #[default]
641 Center,
642 Top,
643 Bottom,
644}
645
646impl NextScrollCursorCenterTopBottom {
647 fn next(&self) -> Self {
648 match self {
649 Self::Center => Self::Top,
650 Self::Top => Self::Bottom,
651 Self::Bottom => Self::Center,
652 }
653 }
654}
655
656#[derive(Clone)]
657pub struct EditorSnapshot {
658 pub mode: EditorMode,
659 show_gutter: bool,
660 show_line_numbers: Option<bool>,
661 show_git_diff_gutter: Option<bool>,
662 show_code_actions: Option<bool>,
663 show_runnables: Option<bool>,
664 render_git_blame_gutter: bool,
665 pub display_snapshot: DisplaySnapshot,
666 pub placeholder_text: Option<Arc<str>>,
667 is_focused: bool,
668 scroll_anchor: ScrollAnchor,
669 ongoing_scroll: OngoingScroll,
670 current_line_highlight: CurrentLineHighlight,
671 gutter_hovered: bool,
672}
673
674const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
675
676#[derive(Default, Debug, Clone, Copy)]
677pub struct GutterDimensions {
678 pub left_padding: Pixels,
679 pub right_padding: Pixels,
680 pub width: Pixels,
681 pub margin: Pixels,
682 pub git_blame_entries_width: Option<Pixels>,
683}
684
685impl GutterDimensions {
686 /// The full width of the space taken up by the gutter.
687 pub fn full_width(&self) -> Pixels {
688 self.margin + self.width
689 }
690
691 /// The width of the space reserved for the fold indicators,
692 /// use alongside 'justify_end' and `gutter_width` to
693 /// right align content with the line numbers
694 pub fn fold_area_width(&self) -> Pixels {
695 self.margin + self.right_padding
696 }
697}
698
699#[derive(Debug)]
700pub struct RemoteSelection {
701 pub replica_id: ReplicaId,
702 pub selection: Selection<Anchor>,
703 pub cursor_shape: CursorShape,
704 pub peer_id: PeerId,
705 pub line_mode: bool,
706 pub participant_index: Option<ParticipantIndex>,
707 pub user_name: Option<SharedString>,
708}
709
710#[derive(Clone, Debug)]
711struct SelectionHistoryEntry {
712 selections: Arc<[Selection<Anchor>]>,
713 select_next_state: Option<SelectNextState>,
714 select_prev_state: Option<SelectNextState>,
715 add_selections_state: Option<AddSelectionsState>,
716}
717
718enum SelectionHistoryMode {
719 Normal,
720 Undoing,
721 Redoing,
722}
723
724#[derive(Clone, PartialEq, Eq, Hash)]
725struct HoveredCursor {
726 replica_id: u16,
727 selection_id: usize,
728}
729
730impl Default for SelectionHistoryMode {
731 fn default() -> Self {
732 Self::Normal
733 }
734}
735
736#[derive(Default)]
737struct SelectionHistory {
738 #[allow(clippy::type_complexity)]
739 selections_by_transaction:
740 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
741 mode: SelectionHistoryMode,
742 undo_stack: VecDeque<SelectionHistoryEntry>,
743 redo_stack: VecDeque<SelectionHistoryEntry>,
744}
745
746impl SelectionHistory {
747 fn insert_transaction(
748 &mut self,
749 transaction_id: TransactionId,
750 selections: Arc<[Selection<Anchor>]>,
751 ) {
752 self.selections_by_transaction
753 .insert(transaction_id, (selections, None));
754 }
755
756 #[allow(clippy::type_complexity)]
757 fn transaction(
758 &self,
759 transaction_id: TransactionId,
760 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
761 self.selections_by_transaction.get(&transaction_id)
762 }
763
764 #[allow(clippy::type_complexity)]
765 fn transaction_mut(
766 &mut self,
767 transaction_id: TransactionId,
768 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
769 self.selections_by_transaction.get_mut(&transaction_id)
770 }
771
772 fn push(&mut self, entry: SelectionHistoryEntry) {
773 if !entry.selections.is_empty() {
774 match self.mode {
775 SelectionHistoryMode::Normal => {
776 self.push_undo(entry);
777 self.redo_stack.clear();
778 }
779 SelectionHistoryMode::Undoing => self.push_redo(entry),
780 SelectionHistoryMode::Redoing => self.push_undo(entry),
781 }
782 }
783 }
784
785 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
786 if self
787 .undo_stack
788 .back()
789 .map_or(true, |e| e.selections != entry.selections)
790 {
791 self.undo_stack.push_back(entry);
792 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
793 self.undo_stack.pop_front();
794 }
795 }
796 }
797
798 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
799 if self
800 .redo_stack
801 .back()
802 .map_or(true, |e| e.selections != entry.selections)
803 {
804 self.redo_stack.push_back(entry);
805 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
806 self.redo_stack.pop_front();
807 }
808 }
809 }
810}
811
812struct RowHighlight {
813 index: usize,
814 range: RangeInclusive<Anchor>,
815 color: Option<Hsla>,
816 should_autoscroll: bool,
817}
818
819#[derive(Clone, Debug)]
820struct AddSelectionsState {
821 above: bool,
822 stack: Vec<usize>,
823}
824
825#[derive(Clone)]
826struct SelectNextState {
827 query: AhoCorasick,
828 wordwise: bool,
829 done: bool,
830}
831
832impl std::fmt::Debug for SelectNextState {
833 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834 f.debug_struct(std::any::type_name::<Self>())
835 .field("wordwise", &self.wordwise)
836 .field("done", &self.done)
837 .finish()
838 }
839}
840
841#[derive(Debug)]
842struct AutocloseRegion {
843 selection_id: usize,
844 range: Range<Anchor>,
845 pair: BracketPair,
846}
847
848#[derive(Debug)]
849struct SnippetState {
850 ranges: Vec<Vec<Range<Anchor>>>,
851 active_index: usize,
852}
853
854#[doc(hidden)]
855pub struct RenameState {
856 pub range: Range<Anchor>,
857 pub old_name: Arc<str>,
858 pub editor: View<Editor>,
859 block_id: CustomBlockId,
860}
861
862struct InvalidationStack<T>(Vec<T>);
863
864struct RegisteredInlineCompletionProvider {
865 provider: Arc<dyn InlineCompletionProviderHandle>,
866 _subscription: Subscription,
867}
868
869enum ContextMenu {
870 Completions(CompletionsMenu),
871 CodeActions(CodeActionsMenu),
872}
873
874impl ContextMenu {
875 fn select_first(
876 &mut self,
877 project: Option<&Model<Project>>,
878 cx: &mut ViewContext<Editor>,
879 ) -> bool {
880 if self.visible() {
881 match self {
882 ContextMenu::Completions(menu) => menu.select_first(project, cx),
883 ContextMenu::CodeActions(menu) => menu.select_first(cx),
884 }
885 true
886 } else {
887 false
888 }
889 }
890
891 fn select_prev(
892 &mut self,
893 project: Option<&Model<Project>>,
894 cx: &mut ViewContext<Editor>,
895 ) -> bool {
896 if self.visible() {
897 match self {
898 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
899 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
900 }
901 true
902 } else {
903 false
904 }
905 }
906
907 fn select_next(
908 &mut self,
909 project: Option<&Model<Project>>,
910 cx: &mut ViewContext<Editor>,
911 ) -> bool {
912 if self.visible() {
913 match self {
914 ContextMenu::Completions(menu) => menu.select_next(project, cx),
915 ContextMenu::CodeActions(menu) => menu.select_next(cx),
916 }
917 true
918 } else {
919 false
920 }
921 }
922
923 fn select_last(
924 &mut self,
925 project: Option<&Model<Project>>,
926 cx: &mut ViewContext<Editor>,
927 ) -> bool {
928 if self.visible() {
929 match self {
930 ContextMenu::Completions(menu) => menu.select_last(project, cx),
931 ContextMenu::CodeActions(menu) => menu.select_last(cx),
932 }
933 true
934 } else {
935 false
936 }
937 }
938
939 fn visible(&self) -> bool {
940 match self {
941 ContextMenu::Completions(menu) => menu.visible(),
942 ContextMenu::CodeActions(menu) => menu.visible(),
943 }
944 }
945
946 fn render(
947 &self,
948 cursor_position: DisplayPoint,
949 style: &EditorStyle,
950 max_height: Pixels,
951 workspace: Option<WeakView<Workspace>>,
952 cx: &mut ViewContext<Editor>,
953 ) -> (ContextMenuOrigin, AnyElement) {
954 match self {
955 ContextMenu::Completions(menu) => (
956 ContextMenuOrigin::EditorPoint(cursor_position),
957 menu.render(style, max_height, workspace, cx),
958 ),
959 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
960 }
961 }
962}
963
964enum ContextMenuOrigin {
965 EditorPoint(DisplayPoint),
966 GutterIndicator(DisplayRow),
967}
968
969#[derive(Clone)]
970struct CompletionsMenu {
971 id: CompletionId,
972 sort_completions: bool,
973 initial_position: Anchor,
974 buffer: Model<Buffer>,
975 completions: Arc<RwLock<Box<[Completion]>>>,
976 match_candidates: Arc<[StringMatchCandidate]>,
977 matches: Arc<[StringMatch]>,
978 selected_item: usize,
979 scroll_handle: UniformListScrollHandle,
980 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
981}
982
983impl CompletionsMenu {
984 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
985 self.selected_item = 0;
986 self.scroll_handle.scroll_to_item(self.selected_item);
987 self.attempt_resolve_selected_completion_documentation(project, cx);
988 cx.notify();
989 }
990
991 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
992 if self.selected_item > 0 {
993 self.selected_item -= 1;
994 } else {
995 self.selected_item = self.matches.len() - 1;
996 }
997 self.scroll_handle.scroll_to_item(self.selected_item);
998 self.attempt_resolve_selected_completion_documentation(project, cx);
999 cx.notify();
1000 }
1001
1002 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1003 if self.selected_item + 1 < self.matches.len() {
1004 self.selected_item += 1;
1005 } else {
1006 self.selected_item = 0;
1007 }
1008 self.scroll_handle.scroll_to_item(self.selected_item);
1009 self.attempt_resolve_selected_completion_documentation(project, cx);
1010 cx.notify();
1011 }
1012
1013 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1014 self.selected_item = self.matches.len() - 1;
1015 self.scroll_handle.scroll_to_item(self.selected_item);
1016 self.attempt_resolve_selected_completion_documentation(project, cx);
1017 cx.notify();
1018 }
1019
1020 fn pre_resolve_completion_documentation(
1021 buffer: Model<Buffer>,
1022 completions: Arc<RwLock<Box<[Completion]>>>,
1023 matches: Arc<[StringMatch]>,
1024 editor: &Editor,
1025 cx: &mut ViewContext<Editor>,
1026 ) -> Task<()> {
1027 let settings = EditorSettings::get_global(cx);
1028 if !settings.show_completion_documentation {
1029 return Task::ready(());
1030 }
1031
1032 let Some(provider) = editor.completion_provider.as_ref() else {
1033 return Task::ready(());
1034 };
1035
1036 let resolve_task = provider.resolve_completions(
1037 buffer,
1038 matches.iter().map(|m| m.candidate_id).collect(),
1039 completions.clone(),
1040 cx,
1041 );
1042
1043 cx.spawn(move |this, mut cx| async move {
1044 if let Some(true) = resolve_task.await.log_err() {
1045 this.update(&mut cx, |_, cx| cx.notify()).ok();
1046 }
1047 })
1048 }
1049
1050 fn attempt_resolve_selected_completion_documentation(
1051 &mut self,
1052 project: Option<&Model<Project>>,
1053 cx: &mut ViewContext<Editor>,
1054 ) {
1055 let settings = EditorSettings::get_global(cx);
1056 if !settings.show_completion_documentation {
1057 return;
1058 }
1059
1060 let completion_index = self.matches[self.selected_item].candidate_id;
1061 let Some(project) = project else {
1062 return;
1063 };
1064
1065 let resolve_task = project.update(cx, |project, cx| {
1066 project.resolve_completions(
1067 self.buffer.clone(),
1068 vec![completion_index],
1069 self.completions.clone(),
1070 cx,
1071 )
1072 });
1073
1074 let delay_ms =
1075 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1076 let delay = Duration::from_millis(delay_ms);
1077
1078 self.selected_completion_documentation_resolve_debounce
1079 .lock()
1080 .fire_new(delay, cx, |_, cx| {
1081 cx.spawn(move |this, mut cx| async move {
1082 if let Some(true) = resolve_task.await.log_err() {
1083 this.update(&mut cx, |_, cx| cx.notify()).ok();
1084 }
1085 })
1086 });
1087 }
1088
1089 fn visible(&self) -> bool {
1090 !self.matches.is_empty()
1091 }
1092
1093 fn render(
1094 &self,
1095 style: &EditorStyle,
1096 max_height: Pixels,
1097 workspace: Option<WeakView<Workspace>>,
1098 cx: &mut ViewContext<Editor>,
1099 ) -> AnyElement {
1100 let settings = EditorSettings::get_global(cx);
1101 let show_completion_documentation = settings.show_completion_documentation;
1102
1103 let widest_completion_ix = self
1104 .matches
1105 .iter()
1106 .enumerate()
1107 .max_by_key(|(_, mat)| {
1108 let completions = self.completions.read();
1109 let completion = &completions[mat.candidate_id];
1110 let documentation = &completion.documentation;
1111
1112 let mut len = completion.label.text.chars().count();
1113 if let Some(Documentation::SingleLine(text)) = documentation {
1114 if show_completion_documentation {
1115 len += text.chars().count();
1116 }
1117 }
1118
1119 len
1120 })
1121 .map(|(ix, _)| ix);
1122
1123 let completions = self.completions.clone();
1124 let matches = self.matches.clone();
1125 let selected_item = self.selected_item;
1126 let style = style.clone();
1127
1128 let multiline_docs = if show_completion_documentation {
1129 let mat = &self.matches[selected_item];
1130 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1131 Some(Documentation::MultiLinePlainText(text)) => {
1132 Some(div().child(SharedString::from(text.clone())))
1133 }
1134 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1135 Some(div().child(render_parsed_markdown(
1136 "completions_markdown",
1137 parsed,
1138 &style,
1139 workspace,
1140 cx,
1141 )))
1142 }
1143 _ => None,
1144 };
1145 multiline_docs.map(|div| {
1146 div.id("multiline_docs")
1147 .max_h(max_height)
1148 .flex_1()
1149 .px_1p5()
1150 .py_1()
1151 .min_w(px(260.))
1152 .max_w(px(640.))
1153 .w(px(500.))
1154 .overflow_y_scroll()
1155 .occlude()
1156 })
1157 } else {
1158 None
1159 };
1160
1161 let list = uniform_list(
1162 cx.view().clone(),
1163 "completions",
1164 matches.len(),
1165 move |_editor, range, cx| {
1166 let start_ix = range.start;
1167 let completions_guard = completions.read();
1168
1169 matches[range]
1170 .iter()
1171 .enumerate()
1172 .map(|(ix, mat)| {
1173 let item_ix = start_ix + ix;
1174 let candidate_id = mat.candidate_id;
1175 let completion = &completions_guard[candidate_id];
1176
1177 let documentation = if show_completion_documentation {
1178 &completion.documentation
1179 } else {
1180 &None
1181 };
1182
1183 let highlights = gpui::combine_highlights(
1184 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1185 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1186 |(range, mut highlight)| {
1187 // Ignore font weight for syntax highlighting, as we'll use it
1188 // for fuzzy matches.
1189 highlight.font_weight = None;
1190
1191 if completion.lsp_completion.deprecated.unwrap_or(false) {
1192 highlight.strikethrough = Some(StrikethroughStyle {
1193 thickness: 1.0.into(),
1194 ..Default::default()
1195 });
1196 highlight.color = Some(cx.theme().colors().text_muted);
1197 }
1198
1199 (range, highlight)
1200 },
1201 ),
1202 );
1203 let completion_label = StyledText::new(completion.label.text.clone())
1204 .with_highlights(&style.text, highlights);
1205 let documentation_label =
1206 if let Some(Documentation::SingleLine(text)) = documentation {
1207 if text.trim().is_empty() {
1208 None
1209 } else {
1210 Some(
1211 Label::new(text.clone())
1212 .ml_4()
1213 .size(LabelSize::Small)
1214 .color(Color::Muted),
1215 )
1216 }
1217 } else {
1218 None
1219 };
1220
1221 div().min_w(px(220.)).max_w(px(540.)).child(
1222 ListItem::new(mat.candidate_id)
1223 .inset(true)
1224 .selected(item_ix == selected_item)
1225 .on_click(cx.listener(move |editor, _event, cx| {
1226 cx.stop_propagation();
1227 if let Some(task) = editor.confirm_completion(
1228 &ConfirmCompletion {
1229 item_ix: Some(item_ix),
1230 },
1231 cx,
1232 ) {
1233 task.detach_and_log_err(cx)
1234 }
1235 }))
1236 .child(h_flex().overflow_hidden().child(completion_label))
1237 .end_slot::<Label>(documentation_label),
1238 )
1239 })
1240 .collect()
1241 },
1242 )
1243 .occlude()
1244 .max_h(max_height)
1245 .track_scroll(self.scroll_handle.clone())
1246 .with_width_from_item(widest_completion_ix)
1247 .with_sizing_behavior(ListSizingBehavior::Infer);
1248
1249 Popover::new()
1250 .child(list)
1251 .when_some(multiline_docs, |popover, multiline_docs| {
1252 popover.aside(multiline_docs)
1253 })
1254 .into_any_element()
1255 }
1256
1257 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1258 let mut matches = if let Some(query) = query {
1259 fuzzy::match_strings(
1260 &self.match_candidates,
1261 query,
1262 query.chars().any(|c| c.is_uppercase()),
1263 100,
1264 &Default::default(),
1265 executor,
1266 )
1267 .await
1268 } else {
1269 self.match_candidates
1270 .iter()
1271 .enumerate()
1272 .map(|(candidate_id, candidate)| StringMatch {
1273 candidate_id,
1274 score: Default::default(),
1275 positions: Default::default(),
1276 string: candidate.string.clone(),
1277 })
1278 .collect()
1279 };
1280
1281 // Remove all candidates where the query's start does not match the start of any word in the candidate
1282 if let Some(query) = query {
1283 if let Some(query_start) = query.chars().next() {
1284 matches.retain(|string_match| {
1285 split_words(&string_match.string).any(|word| {
1286 // Check that the first codepoint of the word as lowercase matches the first
1287 // codepoint of the query as lowercase
1288 word.chars()
1289 .flat_map(|codepoint| codepoint.to_lowercase())
1290 .zip(query_start.to_lowercase())
1291 .all(|(word_cp, query_cp)| word_cp == query_cp)
1292 })
1293 });
1294 }
1295 }
1296
1297 let completions = self.completions.read();
1298 if self.sort_completions {
1299 matches.sort_unstable_by_key(|mat| {
1300 // We do want to strike a balance here between what the language server tells us
1301 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1302 // `Creat` and there is a local variable called `CreateComponent`).
1303 // So what we do is: we bucket all matches into two buckets
1304 // - Strong matches
1305 // - Weak matches
1306 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1307 // and the Weak matches are the rest.
1308 //
1309 // For the strong matches, we sort by the language-servers score first and for the weak
1310 // matches, we prefer our fuzzy finder first.
1311 //
1312 // The thinking behind that: it's useless to take the sort_text the language-server gives
1313 // us into account when it's obviously a bad match.
1314
1315 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1316 enum MatchScore<'a> {
1317 Strong {
1318 sort_text: Option<&'a str>,
1319 score: Reverse<OrderedFloat<f64>>,
1320 sort_key: (usize, &'a str),
1321 },
1322 Weak {
1323 score: Reverse<OrderedFloat<f64>>,
1324 sort_text: Option<&'a str>,
1325 sort_key: (usize, &'a str),
1326 },
1327 }
1328
1329 let completion = &completions[mat.candidate_id];
1330 let sort_key = completion.sort_key();
1331 let sort_text = completion.lsp_completion.sort_text.as_deref();
1332 let score = Reverse(OrderedFloat(mat.score));
1333
1334 if mat.score >= 0.2 {
1335 MatchScore::Strong {
1336 sort_text,
1337 score,
1338 sort_key,
1339 }
1340 } else {
1341 MatchScore::Weak {
1342 score,
1343 sort_text,
1344 sort_key,
1345 }
1346 }
1347 });
1348 }
1349
1350 for mat in &mut matches {
1351 let completion = &completions[mat.candidate_id];
1352 mat.string.clone_from(&completion.label.text);
1353 for position in &mut mat.positions {
1354 *position += completion.label.filter_range.start;
1355 }
1356 }
1357 drop(completions);
1358
1359 self.matches = matches.into();
1360 self.selected_item = 0;
1361 }
1362}
1363
1364struct AvailableCodeAction {
1365 excerpt_id: ExcerptId,
1366 action: CodeAction,
1367 provider: Arc<dyn CodeActionProvider>,
1368}
1369
1370#[derive(Clone)]
1371struct CodeActionContents {
1372 tasks: Option<Arc<ResolvedTasks>>,
1373 actions: Option<Arc<[AvailableCodeAction]>>,
1374}
1375
1376impl CodeActionContents {
1377 fn len(&self) -> usize {
1378 match (&self.tasks, &self.actions) {
1379 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1380 (Some(tasks), None) => tasks.templates.len(),
1381 (None, Some(actions)) => actions.len(),
1382 (None, None) => 0,
1383 }
1384 }
1385
1386 fn is_empty(&self) -> bool {
1387 match (&self.tasks, &self.actions) {
1388 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1389 (Some(tasks), None) => tasks.templates.is_empty(),
1390 (None, Some(actions)) => actions.is_empty(),
1391 (None, None) => true,
1392 }
1393 }
1394
1395 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1396 self.tasks
1397 .iter()
1398 .flat_map(|tasks| {
1399 tasks
1400 .templates
1401 .iter()
1402 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1403 })
1404 .chain(self.actions.iter().flat_map(|actions| {
1405 actions.iter().map(|available| CodeActionsItem::CodeAction {
1406 excerpt_id: available.excerpt_id,
1407 action: available.action.clone(),
1408 provider: available.provider.clone(),
1409 })
1410 }))
1411 }
1412 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1413 match (&self.tasks, &self.actions) {
1414 (Some(tasks), Some(actions)) => {
1415 if index < tasks.templates.len() {
1416 tasks
1417 .templates
1418 .get(index)
1419 .cloned()
1420 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1421 } else {
1422 actions.get(index - tasks.templates.len()).map(|available| {
1423 CodeActionsItem::CodeAction {
1424 excerpt_id: available.excerpt_id,
1425 action: available.action.clone(),
1426 provider: available.provider.clone(),
1427 }
1428 })
1429 }
1430 }
1431 (Some(tasks), None) => tasks
1432 .templates
1433 .get(index)
1434 .cloned()
1435 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1436 (None, Some(actions)) => {
1437 actions
1438 .get(index)
1439 .map(|available| CodeActionsItem::CodeAction {
1440 excerpt_id: available.excerpt_id,
1441 action: available.action.clone(),
1442 provider: available.provider.clone(),
1443 })
1444 }
1445 (None, None) => None,
1446 }
1447 }
1448}
1449
1450#[allow(clippy::large_enum_variant)]
1451#[derive(Clone)]
1452enum CodeActionsItem {
1453 Task(TaskSourceKind, ResolvedTask),
1454 CodeAction {
1455 excerpt_id: ExcerptId,
1456 action: CodeAction,
1457 provider: Arc<dyn CodeActionProvider>,
1458 },
1459}
1460
1461impl CodeActionsItem {
1462 fn as_task(&self) -> Option<&ResolvedTask> {
1463 let Self::Task(_, task) = self else {
1464 return None;
1465 };
1466 Some(task)
1467 }
1468 fn as_code_action(&self) -> Option<&CodeAction> {
1469 let Self::CodeAction { action, .. } = self else {
1470 return None;
1471 };
1472 Some(action)
1473 }
1474 fn label(&self) -> String {
1475 match self {
1476 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1477 Self::Task(_, task) => task.resolved_label.clone(),
1478 }
1479 }
1480}
1481
1482struct CodeActionsMenu {
1483 actions: CodeActionContents,
1484 buffer: Model<Buffer>,
1485 selected_item: usize,
1486 scroll_handle: UniformListScrollHandle,
1487 deployed_from_indicator: Option<DisplayRow>,
1488}
1489
1490impl CodeActionsMenu {
1491 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1492 self.selected_item = 0;
1493 self.scroll_handle.scroll_to_item(self.selected_item);
1494 cx.notify()
1495 }
1496
1497 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1498 if self.selected_item > 0 {
1499 self.selected_item -= 1;
1500 } else {
1501 self.selected_item = self.actions.len() - 1;
1502 }
1503 self.scroll_handle.scroll_to_item(self.selected_item);
1504 cx.notify();
1505 }
1506
1507 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1508 if self.selected_item + 1 < self.actions.len() {
1509 self.selected_item += 1;
1510 } else {
1511 self.selected_item = 0;
1512 }
1513 self.scroll_handle.scroll_to_item(self.selected_item);
1514 cx.notify();
1515 }
1516
1517 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1518 self.selected_item = self.actions.len() - 1;
1519 self.scroll_handle.scroll_to_item(self.selected_item);
1520 cx.notify()
1521 }
1522
1523 fn visible(&self) -> bool {
1524 !self.actions.is_empty()
1525 }
1526
1527 fn render(
1528 &self,
1529 cursor_position: DisplayPoint,
1530 _style: &EditorStyle,
1531 max_height: Pixels,
1532 cx: &mut ViewContext<Editor>,
1533 ) -> (ContextMenuOrigin, AnyElement) {
1534 let actions = self.actions.clone();
1535 let selected_item = self.selected_item;
1536 let element = uniform_list(
1537 cx.view().clone(),
1538 "code_actions_menu",
1539 self.actions.len(),
1540 move |_this, range, cx| {
1541 actions
1542 .iter()
1543 .skip(range.start)
1544 .take(range.end - range.start)
1545 .enumerate()
1546 .map(|(ix, action)| {
1547 let item_ix = range.start + ix;
1548 let selected = selected_item == item_ix;
1549 let colors = cx.theme().colors();
1550 div()
1551 .px_1()
1552 .rounded_md()
1553 .text_color(colors.text)
1554 .when(selected, |style| {
1555 style
1556 .bg(colors.element_active)
1557 .text_color(colors.text_accent)
1558 })
1559 .hover(|style| {
1560 style
1561 .bg(colors.element_hover)
1562 .text_color(colors.text_accent)
1563 })
1564 .whitespace_nowrap()
1565 .when_some(action.as_code_action(), |this, action| {
1566 this.on_mouse_down(
1567 MouseButton::Left,
1568 cx.listener(move |editor, _, cx| {
1569 cx.stop_propagation();
1570 if let Some(task) = editor.confirm_code_action(
1571 &ConfirmCodeAction {
1572 item_ix: Some(item_ix),
1573 },
1574 cx,
1575 ) {
1576 task.detach_and_log_err(cx)
1577 }
1578 }),
1579 )
1580 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1581 .child(SharedString::from(action.lsp_action.title.clone()))
1582 })
1583 .when_some(action.as_task(), |this, task| {
1584 this.on_mouse_down(
1585 MouseButton::Left,
1586 cx.listener(move |editor, _, cx| {
1587 cx.stop_propagation();
1588 if let Some(task) = editor.confirm_code_action(
1589 &ConfirmCodeAction {
1590 item_ix: Some(item_ix),
1591 },
1592 cx,
1593 ) {
1594 task.detach_and_log_err(cx)
1595 }
1596 }),
1597 )
1598 .child(SharedString::from(task.resolved_label.clone()))
1599 })
1600 })
1601 .collect()
1602 },
1603 )
1604 .elevation_1(cx)
1605 .p_1()
1606 .max_h(max_height)
1607 .occlude()
1608 .track_scroll(self.scroll_handle.clone())
1609 .with_width_from_item(
1610 self.actions
1611 .iter()
1612 .enumerate()
1613 .max_by_key(|(_, action)| match action {
1614 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1615 CodeActionsItem::CodeAction { action, .. } => {
1616 action.lsp_action.title.chars().count()
1617 }
1618 })
1619 .map(|(ix, _)| ix),
1620 )
1621 .with_sizing_behavior(ListSizingBehavior::Infer)
1622 .into_any_element();
1623
1624 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1625 ContextMenuOrigin::GutterIndicator(row)
1626 } else {
1627 ContextMenuOrigin::EditorPoint(cursor_position)
1628 };
1629
1630 (cursor_position, element)
1631 }
1632}
1633
1634#[derive(Debug)]
1635struct ActiveDiagnosticGroup {
1636 primary_range: Range<Anchor>,
1637 primary_message: String,
1638 group_id: usize,
1639 blocks: HashMap<CustomBlockId, Diagnostic>,
1640 is_valid: bool,
1641}
1642
1643#[derive(Serialize, Deserialize, Clone, Debug)]
1644pub struct ClipboardSelection {
1645 pub len: usize,
1646 pub is_entire_line: bool,
1647 pub first_line_indent: u32,
1648}
1649
1650#[derive(Debug)]
1651pub(crate) struct NavigationData {
1652 cursor_anchor: Anchor,
1653 cursor_position: Point,
1654 scroll_anchor: ScrollAnchor,
1655 scroll_top_row: u32,
1656}
1657
1658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1659enum GotoDefinitionKind {
1660 Symbol,
1661 Declaration,
1662 Type,
1663 Implementation,
1664}
1665
1666#[derive(Debug, Clone)]
1667enum InlayHintRefreshReason {
1668 Toggle(bool),
1669 SettingsChange(InlayHintSettings),
1670 NewLinesShown,
1671 BufferEdited(HashSet<Arc<Language>>),
1672 RefreshRequested,
1673 ExcerptsRemoved(Vec<ExcerptId>),
1674}
1675
1676impl InlayHintRefreshReason {
1677 fn description(&self) -> &'static str {
1678 match self {
1679 Self::Toggle(_) => "toggle",
1680 Self::SettingsChange(_) => "settings change",
1681 Self::NewLinesShown => "new lines shown",
1682 Self::BufferEdited(_) => "buffer edited",
1683 Self::RefreshRequested => "refresh requested",
1684 Self::ExcerptsRemoved(_) => "excerpts removed",
1685 }
1686 }
1687}
1688
1689pub(crate) struct FocusedBlock {
1690 id: BlockId,
1691 focus_handle: WeakFocusHandle,
1692}
1693
1694impl Editor {
1695 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1696 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1697 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1698 Self::new(
1699 EditorMode::SingleLine { auto_width: false },
1700 buffer,
1701 None,
1702 false,
1703 cx,
1704 )
1705 }
1706
1707 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1708 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1709 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1710 Self::new(EditorMode::Full, buffer, None, false, cx)
1711 }
1712
1713 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1714 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1715 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1716 Self::new(
1717 EditorMode::SingleLine { auto_width: true },
1718 buffer,
1719 None,
1720 false,
1721 cx,
1722 )
1723 }
1724
1725 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1726 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1727 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1728 Self::new(
1729 EditorMode::AutoHeight { max_lines },
1730 buffer,
1731 None,
1732 false,
1733 cx,
1734 )
1735 }
1736
1737 pub fn for_buffer(
1738 buffer: Model<Buffer>,
1739 project: Option<Model<Project>>,
1740 cx: &mut ViewContext<Self>,
1741 ) -> Self {
1742 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1743 Self::new(EditorMode::Full, buffer, project, false, cx)
1744 }
1745
1746 pub fn for_multibuffer(
1747 buffer: Model<MultiBuffer>,
1748 project: Option<Model<Project>>,
1749 show_excerpt_controls: bool,
1750 cx: &mut ViewContext<Self>,
1751 ) -> Self {
1752 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1753 }
1754
1755 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1756 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1757 let mut clone = Self::new(
1758 self.mode,
1759 self.buffer.clone(),
1760 self.project.clone(),
1761 show_excerpt_controls,
1762 cx,
1763 );
1764 self.display_map.update(cx, |display_map, cx| {
1765 let snapshot = display_map.snapshot(cx);
1766 clone.display_map.update(cx, |display_map, cx| {
1767 display_map.set_state(&snapshot, cx);
1768 });
1769 });
1770 clone.selections.clone_state(&self.selections);
1771 clone.scroll_manager.clone_state(&self.scroll_manager);
1772 clone.searchable = self.searchable;
1773 clone
1774 }
1775
1776 pub fn new(
1777 mode: EditorMode,
1778 buffer: Model<MultiBuffer>,
1779 project: Option<Model<Project>>,
1780 show_excerpt_controls: bool,
1781 cx: &mut ViewContext<Self>,
1782 ) -> Self {
1783 let style = cx.text_style();
1784 let font_size = style.font_size.to_pixels(cx.rem_size());
1785 let editor = cx.view().downgrade();
1786 let fold_placeholder = FoldPlaceholder {
1787 constrain_width: true,
1788 render: Arc::new(move |fold_id, fold_range, cx| {
1789 let editor = editor.clone();
1790 div()
1791 .id(fold_id)
1792 .bg(cx.theme().colors().ghost_element_background)
1793 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1794 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1795 .rounded_sm()
1796 .size_full()
1797 .cursor_pointer()
1798 .child("⋯")
1799 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1800 .on_click(move |_, cx| {
1801 editor
1802 .update(cx, |editor, cx| {
1803 editor.unfold_ranges(
1804 [fold_range.start..fold_range.end],
1805 true,
1806 false,
1807 cx,
1808 );
1809 cx.stop_propagation();
1810 })
1811 .ok();
1812 })
1813 .into_any()
1814 }),
1815 merge_adjacent: true,
1816 };
1817 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1818 let display_map = cx.new_model(|cx| {
1819 DisplayMap::new(
1820 buffer.clone(),
1821 style.font(),
1822 font_size,
1823 None,
1824 show_excerpt_controls,
1825 file_header_size,
1826 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1827 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1828 fold_placeholder,
1829 cx,
1830 )
1831 });
1832
1833 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1834
1835 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1836
1837 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1838 .then(|| language_settings::SoftWrap::PreferLine);
1839
1840 let mut project_subscriptions = Vec::new();
1841 if mode == EditorMode::Full {
1842 if let Some(project) = project.as_ref() {
1843 if buffer.read(cx).is_singleton() {
1844 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1845 cx.emit(EditorEvent::TitleChanged);
1846 }));
1847 }
1848 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1849 if let project::Event::RefreshInlayHints = event {
1850 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1851 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1852 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1853 let focus_handle = editor.focus_handle(cx);
1854 if focus_handle.is_focused(cx) {
1855 let snapshot = buffer.read(cx).snapshot();
1856 for (range, snippet) in snippet_edits {
1857 let editor_range =
1858 language::range_from_lsp(*range).to_offset(&snapshot);
1859 editor
1860 .insert_snippet(&[editor_range], snippet.clone(), cx)
1861 .ok();
1862 }
1863 }
1864 }
1865 }
1866 }));
1867 let task_inventory = project.read(cx).task_inventory().clone();
1868 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1869 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1870 }));
1871 }
1872 }
1873
1874 let inlay_hint_settings = inlay_hint_settings(
1875 selections.newest_anchor().head(),
1876 &buffer.read(cx).snapshot(cx),
1877 cx,
1878 );
1879 let focus_handle = cx.focus_handle();
1880 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1881 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1882 .detach();
1883 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1884 .detach();
1885 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1886
1887 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1888 Some(false)
1889 } else {
1890 None
1891 };
1892
1893 let mut code_action_providers = Vec::new();
1894 if let Some(project) = project.clone() {
1895 code_action_providers.push(Arc::new(project) as Arc<_>);
1896 }
1897
1898 let mut this = Self {
1899 focus_handle,
1900 show_cursor_when_unfocused: false,
1901 last_focused_descendant: None,
1902 buffer: buffer.clone(),
1903 display_map: display_map.clone(),
1904 selections,
1905 scroll_manager: ScrollManager::new(cx),
1906 columnar_selection_tail: None,
1907 add_selections_state: None,
1908 select_next_state: None,
1909 select_prev_state: None,
1910 selection_history: Default::default(),
1911 autoclose_regions: Default::default(),
1912 snippet_stack: Default::default(),
1913 select_larger_syntax_node_stack: Vec::new(),
1914 ime_transaction: Default::default(),
1915 active_diagnostics: None,
1916 soft_wrap_mode_override,
1917 completion_provider: project.clone().map(|project| Box::new(project) as _),
1918 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1919 project,
1920 blink_manager: blink_manager.clone(),
1921 show_local_selections: true,
1922 mode,
1923 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1924 show_gutter: mode == EditorMode::Full,
1925 show_line_numbers: None,
1926 use_relative_line_numbers: None,
1927 show_git_diff_gutter: None,
1928 show_code_actions: None,
1929 show_runnables: None,
1930 show_wrap_guides: None,
1931 show_indent_guides,
1932 placeholder_text: None,
1933 highlight_order: 0,
1934 highlighted_rows: HashMap::default(),
1935 background_highlights: Default::default(),
1936 gutter_highlights: TreeMap::default(),
1937 scrollbar_marker_state: ScrollbarMarkerState::default(),
1938 active_indent_guides_state: ActiveIndentGuidesState::default(),
1939 nav_history: None,
1940 context_menu: RwLock::new(None),
1941 mouse_context_menu: None,
1942 completion_tasks: Default::default(),
1943 signature_help_state: SignatureHelpState::default(),
1944 auto_signature_help: None,
1945 find_all_references_task_sources: Vec::new(),
1946 next_completion_id: 0,
1947 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1948 next_inlay_id: 0,
1949 code_action_providers,
1950 available_code_actions: Default::default(),
1951 code_actions_task: Default::default(),
1952 document_highlights_task: Default::default(),
1953 linked_editing_range_task: Default::default(),
1954 pending_rename: Default::default(),
1955 searchable: true,
1956 cursor_shape: EditorSettings::get_global(cx)
1957 .cursor_shape
1958 .unwrap_or_default(),
1959 current_line_highlight: None,
1960 autoindent_mode: Some(AutoindentMode::EachLine),
1961 collapse_matches: false,
1962 workspace: None,
1963 input_enabled: true,
1964 use_modal_editing: mode == EditorMode::Full,
1965 read_only: false,
1966 use_autoclose: true,
1967 use_auto_surround: true,
1968 auto_replace_emoji_shortcode: false,
1969 leader_peer_id: None,
1970 remote_id: None,
1971 hover_state: Default::default(),
1972 hovered_link_state: Default::default(),
1973 inline_completion_provider: None,
1974 active_inline_completion: None,
1975 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1976 expanded_hunks: ExpandedHunks::default(),
1977 gutter_hovered: false,
1978 pixel_position_of_newest_cursor: None,
1979 last_bounds: None,
1980 expect_bounds_change: None,
1981 gutter_dimensions: GutterDimensions::default(),
1982 style: None,
1983 show_cursor_names: false,
1984 hovered_cursors: Default::default(),
1985 next_editor_action_id: EditorActionId::default(),
1986 editor_actions: Rc::default(),
1987 show_inline_completions_override: None,
1988 enable_inline_completions: true,
1989 custom_context_menu: None,
1990 show_git_blame_gutter: false,
1991 show_git_blame_inline: false,
1992 show_selection_menu: None,
1993 show_git_blame_inline_delay_task: None,
1994 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1995 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1996 .session
1997 .restore_unsaved_buffers,
1998 blame: None,
1999 blame_subscription: None,
2000 file_header_size,
2001 tasks: Default::default(),
2002 _subscriptions: vec![
2003 cx.observe(&buffer, Self::on_buffer_changed),
2004 cx.subscribe(&buffer, Self::on_buffer_event),
2005 cx.observe(&display_map, Self::on_display_map_changed),
2006 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2007 cx.observe_global::<SettingsStore>(Self::settings_changed),
2008 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2009 cx.observe_window_activation(|editor, cx| {
2010 let active = cx.is_window_active();
2011 editor.blink_manager.update(cx, |blink_manager, cx| {
2012 if active {
2013 blink_manager.enable(cx);
2014 } else {
2015 blink_manager.disable(cx);
2016 }
2017 });
2018 }),
2019 ],
2020 tasks_update_task: None,
2021 linked_edit_ranges: Default::default(),
2022 previous_search_ranges: None,
2023 breadcrumb_header: None,
2024 focused_block: None,
2025 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2026 addons: HashMap::default(),
2027 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2028 };
2029 this.tasks_update_task = Some(this.refresh_runnables(cx));
2030 this._subscriptions.extend(project_subscriptions);
2031
2032 this.end_selection(cx);
2033 this.scroll_manager.show_scrollbar(cx);
2034
2035 if mode == EditorMode::Full {
2036 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2037 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2038
2039 if this.git_blame_inline_enabled {
2040 this.git_blame_inline_enabled = true;
2041 this.start_git_blame_inline(false, cx);
2042 }
2043 }
2044
2045 this.report_editor_event("open", None, cx);
2046 this
2047 }
2048
2049 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2050 self.mouse_context_menu
2051 .as_ref()
2052 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2053 }
2054
2055 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2056 let mut key_context = KeyContext::new_with_defaults();
2057 key_context.add("Editor");
2058 let mode = match self.mode {
2059 EditorMode::SingleLine { .. } => "single_line",
2060 EditorMode::AutoHeight { .. } => "auto_height",
2061 EditorMode::Full => "full",
2062 };
2063
2064 if EditorSettings::jupyter_enabled(cx) {
2065 key_context.add("jupyter");
2066 }
2067
2068 key_context.set("mode", mode);
2069 if self.pending_rename.is_some() {
2070 key_context.add("renaming");
2071 }
2072 if self.context_menu_visible() {
2073 match self.context_menu.read().as_ref() {
2074 Some(ContextMenu::Completions(_)) => {
2075 key_context.add("menu");
2076 key_context.add("showing_completions")
2077 }
2078 Some(ContextMenu::CodeActions(_)) => {
2079 key_context.add("menu");
2080 key_context.add("showing_code_actions")
2081 }
2082 None => {}
2083 }
2084 }
2085
2086 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2087 if !self.focus_handle(cx).contains_focused(cx)
2088 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2089 {
2090 for addon in self.addons.values() {
2091 addon.extend_key_context(&mut key_context, cx)
2092 }
2093 }
2094
2095 if let Some(extension) = self
2096 .buffer
2097 .read(cx)
2098 .as_singleton()
2099 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2100 {
2101 key_context.set("extension", extension.to_string());
2102 }
2103
2104 if self.has_active_inline_completion(cx) {
2105 key_context.add("copilot_suggestion");
2106 key_context.add("inline_completion");
2107 }
2108
2109 key_context
2110 }
2111
2112 pub fn new_file(
2113 workspace: &mut Workspace,
2114 _: &workspace::NewFile,
2115 cx: &mut ViewContext<Workspace>,
2116 ) {
2117 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2118 "Failed to create buffer",
2119 cx,
2120 |e, _| match e.error_code() {
2121 ErrorCode::RemoteUpgradeRequired => Some(format!(
2122 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2123 e.error_tag("required").unwrap_or("the latest version")
2124 )),
2125 _ => None,
2126 },
2127 );
2128 }
2129
2130 pub fn new_in_workspace(
2131 workspace: &mut Workspace,
2132 cx: &mut ViewContext<Workspace>,
2133 ) -> Task<Result<View<Editor>>> {
2134 let project = workspace.project().clone();
2135 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2136
2137 cx.spawn(|workspace, mut cx| async move {
2138 let buffer = create.await?;
2139 workspace.update(&mut cx, |workspace, cx| {
2140 let editor =
2141 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2142 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2143 editor
2144 })
2145 })
2146 }
2147
2148 fn new_file_vertical(
2149 workspace: &mut Workspace,
2150 _: &workspace::NewFileSplitVertical,
2151 cx: &mut ViewContext<Workspace>,
2152 ) {
2153 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2154 }
2155
2156 fn new_file_horizontal(
2157 workspace: &mut Workspace,
2158 _: &workspace::NewFileSplitHorizontal,
2159 cx: &mut ViewContext<Workspace>,
2160 ) {
2161 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2162 }
2163
2164 fn new_file_in_direction(
2165 workspace: &mut Workspace,
2166 direction: SplitDirection,
2167 cx: &mut ViewContext<Workspace>,
2168 ) {
2169 let project = workspace.project().clone();
2170 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2171
2172 cx.spawn(|workspace, mut cx| async move {
2173 let buffer = create.await?;
2174 workspace.update(&mut cx, move |workspace, cx| {
2175 workspace.split_item(
2176 direction,
2177 Box::new(
2178 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2179 ),
2180 cx,
2181 )
2182 })?;
2183 anyhow::Ok(())
2184 })
2185 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2186 ErrorCode::RemoteUpgradeRequired => Some(format!(
2187 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2188 e.error_tag("required").unwrap_or("the latest version")
2189 )),
2190 _ => None,
2191 });
2192 }
2193
2194 pub fn leader_peer_id(&self) -> Option<PeerId> {
2195 self.leader_peer_id
2196 }
2197
2198 pub fn buffer(&self) -> &Model<MultiBuffer> {
2199 &self.buffer
2200 }
2201
2202 pub fn workspace(&self) -> Option<View<Workspace>> {
2203 self.workspace.as_ref()?.0.upgrade()
2204 }
2205
2206 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2207 self.buffer().read(cx).title(cx)
2208 }
2209
2210 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2211 EditorSnapshot {
2212 mode: self.mode,
2213 show_gutter: self.show_gutter,
2214 show_line_numbers: self.show_line_numbers,
2215 show_git_diff_gutter: self.show_git_diff_gutter,
2216 show_code_actions: self.show_code_actions,
2217 show_runnables: self.show_runnables,
2218 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2219 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2220 scroll_anchor: self.scroll_manager.anchor(),
2221 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2222 placeholder_text: self.placeholder_text.clone(),
2223 is_focused: self.focus_handle.is_focused(cx),
2224 current_line_highlight: self
2225 .current_line_highlight
2226 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2227 gutter_hovered: self.gutter_hovered,
2228 }
2229 }
2230
2231 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2232 self.buffer.read(cx).language_at(point, cx)
2233 }
2234
2235 pub fn file_at<T: ToOffset>(
2236 &self,
2237 point: T,
2238 cx: &AppContext,
2239 ) -> Option<Arc<dyn language::File>> {
2240 self.buffer.read(cx).read(cx).file_at(point).cloned()
2241 }
2242
2243 pub fn active_excerpt(
2244 &self,
2245 cx: &AppContext,
2246 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2247 self.buffer
2248 .read(cx)
2249 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2250 }
2251
2252 pub fn mode(&self) -> EditorMode {
2253 self.mode
2254 }
2255
2256 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2257 self.collaboration_hub.as_deref()
2258 }
2259
2260 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2261 self.collaboration_hub = Some(hub);
2262 }
2263
2264 pub fn set_custom_context_menu(
2265 &mut self,
2266 f: impl 'static
2267 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2268 ) {
2269 self.custom_context_menu = Some(Box::new(f))
2270 }
2271
2272 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2273 self.completion_provider = Some(provider);
2274 }
2275
2276 pub fn set_inline_completion_provider<T>(
2277 &mut self,
2278 provider: Option<Model<T>>,
2279 cx: &mut ViewContext<Self>,
2280 ) where
2281 T: InlineCompletionProvider,
2282 {
2283 self.inline_completion_provider =
2284 provider.map(|provider| RegisteredInlineCompletionProvider {
2285 _subscription: cx.observe(&provider, |this, _, cx| {
2286 if this.focus_handle.is_focused(cx) {
2287 this.update_visible_inline_completion(cx);
2288 }
2289 }),
2290 provider: Arc::new(provider),
2291 });
2292 self.refresh_inline_completion(false, false, cx);
2293 }
2294
2295 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2296 self.placeholder_text.as_deref()
2297 }
2298
2299 pub fn set_placeholder_text(
2300 &mut self,
2301 placeholder_text: impl Into<Arc<str>>,
2302 cx: &mut ViewContext<Self>,
2303 ) {
2304 let placeholder_text = Some(placeholder_text.into());
2305 if self.placeholder_text != placeholder_text {
2306 self.placeholder_text = placeholder_text;
2307 cx.notify();
2308 }
2309 }
2310
2311 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2312 self.cursor_shape = cursor_shape;
2313
2314 // Disrupt blink for immediate user feedback that the cursor shape has changed
2315 self.blink_manager.update(cx, BlinkManager::show_cursor);
2316
2317 cx.notify();
2318 }
2319
2320 pub fn set_current_line_highlight(
2321 &mut self,
2322 current_line_highlight: Option<CurrentLineHighlight>,
2323 ) {
2324 self.current_line_highlight = current_line_highlight;
2325 }
2326
2327 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2328 self.collapse_matches = collapse_matches;
2329 }
2330
2331 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2332 if self.collapse_matches {
2333 return range.start..range.start;
2334 }
2335 range.clone()
2336 }
2337
2338 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2339 if self.display_map.read(cx).clip_at_line_ends != clip {
2340 self.display_map
2341 .update(cx, |map, _| map.clip_at_line_ends = clip);
2342 }
2343 }
2344
2345 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2346 self.input_enabled = input_enabled;
2347 }
2348
2349 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2350 self.enable_inline_completions = enabled;
2351 }
2352
2353 pub fn set_autoindent(&mut self, autoindent: bool) {
2354 if autoindent {
2355 self.autoindent_mode = Some(AutoindentMode::EachLine);
2356 } else {
2357 self.autoindent_mode = None;
2358 }
2359 }
2360
2361 pub fn read_only(&self, cx: &AppContext) -> bool {
2362 self.read_only || self.buffer.read(cx).read_only()
2363 }
2364
2365 pub fn set_read_only(&mut self, read_only: bool) {
2366 self.read_only = read_only;
2367 }
2368
2369 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2370 self.use_autoclose = autoclose;
2371 }
2372
2373 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2374 self.use_auto_surround = auto_surround;
2375 }
2376
2377 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2378 self.auto_replace_emoji_shortcode = auto_replace;
2379 }
2380
2381 pub fn toggle_inline_completions(
2382 &mut self,
2383 _: &ToggleInlineCompletions,
2384 cx: &mut ViewContext<Self>,
2385 ) {
2386 if self.show_inline_completions_override.is_some() {
2387 self.set_show_inline_completions(None, cx);
2388 } else {
2389 let cursor = self.selections.newest_anchor().head();
2390 if let Some((buffer, cursor_buffer_position)) =
2391 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2392 {
2393 let show_inline_completions =
2394 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2395 self.set_show_inline_completions(Some(show_inline_completions), cx);
2396 }
2397 }
2398 }
2399
2400 pub fn set_show_inline_completions(
2401 &mut self,
2402 show_inline_completions: Option<bool>,
2403 cx: &mut ViewContext<Self>,
2404 ) {
2405 self.show_inline_completions_override = show_inline_completions;
2406 self.refresh_inline_completion(false, true, cx);
2407 }
2408
2409 fn should_show_inline_completions(
2410 &self,
2411 buffer: &Model<Buffer>,
2412 buffer_position: language::Anchor,
2413 cx: &AppContext,
2414 ) -> bool {
2415 if let Some(provider) = self.inline_completion_provider() {
2416 if let Some(show_inline_completions) = self.show_inline_completions_override {
2417 show_inline_completions
2418 } else {
2419 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2420 }
2421 } else {
2422 false
2423 }
2424 }
2425
2426 pub fn set_use_modal_editing(&mut self, to: bool) {
2427 self.use_modal_editing = to;
2428 }
2429
2430 pub fn use_modal_editing(&self) -> bool {
2431 self.use_modal_editing
2432 }
2433
2434 fn selections_did_change(
2435 &mut self,
2436 local: bool,
2437 old_cursor_position: &Anchor,
2438 show_completions: bool,
2439 cx: &mut ViewContext<Self>,
2440 ) {
2441 cx.invalidate_character_coordinates();
2442
2443 // Copy selections to primary selection buffer
2444 #[cfg(target_os = "linux")]
2445 if local {
2446 let selections = self.selections.all::<usize>(cx);
2447 let buffer_handle = self.buffer.read(cx).read(cx);
2448
2449 let mut text = String::new();
2450 for (index, selection) in selections.iter().enumerate() {
2451 let text_for_selection = buffer_handle
2452 .text_for_range(selection.start..selection.end)
2453 .collect::<String>();
2454
2455 text.push_str(&text_for_selection);
2456 if index != selections.len() - 1 {
2457 text.push('\n');
2458 }
2459 }
2460
2461 if !text.is_empty() {
2462 cx.write_to_primary(ClipboardItem::new_string(text));
2463 }
2464 }
2465
2466 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2467 self.buffer.update(cx, |buffer, cx| {
2468 buffer.set_active_selections(
2469 &self.selections.disjoint_anchors(),
2470 self.selections.line_mode,
2471 self.cursor_shape,
2472 cx,
2473 )
2474 });
2475 }
2476 let display_map = self
2477 .display_map
2478 .update(cx, |display_map, cx| display_map.snapshot(cx));
2479 let buffer = &display_map.buffer_snapshot;
2480 self.add_selections_state = None;
2481 self.select_next_state = None;
2482 self.select_prev_state = None;
2483 self.select_larger_syntax_node_stack.clear();
2484 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2485 self.snippet_stack
2486 .invalidate(&self.selections.disjoint_anchors(), buffer);
2487 self.take_rename(false, cx);
2488
2489 let new_cursor_position = self.selections.newest_anchor().head();
2490
2491 self.push_to_nav_history(
2492 *old_cursor_position,
2493 Some(new_cursor_position.to_point(buffer)),
2494 cx,
2495 );
2496
2497 if local {
2498 let new_cursor_position = self.selections.newest_anchor().head();
2499 let mut context_menu = self.context_menu.write();
2500 let completion_menu = match context_menu.as_ref() {
2501 Some(ContextMenu::Completions(menu)) => Some(menu),
2502
2503 _ => {
2504 *context_menu = None;
2505 None
2506 }
2507 };
2508
2509 if let Some(completion_menu) = completion_menu {
2510 let cursor_position = new_cursor_position.to_offset(buffer);
2511 let (word_range, kind) =
2512 buffer.surrounding_word(completion_menu.initial_position, true);
2513 if kind == Some(CharKind::Word)
2514 && word_range.to_inclusive().contains(&cursor_position)
2515 {
2516 let mut completion_menu = completion_menu.clone();
2517 drop(context_menu);
2518
2519 let query = Self::completion_query(buffer, cursor_position);
2520 cx.spawn(move |this, mut cx| async move {
2521 completion_menu
2522 .filter(query.as_deref(), cx.background_executor().clone())
2523 .await;
2524
2525 this.update(&mut cx, |this, cx| {
2526 let mut context_menu = this.context_menu.write();
2527 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2528 return;
2529 };
2530
2531 if menu.id > completion_menu.id {
2532 return;
2533 }
2534
2535 *context_menu = Some(ContextMenu::Completions(completion_menu));
2536 drop(context_menu);
2537 cx.notify();
2538 })
2539 })
2540 .detach();
2541
2542 if show_completions {
2543 self.show_completions(&ShowCompletions { trigger: None }, cx);
2544 }
2545 } else {
2546 drop(context_menu);
2547 self.hide_context_menu(cx);
2548 }
2549 } else {
2550 drop(context_menu);
2551 }
2552
2553 hide_hover(self, cx);
2554
2555 if old_cursor_position.to_display_point(&display_map).row()
2556 != new_cursor_position.to_display_point(&display_map).row()
2557 {
2558 self.available_code_actions.take();
2559 }
2560 self.refresh_code_actions(cx);
2561 self.refresh_document_highlights(cx);
2562 refresh_matching_bracket_highlights(self, cx);
2563 self.discard_inline_completion(false, cx);
2564 linked_editing_ranges::refresh_linked_ranges(self, cx);
2565 if self.git_blame_inline_enabled {
2566 self.start_inline_blame_timer(cx);
2567 }
2568 }
2569
2570 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2571 cx.emit(EditorEvent::SelectionsChanged { local });
2572
2573 if self.selections.disjoint_anchors().len() == 1 {
2574 cx.emit(SearchEvent::ActiveMatchChanged)
2575 }
2576 cx.notify();
2577 }
2578
2579 pub fn change_selections<R>(
2580 &mut self,
2581 autoscroll: Option<Autoscroll>,
2582 cx: &mut ViewContext<Self>,
2583 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2584 ) -> R {
2585 self.change_selections_inner(autoscroll, true, cx, change)
2586 }
2587
2588 pub fn change_selections_inner<R>(
2589 &mut self,
2590 autoscroll: Option<Autoscroll>,
2591 request_completions: bool,
2592 cx: &mut ViewContext<Self>,
2593 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2594 ) -> R {
2595 let old_cursor_position = self.selections.newest_anchor().head();
2596 self.push_to_selection_history();
2597
2598 let (changed, result) = self.selections.change_with(cx, change);
2599
2600 if changed {
2601 if let Some(autoscroll) = autoscroll {
2602 self.request_autoscroll(autoscroll, cx);
2603 }
2604 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2605
2606 if self.should_open_signature_help_automatically(
2607 &old_cursor_position,
2608 self.signature_help_state.backspace_pressed(),
2609 cx,
2610 ) {
2611 self.show_signature_help(&ShowSignatureHelp, cx);
2612 }
2613 self.signature_help_state.set_backspace_pressed(false);
2614 }
2615
2616 result
2617 }
2618
2619 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2620 where
2621 I: IntoIterator<Item = (Range<S>, T)>,
2622 S: ToOffset,
2623 T: Into<Arc<str>>,
2624 {
2625 if self.read_only(cx) {
2626 return;
2627 }
2628
2629 self.buffer
2630 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2631 }
2632
2633 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2634 where
2635 I: IntoIterator<Item = (Range<S>, T)>,
2636 S: ToOffset,
2637 T: Into<Arc<str>>,
2638 {
2639 if self.read_only(cx) {
2640 return;
2641 }
2642
2643 self.buffer.update(cx, |buffer, cx| {
2644 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2645 });
2646 }
2647
2648 pub fn edit_with_block_indent<I, S, T>(
2649 &mut self,
2650 edits: I,
2651 original_indent_columns: Vec<u32>,
2652 cx: &mut ViewContext<Self>,
2653 ) where
2654 I: IntoIterator<Item = (Range<S>, T)>,
2655 S: ToOffset,
2656 T: Into<Arc<str>>,
2657 {
2658 if self.read_only(cx) {
2659 return;
2660 }
2661
2662 self.buffer.update(cx, |buffer, cx| {
2663 buffer.edit(
2664 edits,
2665 Some(AutoindentMode::Block {
2666 original_indent_columns,
2667 }),
2668 cx,
2669 )
2670 });
2671 }
2672
2673 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2674 self.hide_context_menu(cx);
2675
2676 match phase {
2677 SelectPhase::Begin {
2678 position,
2679 add,
2680 click_count,
2681 } => self.begin_selection(position, add, click_count, cx),
2682 SelectPhase::BeginColumnar {
2683 position,
2684 goal_column,
2685 reset,
2686 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2687 SelectPhase::Extend {
2688 position,
2689 click_count,
2690 } => self.extend_selection(position, click_count, cx),
2691 SelectPhase::Update {
2692 position,
2693 goal_column,
2694 scroll_delta,
2695 } => self.update_selection(position, goal_column, scroll_delta, cx),
2696 SelectPhase::End => self.end_selection(cx),
2697 }
2698 }
2699
2700 fn extend_selection(
2701 &mut self,
2702 position: DisplayPoint,
2703 click_count: usize,
2704 cx: &mut ViewContext<Self>,
2705 ) {
2706 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2707 let tail = self.selections.newest::<usize>(cx).tail();
2708 self.begin_selection(position, false, click_count, cx);
2709
2710 let position = position.to_offset(&display_map, Bias::Left);
2711 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2712
2713 let mut pending_selection = self
2714 .selections
2715 .pending_anchor()
2716 .expect("extend_selection not called with pending selection");
2717 if position >= tail {
2718 pending_selection.start = tail_anchor;
2719 } else {
2720 pending_selection.end = tail_anchor;
2721 pending_selection.reversed = true;
2722 }
2723
2724 let mut pending_mode = self.selections.pending_mode().unwrap();
2725 match &mut pending_mode {
2726 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2727 _ => {}
2728 }
2729
2730 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2731 s.set_pending(pending_selection, pending_mode)
2732 });
2733 }
2734
2735 fn begin_selection(
2736 &mut self,
2737 position: DisplayPoint,
2738 add: bool,
2739 click_count: usize,
2740 cx: &mut ViewContext<Self>,
2741 ) {
2742 if !self.focus_handle.is_focused(cx) {
2743 self.last_focused_descendant = None;
2744 cx.focus(&self.focus_handle);
2745 }
2746
2747 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2748 let buffer = &display_map.buffer_snapshot;
2749 let newest_selection = self.selections.newest_anchor().clone();
2750 let position = display_map.clip_point(position, Bias::Left);
2751
2752 let start;
2753 let end;
2754 let mode;
2755 let auto_scroll;
2756 match click_count {
2757 1 => {
2758 start = buffer.anchor_before(position.to_point(&display_map));
2759 end = start;
2760 mode = SelectMode::Character;
2761 auto_scroll = true;
2762 }
2763 2 => {
2764 let range = movement::surrounding_word(&display_map, position);
2765 start = buffer.anchor_before(range.start.to_point(&display_map));
2766 end = buffer.anchor_before(range.end.to_point(&display_map));
2767 mode = SelectMode::Word(start..end);
2768 auto_scroll = true;
2769 }
2770 3 => {
2771 let position = display_map
2772 .clip_point(position, Bias::Left)
2773 .to_point(&display_map);
2774 let line_start = display_map.prev_line_boundary(position).0;
2775 let next_line_start = buffer.clip_point(
2776 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2777 Bias::Left,
2778 );
2779 start = buffer.anchor_before(line_start);
2780 end = buffer.anchor_before(next_line_start);
2781 mode = SelectMode::Line(start..end);
2782 auto_scroll = true;
2783 }
2784 _ => {
2785 start = buffer.anchor_before(0);
2786 end = buffer.anchor_before(buffer.len());
2787 mode = SelectMode::All;
2788 auto_scroll = false;
2789 }
2790 }
2791
2792 let point_to_delete: Option<usize> = {
2793 let selected_points: Vec<Selection<Point>> =
2794 self.selections.disjoint_in_range(start..end, cx);
2795
2796 if !add || click_count > 1 {
2797 None
2798 } else if !selected_points.is_empty() {
2799 Some(selected_points[0].id)
2800 } else {
2801 let clicked_point_already_selected =
2802 self.selections.disjoint.iter().find(|selection| {
2803 selection.start.to_point(buffer) == start.to_point(buffer)
2804 || selection.end.to_point(buffer) == end.to_point(buffer)
2805 });
2806
2807 clicked_point_already_selected.map(|selection| selection.id)
2808 }
2809 };
2810
2811 let selections_count = self.selections.count();
2812
2813 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2814 if let Some(point_to_delete) = point_to_delete {
2815 s.delete(point_to_delete);
2816
2817 if selections_count == 1 {
2818 s.set_pending_anchor_range(start..end, mode);
2819 }
2820 } else {
2821 if !add {
2822 s.clear_disjoint();
2823 } else if click_count > 1 {
2824 s.delete(newest_selection.id)
2825 }
2826
2827 s.set_pending_anchor_range(start..end, mode);
2828 }
2829 });
2830 }
2831
2832 fn begin_columnar_selection(
2833 &mut self,
2834 position: DisplayPoint,
2835 goal_column: u32,
2836 reset: bool,
2837 cx: &mut ViewContext<Self>,
2838 ) {
2839 if !self.focus_handle.is_focused(cx) {
2840 self.last_focused_descendant = None;
2841 cx.focus(&self.focus_handle);
2842 }
2843
2844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2845
2846 if reset {
2847 let pointer_position = display_map
2848 .buffer_snapshot
2849 .anchor_before(position.to_point(&display_map));
2850
2851 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2852 s.clear_disjoint();
2853 s.set_pending_anchor_range(
2854 pointer_position..pointer_position,
2855 SelectMode::Character,
2856 );
2857 });
2858 }
2859
2860 let tail = self.selections.newest::<Point>(cx).tail();
2861 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2862
2863 if !reset {
2864 self.select_columns(
2865 tail.to_display_point(&display_map),
2866 position,
2867 goal_column,
2868 &display_map,
2869 cx,
2870 );
2871 }
2872 }
2873
2874 fn update_selection(
2875 &mut self,
2876 position: DisplayPoint,
2877 goal_column: u32,
2878 scroll_delta: gpui::Point<f32>,
2879 cx: &mut ViewContext<Self>,
2880 ) {
2881 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2882
2883 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2884 let tail = tail.to_display_point(&display_map);
2885 self.select_columns(tail, position, goal_column, &display_map, cx);
2886 } else if let Some(mut pending) = self.selections.pending_anchor() {
2887 let buffer = self.buffer.read(cx).snapshot(cx);
2888 let head;
2889 let tail;
2890 let mode = self.selections.pending_mode().unwrap();
2891 match &mode {
2892 SelectMode::Character => {
2893 head = position.to_point(&display_map);
2894 tail = pending.tail().to_point(&buffer);
2895 }
2896 SelectMode::Word(original_range) => {
2897 let original_display_range = original_range.start.to_display_point(&display_map)
2898 ..original_range.end.to_display_point(&display_map);
2899 let original_buffer_range = original_display_range.start.to_point(&display_map)
2900 ..original_display_range.end.to_point(&display_map);
2901 if movement::is_inside_word(&display_map, position)
2902 || original_display_range.contains(&position)
2903 {
2904 let word_range = movement::surrounding_word(&display_map, position);
2905 if word_range.start < original_display_range.start {
2906 head = word_range.start.to_point(&display_map);
2907 } else {
2908 head = word_range.end.to_point(&display_map);
2909 }
2910 } else {
2911 head = position.to_point(&display_map);
2912 }
2913
2914 if head <= original_buffer_range.start {
2915 tail = original_buffer_range.end;
2916 } else {
2917 tail = original_buffer_range.start;
2918 }
2919 }
2920 SelectMode::Line(original_range) => {
2921 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2922
2923 let position = display_map
2924 .clip_point(position, Bias::Left)
2925 .to_point(&display_map);
2926 let line_start = display_map.prev_line_boundary(position).0;
2927 let next_line_start = buffer.clip_point(
2928 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2929 Bias::Left,
2930 );
2931
2932 if line_start < original_range.start {
2933 head = line_start
2934 } else {
2935 head = next_line_start
2936 }
2937
2938 if head <= original_range.start {
2939 tail = original_range.end;
2940 } else {
2941 tail = original_range.start;
2942 }
2943 }
2944 SelectMode::All => {
2945 return;
2946 }
2947 };
2948
2949 if head < tail {
2950 pending.start = buffer.anchor_before(head);
2951 pending.end = buffer.anchor_before(tail);
2952 pending.reversed = true;
2953 } else {
2954 pending.start = buffer.anchor_before(tail);
2955 pending.end = buffer.anchor_before(head);
2956 pending.reversed = false;
2957 }
2958
2959 self.change_selections(None, cx, |s| {
2960 s.set_pending(pending, mode);
2961 });
2962 } else {
2963 log::error!("update_selection dispatched with no pending selection");
2964 return;
2965 }
2966
2967 self.apply_scroll_delta(scroll_delta, cx);
2968 cx.notify();
2969 }
2970
2971 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2972 self.columnar_selection_tail.take();
2973 if self.selections.pending_anchor().is_some() {
2974 let selections = self.selections.all::<usize>(cx);
2975 self.change_selections(None, cx, |s| {
2976 s.select(selections);
2977 s.clear_pending();
2978 });
2979 }
2980 }
2981
2982 fn select_columns(
2983 &mut self,
2984 tail: DisplayPoint,
2985 head: DisplayPoint,
2986 goal_column: u32,
2987 display_map: &DisplaySnapshot,
2988 cx: &mut ViewContext<Self>,
2989 ) {
2990 let start_row = cmp::min(tail.row(), head.row());
2991 let end_row = cmp::max(tail.row(), head.row());
2992 let start_column = cmp::min(tail.column(), goal_column);
2993 let end_column = cmp::max(tail.column(), goal_column);
2994 let reversed = start_column < tail.column();
2995
2996 let selection_ranges = (start_row.0..=end_row.0)
2997 .map(DisplayRow)
2998 .filter_map(|row| {
2999 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3000 let start = display_map
3001 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3002 .to_point(display_map);
3003 let end = display_map
3004 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3005 .to_point(display_map);
3006 if reversed {
3007 Some(end..start)
3008 } else {
3009 Some(start..end)
3010 }
3011 } else {
3012 None
3013 }
3014 })
3015 .collect::<Vec<_>>();
3016
3017 self.change_selections(None, cx, |s| {
3018 s.select_ranges(selection_ranges);
3019 });
3020 cx.notify();
3021 }
3022
3023 pub fn has_pending_nonempty_selection(&self) -> bool {
3024 let pending_nonempty_selection = match self.selections.pending_anchor() {
3025 Some(Selection { start, end, .. }) => start != end,
3026 None => false,
3027 };
3028
3029 pending_nonempty_selection
3030 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3031 }
3032
3033 pub fn has_pending_selection(&self) -> bool {
3034 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3035 }
3036
3037 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3038 if self.clear_clicked_diff_hunks(cx) {
3039 cx.notify();
3040 return;
3041 }
3042 if self.dismiss_menus_and_popups(true, cx) {
3043 return;
3044 }
3045
3046 if self.mode == EditorMode::Full
3047 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3048 {
3049 return;
3050 }
3051
3052 cx.propagate();
3053 }
3054
3055 pub fn dismiss_menus_and_popups(
3056 &mut self,
3057 should_report_inline_completion_event: bool,
3058 cx: &mut ViewContext<Self>,
3059 ) -> bool {
3060 if self.take_rename(false, cx).is_some() {
3061 return true;
3062 }
3063
3064 if hide_hover(self, cx) {
3065 return true;
3066 }
3067
3068 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3069 return true;
3070 }
3071
3072 if self.hide_context_menu(cx).is_some() {
3073 return true;
3074 }
3075
3076 if self.mouse_context_menu.take().is_some() {
3077 return true;
3078 }
3079
3080 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3081 return true;
3082 }
3083
3084 if self.snippet_stack.pop().is_some() {
3085 return true;
3086 }
3087
3088 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3089 self.dismiss_diagnostics(cx);
3090 return true;
3091 }
3092
3093 false
3094 }
3095
3096 fn linked_editing_ranges_for(
3097 &self,
3098 selection: Range<text::Anchor>,
3099 cx: &AppContext,
3100 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3101 if self.linked_edit_ranges.is_empty() {
3102 return None;
3103 }
3104 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3105 selection.end.buffer_id.and_then(|end_buffer_id| {
3106 if selection.start.buffer_id != Some(end_buffer_id) {
3107 return None;
3108 }
3109 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3110 let snapshot = buffer.read(cx).snapshot();
3111 self.linked_edit_ranges
3112 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3113 .map(|ranges| (ranges, snapshot, buffer))
3114 })?;
3115 use text::ToOffset as TO;
3116 // find offset from the start of current range to current cursor position
3117 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3118
3119 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3120 let start_difference = start_offset - start_byte_offset;
3121 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3122 let end_difference = end_offset - start_byte_offset;
3123 // Current range has associated linked ranges.
3124 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3125 for range in linked_ranges.iter() {
3126 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3127 let end_offset = start_offset + end_difference;
3128 let start_offset = start_offset + start_difference;
3129 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3130 continue;
3131 }
3132 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3133 if s.start.buffer_id != selection.start.buffer_id
3134 || s.end.buffer_id != selection.end.buffer_id
3135 {
3136 return false;
3137 }
3138 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3139 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3140 }) {
3141 continue;
3142 }
3143 let start = buffer_snapshot.anchor_after(start_offset);
3144 let end = buffer_snapshot.anchor_after(end_offset);
3145 linked_edits
3146 .entry(buffer.clone())
3147 .or_default()
3148 .push(start..end);
3149 }
3150 Some(linked_edits)
3151 }
3152
3153 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3154 let text: Arc<str> = text.into();
3155
3156 if self.read_only(cx) {
3157 return;
3158 }
3159
3160 let selections = self.selections.all_adjusted(cx);
3161 let mut bracket_inserted = false;
3162 let mut edits = Vec::new();
3163 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3164 let mut new_selections = Vec::with_capacity(selections.len());
3165 let mut new_autoclose_regions = Vec::new();
3166 let snapshot = self.buffer.read(cx).read(cx);
3167
3168 for (selection, autoclose_region) in
3169 self.selections_with_autoclose_regions(selections, &snapshot)
3170 {
3171 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3172 // Determine if the inserted text matches the opening or closing
3173 // bracket of any of this language's bracket pairs.
3174 let mut bracket_pair = None;
3175 let mut is_bracket_pair_start = false;
3176 let mut is_bracket_pair_end = false;
3177 if !text.is_empty() {
3178 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3179 // and they are removing the character that triggered IME popup.
3180 for (pair, enabled) in scope.brackets() {
3181 if !pair.close && !pair.surround {
3182 continue;
3183 }
3184
3185 if enabled && pair.start.ends_with(text.as_ref()) {
3186 bracket_pair = Some(pair.clone());
3187 is_bracket_pair_start = true;
3188 break;
3189 }
3190 if pair.end.as_str() == text.as_ref() {
3191 bracket_pair = Some(pair.clone());
3192 is_bracket_pair_end = true;
3193 break;
3194 }
3195 }
3196 }
3197
3198 if let Some(bracket_pair) = bracket_pair {
3199 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3200 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3201 let auto_surround =
3202 self.use_auto_surround && snapshot_settings.use_auto_surround;
3203 if selection.is_empty() {
3204 if is_bracket_pair_start {
3205 let prefix_len = bracket_pair.start.len() - text.len();
3206
3207 // If the inserted text is a suffix of an opening bracket and the
3208 // selection is preceded by the rest of the opening bracket, then
3209 // insert the closing bracket.
3210 let following_text_allows_autoclose = snapshot
3211 .chars_at(selection.start)
3212 .next()
3213 .map_or(true, |c| scope.should_autoclose_before(c));
3214 let preceding_text_matches_prefix = prefix_len == 0
3215 || (selection.start.column >= (prefix_len as u32)
3216 && snapshot.contains_str_at(
3217 Point::new(
3218 selection.start.row,
3219 selection.start.column - (prefix_len as u32),
3220 ),
3221 &bracket_pair.start[..prefix_len],
3222 ));
3223
3224 if autoclose
3225 && bracket_pair.close
3226 && following_text_allows_autoclose
3227 && preceding_text_matches_prefix
3228 {
3229 let anchor = snapshot.anchor_before(selection.end);
3230 new_selections.push((selection.map(|_| anchor), text.len()));
3231 new_autoclose_regions.push((
3232 anchor,
3233 text.len(),
3234 selection.id,
3235 bracket_pair.clone(),
3236 ));
3237 edits.push((
3238 selection.range(),
3239 format!("{}{}", text, bracket_pair.end).into(),
3240 ));
3241 bracket_inserted = true;
3242 continue;
3243 }
3244 }
3245
3246 if let Some(region) = autoclose_region {
3247 // If the selection is followed by an auto-inserted closing bracket,
3248 // then don't insert that closing bracket again; just move the selection
3249 // past the closing bracket.
3250 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3251 && text.as_ref() == region.pair.end.as_str();
3252 if should_skip {
3253 let anchor = snapshot.anchor_after(selection.end);
3254 new_selections
3255 .push((selection.map(|_| anchor), region.pair.end.len()));
3256 continue;
3257 }
3258 }
3259
3260 let always_treat_brackets_as_autoclosed = snapshot
3261 .settings_at(selection.start, cx)
3262 .always_treat_brackets_as_autoclosed;
3263 if always_treat_brackets_as_autoclosed
3264 && is_bracket_pair_end
3265 && snapshot.contains_str_at(selection.end, text.as_ref())
3266 {
3267 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3268 // and the inserted text is a closing bracket and the selection is followed
3269 // by the closing bracket then move the selection past the closing bracket.
3270 let anchor = snapshot.anchor_after(selection.end);
3271 new_selections.push((selection.map(|_| anchor), text.len()));
3272 continue;
3273 }
3274 }
3275 // If an opening bracket is 1 character long and is typed while
3276 // text is selected, then surround that text with the bracket pair.
3277 else if auto_surround
3278 && bracket_pair.surround
3279 && is_bracket_pair_start
3280 && bracket_pair.start.chars().count() == 1
3281 {
3282 edits.push((selection.start..selection.start, text.clone()));
3283 edits.push((
3284 selection.end..selection.end,
3285 bracket_pair.end.as_str().into(),
3286 ));
3287 bracket_inserted = true;
3288 new_selections.push((
3289 Selection {
3290 id: selection.id,
3291 start: snapshot.anchor_after(selection.start),
3292 end: snapshot.anchor_before(selection.end),
3293 reversed: selection.reversed,
3294 goal: selection.goal,
3295 },
3296 0,
3297 ));
3298 continue;
3299 }
3300 }
3301 }
3302
3303 if self.auto_replace_emoji_shortcode
3304 && selection.is_empty()
3305 && text.as_ref().ends_with(':')
3306 {
3307 if let Some(possible_emoji_short_code) =
3308 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3309 {
3310 if !possible_emoji_short_code.is_empty() {
3311 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3312 let emoji_shortcode_start = Point::new(
3313 selection.start.row,
3314 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3315 );
3316
3317 // Remove shortcode from buffer
3318 edits.push((
3319 emoji_shortcode_start..selection.start,
3320 "".to_string().into(),
3321 ));
3322 new_selections.push((
3323 Selection {
3324 id: selection.id,
3325 start: snapshot.anchor_after(emoji_shortcode_start),
3326 end: snapshot.anchor_before(selection.start),
3327 reversed: selection.reversed,
3328 goal: selection.goal,
3329 },
3330 0,
3331 ));
3332
3333 // Insert emoji
3334 let selection_start_anchor = snapshot.anchor_after(selection.start);
3335 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3336 edits.push((selection.start..selection.end, emoji.to_string().into()));
3337
3338 continue;
3339 }
3340 }
3341 }
3342 }
3343
3344 // If not handling any auto-close operation, then just replace the selected
3345 // text with the given input and move the selection to the end of the
3346 // newly inserted text.
3347 let anchor = snapshot.anchor_after(selection.end);
3348 if !self.linked_edit_ranges.is_empty() {
3349 let start_anchor = snapshot.anchor_before(selection.start);
3350
3351 let is_word_char = text.chars().next().map_or(true, |char| {
3352 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3353 classifier.is_word(char)
3354 });
3355
3356 if is_word_char {
3357 if let Some(ranges) = self
3358 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3359 {
3360 for (buffer, edits) in ranges {
3361 linked_edits
3362 .entry(buffer.clone())
3363 .or_default()
3364 .extend(edits.into_iter().map(|range| (range, text.clone())));
3365 }
3366 }
3367 }
3368 }
3369
3370 new_selections.push((selection.map(|_| anchor), 0));
3371 edits.push((selection.start..selection.end, text.clone()));
3372 }
3373
3374 drop(snapshot);
3375
3376 self.transact(cx, |this, cx| {
3377 this.buffer.update(cx, |buffer, cx| {
3378 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3379 });
3380 for (buffer, edits) in linked_edits {
3381 buffer.update(cx, |buffer, cx| {
3382 let snapshot = buffer.snapshot();
3383 let edits = edits
3384 .into_iter()
3385 .map(|(range, text)| {
3386 use text::ToPoint as TP;
3387 let end_point = TP::to_point(&range.end, &snapshot);
3388 let start_point = TP::to_point(&range.start, &snapshot);
3389 (start_point..end_point, text)
3390 })
3391 .sorted_by_key(|(range, _)| range.start)
3392 .collect::<Vec<_>>();
3393 buffer.edit(edits, None, cx);
3394 })
3395 }
3396 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3397 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3398 let snapshot = this.buffer.read(cx).read(cx);
3399 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3400 .zip(new_selection_deltas)
3401 .map(|(selection, delta)| Selection {
3402 id: selection.id,
3403 start: selection.start + delta,
3404 end: selection.end + delta,
3405 reversed: selection.reversed,
3406 goal: SelectionGoal::None,
3407 })
3408 .collect::<Vec<_>>();
3409
3410 let mut i = 0;
3411 for (position, delta, selection_id, pair) in new_autoclose_regions {
3412 let position = position.to_offset(&snapshot) + delta;
3413 let start = snapshot.anchor_before(position);
3414 let end = snapshot.anchor_after(position);
3415 while let Some(existing_state) = this.autoclose_regions.get(i) {
3416 match existing_state.range.start.cmp(&start, &snapshot) {
3417 Ordering::Less => i += 1,
3418 Ordering::Greater => break,
3419 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3420 Ordering::Less => i += 1,
3421 Ordering::Equal => break,
3422 Ordering::Greater => break,
3423 },
3424 }
3425 }
3426 this.autoclose_regions.insert(
3427 i,
3428 AutocloseRegion {
3429 selection_id,
3430 range: start..end,
3431 pair,
3432 },
3433 );
3434 }
3435
3436 drop(snapshot);
3437 let had_active_inline_completion = this.has_active_inline_completion(cx);
3438 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3439 s.select(new_selections)
3440 });
3441
3442 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3443 if let Some(on_type_format_task) =
3444 this.trigger_on_type_formatting(text.to_string(), cx)
3445 {
3446 on_type_format_task.detach_and_log_err(cx);
3447 }
3448 }
3449
3450 let editor_settings = EditorSettings::get_global(cx);
3451 if bracket_inserted
3452 && (editor_settings.auto_signature_help
3453 || editor_settings.show_signature_help_after_edits)
3454 {
3455 this.show_signature_help(&ShowSignatureHelp, cx);
3456 }
3457
3458 let trigger_in_words = !had_active_inline_completion;
3459 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3460 linked_editing_ranges::refresh_linked_ranges(this, cx);
3461 this.refresh_inline_completion(true, false, cx);
3462 });
3463 }
3464
3465 fn find_possible_emoji_shortcode_at_position(
3466 snapshot: &MultiBufferSnapshot,
3467 position: Point,
3468 ) -> Option<String> {
3469 let mut chars = Vec::new();
3470 let mut found_colon = false;
3471 for char in snapshot.reversed_chars_at(position).take(100) {
3472 // Found a possible emoji shortcode in the middle of the buffer
3473 if found_colon {
3474 if char.is_whitespace() {
3475 chars.reverse();
3476 return Some(chars.iter().collect());
3477 }
3478 // If the previous character is not a whitespace, we are in the middle of a word
3479 // and we only want to complete the shortcode if the word is made up of other emojis
3480 let mut containing_word = String::new();
3481 for ch in snapshot
3482 .reversed_chars_at(position)
3483 .skip(chars.len() + 1)
3484 .take(100)
3485 {
3486 if ch.is_whitespace() {
3487 break;
3488 }
3489 containing_word.push(ch);
3490 }
3491 let containing_word = containing_word.chars().rev().collect::<String>();
3492 if util::word_consists_of_emojis(containing_word.as_str()) {
3493 chars.reverse();
3494 return Some(chars.iter().collect());
3495 }
3496 }
3497
3498 if char.is_whitespace() || !char.is_ascii() {
3499 return None;
3500 }
3501 if char == ':' {
3502 found_colon = true;
3503 } else {
3504 chars.push(char);
3505 }
3506 }
3507 // Found a possible emoji shortcode at the beginning of the buffer
3508 chars.reverse();
3509 Some(chars.iter().collect())
3510 }
3511
3512 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3513 self.transact(cx, |this, cx| {
3514 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3515 let selections = this.selections.all::<usize>(cx);
3516 let multi_buffer = this.buffer.read(cx);
3517 let buffer = multi_buffer.snapshot(cx);
3518 selections
3519 .iter()
3520 .map(|selection| {
3521 let start_point = selection.start.to_point(&buffer);
3522 let mut indent =
3523 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3524 indent.len = cmp::min(indent.len, start_point.column);
3525 let start = selection.start;
3526 let end = selection.end;
3527 let selection_is_empty = start == end;
3528 let language_scope = buffer.language_scope_at(start);
3529 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3530 &language_scope
3531 {
3532 let leading_whitespace_len = buffer
3533 .reversed_chars_at(start)
3534 .take_while(|c| c.is_whitespace() && *c != '\n')
3535 .map(|c| c.len_utf8())
3536 .sum::<usize>();
3537
3538 let trailing_whitespace_len = buffer
3539 .chars_at(end)
3540 .take_while(|c| c.is_whitespace() && *c != '\n')
3541 .map(|c| c.len_utf8())
3542 .sum::<usize>();
3543
3544 let insert_extra_newline =
3545 language.brackets().any(|(pair, enabled)| {
3546 let pair_start = pair.start.trim_end();
3547 let pair_end = pair.end.trim_start();
3548
3549 enabled
3550 && pair.newline
3551 && buffer.contains_str_at(
3552 end + trailing_whitespace_len,
3553 pair_end,
3554 )
3555 && buffer.contains_str_at(
3556 (start - leading_whitespace_len)
3557 .saturating_sub(pair_start.len()),
3558 pair_start,
3559 )
3560 });
3561
3562 // Comment extension on newline is allowed only for cursor selections
3563 let comment_delimiter = maybe!({
3564 if !selection_is_empty {
3565 return None;
3566 }
3567
3568 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3569 return None;
3570 }
3571
3572 let delimiters = language.line_comment_prefixes();
3573 let max_len_of_delimiter =
3574 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3575 let (snapshot, range) =
3576 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3577
3578 let mut index_of_first_non_whitespace = 0;
3579 let comment_candidate = snapshot
3580 .chars_for_range(range)
3581 .skip_while(|c| {
3582 let should_skip = c.is_whitespace();
3583 if should_skip {
3584 index_of_first_non_whitespace += 1;
3585 }
3586 should_skip
3587 })
3588 .take(max_len_of_delimiter)
3589 .collect::<String>();
3590 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3591 comment_candidate.starts_with(comment_prefix.as_ref())
3592 })?;
3593 let cursor_is_placed_after_comment_marker =
3594 index_of_first_non_whitespace + comment_prefix.len()
3595 <= start_point.column as usize;
3596 if cursor_is_placed_after_comment_marker {
3597 Some(comment_prefix.clone())
3598 } else {
3599 None
3600 }
3601 });
3602 (comment_delimiter, insert_extra_newline)
3603 } else {
3604 (None, false)
3605 };
3606
3607 let capacity_for_delimiter = comment_delimiter
3608 .as_deref()
3609 .map(str::len)
3610 .unwrap_or_default();
3611 let mut new_text =
3612 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3613 new_text.push('\n');
3614 new_text.extend(indent.chars());
3615 if let Some(delimiter) = &comment_delimiter {
3616 new_text.push_str(delimiter);
3617 }
3618 if insert_extra_newline {
3619 new_text = new_text.repeat(2);
3620 }
3621
3622 let anchor = buffer.anchor_after(end);
3623 let new_selection = selection.map(|_| anchor);
3624 (
3625 (start..end, new_text),
3626 (insert_extra_newline, new_selection),
3627 )
3628 })
3629 .unzip()
3630 };
3631
3632 this.edit_with_autoindent(edits, cx);
3633 let buffer = this.buffer.read(cx).snapshot(cx);
3634 let new_selections = selection_fixup_info
3635 .into_iter()
3636 .map(|(extra_newline_inserted, new_selection)| {
3637 let mut cursor = new_selection.end.to_point(&buffer);
3638 if extra_newline_inserted {
3639 cursor.row -= 1;
3640 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3641 }
3642 new_selection.map(|_| cursor)
3643 })
3644 .collect();
3645
3646 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3647 this.refresh_inline_completion(true, false, cx);
3648 });
3649 }
3650
3651 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3652 let buffer = self.buffer.read(cx);
3653 let snapshot = buffer.snapshot(cx);
3654
3655 let mut edits = Vec::new();
3656 let mut rows = Vec::new();
3657
3658 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3659 let cursor = selection.head();
3660 let row = cursor.row;
3661
3662 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3663
3664 let newline = "\n".to_string();
3665 edits.push((start_of_line..start_of_line, newline));
3666
3667 rows.push(row + rows_inserted as u32);
3668 }
3669
3670 self.transact(cx, |editor, cx| {
3671 editor.edit(edits, cx);
3672
3673 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3674 let mut index = 0;
3675 s.move_cursors_with(|map, _, _| {
3676 let row = rows[index];
3677 index += 1;
3678
3679 let point = Point::new(row, 0);
3680 let boundary = map.next_line_boundary(point).1;
3681 let clipped = map.clip_point(boundary, Bias::Left);
3682
3683 (clipped, SelectionGoal::None)
3684 });
3685 });
3686
3687 let mut indent_edits = Vec::new();
3688 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3689 for row in rows {
3690 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3691 for (row, indent) in indents {
3692 if indent.len == 0 {
3693 continue;
3694 }
3695
3696 let text = match indent.kind {
3697 IndentKind::Space => " ".repeat(indent.len as usize),
3698 IndentKind::Tab => "\t".repeat(indent.len as usize),
3699 };
3700 let point = Point::new(row.0, 0);
3701 indent_edits.push((point..point, text));
3702 }
3703 }
3704 editor.edit(indent_edits, cx);
3705 });
3706 }
3707
3708 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3709 let buffer = self.buffer.read(cx);
3710 let snapshot = buffer.snapshot(cx);
3711
3712 let mut edits = Vec::new();
3713 let mut rows = Vec::new();
3714 let mut rows_inserted = 0;
3715
3716 for selection in self.selections.all_adjusted(cx) {
3717 let cursor = selection.head();
3718 let row = cursor.row;
3719
3720 let point = Point::new(row + 1, 0);
3721 let start_of_line = snapshot.clip_point(point, Bias::Left);
3722
3723 let newline = "\n".to_string();
3724 edits.push((start_of_line..start_of_line, newline));
3725
3726 rows_inserted += 1;
3727 rows.push(row + rows_inserted);
3728 }
3729
3730 self.transact(cx, |editor, cx| {
3731 editor.edit(edits, cx);
3732
3733 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3734 let mut index = 0;
3735 s.move_cursors_with(|map, _, _| {
3736 let row = rows[index];
3737 index += 1;
3738
3739 let point = Point::new(row, 0);
3740 let boundary = map.next_line_boundary(point).1;
3741 let clipped = map.clip_point(boundary, Bias::Left);
3742
3743 (clipped, SelectionGoal::None)
3744 });
3745 });
3746
3747 let mut indent_edits = Vec::new();
3748 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3749 for row in rows {
3750 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3751 for (row, indent) in indents {
3752 if indent.len == 0 {
3753 continue;
3754 }
3755
3756 let text = match indent.kind {
3757 IndentKind::Space => " ".repeat(indent.len as usize),
3758 IndentKind::Tab => "\t".repeat(indent.len as usize),
3759 };
3760 let point = Point::new(row.0, 0);
3761 indent_edits.push((point..point, text));
3762 }
3763 }
3764 editor.edit(indent_edits, cx);
3765 });
3766 }
3767
3768 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3769 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3770 original_indent_columns: Vec::new(),
3771 });
3772 self.insert_with_autoindent_mode(text, autoindent, cx);
3773 }
3774
3775 fn insert_with_autoindent_mode(
3776 &mut self,
3777 text: &str,
3778 autoindent_mode: Option<AutoindentMode>,
3779 cx: &mut ViewContext<Self>,
3780 ) {
3781 if self.read_only(cx) {
3782 return;
3783 }
3784
3785 let text: Arc<str> = text.into();
3786 self.transact(cx, |this, cx| {
3787 let old_selections = this.selections.all_adjusted(cx);
3788 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3789 let anchors = {
3790 let snapshot = buffer.read(cx);
3791 old_selections
3792 .iter()
3793 .map(|s| {
3794 let anchor = snapshot.anchor_after(s.head());
3795 s.map(|_| anchor)
3796 })
3797 .collect::<Vec<_>>()
3798 };
3799 buffer.edit(
3800 old_selections
3801 .iter()
3802 .map(|s| (s.start..s.end, text.clone())),
3803 autoindent_mode,
3804 cx,
3805 );
3806 anchors
3807 });
3808
3809 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3810 s.select_anchors(selection_anchors);
3811 })
3812 });
3813 }
3814
3815 fn trigger_completion_on_input(
3816 &mut self,
3817 text: &str,
3818 trigger_in_words: bool,
3819 cx: &mut ViewContext<Self>,
3820 ) {
3821 if self.is_completion_trigger(text, trigger_in_words, cx) {
3822 self.show_completions(
3823 &ShowCompletions {
3824 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3825 },
3826 cx,
3827 );
3828 } else {
3829 self.hide_context_menu(cx);
3830 }
3831 }
3832
3833 fn is_completion_trigger(
3834 &self,
3835 text: &str,
3836 trigger_in_words: bool,
3837 cx: &mut ViewContext<Self>,
3838 ) -> bool {
3839 let position = self.selections.newest_anchor().head();
3840 let multibuffer = self.buffer.read(cx);
3841 let Some(buffer) = position
3842 .buffer_id
3843 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3844 else {
3845 return false;
3846 };
3847
3848 if let Some(completion_provider) = &self.completion_provider {
3849 completion_provider.is_completion_trigger(
3850 &buffer,
3851 position.text_anchor,
3852 text,
3853 trigger_in_words,
3854 cx,
3855 )
3856 } else {
3857 false
3858 }
3859 }
3860
3861 /// If any empty selections is touching the start of its innermost containing autoclose
3862 /// region, expand it to select the brackets.
3863 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3864 let selections = self.selections.all::<usize>(cx);
3865 let buffer = self.buffer.read(cx).read(cx);
3866 let new_selections = self
3867 .selections_with_autoclose_regions(selections, &buffer)
3868 .map(|(mut selection, region)| {
3869 if !selection.is_empty() {
3870 return selection;
3871 }
3872
3873 if let Some(region) = region {
3874 let mut range = region.range.to_offset(&buffer);
3875 if selection.start == range.start && range.start >= region.pair.start.len() {
3876 range.start -= region.pair.start.len();
3877 if buffer.contains_str_at(range.start, ®ion.pair.start)
3878 && buffer.contains_str_at(range.end, ®ion.pair.end)
3879 {
3880 range.end += region.pair.end.len();
3881 selection.start = range.start;
3882 selection.end = range.end;
3883
3884 return selection;
3885 }
3886 }
3887 }
3888
3889 let always_treat_brackets_as_autoclosed = buffer
3890 .settings_at(selection.start, cx)
3891 .always_treat_brackets_as_autoclosed;
3892
3893 if !always_treat_brackets_as_autoclosed {
3894 return selection;
3895 }
3896
3897 if let Some(scope) = buffer.language_scope_at(selection.start) {
3898 for (pair, enabled) in scope.brackets() {
3899 if !enabled || !pair.close {
3900 continue;
3901 }
3902
3903 if buffer.contains_str_at(selection.start, &pair.end) {
3904 let pair_start_len = pair.start.len();
3905 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3906 {
3907 selection.start -= pair_start_len;
3908 selection.end += pair.end.len();
3909
3910 return selection;
3911 }
3912 }
3913 }
3914 }
3915
3916 selection
3917 })
3918 .collect();
3919
3920 drop(buffer);
3921 self.change_selections(None, cx, |selections| selections.select(new_selections));
3922 }
3923
3924 /// Iterate the given selections, and for each one, find the smallest surrounding
3925 /// autoclose region. This uses the ordering of the selections and the autoclose
3926 /// regions to avoid repeated comparisons.
3927 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3928 &'a self,
3929 selections: impl IntoIterator<Item = Selection<D>>,
3930 buffer: &'a MultiBufferSnapshot,
3931 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3932 let mut i = 0;
3933 let mut regions = self.autoclose_regions.as_slice();
3934 selections.into_iter().map(move |selection| {
3935 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3936
3937 let mut enclosing = None;
3938 while let Some(pair_state) = regions.get(i) {
3939 if pair_state.range.end.to_offset(buffer) < range.start {
3940 regions = ®ions[i + 1..];
3941 i = 0;
3942 } else if pair_state.range.start.to_offset(buffer) > range.end {
3943 break;
3944 } else {
3945 if pair_state.selection_id == selection.id {
3946 enclosing = Some(pair_state);
3947 }
3948 i += 1;
3949 }
3950 }
3951
3952 (selection.clone(), enclosing)
3953 })
3954 }
3955
3956 /// Remove any autoclose regions that no longer contain their selection.
3957 fn invalidate_autoclose_regions(
3958 &mut self,
3959 mut selections: &[Selection<Anchor>],
3960 buffer: &MultiBufferSnapshot,
3961 ) {
3962 self.autoclose_regions.retain(|state| {
3963 let mut i = 0;
3964 while let Some(selection) = selections.get(i) {
3965 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3966 selections = &selections[1..];
3967 continue;
3968 }
3969 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3970 break;
3971 }
3972 if selection.id == state.selection_id {
3973 return true;
3974 } else {
3975 i += 1;
3976 }
3977 }
3978 false
3979 });
3980 }
3981
3982 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3983 let offset = position.to_offset(buffer);
3984 let (word_range, kind) = buffer.surrounding_word(offset, true);
3985 if offset > word_range.start && kind == Some(CharKind::Word) {
3986 Some(
3987 buffer
3988 .text_for_range(word_range.start..offset)
3989 .collect::<String>(),
3990 )
3991 } else {
3992 None
3993 }
3994 }
3995
3996 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3997 self.refresh_inlay_hints(
3998 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3999 cx,
4000 );
4001 }
4002
4003 pub fn inlay_hints_enabled(&self) -> bool {
4004 self.inlay_hint_cache.enabled
4005 }
4006
4007 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4008 if self.project.is_none() || self.mode != EditorMode::Full {
4009 return;
4010 }
4011
4012 let reason_description = reason.description();
4013 let ignore_debounce = matches!(
4014 reason,
4015 InlayHintRefreshReason::SettingsChange(_)
4016 | InlayHintRefreshReason::Toggle(_)
4017 | InlayHintRefreshReason::ExcerptsRemoved(_)
4018 );
4019 let (invalidate_cache, required_languages) = match reason {
4020 InlayHintRefreshReason::Toggle(enabled) => {
4021 self.inlay_hint_cache.enabled = enabled;
4022 if enabled {
4023 (InvalidationStrategy::RefreshRequested, None)
4024 } else {
4025 self.inlay_hint_cache.clear();
4026 self.splice_inlays(
4027 self.visible_inlay_hints(cx)
4028 .iter()
4029 .map(|inlay| inlay.id)
4030 .collect(),
4031 Vec::new(),
4032 cx,
4033 );
4034 return;
4035 }
4036 }
4037 InlayHintRefreshReason::SettingsChange(new_settings) => {
4038 match self.inlay_hint_cache.update_settings(
4039 &self.buffer,
4040 new_settings,
4041 self.visible_inlay_hints(cx),
4042 cx,
4043 ) {
4044 ControlFlow::Break(Some(InlaySplice {
4045 to_remove,
4046 to_insert,
4047 })) => {
4048 self.splice_inlays(to_remove, to_insert, cx);
4049 return;
4050 }
4051 ControlFlow::Break(None) => return,
4052 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4053 }
4054 }
4055 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4056 if let Some(InlaySplice {
4057 to_remove,
4058 to_insert,
4059 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4060 {
4061 self.splice_inlays(to_remove, to_insert, cx);
4062 }
4063 return;
4064 }
4065 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4066 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4067 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4068 }
4069 InlayHintRefreshReason::RefreshRequested => {
4070 (InvalidationStrategy::RefreshRequested, None)
4071 }
4072 };
4073
4074 if let Some(InlaySplice {
4075 to_remove,
4076 to_insert,
4077 }) = self.inlay_hint_cache.spawn_hint_refresh(
4078 reason_description,
4079 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4080 invalidate_cache,
4081 ignore_debounce,
4082 cx,
4083 ) {
4084 self.splice_inlays(to_remove, to_insert, cx);
4085 }
4086 }
4087
4088 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4089 self.display_map
4090 .read(cx)
4091 .current_inlays()
4092 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4093 .cloned()
4094 .collect()
4095 }
4096
4097 pub fn excerpts_for_inlay_hints_query(
4098 &self,
4099 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4100 cx: &mut ViewContext<Editor>,
4101 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4102 let Some(project) = self.project.as_ref() else {
4103 return HashMap::default();
4104 };
4105 let project = project.read(cx);
4106 let multi_buffer = self.buffer().read(cx);
4107 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4108 let multi_buffer_visible_start = self
4109 .scroll_manager
4110 .anchor()
4111 .anchor
4112 .to_point(&multi_buffer_snapshot);
4113 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4114 multi_buffer_visible_start
4115 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4116 Bias::Left,
4117 );
4118 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4119 multi_buffer
4120 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4121 .into_iter()
4122 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4123 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4124 let buffer = buffer_handle.read(cx);
4125 let buffer_file = project::File::from_dyn(buffer.file())?;
4126 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4127 let worktree_entry = buffer_worktree
4128 .read(cx)
4129 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4130 if worktree_entry.is_ignored {
4131 return None;
4132 }
4133
4134 let language = buffer.language()?;
4135 if let Some(restrict_to_languages) = restrict_to_languages {
4136 if !restrict_to_languages.contains(language) {
4137 return None;
4138 }
4139 }
4140 Some((
4141 excerpt_id,
4142 (
4143 buffer_handle,
4144 buffer.version().clone(),
4145 excerpt_visible_range,
4146 ),
4147 ))
4148 })
4149 .collect()
4150 }
4151
4152 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4153 TextLayoutDetails {
4154 text_system: cx.text_system().clone(),
4155 editor_style: self.style.clone().unwrap(),
4156 rem_size: cx.rem_size(),
4157 scroll_anchor: self.scroll_manager.anchor(),
4158 visible_rows: self.visible_line_count(),
4159 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4160 }
4161 }
4162
4163 fn splice_inlays(
4164 &self,
4165 to_remove: Vec<InlayId>,
4166 to_insert: Vec<Inlay>,
4167 cx: &mut ViewContext<Self>,
4168 ) {
4169 self.display_map.update(cx, |display_map, cx| {
4170 display_map.splice_inlays(to_remove, to_insert, cx);
4171 });
4172 cx.notify();
4173 }
4174
4175 fn trigger_on_type_formatting(
4176 &self,
4177 input: String,
4178 cx: &mut ViewContext<Self>,
4179 ) -> Option<Task<Result<()>>> {
4180 if input.len() != 1 {
4181 return None;
4182 }
4183
4184 let project = self.project.as_ref()?;
4185 let position = self.selections.newest_anchor().head();
4186 let (buffer, buffer_position) = self
4187 .buffer
4188 .read(cx)
4189 .text_anchor_for_position(position, cx)?;
4190
4191 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4192 // hence we do LSP request & edit on host side only — add formats to host's history.
4193 let push_to_lsp_host_history = true;
4194 // If this is not the host, append its history with new edits.
4195 let push_to_client_history = project.read(cx).is_via_collab();
4196
4197 let on_type_formatting = project.update(cx, |project, cx| {
4198 project.on_type_format(
4199 buffer.clone(),
4200 buffer_position,
4201 input,
4202 push_to_lsp_host_history,
4203 cx,
4204 )
4205 });
4206 Some(cx.spawn(|editor, mut cx| async move {
4207 if let Some(transaction) = on_type_formatting.await? {
4208 if push_to_client_history {
4209 buffer
4210 .update(&mut cx, |buffer, _| {
4211 buffer.push_transaction(transaction, Instant::now());
4212 })
4213 .ok();
4214 }
4215 editor.update(&mut cx, |editor, cx| {
4216 editor.refresh_document_highlights(cx);
4217 })?;
4218 }
4219 Ok(())
4220 }))
4221 }
4222
4223 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4224 if self.pending_rename.is_some() {
4225 return;
4226 }
4227
4228 let Some(provider) = self.completion_provider.as_ref() else {
4229 return;
4230 };
4231
4232 let position = self.selections.newest_anchor().head();
4233 let (buffer, buffer_position) =
4234 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4235 output
4236 } else {
4237 return;
4238 };
4239
4240 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4241 let is_followup_invoke = {
4242 let context_menu_state = self.context_menu.read();
4243 matches!(
4244 context_menu_state.deref(),
4245 Some(ContextMenu::Completions(_))
4246 )
4247 };
4248 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4249 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4250 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4251 CompletionTriggerKind::TRIGGER_CHARACTER
4252 }
4253
4254 _ => CompletionTriggerKind::INVOKED,
4255 };
4256 let completion_context = CompletionContext {
4257 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4258 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4259 Some(String::from(trigger))
4260 } else {
4261 None
4262 }
4263 }),
4264 trigger_kind,
4265 };
4266 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4267 let sort_completions = provider.sort_completions();
4268
4269 let id = post_inc(&mut self.next_completion_id);
4270 let task = cx.spawn(|this, mut cx| {
4271 async move {
4272 this.update(&mut cx, |this, _| {
4273 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4274 })?;
4275 let completions = completions.await.log_err();
4276 let menu = if let Some(completions) = completions {
4277 let mut menu = CompletionsMenu {
4278 id,
4279 sort_completions,
4280 initial_position: position,
4281 match_candidates: completions
4282 .iter()
4283 .enumerate()
4284 .map(|(id, completion)| {
4285 StringMatchCandidate::new(
4286 id,
4287 completion.label.text[completion.label.filter_range.clone()]
4288 .into(),
4289 )
4290 })
4291 .collect(),
4292 buffer: buffer.clone(),
4293 completions: Arc::new(RwLock::new(completions.into())),
4294 matches: Vec::new().into(),
4295 selected_item: 0,
4296 scroll_handle: UniformListScrollHandle::new(),
4297 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4298 DebouncedDelay::new(),
4299 )),
4300 };
4301 menu.filter(query.as_deref(), cx.background_executor().clone())
4302 .await;
4303
4304 if menu.matches.is_empty() {
4305 None
4306 } else {
4307 this.update(&mut cx, |editor, cx| {
4308 let completions = menu.completions.clone();
4309 let matches = menu.matches.clone();
4310
4311 let delay_ms = EditorSettings::get_global(cx)
4312 .completion_documentation_secondary_query_debounce;
4313 let delay = Duration::from_millis(delay_ms);
4314 editor
4315 .completion_documentation_pre_resolve_debounce
4316 .fire_new(delay, cx, |editor, cx| {
4317 CompletionsMenu::pre_resolve_completion_documentation(
4318 buffer,
4319 completions,
4320 matches,
4321 editor,
4322 cx,
4323 )
4324 });
4325 })
4326 .ok();
4327 Some(menu)
4328 }
4329 } else {
4330 None
4331 };
4332
4333 this.update(&mut cx, |this, cx| {
4334 let mut context_menu = this.context_menu.write();
4335 match context_menu.as_ref() {
4336 None => {}
4337
4338 Some(ContextMenu::Completions(prev_menu)) => {
4339 if prev_menu.id > id {
4340 return;
4341 }
4342 }
4343
4344 _ => return,
4345 }
4346
4347 if this.focus_handle.is_focused(cx) && menu.is_some() {
4348 let menu = menu.unwrap();
4349 *context_menu = Some(ContextMenu::Completions(menu));
4350 drop(context_menu);
4351 this.discard_inline_completion(false, cx);
4352 cx.notify();
4353 } else if this.completion_tasks.len() <= 1 {
4354 // If there are no more completion tasks and the last menu was
4355 // empty, we should hide it. If it was already hidden, we should
4356 // also show the copilot completion when available.
4357 drop(context_menu);
4358 if this.hide_context_menu(cx).is_none() {
4359 this.update_visible_inline_completion(cx);
4360 }
4361 }
4362 })?;
4363
4364 Ok::<_, anyhow::Error>(())
4365 }
4366 .log_err()
4367 });
4368
4369 self.completion_tasks.push((id, task));
4370 }
4371
4372 pub fn confirm_completion(
4373 &mut self,
4374 action: &ConfirmCompletion,
4375 cx: &mut ViewContext<Self>,
4376 ) -> Option<Task<Result<()>>> {
4377 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4378 }
4379
4380 pub fn compose_completion(
4381 &mut self,
4382 action: &ComposeCompletion,
4383 cx: &mut ViewContext<Self>,
4384 ) -> Option<Task<Result<()>>> {
4385 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4386 }
4387
4388 fn do_completion(
4389 &mut self,
4390 item_ix: Option<usize>,
4391 intent: CompletionIntent,
4392 cx: &mut ViewContext<Editor>,
4393 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4394 use language::ToOffset as _;
4395
4396 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4397 menu
4398 } else {
4399 return None;
4400 };
4401
4402 let mat = completions_menu
4403 .matches
4404 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4405 let buffer_handle = completions_menu.buffer;
4406 let completions = completions_menu.completions.read();
4407 let completion = completions.get(mat.candidate_id)?;
4408 cx.stop_propagation();
4409
4410 let snippet;
4411 let text;
4412
4413 if completion.is_snippet() {
4414 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4415 text = snippet.as_ref().unwrap().text.clone();
4416 } else {
4417 snippet = None;
4418 text = completion.new_text.clone();
4419 };
4420 let selections = self.selections.all::<usize>(cx);
4421 let buffer = buffer_handle.read(cx);
4422 let old_range = completion.old_range.to_offset(buffer);
4423 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4424
4425 let newest_selection = self.selections.newest_anchor();
4426 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4427 return None;
4428 }
4429
4430 let lookbehind = newest_selection
4431 .start
4432 .text_anchor
4433 .to_offset(buffer)
4434 .saturating_sub(old_range.start);
4435 let lookahead = old_range
4436 .end
4437 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4438 let mut common_prefix_len = old_text
4439 .bytes()
4440 .zip(text.bytes())
4441 .take_while(|(a, b)| a == b)
4442 .count();
4443
4444 let snapshot = self.buffer.read(cx).snapshot(cx);
4445 let mut range_to_replace: Option<Range<isize>> = None;
4446 let mut ranges = Vec::new();
4447 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4448 for selection in &selections {
4449 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4450 let start = selection.start.saturating_sub(lookbehind);
4451 let end = selection.end + lookahead;
4452 if selection.id == newest_selection.id {
4453 range_to_replace = Some(
4454 ((start + common_prefix_len) as isize - selection.start as isize)
4455 ..(end as isize - selection.start as isize),
4456 );
4457 }
4458 ranges.push(start + common_prefix_len..end);
4459 } else {
4460 common_prefix_len = 0;
4461 ranges.clear();
4462 ranges.extend(selections.iter().map(|s| {
4463 if s.id == newest_selection.id {
4464 range_to_replace = Some(
4465 old_range.start.to_offset_utf16(&snapshot).0 as isize
4466 - selection.start as isize
4467 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4468 - selection.start as isize,
4469 );
4470 old_range.clone()
4471 } else {
4472 s.start..s.end
4473 }
4474 }));
4475 break;
4476 }
4477 if !self.linked_edit_ranges.is_empty() {
4478 let start_anchor = snapshot.anchor_before(selection.head());
4479 let end_anchor = snapshot.anchor_after(selection.tail());
4480 if let Some(ranges) = self
4481 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4482 {
4483 for (buffer, edits) in ranges {
4484 linked_edits.entry(buffer.clone()).or_default().extend(
4485 edits
4486 .into_iter()
4487 .map(|range| (range, text[common_prefix_len..].to_owned())),
4488 );
4489 }
4490 }
4491 }
4492 }
4493 let text = &text[common_prefix_len..];
4494
4495 cx.emit(EditorEvent::InputHandled {
4496 utf16_range_to_replace: range_to_replace,
4497 text: text.into(),
4498 });
4499
4500 self.transact(cx, |this, cx| {
4501 if let Some(mut snippet) = snippet {
4502 snippet.text = text.to_string();
4503 for tabstop in snippet.tabstops.iter_mut().flatten() {
4504 tabstop.start -= common_prefix_len as isize;
4505 tabstop.end -= common_prefix_len as isize;
4506 }
4507
4508 this.insert_snippet(&ranges, snippet, cx).log_err();
4509 } else {
4510 this.buffer.update(cx, |buffer, cx| {
4511 buffer.edit(
4512 ranges.iter().map(|range| (range.clone(), text)),
4513 this.autoindent_mode.clone(),
4514 cx,
4515 );
4516 });
4517 }
4518 for (buffer, edits) in linked_edits {
4519 buffer.update(cx, |buffer, cx| {
4520 let snapshot = buffer.snapshot();
4521 let edits = edits
4522 .into_iter()
4523 .map(|(range, text)| {
4524 use text::ToPoint as TP;
4525 let end_point = TP::to_point(&range.end, &snapshot);
4526 let start_point = TP::to_point(&range.start, &snapshot);
4527 (start_point..end_point, text)
4528 })
4529 .sorted_by_key(|(range, _)| range.start)
4530 .collect::<Vec<_>>();
4531 buffer.edit(edits, None, cx);
4532 })
4533 }
4534
4535 this.refresh_inline_completion(true, false, cx);
4536 });
4537
4538 let show_new_completions_on_confirm = completion
4539 .confirm
4540 .as_ref()
4541 .map_or(false, |confirm| confirm(intent, cx));
4542 if show_new_completions_on_confirm {
4543 self.show_completions(&ShowCompletions { trigger: None }, cx);
4544 }
4545
4546 let provider = self.completion_provider.as_ref()?;
4547 let apply_edits = provider.apply_additional_edits_for_completion(
4548 buffer_handle,
4549 completion.clone(),
4550 true,
4551 cx,
4552 );
4553
4554 let editor_settings = EditorSettings::get_global(cx);
4555 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4556 // After the code completion is finished, users often want to know what signatures are needed.
4557 // so we should automatically call signature_help
4558 self.show_signature_help(&ShowSignatureHelp, cx);
4559 }
4560
4561 Some(cx.foreground_executor().spawn(async move {
4562 apply_edits.await?;
4563 Ok(())
4564 }))
4565 }
4566
4567 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4568 let mut context_menu = self.context_menu.write();
4569 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4570 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4571 // Toggle if we're selecting the same one
4572 *context_menu = None;
4573 cx.notify();
4574 return;
4575 } else {
4576 // Otherwise, clear it and start a new one
4577 *context_menu = None;
4578 cx.notify();
4579 }
4580 }
4581 drop(context_menu);
4582 let snapshot = self.snapshot(cx);
4583 let deployed_from_indicator = action.deployed_from_indicator;
4584 let mut task = self.code_actions_task.take();
4585 let action = action.clone();
4586 cx.spawn(|editor, mut cx| async move {
4587 while let Some(prev_task) = task {
4588 prev_task.await.log_err();
4589 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4590 }
4591
4592 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4593 if editor.focus_handle.is_focused(cx) {
4594 let multibuffer_point = action
4595 .deployed_from_indicator
4596 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4597 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4598 let (buffer, buffer_row) = snapshot
4599 .buffer_snapshot
4600 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4601 .and_then(|(buffer_snapshot, range)| {
4602 editor
4603 .buffer
4604 .read(cx)
4605 .buffer(buffer_snapshot.remote_id())
4606 .map(|buffer| (buffer, range.start.row))
4607 })?;
4608 let (_, code_actions) = editor
4609 .available_code_actions
4610 .clone()
4611 .and_then(|(location, code_actions)| {
4612 let snapshot = location.buffer.read(cx).snapshot();
4613 let point_range = location.range.to_point(&snapshot);
4614 let point_range = point_range.start.row..=point_range.end.row;
4615 if point_range.contains(&buffer_row) {
4616 Some((location, code_actions))
4617 } else {
4618 None
4619 }
4620 })
4621 .unzip();
4622 let buffer_id = buffer.read(cx).remote_id();
4623 let tasks = editor
4624 .tasks
4625 .get(&(buffer_id, buffer_row))
4626 .map(|t| Arc::new(t.to_owned()));
4627 if tasks.is_none() && code_actions.is_none() {
4628 return None;
4629 }
4630
4631 editor.completion_tasks.clear();
4632 editor.discard_inline_completion(false, cx);
4633 let task_context =
4634 tasks
4635 .as_ref()
4636 .zip(editor.project.clone())
4637 .map(|(tasks, project)| {
4638 let position = Point::new(buffer_row, tasks.column);
4639 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4640 let location = Location {
4641 buffer: buffer.clone(),
4642 range: range_start..range_start,
4643 };
4644 // Fill in the environmental variables from the tree-sitter captures
4645 let mut captured_task_variables = TaskVariables::default();
4646 for (capture_name, value) in tasks.extra_variables.clone() {
4647 captured_task_variables.insert(
4648 task::VariableName::Custom(capture_name.into()),
4649 value.clone(),
4650 );
4651 }
4652 project.update(cx, |project, cx| {
4653 project.task_context_for_location(
4654 captured_task_variables,
4655 location,
4656 cx,
4657 )
4658 })
4659 });
4660
4661 Some(cx.spawn(|editor, mut cx| async move {
4662 let task_context = match task_context {
4663 Some(task_context) => task_context.await,
4664 None => None,
4665 };
4666 let resolved_tasks =
4667 tasks.zip(task_context).map(|(tasks, task_context)| {
4668 Arc::new(ResolvedTasks {
4669 templates: tasks
4670 .templates
4671 .iter()
4672 .filter_map(|(kind, template)| {
4673 template
4674 .resolve_task(&kind.to_id_base(), &task_context)
4675 .map(|task| (kind.clone(), task))
4676 })
4677 .collect(),
4678 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4679 multibuffer_point.row,
4680 tasks.column,
4681 )),
4682 })
4683 });
4684 let spawn_straight_away = resolved_tasks
4685 .as_ref()
4686 .map_or(false, |tasks| tasks.templates.len() == 1)
4687 && code_actions
4688 .as_ref()
4689 .map_or(true, |actions| actions.is_empty());
4690 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4691 *editor.context_menu.write() =
4692 Some(ContextMenu::CodeActions(CodeActionsMenu {
4693 buffer,
4694 actions: CodeActionContents {
4695 tasks: resolved_tasks,
4696 actions: code_actions,
4697 },
4698 selected_item: Default::default(),
4699 scroll_handle: UniformListScrollHandle::default(),
4700 deployed_from_indicator,
4701 }));
4702 if spawn_straight_away {
4703 if let Some(task) = editor.confirm_code_action(
4704 &ConfirmCodeAction { item_ix: Some(0) },
4705 cx,
4706 ) {
4707 cx.notify();
4708 return task;
4709 }
4710 }
4711 cx.notify();
4712 Task::ready(Ok(()))
4713 }) {
4714 task.await
4715 } else {
4716 Ok(())
4717 }
4718 }))
4719 } else {
4720 Some(Task::ready(Ok(())))
4721 }
4722 })?;
4723 if let Some(task) = spawned_test_task {
4724 task.await?;
4725 }
4726
4727 Ok::<_, anyhow::Error>(())
4728 })
4729 .detach_and_log_err(cx);
4730 }
4731
4732 pub fn confirm_code_action(
4733 &mut self,
4734 action: &ConfirmCodeAction,
4735 cx: &mut ViewContext<Self>,
4736 ) -> Option<Task<Result<()>>> {
4737 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4738 menu
4739 } else {
4740 return None;
4741 };
4742 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4743 let action = actions_menu.actions.get(action_ix)?;
4744 let title = action.label();
4745 let buffer = actions_menu.buffer;
4746 let workspace = self.workspace()?;
4747
4748 match action {
4749 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4750 workspace.update(cx, |workspace, cx| {
4751 workspace::tasks::schedule_resolved_task(
4752 workspace,
4753 task_source_kind,
4754 resolved_task,
4755 false,
4756 cx,
4757 );
4758
4759 Some(Task::ready(Ok(())))
4760 })
4761 }
4762 CodeActionsItem::CodeAction {
4763 excerpt_id,
4764 action,
4765 provider,
4766 } => {
4767 let apply_code_action =
4768 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4769 let workspace = workspace.downgrade();
4770 Some(cx.spawn(|editor, cx| async move {
4771 let project_transaction = apply_code_action.await?;
4772 Self::open_project_transaction(
4773 &editor,
4774 workspace,
4775 project_transaction,
4776 title,
4777 cx,
4778 )
4779 .await
4780 }))
4781 }
4782 }
4783 }
4784
4785 pub async fn open_project_transaction(
4786 this: &WeakView<Editor>,
4787 workspace: WeakView<Workspace>,
4788 transaction: ProjectTransaction,
4789 title: String,
4790 mut cx: AsyncWindowContext,
4791 ) -> Result<()> {
4792 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4793 cx.update(|cx| {
4794 entries.sort_unstable_by_key(|(buffer, _)| {
4795 buffer.read(cx).file().map(|f| f.path().clone())
4796 });
4797 })?;
4798
4799 // If the project transaction's edits are all contained within this editor, then
4800 // avoid opening a new editor to display them.
4801
4802 if let Some((buffer, transaction)) = entries.first() {
4803 if entries.len() == 1 {
4804 let excerpt = this.update(&mut cx, |editor, cx| {
4805 editor
4806 .buffer()
4807 .read(cx)
4808 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4809 })?;
4810 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4811 if excerpted_buffer == *buffer {
4812 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4813 let excerpt_range = excerpt_range.to_offset(buffer);
4814 buffer
4815 .edited_ranges_for_transaction::<usize>(transaction)
4816 .all(|range| {
4817 excerpt_range.start <= range.start
4818 && excerpt_range.end >= range.end
4819 })
4820 })?;
4821
4822 if all_edits_within_excerpt {
4823 return Ok(());
4824 }
4825 }
4826 }
4827 }
4828 } else {
4829 return Ok(());
4830 }
4831
4832 let mut ranges_to_highlight = Vec::new();
4833 let excerpt_buffer = cx.new_model(|cx| {
4834 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4835 for (buffer_handle, transaction) in &entries {
4836 let buffer = buffer_handle.read(cx);
4837 ranges_to_highlight.extend(
4838 multibuffer.push_excerpts_with_context_lines(
4839 buffer_handle.clone(),
4840 buffer
4841 .edited_ranges_for_transaction::<usize>(transaction)
4842 .collect(),
4843 DEFAULT_MULTIBUFFER_CONTEXT,
4844 cx,
4845 ),
4846 );
4847 }
4848 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4849 multibuffer
4850 })?;
4851
4852 workspace.update(&mut cx, |workspace, cx| {
4853 let project = workspace.project().clone();
4854 let editor =
4855 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4856 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4857 editor.update(cx, |editor, cx| {
4858 editor.highlight_background::<Self>(
4859 &ranges_to_highlight,
4860 |theme| theme.editor_highlighted_line_background,
4861 cx,
4862 );
4863 });
4864 })?;
4865
4866 Ok(())
4867 }
4868
4869 pub fn push_code_action_provider(
4870 &mut self,
4871 provider: Arc<dyn CodeActionProvider>,
4872 cx: &mut ViewContext<Self>,
4873 ) {
4874 self.code_action_providers.push(provider);
4875 self.refresh_code_actions(cx);
4876 }
4877
4878 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4879 let buffer = self.buffer.read(cx);
4880 let newest_selection = self.selections.newest_anchor().clone();
4881 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4882 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4883 if start_buffer != end_buffer {
4884 return None;
4885 }
4886
4887 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4888 cx.background_executor()
4889 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4890 .await;
4891
4892 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4893 let providers = this.code_action_providers.clone();
4894 let tasks = this
4895 .code_action_providers
4896 .iter()
4897 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4898 .collect::<Vec<_>>();
4899 (providers, tasks)
4900 })?;
4901
4902 let mut actions = Vec::new();
4903 for (provider, provider_actions) in
4904 providers.into_iter().zip(future::join_all(tasks).await)
4905 {
4906 if let Some(provider_actions) = provider_actions.log_err() {
4907 actions.extend(provider_actions.into_iter().map(|action| {
4908 AvailableCodeAction {
4909 excerpt_id: newest_selection.start.excerpt_id,
4910 action,
4911 provider: provider.clone(),
4912 }
4913 }));
4914 }
4915 }
4916
4917 this.update(&mut cx, |this, cx| {
4918 this.available_code_actions = if actions.is_empty() {
4919 None
4920 } else {
4921 Some((
4922 Location {
4923 buffer: start_buffer,
4924 range: start..end,
4925 },
4926 actions.into(),
4927 ))
4928 };
4929 cx.notify();
4930 })
4931 }));
4932 None
4933 }
4934
4935 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4936 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4937 self.show_git_blame_inline = false;
4938
4939 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4940 cx.background_executor().timer(delay).await;
4941
4942 this.update(&mut cx, |this, cx| {
4943 this.show_git_blame_inline = true;
4944 cx.notify();
4945 })
4946 .log_err();
4947 }));
4948 }
4949 }
4950
4951 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4952 if self.pending_rename.is_some() {
4953 return None;
4954 }
4955
4956 let project = self.project.clone()?;
4957 let buffer = self.buffer.read(cx);
4958 let newest_selection = self.selections.newest_anchor().clone();
4959 let cursor_position = newest_selection.head();
4960 let (cursor_buffer, cursor_buffer_position) =
4961 buffer.text_anchor_for_position(cursor_position, cx)?;
4962 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4963 if cursor_buffer != tail_buffer {
4964 return None;
4965 }
4966
4967 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4968 cx.background_executor()
4969 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4970 .await;
4971
4972 let highlights = if let Some(highlights) = project
4973 .update(&mut cx, |project, cx| {
4974 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4975 })
4976 .log_err()
4977 {
4978 highlights.await.log_err()
4979 } else {
4980 None
4981 };
4982
4983 if let Some(highlights) = highlights {
4984 this.update(&mut cx, |this, cx| {
4985 if this.pending_rename.is_some() {
4986 return;
4987 }
4988
4989 let buffer_id = cursor_position.buffer_id;
4990 let buffer = this.buffer.read(cx);
4991 if !buffer
4992 .text_anchor_for_position(cursor_position, cx)
4993 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4994 {
4995 return;
4996 }
4997
4998 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4999 let mut write_ranges = Vec::new();
5000 let mut read_ranges = Vec::new();
5001 for highlight in highlights {
5002 for (excerpt_id, excerpt_range) in
5003 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5004 {
5005 let start = highlight
5006 .range
5007 .start
5008 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5009 let end = highlight
5010 .range
5011 .end
5012 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5013 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5014 continue;
5015 }
5016
5017 let range = Anchor {
5018 buffer_id,
5019 excerpt_id,
5020 text_anchor: start,
5021 }..Anchor {
5022 buffer_id,
5023 excerpt_id,
5024 text_anchor: end,
5025 };
5026 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5027 write_ranges.push(range);
5028 } else {
5029 read_ranges.push(range);
5030 }
5031 }
5032 }
5033
5034 this.highlight_background::<DocumentHighlightRead>(
5035 &read_ranges,
5036 |theme| theme.editor_document_highlight_read_background,
5037 cx,
5038 );
5039 this.highlight_background::<DocumentHighlightWrite>(
5040 &write_ranges,
5041 |theme| theme.editor_document_highlight_write_background,
5042 cx,
5043 );
5044 cx.notify();
5045 })
5046 .log_err();
5047 }
5048 }));
5049 None
5050 }
5051
5052 pub fn refresh_inline_completion(
5053 &mut self,
5054 debounce: bool,
5055 user_requested: bool,
5056 cx: &mut ViewContext<Self>,
5057 ) -> Option<()> {
5058 let provider = self.inline_completion_provider()?;
5059 let cursor = self.selections.newest_anchor().head();
5060 let (buffer, cursor_buffer_position) =
5061 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5062
5063 if !user_requested
5064 && (!self.enable_inline_completions
5065 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5066 {
5067 self.discard_inline_completion(false, cx);
5068 return None;
5069 }
5070
5071 self.update_visible_inline_completion(cx);
5072 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5073 Some(())
5074 }
5075
5076 fn cycle_inline_completion(
5077 &mut self,
5078 direction: Direction,
5079 cx: &mut ViewContext<Self>,
5080 ) -> Option<()> {
5081 let provider = self.inline_completion_provider()?;
5082 let cursor = self.selections.newest_anchor().head();
5083 let (buffer, cursor_buffer_position) =
5084 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5085 if !self.enable_inline_completions
5086 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5087 {
5088 return None;
5089 }
5090
5091 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5092 self.update_visible_inline_completion(cx);
5093
5094 Some(())
5095 }
5096
5097 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5098 if !self.has_active_inline_completion(cx) {
5099 self.refresh_inline_completion(false, true, cx);
5100 return;
5101 }
5102
5103 self.update_visible_inline_completion(cx);
5104 }
5105
5106 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5107 self.show_cursor_names(cx);
5108 }
5109
5110 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5111 self.show_cursor_names = true;
5112 cx.notify();
5113 cx.spawn(|this, mut cx| async move {
5114 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5115 this.update(&mut cx, |this, cx| {
5116 this.show_cursor_names = false;
5117 cx.notify()
5118 })
5119 .ok()
5120 })
5121 .detach();
5122 }
5123
5124 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5125 if self.has_active_inline_completion(cx) {
5126 self.cycle_inline_completion(Direction::Next, cx);
5127 } else {
5128 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5129 if is_copilot_disabled {
5130 cx.propagate();
5131 }
5132 }
5133 }
5134
5135 pub fn previous_inline_completion(
5136 &mut self,
5137 _: &PreviousInlineCompletion,
5138 cx: &mut ViewContext<Self>,
5139 ) {
5140 if self.has_active_inline_completion(cx) {
5141 self.cycle_inline_completion(Direction::Prev, cx);
5142 } else {
5143 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5144 if is_copilot_disabled {
5145 cx.propagate();
5146 }
5147 }
5148 }
5149
5150 pub fn accept_inline_completion(
5151 &mut self,
5152 _: &AcceptInlineCompletion,
5153 cx: &mut ViewContext<Self>,
5154 ) {
5155 let Some(completion) = self.take_active_inline_completion(cx) else {
5156 return;
5157 };
5158 if let Some(provider) = self.inline_completion_provider() {
5159 provider.accept(cx);
5160 }
5161
5162 cx.emit(EditorEvent::InputHandled {
5163 utf16_range_to_replace: None,
5164 text: completion.text.to_string().into(),
5165 });
5166
5167 if let Some(range) = completion.delete_range {
5168 self.change_selections(None, cx, |s| s.select_ranges([range]))
5169 }
5170 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5171 self.refresh_inline_completion(true, true, cx);
5172 cx.notify();
5173 }
5174
5175 pub fn accept_partial_inline_completion(
5176 &mut self,
5177 _: &AcceptPartialInlineCompletion,
5178 cx: &mut ViewContext<Self>,
5179 ) {
5180 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5181 if let Some(completion) = self.take_active_inline_completion(cx) {
5182 let mut partial_completion = completion
5183 .text
5184 .chars()
5185 .by_ref()
5186 .take_while(|c| c.is_alphabetic())
5187 .collect::<String>();
5188 if partial_completion.is_empty() {
5189 partial_completion = completion
5190 .text
5191 .chars()
5192 .by_ref()
5193 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5194 .collect::<String>();
5195 }
5196
5197 cx.emit(EditorEvent::InputHandled {
5198 utf16_range_to_replace: None,
5199 text: partial_completion.clone().into(),
5200 });
5201
5202 if let Some(range) = completion.delete_range {
5203 self.change_selections(None, cx, |s| s.select_ranges([range]))
5204 }
5205 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5206
5207 self.refresh_inline_completion(true, true, cx);
5208 cx.notify();
5209 }
5210 }
5211 }
5212
5213 fn discard_inline_completion(
5214 &mut self,
5215 should_report_inline_completion_event: bool,
5216 cx: &mut ViewContext<Self>,
5217 ) -> bool {
5218 if let Some(provider) = self.inline_completion_provider() {
5219 provider.discard(should_report_inline_completion_event, cx);
5220 }
5221
5222 self.take_active_inline_completion(cx).is_some()
5223 }
5224
5225 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5226 if let Some(completion) = self.active_inline_completion.as_ref() {
5227 let buffer = self.buffer.read(cx).read(cx);
5228 completion.position.is_valid(&buffer)
5229 } else {
5230 false
5231 }
5232 }
5233
5234 fn take_active_inline_completion(
5235 &mut self,
5236 cx: &mut ViewContext<Self>,
5237 ) -> Option<CompletionState> {
5238 let completion = self.active_inline_completion.take()?;
5239 let render_inlay_ids = completion.render_inlay_ids.clone();
5240 self.display_map.update(cx, |map, cx| {
5241 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5242 });
5243 let buffer = self.buffer.read(cx).read(cx);
5244
5245 if completion.position.is_valid(&buffer) {
5246 Some(completion)
5247 } else {
5248 None
5249 }
5250 }
5251
5252 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5253 let selection = self.selections.newest_anchor();
5254 let cursor = selection.head();
5255
5256 let excerpt_id = cursor.excerpt_id;
5257
5258 if self.context_menu.read().is_none()
5259 && self.completion_tasks.is_empty()
5260 && selection.start == selection.end
5261 {
5262 if let Some(provider) = self.inline_completion_provider() {
5263 if let Some((buffer, cursor_buffer_position)) =
5264 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5265 {
5266 if let Some(proposal) =
5267 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5268 {
5269 let mut to_remove = Vec::new();
5270 if let Some(completion) = self.active_inline_completion.take() {
5271 to_remove.extend(completion.render_inlay_ids.iter());
5272 }
5273
5274 let to_add = proposal
5275 .inlays
5276 .iter()
5277 .filter_map(|inlay| {
5278 let snapshot = self.buffer.read(cx).snapshot(cx);
5279 let id = post_inc(&mut self.next_inlay_id);
5280 match inlay {
5281 InlayProposal::Hint(position, hint) => {
5282 let position =
5283 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5284 Some(Inlay::hint(id, position, hint))
5285 }
5286 InlayProposal::Suggestion(position, text) => {
5287 let position =
5288 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5289 Some(Inlay::suggestion(id, position, text.clone()))
5290 }
5291 }
5292 })
5293 .collect_vec();
5294
5295 self.active_inline_completion = Some(CompletionState {
5296 position: cursor,
5297 text: proposal.text,
5298 delete_range: proposal.delete_range.and_then(|range| {
5299 let snapshot = self.buffer.read(cx).snapshot(cx);
5300 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5301 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5302 Some(start?..end?)
5303 }),
5304 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5305 });
5306
5307 self.display_map
5308 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5309
5310 cx.notify();
5311 return;
5312 }
5313 }
5314 }
5315 }
5316
5317 self.discard_inline_completion(false, cx);
5318 }
5319
5320 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5321 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5322 }
5323
5324 fn render_code_actions_indicator(
5325 &self,
5326 _style: &EditorStyle,
5327 row: DisplayRow,
5328 is_active: bool,
5329 cx: &mut ViewContext<Self>,
5330 ) -> Option<IconButton> {
5331 if self.available_code_actions.is_some() {
5332 Some(
5333 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5334 .shape(ui::IconButtonShape::Square)
5335 .icon_size(IconSize::XSmall)
5336 .icon_color(Color::Muted)
5337 .selected(is_active)
5338 .on_click(cx.listener(move |editor, _e, cx| {
5339 editor.focus(cx);
5340 editor.toggle_code_actions(
5341 &ToggleCodeActions {
5342 deployed_from_indicator: Some(row),
5343 },
5344 cx,
5345 );
5346 })),
5347 )
5348 } else {
5349 None
5350 }
5351 }
5352
5353 fn clear_tasks(&mut self) {
5354 self.tasks.clear()
5355 }
5356
5357 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5358 if self.tasks.insert(key, value).is_some() {
5359 // This case should hopefully be rare, but just in case...
5360 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5361 }
5362 }
5363
5364 fn render_run_indicator(
5365 &self,
5366 _style: &EditorStyle,
5367 is_active: bool,
5368 row: DisplayRow,
5369 cx: &mut ViewContext<Self>,
5370 ) -> IconButton {
5371 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5372 .shape(ui::IconButtonShape::Square)
5373 .icon_size(IconSize::XSmall)
5374 .icon_color(Color::Muted)
5375 .selected(is_active)
5376 .on_click(cx.listener(move |editor, _e, cx| {
5377 editor.focus(cx);
5378 editor.toggle_code_actions(
5379 &ToggleCodeActions {
5380 deployed_from_indicator: Some(row),
5381 },
5382 cx,
5383 );
5384 }))
5385 }
5386
5387 fn close_hunk_diff_button(
5388 &self,
5389 hunk: HoveredHunk,
5390 row: DisplayRow,
5391 cx: &mut ViewContext<Self>,
5392 ) -> IconButton {
5393 IconButton::new(
5394 ("close_hunk_diff_indicator", row.0 as usize),
5395 ui::IconName::Close,
5396 )
5397 .shape(ui::IconButtonShape::Square)
5398 .icon_size(IconSize::XSmall)
5399 .icon_color(Color::Muted)
5400 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5401 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5402 }
5403
5404 pub fn context_menu_visible(&self) -> bool {
5405 self.context_menu
5406 .read()
5407 .as_ref()
5408 .map_or(false, |menu| menu.visible())
5409 }
5410
5411 fn render_context_menu(
5412 &self,
5413 cursor_position: DisplayPoint,
5414 style: &EditorStyle,
5415 max_height: Pixels,
5416 cx: &mut ViewContext<Editor>,
5417 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5418 self.context_menu.read().as_ref().map(|menu| {
5419 menu.render(
5420 cursor_position,
5421 style,
5422 max_height,
5423 self.workspace.as_ref().map(|(w, _)| w.clone()),
5424 cx,
5425 )
5426 })
5427 }
5428
5429 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5430 cx.notify();
5431 self.completion_tasks.clear();
5432 let context_menu = self.context_menu.write().take();
5433 if context_menu.is_some() {
5434 self.update_visible_inline_completion(cx);
5435 }
5436 context_menu
5437 }
5438
5439 pub fn insert_snippet(
5440 &mut self,
5441 insertion_ranges: &[Range<usize>],
5442 snippet: Snippet,
5443 cx: &mut ViewContext<Self>,
5444 ) -> Result<()> {
5445 struct Tabstop<T> {
5446 is_end_tabstop: bool,
5447 ranges: Vec<Range<T>>,
5448 }
5449
5450 let tabstops = self.buffer.update(cx, |buffer, cx| {
5451 let snippet_text: Arc<str> = snippet.text.clone().into();
5452 buffer.edit(
5453 insertion_ranges
5454 .iter()
5455 .cloned()
5456 .map(|range| (range, snippet_text.clone())),
5457 Some(AutoindentMode::EachLine),
5458 cx,
5459 );
5460
5461 let snapshot = &*buffer.read(cx);
5462 let snippet = &snippet;
5463 snippet
5464 .tabstops
5465 .iter()
5466 .map(|tabstop| {
5467 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5468 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5469 });
5470 let mut tabstop_ranges = tabstop
5471 .iter()
5472 .flat_map(|tabstop_range| {
5473 let mut delta = 0_isize;
5474 insertion_ranges.iter().map(move |insertion_range| {
5475 let insertion_start = insertion_range.start as isize + delta;
5476 delta +=
5477 snippet.text.len() as isize - insertion_range.len() as isize;
5478
5479 let start = ((insertion_start + tabstop_range.start) as usize)
5480 .min(snapshot.len());
5481 let end = ((insertion_start + tabstop_range.end) as usize)
5482 .min(snapshot.len());
5483 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5484 })
5485 })
5486 .collect::<Vec<_>>();
5487 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5488
5489 Tabstop {
5490 is_end_tabstop,
5491 ranges: tabstop_ranges,
5492 }
5493 })
5494 .collect::<Vec<_>>()
5495 });
5496 if let Some(tabstop) = tabstops.first() {
5497 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5498 s.select_ranges(tabstop.ranges.iter().cloned());
5499 });
5500
5501 // If we're already at the last tabstop and it's at the end of the snippet,
5502 // we're done, we don't need to keep the state around.
5503 if !tabstop.is_end_tabstop {
5504 let ranges = tabstops
5505 .into_iter()
5506 .map(|tabstop| tabstop.ranges)
5507 .collect::<Vec<_>>();
5508 self.snippet_stack.push(SnippetState {
5509 active_index: 0,
5510 ranges,
5511 });
5512 }
5513
5514 // Check whether the just-entered snippet ends with an auto-closable bracket.
5515 if self.autoclose_regions.is_empty() {
5516 let snapshot = self.buffer.read(cx).snapshot(cx);
5517 for selection in &mut self.selections.all::<Point>(cx) {
5518 let selection_head = selection.head();
5519 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5520 continue;
5521 };
5522
5523 let mut bracket_pair = None;
5524 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5525 let prev_chars = snapshot
5526 .reversed_chars_at(selection_head)
5527 .collect::<String>();
5528 for (pair, enabled) in scope.brackets() {
5529 if enabled
5530 && pair.close
5531 && prev_chars.starts_with(pair.start.as_str())
5532 && next_chars.starts_with(pair.end.as_str())
5533 {
5534 bracket_pair = Some(pair.clone());
5535 break;
5536 }
5537 }
5538 if let Some(pair) = bracket_pair {
5539 let start = snapshot.anchor_after(selection_head);
5540 let end = snapshot.anchor_after(selection_head);
5541 self.autoclose_regions.push(AutocloseRegion {
5542 selection_id: selection.id,
5543 range: start..end,
5544 pair,
5545 });
5546 }
5547 }
5548 }
5549 }
5550 Ok(())
5551 }
5552
5553 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5554 self.move_to_snippet_tabstop(Bias::Right, cx)
5555 }
5556
5557 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5558 self.move_to_snippet_tabstop(Bias::Left, cx)
5559 }
5560
5561 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5562 if let Some(mut snippet) = self.snippet_stack.pop() {
5563 match bias {
5564 Bias::Left => {
5565 if snippet.active_index > 0 {
5566 snippet.active_index -= 1;
5567 } else {
5568 self.snippet_stack.push(snippet);
5569 return false;
5570 }
5571 }
5572 Bias::Right => {
5573 if snippet.active_index + 1 < snippet.ranges.len() {
5574 snippet.active_index += 1;
5575 } else {
5576 self.snippet_stack.push(snippet);
5577 return false;
5578 }
5579 }
5580 }
5581 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5582 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5583 s.select_anchor_ranges(current_ranges.iter().cloned())
5584 });
5585 // If snippet state is not at the last tabstop, push it back on the stack
5586 if snippet.active_index + 1 < snippet.ranges.len() {
5587 self.snippet_stack.push(snippet);
5588 }
5589 return true;
5590 }
5591 }
5592
5593 false
5594 }
5595
5596 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5597 self.transact(cx, |this, cx| {
5598 this.select_all(&SelectAll, cx);
5599 this.insert("", cx);
5600 });
5601 }
5602
5603 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5604 self.transact(cx, |this, cx| {
5605 this.select_autoclose_pair(cx);
5606 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5607 if !this.linked_edit_ranges.is_empty() {
5608 let selections = this.selections.all::<MultiBufferPoint>(cx);
5609 let snapshot = this.buffer.read(cx).snapshot(cx);
5610
5611 for selection in selections.iter() {
5612 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5613 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5614 if selection_start.buffer_id != selection_end.buffer_id {
5615 continue;
5616 }
5617 if let Some(ranges) =
5618 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5619 {
5620 for (buffer, entries) in ranges {
5621 linked_ranges.entry(buffer).or_default().extend(entries);
5622 }
5623 }
5624 }
5625 }
5626
5627 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5628 if !this.selections.line_mode {
5629 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5630 for selection in &mut selections {
5631 if selection.is_empty() {
5632 let old_head = selection.head();
5633 let mut new_head =
5634 movement::left(&display_map, old_head.to_display_point(&display_map))
5635 .to_point(&display_map);
5636 if let Some((buffer, line_buffer_range)) = display_map
5637 .buffer_snapshot
5638 .buffer_line_for_row(MultiBufferRow(old_head.row))
5639 {
5640 let indent_size =
5641 buffer.indent_size_for_line(line_buffer_range.start.row);
5642 let indent_len = match indent_size.kind {
5643 IndentKind::Space => {
5644 buffer.settings_at(line_buffer_range.start, cx).tab_size
5645 }
5646 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5647 };
5648 if old_head.column <= indent_size.len && old_head.column > 0 {
5649 let indent_len = indent_len.get();
5650 new_head = cmp::min(
5651 new_head,
5652 MultiBufferPoint::new(
5653 old_head.row,
5654 ((old_head.column - 1) / indent_len) * indent_len,
5655 ),
5656 );
5657 }
5658 }
5659
5660 selection.set_head(new_head, SelectionGoal::None);
5661 }
5662 }
5663 }
5664
5665 this.signature_help_state.set_backspace_pressed(true);
5666 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5667 this.insert("", cx);
5668 let empty_str: Arc<str> = Arc::from("");
5669 for (buffer, edits) in linked_ranges {
5670 let snapshot = buffer.read(cx).snapshot();
5671 use text::ToPoint as TP;
5672
5673 let edits = edits
5674 .into_iter()
5675 .map(|range| {
5676 let end_point = TP::to_point(&range.end, &snapshot);
5677 let mut start_point = TP::to_point(&range.start, &snapshot);
5678
5679 if end_point == start_point {
5680 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5681 .saturating_sub(1);
5682 start_point = TP::to_point(&offset, &snapshot);
5683 };
5684
5685 (start_point..end_point, empty_str.clone())
5686 })
5687 .sorted_by_key(|(range, _)| range.start)
5688 .collect::<Vec<_>>();
5689 buffer.update(cx, |this, cx| {
5690 this.edit(edits, None, cx);
5691 })
5692 }
5693 this.refresh_inline_completion(true, false, cx);
5694 linked_editing_ranges::refresh_linked_ranges(this, cx);
5695 });
5696 }
5697
5698 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5699 self.transact(cx, |this, cx| {
5700 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5701 let line_mode = s.line_mode;
5702 s.move_with(|map, selection| {
5703 if selection.is_empty() && !line_mode {
5704 let cursor = movement::right(map, selection.head());
5705 selection.end = cursor;
5706 selection.reversed = true;
5707 selection.goal = SelectionGoal::None;
5708 }
5709 })
5710 });
5711 this.insert("", cx);
5712 this.refresh_inline_completion(true, false, cx);
5713 });
5714 }
5715
5716 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5717 if self.move_to_prev_snippet_tabstop(cx) {
5718 return;
5719 }
5720
5721 self.outdent(&Outdent, cx);
5722 }
5723
5724 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5725 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5726 return;
5727 }
5728
5729 let mut selections = self.selections.all_adjusted(cx);
5730 let buffer = self.buffer.read(cx);
5731 let snapshot = buffer.snapshot(cx);
5732 let rows_iter = selections.iter().map(|s| s.head().row);
5733 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5734
5735 let mut edits = Vec::new();
5736 let mut prev_edited_row = 0;
5737 let mut row_delta = 0;
5738 for selection in &mut selections {
5739 if selection.start.row != prev_edited_row {
5740 row_delta = 0;
5741 }
5742 prev_edited_row = selection.end.row;
5743
5744 // If the selection is non-empty, then increase the indentation of the selected lines.
5745 if !selection.is_empty() {
5746 row_delta =
5747 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5748 continue;
5749 }
5750
5751 // If the selection is empty and the cursor is in the leading whitespace before the
5752 // suggested indentation, then auto-indent the line.
5753 let cursor = selection.head();
5754 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5755 if let Some(suggested_indent) =
5756 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5757 {
5758 if cursor.column < suggested_indent.len
5759 && cursor.column <= current_indent.len
5760 && current_indent.len <= suggested_indent.len
5761 {
5762 selection.start = Point::new(cursor.row, suggested_indent.len);
5763 selection.end = selection.start;
5764 if row_delta == 0 {
5765 edits.extend(Buffer::edit_for_indent_size_adjustment(
5766 cursor.row,
5767 current_indent,
5768 suggested_indent,
5769 ));
5770 row_delta = suggested_indent.len - current_indent.len;
5771 }
5772 continue;
5773 }
5774 }
5775
5776 // Otherwise, insert a hard or soft tab.
5777 let settings = buffer.settings_at(cursor, cx);
5778 let tab_size = if settings.hard_tabs {
5779 IndentSize::tab()
5780 } else {
5781 let tab_size = settings.tab_size.get();
5782 let char_column = snapshot
5783 .text_for_range(Point::new(cursor.row, 0)..cursor)
5784 .flat_map(str::chars)
5785 .count()
5786 + row_delta as usize;
5787 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5788 IndentSize::spaces(chars_to_next_tab_stop)
5789 };
5790 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5791 selection.end = selection.start;
5792 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5793 row_delta += tab_size.len;
5794 }
5795
5796 self.transact(cx, |this, cx| {
5797 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5798 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5799 this.refresh_inline_completion(true, false, cx);
5800 });
5801 }
5802
5803 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5804 if self.read_only(cx) {
5805 return;
5806 }
5807 let mut selections = self.selections.all::<Point>(cx);
5808 let mut prev_edited_row = 0;
5809 let mut row_delta = 0;
5810 let mut edits = Vec::new();
5811 let buffer = self.buffer.read(cx);
5812 let snapshot = buffer.snapshot(cx);
5813 for selection in &mut selections {
5814 if selection.start.row != prev_edited_row {
5815 row_delta = 0;
5816 }
5817 prev_edited_row = selection.end.row;
5818
5819 row_delta =
5820 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5821 }
5822
5823 self.transact(cx, |this, cx| {
5824 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5825 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5826 });
5827 }
5828
5829 fn indent_selection(
5830 buffer: &MultiBuffer,
5831 snapshot: &MultiBufferSnapshot,
5832 selection: &mut Selection<Point>,
5833 edits: &mut Vec<(Range<Point>, String)>,
5834 delta_for_start_row: u32,
5835 cx: &AppContext,
5836 ) -> u32 {
5837 let settings = buffer.settings_at(selection.start, cx);
5838 let tab_size = settings.tab_size.get();
5839 let indent_kind = if settings.hard_tabs {
5840 IndentKind::Tab
5841 } else {
5842 IndentKind::Space
5843 };
5844 let mut start_row = selection.start.row;
5845 let mut end_row = selection.end.row + 1;
5846
5847 // If a selection ends at the beginning of a line, don't indent
5848 // that last line.
5849 if selection.end.column == 0 && selection.end.row > selection.start.row {
5850 end_row -= 1;
5851 }
5852
5853 // Avoid re-indenting a row that has already been indented by a
5854 // previous selection, but still update this selection's column
5855 // to reflect that indentation.
5856 if delta_for_start_row > 0 {
5857 start_row += 1;
5858 selection.start.column += delta_for_start_row;
5859 if selection.end.row == selection.start.row {
5860 selection.end.column += delta_for_start_row;
5861 }
5862 }
5863
5864 let mut delta_for_end_row = 0;
5865 let has_multiple_rows = start_row + 1 != end_row;
5866 for row in start_row..end_row {
5867 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5868 let indent_delta = match (current_indent.kind, indent_kind) {
5869 (IndentKind::Space, IndentKind::Space) => {
5870 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5871 IndentSize::spaces(columns_to_next_tab_stop)
5872 }
5873 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5874 (_, IndentKind::Tab) => IndentSize::tab(),
5875 };
5876
5877 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5878 0
5879 } else {
5880 selection.start.column
5881 };
5882 let row_start = Point::new(row, start);
5883 edits.push((
5884 row_start..row_start,
5885 indent_delta.chars().collect::<String>(),
5886 ));
5887
5888 // Update this selection's endpoints to reflect the indentation.
5889 if row == selection.start.row {
5890 selection.start.column += indent_delta.len;
5891 }
5892 if row == selection.end.row {
5893 selection.end.column += indent_delta.len;
5894 delta_for_end_row = indent_delta.len;
5895 }
5896 }
5897
5898 if selection.start.row == selection.end.row {
5899 delta_for_start_row + delta_for_end_row
5900 } else {
5901 delta_for_end_row
5902 }
5903 }
5904
5905 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5906 if self.read_only(cx) {
5907 return;
5908 }
5909 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5910 let selections = self.selections.all::<Point>(cx);
5911 let mut deletion_ranges = Vec::new();
5912 let mut last_outdent = None;
5913 {
5914 let buffer = self.buffer.read(cx);
5915 let snapshot = buffer.snapshot(cx);
5916 for selection in &selections {
5917 let settings = buffer.settings_at(selection.start, cx);
5918 let tab_size = settings.tab_size.get();
5919 let mut rows = selection.spanned_rows(false, &display_map);
5920
5921 // Avoid re-outdenting a row that has already been outdented by a
5922 // previous selection.
5923 if let Some(last_row) = last_outdent {
5924 if last_row == rows.start {
5925 rows.start = rows.start.next_row();
5926 }
5927 }
5928 let has_multiple_rows = rows.len() > 1;
5929 for row in rows.iter_rows() {
5930 let indent_size = snapshot.indent_size_for_line(row);
5931 if indent_size.len > 0 {
5932 let deletion_len = match indent_size.kind {
5933 IndentKind::Space => {
5934 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5935 if columns_to_prev_tab_stop == 0 {
5936 tab_size
5937 } else {
5938 columns_to_prev_tab_stop
5939 }
5940 }
5941 IndentKind::Tab => 1,
5942 };
5943 let start = if has_multiple_rows
5944 || deletion_len > selection.start.column
5945 || indent_size.len < selection.start.column
5946 {
5947 0
5948 } else {
5949 selection.start.column - deletion_len
5950 };
5951 deletion_ranges.push(
5952 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5953 );
5954 last_outdent = Some(row);
5955 }
5956 }
5957 }
5958 }
5959
5960 self.transact(cx, |this, cx| {
5961 this.buffer.update(cx, |buffer, cx| {
5962 let empty_str: Arc<str> = Arc::default();
5963 buffer.edit(
5964 deletion_ranges
5965 .into_iter()
5966 .map(|range| (range, empty_str.clone())),
5967 None,
5968 cx,
5969 );
5970 });
5971 let selections = this.selections.all::<usize>(cx);
5972 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5973 });
5974 }
5975
5976 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5978 let selections = self.selections.all::<Point>(cx);
5979
5980 let mut new_cursors = Vec::new();
5981 let mut edit_ranges = Vec::new();
5982 let mut selections = selections.iter().peekable();
5983 while let Some(selection) = selections.next() {
5984 let mut rows = selection.spanned_rows(false, &display_map);
5985 let goal_display_column = selection.head().to_display_point(&display_map).column();
5986
5987 // Accumulate contiguous regions of rows that we want to delete.
5988 while let Some(next_selection) = selections.peek() {
5989 let next_rows = next_selection.spanned_rows(false, &display_map);
5990 if next_rows.start <= rows.end {
5991 rows.end = next_rows.end;
5992 selections.next().unwrap();
5993 } else {
5994 break;
5995 }
5996 }
5997
5998 let buffer = &display_map.buffer_snapshot;
5999 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6000 let edit_end;
6001 let cursor_buffer_row;
6002 if buffer.max_point().row >= rows.end.0 {
6003 // If there's a line after the range, delete the \n from the end of the row range
6004 // and position the cursor on the next line.
6005 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6006 cursor_buffer_row = rows.end;
6007 } else {
6008 // If there isn't a line after the range, delete the \n from the line before the
6009 // start of the row range and position the cursor there.
6010 edit_start = edit_start.saturating_sub(1);
6011 edit_end = buffer.len();
6012 cursor_buffer_row = rows.start.previous_row();
6013 }
6014
6015 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6016 *cursor.column_mut() =
6017 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6018
6019 new_cursors.push((
6020 selection.id,
6021 buffer.anchor_after(cursor.to_point(&display_map)),
6022 ));
6023 edit_ranges.push(edit_start..edit_end);
6024 }
6025
6026 self.transact(cx, |this, cx| {
6027 let buffer = this.buffer.update(cx, |buffer, cx| {
6028 let empty_str: Arc<str> = Arc::default();
6029 buffer.edit(
6030 edit_ranges
6031 .into_iter()
6032 .map(|range| (range, empty_str.clone())),
6033 None,
6034 cx,
6035 );
6036 buffer.snapshot(cx)
6037 });
6038 let new_selections = new_cursors
6039 .into_iter()
6040 .map(|(id, cursor)| {
6041 let cursor = cursor.to_point(&buffer);
6042 Selection {
6043 id,
6044 start: cursor,
6045 end: cursor,
6046 reversed: false,
6047 goal: SelectionGoal::None,
6048 }
6049 })
6050 .collect();
6051
6052 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6053 s.select(new_selections);
6054 });
6055 });
6056 }
6057
6058 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6059 if self.read_only(cx) {
6060 return;
6061 }
6062 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6063 for selection in self.selections.all::<Point>(cx) {
6064 let start = MultiBufferRow(selection.start.row);
6065 let end = if selection.start.row == selection.end.row {
6066 MultiBufferRow(selection.start.row + 1)
6067 } else {
6068 MultiBufferRow(selection.end.row)
6069 };
6070
6071 if let Some(last_row_range) = row_ranges.last_mut() {
6072 if start <= last_row_range.end {
6073 last_row_range.end = end;
6074 continue;
6075 }
6076 }
6077 row_ranges.push(start..end);
6078 }
6079
6080 let snapshot = self.buffer.read(cx).snapshot(cx);
6081 let mut cursor_positions = Vec::new();
6082 for row_range in &row_ranges {
6083 let anchor = snapshot.anchor_before(Point::new(
6084 row_range.end.previous_row().0,
6085 snapshot.line_len(row_range.end.previous_row()),
6086 ));
6087 cursor_positions.push(anchor..anchor);
6088 }
6089
6090 self.transact(cx, |this, cx| {
6091 for row_range in row_ranges.into_iter().rev() {
6092 for row in row_range.iter_rows().rev() {
6093 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6094 let next_line_row = row.next_row();
6095 let indent = snapshot.indent_size_for_line(next_line_row);
6096 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6097
6098 let replace = if snapshot.line_len(next_line_row) > indent.len {
6099 " "
6100 } else {
6101 ""
6102 };
6103
6104 this.buffer.update(cx, |buffer, cx| {
6105 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6106 });
6107 }
6108 }
6109
6110 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6111 s.select_anchor_ranges(cursor_positions)
6112 });
6113 });
6114 }
6115
6116 pub fn sort_lines_case_sensitive(
6117 &mut self,
6118 _: &SortLinesCaseSensitive,
6119 cx: &mut ViewContext<Self>,
6120 ) {
6121 self.manipulate_lines(cx, |lines| lines.sort())
6122 }
6123
6124 pub fn sort_lines_case_insensitive(
6125 &mut self,
6126 _: &SortLinesCaseInsensitive,
6127 cx: &mut ViewContext<Self>,
6128 ) {
6129 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6130 }
6131
6132 pub fn unique_lines_case_insensitive(
6133 &mut self,
6134 _: &UniqueLinesCaseInsensitive,
6135 cx: &mut ViewContext<Self>,
6136 ) {
6137 self.manipulate_lines(cx, |lines| {
6138 let mut seen = HashSet::default();
6139 lines.retain(|line| seen.insert(line.to_lowercase()));
6140 })
6141 }
6142
6143 pub fn unique_lines_case_sensitive(
6144 &mut self,
6145 _: &UniqueLinesCaseSensitive,
6146 cx: &mut ViewContext<Self>,
6147 ) {
6148 self.manipulate_lines(cx, |lines| {
6149 let mut seen = HashSet::default();
6150 lines.retain(|line| seen.insert(*line));
6151 })
6152 }
6153
6154 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6155 let mut revert_changes = HashMap::default();
6156 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6157 for hunk in hunks_for_rows(
6158 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6159 &multi_buffer_snapshot,
6160 ) {
6161 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6162 }
6163 if !revert_changes.is_empty() {
6164 self.transact(cx, |editor, cx| {
6165 editor.revert(revert_changes, cx);
6166 });
6167 }
6168 }
6169
6170 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6171 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6172 if !revert_changes.is_empty() {
6173 self.transact(cx, |editor, cx| {
6174 editor.revert(revert_changes, cx);
6175 });
6176 }
6177 }
6178
6179 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6180 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6181 let project_path = buffer.read(cx).project_path(cx)?;
6182 let project = self.project.as_ref()?.read(cx);
6183 let entry = project.entry_for_path(&project_path, cx)?;
6184 let abs_path = project.absolute_path(&project_path, cx)?;
6185 let parent = if entry.is_symlink {
6186 abs_path.canonicalize().ok()?
6187 } else {
6188 abs_path
6189 }
6190 .parent()?
6191 .to_path_buf();
6192 Some(parent)
6193 }) {
6194 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6195 }
6196 }
6197
6198 fn gather_revert_changes(
6199 &mut self,
6200 selections: &[Selection<Anchor>],
6201 cx: &mut ViewContext<'_, Editor>,
6202 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6203 let mut revert_changes = HashMap::default();
6204 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6205 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6206 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6207 }
6208 revert_changes
6209 }
6210
6211 pub fn prepare_revert_change(
6212 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6213 multi_buffer: &Model<MultiBuffer>,
6214 hunk: &MultiBufferDiffHunk,
6215 cx: &AppContext,
6216 ) -> Option<()> {
6217 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6218 let buffer = buffer.read(cx);
6219 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6220 let buffer_snapshot = buffer.snapshot();
6221 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6222 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6223 probe
6224 .0
6225 .start
6226 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6227 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6228 }) {
6229 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6230 Some(())
6231 } else {
6232 None
6233 }
6234 }
6235
6236 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6237 self.manipulate_lines(cx, |lines| lines.reverse())
6238 }
6239
6240 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6241 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6242 }
6243
6244 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6245 where
6246 Fn: FnMut(&mut Vec<&str>),
6247 {
6248 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6249 let buffer = self.buffer.read(cx).snapshot(cx);
6250
6251 let mut edits = Vec::new();
6252
6253 let selections = self.selections.all::<Point>(cx);
6254 let mut selections = selections.iter().peekable();
6255 let mut contiguous_row_selections = Vec::new();
6256 let mut new_selections = Vec::new();
6257 let mut added_lines = 0;
6258 let mut removed_lines = 0;
6259
6260 while let Some(selection) = selections.next() {
6261 let (start_row, end_row) = consume_contiguous_rows(
6262 &mut contiguous_row_selections,
6263 selection,
6264 &display_map,
6265 &mut selections,
6266 );
6267
6268 let start_point = Point::new(start_row.0, 0);
6269 let end_point = Point::new(
6270 end_row.previous_row().0,
6271 buffer.line_len(end_row.previous_row()),
6272 );
6273 let text = buffer
6274 .text_for_range(start_point..end_point)
6275 .collect::<String>();
6276
6277 let mut lines = text.split('\n').collect_vec();
6278
6279 let lines_before = lines.len();
6280 callback(&mut lines);
6281 let lines_after = lines.len();
6282
6283 edits.push((start_point..end_point, lines.join("\n")));
6284
6285 // Selections must change based on added and removed line count
6286 let start_row =
6287 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6288 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6289 new_selections.push(Selection {
6290 id: selection.id,
6291 start: start_row,
6292 end: end_row,
6293 goal: SelectionGoal::None,
6294 reversed: selection.reversed,
6295 });
6296
6297 if lines_after > lines_before {
6298 added_lines += lines_after - lines_before;
6299 } else if lines_before > lines_after {
6300 removed_lines += lines_before - lines_after;
6301 }
6302 }
6303
6304 self.transact(cx, |this, cx| {
6305 let buffer = this.buffer.update(cx, |buffer, cx| {
6306 buffer.edit(edits, None, cx);
6307 buffer.snapshot(cx)
6308 });
6309
6310 // Recalculate offsets on newly edited buffer
6311 let new_selections = new_selections
6312 .iter()
6313 .map(|s| {
6314 let start_point = Point::new(s.start.0, 0);
6315 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6316 Selection {
6317 id: s.id,
6318 start: buffer.point_to_offset(start_point),
6319 end: buffer.point_to_offset(end_point),
6320 goal: s.goal,
6321 reversed: s.reversed,
6322 }
6323 })
6324 .collect();
6325
6326 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6327 s.select(new_selections);
6328 });
6329
6330 this.request_autoscroll(Autoscroll::fit(), cx);
6331 });
6332 }
6333
6334 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6335 self.manipulate_text(cx, |text| text.to_uppercase())
6336 }
6337
6338 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6339 self.manipulate_text(cx, |text| text.to_lowercase())
6340 }
6341
6342 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6343 self.manipulate_text(cx, |text| {
6344 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6345 // https://github.com/rutrum/convert-case/issues/16
6346 text.split('\n')
6347 .map(|line| line.to_case(Case::Title))
6348 .join("\n")
6349 })
6350 }
6351
6352 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6353 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6354 }
6355
6356 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6357 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6358 }
6359
6360 pub fn convert_to_upper_camel_case(
6361 &mut self,
6362 _: &ConvertToUpperCamelCase,
6363 cx: &mut ViewContext<Self>,
6364 ) {
6365 self.manipulate_text(cx, |text| {
6366 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6367 // https://github.com/rutrum/convert-case/issues/16
6368 text.split('\n')
6369 .map(|line| line.to_case(Case::UpperCamel))
6370 .join("\n")
6371 })
6372 }
6373
6374 pub fn convert_to_lower_camel_case(
6375 &mut self,
6376 _: &ConvertToLowerCamelCase,
6377 cx: &mut ViewContext<Self>,
6378 ) {
6379 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6380 }
6381
6382 pub fn convert_to_opposite_case(
6383 &mut self,
6384 _: &ConvertToOppositeCase,
6385 cx: &mut ViewContext<Self>,
6386 ) {
6387 self.manipulate_text(cx, |text| {
6388 text.chars()
6389 .fold(String::with_capacity(text.len()), |mut t, c| {
6390 if c.is_uppercase() {
6391 t.extend(c.to_lowercase());
6392 } else {
6393 t.extend(c.to_uppercase());
6394 }
6395 t
6396 })
6397 })
6398 }
6399
6400 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6401 where
6402 Fn: FnMut(&str) -> String,
6403 {
6404 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6405 let buffer = self.buffer.read(cx).snapshot(cx);
6406
6407 let mut new_selections = Vec::new();
6408 let mut edits = Vec::new();
6409 let mut selection_adjustment = 0i32;
6410
6411 for selection in self.selections.all::<usize>(cx) {
6412 let selection_is_empty = selection.is_empty();
6413
6414 let (start, end) = if selection_is_empty {
6415 let word_range = movement::surrounding_word(
6416 &display_map,
6417 selection.start.to_display_point(&display_map),
6418 );
6419 let start = word_range.start.to_offset(&display_map, Bias::Left);
6420 let end = word_range.end.to_offset(&display_map, Bias::Left);
6421 (start, end)
6422 } else {
6423 (selection.start, selection.end)
6424 };
6425
6426 let text = buffer.text_for_range(start..end).collect::<String>();
6427 let old_length = text.len() as i32;
6428 let text = callback(&text);
6429
6430 new_selections.push(Selection {
6431 start: (start as i32 - selection_adjustment) as usize,
6432 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6433 goal: SelectionGoal::None,
6434 ..selection
6435 });
6436
6437 selection_adjustment += old_length - text.len() as i32;
6438
6439 edits.push((start..end, text));
6440 }
6441
6442 self.transact(cx, |this, cx| {
6443 this.buffer.update(cx, |buffer, cx| {
6444 buffer.edit(edits, None, cx);
6445 });
6446
6447 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6448 s.select(new_selections);
6449 });
6450
6451 this.request_autoscroll(Autoscroll::fit(), cx);
6452 });
6453 }
6454
6455 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6457 let buffer = &display_map.buffer_snapshot;
6458 let selections = self.selections.all::<Point>(cx);
6459
6460 let mut edits = Vec::new();
6461 let mut selections_iter = selections.iter().peekable();
6462 while let Some(selection) = selections_iter.next() {
6463 // Avoid duplicating the same lines twice.
6464 let mut rows = selection.spanned_rows(false, &display_map);
6465
6466 while let Some(next_selection) = selections_iter.peek() {
6467 let next_rows = next_selection.spanned_rows(false, &display_map);
6468 if next_rows.start < rows.end {
6469 rows.end = next_rows.end;
6470 selections_iter.next().unwrap();
6471 } else {
6472 break;
6473 }
6474 }
6475
6476 // Copy the text from the selected row region and splice it either at the start
6477 // or end of the region.
6478 let start = Point::new(rows.start.0, 0);
6479 let end = Point::new(
6480 rows.end.previous_row().0,
6481 buffer.line_len(rows.end.previous_row()),
6482 );
6483 let text = buffer
6484 .text_for_range(start..end)
6485 .chain(Some("\n"))
6486 .collect::<String>();
6487 let insert_location = if upwards {
6488 Point::new(rows.end.0, 0)
6489 } else {
6490 start
6491 };
6492 edits.push((insert_location..insert_location, text));
6493 }
6494
6495 self.transact(cx, |this, cx| {
6496 this.buffer.update(cx, |buffer, cx| {
6497 buffer.edit(edits, None, cx);
6498 });
6499
6500 this.request_autoscroll(Autoscroll::fit(), cx);
6501 });
6502 }
6503
6504 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6505 self.duplicate_line(true, cx);
6506 }
6507
6508 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6509 self.duplicate_line(false, cx);
6510 }
6511
6512 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6514 let buffer = self.buffer.read(cx).snapshot(cx);
6515
6516 let mut edits = Vec::new();
6517 let mut unfold_ranges = Vec::new();
6518 let mut refold_ranges = Vec::new();
6519
6520 let selections = self.selections.all::<Point>(cx);
6521 let mut selections = selections.iter().peekable();
6522 let mut contiguous_row_selections = Vec::new();
6523 let mut new_selections = Vec::new();
6524
6525 while let Some(selection) = selections.next() {
6526 // Find all the selections that span a contiguous row range
6527 let (start_row, end_row) = consume_contiguous_rows(
6528 &mut contiguous_row_selections,
6529 selection,
6530 &display_map,
6531 &mut selections,
6532 );
6533
6534 // Move the text spanned by the row range to be before the line preceding the row range
6535 if start_row.0 > 0 {
6536 let range_to_move = Point::new(
6537 start_row.previous_row().0,
6538 buffer.line_len(start_row.previous_row()),
6539 )
6540 ..Point::new(
6541 end_row.previous_row().0,
6542 buffer.line_len(end_row.previous_row()),
6543 );
6544 let insertion_point = display_map
6545 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6546 .0;
6547
6548 // Don't move lines across excerpts
6549 if buffer
6550 .excerpt_boundaries_in_range((
6551 Bound::Excluded(insertion_point),
6552 Bound::Included(range_to_move.end),
6553 ))
6554 .next()
6555 .is_none()
6556 {
6557 let text = buffer
6558 .text_for_range(range_to_move.clone())
6559 .flat_map(|s| s.chars())
6560 .skip(1)
6561 .chain(['\n'])
6562 .collect::<String>();
6563
6564 edits.push((
6565 buffer.anchor_after(range_to_move.start)
6566 ..buffer.anchor_before(range_to_move.end),
6567 String::new(),
6568 ));
6569 let insertion_anchor = buffer.anchor_after(insertion_point);
6570 edits.push((insertion_anchor..insertion_anchor, text));
6571
6572 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6573
6574 // Move selections up
6575 new_selections.extend(contiguous_row_selections.drain(..).map(
6576 |mut selection| {
6577 selection.start.row -= row_delta;
6578 selection.end.row -= row_delta;
6579 selection
6580 },
6581 ));
6582
6583 // Move folds up
6584 unfold_ranges.push(range_to_move.clone());
6585 for fold in display_map.folds_in_range(
6586 buffer.anchor_before(range_to_move.start)
6587 ..buffer.anchor_after(range_to_move.end),
6588 ) {
6589 let mut start = fold.range.start.to_point(&buffer);
6590 let mut end = fold.range.end.to_point(&buffer);
6591 start.row -= row_delta;
6592 end.row -= row_delta;
6593 refold_ranges.push((start..end, fold.placeholder.clone()));
6594 }
6595 }
6596 }
6597
6598 // If we didn't move line(s), preserve the existing selections
6599 new_selections.append(&mut contiguous_row_selections);
6600 }
6601
6602 self.transact(cx, |this, cx| {
6603 this.unfold_ranges(unfold_ranges, true, true, cx);
6604 this.buffer.update(cx, |buffer, cx| {
6605 for (range, text) in edits {
6606 buffer.edit([(range, text)], None, cx);
6607 }
6608 });
6609 this.fold_ranges(refold_ranges, true, cx);
6610 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6611 s.select(new_selections);
6612 })
6613 });
6614 }
6615
6616 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6617 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6618 let buffer = self.buffer.read(cx).snapshot(cx);
6619
6620 let mut edits = Vec::new();
6621 let mut unfold_ranges = Vec::new();
6622 let mut refold_ranges = Vec::new();
6623
6624 let selections = self.selections.all::<Point>(cx);
6625 let mut selections = selections.iter().peekable();
6626 let mut contiguous_row_selections = Vec::new();
6627 let mut new_selections = Vec::new();
6628
6629 while let Some(selection) = selections.next() {
6630 // Find all the selections that span a contiguous row range
6631 let (start_row, end_row) = consume_contiguous_rows(
6632 &mut contiguous_row_selections,
6633 selection,
6634 &display_map,
6635 &mut selections,
6636 );
6637
6638 // Move the text spanned by the row range to be after the last line of the row range
6639 if end_row.0 <= buffer.max_point().row {
6640 let range_to_move =
6641 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6642 let insertion_point = display_map
6643 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6644 .0;
6645
6646 // Don't move lines across excerpt boundaries
6647 if buffer
6648 .excerpt_boundaries_in_range((
6649 Bound::Excluded(range_to_move.start),
6650 Bound::Included(insertion_point),
6651 ))
6652 .next()
6653 .is_none()
6654 {
6655 let mut text = String::from("\n");
6656 text.extend(buffer.text_for_range(range_to_move.clone()));
6657 text.pop(); // Drop trailing newline
6658 edits.push((
6659 buffer.anchor_after(range_to_move.start)
6660 ..buffer.anchor_before(range_to_move.end),
6661 String::new(),
6662 ));
6663 let insertion_anchor = buffer.anchor_after(insertion_point);
6664 edits.push((insertion_anchor..insertion_anchor, text));
6665
6666 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6667
6668 // Move selections down
6669 new_selections.extend(contiguous_row_selections.drain(..).map(
6670 |mut selection| {
6671 selection.start.row += row_delta;
6672 selection.end.row += row_delta;
6673 selection
6674 },
6675 ));
6676
6677 // Move folds down
6678 unfold_ranges.push(range_to_move.clone());
6679 for fold in display_map.folds_in_range(
6680 buffer.anchor_before(range_to_move.start)
6681 ..buffer.anchor_after(range_to_move.end),
6682 ) {
6683 let mut start = fold.range.start.to_point(&buffer);
6684 let mut end = fold.range.end.to_point(&buffer);
6685 start.row += row_delta;
6686 end.row += row_delta;
6687 refold_ranges.push((start..end, fold.placeholder.clone()));
6688 }
6689 }
6690 }
6691
6692 // If we didn't move line(s), preserve the existing selections
6693 new_selections.append(&mut contiguous_row_selections);
6694 }
6695
6696 self.transact(cx, |this, cx| {
6697 this.unfold_ranges(unfold_ranges, true, true, cx);
6698 this.buffer.update(cx, |buffer, cx| {
6699 for (range, text) in edits {
6700 buffer.edit([(range, text)], None, cx);
6701 }
6702 });
6703 this.fold_ranges(refold_ranges, true, cx);
6704 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6705 });
6706 }
6707
6708 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6709 let text_layout_details = &self.text_layout_details(cx);
6710 self.transact(cx, |this, cx| {
6711 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6712 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6713 let line_mode = s.line_mode;
6714 s.move_with(|display_map, selection| {
6715 if !selection.is_empty() || line_mode {
6716 return;
6717 }
6718
6719 let mut head = selection.head();
6720 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6721 if head.column() == display_map.line_len(head.row()) {
6722 transpose_offset = display_map
6723 .buffer_snapshot
6724 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6725 }
6726
6727 if transpose_offset == 0 {
6728 return;
6729 }
6730
6731 *head.column_mut() += 1;
6732 head = display_map.clip_point(head, Bias::Right);
6733 let goal = SelectionGoal::HorizontalPosition(
6734 display_map
6735 .x_for_display_point(head, text_layout_details)
6736 .into(),
6737 );
6738 selection.collapse_to(head, goal);
6739
6740 let transpose_start = display_map
6741 .buffer_snapshot
6742 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6743 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6744 let transpose_end = display_map
6745 .buffer_snapshot
6746 .clip_offset(transpose_offset + 1, Bias::Right);
6747 if let Some(ch) =
6748 display_map.buffer_snapshot.chars_at(transpose_start).next()
6749 {
6750 edits.push((transpose_start..transpose_offset, String::new()));
6751 edits.push((transpose_end..transpose_end, ch.to_string()));
6752 }
6753 }
6754 });
6755 edits
6756 });
6757 this.buffer
6758 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6759 let selections = this.selections.all::<usize>(cx);
6760 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6761 s.select(selections);
6762 });
6763 });
6764 }
6765
6766 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6767 self.rewrap_impl(true, cx)
6768 }
6769
6770 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6771 let buffer = self.buffer.read(cx).snapshot(cx);
6772 let selections = self.selections.all::<Point>(cx);
6773 let mut selections = selections.iter().peekable();
6774
6775 let mut edits = Vec::new();
6776 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6777
6778 while let Some(selection) = selections.next() {
6779 let mut start_row = selection.start.row;
6780 let mut end_row = selection.end.row;
6781
6782 // Skip selections that overlap with a range that has already been rewrapped.
6783 let selection_range = start_row..end_row;
6784 if rewrapped_row_ranges
6785 .iter()
6786 .any(|range| range.overlaps(&selection_range))
6787 {
6788 continue;
6789 }
6790
6791 let mut should_rewrap = !only_text;
6792
6793 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6794 match language_scope.language_name().0.as_ref() {
6795 "Markdown" | "Plain Text" => {
6796 should_rewrap = true;
6797 }
6798 _ => {}
6799 }
6800 }
6801
6802 // Since not all lines in the selection may be at the same indent
6803 // level, choose the indent size that is the most common between all
6804 // of the lines.
6805 //
6806 // If there is a tie, we use the deepest indent.
6807 let (indent_size, indent_end) = {
6808 let mut indent_size_occurrences = HashMap::default();
6809 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6810
6811 for row in start_row..=end_row {
6812 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6813 rows_by_indent_size.entry(indent).or_default().push(row);
6814 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6815 }
6816
6817 let indent_size = indent_size_occurrences
6818 .into_iter()
6819 .max_by_key(|(indent, count)| (*count, indent.len))
6820 .map(|(indent, _)| indent)
6821 .unwrap_or_default();
6822 let row = rows_by_indent_size[&indent_size][0];
6823 let indent_end = Point::new(row, indent_size.len);
6824
6825 (indent_size, indent_end)
6826 };
6827
6828 let mut line_prefix = indent_size.chars().collect::<String>();
6829
6830 if let Some(comment_prefix) =
6831 buffer
6832 .language_scope_at(selection.head())
6833 .and_then(|language| {
6834 language
6835 .line_comment_prefixes()
6836 .iter()
6837 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6838 .cloned()
6839 })
6840 {
6841 line_prefix.push_str(&comment_prefix);
6842 should_rewrap = true;
6843 }
6844
6845 if selection.is_empty() {
6846 'expand_upwards: while start_row > 0 {
6847 let prev_row = start_row - 1;
6848 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6849 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6850 {
6851 start_row = prev_row;
6852 } else {
6853 break 'expand_upwards;
6854 }
6855 }
6856
6857 'expand_downwards: while end_row < buffer.max_point().row {
6858 let next_row = end_row + 1;
6859 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6860 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6861 {
6862 end_row = next_row;
6863 } else {
6864 break 'expand_downwards;
6865 }
6866 }
6867 }
6868
6869 if !should_rewrap {
6870 continue;
6871 }
6872
6873 let start = Point::new(start_row, 0);
6874 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6875 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6876 let Some(lines_without_prefixes) = selection_text
6877 .lines()
6878 .map(|line| {
6879 line.strip_prefix(&line_prefix)
6880 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6881 .ok_or_else(|| {
6882 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6883 })
6884 })
6885 .collect::<Result<Vec<_>, _>>()
6886 .log_err()
6887 else {
6888 continue;
6889 };
6890
6891 let unwrapped_text = lines_without_prefixes.join(" ");
6892 let wrap_column = buffer
6893 .settings_at(Point::new(start_row, 0), cx)
6894 .preferred_line_length as usize;
6895 let mut wrapped_text = String::new();
6896 let mut current_line = line_prefix.clone();
6897 for word in unwrapped_text.split_whitespace() {
6898 if current_line.len() + word.len() >= wrap_column {
6899 wrapped_text.push_str(¤t_line);
6900 wrapped_text.push('\n');
6901 current_line.truncate(line_prefix.len());
6902 }
6903
6904 if current_line.len() > line_prefix.len() {
6905 current_line.push(' ');
6906 }
6907
6908 current_line.push_str(word);
6909 }
6910
6911 if !current_line.is_empty() {
6912 wrapped_text.push_str(¤t_line);
6913 }
6914
6915 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6916 let mut offset = start.to_offset(&buffer);
6917 let mut moved_since_edit = true;
6918
6919 for change in diff.iter_all_changes() {
6920 let value = change.value();
6921 match change.tag() {
6922 ChangeTag::Equal => {
6923 offset += value.len();
6924 moved_since_edit = true;
6925 }
6926 ChangeTag::Delete => {
6927 let start = buffer.anchor_after(offset);
6928 let end = buffer.anchor_before(offset + value.len());
6929
6930 if moved_since_edit {
6931 edits.push((start..end, String::new()));
6932 } else {
6933 edits.last_mut().unwrap().0.end = end;
6934 }
6935
6936 offset += value.len();
6937 moved_since_edit = false;
6938 }
6939 ChangeTag::Insert => {
6940 if moved_since_edit {
6941 let anchor = buffer.anchor_after(offset);
6942 edits.push((anchor..anchor, value.to_string()));
6943 } else {
6944 edits.last_mut().unwrap().1.push_str(value);
6945 }
6946
6947 moved_since_edit = false;
6948 }
6949 }
6950 }
6951
6952 rewrapped_row_ranges.push(start_row..=end_row);
6953 }
6954
6955 self.buffer
6956 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6957 }
6958
6959 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6960 let mut text = String::new();
6961 let buffer = self.buffer.read(cx).snapshot(cx);
6962 let mut selections = self.selections.all::<Point>(cx);
6963 let mut clipboard_selections = Vec::with_capacity(selections.len());
6964 {
6965 let max_point = buffer.max_point();
6966 let mut is_first = true;
6967 for selection in &mut selections {
6968 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6969 if is_entire_line {
6970 selection.start = Point::new(selection.start.row, 0);
6971 if !selection.is_empty() && selection.end.column == 0 {
6972 selection.end = cmp::min(max_point, selection.end);
6973 } else {
6974 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6975 }
6976 selection.goal = SelectionGoal::None;
6977 }
6978 if is_first {
6979 is_first = false;
6980 } else {
6981 text += "\n";
6982 }
6983 let mut len = 0;
6984 for chunk in buffer.text_for_range(selection.start..selection.end) {
6985 text.push_str(chunk);
6986 len += chunk.len();
6987 }
6988 clipboard_selections.push(ClipboardSelection {
6989 len,
6990 is_entire_line,
6991 first_line_indent: buffer
6992 .indent_size_for_line(MultiBufferRow(selection.start.row))
6993 .len,
6994 });
6995 }
6996 }
6997
6998 self.transact(cx, |this, cx| {
6999 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7000 s.select(selections);
7001 });
7002 this.insert("", cx);
7003 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7004 text,
7005 clipboard_selections,
7006 ));
7007 });
7008 }
7009
7010 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7011 let selections = self.selections.all::<Point>(cx);
7012 let buffer = self.buffer.read(cx).read(cx);
7013 let mut text = String::new();
7014
7015 let mut clipboard_selections = Vec::with_capacity(selections.len());
7016 {
7017 let max_point = buffer.max_point();
7018 let mut is_first = true;
7019 for selection in selections.iter() {
7020 let mut start = selection.start;
7021 let mut end = selection.end;
7022 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7023 if is_entire_line {
7024 start = Point::new(start.row, 0);
7025 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7026 }
7027 if is_first {
7028 is_first = false;
7029 } else {
7030 text += "\n";
7031 }
7032 let mut len = 0;
7033 for chunk in buffer.text_for_range(start..end) {
7034 text.push_str(chunk);
7035 len += chunk.len();
7036 }
7037 clipboard_selections.push(ClipboardSelection {
7038 len,
7039 is_entire_line,
7040 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7041 });
7042 }
7043 }
7044
7045 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7046 text,
7047 clipboard_selections,
7048 ));
7049 }
7050
7051 pub fn do_paste(
7052 &mut self,
7053 text: &String,
7054 clipboard_selections: Option<Vec<ClipboardSelection>>,
7055 handle_entire_lines: bool,
7056 cx: &mut ViewContext<Self>,
7057 ) {
7058 if self.read_only(cx) {
7059 return;
7060 }
7061
7062 let clipboard_text = Cow::Borrowed(text);
7063
7064 self.transact(cx, |this, cx| {
7065 if let Some(mut clipboard_selections) = clipboard_selections {
7066 let old_selections = this.selections.all::<usize>(cx);
7067 let all_selections_were_entire_line =
7068 clipboard_selections.iter().all(|s| s.is_entire_line);
7069 let first_selection_indent_column =
7070 clipboard_selections.first().map(|s| s.first_line_indent);
7071 if clipboard_selections.len() != old_selections.len() {
7072 clipboard_selections.drain(..);
7073 }
7074
7075 this.buffer.update(cx, |buffer, cx| {
7076 let snapshot = buffer.read(cx);
7077 let mut start_offset = 0;
7078 let mut edits = Vec::new();
7079 let mut original_indent_columns = Vec::new();
7080 for (ix, selection) in old_selections.iter().enumerate() {
7081 let to_insert;
7082 let entire_line;
7083 let original_indent_column;
7084 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7085 let end_offset = start_offset + clipboard_selection.len;
7086 to_insert = &clipboard_text[start_offset..end_offset];
7087 entire_line = clipboard_selection.is_entire_line;
7088 start_offset = end_offset + 1;
7089 original_indent_column = Some(clipboard_selection.first_line_indent);
7090 } else {
7091 to_insert = clipboard_text.as_str();
7092 entire_line = all_selections_were_entire_line;
7093 original_indent_column = first_selection_indent_column
7094 }
7095
7096 // If the corresponding selection was empty when this slice of the
7097 // clipboard text was written, then the entire line containing the
7098 // selection was copied. If this selection is also currently empty,
7099 // then paste the line before the current line of the buffer.
7100 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7101 let column = selection.start.to_point(&snapshot).column as usize;
7102 let line_start = selection.start - column;
7103 line_start..line_start
7104 } else {
7105 selection.range()
7106 };
7107
7108 edits.push((range, to_insert));
7109 original_indent_columns.extend(original_indent_column);
7110 }
7111 drop(snapshot);
7112
7113 buffer.edit(
7114 edits,
7115 Some(AutoindentMode::Block {
7116 original_indent_columns,
7117 }),
7118 cx,
7119 );
7120 });
7121
7122 let selections = this.selections.all::<usize>(cx);
7123 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7124 } else {
7125 this.insert(&clipboard_text, cx);
7126 }
7127 });
7128 }
7129
7130 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7131 if let Some(item) = cx.read_from_clipboard() {
7132 let entries = item.entries();
7133
7134 match entries.first() {
7135 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7136 // of all the pasted entries.
7137 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7138 .do_paste(
7139 clipboard_string.text(),
7140 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7141 true,
7142 cx,
7143 ),
7144 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7145 }
7146 }
7147 }
7148
7149 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7150 if self.read_only(cx) {
7151 return;
7152 }
7153
7154 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7155 if let Some((selections, _)) =
7156 self.selection_history.transaction(transaction_id).cloned()
7157 {
7158 self.change_selections(None, cx, |s| {
7159 s.select_anchors(selections.to_vec());
7160 });
7161 }
7162 self.request_autoscroll(Autoscroll::fit(), cx);
7163 self.unmark_text(cx);
7164 self.refresh_inline_completion(true, false, cx);
7165 cx.emit(EditorEvent::Edited { transaction_id });
7166 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7167 }
7168 }
7169
7170 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7171 if self.read_only(cx) {
7172 return;
7173 }
7174
7175 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7176 if let Some((_, Some(selections))) =
7177 self.selection_history.transaction(transaction_id).cloned()
7178 {
7179 self.change_selections(None, cx, |s| {
7180 s.select_anchors(selections.to_vec());
7181 });
7182 }
7183 self.request_autoscroll(Autoscroll::fit(), cx);
7184 self.unmark_text(cx);
7185 self.refresh_inline_completion(true, false, cx);
7186 cx.emit(EditorEvent::Edited { transaction_id });
7187 }
7188 }
7189
7190 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7191 self.buffer
7192 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7193 }
7194
7195 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7196 self.buffer
7197 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7198 }
7199
7200 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7201 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7202 let line_mode = s.line_mode;
7203 s.move_with(|map, selection| {
7204 let cursor = if selection.is_empty() && !line_mode {
7205 movement::left(map, selection.start)
7206 } else {
7207 selection.start
7208 };
7209 selection.collapse_to(cursor, SelectionGoal::None);
7210 });
7211 })
7212 }
7213
7214 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7215 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7216 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7217 })
7218 }
7219
7220 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7221 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7222 let line_mode = s.line_mode;
7223 s.move_with(|map, selection| {
7224 let cursor = if selection.is_empty() && !line_mode {
7225 movement::right(map, selection.end)
7226 } else {
7227 selection.end
7228 };
7229 selection.collapse_to(cursor, SelectionGoal::None)
7230 });
7231 })
7232 }
7233
7234 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7235 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7236 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7237 })
7238 }
7239
7240 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7241 if self.take_rename(true, cx).is_some() {
7242 return;
7243 }
7244
7245 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7246 cx.propagate();
7247 return;
7248 }
7249
7250 let text_layout_details = &self.text_layout_details(cx);
7251 let selection_count = self.selections.count();
7252 let first_selection = self.selections.first_anchor();
7253
7254 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7255 let line_mode = s.line_mode;
7256 s.move_with(|map, selection| {
7257 if !selection.is_empty() && !line_mode {
7258 selection.goal = SelectionGoal::None;
7259 }
7260 let (cursor, goal) = movement::up(
7261 map,
7262 selection.start,
7263 selection.goal,
7264 false,
7265 text_layout_details,
7266 );
7267 selection.collapse_to(cursor, goal);
7268 });
7269 });
7270
7271 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7272 {
7273 cx.propagate();
7274 }
7275 }
7276
7277 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7278 if self.take_rename(true, cx).is_some() {
7279 return;
7280 }
7281
7282 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7283 cx.propagate();
7284 return;
7285 }
7286
7287 let text_layout_details = &self.text_layout_details(cx);
7288
7289 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7290 let line_mode = s.line_mode;
7291 s.move_with(|map, selection| {
7292 if !selection.is_empty() && !line_mode {
7293 selection.goal = SelectionGoal::None;
7294 }
7295 let (cursor, goal) = movement::up_by_rows(
7296 map,
7297 selection.start,
7298 action.lines,
7299 selection.goal,
7300 false,
7301 text_layout_details,
7302 );
7303 selection.collapse_to(cursor, goal);
7304 });
7305 })
7306 }
7307
7308 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7309 if self.take_rename(true, cx).is_some() {
7310 return;
7311 }
7312
7313 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7314 cx.propagate();
7315 return;
7316 }
7317
7318 let text_layout_details = &self.text_layout_details(cx);
7319
7320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7321 let line_mode = s.line_mode;
7322 s.move_with(|map, selection| {
7323 if !selection.is_empty() && !line_mode {
7324 selection.goal = SelectionGoal::None;
7325 }
7326 let (cursor, goal) = movement::down_by_rows(
7327 map,
7328 selection.start,
7329 action.lines,
7330 selection.goal,
7331 false,
7332 text_layout_details,
7333 );
7334 selection.collapse_to(cursor, goal);
7335 });
7336 })
7337 }
7338
7339 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7340 let text_layout_details = &self.text_layout_details(cx);
7341 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7342 s.move_heads_with(|map, head, goal| {
7343 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7344 })
7345 })
7346 }
7347
7348 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7349 let text_layout_details = &self.text_layout_details(cx);
7350 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7351 s.move_heads_with(|map, head, goal| {
7352 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7353 })
7354 })
7355 }
7356
7357 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7358 let Some(row_count) = self.visible_row_count() else {
7359 return;
7360 };
7361
7362 let text_layout_details = &self.text_layout_details(cx);
7363
7364 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7365 s.move_heads_with(|map, head, goal| {
7366 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7367 })
7368 })
7369 }
7370
7371 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7372 if self.take_rename(true, cx).is_some() {
7373 return;
7374 }
7375
7376 if self
7377 .context_menu
7378 .write()
7379 .as_mut()
7380 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7381 .unwrap_or(false)
7382 {
7383 return;
7384 }
7385
7386 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7387 cx.propagate();
7388 return;
7389 }
7390
7391 let Some(row_count) = self.visible_row_count() else {
7392 return;
7393 };
7394
7395 let autoscroll = if action.center_cursor {
7396 Autoscroll::center()
7397 } else {
7398 Autoscroll::fit()
7399 };
7400
7401 let text_layout_details = &self.text_layout_details(cx);
7402
7403 self.change_selections(Some(autoscroll), cx, |s| {
7404 let line_mode = s.line_mode;
7405 s.move_with(|map, selection| {
7406 if !selection.is_empty() && !line_mode {
7407 selection.goal = SelectionGoal::None;
7408 }
7409 let (cursor, goal) = movement::up_by_rows(
7410 map,
7411 selection.end,
7412 row_count,
7413 selection.goal,
7414 false,
7415 text_layout_details,
7416 );
7417 selection.collapse_to(cursor, goal);
7418 });
7419 });
7420 }
7421
7422 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7423 let text_layout_details = &self.text_layout_details(cx);
7424 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7425 s.move_heads_with(|map, head, goal| {
7426 movement::up(map, head, goal, false, text_layout_details)
7427 })
7428 })
7429 }
7430
7431 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7432 self.take_rename(true, cx);
7433
7434 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7435 cx.propagate();
7436 return;
7437 }
7438
7439 let text_layout_details = &self.text_layout_details(cx);
7440 let selection_count = self.selections.count();
7441 let first_selection = self.selections.first_anchor();
7442
7443 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7444 let line_mode = s.line_mode;
7445 s.move_with(|map, selection| {
7446 if !selection.is_empty() && !line_mode {
7447 selection.goal = SelectionGoal::None;
7448 }
7449 let (cursor, goal) = movement::down(
7450 map,
7451 selection.end,
7452 selection.goal,
7453 false,
7454 text_layout_details,
7455 );
7456 selection.collapse_to(cursor, goal);
7457 });
7458 });
7459
7460 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7461 {
7462 cx.propagate();
7463 }
7464 }
7465
7466 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7467 let Some(row_count) = self.visible_row_count() else {
7468 return;
7469 };
7470
7471 let text_layout_details = &self.text_layout_details(cx);
7472
7473 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7474 s.move_heads_with(|map, head, goal| {
7475 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7476 })
7477 })
7478 }
7479
7480 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7481 if self.take_rename(true, cx).is_some() {
7482 return;
7483 }
7484
7485 if self
7486 .context_menu
7487 .write()
7488 .as_mut()
7489 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7490 .unwrap_or(false)
7491 {
7492 return;
7493 }
7494
7495 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7496 cx.propagate();
7497 return;
7498 }
7499
7500 let Some(row_count) = self.visible_row_count() else {
7501 return;
7502 };
7503
7504 let autoscroll = if action.center_cursor {
7505 Autoscroll::center()
7506 } else {
7507 Autoscroll::fit()
7508 };
7509
7510 let text_layout_details = &self.text_layout_details(cx);
7511 self.change_selections(Some(autoscroll), cx, |s| {
7512 let line_mode = s.line_mode;
7513 s.move_with(|map, selection| {
7514 if !selection.is_empty() && !line_mode {
7515 selection.goal = SelectionGoal::None;
7516 }
7517 let (cursor, goal) = movement::down_by_rows(
7518 map,
7519 selection.end,
7520 row_count,
7521 selection.goal,
7522 false,
7523 text_layout_details,
7524 );
7525 selection.collapse_to(cursor, goal);
7526 });
7527 });
7528 }
7529
7530 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7531 let text_layout_details = &self.text_layout_details(cx);
7532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7533 s.move_heads_with(|map, head, goal| {
7534 movement::down(map, head, goal, false, text_layout_details)
7535 })
7536 });
7537 }
7538
7539 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7540 if let Some(context_menu) = self.context_menu.write().as_mut() {
7541 context_menu.select_first(self.project.as_ref(), cx);
7542 }
7543 }
7544
7545 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7546 if let Some(context_menu) = self.context_menu.write().as_mut() {
7547 context_menu.select_prev(self.project.as_ref(), cx);
7548 }
7549 }
7550
7551 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7552 if let Some(context_menu) = self.context_menu.write().as_mut() {
7553 context_menu.select_next(self.project.as_ref(), cx);
7554 }
7555 }
7556
7557 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7558 if let Some(context_menu) = self.context_menu.write().as_mut() {
7559 context_menu.select_last(self.project.as_ref(), cx);
7560 }
7561 }
7562
7563 pub fn move_to_previous_word_start(
7564 &mut self,
7565 _: &MoveToPreviousWordStart,
7566 cx: &mut ViewContext<Self>,
7567 ) {
7568 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7569 s.move_cursors_with(|map, head, _| {
7570 (
7571 movement::previous_word_start(map, head),
7572 SelectionGoal::None,
7573 )
7574 });
7575 })
7576 }
7577
7578 pub fn move_to_previous_subword_start(
7579 &mut self,
7580 _: &MoveToPreviousSubwordStart,
7581 cx: &mut ViewContext<Self>,
7582 ) {
7583 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7584 s.move_cursors_with(|map, head, _| {
7585 (
7586 movement::previous_subword_start(map, head),
7587 SelectionGoal::None,
7588 )
7589 });
7590 })
7591 }
7592
7593 pub fn select_to_previous_word_start(
7594 &mut self,
7595 _: &SelectToPreviousWordStart,
7596 cx: &mut ViewContext<Self>,
7597 ) {
7598 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7599 s.move_heads_with(|map, head, _| {
7600 (
7601 movement::previous_word_start(map, head),
7602 SelectionGoal::None,
7603 )
7604 });
7605 })
7606 }
7607
7608 pub fn select_to_previous_subword_start(
7609 &mut self,
7610 _: &SelectToPreviousSubwordStart,
7611 cx: &mut ViewContext<Self>,
7612 ) {
7613 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 s.move_heads_with(|map, head, _| {
7615 (
7616 movement::previous_subword_start(map, head),
7617 SelectionGoal::None,
7618 )
7619 });
7620 })
7621 }
7622
7623 pub fn delete_to_previous_word_start(
7624 &mut self,
7625 action: &DeleteToPreviousWordStart,
7626 cx: &mut ViewContext<Self>,
7627 ) {
7628 self.transact(cx, |this, cx| {
7629 this.select_autoclose_pair(cx);
7630 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7631 let line_mode = s.line_mode;
7632 s.move_with(|map, selection| {
7633 if selection.is_empty() && !line_mode {
7634 let cursor = if action.ignore_newlines {
7635 movement::previous_word_start(map, selection.head())
7636 } else {
7637 movement::previous_word_start_or_newline(map, selection.head())
7638 };
7639 selection.set_head(cursor, SelectionGoal::None);
7640 }
7641 });
7642 });
7643 this.insert("", cx);
7644 });
7645 }
7646
7647 pub fn delete_to_previous_subword_start(
7648 &mut self,
7649 _: &DeleteToPreviousSubwordStart,
7650 cx: &mut ViewContext<Self>,
7651 ) {
7652 self.transact(cx, |this, cx| {
7653 this.select_autoclose_pair(cx);
7654 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7655 let line_mode = s.line_mode;
7656 s.move_with(|map, selection| {
7657 if selection.is_empty() && !line_mode {
7658 let cursor = movement::previous_subword_start(map, selection.head());
7659 selection.set_head(cursor, SelectionGoal::None);
7660 }
7661 });
7662 });
7663 this.insert("", cx);
7664 });
7665 }
7666
7667 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7668 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7669 s.move_cursors_with(|map, head, _| {
7670 (movement::next_word_end(map, head), SelectionGoal::None)
7671 });
7672 })
7673 }
7674
7675 pub fn move_to_next_subword_end(
7676 &mut self,
7677 _: &MoveToNextSubwordEnd,
7678 cx: &mut ViewContext<Self>,
7679 ) {
7680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7681 s.move_cursors_with(|map, head, _| {
7682 (movement::next_subword_end(map, head), SelectionGoal::None)
7683 });
7684 })
7685 }
7686
7687 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7688 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7689 s.move_heads_with(|map, head, _| {
7690 (movement::next_word_end(map, head), SelectionGoal::None)
7691 });
7692 })
7693 }
7694
7695 pub fn select_to_next_subword_end(
7696 &mut self,
7697 _: &SelectToNextSubwordEnd,
7698 cx: &mut ViewContext<Self>,
7699 ) {
7700 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7701 s.move_heads_with(|map, head, _| {
7702 (movement::next_subword_end(map, head), SelectionGoal::None)
7703 });
7704 })
7705 }
7706
7707 pub fn delete_to_next_word_end(
7708 &mut self,
7709 action: &DeleteToNextWordEnd,
7710 cx: &mut ViewContext<Self>,
7711 ) {
7712 self.transact(cx, |this, cx| {
7713 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7714 let line_mode = s.line_mode;
7715 s.move_with(|map, selection| {
7716 if selection.is_empty() && !line_mode {
7717 let cursor = if action.ignore_newlines {
7718 movement::next_word_end(map, selection.head())
7719 } else {
7720 movement::next_word_end_or_newline(map, selection.head())
7721 };
7722 selection.set_head(cursor, SelectionGoal::None);
7723 }
7724 });
7725 });
7726 this.insert("", cx);
7727 });
7728 }
7729
7730 pub fn delete_to_next_subword_end(
7731 &mut self,
7732 _: &DeleteToNextSubwordEnd,
7733 cx: &mut ViewContext<Self>,
7734 ) {
7735 self.transact(cx, |this, cx| {
7736 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7737 s.move_with(|map, selection| {
7738 if selection.is_empty() {
7739 let cursor = movement::next_subword_end(map, selection.head());
7740 selection.set_head(cursor, SelectionGoal::None);
7741 }
7742 });
7743 });
7744 this.insert("", cx);
7745 });
7746 }
7747
7748 pub fn move_to_beginning_of_line(
7749 &mut self,
7750 action: &MoveToBeginningOfLine,
7751 cx: &mut ViewContext<Self>,
7752 ) {
7753 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7754 s.move_cursors_with(|map, head, _| {
7755 (
7756 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7757 SelectionGoal::None,
7758 )
7759 });
7760 })
7761 }
7762
7763 pub fn select_to_beginning_of_line(
7764 &mut self,
7765 action: &SelectToBeginningOfLine,
7766 cx: &mut ViewContext<Self>,
7767 ) {
7768 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7769 s.move_heads_with(|map, head, _| {
7770 (
7771 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7772 SelectionGoal::None,
7773 )
7774 });
7775 });
7776 }
7777
7778 pub fn delete_to_beginning_of_line(
7779 &mut self,
7780 _: &DeleteToBeginningOfLine,
7781 cx: &mut ViewContext<Self>,
7782 ) {
7783 self.transact(cx, |this, cx| {
7784 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7785 s.move_with(|_, selection| {
7786 selection.reversed = true;
7787 });
7788 });
7789
7790 this.select_to_beginning_of_line(
7791 &SelectToBeginningOfLine {
7792 stop_at_soft_wraps: false,
7793 },
7794 cx,
7795 );
7796 this.backspace(&Backspace, cx);
7797 });
7798 }
7799
7800 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7801 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7802 s.move_cursors_with(|map, head, _| {
7803 (
7804 movement::line_end(map, head, action.stop_at_soft_wraps),
7805 SelectionGoal::None,
7806 )
7807 });
7808 })
7809 }
7810
7811 pub fn select_to_end_of_line(
7812 &mut self,
7813 action: &SelectToEndOfLine,
7814 cx: &mut ViewContext<Self>,
7815 ) {
7816 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7817 s.move_heads_with(|map, head, _| {
7818 (
7819 movement::line_end(map, head, action.stop_at_soft_wraps),
7820 SelectionGoal::None,
7821 )
7822 });
7823 })
7824 }
7825
7826 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7827 self.transact(cx, |this, cx| {
7828 this.select_to_end_of_line(
7829 &SelectToEndOfLine {
7830 stop_at_soft_wraps: false,
7831 },
7832 cx,
7833 );
7834 this.delete(&Delete, cx);
7835 });
7836 }
7837
7838 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7839 self.transact(cx, |this, cx| {
7840 this.select_to_end_of_line(
7841 &SelectToEndOfLine {
7842 stop_at_soft_wraps: false,
7843 },
7844 cx,
7845 );
7846 this.cut(&Cut, cx);
7847 });
7848 }
7849
7850 pub fn move_to_start_of_paragraph(
7851 &mut self,
7852 _: &MoveToStartOfParagraph,
7853 cx: &mut ViewContext<Self>,
7854 ) {
7855 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7856 cx.propagate();
7857 return;
7858 }
7859
7860 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7861 s.move_with(|map, selection| {
7862 selection.collapse_to(
7863 movement::start_of_paragraph(map, selection.head(), 1),
7864 SelectionGoal::None,
7865 )
7866 });
7867 })
7868 }
7869
7870 pub fn move_to_end_of_paragraph(
7871 &mut self,
7872 _: &MoveToEndOfParagraph,
7873 cx: &mut ViewContext<Self>,
7874 ) {
7875 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7876 cx.propagate();
7877 return;
7878 }
7879
7880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7881 s.move_with(|map, selection| {
7882 selection.collapse_to(
7883 movement::end_of_paragraph(map, selection.head(), 1),
7884 SelectionGoal::None,
7885 )
7886 });
7887 })
7888 }
7889
7890 pub fn select_to_start_of_paragraph(
7891 &mut self,
7892 _: &SelectToStartOfParagraph,
7893 cx: &mut ViewContext<Self>,
7894 ) {
7895 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7896 cx.propagate();
7897 return;
7898 }
7899
7900 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7901 s.move_heads_with(|map, head, _| {
7902 (
7903 movement::start_of_paragraph(map, head, 1),
7904 SelectionGoal::None,
7905 )
7906 });
7907 })
7908 }
7909
7910 pub fn select_to_end_of_paragraph(
7911 &mut self,
7912 _: &SelectToEndOfParagraph,
7913 cx: &mut ViewContext<Self>,
7914 ) {
7915 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7916 cx.propagate();
7917 return;
7918 }
7919
7920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7921 s.move_heads_with(|map, head, _| {
7922 (
7923 movement::end_of_paragraph(map, head, 1),
7924 SelectionGoal::None,
7925 )
7926 });
7927 })
7928 }
7929
7930 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7931 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7932 cx.propagate();
7933 return;
7934 }
7935
7936 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7937 s.select_ranges(vec![0..0]);
7938 });
7939 }
7940
7941 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7942 let mut selection = self.selections.last::<Point>(cx);
7943 selection.set_head(Point::zero(), SelectionGoal::None);
7944
7945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7946 s.select(vec![selection]);
7947 });
7948 }
7949
7950 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7951 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7952 cx.propagate();
7953 return;
7954 }
7955
7956 let cursor = self.buffer.read(cx).read(cx).len();
7957 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7958 s.select_ranges(vec![cursor..cursor])
7959 });
7960 }
7961
7962 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7963 self.nav_history = nav_history;
7964 }
7965
7966 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7967 self.nav_history.as_ref()
7968 }
7969
7970 fn push_to_nav_history(
7971 &mut self,
7972 cursor_anchor: Anchor,
7973 new_position: Option<Point>,
7974 cx: &mut ViewContext<Self>,
7975 ) {
7976 if let Some(nav_history) = self.nav_history.as_mut() {
7977 let buffer = self.buffer.read(cx).read(cx);
7978 let cursor_position = cursor_anchor.to_point(&buffer);
7979 let scroll_state = self.scroll_manager.anchor();
7980 let scroll_top_row = scroll_state.top_row(&buffer);
7981 drop(buffer);
7982
7983 if let Some(new_position) = new_position {
7984 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7985 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7986 return;
7987 }
7988 }
7989
7990 nav_history.push(
7991 Some(NavigationData {
7992 cursor_anchor,
7993 cursor_position,
7994 scroll_anchor: scroll_state,
7995 scroll_top_row,
7996 }),
7997 cx,
7998 );
7999 }
8000 }
8001
8002 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8003 let buffer = self.buffer.read(cx).snapshot(cx);
8004 let mut selection = self.selections.first::<usize>(cx);
8005 selection.set_head(buffer.len(), SelectionGoal::None);
8006 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8007 s.select(vec![selection]);
8008 });
8009 }
8010
8011 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8012 let end = self.buffer.read(cx).read(cx).len();
8013 self.change_selections(None, cx, |s| {
8014 s.select_ranges(vec![0..end]);
8015 });
8016 }
8017
8018 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8020 let mut selections = self.selections.all::<Point>(cx);
8021 let max_point = display_map.buffer_snapshot.max_point();
8022 for selection in &mut selections {
8023 let rows = selection.spanned_rows(true, &display_map);
8024 selection.start = Point::new(rows.start.0, 0);
8025 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8026 selection.reversed = false;
8027 }
8028 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8029 s.select(selections);
8030 });
8031 }
8032
8033 pub fn split_selection_into_lines(
8034 &mut self,
8035 _: &SplitSelectionIntoLines,
8036 cx: &mut ViewContext<Self>,
8037 ) {
8038 let mut to_unfold = Vec::new();
8039 let mut new_selection_ranges = Vec::new();
8040 {
8041 let selections = self.selections.all::<Point>(cx);
8042 let buffer = self.buffer.read(cx).read(cx);
8043 for selection in selections {
8044 for row in selection.start.row..selection.end.row {
8045 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8046 new_selection_ranges.push(cursor..cursor);
8047 }
8048 new_selection_ranges.push(selection.end..selection.end);
8049 to_unfold.push(selection.start..selection.end);
8050 }
8051 }
8052 self.unfold_ranges(to_unfold, true, true, cx);
8053 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8054 s.select_ranges(new_selection_ranges);
8055 });
8056 }
8057
8058 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8059 self.add_selection(true, cx);
8060 }
8061
8062 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8063 self.add_selection(false, cx);
8064 }
8065
8066 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8067 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8068 let mut selections = self.selections.all::<Point>(cx);
8069 let text_layout_details = self.text_layout_details(cx);
8070 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8071 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8072 let range = oldest_selection.display_range(&display_map).sorted();
8073
8074 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8075 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8076 let positions = start_x.min(end_x)..start_x.max(end_x);
8077
8078 selections.clear();
8079 let mut stack = Vec::new();
8080 for row in range.start.row().0..=range.end.row().0 {
8081 if let Some(selection) = self.selections.build_columnar_selection(
8082 &display_map,
8083 DisplayRow(row),
8084 &positions,
8085 oldest_selection.reversed,
8086 &text_layout_details,
8087 ) {
8088 stack.push(selection.id);
8089 selections.push(selection);
8090 }
8091 }
8092
8093 if above {
8094 stack.reverse();
8095 }
8096
8097 AddSelectionsState { above, stack }
8098 });
8099
8100 let last_added_selection = *state.stack.last().unwrap();
8101 let mut new_selections = Vec::new();
8102 if above == state.above {
8103 let end_row = if above {
8104 DisplayRow(0)
8105 } else {
8106 display_map.max_point().row()
8107 };
8108
8109 'outer: for selection in selections {
8110 if selection.id == last_added_selection {
8111 let range = selection.display_range(&display_map).sorted();
8112 debug_assert_eq!(range.start.row(), range.end.row());
8113 let mut row = range.start.row();
8114 let positions =
8115 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8116 px(start)..px(end)
8117 } else {
8118 let start_x =
8119 display_map.x_for_display_point(range.start, &text_layout_details);
8120 let end_x =
8121 display_map.x_for_display_point(range.end, &text_layout_details);
8122 start_x.min(end_x)..start_x.max(end_x)
8123 };
8124
8125 while row != end_row {
8126 if above {
8127 row.0 -= 1;
8128 } else {
8129 row.0 += 1;
8130 }
8131
8132 if let Some(new_selection) = self.selections.build_columnar_selection(
8133 &display_map,
8134 row,
8135 &positions,
8136 selection.reversed,
8137 &text_layout_details,
8138 ) {
8139 state.stack.push(new_selection.id);
8140 if above {
8141 new_selections.push(new_selection);
8142 new_selections.push(selection);
8143 } else {
8144 new_selections.push(selection);
8145 new_selections.push(new_selection);
8146 }
8147
8148 continue 'outer;
8149 }
8150 }
8151 }
8152
8153 new_selections.push(selection);
8154 }
8155 } else {
8156 new_selections = selections;
8157 new_selections.retain(|s| s.id != last_added_selection);
8158 state.stack.pop();
8159 }
8160
8161 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8162 s.select(new_selections);
8163 });
8164 if state.stack.len() > 1 {
8165 self.add_selections_state = Some(state);
8166 }
8167 }
8168
8169 pub fn select_next_match_internal(
8170 &mut self,
8171 display_map: &DisplaySnapshot,
8172 replace_newest: bool,
8173 autoscroll: Option<Autoscroll>,
8174 cx: &mut ViewContext<Self>,
8175 ) -> Result<()> {
8176 fn select_next_match_ranges(
8177 this: &mut Editor,
8178 range: Range<usize>,
8179 replace_newest: bool,
8180 auto_scroll: Option<Autoscroll>,
8181 cx: &mut ViewContext<Editor>,
8182 ) {
8183 this.unfold_ranges([range.clone()], false, true, cx);
8184 this.change_selections(auto_scroll, cx, |s| {
8185 if replace_newest {
8186 s.delete(s.newest_anchor().id);
8187 }
8188 s.insert_range(range.clone());
8189 });
8190 }
8191
8192 let buffer = &display_map.buffer_snapshot;
8193 let mut selections = self.selections.all::<usize>(cx);
8194 if let Some(mut select_next_state) = self.select_next_state.take() {
8195 let query = &select_next_state.query;
8196 if !select_next_state.done {
8197 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8198 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8199 let mut next_selected_range = None;
8200
8201 let bytes_after_last_selection =
8202 buffer.bytes_in_range(last_selection.end..buffer.len());
8203 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8204 let query_matches = query
8205 .stream_find_iter(bytes_after_last_selection)
8206 .map(|result| (last_selection.end, result))
8207 .chain(
8208 query
8209 .stream_find_iter(bytes_before_first_selection)
8210 .map(|result| (0, result)),
8211 );
8212
8213 for (start_offset, query_match) in query_matches {
8214 let query_match = query_match.unwrap(); // can only fail due to I/O
8215 let offset_range =
8216 start_offset + query_match.start()..start_offset + query_match.end();
8217 let display_range = offset_range.start.to_display_point(display_map)
8218 ..offset_range.end.to_display_point(display_map);
8219
8220 if !select_next_state.wordwise
8221 || (!movement::is_inside_word(display_map, display_range.start)
8222 && !movement::is_inside_word(display_map, display_range.end))
8223 {
8224 // TODO: This is n^2, because we might check all the selections
8225 if !selections
8226 .iter()
8227 .any(|selection| selection.range().overlaps(&offset_range))
8228 {
8229 next_selected_range = Some(offset_range);
8230 break;
8231 }
8232 }
8233 }
8234
8235 if let Some(next_selected_range) = next_selected_range {
8236 select_next_match_ranges(
8237 self,
8238 next_selected_range,
8239 replace_newest,
8240 autoscroll,
8241 cx,
8242 );
8243 } else {
8244 select_next_state.done = true;
8245 }
8246 }
8247
8248 self.select_next_state = Some(select_next_state);
8249 } else {
8250 let mut only_carets = true;
8251 let mut same_text_selected = true;
8252 let mut selected_text = None;
8253
8254 let mut selections_iter = selections.iter().peekable();
8255 while let Some(selection) = selections_iter.next() {
8256 if selection.start != selection.end {
8257 only_carets = false;
8258 }
8259
8260 if same_text_selected {
8261 if selected_text.is_none() {
8262 selected_text =
8263 Some(buffer.text_for_range(selection.range()).collect::<String>());
8264 }
8265
8266 if let Some(next_selection) = selections_iter.peek() {
8267 if next_selection.range().len() == selection.range().len() {
8268 let next_selected_text = buffer
8269 .text_for_range(next_selection.range())
8270 .collect::<String>();
8271 if Some(next_selected_text) != selected_text {
8272 same_text_selected = false;
8273 selected_text = None;
8274 }
8275 } else {
8276 same_text_selected = false;
8277 selected_text = None;
8278 }
8279 }
8280 }
8281 }
8282
8283 if only_carets {
8284 for selection in &mut selections {
8285 let word_range = movement::surrounding_word(
8286 display_map,
8287 selection.start.to_display_point(display_map),
8288 );
8289 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8290 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8291 selection.goal = SelectionGoal::None;
8292 selection.reversed = false;
8293 select_next_match_ranges(
8294 self,
8295 selection.start..selection.end,
8296 replace_newest,
8297 autoscroll,
8298 cx,
8299 );
8300 }
8301
8302 if selections.len() == 1 {
8303 let selection = selections
8304 .last()
8305 .expect("ensured that there's only one selection");
8306 let query = buffer
8307 .text_for_range(selection.start..selection.end)
8308 .collect::<String>();
8309 let is_empty = query.is_empty();
8310 let select_state = SelectNextState {
8311 query: AhoCorasick::new(&[query])?,
8312 wordwise: true,
8313 done: is_empty,
8314 };
8315 self.select_next_state = Some(select_state);
8316 } else {
8317 self.select_next_state = None;
8318 }
8319 } else if let Some(selected_text) = selected_text {
8320 self.select_next_state = Some(SelectNextState {
8321 query: AhoCorasick::new(&[selected_text])?,
8322 wordwise: false,
8323 done: false,
8324 });
8325 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8326 }
8327 }
8328 Ok(())
8329 }
8330
8331 pub fn select_all_matches(
8332 &mut self,
8333 _action: &SelectAllMatches,
8334 cx: &mut ViewContext<Self>,
8335 ) -> Result<()> {
8336 self.push_to_selection_history();
8337 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8338
8339 self.select_next_match_internal(&display_map, false, None, cx)?;
8340 let Some(select_next_state) = self.select_next_state.as_mut() else {
8341 return Ok(());
8342 };
8343 if select_next_state.done {
8344 return Ok(());
8345 }
8346
8347 let mut new_selections = self.selections.all::<usize>(cx);
8348
8349 let buffer = &display_map.buffer_snapshot;
8350 let query_matches = select_next_state
8351 .query
8352 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8353
8354 for query_match in query_matches {
8355 let query_match = query_match.unwrap(); // can only fail due to I/O
8356 let offset_range = query_match.start()..query_match.end();
8357 let display_range = offset_range.start.to_display_point(&display_map)
8358 ..offset_range.end.to_display_point(&display_map);
8359
8360 if !select_next_state.wordwise
8361 || (!movement::is_inside_word(&display_map, display_range.start)
8362 && !movement::is_inside_word(&display_map, display_range.end))
8363 {
8364 self.selections.change_with(cx, |selections| {
8365 new_selections.push(Selection {
8366 id: selections.new_selection_id(),
8367 start: offset_range.start,
8368 end: offset_range.end,
8369 reversed: false,
8370 goal: SelectionGoal::None,
8371 });
8372 });
8373 }
8374 }
8375
8376 new_selections.sort_by_key(|selection| selection.start);
8377 let mut ix = 0;
8378 while ix + 1 < new_selections.len() {
8379 let current_selection = &new_selections[ix];
8380 let next_selection = &new_selections[ix + 1];
8381 if current_selection.range().overlaps(&next_selection.range()) {
8382 if current_selection.id < next_selection.id {
8383 new_selections.remove(ix + 1);
8384 } else {
8385 new_selections.remove(ix);
8386 }
8387 } else {
8388 ix += 1;
8389 }
8390 }
8391
8392 select_next_state.done = true;
8393 self.unfold_ranges(
8394 new_selections.iter().map(|selection| selection.range()),
8395 false,
8396 false,
8397 cx,
8398 );
8399 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8400 selections.select(new_selections)
8401 });
8402
8403 Ok(())
8404 }
8405
8406 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8407 self.push_to_selection_history();
8408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8409 self.select_next_match_internal(
8410 &display_map,
8411 action.replace_newest,
8412 Some(Autoscroll::newest()),
8413 cx,
8414 )?;
8415 Ok(())
8416 }
8417
8418 pub fn select_previous(
8419 &mut self,
8420 action: &SelectPrevious,
8421 cx: &mut ViewContext<Self>,
8422 ) -> Result<()> {
8423 self.push_to_selection_history();
8424 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8425 let buffer = &display_map.buffer_snapshot;
8426 let mut selections = self.selections.all::<usize>(cx);
8427 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8428 let query = &select_prev_state.query;
8429 if !select_prev_state.done {
8430 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8431 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8432 let mut next_selected_range = None;
8433 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8434 let bytes_before_last_selection =
8435 buffer.reversed_bytes_in_range(0..last_selection.start);
8436 let bytes_after_first_selection =
8437 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8438 let query_matches = query
8439 .stream_find_iter(bytes_before_last_selection)
8440 .map(|result| (last_selection.start, result))
8441 .chain(
8442 query
8443 .stream_find_iter(bytes_after_first_selection)
8444 .map(|result| (buffer.len(), result)),
8445 );
8446 for (end_offset, query_match) in query_matches {
8447 let query_match = query_match.unwrap(); // can only fail due to I/O
8448 let offset_range =
8449 end_offset - query_match.end()..end_offset - query_match.start();
8450 let display_range = offset_range.start.to_display_point(&display_map)
8451 ..offset_range.end.to_display_point(&display_map);
8452
8453 if !select_prev_state.wordwise
8454 || (!movement::is_inside_word(&display_map, display_range.start)
8455 && !movement::is_inside_word(&display_map, display_range.end))
8456 {
8457 next_selected_range = Some(offset_range);
8458 break;
8459 }
8460 }
8461
8462 if let Some(next_selected_range) = next_selected_range {
8463 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8464 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8465 if action.replace_newest {
8466 s.delete(s.newest_anchor().id);
8467 }
8468 s.insert_range(next_selected_range);
8469 });
8470 } else {
8471 select_prev_state.done = true;
8472 }
8473 }
8474
8475 self.select_prev_state = Some(select_prev_state);
8476 } else {
8477 let mut only_carets = true;
8478 let mut same_text_selected = true;
8479 let mut selected_text = None;
8480
8481 let mut selections_iter = selections.iter().peekable();
8482 while let Some(selection) = selections_iter.next() {
8483 if selection.start != selection.end {
8484 only_carets = false;
8485 }
8486
8487 if same_text_selected {
8488 if selected_text.is_none() {
8489 selected_text =
8490 Some(buffer.text_for_range(selection.range()).collect::<String>());
8491 }
8492
8493 if let Some(next_selection) = selections_iter.peek() {
8494 if next_selection.range().len() == selection.range().len() {
8495 let next_selected_text = buffer
8496 .text_for_range(next_selection.range())
8497 .collect::<String>();
8498 if Some(next_selected_text) != selected_text {
8499 same_text_selected = false;
8500 selected_text = None;
8501 }
8502 } else {
8503 same_text_selected = false;
8504 selected_text = None;
8505 }
8506 }
8507 }
8508 }
8509
8510 if only_carets {
8511 for selection in &mut selections {
8512 let word_range = movement::surrounding_word(
8513 &display_map,
8514 selection.start.to_display_point(&display_map),
8515 );
8516 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8517 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8518 selection.goal = SelectionGoal::None;
8519 selection.reversed = false;
8520 }
8521 if selections.len() == 1 {
8522 let selection = selections
8523 .last()
8524 .expect("ensured that there's only one selection");
8525 let query = buffer
8526 .text_for_range(selection.start..selection.end)
8527 .collect::<String>();
8528 let is_empty = query.is_empty();
8529 let select_state = SelectNextState {
8530 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8531 wordwise: true,
8532 done: is_empty,
8533 };
8534 self.select_prev_state = Some(select_state);
8535 } else {
8536 self.select_prev_state = None;
8537 }
8538
8539 self.unfold_ranges(
8540 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8541 false,
8542 true,
8543 cx,
8544 );
8545 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8546 s.select(selections);
8547 });
8548 } else if let Some(selected_text) = selected_text {
8549 self.select_prev_state = Some(SelectNextState {
8550 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8551 wordwise: false,
8552 done: false,
8553 });
8554 self.select_previous(action, cx)?;
8555 }
8556 }
8557 Ok(())
8558 }
8559
8560 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8561 let text_layout_details = &self.text_layout_details(cx);
8562 self.transact(cx, |this, cx| {
8563 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8564 let mut edits = Vec::new();
8565 let mut selection_edit_ranges = Vec::new();
8566 let mut last_toggled_row = None;
8567 let snapshot = this.buffer.read(cx).read(cx);
8568 let empty_str: Arc<str> = Arc::default();
8569 let mut suffixes_inserted = Vec::new();
8570
8571 fn comment_prefix_range(
8572 snapshot: &MultiBufferSnapshot,
8573 row: MultiBufferRow,
8574 comment_prefix: &str,
8575 comment_prefix_whitespace: &str,
8576 ) -> Range<Point> {
8577 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8578
8579 let mut line_bytes = snapshot
8580 .bytes_in_range(start..snapshot.max_point())
8581 .flatten()
8582 .copied();
8583
8584 // If this line currently begins with the line comment prefix, then record
8585 // the range containing the prefix.
8586 if line_bytes
8587 .by_ref()
8588 .take(comment_prefix.len())
8589 .eq(comment_prefix.bytes())
8590 {
8591 // Include any whitespace that matches the comment prefix.
8592 let matching_whitespace_len = line_bytes
8593 .zip(comment_prefix_whitespace.bytes())
8594 .take_while(|(a, b)| a == b)
8595 .count() as u32;
8596 let end = Point::new(
8597 start.row,
8598 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8599 );
8600 start..end
8601 } else {
8602 start..start
8603 }
8604 }
8605
8606 fn comment_suffix_range(
8607 snapshot: &MultiBufferSnapshot,
8608 row: MultiBufferRow,
8609 comment_suffix: &str,
8610 comment_suffix_has_leading_space: bool,
8611 ) -> Range<Point> {
8612 let end = Point::new(row.0, snapshot.line_len(row));
8613 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8614
8615 let mut line_end_bytes = snapshot
8616 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8617 .flatten()
8618 .copied();
8619
8620 let leading_space_len = if suffix_start_column > 0
8621 && line_end_bytes.next() == Some(b' ')
8622 && comment_suffix_has_leading_space
8623 {
8624 1
8625 } else {
8626 0
8627 };
8628
8629 // If this line currently begins with the line comment prefix, then record
8630 // the range containing the prefix.
8631 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8632 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8633 start..end
8634 } else {
8635 end..end
8636 }
8637 }
8638
8639 // TODO: Handle selections that cross excerpts
8640 for selection in &mut selections {
8641 let start_column = snapshot
8642 .indent_size_for_line(MultiBufferRow(selection.start.row))
8643 .len;
8644 let language = if let Some(language) =
8645 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8646 {
8647 language
8648 } else {
8649 continue;
8650 };
8651
8652 selection_edit_ranges.clear();
8653
8654 // If multiple selections contain a given row, avoid processing that
8655 // row more than once.
8656 let mut start_row = MultiBufferRow(selection.start.row);
8657 if last_toggled_row == Some(start_row) {
8658 start_row = start_row.next_row();
8659 }
8660 let end_row =
8661 if selection.end.row > selection.start.row && selection.end.column == 0 {
8662 MultiBufferRow(selection.end.row - 1)
8663 } else {
8664 MultiBufferRow(selection.end.row)
8665 };
8666 last_toggled_row = Some(end_row);
8667
8668 if start_row > end_row {
8669 continue;
8670 }
8671
8672 // If the language has line comments, toggle those.
8673 let full_comment_prefixes = language.line_comment_prefixes();
8674 if !full_comment_prefixes.is_empty() {
8675 let first_prefix = full_comment_prefixes
8676 .first()
8677 .expect("prefixes is non-empty");
8678 let prefix_trimmed_lengths = full_comment_prefixes
8679 .iter()
8680 .map(|p| p.trim_end_matches(' ').len())
8681 .collect::<SmallVec<[usize; 4]>>();
8682
8683 let mut all_selection_lines_are_comments = true;
8684
8685 for row in start_row.0..=end_row.0 {
8686 let row = MultiBufferRow(row);
8687 if start_row < end_row && snapshot.is_line_blank(row) {
8688 continue;
8689 }
8690
8691 let prefix_range = full_comment_prefixes
8692 .iter()
8693 .zip(prefix_trimmed_lengths.iter().copied())
8694 .map(|(prefix, trimmed_prefix_len)| {
8695 comment_prefix_range(
8696 snapshot.deref(),
8697 row,
8698 &prefix[..trimmed_prefix_len],
8699 &prefix[trimmed_prefix_len..],
8700 )
8701 })
8702 .max_by_key(|range| range.end.column - range.start.column)
8703 .expect("prefixes is non-empty");
8704
8705 if prefix_range.is_empty() {
8706 all_selection_lines_are_comments = false;
8707 }
8708
8709 selection_edit_ranges.push(prefix_range);
8710 }
8711
8712 if all_selection_lines_are_comments {
8713 edits.extend(
8714 selection_edit_ranges
8715 .iter()
8716 .cloned()
8717 .map(|range| (range, empty_str.clone())),
8718 );
8719 } else {
8720 let min_column = selection_edit_ranges
8721 .iter()
8722 .map(|range| range.start.column)
8723 .min()
8724 .unwrap_or(0);
8725 edits.extend(selection_edit_ranges.iter().map(|range| {
8726 let position = Point::new(range.start.row, min_column);
8727 (position..position, first_prefix.clone())
8728 }));
8729 }
8730 } else if let Some((full_comment_prefix, comment_suffix)) =
8731 language.block_comment_delimiters()
8732 {
8733 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8734 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8735 let prefix_range = comment_prefix_range(
8736 snapshot.deref(),
8737 start_row,
8738 comment_prefix,
8739 comment_prefix_whitespace,
8740 );
8741 let suffix_range = comment_suffix_range(
8742 snapshot.deref(),
8743 end_row,
8744 comment_suffix.trim_start_matches(' '),
8745 comment_suffix.starts_with(' '),
8746 );
8747
8748 if prefix_range.is_empty() || suffix_range.is_empty() {
8749 edits.push((
8750 prefix_range.start..prefix_range.start,
8751 full_comment_prefix.clone(),
8752 ));
8753 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8754 suffixes_inserted.push((end_row, comment_suffix.len()));
8755 } else {
8756 edits.push((prefix_range, empty_str.clone()));
8757 edits.push((suffix_range, empty_str.clone()));
8758 }
8759 } else {
8760 continue;
8761 }
8762 }
8763
8764 drop(snapshot);
8765 this.buffer.update(cx, |buffer, cx| {
8766 buffer.edit(edits, None, cx);
8767 });
8768
8769 // Adjust selections so that they end before any comment suffixes that
8770 // were inserted.
8771 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8772 let mut selections = this.selections.all::<Point>(cx);
8773 let snapshot = this.buffer.read(cx).read(cx);
8774 for selection in &mut selections {
8775 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8776 match row.cmp(&MultiBufferRow(selection.end.row)) {
8777 Ordering::Less => {
8778 suffixes_inserted.next();
8779 continue;
8780 }
8781 Ordering::Greater => break,
8782 Ordering::Equal => {
8783 if selection.end.column == snapshot.line_len(row) {
8784 if selection.is_empty() {
8785 selection.start.column -= suffix_len as u32;
8786 }
8787 selection.end.column -= suffix_len as u32;
8788 }
8789 break;
8790 }
8791 }
8792 }
8793 }
8794
8795 drop(snapshot);
8796 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8797
8798 let selections = this.selections.all::<Point>(cx);
8799 let selections_on_single_row = selections.windows(2).all(|selections| {
8800 selections[0].start.row == selections[1].start.row
8801 && selections[0].end.row == selections[1].end.row
8802 && selections[0].start.row == selections[0].end.row
8803 });
8804 let selections_selecting = selections
8805 .iter()
8806 .any(|selection| selection.start != selection.end);
8807 let advance_downwards = action.advance_downwards
8808 && selections_on_single_row
8809 && !selections_selecting
8810 && !matches!(this.mode, EditorMode::SingleLine { .. });
8811
8812 if advance_downwards {
8813 let snapshot = this.buffer.read(cx).snapshot(cx);
8814
8815 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8816 s.move_cursors_with(|display_snapshot, display_point, _| {
8817 let mut point = display_point.to_point(display_snapshot);
8818 point.row += 1;
8819 point = snapshot.clip_point(point, Bias::Left);
8820 let display_point = point.to_display_point(display_snapshot);
8821 let goal = SelectionGoal::HorizontalPosition(
8822 display_snapshot
8823 .x_for_display_point(display_point, text_layout_details)
8824 .into(),
8825 );
8826 (display_point, goal)
8827 })
8828 });
8829 }
8830 });
8831 }
8832
8833 pub fn select_enclosing_symbol(
8834 &mut self,
8835 _: &SelectEnclosingSymbol,
8836 cx: &mut ViewContext<Self>,
8837 ) {
8838 let buffer = self.buffer.read(cx).snapshot(cx);
8839 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8840
8841 fn update_selection(
8842 selection: &Selection<usize>,
8843 buffer_snap: &MultiBufferSnapshot,
8844 ) -> Option<Selection<usize>> {
8845 let cursor = selection.head();
8846 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8847 for symbol in symbols.iter().rev() {
8848 let start = symbol.range.start.to_offset(buffer_snap);
8849 let end = symbol.range.end.to_offset(buffer_snap);
8850 let new_range = start..end;
8851 if start < selection.start || end > selection.end {
8852 return Some(Selection {
8853 id: selection.id,
8854 start: new_range.start,
8855 end: new_range.end,
8856 goal: SelectionGoal::None,
8857 reversed: selection.reversed,
8858 });
8859 }
8860 }
8861 None
8862 }
8863
8864 let mut selected_larger_symbol = false;
8865 let new_selections = old_selections
8866 .iter()
8867 .map(|selection| match update_selection(selection, &buffer) {
8868 Some(new_selection) => {
8869 if new_selection.range() != selection.range() {
8870 selected_larger_symbol = true;
8871 }
8872 new_selection
8873 }
8874 None => selection.clone(),
8875 })
8876 .collect::<Vec<_>>();
8877
8878 if selected_larger_symbol {
8879 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8880 s.select(new_selections);
8881 });
8882 }
8883 }
8884
8885 pub fn select_larger_syntax_node(
8886 &mut self,
8887 _: &SelectLargerSyntaxNode,
8888 cx: &mut ViewContext<Self>,
8889 ) {
8890 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8891 let buffer = self.buffer.read(cx).snapshot(cx);
8892 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8893
8894 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8895 let mut selected_larger_node = false;
8896 let new_selections = old_selections
8897 .iter()
8898 .map(|selection| {
8899 let old_range = selection.start..selection.end;
8900 let mut new_range = old_range.clone();
8901 while let Some(containing_range) =
8902 buffer.range_for_syntax_ancestor(new_range.clone())
8903 {
8904 new_range = containing_range;
8905 if !display_map.intersects_fold(new_range.start)
8906 && !display_map.intersects_fold(new_range.end)
8907 {
8908 break;
8909 }
8910 }
8911
8912 selected_larger_node |= new_range != old_range;
8913 Selection {
8914 id: selection.id,
8915 start: new_range.start,
8916 end: new_range.end,
8917 goal: SelectionGoal::None,
8918 reversed: selection.reversed,
8919 }
8920 })
8921 .collect::<Vec<_>>();
8922
8923 if selected_larger_node {
8924 stack.push(old_selections);
8925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8926 s.select(new_selections);
8927 });
8928 }
8929 self.select_larger_syntax_node_stack = stack;
8930 }
8931
8932 pub fn select_smaller_syntax_node(
8933 &mut self,
8934 _: &SelectSmallerSyntaxNode,
8935 cx: &mut ViewContext<Self>,
8936 ) {
8937 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8938 if let Some(selections) = stack.pop() {
8939 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8940 s.select(selections.to_vec());
8941 });
8942 }
8943 self.select_larger_syntax_node_stack = stack;
8944 }
8945
8946 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8947 if !EditorSettings::get_global(cx).gutter.runnables {
8948 self.clear_tasks();
8949 return Task::ready(());
8950 }
8951 let project = self.project.clone();
8952 cx.spawn(|this, mut cx| async move {
8953 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8954 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8955 }) else {
8956 return;
8957 };
8958
8959 let Some(project) = project else {
8960 return;
8961 };
8962
8963 let hide_runnables = project
8964 .update(&mut cx, |project, cx| {
8965 // Do not display any test indicators in non-dev server remote projects.
8966 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8967 })
8968 .unwrap_or(true);
8969 if hide_runnables {
8970 return;
8971 }
8972 let new_rows =
8973 cx.background_executor()
8974 .spawn({
8975 let snapshot = display_snapshot.clone();
8976 async move {
8977 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8978 }
8979 })
8980 .await;
8981 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8982
8983 this.update(&mut cx, |this, _| {
8984 this.clear_tasks();
8985 for (key, value) in rows {
8986 this.insert_tasks(key, value);
8987 }
8988 })
8989 .ok();
8990 })
8991 }
8992 fn fetch_runnable_ranges(
8993 snapshot: &DisplaySnapshot,
8994 range: Range<Anchor>,
8995 ) -> Vec<language::RunnableRange> {
8996 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8997 }
8998
8999 fn runnable_rows(
9000 project: Model<Project>,
9001 snapshot: DisplaySnapshot,
9002 runnable_ranges: Vec<RunnableRange>,
9003 mut cx: AsyncWindowContext,
9004 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9005 runnable_ranges
9006 .into_iter()
9007 .filter_map(|mut runnable| {
9008 let tasks = cx
9009 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9010 .ok()?;
9011 if tasks.is_empty() {
9012 return None;
9013 }
9014
9015 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9016
9017 let row = snapshot
9018 .buffer_snapshot
9019 .buffer_line_for_row(MultiBufferRow(point.row))?
9020 .1
9021 .start
9022 .row;
9023
9024 let context_range =
9025 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9026 Some((
9027 (runnable.buffer_id, row),
9028 RunnableTasks {
9029 templates: tasks,
9030 offset: MultiBufferOffset(runnable.run_range.start),
9031 context_range,
9032 column: point.column,
9033 extra_variables: runnable.extra_captures,
9034 },
9035 ))
9036 })
9037 .collect()
9038 }
9039
9040 fn templates_with_tags(
9041 project: &Model<Project>,
9042 runnable: &mut Runnable,
9043 cx: &WindowContext<'_>,
9044 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9045 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9046 let (worktree_id, file) = project
9047 .buffer_for_id(runnable.buffer, cx)
9048 .and_then(|buffer| buffer.read(cx).file())
9049 .map(|file| (file.worktree_id(cx), file.clone()))
9050 .unzip();
9051
9052 (project.task_inventory().clone(), worktree_id, file)
9053 });
9054
9055 let inventory = inventory.read(cx);
9056 let tags = mem::take(&mut runnable.tags);
9057 let mut tags: Vec<_> = tags
9058 .into_iter()
9059 .flat_map(|tag| {
9060 let tag = tag.0.clone();
9061 inventory
9062 .list_tasks(
9063 file.clone(),
9064 Some(runnable.language.clone()),
9065 worktree_id,
9066 cx,
9067 )
9068 .into_iter()
9069 .filter(move |(_, template)| {
9070 template.tags.iter().any(|source_tag| source_tag == &tag)
9071 })
9072 })
9073 .sorted_by_key(|(kind, _)| kind.to_owned())
9074 .collect();
9075 if let Some((leading_tag_source, _)) = tags.first() {
9076 // Strongest source wins; if we have worktree tag binding, prefer that to
9077 // global and language bindings;
9078 // if we have a global binding, prefer that to language binding.
9079 let first_mismatch = tags
9080 .iter()
9081 .position(|(tag_source, _)| tag_source != leading_tag_source);
9082 if let Some(index) = first_mismatch {
9083 tags.truncate(index);
9084 }
9085 }
9086
9087 tags
9088 }
9089
9090 pub fn move_to_enclosing_bracket(
9091 &mut self,
9092 _: &MoveToEnclosingBracket,
9093 cx: &mut ViewContext<Self>,
9094 ) {
9095 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9096 s.move_offsets_with(|snapshot, selection| {
9097 let Some(enclosing_bracket_ranges) =
9098 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9099 else {
9100 return;
9101 };
9102
9103 let mut best_length = usize::MAX;
9104 let mut best_inside = false;
9105 let mut best_in_bracket_range = false;
9106 let mut best_destination = None;
9107 for (open, close) in enclosing_bracket_ranges {
9108 let close = close.to_inclusive();
9109 let length = close.end() - open.start;
9110 let inside = selection.start >= open.end && selection.end <= *close.start();
9111 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9112 || close.contains(&selection.head());
9113
9114 // If best is next to a bracket and current isn't, skip
9115 if !in_bracket_range && best_in_bracket_range {
9116 continue;
9117 }
9118
9119 // Prefer smaller lengths unless best is inside and current isn't
9120 if length > best_length && (best_inside || !inside) {
9121 continue;
9122 }
9123
9124 best_length = length;
9125 best_inside = inside;
9126 best_in_bracket_range = in_bracket_range;
9127 best_destination = Some(
9128 if close.contains(&selection.start) && close.contains(&selection.end) {
9129 if inside {
9130 open.end
9131 } else {
9132 open.start
9133 }
9134 } else if inside {
9135 *close.start()
9136 } else {
9137 *close.end()
9138 },
9139 );
9140 }
9141
9142 if let Some(destination) = best_destination {
9143 selection.collapse_to(destination, SelectionGoal::None);
9144 }
9145 })
9146 });
9147 }
9148
9149 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9150 self.end_selection(cx);
9151 self.selection_history.mode = SelectionHistoryMode::Undoing;
9152 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9153 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9154 self.select_next_state = entry.select_next_state;
9155 self.select_prev_state = entry.select_prev_state;
9156 self.add_selections_state = entry.add_selections_state;
9157 self.request_autoscroll(Autoscroll::newest(), cx);
9158 }
9159 self.selection_history.mode = SelectionHistoryMode::Normal;
9160 }
9161
9162 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9163 self.end_selection(cx);
9164 self.selection_history.mode = SelectionHistoryMode::Redoing;
9165 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9166 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9167 self.select_next_state = entry.select_next_state;
9168 self.select_prev_state = entry.select_prev_state;
9169 self.add_selections_state = entry.add_selections_state;
9170 self.request_autoscroll(Autoscroll::newest(), cx);
9171 }
9172 self.selection_history.mode = SelectionHistoryMode::Normal;
9173 }
9174
9175 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9176 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9177 }
9178
9179 pub fn expand_excerpts_down(
9180 &mut self,
9181 action: &ExpandExcerptsDown,
9182 cx: &mut ViewContext<Self>,
9183 ) {
9184 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9185 }
9186
9187 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9188 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9189 }
9190
9191 pub fn expand_excerpts_for_direction(
9192 &mut self,
9193 lines: u32,
9194 direction: ExpandExcerptDirection,
9195 cx: &mut ViewContext<Self>,
9196 ) {
9197 let selections = self.selections.disjoint_anchors();
9198
9199 let lines = if lines == 0 {
9200 EditorSettings::get_global(cx).expand_excerpt_lines
9201 } else {
9202 lines
9203 };
9204
9205 self.buffer.update(cx, |buffer, cx| {
9206 buffer.expand_excerpts(
9207 selections
9208 .iter()
9209 .map(|selection| selection.head().excerpt_id)
9210 .dedup(),
9211 lines,
9212 direction,
9213 cx,
9214 )
9215 })
9216 }
9217
9218 pub fn expand_excerpt(
9219 &mut self,
9220 excerpt: ExcerptId,
9221 direction: ExpandExcerptDirection,
9222 cx: &mut ViewContext<Self>,
9223 ) {
9224 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9225 self.buffer.update(cx, |buffer, cx| {
9226 buffer.expand_excerpts([excerpt], lines, direction, cx)
9227 })
9228 }
9229
9230 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9231 self.go_to_diagnostic_impl(Direction::Next, cx)
9232 }
9233
9234 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9235 self.go_to_diagnostic_impl(Direction::Prev, cx)
9236 }
9237
9238 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9239 let buffer = self.buffer.read(cx).snapshot(cx);
9240 let selection = self.selections.newest::<usize>(cx);
9241
9242 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9243 if direction == Direction::Next {
9244 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9245 let (group_id, jump_to) = popover.activation_info();
9246 if self.activate_diagnostics(group_id, cx) {
9247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9248 let mut new_selection = s.newest_anchor().clone();
9249 new_selection.collapse_to(jump_to, SelectionGoal::None);
9250 s.select_anchors(vec![new_selection.clone()]);
9251 });
9252 }
9253 return;
9254 }
9255 }
9256
9257 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9258 active_diagnostics
9259 .primary_range
9260 .to_offset(&buffer)
9261 .to_inclusive()
9262 });
9263 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9264 if active_primary_range.contains(&selection.head()) {
9265 *active_primary_range.start()
9266 } else {
9267 selection.head()
9268 }
9269 } else {
9270 selection.head()
9271 };
9272 let snapshot = self.snapshot(cx);
9273 loop {
9274 let diagnostics = if direction == Direction::Prev {
9275 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9276 } else {
9277 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9278 }
9279 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9280 let group = diagnostics
9281 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9282 // be sorted in a stable way
9283 // skip until we are at current active diagnostic, if it exists
9284 .skip_while(|entry| {
9285 (match direction {
9286 Direction::Prev => entry.range.start >= search_start,
9287 Direction::Next => entry.range.start <= search_start,
9288 }) && self
9289 .active_diagnostics
9290 .as_ref()
9291 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9292 })
9293 .find_map(|entry| {
9294 if entry.diagnostic.is_primary
9295 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9296 && !entry.range.is_empty()
9297 // if we match with the active diagnostic, skip it
9298 && Some(entry.diagnostic.group_id)
9299 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9300 {
9301 Some((entry.range, entry.diagnostic.group_id))
9302 } else {
9303 None
9304 }
9305 });
9306
9307 if let Some((primary_range, group_id)) = group {
9308 if self.activate_diagnostics(group_id, cx) {
9309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9310 s.select(vec![Selection {
9311 id: selection.id,
9312 start: primary_range.start,
9313 end: primary_range.start,
9314 reversed: false,
9315 goal: SelectionGoal::None,
9316 }]);
9317 });
9318 }
9319 break;
9320 } else {
9321 // Cycle around to the start of the buffer, potentially moving back to the start of
9322 // the currently active diagnostic.
9323 active_primary_range.take();
9324 if direction == Direction::Prev {
9325 if search_start == buffer.len() {
9326 break;
9327 } else {
9328 search_start = buffer.len();
9329 }
9330 } else if search_start == 0 {
9331 break;
9332 } else {
9333 search_start = 0;
9334 }
9335 }
9336 }
9337 }
9338
9339 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9340 let snapshot = self
9341 .display_map
9342 .update(cx, |display_map, cx| display_map.snapshot(cx));
9343 let selection = self.selections.newest::<Point>(cx);
9344
9345 if !self.seek_in_direction(
9346 &snapshot,
9347 selection.head(),
9348 false,
9349 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9350 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9351 ),
9352 cx,
9353 ) {
9354 let wrapped_point = Point::zero();
9355 self.seek_in_direction(
9356 &snapshot,
9357 wrapped_point,
9358 true,
9359 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9360 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9361 ),
9362 cx,
9363 );
9364 }
9365 }
9366
9367 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9368 let snapshot = self
9369 .display_map
9370 .update(cx, |display_map, cx| display_map.snapshot(cx));
9371 let selection = self.selections.newest::<Point>(cx);
9372
9373 if !self.seek_in_direction(
9374 &snapshot,
9375 selection.head(),
9376 false,
9377 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9378 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9379 ),
9380 cx,
9381 ) {
9382 let wrapped_point = snapshot.buffer_snapshot.max_point();
9383 self.seek_in_direction(
9384 &snapshot,
9385 wrapped_point,
9386 true,
9387 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9388 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9389 ),
9390 cx,
9391 );
9392 }
9393 }
9394
9395 fn seek_in_direction(
9396 &mut self,
9397 snapshot: &DisplaySnapshot,
9398 initial_point: Point,
9399 is_wrapped: bool,
9400 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9401 cx: &mut ViewContext<Editor>,
9402 ) -> bool {
9403 let display_point = initial_point.to_display_point(snapshot);
9404 let mut hunks = hunks
9405 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9406 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9407 .dedup();
9408
9409 if let Some(hunk) = hunks.next() {
9410 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9411 let row = hunk.start_display_row();
9412 let point = DisplayPoint::new(row, 0);
9413 s.select_display_ranges([point..point]);
9414 });
9415
9416 true
9417 } else {
9418 false
9419 }
9420 }
9421
9422 pub fn go_to_definition(
9423 &mut self,
9424 _: &GoToDefinition,
9425 cx: &mut ViewContext<Self>,
9426 ) -> Task<Result<Navigated>> {
9427 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9428 cx.spawn(|editor, mut cx| async move {
9429 if definition.await? == Navigated::Yes {
9430 return Ok(Navigated::Yes);
9431 }
9432 match editor.update(&mut cx, |editor, cx| {
9433 editor.find_all_references(&FindAllReferences, cx)
9434 })? {
9435 Some(references) => references.await,
9436 None => Ok(Navigated::No),
9437 }
9438 })
9439 }
9440
9441 pub fn go_to_declaration(
9442 &mut self,
9443 _: &GoToDeclaration,
9444 cx: &mut ViewContext<Self>,
9445 ) -> Task<Result<Navigated>> {
9446 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9447 }
9448
9449 pub fn go_to_declaration_split(
9450 &mut self,
9451 _: &GoToDeclaration,
9452 cx: &mut ViewContext<Self>,
9453 ) -> Task<Result<Navigated>> {
9454 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9455 }
9456
9457 pub fn go_to_implementation(
9458 &mut self,
9459 _: &GoToImplementation,
9460 cx: &mut ViewContext<Self>,
9461 ) -> Task<Result<Navigated>> {
9462 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9463 }
9464
9465 pub fn go_to_implementation_split(
9466 &mut self,
9467 _: &GoToImplementationSplit,
9468 cx: &mut ViewContext<Self>,
9469 ) -> Task<Result<Navigated>> {
9470 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9471 }
9472
9473 pub fn go_to_type_definition(
9474 &mut self,
9475 _: &GoToTypeDefinition,
9476 cx: &mut ViewContext<Self>,
9477 ) -> Task<Result<Navigated>> {
9478 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9479 }
9480
9481 pub fn go_to_definition_split(
9482 &mut self,
9483 _: &GoToDefinitionSplit,
9484 cx: &mut ViewContext<Self>,
9485 ) -> Task<Result<Navigated>> {
9486 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9487 }
9488
9489 pub fn go_to_type_definition_split(
9490 &mut self,
9491 _: &GoToTypeDefinitionSplit,
9492 cx: &mut ViewContext<Self>,
9493 ) -> Task<Result<Navigated>> {
9494 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9495 }
9496
9497 fn go_to_definition_of_kind(
9498 &mut self,
9499 kind: GotoDefinitionKind,
9500 split: bool,
9501 cx: &mut ViewContext<Self>,
9502 ) -> Task<Result<Navigated>> {
9503 let Some(workspace) = self.workspace() else {
9504 return Task::ready(Ok(Navigated::No));
9505 };
9506 let buffer = self.buffer.read(cx);
9507 let head = self.selections.newest::<usize>(cx).head();
9508 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9509 text_anchor
9510 } else {
9511 return Task::ready(Ok(Navigated::No));
9512 };
9513
9514 let project = workspace.read(cx).project().clone();
9515 let definitions = project.update(cx, |project, cx| match kind {
9516 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9517 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9518 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9519 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9520 });
9521
9522 cx.spawn(|editor, mut cx| async move {
9523 let definitions = definitions.await?;
9524 let navigated = editor
9525 .update(&mut cx, |editor, cx| {
9526 editor.navigate_to_hover_links(
9527 Some(kind),
9528 definitions
9529 .into_iter()
9530 .filter(|location| {
9531 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9532 })
9533 .map(HoverLink::Text)
9534 .collect::<Vec<_>>(),
9535 split,
9536 cx,
9537 )
9538 })?
9539 .await?;
9540 anyhow::Ok(navigated)
9541 })
9542 }
9543
9544 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9545 let position = self.selections.newest_anchor().head();
9546 let Some((buffer, buffer_position)) =
9547 self.buffer.read(cx).text_anchor_for_position(position, cx)
9548 else {
9549 return;
9550 };
9551
9552 cx.spawn(|editor, mut cx| async move {
9553 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9554 editor.update(&mut cx, |_, cx| {
9555 cx.open_url(&url);
9556 })
9557 } else {
9558 Ok(())
9559 }
9560 })
9561 .detach();
9562 }
9563
9564 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9565 let Some(workspace) = self.workspace() else {
9566 return;
9567 };
9568
9569 let position = self.selections.newest_anchor().head();
9570
9571 let Some((buffer, buffer_position)) =
9572 self.buffer.read(cx).text_anchor_for_position(position, cx)
9573 else {
9574 return;
9575 };
9576
9577 let Some(project) = self.project.clone() else {
9578 return;
9579 };
9580
9581 cx.spawn(|_, mut cx| async move {
9582 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9583
9584 if let Some((_, path)) = result {
9585 workspace
9586 .update(&mut cx, |workspace, cx| {
9587 workspace.open_resolved_path(path, cx)
9588 })?
9589 .await?;
9590 }
9591 anyhow::Ok(())
9592 })
9593 .detach();
9594 }
9595
9596 pub(crate) fn navigate_to_hover_links(
9597 &mut self,
9598 kind: Option<GotoDefinitionKind>,
9599 mut definitions: Vec<HoverLink>,
9600 split: bool,
9601 cx: &mut ViewContext<Editor>,
9602 ) -> Task<Result<Navigated>> {
9603 // If there is one definition, just open it directly
9604 if definitions.len() == 1 {
9605 let definition = definitions.pop().unwrap();
9606
9607 enum TargetTaskResult {
9608 Location(Option<Location>),
9609 AlreadyNavigated,
9610 }
9611
9612 let target_task = match definition {
9613 HoverLink::Text(link) => {
9614 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9615 }
9616 HoverLink::InlayHint(lsp_location, server_id) => {
9617 let computation = self.compute_target_location(lsp_location, server_id, cx);
9618 cx.background_executor().spawn(async move {
9619 let location = computation.await?;
9620 Ok(TargetTaskResult::Location(location))
9621 })
9622 }
9623 HoverLink::Url(url) => {
9624 cx.open_url(&url);
9625 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9626 }
9627 HoverLink::File(path) => {
9628 if let Some(workspace) = self.workspace() {
9629 cx.spawn(|_, mut cx| async move {
9630 workspace
9631 .update(&mut cx, |workspace, cx| {
9632 workspace.open_resolved_path(path, cx)
9633 })?
9634 .await
9635 .map(|_| TargetTaskResult::AlreadyNavigated)
9636 })
9637 } else {
9638 Task::ready(Ok(TargetTaskResult::Location(None)))
9639 }
9640 }
9641 };
9642 cx.spawn(|editor, mut cx| async move {
9643 let target = match target_task.await.context("target resolution task")? {
9644 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9645 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9646 TargetTaskResult::Location(Some(target)) => target,
9647 };
9648
9649 editor.update(&mut cx, |editor, cx| {
9650 let Some(workspace) = editor.workspace() else {
9651 return Navigated::No;
9652 };
9653 let pane = workspace.read(cx).active_pane().clone();
9654
9655 let range = target.range.to_offset(target.buffer.read(cx));
9656 let range = editor.range_for_match(&range);
9657
9658 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9659 let buffer = target.buffer.read(cx);
9660 let range = check_multiline_range(buffer, range);
9661 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9662 s.select_ranges([range]);
9663 });
9664 } else {
9665 cx.window_context().defer(move |cx| {
9666 let target_editor: View<Self> =
9667 workspace.update(cx, |workspace, cx| {
9668 let pane = if split {
9669 workspace.adjacent_pane(cx)
9670 } else {
9671 workspace.active_pane().clone()
9672 };
9673
9674 workspace.open_project_item(
9675 pane,
9676 target.buffer.clone(),
9677 true,
9678 true,
9679 cx,
9680 )
9681 });
9682 target_editor.update(cx, |target_editor, cx| {
9683 // When selecting a definition in a different buffer, disable the nav history
9684 // to avoid creating a history entry at the previous cursor location.
9685 pane.update(cx, |pane, _| pane.disable_history());
9686 let buffer = target.buffer.read(cx);
9687 let range = check_multiline_range(buffer, range);
9688 target_editor.change_selections(
9689 Some(Autoscroll::focused()),
9690 cx,
9691 |s| {
9692 s.select_ranges([range]);
9693 },
9694 );
9695 pane.update(cx, |pane, _| pane.enable_history());
9696 });
9697 });
9698 }
9699 Navigated::Yes
9700 })
9701 })
9702 } else if !definitions.is_empty() {
9703 cx.spawn(|editor, mut cx| async move {
9704 let (title, location_tasks, workspace) = editor
9705 .update(&mut cx, |editor, cx| {
9706 let tab_kind = match kind {
9707 Some(GotoDefinitionKind::Implementation) => "Implementations",
9708 _ => "Definitions",
9709 };
9710 let title = definitions
9711 .iter()
9712 .find_map(|definition| match definition {
9713 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9714 let buffer = origin.buffer.read(cx);
9715 format!(
9716 "{} for {}",
9717 tab_kind,
9718 buffer
9719 .text_for_range(origin.range.clone())
9720 .collect::<String>()
9721 )
9722 }),
9723 HoverLink::InlayHint(_, _) => None,
9724 HoverLink::Url(_) => None,
9725 HoverLink::File(_) => None,
9726 })
9727 .unwrap_or(tab_kind.to_string());
9728 let location_tasks = definitions
9729 .into_iter()
9730 .map(|definition| match definition {
9731 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9732 HoverLink::InlayHint(lsp_location, server_id) => {
9733 editor.compute_target_location(lsp_location, server_id, cx)
9734 }
9735 HoverLink::Url(_) => Task::ready(Ok(None)),
9736 HoverLink::File(_) => Task::ready(Ok(None)),
9737 })
9738 .collect::<Vec<_>>();
9739 (title, location_tasks, editor.workspace().clone())
9740 })
9741 .context("location tasks preparation")?;
9742
9743 let locations = future::join_all(location_tasks)
9744 .await
9745 .into_iter()
9746 .filter_map(|location| location.transpose())
9747 .collect::<Result<_>>()
9748 .context("location tasks")?;
9749
9750 let Some(workspace) = workspace else {
9751 return Ok(Navigated::No);
9752 };
9753 let opened = workspace
9754 .update(&mut cx, |workspace, cx| {
9755 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9756 })
9757 .ok();
9758
9759 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9760 })
9761 } else {
9762 Task::ready(Ok(Navigated::No))
9763 }
9764 }
9765
9766 fn compute_target_location(
9767 &self,
9768 lsp_location: lsp::Location,
9769 server_id: LanguageServerId,
9770 cx: &mut ViewContext<Editor>,
9771 ) -> Task<anyhow::Result<Option<Location>>> {
9772 let Some(project) = self.project.clone() else {
9773 return Task::Ready(Some(Ok(None)));
9774 };
9775
9776 cx.spawn(move |editor, mut cx| async move {
9777 let location_task = editor.update(&mut cx, |editor, cx| {
9778 project.update(cx, |project, cx| {
9779 let language_server_name =
9780 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9781 project
9782 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9783 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9784 });
9785 language_server_name.map(|language_server_name| {
9786 project.open_local_buffer_via_lsp(
9787 lsp_location.uri.clone(),
9788 server_id,
9789 language_server_name,
9790 cx,
9791 )
9792 })
9793 })
9794 })?;
9795 let location = match location_task {
9796 Some(task) => Some({
9797 let target_buffer_handle = task.await.context("open local buffer")?;
9798 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9799 let target_start = target_buffer
9800 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9801 let target_end = target_buffer
9802 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9803 target_buffer.anchor_after(target_start)
9804 ..target_buffer.anchor_before(target_end)
9805 })?;
9806 Location {
9807 buffer: target_buffer_handle,
9808 range,
9809 }
9810 }),
9811 None => None,
9812 };
9813 Ok(location)
9814 })
9815 }
9816
9817 pub fn find_all_references(
9818 &mut self,
9819 _: &FindAllReferences,
9820 cx: &mut ViewContext<Self>,
9821 ) -> Option<Task<Result<Navigated>>> {
9822 let multi_buffer = self.buffer.read(cx);
9823 let selection = self.selections.newest::<usize>(cx);
9824 let head = selection.head();
9825
9826 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9827 let head_anchor = multi_buffer_snapshot.anchor_at(
9828 head,
9829 if head < selection.tail() {
9830 Bias::Right
9831 } else {
9832 Bias::Left
9833 },
9834 );
9835
9836 match self
9837 .find_all_references_task_sources
9838 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9839 {
9840 Ok(_) => {
9841 log::info!(
9842 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9843 );
9844 return None;
9845 }
9846 Err(i) => {
9847 self.find_all_references_task_sources.insert(i, head_anchor);
9848 }
9849 }
9850
9851 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9852 let workspace = self.workspace()?;
9853 let project = workspace.read(cx).project().clone();
9854 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9855 Some(cx.spawn(|editor, mut cx| async move {
9856 let _cleanup = defer({
9857 let mut cx = cx.clone();
9858 move || {
9859 let _ = editor.update(&mut cx, |editor, _| {
9860 if let Ok(i) =
9861 editor
9862 .find_all_references_task_sources
9863 .binary_search_by(|anchor| {
9864 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9865 })
9866 {
9867 editor.find_all_references_task_sources.remove(i);
9868 }
9869 });
9870 }
9871 });
9872
9873 let locations = references.await?;
9874 if locations.is_empty() {
9875 return anyhow::Ok(Navigated::No);
9876 }
9877
9878 workspace.update(&mut cx, |workspace, cx| {
9879 let title = locations
9880 .first()
9881 .as_ref()
9882 .map(|location| {
9883 let buffer = location.buffer.read(cx);
9884 format!(
9885 "References to `{}`",
9886 buffer
9887 .text_for_range(location.range.clone())
9888 .collect::<String>()
9889 )
9890 })
9891 .unwrap();
9892 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9893 Navigated::Yes
9894 })
9895 }))
9896 }
9897
9898 /// Opens a multibuffer with the given project locations in it
9899 pub fn open_locations_in_multibuffer(
9900 workspace: &mut Workspace,
9901 mut locations: Vec<Location>,
9902 title: String,
9903 split: bool,
9904 cx: &mut ViewContext<Workspace>,
9905 ) {
9906 // If there are multiple definitions, open them in a multibuffer
9907 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9908 let mut locations = locations.into_iter().peekable();
9909 let mut ranges_to_highlight = Vec::new();
9910 let capability = workspace.project().read(cx).capability();
9911
9912 let excerpt_buffer = cx.new_model(|cx| {
9913 let mut multibuffer = MultiBuffer::new(capability);
9914 while let Some(location) = locations.next() {
9915 let buffer = location.buffer.read(cx);
9916 let mut ranges_for_buffer = Vec::new();
9917 let range = location.range.to_offset(buffer);
9918 ranges_for_buffer.push(range.clone());
9919
9920 while let Some(next_location) = locations.peek() {
9921 if next_location.buffer == location.buffer {
9922 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9923 locations.next();
9924 } else {
9925 break;
9926 }
9927 }
9928
9929 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9930 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9931 location.buffer.clone(),
9932 ranges_for_buffer,
9933 DEFAULT_MULTIBUFFER_CONTEXT,
9934 cx,
9935 ))
9936 }
9937
9938 multibuffer.with_title(title)
9939 });
9940
9941 let editor = cx.new_view(|cx| {
9942 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9943 });
9944 editor.update(cx, |editor, cx| {
9945 if let Some(first_range) = ranges_to_highlight.first() {
9946 editor.change_selections(None, cx, |selections| {
9947 selections.clear_disjoint();
9948 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9949 });
9950 }
9951 editor.highlight_background::<Self>(
9952 &ranges_to_highlight,
9953 |theme| theme.editor_highlighted_line_background,
9954 cx,
9955 );
9956 });
9957
9958 let item = Box::new(editor);
9959 let item_id = item.item_id();
9960
9961 if split {
9962 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9963 } else {
9964 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9965 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9966 pane.close_current_preview_item(cx)
9967 } else {
9968 None
9969 }
9970 });
9971 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9972 }
9973 workspace.active_pane().update(cx, |pane, cx| {
9974 pane.set_preview_item_id(Some(item_id), cx);
9975 });
9976 }
9977
9978 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9979 use language::ToOffset as _;
9980
9981 let project = self.project.clone()?;
9982 let selection = self.selections.newest_anchor().clone();
9983 let (cursor_buffer, cursor_buffer_position) = self
9984 .buffer
9985 .read(cx)
9986 .text_anchor_for_position(selection.head(), cx)?;
9987 let (tail_buffer, cursor_buffer_position_end) = self
9988 .buffer
9989 .read(cx)
9990 .text_anchor_for_position(selection.tail(), cx)?;
9991 if tail_buffer != cursor_buffer {
9992 return None;
9993 }
9994
9995 let snapshot = cursor_buffer.read(cx).snapshot();
9996 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9997 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9998 let prepare_rename = project.update(cx, |project, cx| {
9999 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10000 });
10001 drop(snapshot);
10002
10003 Some(cx.spawn(|this, mut cx| async move {
10004 let rename_range = if let Some(range) = prepare_rename.await? {
10005 Some(range)
10006 } else {
10007 this.update(&mut cx, |this, cx| {
10008 let buffer = this.buffer.read(cx).snapshot(cx);
10009 let mut buffer_highlights = this
10010 .document_highlights_for_position(selection.head(), &buffer)
10011 .filter(|highlight| {
10012 highlight.start.excerpt_id == selection.head().excerpt_id
10013 && highlight.end.excerpt_id == selection.head().excerpt_id
10014 });
10015 buffer_highlights
10016 .next()
10017 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10018 })?
10019 };
10020 if let Some(rename_range) = rename_range {
10021 this.update(&mut cx, |this, cx| {
10022 let snapshot = cursor_buffer.read(cx).snapshot();
10023 let rename_buffer_range = rename_range.to_offset(&snapshot);
10024 let cursor_offset_in_rename_range =
10025 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10026 let cursor_offset_in_rename_range_end =
10027 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10028
10029 this.take_rename(false, cx);
10030 let buffer = this.buffer.read(cx).read(cx);
10031 let cursor_offset = selection.head().to_offset(&buffer);
10032 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10033 let rename_end = rename_start + rename_buffer_range.len();
10034 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10035 let mut old_highlight_id = None;
10036 let old_name: Arc<str> = buffer
10037 .chunks(rename_start..rename_end, true)
10038 .map(|chunk| {
10039 if old_highlight_id.is_none() {
10040 old_highlight_id = chunk.syntax_highlight_id;
10041 }
10042 chunk.text
10043 })
10044 .collect::<String>()
10045 .into();
10046
10047 drop(buffer);
10048
10049 // Position the selection in the rename editor so that it matches the current selection.
10050 this.show_local_selections = false;
10051 let rename_editor = cx.new_view(|cx| {
10052 let mut editor = Editor::single_line(cx);
10053 editor.buffer.update(cx, |buffer, cx| {
10054 buffer.edit([(0..0, old_name.clone())], None, cx)
10055 });
10056 let rename_selection_range = match cursor_offset_in_rename_range
10057 .cmp(&cursor_offset_in_rename_range_end)
10058 {
10059 Ordering::Equal => {
10060 editor.select_all(&SelectAll, cx);
10061 return editor;
10062 }
10063 Ordering::Less => {
10064 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10065 }
10066 Ordering::Greater => {
10067 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10068 }
10069 };
10070 if rename_selection_range.end > old_name.len() {
10071 editor.select_all(&SelectAll, cx);
10072 } else {
10073 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10074 s.select_ranges([rename_selection_range]);
10075 });
10076 }
10077 editor
10078 });
10079 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10080 if e == &EditorEvent::Focused {
10081 cx.emit(EditorEvent::FocusedIn)
10082 }
10083 })
10084 .detach();
10085
10086 let write_highlights =
10087 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10088 let read_highlights =
10089 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10090 let ranges = write_highlights
10091 .iter()
10092 .flat_map(|(_, ranges)| ranges.iter())
10093 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10094 .cloned()
10095 .collect();
10096
10097 this.highlight_text::<Rename>(
10098 ranges,
10099 HighlightStyle {
10100 fade_out: Some(0.6),
10101 ..Default::default()
10102 },
10103 cx,
10104 );
10105 let rename_focus_handle = rename_editor.focus_handle(cx);
10106 cx.focus(&rename_focus_handle);
10107 let block_id = this.insert_blocks(
10108 [BlockProperties {
10109 style: BlockStyle::Flex,
10110 position: range.start,
10111 height: 1,
10112 render: Box::new({
10113 let rename_editor = rename_editor.clone();
10114 move |cx: &mut BlockContext| {
10115 let mut text_style = cx.editor_style.text.clone();
10116 if let Some(highlight_style) = old_highlight_id
10117 .and_then(|h| h.style(&cx.editor_style.syntax))
10118 {
10119 text_style = text_style.highlight(highlight_style);
10120 }
10121 div()
10122 .pl(cx.anchor_x)
10123 .child(EditorElement::new(
10124 &rename_editor,
10125 EditorStyle {
10126 background: cx.theme().system().transparent,
10127 local_player: cx.editor_style.local_player,
10128 text: text_style,
10129 scrollbar_width: cx.editor_style.scrollbar_width,
10130 syntax: cx.editor_style.syntax.clone(),
10131 status: cx.editor_style.status.clone(),
10132 inlay_hints_style: HighlightStyle {
10133 font_weight: Some(FontWeight::BOLD),
10134 ..make_inlay_hints_style(cx)
10135 },
10136 suggestions_style: HighlightStyle {
10137 color: Some(cx.theme().status().predictive),
10138 ..HighlightStyle::default()
10139 },
10140 ..EditorStyle::default()
10141 },
10142 ))
10143 .into_any_element()
10144 }
10145 }),
10146 disposition: BlockDisposition::Below,
10147 priority: 0,
10148 }],
10149 Some(Autoscroll::fit()),
10150 cx,
10151 )[0];
10152 this.pending_rename = Some(RenameState {
10153 range,
10154 old_name,
10155 editor: rename_editor,
10156 block_id,
10157 });
10158 })?;
10159 }
10160
10161 Ok(())
10162 }))
10163 }
10164
10165 pub fn confirm_rename(
10166 &mut self,
10167 _: &ConfirmRename,
10168 cx: &mut ViewContext<Self>,
10169 ) -> Option<Task<Result<()>>> {
10170 let rename = self.take_rename(false, cx)?;
10171 let workspace = self.workspace()?;
10172 let (start_buffer, start) = self
10173 .buffer
10174 .read(cx)
10175 .text_anchor_for_position(rename.range.start, cx)?;
10176 let (end_buffer, end) = self
10177 .buffer
10178 .read(cx)
10179 .text_anchor_for_position(rename.range.end, cx)?;
10180 if start_buffer != end_buffer {
10181 return None;
10182 }
10183
10184 let buffer = start_buffer;
10185 let range = start..end;
10186 let old_name = rename.old_name;
10187 let new_name = rename.editor.read(cx).text(cx);
10188
10189 let rename = workspace
10190 .read(cx)
10191 .project()
10192 .clone()
10193 .update(cx, |project, cx| {
10194 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10195 });
10196 let workspace = workspace.downgrade();
10197
10198 Some(cx.spawn(|editor, mut cx| async move {
10199 let project_transaction = rename.await?;
10200 Self::open_project_transaction(
10201 &editor,
10202 workspace,
10203 project_transaction,
10204 format!("Rename: {} → {}", old_name, new_name),
10205 cx.clone(),
10206 )
10207 .await?;
10208
10209 editor.update(&mut cx, |editor, cx| {
10210 editor.refresh_document_highlights(cx);
10211 })?;
10212 Ok(())
10213 }))
10214 }
10215
10216 fn take_rename(
10217 &mut self,
10218 moving_cursor: bool,
10219 cx: &mut ViewContext<Self>,
10220 ) -> Option<RenameState> {
10221 let rename = self.pending_rename.take()?;
10222 if rename.editor.focus_handle(cx).is_focused(cx) {
10223 cx.focus(&self.focus_handle);
10224 }
10225
10226 self.remove_blocks(
10227 [rename.block_id].into_iter().collect(),
10228 Some(Autoscroll::fit()),
10229 cx,
10230 );
10231 self.clear_highlights::<Rename>(cx);
10232 self.show_local_selections = true;
10233
10234 if moving_cursor {
10235 let rename_editor = rename.editor.read(cx);
10236 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10237
10238 // Update the selection to match the position of the selection inside
10239 // the rename editor.
10240 let snapshot = self.buffer.read(cx).read(cx);
10241 let rename_range = rename.range.to_offset(&snapshot);
10242 let cursor_in_editor = snapshot
10243 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10244 .min(rename_range.end);
10245 drop(snapshot);
10246
10247 self.change_selections(None, cx, |s| {
10248 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10249 });
10250 } else {
10251 self.refresh_document_highlights(cx);
10252 }
10253
10254 Some(rename)
10255 }
10256
10257 pub fn pending_rename(&self) -> Option<&RenameState> {
10258 self.pending_rename.as_ref()
10259 }
10260
10261 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10262 let project = match &self.project {
10263 Some(project) => project.clone(),
10264 None => return None,
10265 };
10266
10267 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10268 }
10269
10270 fn perform_format(
10271 &mut self,
10272 project: Model<Project>,
10273 trigger: FormatTrigger,
10274 cx: &mut ViewContext<Self>,
10275 ) -> Task<Result<()>> {
10276 let buffer = self.buffer().clone();
10277 let mut buffers = buffer.read(cx).all_buffers();
10278 if trigger == FormatTrigger::Save {
10279 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10280 }
10281
10282 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10283 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10284
10285 cx.spawn(|_, mut cx| async move {
10286 let transaction = futures::select_biased! {
10287 () = timeout => {
10288 log::warn!("timed out waiting for formatting");
10289 None
10290 }
10291 transaction = format.log_err().fuse() => transaction,
10292 };
10293
10294 buffer
10295 .update(&mut cx, |buffer, cx| {
10296 if let Some(transaction) = transaction {
10297 if !buffer.is_singleton() {
10298 buffer.push_transaction(&transaction.0, cx);
10299 }
10300 }
10301
10302 cx.notify();
10303 })
10304 .ok();
10305
10306 Ok(())
10307 })
10308 }
10309
10310 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10311 if let Some(project) = self.project.clone() {
10312 self.buffer.update(cx, |multi_buffer, cx| {
10313 project.update(cx, |project, cx| {
10314 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10315 });
10316 })
10317 }
10318 }
10319
10320 fn cancel_language_server_work(
10321 &mut self,
10322 _: &CancelLanguageServerWork,
10323 cx: &mut ViewContext<Self>,
10324 ) {
10325 if let Some(project) = self.project.clone() {
10326 self.buffer.update(cx, |multi_buffer, cx| {
10327 project.update(cx, |project, cx| {
10328 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10329 });
10330 })
10331 }
10332 }
10333
10334 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10335 cx.show_character_palette();
10336 }
10337
10338 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10339 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10340 let buffer = self.buffer.read(cx).snapshot(cx);
10341 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10342 let is_valid = buffer
10343 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10344 .any(|entry| {
10345 entry.diagnostic.is_primary
10346 && !entry.range.is_empty()
10347 && entry.range.start == primary_range_start
10348 && entry.diagnostic.message == active_diagnostics.primary_message
10349 });
10350
10351 if is_valid != active_diagnostics.is_valid {
10352 active_diagnostics.is_valid = is_valid;
10353 let mut new_styles = HashMap::default();
10354 for (block_id, diagnostic) in &active_diagnostics.blocks {
10355 new_styles.insert(
10356 *block_id,
10357 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10358 );
10359 }
10360 self.display_map.update(cx, |display_map, _cx| {
10361 display_map.replace_blocks(new_styles)
10362 });
10363 }
10364 }
10365 }
10366
10367 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10368 self.dismiss_diagnostics(cx);
10369 let snapshot = self.snapshot(cx);
10370 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10371 let buffer = self.buffer.read(cx).snapshot(cx);
10372
10373 let mut primary_range = None;
10374 let mut primary_message = None;
10375 let mut group_end = Point::zero();
10376 let diagnostic_group = buffer
10377 .diagnostic_group::<MultiBufferPoint>(group_id)
10378 .filter_map(|entry| {
10379 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10380 && (entry.range.start.row == entry.range.end.row
10381 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10382 {
10383 return None;
10384 }
10385 if entry.range.end > group_end {
10386 group_end = entry.range.end;
10387 }
10388 if entry.diagnostic.is_primary {
10389 primary_range = Some(entry.range.clone());
10390 primary_message = Some(entry.diagnostic.message.clone());
10391 }
10392 Some(entry)
10393 })
10394 .collect::<Vec<_>>();
10395 let primary_range = primary_range?;
10396 let primary_message = primary_message?;
10397 let primary_range =
10398 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10399
10400 let blocks = display_map
10401 .insert_blocks(
10402 diagnostic_group.iter().map(|entry| {
10403 let diagnostic = entry.diagnostic.clone();
10404 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10405 BlockProperties {
10406 style: BlockStyle::Fixed,
10407 position: buffer.anchor_after(entry.range.start),
10408 height: message_height,
10409 render: diagnostic_block_renderer(diagnostic, None, true, true),
10410 disposition: BlockDisposition::Below,
10411 priority: 0,
10412 }
10413 }),
10414 cx,
10415 )
10416 .into_iter()
10417 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10418 .collect();
10419
10420 Some(ActiveDiagnosticGroup {
10421 primary_range,
10422 primary_message,
10423 group_id,
10424 blocks,
10425 is_valid: true,
10426 })
10427 });
10428 self.active_diagnostics.is_some()
10429 }
10430
10431 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10432 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10433 self.display_map.update(cx, |display_map, cx| {
10434 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10435 });
10436 cx.notify();
10437 }
10438 }
10439
10440 pub fn set_selections_from_remote(
10441 &mut self,
10442 selections: Vec<Selection<Anchor>>,
10443 pending_selection: Option<Selection<Anchor>>,
10444 cx: &mut ViewContext<Self>,
10445 ) {
10446 let old_cursor_position = self.selections.newest_anchor().head();
10447 self.selections.change_with(cx, |s| {
10448 s.select_anchors(selections);
10449 if let Some(pending_selection) = pending_selection {
10450 s.set_pending(pending_selection, SelectMode::Character);
10451 } else {
10452 s.clear_pending();
10453 }
10454 });
10455 self.selections_did_change(false, &old_cursor_position, true, cx);
10456 }
10457
10458 fn push_to_selection_history(&mut self) {
10459 self.selection_history.push(SelectionHistoryEntry {
10460 selections: self.selections.disjoint_anchors(),
10461 select_next_state: self.select_next_state.clone(),
10462 select_prev_state: self.select_prev_state.clone(),
10463 add_selections_state: self.add_selections_state.clone(),
10464 });
10465 }
10466
10467 pub fn transact(
10468 &mut self,
10469 cx: &mut ViewContext<Self>,
10470 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10471 ) -> Option<TransactionId> {
10472 self.start_transaction_at(Instant::now(), cx);
10473 update(self, cx);
10474 self.end_transaction_at(Instant::now(), cx)
10475 }
10476
10477 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10478 self.end_selection(cx);
10479 if let Some(tx_id) = self
10480 .buffer
10481 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10482 {
10483 self.selection_history
10484 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10485 cx.emit(EditorEvent::TransactionBegun {
10486 transaction_id: tx_id,
10487 })
10488 }
10489 }
10490
10491 fn end_transaction_at(
10492 &mut self,
10493 now: Instant,
10494 cx: &mut ViewContext<Self>,
10495 ) -> Option<TransactionId> {
10496 if let Some(transaction_id) = self
10497 .buffer
10498 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10499 {
10500 if let Some((_, end_selections)) =
10501 self.selection_history.transaction_mut(transaction_id)
10502 {
10503 *end_selections = Some(self.selections.disjoint_anchors());
10504 } else {
10505 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10506 }
10507
10508 cx.emit(EditorEvent::Edited { transaction_id });
10509 Some(transaction_id)
10510 } else {
10511 None
10512 }
10513 }
10514
10515 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10516 let mut fold_ranges = Vec::new();
10517
10518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10519
10520 let selections = self.selections.all_adjusted(cx);
10521 for selection in selections {
10522 let range = selection.range().sorted();
10523 let buffer_start_row = range.start.row;
10524
10525 for row in (0..=range.end.row).rev() {
10526 if let Some((foldable_range, fold_text)) =
10527 display_map.foldable_range(MultiBufferRow(row))
10528 {
10529 if foldable_range.end.row >= buffer_start_row {
10530 fold_ranges.push((foldable_range, fold_text));
10531 if row <= range.start.row {
10532 break;
10533 }
10534 }
10535 }
10536 }
10537 }
10538
10539 self.fold_ranges(fold_ranges, true, cx);
10540 }
10541
10542 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10543 let buffer_row = fold_at.buffer_row;
10544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10545
10546 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10547 let autoscroll = self
10548 .selections
10549 .all::<Point>(cx)
10550 .iter()
10551 .any(|selection| fold_range.overlaps(&selection.range()));
10552
10553 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10554 }
10555 }
10556
10557 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10558 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10559 let buffer = &display_map.buffer_snapshot;
10560 let selections = self.selections.all::<Point>(cx);
10561 let ranges = selections
10562 .iter()
10563 .map(|s| {
10564 let range = s.display_range(&display_map).sorted();
10565 let mut start = range.start.to_point(&display_map);
10566 let mut end = range.end.to_point(&display_map);
10567 start.column = 0;
10568 end.column = buffer.line_len(MultiBufferRow(end.row));
10569 start..end
10570 })
10571 .collect::<Vec<_>>();
10572
10573 self.unfold_ranges(ranges, true, true, cx);
10574 }
10575
10576 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10577 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10578
10579 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10580 ..Point::new(
10581 unfold_at.buffer_row.0,
10582 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10583 );
10584
10585 let autoscroll = self
10586 .selections
10587 .all::<Point>(cx)
10588 .iter()
10589 .any(|selection| selection.range().overlaps(&intersection_range));
10590
10591 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10592 }
10593
10594 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10595 let selections = self.selections.all::<Point>(cx);
10596 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10597 let line_mode = self.selections.line_mode;
10598 let ranges = selections.into_iter().map(|s| {
10599 if line_mode {
10600 let start = Point::new(s.start.row, 0);
10601 let end = Point::new(
10602 s.end.row,
10603 display_map
10604 .buffer_snapshot
10605 .line_len(MultiBufferRow(s.end.row)),
10606 );
10607 (start..end, display_map.fold_placeholder.clone())
10608 } else {
10609 (s.start..s.end, display_map.fold_placeholder.clone())
10610 }
10611 });
10612 self.fold_ranges(ranges, true, cx);
10613 }
10614
10615 pub fn fold_ranges<T: ToOffset + Clone>(
10616 &mut self,
10617 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10618 auto_scroll: bool,
10619 cx: &mut ViewContext<Self>,
10620 ) {
10621 let mut fold_ranges = Vec::new();
10622 let mut buffers_affected = HashMap::default();
10623 let multi_buffer = self.buffer().read(cx);
10624 for (fold_range, fold_text) in ranges {
10625 if let Some((_, buffer, _)) =
10626 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10627 {
10628 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10629 };
10630 fold_ranges.push((fold_range, fold_text));
10631 }
10632
10633 let mut ranges = fold_ranges.into_iter().peekable();
10634 if ranges.peek().is_some() {
10635 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10636
10637 if auto_scroll {
10638 self.request_autoscroll(Autoscroll::fit(), cx);
10639 }
10640
10641 for buffer in buffers_affected.into_values() {
10642 self.sync_expanded_diff_hunks(buffer, cx);
10643 }
10644
10645 cx.notify();
10646
10647 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10648 // Clear diagnostics block when folding a range that contains it.
10649 let snapshot = self.snapshot(cx);
10650 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10651 drop(snapshot);
10652 self.active_diagnostics = Some(active_diagnostics);
10653 self.dismiss_diagnostics(cx);
10654 } else {
10655 self.active_diagnostics = Some(active_diagnostics);
10656 }
10657 }
10658
10659 self.scrollbar_marker_state.dirty = true;
10660 }
10661 }
10662
10663 pub fn unfold_ranges<T: ToOffset + Clone>(
10664 &mut self,
10665 ranges: impl IntoIterator<Item = Range<T>>,
10666 inclusive: bool,
10667 auto_scroll: bool,
10668 cx: &mut ViewContext<Self>,
10669 ) {
10670 let mut unfold_ranges = Vec::new();
10671 let mut buffers_affected = HashMap::default();
10672 let multi_buffer = self.buffer().read(cx);
10673 for range in ranges {
10674 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10675 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10676 };
10677 unfold_ranges.push(range);
10678 }
10679
10680 let mut ranges = unfold_ranges.into_iter().peekable();
10681 if ranges.peek().is_some() {
10682 self.display_map
10683 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10684 if auto_scroll {
10685 self.request_autoscroll(Autoscroll::fit(), cx);
10686 }
10687
10688 for buffer in buffers_affected.into_values() {
10689 self.sync_expanded_diff_hunks(buffer, cx);
10690 }
10691
10692 cx.notify();
10693 self.scrollbar_marker_state.dirty = true;
10694 self.active_indent_guides_state.dirty = true;
10695 }
10696 }
10697
10698 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10699 self.display_map.read(cx).fold_placeholder.clone()
10700 }
10701
10702 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10703 if hovered != self.gutter_hovered {
10704 self.gutter_hovered = hovered;
10705 cx.notify();
10706 }
10707 }
10708
10709 pub fn insert_blocks(
10710 &mut self,
10711 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10712 autoscroll: Option<Autoscroll>,
10713 cx: &mut ViewContext<Self>,
10714 ) -> Vec<CustomBlockId> {
10715 let blocks = self
10716 .display_map
10717 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10718 if let Some(autoscroll) = autoscroll {
10719 self.request_autoscroll(autoscroll, cx);
10720 }
10721 cx.notify();
10722 blocks
10723 }
10724
10725 pub fn resize_blocks(
10726 &mut self,
10727 heights: HashMap<CustomBlockId, u32>,
10728 autoscroll: Option<Autoscroll>,
10729 cx: &mut ViewContext<Self>,
10730 ) {
10731 self.display_map
10732 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10733 if let Some(autoscroll) = autoscroll {
10734 self.request_autoscroll(autoscroll, cx);
10735 }
10736 cx.notify();
10737 }
10738
10739 pub fn replace_blocks(
10740 &mut self,
10741 renderers: HashMap<CustomBlockId, RenderBlock>,
10742 autoscroll: Option<Autoscroll>,
10743 cx: &mut ViewContext<Self>,
10744 ) {
10745 self.display_map
10746 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10747 if let Some(autoscroll) = autoscroll {
10748 self.request_autoscroll(autoscroll, cx);
10749 }
10750 cx.notify();
10751 }
10752
10753 pub fn remove_blocks(
10754 &mut self,
10755 block_ids: HashSet<CustomBlockId>,
10756 autoscroll: Option<Autoscroll>,
10757 cx: &mut ViewContext<Self>,
10758 ) {
10759 self.display_map.update(cx, |display_map, cx| {
10760 display_map.remove_blocks(block_ids, cx)
10761 });
10762 if let Some(autoscroll) = autoscroll {
10763 self.request_autoscroll(autoscroll, cx);
10764 }
10765 cx.notify();
10766 }
10767
10768 pub fn row_for_block(
10769 &self,
10770 block_id: CustomBlockId,
10771 cx: &mut ViewContext<Self>,
10772 ) -> Option<DisplayRow> {
10773 self.display_map
10774 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10775 }
10776
10777 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10778 self.focused_block = Some(focused_block);
10779 }
10780
10781 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10782 self.focused_block.take()
10783 }
10784
10785 pub fn insert_creases(
10786 &mut self,
10787 creases: impl IntoIterator<Item = Crease>,
10788 cx: &mut ViewContext<Self>,
10789 ) -> Vec<CreaseId> {
10790 self.display_map
10791 .update(cx, |map, cx| map.insert_creases(creases, cx))
10792 }
10793
10794 pub fn remove_creases(
10795 &mut self,
10796 ids: impl IntoIterator<Item = CreaseId>,
10797 cx: &mut ViewContext<Self>,
10798 ) {
10799 self.display_map
10800 .update(cx, |map, cx| map.remove_creases(ids, cx));
10801 }
10802
10803 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10804 self.display_map
10805 .update(cx, |map, cx| map.snapshot(cx))
10806 .longest_row()
10807 }
10808
10809 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10810 self.display_map
10811 .update(cx, |map, cx| map.snapshot(cx))
10812 .max_point()
10813 }
10814
10815 pub fn text(&self, cx: &AppContext) -> String {
10816 self.buffer.read(cx).read(cx).text()
10817 }
10818
10819 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10820 let text = self.text(cx);
10821 let text = text.trim();
10822
10823 if text.is_empty() {
10824 return None;
10825 }
10826
10827 Some(text.to_string())
10828 }
10829
10830 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10831 self.transact(cx, |this, cx| {
10832 this.buffer
10833 .read(cx)
10834 .as_singleton()
10835 .expect("you can only call set_text on editors for singleton buffers")
10836 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10837 });
10838 }
10839
10840 pub fn display_text(&self, cx: &mut AppContext) -> String {
10841 self.display_map
10842 .update(cx, |map, cx| map.snapshot(cx))
10843 .text()
10844 }
10845
10846 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10847 let mut wrap_guides = smallvec::smallvec![];
10848
10849 if self.show_wrap_guides == Some(false) {
10850 return wrap_guides;
10851 }
10852
10853 let settings = self.buffer.read(cx).settings_at(0, cx);
10854 if settings.show_wrap_guides {
10855 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10856 wrap_guides.push((soft_wrap as usize, true));
10857 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10858 wrap_guides.push((soft_wrap as usize, true));
10859 }
10860 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10861 }
10862
10863 wrap_guides
10864 }
10865
10866 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10867 let settings = self.buffer.read(cx).settings_at(0, cx);
10868 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10869 match mode {
10870 language_settings::SoftWrap::None => SoftWrap::None,
10871 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10872 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10873 language_settings::SoftWrap::PreferredLineLength => {
10874 SoftWrap::Column(settings.preferred_line_length)
10875 }
10876 language_settings::SoftWrap::Bounded => {
10877 SoftWrap::Bounded(settings.preferred_line_length)
10878 }
10879 }
10880 }
10881
10882 pub fn set_soft_wrap_mode(
10883 &mut self,
10884 mode: language_settings::SoftWrap,
10885 cx: &mut ViewContext<Self>,
10886 ) {
10887 self.soft_wrap_mode_override = Some(mode);
10888 cx.notify();
10889 }
10890
10891 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10892 let rem_size = cx.rem_size();
10893 self.display_map.update(cx, |map, cx| {
10894 map.set_font(
10895 style.text.font(),
10896 style.text.font_size.to_pixels(rem_size),
10897 cx,
10898 )
10899 });
10900 self.style = Some(style);
10901 }
10902
10903 pub fn style(&self) -> Option<&EditorStyle> {
10904 self.style.as_ref()
10905 }
10906
10907 // Called by the element. This method is not designed to be called outside of the editor
10908 // element's layout code because it does not notify when rewrapping is computed synchronously.
10909 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10910 self.display_map
10911 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10912 }
10913
10914 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10915 if self.soft_wrap_mode_override.is_some() {
10916 self.soft_wrap_mode_override.take();
10917 } else {
10918 let soft_wrap = match self.soft_wrap_mode(cx) {
10919 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10920 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10921 language_settings::SoftWrap::PreferLine
10922 }
10923 };
10924 self.soft_wrap_mode_override = Some(soft_wrap);
10925 }
10926 cx.notify();
10927 }
10928
10929 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10930 let Some(workspace) = self.workspace() else {
10931 return;
10932 };
10933 let fs = workspace.read(cx).app_state().fs.clone();
10934 let current_show = TabBarSettings::get_global(cx).show;
10935 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10936 setting.show = Some(!current_show);
10937 });
10938 }
10939
10940 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10941 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10942 self.buffer
10943 .read(cx)
10944 .settings_at(0, cx)
10945 .indent_guides
10946 .enabled
10947 });
10948 self.show_indent_guides = Some(!currently_enabled);
10949 cx.notify();
10950 }
10951
10952 fn should_show_indent_guides(&self) -> Option<bool> {
10953 self.show_indent_guides
10954 }
10955
10956 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10957 let mut editor_settings = EditorSettings::get_global(cx).clone();
10958 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10959 EditorSettings::override_global(editor_settings, cx);
10960 }
10961
10962 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10963 self.use_relative_line_numbers
10964 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10965 }
10966
10967 pub fn toggle_relative_line_numbers(
10968 &mut self,
10969 _: &ToggleRelativeLineNumbers,
10970 cx: &mut ViewContext<Self>,
10971 ) {
10972 let is_relative = self.should_use_relative_line_numbers(cx);
10973 self.set_relative_line_number(Some(!is_relative), cx)
10974 }
10975
10976 pub fn set_relative_line_number(
10977 &mut self,
10978 is_relative: Option<bool>,
10979 cx: &mut ViewContext<Self>,
10980 ) {
10981 self.use_relative_line_numbers = is_relative;
10982 cx.notify();
10983 }
10984
10985 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10986 self.show_gutter = show_gutter;
10987 cx.notify();
10988 }
10989
10990 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10991 self.show_line_numbers = Some(show_line_numbers);
10992 cx.notify();
10993 }
10994
10995 pub fn set_show_git_diff_gutter(
10996 &mut self,
10997 show_git_diff_gutter: bool,
10998 cx: &mut ViewContext<Self>,
10999 ) {
11000 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11001 cx.notify();
11002 }
11003
11004 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11005 self.show_code_actions = Some(show_code_actions);
11006 cx.notify();
11007 }
11008
11009 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11010 self.show_runnables = Some(show_runnables);
11011 cx.notify();
11012 }
11013
11014 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11015 if self.display_map.read(cx).masked != masked {
11016 self.display_map.update(cx, |map, _| map.masked = masked);
11017 }
11018 cx.notify()
11019 }
11020
11021 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11022 self.show_wrap_guides = Some(show_wrap_guides);
11023 cx.notify();
11024 }
11025
11026 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11027 self.show_indent_guides = Some(show_indent_guides);
11028 cx.notify();
11029 }
11030
11031 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11032 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11033 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11034 if let Some(dir) = file.abs_path(cx).parent() {
11035 return Some(dir.to_owned());
11036 }
11037 }
11038
11039 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11040 return Some(project_path.path.to_path_buf());
11041 }
11042 }
11043
11044 None
11045 }
11046
11047 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11048 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11049 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11050 cx.reveal_path(&file.abs_path(cx));
11051 }
11052 }
11053 }
11054
11055 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11056 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11057 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11058 if let Some(path) = file.abs_path(cx).to_str() {
11059 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11060 }
11061 }
11062 }
11063 }
11064
11065 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11066 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11067 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11068 if let Some(path) = file.path().to_str() {
11069 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11070 }
11071 }
11072 }
11073 }
11074
11075 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11076 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11077
11078 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11079 self.start_git_blame(true, cx);
11080 }
11081
11082 cx.notify();
11083 }
11084
11085 pub fn toggle_git_blame_inline(
11086 &mut self,
11087 _: &ToggleGitBlameInline,
11088 cx: &mut ViewContext<Self>,
11089 ) {
11090 self.toggle_git_blame_inline_internal(true, cx);
11091 cx.notify();
11092 }
11093
11094 pub fn git_blame_inline_enabled(&self) -> bool {
11095 self.git_blame_inline_enabled
11096 }
11097
11098 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11099 self.show_selection_menu = self
11100 .show_selection_menu
11101 .map(|show_selections_menu| !show_selections_menu)
11102 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11103
11104 cx.notify();
11105 }
11106
11107 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11108 self.show_selection_menu
11109 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11110 }
11111
11112 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11113 if let Some(project) = self.project.as_ref() {
11114 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11115 return;
11116 };
11117
11118 if buffer.read(cx).file().is_none() {
11119 return;
11120 }
11121
11122 let focused = self.focus_handle(cx).contains_focused(cx);
11123
11124 let project = project.clone();
11125 let blame =
11126 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11127 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11128 self.blame = Some(blame);
11129 }
11130 }
11131
11132 fn toggle_git_blame_inline_internal(
11133 &mut self,
11134 user_triggered: bool,
11135 cx: &mut ViewContext<Self>,
11136 ) {
11137 if self.git_blame_inline_enabled {
11138 self.git_blame_inline_enabled = false;
11139 self.show_git_blame_inline = false;
11140 self.show_git_blame_inline_delay_task.take();
11141 } else {
11142 self.git_blame_inline_enabled = true;
11143 self.start_git_blame_inline(user_triggered, cx);
11144 }
11145
11146 cx.notify();
11147 }
11148
11149 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11150 self.start_git_blame(user_triggered, cx);
11151
11152 if ProjectSettings::get_global(cx)
11153 .git
11154 .inline_blame_delay()
11155 .is_some()
11156 {
11157 self.start_inline_blame_timer(cx);
11158 } else {
11159 self.show_git_blame_inline = true
11160 }
11161 }
11162
11163 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11164 self.blame.as_ref()
11165 }
11166
11167 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11168 self.show_git_blame_gutter && self.has_blame_entries(cx)
11169 }
11170
11171 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11172 self.show_git_blame_inline
11173 && self.focus_handle.is_focused(cx)
11174 && !self.newest_selection_head_on_empty_line(cx)
11175 && self.has_blame_entries(cx)
11176 }
11177
11178 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11179 self.blame()
11180 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11181 }
11182
11183 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11184 let cursor_anchor = self.selections.newest_anchor().head();
11185
11186 let snapshot = self.buffer.read(cx).snapshot(cx);
11187 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11188
11189 snapshot.line_len(buffer_row) == 0
11190 }
11191
11192 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11193 let (path, selection, repo) = maybe!({
11194 let project_handle = self.project.as_ref()?.clone();
11195 let project = project_handle.read(cx);
11196
11197 let selection = self.selections.newest::<Point>(cx);
11198 let selection_range = selection.range();
11199
11200 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11201 (buffer, selection_range.start.row..selection_range.end.row)
11202 } else {
11203 let buffer_ranges = self
11204 .buffer()
11205 .read(cx)
11206 .range_to_buffer_ranges(selection_range, cx);
11207
11208 let (buffer, range, _) = if selection.reversed {
11209 buffer_ranges.first()
11210 } else {
11211 buffer_ranges.last()
11212 }?;
11213
11214 let snapshot = buffer.read(cx).snapshot();
11215 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11216 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11217 (buffer.clone(), selection)
11218 };
11219
11220 let path = buffer
11221 .read(cx)
11222 .file()?
11223 .as_local()?
11224 .path()
11225 .to_str()?
11226 .to_string();
11227 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11228 Some((path, selection, repo))
11229 })
11230 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11231
11232 const REMOTE_NAME: &str = "origin";
11233 let origin_url = repo
11234 .remote_url(REMOTE_NAME)
11235 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11236 let sha = repo
11237 .head_sha()
11238 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11239
11240 let (provider, remote) =
11241 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11242 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11243
11244 Ok(provider.build_permalink(
11245 remote,
11246 BuildPermalinkParams {
11247 sha: &sha,
11248 path: &path,
11249 selection: Some(selection),
11250 },
11251 ))
11252 }
11253
11254 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11255 let permalink = self.get_permalink_to_line(cx);
11256
11257 match permalink {
11258 Ok(permalink) => {
11259 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11260 }
11261 Err(err) => {
11262 let message = format!("Failed to copy permalink: {err}");
11263
11264 Err::<(), anyhow::Error>(err).log_err();
11265
11266 if let Some(workspace) = self.workspace() {
11267 workspace.update(cx, |workspace, cx| {
11268 struct CopyPermalinkToLine;
11269
11270 workspace.show_toast(
11271 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11272 cx,
11273 )
11274 })
11275 }
11276 }
11277 }
11278 }
11279
11280 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11281 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11282 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11283 if let Some(path) = file.path().to_str() {
11284 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11285 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11286 }
11287 }
11288 }
11289 }
11290
11291 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11292 let permalink = self.get_permalink_to_line(cx);
11293
11294 match permalink {
11295 Ok(permalink) => {
11296 cx.open_url(permalink.as_ref());
11297 }
11298 Err(err) => {
11299 let message = format!("Failed to open permalink: {err}");
11300
11301 Err::<(), anyhow::Error>(err).log_err();
11302
11303 if let Some(workspace) = self.workspace() {
11304 workspace.update(cx, |workspace, cx| {
11305 struct OpenPermalinkToLine;
11306
11307 workspace.show_toast(
11308 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11309 cx,
11310 )
11311 })
11312 }
11313 }
11314 }
11315 }
11316
11317 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11318 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11319 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11320 pub fn highlight_rows<T: 'static>(
11321 &mut self,
11322 rows: RangeInclusive<Anchor>,
11323 color: Option<Hsla>,
11324 should_autoscroll: bool,
11325 cx: &mut ViewContext<Self>,
11326 ) {
11327 let snapshot = self.buffer().read(cx).snapshot(cx);
11328 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11329 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11330 highlight
11331 .range
11332 .start()
11333 .cmp(rows.start(), &snapshot)
11334 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11335 });
11336 match (color, existing_highlight_index) {
11337 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11338 ix,
11339 RowHighlight {
11340 index: post_inc(&mut self.highlight_order),
11341 range: rows,
11342 should_autoscroll,
11343 color,
11344 },
11345 ),
11346 (None, Ok(i)) => {
11347 row_highlights.remove(i);
11348 }
11349 }
11350 }
11351
11352 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11353 pub fn clear_row_highlights<T: 'static>(&mut self) {
11354 self.highlighted_rows.remove(&TypeId::of::<T>());
11355 }
11356
11357 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11358 pub fn highlighted_rows<T: 'static>(
11359 &self,
11360 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11361 Some(
11362 self.highlighted_rows
11363 .get(&TypeId::of::<T>())?
11364 .iter()
11365 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11366 )
11367 }
11368
11369 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11370 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11371 /// Allows to ignore certain kinds of highlights.
11372 pub fn highlighted_display_rows(
11373 &mut self,
11374 cx: &mut WindowContext,
11375 ) -> BTreeMap<DisplayRow, Hsla> {
11376 let snapshot = self.snapshot(cx);
11377 let mut used_highlight_orders = HashMap::default();
11378 self.highlighted_rows
11379 .iter()
11380 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11381 .fold(
11382 BTreeMap::<DisplayRow, Hsla>::new(),
11383 |mut unique_rows, highlight| {
11384 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11385 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11386 for row in start_row.0..=end_row.0 {
11387 let used_index =
11388 used_highlight_orders.entry(row).or_insert(highlight.index);
11389 if highlight.index >= *used_index {
11390 *used_index = highlight.index;
11391 match highlight.color {
11392 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11393 None => unique_rows.remove(&DisplayRow(row)),
11394 };
11395 }
11396 }
11397 unique_rows
11398 },
11399 )
11400 }
11401
11402 pub fn highlighted_display_row_for_autoscroll(
11403 &self,
11404 snapshot: &DisplaySnapshot,
11405 ) -> Option<DisplayRow> {
11406 self.highlighted_rows
11407 .values()
11408 .flat_map(|highlighted_rows| highlighted_rows.iter())
11409 .filter_map(|highlight| {
11410 if highlight.color.is_none() || !highlight.should_autoscroll {
11411 return None;
11412 }
11413 Some(highlight.range.start().to_display_point(snapshot).row())
11414 })
11415 .min()
11416 }
11417
11418 pub fn set_search_within_ranges(
11419 &mut self,
11420 ranges: &[Range<Anchor>],
11421 cx: &mut ViewContext<Self>,
11422 ) {
11423 self.highlight_background::<SearchWithinRange>(
11424 ranges,
11425 |colors| colors.editor_document_highlight_read_background,
11426 cx,
11427 )
11428 }
11429
11430 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11431 self.breadcrumb_header = Some(new_header);
11432 }
11433
11434 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11435 self.clear_background_highlights::<SearchWithinRange>(cx);
11436 }
11437
11438 pub fn highlight_background<T: 'static>(
11439 &mut self,
11440 ranges: &[Range<Anchor>],
11441 color_fetcher: fn(&ThemeColors) -> Hsla,
11442 cx: &mut ViewContext<Self>,
11443 ) {
11444 self.background_highlights
11445 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11446 self.scrollbar_marker_state.dirty = true;
11447 cx.notify();
11448 }
11449
11450 pub fn clear_background_highlights<T: 'static>(
11451 &mut self,
11452 cx: &mut ViewContext<Self>,
11453 ) -> Option<BackgroundHighlight> {
11454 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11455 if !text_highlights.1.is_empty() {
11456 self.scrollbar_marker_state.dirty = true;
11457 cx.notify();
11458 }
11459 Some(text_highlights)
11460 }
11461
11462 pub fn highlight_gutter<T: 'static>(
11463 &mut self,
11464 ranges: &[Range<Anchor>],
11465 color_fetcher: fn(&AppContext) -> Hsla,
11466 cx: &mut ViewContext<Self>,
11467 ) {
11468 self.gutter_highlights
11469 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11470 cx.notify();
11471 }
11472
11473 pub fn clear_gutter_highlights<T: 'static>(
11474 &mut self,
11475 cx: &mut ViewContext<Self>,
11476 ) -> Option<GutterHighlight> {
11477 cx.notify();
11478 self.gutter_highlights.remove(&TypeId::of::<T>())
11479 }
11480
11481 #[cfg(feature = "test-support")]
11482 pub fn all_text_background_highlights(
11483 &mut self,
11484 cx: &mut ViewContext<Self>,
11485 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11486 let snapshot = self.snapshot(cx);
11487 let buffer = &snapshot.buffer_snapshot;
11488 let start = buffer.anchor_before(0);
11489 let end = buffer.anchor_after(buffer.len());
11490 let theme = cx.theme().colors();
11491 self.background_highlights_in_range(start..end, &snapshot, theme)
11492 }
11493
11494 #[cfg(feature = "test-support")]
11495 pub fn search_background_highlights(
11496 &mut self,
11497 cx: &mut ViewContext<Self>,
11498 ) -> Vec<Range<Point>> {
11499 let snapshot = self.buffer().read(cx).snapshot(cx);
11500
11501 let highlights = self
11502 .background_highlights
11503 .get(&TypeId::of::<items::BufferSearchHighlights>());
11504
11505 if let Some((_color, ranges)) = highlights {
11506 ranges
11507 .iter()
11508 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11509 .collect_vec()
11510 } else {
11511 vec![]
11512 }
11513 }
11514
11515 fn document_highlights_for_position<'a>(
11516 &'a self,
11517 position: Anchor,
11518 buffer: &'a MultiBufferSnapshot,
11519 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11520 let read_highlights = self
11521 .background_highlights
11522 .get(&TypeId::of::<DocumentHighlightRead>())
11523 .map(|h| &h.1);
11524 let write_highlights = self
11525 .background_highlights
11526 .get(&TypeId::of::<DocumentHighlightWrite>())
11527 .map(|h| &h.1);
11528 let left_position = position.bias_left(buffer);
11529 let right_position = position.bias_right(buffer);
11530 read_highlights
11531 .into_iter()
11532 .chain(write_highlights)
11533 .flat_map(move |ranges| {
11534 let start_ix = match ranges.binary_search_by(|probe| {
11535 let cmp = probe.end.cmp(&left_position, buffer);
11536 if cmp.is_ge() {
11537 Ordering::Greater
11538 } else {
11539 Ordering::Less
11540 }
11541 }) {
11542 Ok(i) | Err(i) => i,
11543 };
11544
11545 ranges[start_ix..]
11546 .iter()
11547 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11548 })
11549 }
11550
11551 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11552 self.background_highlights
11553 .get(&TypeId::of::<T>())
11554 .map_or(false, |(_, highlights)| !highlights.is_empty())
11555 }
11556
11557 pub fn background_highlights_in_range(
11558 &self,
11559 search_range: Range<Anchor>,
11560 display_snapshot: &DisplaySnapshot,
11561 theme: &ThemeColors,
11562 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11563 let mut results = Vec::new();
11564 for (color_fetcher, ranges) in self.background_highlights.values() {
11565 let color = color_fetcher(theme);
11566 let start_ix = match ranges.binary_search_by(|probe| {
11567 let cmp = probe
11568 .end
11569 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11570 if cmp.is_gt() {
11571 Ordering::Greater
11572 } else {
11573 Ordering::Less
11574 }
11575 }) {
11576 Ok(i) | Err(i) => i,
11577 };
11578 for range in &ranges[start_ix..] {
11579 if range
11580 .start
11581 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11582 .is_ge()
11583 {
11584 break;
11585 }
11586
11587 let start = range.start.to_display_point(display_snapshot);
11588 let end = range.end.to_display_point(display_snapshot);
11589 results.push((start..end, color))
11590 }
11591 }
11592 results
11593 }
11594
11595 pub fn background_highlight_row_ranges<T: 'static>(
11596 &self,
11597 search_range: Range<Anchor>,
11598 display_snapshot: &DisplaySnapshot,
11599 count: usize,
11600 ) -> Vec<RangeInclusive<DisplayPoint>> {
11601 let mut results = Vec::new();
11602 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11603 return vec![];
11604 };
11605
11606 let start_ix = match ranges.binary_search_by(|probe| {
11607 let cmp = probe
11608 .end
11609 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11610 if cmp.is_gt() {
11611 Ordering::Greater
11612 } else {
11613 Ordering::Less
11614 }
11615 }) {
11616 Ok(i) | Err(i) => i,
11617 };
11618 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11619 if let (Some(start_display), Some(end_display)) = (start, end) {
11620 results.push(
11621 start_display.to_display_point(display_snapshot)
11622 ..=end_display.to_display_point(display_snapshot),
11623 );
11624 }
11625 };
11626 let mut start_row: Option<Point> = None;
11627 let mut end_row: Option<Point> = None;
11628 if ranges.len() > count {
11629 return Vec::new();
11630 }
11631 for range in &ranges[start_ix..] {
11632 if range
11633 .start
11634 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11635 .is_ge()
11636 {
11637 break;
11638 }
11639 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11640 if let Some(current_row) = &end_row {
11641 if end.row == current_row.row {
11642 continue;
11643 }
11644 }
11645 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11646 if start_row.is_none() {
11647 assert_eq!(end_row, None);
11648 start_row = Some(start);
11649 end_row = Some(end);
11650 continue;
11651 }
11652 if let Some(current_end) = end_row.as_mut() {
11653 if start.row > current_end.row + 1 {
11654 push_region(start_row, end_row);
11655 start_row = Some(start);
11656 end_row = Some(end);
11657 } else {
11658 // Merge two hunks.
11659 *current_end = end;
11660 }
11661 } else {
11662 unreachable!();
11663 }
11664 }
11665 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11666 push_region(start_row, end_row);
11667 results
11668 }
11669
11670 pub fn gutter_highlights_in_range(
11671 &self,
11672 search_range: Range<Anchor>,
11673 display_snapshot: &DisplaySnapshot,
11674 cx: &AppContext,
11675 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11676 let mut results = Vec::new();
11677 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11678 let color = color_fetcher(cx);
11679 let start_ix = match ranges.binary_search_by(|probe| {
11680 let cmp = probe
11681 .end
11682 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11683 if cmp.is_gt() {
11684 Ordering::Greater
11685 } else {
11686 Ordering::Less
11687 }
11688 }) {
11689 Ok(i) | Err(i) => i,
11690 };
11691 for range in &ranges[start_ix..] {
11692 if range
11693 .start
11694 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11695 .is_ge()
11696 {
11697 break;
11698 }
11699
11700 let start = range.start.to_display_point(display_snapshot);
11701 let end = range.end.to_display_point(display_snapshot);
11702 results.push((start..end, color))
11703 }
11704 }
11705 results
11706 }
11707
11708 /// Get the text ranges corresponding to the redaction query
11709 pub fn redacted_ranges(
11710 &self,
11711 search_range: Range<Anchor>,
11712 display_snapshot: &DisplaySnapshot,
11713 cx: &WindowContext,
11714 ) -> Vec<Range<DisplayPoint>> {
11715 display_snapshot
11716 .buffer_snapshot
11717 .redacted_ranges(search_range, |file| {
11718 if let Some(file) = file {
11719 file.is_private()
11720 && EditorSettings::get(
11721 Some(SettingsLocation {
11722 worktree_id: file.worktree_id(cx),
11723 path: file.path().as_ref(),
11724 }),
11725 cx,
11726 )
11727 .redact_private_values
11728 } else {
11729 false
11730 }
11731 })
11732 .map(|range| {
11733 range.start.to_display_point(display_snapshot)
11734 ..range.end.to_display_point(display_snapshot)
11735 })
11736 .collect()
11737 }
11738
11739 pub fn highlight_text<T: 'static>(
11740 &mut self,
11741 ranges: Vec<Range<Anchor>>,
11742 style: HighlightStyle,
11743 cx: &mut ViewContext<Self>,
11744 ) {
11745 self.display_map.update(cx, |map, _| {
11746 map.highlight_text(TypeId::of::<T>(), ranges, style)
11747 });
11748 cx.notify();
11749 }
11750
11751 pub(crate) fn highlight_inlays<T: 'static>(
11752 &mut self,
11753 highlights: Vec<InlayHighlight>,
11754 style: HighlightStyle,
11755 cx: &mut ViewContext<Self>,
11756 ) {
11757 self.display_map.update(cx, |map, _| {
11758 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11759 });
11760 cx.notify();
11761 }
11762
11763 pub fn text_highlights<'a, T: 'static>(
11764 &'a self,
11765 cx: &'a AppContext,
11766 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11767 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11768 }
11769
11770 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11771 let cleared = self
11772 .display_map
11773 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11774 if cleared {
11775 cx.notify();
11776 }
11777 }
11778
11779 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11780 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11781 && self.focus_handle.is_focused(cx)
11782 }
11783
11784 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11785 self.show_cursor_when_unfocused = is_enabled;
11786 cx.notify();
11787 }
11788
11789 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11790 cx.notify();
11791 }
11792
11793 fn on_buffer_event(
11794 &mut self,
11795 multibuffer: Model<MultiBuffer>,
11796 event: &multi_buffer::Event,
11797 cx: &mut ViewContext<Self>,
11798 ) {
11799 match event {
11800 multi_buffer::Event::Edited {
11801 singleton_buffer_edited,
11802 } => {
11803 self.scrollbar_marker_state.dirty = true;
11804 self.active_indent_guides_state.dirty = true;
11805 self.refresh_active_diagnostics(cx);
11806 self.refresh_code_actions(cx);
11807 if self.has_active_inline_completion(cx) {
11808 self.update_visible_inline_completion(cx);
11809 }
11810 cx.emit(EditorEvent::BufferEdited);
11811 cx.emit(SearchEvent::MatchesInvalidated);
11812 if *singleton_buffer_edited {
11813 if let Some(project) = &self.project {
11814 let project = project.read(cx);
11815 #[allow(clippy::mutable_key_type)]
11816 let languages_affected = multibuffer
11817 .read(cx)
11818 .all_buffers()
11819 .into_iter()
11820 .filter_map(|buffer| {
11821 let buffer = buffer.read(cx);
11822 let language = buffer.language()?;
11823 if project.is_local_or_ssh()
11824 && project.language_servers_for_buffer(buffer, cx).count() == 0
11825 {
11826 None
11827 } else {
11828 Some(language)
11829 }
11830 })
11831 .cloned()
11832 .collect::<HashSet<_>>();
11833 if !languages_affected.is_empty() {
11834 self.refresh_inlay_hints(
11835 InlayHintRefreshReason::BufferEdited(languages_affected),
11836 cx,
11837 );
11838 }
11839 }
11840 }
11841
11842 let Some(project) = &self.project else { return };
11843 let telemetry = project.read(cx).client().telemetry().clone();
11844 refresh_linked_ranges(self, cx);
11845 telemetry.log_edit_event("editor");
11846 }
11847 multi_buffer::Event::ExcerptsAdded {
11848 buffer,
11849 predecessor,
11850 excerpts,
11851 } => {
11852 self.tasks_update_task = Some(self.refresh_runnables(cx));
11853 cx.emit(EditorEvent::ExcerptsAdded {
11854 buffer: buffer.clone(),
11855 predecessor: *predecessor,
11856 excerpts: excerpts.clone(),
11857 });
11858 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11859 }
11860 multi_buffer::Event::ExcerptsRemoved { ids } => {
11861 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11862 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11863 }
11864 multi_buffer::Event::ExcerptsEdited { ids } => {
11865 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11866 }
11867 multi_buffer::Event::ExcerptsExpanded { ids } => {
11868 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11869 }
11870 multi_buffer::Event::Reparsed(buffer_id) => {
11871 self.tasks_update_task = Some(self.refresh_runnables(cx));
11872
11873 cx.emit(EditorEvent::Reparsed(*buffer_id));
11874 }
11875 multi_buffer::Event::LanguageChanged(buffer_id) => {
11876 linked_editing_ranges::refresh_linked_ranges(self, cx);
11877 cx.emit(EditorEvent::Reparsed(*buffer_id));
11878 cx.notify();
11879 }
11880 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11881 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11882 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11883 cx.emit(EditorEvent::TitleChanged)
11884 }
11885 multi_buffer::Event::DiffBaseChanged => {
11886 self.scrollbar_marker_state.dirty = true;
11887 cx.emit(EditorEvent::DiffBaseChanged);
11888 cx.notify();
11889 }
11890 multi_buffer::Event::DiffUpdated { buffer } => {
11891 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11892 cx.notify();
11893 }
11894 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11895 multi_buffer::Event::DiagnosticsUpdated => {
11896 self.refresh_active_diagnostics(cx);
11897 self.scrollbar_marker_state.dirty = true;
11898 cx.notify();
11899 }
11900 _ => {}
11901 };
11902 }
11903
11904 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11905 cx.notify();
11906 }
11907
11908 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11909 self.tasks_update_task = Some(self.refresh_runnables(cx));
11910 self.refresh_inline_completion(true, false, cx);
11911 self.refresh_inlay_hints(
11912 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11913 self.selections.newest_anchor().head(),
11914 &self.buffer.read(cx).snapshot(cx),
11915 cx,
11916 )),
11917 cx,
11918 );
11919 let editor_settings = EditorSettings::get_global(cx);
11920 if let Some(cursor_shape) = editor_settings.cursor_shape {
11921 self.cursor_shape = cursor_shape;
11922 }
11923 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11924 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11925
11926 let project_settings = ProjectSettings::get_global(cx);
11927 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11928
11929 if self.mode == EditorMode::Full {
11930 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11931 if self.git_blame_inline_enabled != inline_blame_enabled {
11932 self.toggle_git_blame_inline_internal(false, cx);
11933 }
11934 }
11935
11936 cx.notify();
11937 }
11938
11939 pub fn set_searchable(&mut self, searchable: bool) {
11940 self.searchable = searchable;
11941 }
11942
11943 pub fn searchable(&self) -> bool {
11944 self.searchable
11945 }
11946
11947 fn open_proposed_changes_editor(
11948 &mut self,
11949 _: &OpenProposedChangesEditor,
11950 cx: &mut ViewContext<Self>,
11951 ) {
11952 let Some(workspace) = self.workspace() else {
11953 cx.propagate();
11954 return;
11955 };
11956
11957 let buffer = self.buffer.read(cx);
11958 let mut new_selections_by_buffer = HashMap::default();
11959 for selection in self.selections.all::<usize>(cx) {
11960 for (buffer, mut range, _) in
11961 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11962 {
11963 if selection.reversed {
11964 mem::swap(&mut range.start, &mut range.end);
11965 }
11966 let mut range = range.to_point(buffer.read(cx));
11967 range.start.column = 0;
11968 range.end.column = buffer.read(cx).line_len(range.end.row);
11969 new_selections_by_buffer
11970 .entry(buffer)
11971 .or_insert(Vec::new())
11972 .push(range)
11973 }
11974 }
11975
11976 let proposed_changes_buffers = new_selections_by_buffer
11977 .into_iter()
11978 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
11979 .collect::<Vec<_>>();
11980 let proposed_changes_editor = cx.new_view(|cx| {
11981 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
11982 });
11983
11984 cx.window_context().defer(move |cx| {
11985 workspace.update(cx, |workspace, cx| {
11986 workspace.active_pane().update(cx, |pane, cx| {
11987 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
11988 });
11989 });
11990 });
11991 }
11992
11993 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11994 self.open_excerpts_common(true, cx)
11995 }
11996
11997 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11998 self.open_excerpts_common(false, cx)
11999 }
12000
12001 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12002 let buffer = self.buffer.read(cx);
12003 if buffer.is_singleton() {
12004 cx.propagate();
12005 return;
12006 }
12007
12008 let Some(workspace) = self.workspace() else {
12009 cx.propagate();
12010 return;
12011 };
12012
12013 let mut new_selections_by_buffer = HashMap::default();
12014 for selection in self.selections.all::<usize>(cx) {
12015 for (buffer, mut range, _) in
12016 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12017 {
12018 if selection.reversed {
12019 mem::swap(&mut range.start, &mut range.end);
12020 }
12021 new_selections_by_buffer
12022 .entry(buffer)
12023 .or_insert(Vec::new())
12024 .push(range)
12025 }
12026 }
12027
12028 // We defer the pane interaction because we ourselves are a workspace item
12029 // and activating a new item causes the pane to call a method on us reentrantly,
12030 // which panics if we're on the stack.
12031 cx.window_context().defer(move |cx| {
12032 workspace.update(cx, |workspace, cx| {
12033 let pane = if split {
12034 workspace.adjacent_pane(cx)
12035 } else {
12036 workspace.active_pane().clone()
12037 };
12038
12039 for (buffer, ranges) in new_selections_by_buffer {
12040 let editor =
12041 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12042 editor.update(cx, |editor, cx| {
12043 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12044 s.select_ranges(ranges);
12045 });
12046 });
12047 }
12048 })
12049 });
12050 }
12051
12052 fn jump(
12053 &mut self,
12054 path: ProjectPath,
12055 position: Point,
12056 anchor: language::Anchor,
12057 offset_from_top: u32,
12058 cx: &mut ViewContext<Self>,
12059 ) {
12060 let workspace = self.workspace();
12061 cx.spawn(|_, mut cx| async move {
12062 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12063 let editor = workspace.update(&mut cx, |workspace, cx| {
12064 // Reset the preview item id before opening the new item
12065 workspace.active_pane().update(cx, |pane, cx| {
12066 pane.set_preview_item_id(None, cx);
12067 });
12068 workspace.open_path_preview(path, None, true, true, cx)
12069 })?;
12070 let editor = editor
12071 .await?
12072 .downcast::<Editor>()
12073 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12074 .downgrade();
12075 editor.update(&mut cx, |editor, cx| {
12076 let buffer = editor
12077 .buffer()
12078 .read(cx)
12079 .as_singleton()
12080 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12081 let buffer = buffer.read(cx);
12082 let cursor = if buffer.can_resolve(&anchor) {
12083 language::ToPoint::to_point(&anchor, buffer)
12084 } else {
12085 buffer.clip_point(position, Bias::Left)
12086 };
12087
12088 let nav_history = editor.nav_history.take();
12089 editor.change_selections(
12090 Some(Autoscroll::top_relative(offset_from_top as usize)),
12091 cx,
12092 |s| {
12093 s.select_ranges([cursor..cursor]);
12094 },
12095 );
12096 editor.nav_history = nav_history;
12097
12098 anyhow::Ok(())
12099 })??;
12100
12101 anyhow::Ok(())
12102 })
12103 .detach_and_log_err(cx);
12104 }
12105
12106 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12107 let snapshot = self.buffer.read(cx).read(cx);
12108 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12109 Some(
12110 ranges
12111 .iter()
12112 .map(move |range| {
12113 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12114 })
12115 .collect(),
12116 )
12117 }
12118
12119 fn selection_replacement_ranges(
12120 &self,
12121 range: Range<OffsetUtf16>,
12122 cx: &AppContext,
12123 ) -> Vec<Range<OffsetUtf16>> {
12124 let selections = self.selections.all::<OffsetUtf16>(cx);
12125 let newest_selection = selections
12126 .iter()
12127 .max_by_key(|selection| selection.id)
12128 .unwrap();
12129 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12130 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12131 let snapshot = self.buffer.read(cx).read(cx);
12132 selections
12133 .into_iter()
12134 .map(|mut selection| {
12135 selection.start.0 =
12136 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12137 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12138 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12139 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12140 })
12141 .collect()
12142 }
12143
12144 fn report_editor_event(
12145 &self,
12146 operation: &'static str,
12147 file_extension: Option<String>,
12148 cx: &AppContext,
12149 ) {
12150 if cfg!(any(test, feature = "test-support")) {
12151 return;
12152 }
12153
12154 let Some(project) = &self.project else { return };
12155
12156 // If None, we are in a file without an extension
12157 let file = self
12158 .buffer
12159 .read(cx)
12160 .as_singleton()
12161 .and_then(|b| b.read(cx).file());
12162 let file_extension = file_extension.or(file
12163 .as_ref()
12164 .and_then(|file| Path::new(file.file_name(cx)).extension())
12165 .and_then(|e| e.to_str())
12166 .map(|a| a.to_string()));
12167
12168 let vim_mode = cx
12169 .global::<SettingsStore>()
12170 .raw_user_settings()
12171 .get("vim_mode")
12172 == Some(&serde_json::Value::Bool(true));
12173
12174 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12175 == language::language_settings::InlineCompletionProvider::Copilot;
12176 let copilot_enabled_for_language = self
12177 .buffer
12178 .read(cx)
12179 .settings_at(0, cx)
12180 .show_inline_completions;
12181
12182 let telemetry = project.read(cx).client().telemetry().clone();
12183 telemetry.report_editor_event(
12184 file_extension,
12185 vim_mode,
12186 operation,
12187 copilot_enabled,
12188 copilot_enabled_for_language,
12189 )
12190 }
12191
12192 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12193 /// with each line being an array of {text, highlight} objects.
12194 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12195 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12196 return;
12197 };
12198
12199 #[derive(Serialize)]
12200 struct Chunk<'a> {
12201 text: String,
12202 highlight: Option<&'a str>,
12203 }
12204
12205 let snapshot = buffer.read(cx).snapshot();
12206 let range = self
12207 .selected_text_range(false, cx)
12208 .and_then(|selection| {
12209 if selection.range.is_empty() {
12210 None
12211 } else {
12212 Some(selection.range)
12213 }
12214 })
12215 .unwrap_or_else(|| 0..snapshot.len());
12216
12217 let chunks = snapshot.chunks(range, true);
12218 let mut lines = Vec::new();
12219 let mut line: VecDeque<Chunk> = VecDeque::new();
12220
12221 let Some(style) = self.style.as_ref() else {
12222 return;
12223 };
12224
12225 for chunk in chunks {
12226 let highlight = chunk
12227 .syntax_highlight_id
12228 .and_then(|id| id.name(&style.syntax));
12229 let mut chunk_lines = chunk.text.split('\n').peekable();
12230 while let Some(text) = chunk_lines.next() {
12231 let mut merged_with_last_token = false;
12232 if let Some(last_token) = line.back_mut() {
12233 if last_token.highlight == highlight {
12234 last_token.text.push_str(text);
12235 merged_with_last_token = true;
12236 }
12237 }
12238
12239 if !merged_with_last_token {
12240 line.push_back(Chunk {
12241 text: text.into(),
12242 highlight,
12243 });
12244 }
12245
12246 if chunk_lines.peek().is_some() {
12247 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12248 line.pop_front();
12249 }
12250 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12251 line.pop_back();
12252 }
12253
12254 lines.push(mem::take(&mut line));
12255 }
12256 }
12257 }
12258
12259 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12260 return;
12261 };
12262 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12263 }
12264
12265 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12266 &self.inlay_hint_cache
12267 }
12268
12269 pub fn replay_insert_event(
12270 &mut self,
12271 text: &str,
12272 relative_utf16_range: Option<Range<isize>>,
12273 cx: &mut ViewContext<Self>,
12274 ) {
12275 if !self.input_enabled {
12276 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12277 return;
12278 }
12279 if let Some(relative_utf16_range) = relative_utf16_range {
12280 let selections = self.selections.all::<OffsetUtf16>(cx);
12281 self.change_selections(None, cx, |s| {
12282 let new_ranges = selections.into_iter().map(|range| {
12283 let start = OffsetUtf16(
12284 range
12285 .head()
12286 .0
12287 .saturating_add_signed(relative_utf16_range.start),
12288 );
12289 let end = OffsetUtf16(
12290 range
12291 .head()
12292 .0
12293 .saturating_add_signed(relative_utf16_range.end),
12294 );
12295 start..end
12296 });
12297 s.select_ranges(new_ranges);
12298 });
12299 }
12300
12301 self.handle_input(text, cx);
12302 }
12303
12304 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12305 let Some(project) = self.project.as_ref() else {
12306 return false;
12307 };
12308 let project = project.read(cx);
12309
12310 let mut supports = false;
12311 self.buffer().read(cx).for_each_buffer(|buffer| {
12312 if !supports {
12313 supports = project
12314 .language_servers_for_buffer(buffer.read(cx), cx)
12315 .any(
12316 |(_, server)| match server.capabilities().inlay_hint_provider {
12317 Some(lsp::OneOf::Left(enabled)) => enabled,
12318 Some(lsp::OneOf::Right(_)) => true,
12319 None => false,
12320 },
12321 )
12322 }
12323 });
12324 supports
12325 }
12326
12327 pub fn focus(&self, cx: &mut WindowContext) {
12328 cx.focus(&self.focus_handle)
12329 }
12330
12331 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12332 self.focus_handle.is_focused(cx)
12333 }
12334
12335 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12336 cx.emit(EditorEvent::Focused);
12337
12338 if let Some(descendant) = self
12339 .last_focused_descendant
12340 .take()
12341 .and_then(|descendant| descendant.upgrade())
12342 {
12343 cx.focus(&descendant);
12344 } else {
12345 if let Some(blame) = self.blame.as_ref() {
12346 blame.update(cx, GitBlame::focus)
12347 }
12348
12349 self.blink_manager.update(cx, BlinkManager::enable);
12350 self.show_cursor_names(cx);
12351 self.buffer.update(cx, |buffer, cx| {
12352 buffer.finalize_last_transaction(cx);
12353 if self.leader_peer_id.is_none() {
12354 buffer.set_active_selections(
12355 &self.selections.disjoint_anchors(),
12356 self.selections.line_mode,
12357 self.cursor_shape,
12358 cx,
12359 );
12360 }
12361 });
12362 }
12363 }
12364
12365 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12366 cx.emit(EditorEvent::FocusedIn)
12367 }
12368
12369 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12370 if event.blurred != self.focus_handle {
12371 self.last_focused_descendant = Some(event.blurred);
12372 }
12373 }
12374
12375 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12376 self.blink_manager.update(cx, BlinkManager::disable);
12377 self.buffer
12378 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12379
12380 if let Some(blame) = self.blame.as_ref() {
12381 blame.update(cx, GitBlame::blur)
12382 }
12383 if !self.hover_state.focused(cx) {
12384 hide_hover(self, cx);
12385 }
12386
12387 self.hide_context_menu(cx);
12388 cx.emit(EditorEvent::Blurred);
12389 cx.notify();
12390 }
12391
12392 pub fn register_action<A: Action>(
12393 &mut self,
12394 listener: impl Fn(&A, &mut WindowContext) + 'static,
12395 ) -> Subscription {
12396 let id = self.next_editor_action_id.post_inc();
12397 let listener = Arc::new(listener);
12398 self.editor_actions.borrow_mut().insert(
12399 id,
12400 Box::new(move |cx| {
12401 let cx = cx.window_context();
12402 let listener = listener.clone();
12403 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12404 let action = action.downcast_ref().unwrap();
12405 if phase == DispatchPhase::Bubble {
12406 listener(action, cx)
12407 }
12408 })
12409 }),
12410 );
12411
12412 let editor_actions = self.editor_actions.clone();
12413 Subscription::new(move || {
12414 editor_actions.borrow_mut().remove(&id);
12415 })
12416 }
12417
12418 pub fn file_header_size(&self) -> u32 {
12419 self.file_header_size
12420 }
12421
12422 pub fn revert(
12423 &mut self,
12424 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12425 cx: &mut ViewContext<Self>,
12426 ) {
12427 self.buffer().update(cx, |multi_buffer, cx| {
12428 for (buffer_id, changes) in revert_changes {
12429 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12430 buffer.update(cx, |buffer, cx| {
12431 buffer.edit(
12432 changes.into_iter().map(|(range, text)| {
12433 (range, text.to_string().map(Arc::<str>::from))
12434 }),
12435 None,
12436 cx,
12437 );
12438 });
12439 }
12440 }
12441 });
12442 self.change_selections(None, cx, |selections| selections.refresh());
12443 }
12444
12445 pub fn to_pixel_point(
12446 &mut self,
12447 source: multi_buffer::Anchor,
12448 editor_snapshot: &EditorSnapshot,
12449 cx: &mut ViewContext<Self>,
12450 ) -> Option<gpui::Point<Pixels>> {
12451 let source_point = source.to_display_point(editor_snapshot);
12452 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12453 }
12454
12455 pub fn display_to_pixel_point(
12456 &mut self,
12457 source: DisplayPoint,
12458 editor_snapshot: &EditorSnapshot,
12459 cx: &mut ViewContext<Self>,
12460 ) -> Option<gpui::Point<Pixels>> {
12461 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12462 let text_layout_details = self.text_layout_details(cx);
12463 let scroll_top = text_layout_details
12464 .scroll_anchor
12465 .scroll_position(editor_snapshot)
12466 .y;
12467
12468 if source.row().as_f32() < scroll_top.floor() {
12469 return None;
12470 }
12471 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12472 let source_y = line_height * (source.row().as_f32() - scroll_top);
12473 Some(gpui::Point::new(source_x, source_y))
12474 }
12475
12476 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12477 let bounds = self.last_bounds?;
12478 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12479 }
12480
12481 pub fn has_active_completions_menu(&self) -> bool {
12482 self.context_menu.read().as_ref().map_or(false, |menu| {
12483 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12484 })
12485 }
12486
12487 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12488 self.addons
12489 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12490 }
12491
12492 pub fn unregister_addon<T: Addon>(&mut self) {
12493 self.addons.remove(&std::any::TypeId::of::<T>());
12494 }
12495
12496 pub fn addon<T: Addon>(&self) -> Option<&T> {
12497 let type_id = std::any::TypeId::of::<T>();
12498 self.addons
12499 .get(&type_id)
12500 .and_then(|item| item.to_any().downcast_ref::<T>())
12501 }
12502}
12503
12504fn hunks_for_selections(
12505 multi_buffer_snapshot: &MultiBufferSnapshot,
12506 selections: &[Selection<Anchor>],
12507) -> Vec<MultiBufferDiffHunk> {
12508 let buffer_rows_for_selections = selections.iter().map(|selection| {
12509 let head = selection.head();
12510 let tail = selection.tail();
12511 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12512 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12513 if start > end {
12514 end..start
12515 } else {
12516 start..end
12517 }
12518 });
12519
12520 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12521}
12522
12523pub fn hunks_for_rows(
12524 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12525 multi_buffer_snapshot: &MultiBufferSnapshot,
12526) -> Vec<MultiBufferDiffHunk> {
12527 let mut hunks = Vec::new();
12528 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12529 HashMap::default();
12530 for selected_multi_buffer_rows in rows {
12531 let query_rows =
12532 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12533 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12534 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12535 // when the caret is just above or just below the deleted hunk.
12536 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12537 let related_to_selection = if allow_adjacent {
12538 hunk.row_range.overlaps(&query_rows)
12539 || hunk.row_range.start == query_rows.end
12540 || hunk.row_range.end == query_rows.start
12541 } else {
12542 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12543 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12544 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12545 || selected_multi_buffer_rows.end == hunk.row_range.start
12546 };
12547 if related_to_selection {
12548 if !processed_buffer_rows
12549 .entry(hunk.buffer_id)
12550 .or_default()
12551 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12552 {
12553 continue;
12554 }
12555 hunks.push(hunk);
12556 }
12557 }
12558 }
12559
12560 hunks
12561}
12562
12563pub trait CollaborationHub {
12564 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12565 fn user_participant_indices<'a>(
12566 &self,
12567 cx: &'a AppContext,
12568 ) -> &'a HashMap<u64, ParticipantIndex>;
12569 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12570}
12571
12572impl CollaborationHub for Model<Project> {
12573 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12574 self.read(cx).collaborators()
12575 }
12576
12577 fn user_participant_indices<'a>(
12578 &self,
12579 cx: &'a AppContext,
12580 ) -> &'a HashMap<u64, ParticipantIndex> {
12581 self.read(cx).user_store().read(cx).participant_indices()
12582 }
12583
12584 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12585 let this = self.read(cx);
12586 let user_ids = this.collaborators().values().map(|c| c.user_id);
12587 this.user_store().read_with(cx, |user_store, cx| {
12588 user_store.participant_names(user_ids, cx)
12589 })
12590 }
12591}
12592
12593pub trait CompletionProvider {
12594 fn completions(
12595 &self,
12596 buffer: &Model<Buffer>,
12597 buffer_position: text::Anchor,
12598 trigger: CompletionContext,
12599 cx: &mut ViewContext<Editor>,
12600 ) -> Task<Result<Vec<Completion>>>;
12601
12602 fn resolve_completions(
12603 &self,
12604 buffer: Model<Buffer>,
12605 completion_indices: Vec<usize>,
12606 completions: Arc<RwLock<Box<[Completion]>>>,
12607 cx: &mut ViewContext<Editor>,
12608 ) -> Task<Result<bool>>;
12609
12610 fn apply_additional_edits_for_completion(
12611 &self,
12612 buffer: Model<Buffer>,
12613 completion: Completion,
12614 push_to_history: bool,
12615 cx: &mut ViewContext<Editor>,
12616 ) -> Task<Result<Option<language::Transaction>>>;
12617
12618 fn is_completion_trigger(
12619 &self,
12620 buffer: &Model<Buffer>,
12621 position: language::Anchor,
12622 text: &str,
12623 trigger_in_words: bool,
12624 cx: &mut ViewContext<Editor>,
12625 ) -> bool;
12626
12627 fn sort_completions(&self) -> bool {
12628 true
12629 }
12630}
12631
12632pub trait CodeActionProvider {
12633 fn code_actions(
12634 &self,
12635 buffer: &Model<Buffer>,
12636 range: Range<text::Anchor>,
12637 cx: &mut WindowContext,
12638 ) -> Task<Result<Vec<CodeAction>>>;
12639
12640 fn apply_code_action(
12641 &self,
12642 buffer_handle: Model<Buffer>,
12643 action: CodeAction,
12644 excerpt_id: ExcerptId,
12645 push_to_history: bool,
12646 cx: &mut WindowContext,
12647 ) -> Task<Result<ProjectTransaction>>;
12648}
12649
12650impl CodeActionProvider for Model<Project> {
12651 fn code_actions(
12652 &self,
12653 buffer: &Model<Buffer>,
12654 range: Range<text::Anchor>,
12655 cx: &mut WindowContext,
12656 ) -> Task<Result<Vec<CodeAction>>> {
12657 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12658 }
12659
12660 fn apply_code_action(
12661 &self,
12662 buffer_handle: Model<Buffer>,
12663 action: CodeAction,
12664 _excerpt_id: ExcerptId,
12665 push_to_history: bool,
12666 cx: &mut WindowContext,
12667 ) -> Task<Result<ProjectTransaction>> {
12668 self.update(cx, |project, cx| {
12669 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12670 })
12671 }
12672}
12673
12674fn snippet_completions(
12675 project: &Project,
12676 buffer: &Model<Buffer>,
12677 buffer_position: text::Anchor,
12678 cx: &mut AppContext,
12679) -> Vec<Completion> {
12680 let language = buffer.read(cx).language_at(buffer_position);
12681 let language_name = language.as_ref().map(|language| language.lsp_id());
12682 let snippet_store = project.snippets().read(cx);
12683 let snippets = snippet_store.snippets_for(language_name, cx);
12684
12685 if snippets.is_empty() {
12686 return vec![];
12687 }
12688 let snapshot = buffer.read(cx).text_snapshot();
12689 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12690
12691 let mut lines = chunks.lines();
12692 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12693 return vec![];
12694 };
12695
12696 let scope = language.map(|language| language.default_scope());
12697 let classifier = CharClassifier::new(scope).for_completion(true);
12698 let mut last_word = line_at
12699 .chars()
12700 .rev()
12701 .take_while(|c| classifier.is_word(*c))
12702 .collect::<String>();
12703 last_word = last_word.chars().rev().collect();
12704 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12705 let to_lsp = |point: &text::Anchor| {
12706 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12707 point_to_lsp(end)
12708 };
12709 let lsp_end = to_lsp(&buffer_position);
12710 snippets
12711 .into_iter()
12712 .filter_map(|snippet| {
12713 let matching_prefix = snippet
12714 .prefix
12715 .iter()
12716 .find(|prefix| prefix.starts_with(&last_word))?;
12717 let start = as_offset - last_word.len();
12718 let start = snapshot.anchor_before(start);
12719 let range = start..buffer_position;
12720 let lsp_start = to_lsp(&start);
12721 let lsp_range = lsp::Range {
12722 start: lsp_start,
12723 end: lsp_end,
12724 };
12725 Some(Completion {
12726 old_range: range,
12727 new_text: snippet.body.clone(),
12728 label: CodeLabel {
12729 text: matching_prefix.clone(),
12730 runs: vec![],
12731 filter_range: 0..matching_prefix.len(),
12732 },
12733 server_id: LanguageServerId(usize::MAX),
12734 documentation: snippet.description.clone().map(Documentation::SingleLine),
12735 lsp_completion: lsp::CompletionItem {
12736 label: snippet.prefix.first().unwrap().clone(),
12737 kind: Some(CompletionItemKind::SNIPPET),
12738 label_details: snippet.description.as_ref().map(|description| {
12739 lsp::CompletionItemLabelDetails {
12740 detail: Some(description.clone()),
12741 description: None,
12742 }
12743 }),
12744 insert_text_format: Some(InsertTextFormat::SNIPPET),
12745 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12746 lsp::InsertReplaceEdit {
12747 new_text: snippet.body.clone(),
12748 insert: lsp_range,
12749 replace: lsp_range,
12750 },
12751 )),
12752 filter_text: Some(snippet.body.clone()),
12753 sort_text: Some(char::MAX.to_string()),
12754 ..Default::default()
12755 },
12756 confirm: None,
12757 })
12758 })
12759 .collect()
12760}
12761
12762impl CompletionProvider for Model<Project> {
12763 fn completions(
12764 &self,
12765 buffer: &Model<Buffer>,
12766 buffer_position: text::Anchor,
12767 options: CompletionContext,
12768 cx: &mut ViewContext<Editor>,
12769 ) -> Task<Result<Vec<Completion>>> {
12770 self.update(cx, |project, cx| {
12771 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12772 let project_completions = project.completions(buffer, buffer_position, options, cx);
12773 cx.background_executor().spawn(async move {
12774 let mut completions = project_completions.await?;
12775 //let snippets = snippets.into_iter().;
12776 completions.extend(snippets);
12777 Ok(completions)
12778 })
12779 })
12780 }
12781
12782 fn resolve_completions(
12783 &self,
12784 buffer: Model<Buffer>,
12785 completion_indices: Vec<usize>,
12786 completions: Arc<RwLock<Box<[Completion]>>>,
12787 cx: &mut ViewContext<Editor>,
12788 ) -> Task<Result<bool>> {
12789 self.update(cx, |project, cx| {
12790 project.resolve_completions(buffer, completion_indices, completions, cx)
12791 })
12792 }
12793
12794 fn apply_additional_edits_for_completion(
12795 &self,
12796 buffer: Model<Buffer>,
12797 completion: Completion,
12798 push_to_history: bool,
12799 cx: &mut ViewContext<Editor>,
12800 ) -> Task<Result<Option<language::Transaction>>> {
12801 self.update(cx, |project, cx| {
12802 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12803 })
12804 }
12805
12806 fn is_completion_trigger(
12807 &self,
12808 buffer: &Model<Buffer>,
12809 position: language::Anchor,
12810 text: &str,
12811 trigger_in_words: bool,
12812 cx: &mut ViewContext<Editor>,
12813 ) -> bool {
12814 if !EditorSettings::get_global(cx).show_completions_on_input {
12815 return false;
12816 }
12817
12818 let mut chars = text.chars();
12819 let char = if let Some(char) = chars.next() {
12820 char
12821 } else {
12822 return false;
12823 };
12824 if chars.next().is_some() {
12825 return false;
12826 }
12827
12828 let buffer = buffer.read(cx);
12829 let classifier = buffer
12830 .snapshot()
12831 .char_classifier_at(position)
12832 .for_completion(true);
12833 if trigger_in_words && classifier.is_word(char) {
12834 return true;
12835 }
12836
12837 buffer
12838 .completion_triggers()
12839 .iter()
12840 .any(|string| string == text)
12841 }
12842}
12843
12844fn inlay_hint_settings(
12845 location: Anchor,
12846 snapshot: &MultiBufferSnapshot,
12847 cx: &mut ViewContext<'_, Editor>,
12848) -> InlayHintSettings {
12849 let file = snapshot.file_at(location);
12850 let language = snapshot.language_at(location);
12851 let settings = all_language_settings(file, cx);
12852 settings
12853 .language(language.map(|l| l.name()).as_ref())
12854 .inlay_hints
12855}
12856
12857fn consume_contiguous_rows(
12858 contiguous_row_selections: &mut Vec<Selection<Point>>,
12859 selection: &Selection<Point>,
12860 display_map: &DisplaySnapshot,
12861 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12862) -> (MultiBufferRow, MultiBufferRow) {
12863 contiguous_row_selections.push(selection.clone());
12864 let start_row = MultiBufferRow(selection.start.row);
12865 let mut end_row = ending_row(selection, display_map);
12866
12867 while let Some(next_selection) = selections.peek() {
12868 if next_selection.start.row <= end_row.0 {
12869 end_row = ending_row(next_selection, display_map);
12870 contiguous_row_selections.push(selections.next().unwrap().clone());
12871 } else {
12872 break;
12873 }
12874 }
12875 (start_row, end_row)
12876}
12877
12878fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12879 if next_selection.end.column > 0 || next_selection.is_empty() {
12880 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12881 } else {
12882 MultiBufferRow(next_selection.end.row)
12883 }
12884}
12885
12886impl EditorSnapshot {
12887 pub fn remote_selections_in_range<'a>(
12888 &'a self,
12889 range: &'a Range<Anchor>,
12890 collaboration_hub: &dyn CollaborationHub,
12891 cx: &'a AppContext,
12892 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12893 let participant_names = collaboration_hub.user_names(cx);
12894 let participant_indices = collaboration_hub.user_participant_indices(cx);
12895 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12896 let collaborators_by_replica_id = collaborators_by_peer_id
12897 .iter()
12898 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12899 .collect::<HashMap<_, _>>();
12900 self.buffer_snapshot
12901 .selections_in_range(range, false)
12902 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12903 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12904 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12905 let user_name = participant_names.get(&collaborator.user_id).cloned();
12906 Some(RemoteSelection {
12907 replica_id,
12908 selection,
12909 cursor_shape,
12910 line_mode,
12911 participant_index,
12912 peer_id: collaborator.peer_id,
12913 user_name,
12914 })
12915 })
12916 }
12917
12918 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12919 self.display_snapshot.buffer_snapshot.language_at(position)
12920 }
12921
12922 pub fn is_focused(&self) -> bool {
12923 self.is_focused
12924 }
12925
12926 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12927 self.placeholder_text.as_ref()
12928 }
12929
12930 pub fn scroll_position(&self) -> gpui::Point<f32> {
12931 self.scroll_anchor.scroll_position(&self.display_snapshot)
12932 }
12933
12934 fn gutter_dimensions(
12935 &self,
12936 font_id: FontId,
12937 font_size: Pixels,
12938 em_width: Pixels,
12939 max_line_number_width: Pixels,
12940 cx: &AppContext,
12941 ) -> GutterDimensions {
12942 if !self.show_gutter {
12943 return GutterDimensions::default();
12944 }
12945 let descent = cx.text_system().descent(font_id, font_size);
12946
12947 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12948 matches!(
12949 ProjectSettings::get_global(cx).git.git_gutter,
12950 Some(GitGutterSetting::TrackedFiles)
12951 )
12952 });
12953 let gutter_settings = EditorSettings::get_global(cx).gutter;
12954 let show_line_numbers = self
12955 .show_line_numbers
12956 .unwrap_or(gutter_settings.line_numbers);
12957 let line_gutter_width = if show_line_numbers {
12958 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12959 let min_width_for_number_on_gutter = em_width * 4.0;
12960 max_line_number_width.max(min_width_for_number_on_gutter)
12961 } else {
12962 0.0.into()
12963 };
12964
12965 let show_code_actions = self
12966 .show_code_actions
12967 .unwrap_or(gutter_settings.code_actions);
12968
12969 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12970
12971 let git_blame_entries_width = self
12972 .render_git_blame_gutter
12973 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12974
12975 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12976 left_padding += if show_code_actions || show_runnables {
12977 em_width * 3.0
12978 } else if show_git_gutter && show_line_numbers {
12979 em_width * 2.0
12980 } else if show_git_gutter || show_line_numbers {
12981 em_width
12982 } else {
12983 px(0.)
12984 };
12985
12986 let right_padding = if gutter_settings.folds && show_line_numbers {
12987 em_width * 4.0
12988 } else if gutter_settings.folds {
12989 em_width * 3.0
12990 } else if show_line_numbers {
12991 em_width
12992 } else {
12993 px(0.)
12994 };
12995
12996 GutterDimensions {
12997 left_padding,
12998 right_padding,
12999 width: line_gutter_width + left_padding + right_padding,
13000 margin: -descent,
13001 git_blame_entries_width,
13002 }
13003 }
13004
13005 pub fn render_fold_toggle(
13006 &self,
13007 buffer_row: MultiBufferRow,
13008 row_contains_cursor: bool,
13009 editor: View<Editor>,
13010 cx: &mut WindowContext,
13011 ) -> Option<AnyElement> {
13012 let folded = self.is_line_folded(buffer_row);
13013
13014 if let Some(crease) = self
13015 .crease_snapshot
13016 .query_row(buffer_row, &self.buffer_snapshot)
13017 {
13018 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13019 if folded {
13020 editor.update(cx, |editor, cx| {
13021 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13022 });
13023 } else {
13024 editor.update(cx, |editor, cx| {
13025 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13026 });
13027 }
13028 });
13029
13030 Some((crease.render_toggle)(
13031 buffer_row,
13032 folded,
13033 toggle_callback,
13034 cx,
13035 ))
13036 } else if folded
13037 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13038 {
13039 Some(
13040 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13041 .selected(folded)
13042 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13043 if folded {
13044 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13045 } else {
13046 this.fold_at(&FoldAt { buffer_row }, cx);
13047 }
13048 }))
13049 .into_any_element(),
13050 )
13051 } else {
13052 None
13053 }
13054 }
13055
13056 pub fn render_crease_trailer(
13057 &self,
13058 buffer_row: MultiBufferRow,
13059 cx: &mut WindowContext,
13060 ) -> Option<AnyElement> {
13061 let folded = self.is_line_folded(buffer_row);
13062 let crease = self
13063 .crease_snapshot
13064 .query_row(buffer_row, &self.buffer_snapshot)?;
13065 Some((crease.render_trailer)(buffer_row, folded, cx))
13066 }
13067}
13068
13069impl Deref for EditorSnapshot {
13070 type Target = DisplaySnapshot;
13071
13072 fn deref(&self) -> &Self::Target {
13073 &self.display_snapshot
13074 }
13075}
13076
13077#[derive(Clone, Debug, PartialEq, Eq)]
13078pub enum EditorEvent {
13079 InputIgnored {
13080 text: Arc<str>,
13081 },
13082 InputHandled {
13083 utf16_range_to_replace: Option<Range<isize>>,
13084 text: Arc<str>,
13085 },
13086 ExcerptsAdded {
13087 buffer: Model<Buffer>,
13088 predecessor: ExcerptId,
13089 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13090 },
13091 ExcerptsRemoved {
13092 ids: Vec<ExcerptId>,
13093 },
13094 ExcerptsEdited {
13095 ids: Vec<ExcerptId>,
13096 },
13097 ExcerptsExpanded {
13098 ids: Vec<ExcerptId>,
13099 },
13100 BufferEdited,
13101 Edited {
13102 transaction_id: clock::Lamport,
13103 },
13104 Reparsed(BufferId),
13105 Focused,
13106 FocusedIn,
13107 Blurred,
13108 DirtyChanged,
13109 Saved,
13110 TitleChanged,
13111 DiffBaseChanged,
13112 SelectionsChanged {
13113 local: bool,
13114 },
13115 ScrollPositionChanged {
13116 local: bool,
13117 autoscroll: bool,
13118 },
13119 Closed,
13120 TransactionUndone {
13121 transaction_id: clock::Lamport,
13122 },
13123 TransactionBegun {
13124 transaction_id: clock::Lamport,
13125 },
13126}
13127
13128impl EventEmitter<EditorEvent> for Editor {}
13129
13130impl FocusableView for Editor {
13131 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13132 self.focus_handle.clone()
13133 }
13134}
13135
13136impl Render for Editor {
13137 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13138 let settings = ThemeSettings::get_global(cx);
13139
13140 let text_style = match self.mode {
13141 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13142 color: cx.theme().colors().editor_foreground,
13143 font_family: settings.ui_font.family.clone(),
13144 font_features: settings.ui_font.features.clone(),
13145 font_fallbacks: settings.ui_font.fallbacks.clone(),
13146 font_size: rems(0.875).into(),
13147 font_weight: settings.ui_font.weight,
13148 line_height: relative(settings.buffer_line_height.value()),
13149 ..Default::default()
13150 },
13151 EditorMode::Full => TextStyle {
13152 color: cx.theme().colors().editor_foreground,
13153 font_family: settings.buffer_font.family.clone(),
13154 font_features: settings.buffer_font.features.clone(),
13155 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13156 font_size: settings.buffer_font_size(cx).into(),
13157 font_weight: settings.buffer_font.weight,
13158 line_height: relative(settings.buffer_line_height.value()),
13159 ..Default::default()
13160 },
13161 };
13162
13163 let background = match self.mode {
13164 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13165 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13166 EditorMode::Full => cx.theme().colors().editor_background,
13167 };
13168
13169 EditorElement::new(
13170 cx.view(),
13171 EditorStyle {
13172 background,
13173 local_player: cx.theme().players().local(),
13174 text: text_style,
13175 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13176 syntax: cx.theme().syntax().clone(),
13177 status: cx.theme().status().clone(),
13178 inlay_hints_style: make_inlay_hints_style(cx),
13179 suggestions_style: HighlightStyle {
13180 color: Some(cx.theme().status().predictive),
13181 ..HighlightStyle::default()
13182 },
13183 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13184 },
13185 )
13186 }
13187}
13188
13189impl ViewInputHandler for Editor {
13190 fn text_for_range(
13191 &mut self,
13192 range_utf16: Range<usize>,
13193 cx: &mut ViewContext<Self>,
13194 ) -> Option<String> {
13195 Some(
13196 self.buffer
13197 .read(cx)
13198 .read(cx)
13199 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13200 .collect(),
13201 )
13202 }
13203
13204 fn selected_text_range(
13205 &mut self,
13206 ignore_disabled_input: bool,
13207 cx: &mut ViewContext<Self>,
13208 ) -> Option<UTF16Selection> {
13209 // Prevent the IME menu from appearing when holding down an alphabetic key
13210 // while input is disabled.
13211 if !ignore_disabled_input && !self.input_enabled {
13212 return None;
13213 }
13214
13215 let selection = self.selections.newest::<OffsetUtf16>(cx);
13216 let range = selection.range();
13217
13218 Some(UTF16Selection {
13219 range: range.start.0..range.end.0,
13220 reversed: selection.reversed,
13221 })
13222 }
13223
13224 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13225 let snapshot = self.buffer.read(cx).read(cx);
13226 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13227 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13228 }
13229
13230 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13231 self.clear_highlights::<InputComposition>(cx);
13232 self.ime_transaction.take();
13233 }
13234
13235 fn replace_text_in_range(
13236 &mut self,
13237 range_utf16: Option<Range<usize>>,
13238 text: &str,
13239 cx: &mut ViewContext<Self>,
13240 ) {
13241 if !self.input_enabled {
13242 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13243 return;
13244 }
13245
13246 self.transact(cx, |this, cx| {
13247 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13248 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13249 Some(this.selection_replacement_ranges(range_utf16, cx))
13250 } else {
13251 this.marked_text_ranges(cx)
13252 };
13253
13254 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13255 let newest_selection_id = this.selections.newest_anchor().id;
13256 this.selections
13257 .all::<OffsetUtf16>(cx)
13258 .iter()
13259 .zip(ranges_to_replace.iter())
13260 .find_map(|(selection, range)| {
13261 if selection.id == newest_selection_id {
13262 Some(
13263 (range.start.0 as isize - selection.head().0 as isize)
13264 ..(range.end.0 as isize - selection.head().0 as isize),
13265 )
13266 } else {
13267 None
13268 }
13269 })
13270 });
13271
13272 cx.emit(EditorEvent::InputHandled {
13273 utf16_range_to_replace: range_to_replace,
13274 text: text.into(),
13275 });
13276
13277 if let Some(new_selected_ranges) = new_selected_ranges {
13278 this.change_selections(None, cx, |selections| {
13279 selections.select_ranges(new_selected_ranges)
13280 });
13281 this.backspace(&Default::default(), cx);
13282 }
13283
13284 this.handle_input(text, cx);
13285 });
13286
13287 if let Some(transaction) = self.ime_transaction {
13288 self.buffer.update(cx, |buffer, cx| {
13289 buffer.group_until_transaction(transaction, cx);
13290 });
13291 }
13292
13293 self.unmark_text(cx);
13294 }
13295
13296 fn replace_and_mark_text_in_range(
13297 &mut self,
13298 range_utf16: Option<Range<usize>>,
13299 text: &str,
13300 new_selected_range_utf16: Option<Range<usize>>,
13301 cx: &mut ViewContext<Self>,
13302 ) {
13303 if !self.input_enabled {
13304 return;
13305 }
13306
13307 let transaction = self.transact(cx, |this, cx| {
13308 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13309 let snapshot = this.buffer.read(cx).read(cx);
13310 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13311 for marked_range in &mut marked_ranges {
13312 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13313 marked_range.start.0 += relative_range_utf16.start;
13314 marked_range.start =
13315 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13316 marked_range.end =
13317 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13318 }
13319 }
13320 Some(marked_ranges)
13321 } else if let Some(range_utf16) = range_utf16 {
13322 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13323 Some(this.selection_replacement_ranges(range_utf16, cx))
13324 } else {
13325 None
13326 };
13327
13328 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13329 let newest_selection_id = this.selections.newest_anchor().id;
13330 this.selections
13331 .all::<OffsetUtf16>(cx)
13332 .iter()
13333 .zip(ranges_to_replace.iter())
13334 .find_map(|(selection, range)| {
13335 if selection.id == newest_selection_id {
13336 Some(
13337 (range.start.0 as isize - selection.head().0 as isize)
13338 ..(range.end.0 as isize - selection.head().0 as isize),
13339 )
13340 } else {
13341 None
13342 }
13343 })
13344 });
13345
13346 cx.emit(EditorEvent::InputHandled {
13347 utf16_range_to_replace: range_to_replace,
13348 text: text.into(),
13349 });
13350
13351 if let Some(ranges) = ranges_to_replace {
13352 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13353 }
13354
13355 let marked_ranges = {
13356 let snapshot = this.buffer.read(cx).read(cx);
13357 this.selections
13358 .disjoint_anchors()
13359 .iter()
13360 .map(|selection| {
13361 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13362 })
13363 .collect::<Vec<_>>()
13364 };
13365
13366 if text.is_empty() {
13367 this.unmark_text(cx);
13368 } else {
13369 this.highlight_text::<InputComposition>(
13370 marked_ranges.clone(),
13371 HighlightStyle {
13372 underline: Some(UnderlineStyle {
13373 thickness: px(1.),
13374 color: None,
13375 wavy: false,
13376 }),
13377 ..Default::default()
13378 },
13379 cx,
13380 );
13381 }
13382
13383 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13384 let use_autoclose = this.use_autoclose;
13385 let use_auto_surround = this.use_auto_surround;
13386 this.set_use_autoclose(false);
13387 this.set_use_auto_surround(false);
13388 this.handle_input(text, cx);
13389 this.set_use_autoclose(use_autoclose);
13390 this.set_use_auto_surround(use_auto_surround);
13391
13392 if let Some(new_selected_range) = new_selected_range_utf16 {
13393 let snapshot = this.buffer.read(cx).read(cx);
13394 let new_selected_ranges = marked_ranges
13395 .into_iter()
13396 .map(|marked_range| {
13397 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13398 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13399 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13400 snapshot.clip_offset_utf16(new_start, Bias::Left)
13401 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13402 })
13403 .collect::<Vec<_>>();
13404
13405 drop(snapshot);
13406 this.change_selections(None, cx, |selections| {
13407 selections.select_ranges(new_selected_ranges)
13408 });
13409 }
13410 });
13411
13412 self.ime_transaction = self.ime_transaction.or(transaction);
13413 if let Some(transaction) = self.ime_transaction {
13414 self.buffer.update(cx, |buffer, cx| {
13415 buffer.group_until_transaction(transaction, cx);
13416 });
13417 }
13418
13419 if self.text_highlights::<InputComposition>(cx).is_none() {
13420 self.ime_transaction.take();
13421 }
13422 }
13423
13424 fn bounds_for_range(
13425 &mut self,
13426 range_utf16: Range<usize>,
13427 element_bounds: gpui::Bounds<Pixels>,
13428 cx: &mut ViewContext<Self>,
13429 ) -> Option<gpui::Bounds<Pixels>> {
13430 let text_layout_details = self.text_layout_details(cx);
13431 let style = &text_layout_details.editor_style;
13432 let font_id = cx.text_system().resolve_font(&style.text.font());
13433 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13434 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13435
13436 let em_width = cx
13437 .text_system()
13438 .typographic_bounds(font_id, font_size, 'm')
13439 .unwrap()
13440 .size
13441 .width;
13442
13443 let snapshot = self.snapshot(cx);
13444 let scroll_position = snapshot.scroll_position();
13445 let scroll_left = scroll_position.x * em_width;
13446
13447 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13448 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13449 + self.gutter_dimensions.width;
13450 let y = line_height * (start.row().as_f32() - scroll_position.y);
13451
13452 Some(Bounds {
13453 origin: element_bounds.origin + point(x, y),
13454 size: size(em_width, line_height),
13455 })
13456 }
13457}
13458
13459trait SelectionExt {
13460 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13461 fn spanned_rows(
13462 &self,
13463 include_end_if_at_line_start: bool,
13464 map: &DisplaySnapshot,
13465 ) -> Range<MultiBufferRow>;
13466}
13467
13468impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13469 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13470 let start = self
13471 .start
13472 .to_point(&map.buffer_snapshot)
13473 .to_display_point(map);
13474 let end = self
13475 .end
13476 .to_point(&map.buffer_snapshot)
13477 .to_display_point(map);
13478 if self.reversed {
13479 end..start
13480 } else {
13481 start..end
13482 }
13483 }
13484
13485 fn spanned_rows(
13486 &self,
13487 include_end_if_at_line_start: bool,
13488 map: &DisplaySnapshot,
13489 ) -> Range<MultiBufferRow> {
13490 let start = self.start.to_point(&map.buffer_snapshot);
13491 let mut end = self.end.to_point(&map.buffer_snapshot);
13492 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13493 end.row -= 1;
13494 }
13495
13496 let buffer_start = map.prev_line_boundary(start).0;
13497 let buffer_end = map.next_line_boundary(end).0;
13498 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13499 }
13500}
13501
13502impl<T: InvalidationRegion> InvalidationStack<T> {
13503 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13504 where
13505 S: Clone + ToOffset,
13506 {
13507 while let Some(region) = self.last() {
13508 let all_selections_inside_invalidation_ranges =
13509 if selections.len() == region.ranges().len() {
13510 selections
13511 .iter()
13512 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13513 .all(|(selection, invalidation_range)| {
13514 let head = selection.head().to_offset(buffer);
13515 invalidation_range.start <= head && invalidation_range.end >= head
13516 })
13517 } else {
13518 false
13519 };
13520
13521 if all_selections_inside_invalidation_ranges {
13522 break;
13523 } else {
13524 self.pop();
13525 }
13526 }
13527 }
13528}
13529
13530impl<T> Default for InvalidationStack<T> {
13531 fn default() -> Self {
13532 Self(Default::default())
13533 }
13534}
13535
13536impl<T> Deref for InvalidationStack<T> {
13537 type Target = Vec<T>;
13538
13539 fn deref(&self) -> &Self::Target {
13540 &self.0
13541 }
13542}
13543
13544impl<T> DerefMut for InvalidationStack<T> {
13545 fn deref_mut(&mut self) -> &mut Self::Target {
13546 &mut self.0
13547 }
13548}
13549
13550impl InvalidationRegion for SnippetState {
13551 fn ranges(&self) -> &[Range<Anchor>] {
13552 &self.ranges[self.active_index]
13553 }
13554}
13555
13556pub fn diagnostic_block_renderer(
13557 diagnostic: Diagnostic,
13558 max_message_rows: Option<u8>,
13559 allow_closing: bool,
13560 _is_valid: bool,
13561) -> RenderBlock {
13562 let (text_without_backticks, code_ranges) =
13563 highlight_diagnostic_message(&diagnostic, max_message_rows);
13564
13565 Box::new(move |cx: &mut BlockContext| {
13566 let group_id: SharedString = cx.block_id.to_string().into();
13567
13568 let mut text_style = cx.text_style().clone();
13569 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13570 let theme_settings = ThemeSettings::get_global(cx);
13571 text_style.font_family = theme_settings.buffer_font.family.clone();
13572 text_style.font_style = theme_settings.buffer_font.style;
13573 text_style.font_features = theme_settings.buffer_font.features.clone();
13574 text_style.font_weight = theme_settings.buffer_font.weight;
13575
13576 let multi_line_diagnostic = diagnostic.message.contains('\n');
13577
13578 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13579 if multi_line_diagnostic {
13580 v_flex()
13581 } else {
13582 h_flex()
13583 }
13584 .when(allow_closing, |div| {
13585 div.children(diagnostic.is_primary.then(|| {
13586 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13587 .icon_color(Color::Muted)
13588 .size(ButtonSize::Compact)
13589 .style(ButtonStyle::Transparent)
13590 .visible_on_hover(group_id.clone())
13591 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13592 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13593 }))
13594 })
13595 .child(
13596 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13597 .icon_color(Color::Muted)
13598 .size(ButtonSize::Compact)
13599 .style(ButtonStyle::Transparent)
13600 .visible_on_hover(group_id.clone())
13601 .on_click({
13602 let message = diagnostic.message.clone();
13603 move |_click, cx| {
13604 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13605 }
13606 })
13607 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13608 )
13609 };
13610
13611 let icon_size = buttons(&diagnostic, cx.block_id)
13612 .into_any_element()
13613 .layout_as_root(AvailableSpace::min_size(), cx);
13614
13615 h_flex()
13616 .id(cx.block_id)
13617 .group(group_id.clone())
13618 .relative()
13619 .size_full()
13620 .pl(cx.gutter_dimensions.width)
13621 .w(cx.max_width + cx.gutter_dimensions.width)
13622 .child(
13623 div()
13624 .flex()
13625 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13626 .flex_shrink(),
13627 )
13628 .child(buttons(&diagnostic, cx.block_id))
13629 .child(div().flex().flex_shrink_0().child(
13630 StyledText::new(text_without_backticks.clone()).with_highlights(
13631 &text_style,
13632 code_ranges.iter().map(|range| {
13633 (
13634 range.clone(),
13635 HighlightStyle {
13636 font_weight: Some(FontWeight::BOLD),
13637 ..Default::default()
13638 },
13639 )
13640 }),
13641 ),
13642 ))
13643 .into_any_element()
13644 })
13645}
13646
13647pub fn highlight_diagnostic_message(
13648 diagnostic: &Diagnostic,
13649 mut max_message_rows: Option<u8>,
13650) -> (SharedString, Vec<Range<usize>>) {
13651 let mut text_without_backticks = String::new();
13652 let mut code_ranges = Vec::new();
13653
13654 if let Some(source) = &diagnostic.source {
13655 text_without_backticks.push_str(source);
13656 code_ranges.push(0..source.len());
13657 text_without_backticks.push_str(": ");
13658 }
13659
13660 let mut prev_offset = 0;
13661 let mut in_code_block = false;
13662 let has_row_limit = max_message_rows.is_some();
13663 let mut newline_indices = diagnostic
13664 .message
13665 .match_indices('\n')
13666 .filter(|_| has_row_limit)
13667 .map(|(ix, _)| ix)
13668 .fuse()
13669 .peekable();
13670
13671 for (quote_ix, _) in diagnostic
13672 .message
13673 .match_indices('`')
13674 .chain([(diagnostic.message.len(), "")])
13675 {
13676 let mut first_newline_ix = None;
13677 let mut last_newline_ix = None;
13678 while let Some(newline_ix) = newline_indices.peek() {
13679 if *newline_ix < quote_ix {
13680 if first_newline_ix.is_none() {
13681 first_newline_ix = Some(*newline_ix);
13682 }
13683 last_newline_ix = Some(*newline_ix);
13684
13685 if let Some(rows_left) = &mut max_message_rows {
13686 if *rows_left == 0 {
13687 break;
13688 } else {
13689 *rows_left -= 1;
13690 }
13691 }
13692 let _ = newline_indices.next();
13693 } else {
13694 break;
13695 }
13696 }
13697 let prev_len = text_without_backticks.len();
13698 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13699 text_without_backticks.push_str(new_text);
13700 if in_code_block {
13701 code_ranges.push(prev_len..text_without_backticks.len());
13702 }
13703 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13704 in_code_block = !in_code_block;
13705 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13706 text_without_backticks.push_str("...");
13707 break;
13708 }
13709 }
13710
13711 (text_without_backticks.into(), code_ranges)
13712}
13713
13714fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13715 match severity {
13716 DiagnosticSeverity::ERROR => colors.error,
13717 DiagnosticSeverity::WARNING => colors.warning,
13718 DiagnosticSeverity::INFORMATION => colors.info,
13719 DiagnosticSeverity::HINT => colors.info,
13720 _ => colors.ignored,
13721 }
13722}
13723
13724pub fn styled_runs_for_code_label<'a>(
13725 label: &'a CodeLabel,
13726 syntax_theme: &'a theme::SyntaxTheme,
13727) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13728 let fade_out = HighlightStyle {
13729 fade_out: Some(0.35),
13730 ..Default::default()
13731 };
13732
13733 let mut prev_end = label.filter_range.end;
13734 label
13735 .runs
13736 .iter()
13737 .enumerate()
13738 .flat_map(move |(ix, (range, highlight_id))| {
13739 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13740 style
13741 } else {
13742 return Default::default();
13743 };
13744 let mut muted_style = style;
13745 muted_style.highlight(fade_out);
13746
13747 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13748 if range.start >= label.filter_range.end {
13749 if range.start > prev_end {
13750 runs.push((prev_end..range.start, fade_out));
13751 }
13752 runs.push((range.clone(), muted_style));
13753 } else if range.end <= label.filter_range.end {
13754 runs.push((range.clone(), style));
13755 } else {
13756 runs.push((range.start..label.filter_range.end, style));
13757 runs.push((label.filter_range.end..range.end, muted_style));
13758 }
13759 prev_end = cmp::max(prev_end, range.end);
13760
13761 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13762 runs.push((prev_end..label.text.len(), fade_out));
13763 }
13764
13765 runs
13766 })
13767}
13768
13769pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13770 let mut prev_index = 0;
13771 let mut prev_codepoint: Option<char> = None;
13772 text.char_indices()
13773 .chain([(text.len(), '\0')])
13774 .filter_map(move |(index, codepoint)| {
13775 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13776 let is_boundary = index == text.len()
13777 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13778 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13779 if is_boundary {
13780 let chunk = &text[prev_index..index];
13781 prev_index = index;
13782 Some(chunk)
13783 } else {
13784 None
13785 }
13786 })
13787}
13788
13789pub trait RangeToAnchorExt: Sized {
13790 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13791
13792 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13793 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13794 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13795 }
13796}
13797
13798impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13799 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13800 let start_offset = self.start.to_offset(snapshot);
13801 let end_offset = self.end.to_offset(snapshot);
13802 if start_offset == end_offset {
13803 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13804 } else {
13805 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13806 }
13807 }
13808}
13809
13810pub trait RowExt {
13811 fn as_f32(&self) -> f32;
13812
13813 fn next_row(&self) -> Self;
13814
13815 fn previous_row(&self) -> Self;
13816
13817 fn minus(&self, other: Self) -> u32;
13818}
13819
13820impl RowExt for DisplayRow {
13821 fn as_f32(&self) -> f32 {
13822 self.0 as f32
13823 }
13824
13825 fn next_row(&self) -> Self {
13826 Self(self.0 + 1)
13827 }
13828
13829 fn previous_row(&self) -> Self {
13830 Self(self.0.saturating_sub(1))
13831 }
13832
13833 fn minus(&self, other: Self) -> u32 {
13834 self.0 - other.0
13835 }
13836}
13837
13838impl RowExt for MultiBufferRow {
13839 fn as_f32(&self) -> f32 {
13840 self.0 as f32
13841 }
13842
13843 fn next_row(&self) -> Self {
13844 Self(self.0 + 1)
13845 }
13846
13847 fn previous_row(&self) -> Self {
13848 Self(self.0.saturating_sub(1))
13849 }
13850
13851 fn minus(&self, other: Self) -> u32 {
13852 self.0 - other.0
13853 }
13854}
13855
13856trait RowRangeExt {
13857 type Row;
13858
13859 fn len(&self) -> usize;
13860
13861 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13862}
13863
13864impl RowRangeExt for Range<MultiBufferRow> {
13865 type Row = MultiBufferRow;
13866
13867 fn len(&self) -> usize {
13868 (self.end.0 - self.start.0) as usize
13869 }
13870
13871 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13872 (self.start.0..self.end.0).map(MultiBufferRow)
13873 }
13874}
13875
13876impl RowRangeExt for Range<DisplayRow> {
13877 type Row = DisplayRow;
13878
13879 fn len(&self) -> usize {
13880 (self.end.0 - self.start.0) as usize
13881 }
13882
13883 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13884 (self.start.0..self.end.0).map(DisplayRow)
13885 }
13886}
13887
13888fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
13889 if hunk.diff_base_byte_range.is_empty() {
13890 DiffHunkStatus::Added
13891 } else if hunk.row_range.is_empty() {
13892 DiffHunkStatus::Removed
13893 } else {
13894 DiffHunkStatus::Modified
13895 }
13896}
13897
13898/// If select range has more than one line, we
13899/// just point the cursor to range.start.
13900fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13901 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13902 range
13903 } else {
13904 range.start..range.start
13905 }
13906}