1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
52pub(crate) use actions::*;
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use task::{ResolvedTask, TaskTemplate, TaskVariables};
106
107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
108pub use lsp::CompletionContext;
109use lsp::{
110 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
111 LanguageServerId,
112};
113use mouse_context_menu::MouseContextMenu;
114use movement::TextLayoutDetails;
115pub use multi_buffer::{
116 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
117 ToPoint,
118};
119use multi_buffer::{
120 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
121};
122use ordered_float::OrderedFloat;
123use parking_lot::{Mutex, RwLock};
124use project::project_settings::{GitGutterSetting, ProjectSettings};
125use project::{
126 lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
127 ProjectPath, ProjectTransaction, TaskSourceKind,
128};
129use rand::prelude::*;
130use rpc::{proto::*, ErrorExt};
131use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
132use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
133use serde::{Deserialize, Serialize};
134use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
135use smallvec::SmallVec;
136use snippet::Snippet;
137use std::{
138 any::TypeId,
139 borrow::Cow,
140 cell::RefCell,
141 cmp::{self, Ordering, Reverse},
142 mem,
143 num::NonZeroU32,
144 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
145 path::{Path, PathBuf},
146 rc::Rc,
147 sync::Arc,
148 time::{Duration, Instant},
149};
150pub use sum_tree::Bias;
151use sum_tree::TreeMap;
152use text::{BufferId, OffsetUtf16, Rope};
153use theme::{
154 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
155 ThemeColors, ThemeSettings,
156};
157use ui::{
158 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
159 ListItem, Popover, PopoverMenuHandle, Tooltip,
160};
161use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
162use workspace::item::{ItemHandle, PreviewTabsSettings};
163use workspace::notifications::{DetachAndPromptErr, NotificationId};
164use workspace::{
165 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
166};
167use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
168
169use crate::hover_links::find_url;
170use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
171
172pub const FILE_HEADER_HEIGHT: u32 = 1;
173pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
174pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
175pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
176const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
177const MAX_LINE_LEN: usize = 1024;
178const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
179const MAX_SELECTION_HISTORY_LEN: usize = 1024;
180pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
181#[doc(hidden)]
182pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
183#[doc(hidden)]
184pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
185
186pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
187pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
188
189pub fn render_parsed_markdown(
190 element_id: impl Into<ElementId>,
191 parsed: &language::ParsedMarkdown,
192 editor_style: &EditorStyle,
193 workspace: Option<WeakView<Workspace>>,
194 cx: &mut WindowContext,
195) -> InteractiveText {
196 let code_span_background_color = cx
197 .theme()
198 .colors()
199 .editor_document_highlight_read_background;
200
201 let highlights = gpui::combine_highlights(
202 parsed.highlights.iter().filter_map(|(range, highlight)| {
203 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
204 Some((range.clone(), highlight))
205 }),
206 parsed
207 .regions
208 .iter()
209 .zip(&parsed.region_ranges)
210 .filter_map(|(region, range)| {
211 if region.code {
212 Some((
213 range.clone(),
214 HighlightStyle {
215 background_color: Some(code_span_background_color),
216 ..Default::default()
217 },
218 ))
219 } else {
220 None
221 }
222 }),
223 );
224
225 let mut links = Vec::new();
226 let mut link_ranges = Vec::new();
227 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
228 if let Some(link) = region.link.clone() {
229 links.push(link);
230 link_ranges.push(range.clone());
231 }
232 }
233
234 InteractiveText::new(
235 element_id,
236 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
237 )
238 .on_click(link_ranges, move |clicked_range_ix, cx| {
239 match &links[clicked_range_ix] {
240 markdown::Link::Web { url } => cx.open_url(url),
241 markdown::Link::Path { path } => {
242 if let Some(workspace) = &workspace {
243 _ = workspace.update(cx, |workspace, cx| {
244 workspace.open_abs_path(path.clone(), false, cx).detach();
245 });
246 }
247 }
248 }
249 })
250}
251
252#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
253pub(crate) enum InlayId {
254 Suggestion(usize),
255 Hint(usize),
256}
257
258impl InlayId {
259 fn id(&self) -> usize {
260 match self {
261 Self::Suggestion(id) => *id,
262 Self::Hint(id) => *id,
263 }
264 }
265}
266
267enum DiffRowHighlight {}
268enum DocumentHighlightRead {}
269enum DocumentHighlightWrite {}
270enum InputComposition {}
271
272#[derive(Copy, Clone, PartialEq, Eq)]
273pub enum Direction {
274 Prev,
275 Next,
276}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut AppContext) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut AppContext) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new_views(
306 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
318 Editor::new_file(workspace, &Default::default(), cx)
319 })
320 .detach();
321 }
322 });
323 cx.on_action(move |_: &workspace::NewWindow, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
327 Editor::new_file(workspace, &Default::default(), cx)
328 })
329 .detach();
330 }
331 });
332}
333
334pub struct SearchWithinRange;
335
336trait InvalidationRegion {
337 fn ranges(&self) -> &[Range<Anchor>];
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum SelectPhase {
342 Begin {
343 position: DisplayPoint,
344 add: bool,
345 click_count: usize,
346 },
347 BeginColumnar {
348 position: DisplayPoint,
349 reset: bool,
350 goal_column: u32,
351 },
352 Extend {
353 position: DisplayPoint,
354 click_count: usize,
355 },
356 Update {
357 position: DisplayPoint,
358 goal_column: u32,
359 scroll_delta: gpui::Point<f32>,
360 },
361 End,
362}
363
364#[derive(Clone, Debug)]
365pub enum SelectMode {
366 Character,
367 Word(Range<Anchor>),
368 Line(Range<Anchor>),
369 All,
370}
371
372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
373pub enum EditorMode {
374 SingleLine { auto_width: bool },
375 AutoHeight { max_lines: usize },
376 Full,
377}
378
379#[derive(Clone, Debug)]
380pub enum SoftWrap {
381 None,
382 PreferLine,
383 EditorWidth,
384 Column(u32),
385 Bounded(u32),
386}
387
388#[derive(Clone)]
389pub struct EditorStyle {
390 pub background: Hsla,
391 pub local_player: PlayerColor,
392 pub text: TextStyle,
393 pub scrollbar_width: Pixels,
394 pub syntax: Arc<SyntaxTheme>,
395 pub status: StatusColors,
396 pub inlay_hints_style: HighlightStyle,
397 pub suggestions_style: HighlightStyle,
398 pub unnecessary_code_fade: f32,
399}
400
401impl Default for EditorStyle {
402 fn default() -> Self {
403 Self {
404 background: Hsla::default(),
405 local_player: PlayerColor::default(),
406 text: TextStyle::default(),
407 scrollbar_width: Pixels::default(),
408 syntax: Default::default(),
409 // HACK: Status colors don't have a real default.
410 // We should look into removing the status colors from the editor
411 // style and retrieve them directly from the theme.
412 status: StatusColors::dark(),
413 inlay_hints_style: HighlightStyle::default(),
414 suggestions_style: HighlightStyle::default(),
415 unnecessary_code_fade: Default::default(),
416 }
417 }
418}
419
420pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
421 let show_background = all_language_settings(None, cx)
422 .language(None)
423 .inlay_hints
424 .show_background;
425
426 HighlightStyle {
427 color: Some(cx.theme().status().hint),
428 background_color: show_background.then(|| cx.theme().status().hint_background),
429 ..HighlightStyle::default()
430 }
431}
432
433type CompletionId = usize;
434
435#[derive(Clone, Debug)]
436struct CompletionState {
437 // render_inlay_ids represents the inlay hints that are inserted
438 // for rendering the inline completions. They may be discontinuous
439 // in the event that the completion provider returns some intersection
440 // with the existing content.
441 render_inlay_ids: Vec<InlayId>,
442 // text is the resulting rope that is inserted when the user accepts a completion.
443 text: Rope,
444 // position is the position of the cursor when the completion was triggered.
445 position: multi_buffer::Anchor,
446 // delete_range is the range of text that this completion state covers.
447 // if the completion is accepted, this range should be deleted.
448 delete_range: Option<Range<multi_buffer::Anchor>>,
449}
450
451#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
452struct EditorActionId(usize);
453
454impl EditorActionId {
455 pub fn post_inc(&mut self) -> Self {
456 let answer = self.0;
457
458 *self = Self(answer + 1);
459
460 Self(answer)
461 }
462}
463
464// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
465// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
466
467type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
468type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
469
470#[derive(Default)]
471struct ScrollbarMarkerState {
472 scrollbar_size: Size<Pixels>,
473 dirty: bool,
474 markers: Arc<[PaintQuad]>,
475 pending_refresh: Option<Task<Result<()>>>,
476}
477
478impl ScrollbarMarkerState {
479 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
480 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
481 }
482}
483
484#[derive(Clone, Debug)]
485struct RunnableTasks {
486 templates: Vec<(TaskSourceKind, TaskTemplate)>,
487 offset: MultiBufferOffset,
488 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
489 column: u32,
490 // Values of all named captures, including those starting with '_'
491 extra_variables: HashMap<String, String>,
492 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
493 context_range: Range<BufferOffset>,
494}
495
496#[derive(Clone)]
497struct ResolvedTasks {
498 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
499 position: Anchor,
500}
501#[derive(Copy, Clone, Debug)]
502struct MultiBufferOffset(usize);
503#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
504struct BufferOffset(usize);
505
506// Addons allow storing per-editor state in other crates (e.g. Vim)
507pub trait Addon: 'static {
508 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
509
510 fn to_any(&self) -> &dyn std::any::Any;
511}
512
513/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
514///
515/// See the [module level documentation](self) for more information.
516pub struct Editor {
517 focus_handle: FocusHandle,
518 last_focused_descendant: Option<WeakFocusHandle>,
519 /// The text buffer being edited
520 buffer: Model<MultiBuffer>,
521 /// Map of how text in the buffer should be displayed.
522 /// Handles soft wraps, folds, fake inlay text insertions, etc.
523 pub display_map: Model<DisplayMap>,
524 pub selections: SelectionsCollection,
525 pub scroll_manager: ScrollManager,
526 /// When inline assist editors are linked, they all render cursors because
527 /// typing enters text into each of them, even the ones that aren't focused.
528 pub(crate) show_cursor_when_unfocused: bool,
529 columnar_selection_tail: Option<Anchor>,
530 add_selections_state: Option<AddSelectionsState>,
531 select_next_state: Option<SelectNextState>,
532 select_prev_state: Option<SelectNextState>,
533 selection_history: SelectionHistory,
534 autoclose_regions: Vec<AutocloseRegion>,
535 snippet_stack: InvalidationStack<SnippetState>,
536 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
537 ime_transaction: Option<TransactionId>,
538 active_diagnostics: Option<ActiveDiagnosticGroup>,
539 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
540 project: Option<Model<Project>>,
541 completion_provider: Option<Box<dyn CompletionProvider>>,
542 collaboration_hub: Option<Box<dyn CollaborationHub>>,
543 blink_manager: Model<BlinkManager>,
544 show_cursor_names: bool,
545 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
546 pub show_local_selections: bool,
547 mode: EditorMode,
548 show_breadcrumbs: bool,
549 show_gutter: bool,
550 show_line_numbers: Option<bool>,
551 use_relative_line_numbers: Option<bool>,
552 show_git_diff_gutter: Option<bool>,
553 show_code_actions: Option<bool>,
554 show_runnables: Option<bool>,
555 show_wrap_guides: Option<bool>,
556 show_indent_guides: Option<bool>,
557 placeholder_text: Option<Arc<str>>,
558 highlight_order: usize,
559 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
560 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
561 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
562 scrollbar_marker_state: ScrollbarMarkerState,
563 active_indent_guides_state: ActiveIndentGuidesState,
564 nav_history: Option<ItemNavHistory>,
565 context_menu: RwLock<Option<ContextMenu>>,
566 mouse_context_menu: Option<MouseContextMenu>,
567 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
568 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
569 signature_help_state: SignatureHelpState,
570 auto_signature_help: Option<bool>,
571 find_all_references_task_sources: Vec<Anchor>,
572 next_completion_id: CompletionId,
573 completion_documentation_pre_resolve_debounce: DebouncedDelay,
574 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
575 code_actions_task: Option<Task<Result<()>>>,
576 document_highlights_task: Option<Task<()>>,
577 linked_editing_range_task: Option<Task<Option<()>>>,
578 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
579 pending_rename: Option<RenameState>,
580 searchable: bool,
581 cursor_shape: CursorShape,
582 current_line_highlight: Option<CurrentLineHighlight>,
583 collapse_matches: bool,
584 autoindent_mode: Option<AutoindentMode>,
585 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
586 input_enabled: bool,
587 use_modal_editing: bool,
588 read_only: bool,
589 leader_peer_id: Option<PeerId>,
590 remote_id: Option<ViewId>,
591 hover_state: HoverState,
592 gutter_hovered: bool,
593 hovered_link_state: Option<HoveredLinkState>,
594 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
595 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
596 active_inline_completion: Option<CompletionState>,
597 // enable_inline_completions is a switch that Vim can use to disable
598 // inline completions based on its mode.
599 enable_inline_completions: bool,
600 show_inline_completions_override: Option<bool>,
601 inlay_hint_cache: InlayHintCache,
602 expanded_hunks: ExpandedHunks,
603 next_inlay_id: usize,
604 _subscriptions: Vec<Subscription>,
605 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
606 gutter_dimensions: GutterDimensions,
607 style: Option<EditorStyle>,
608 next_editor_action_id: EditorActionId,
609 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
610 use_autoclose: bool,
611 use_auto_surround: bool,
612 auto_replace_emoji_shortcode: bool,
613 show_git_blame_gutter: bool,
614 show_git_blame_inline: bool,
615 show_git_blame_inline_delay_task: Option<Task<()>>,
616 git_blame_inline_enabled: bool,
617 serialize_dirty_buffers: bool,
618 show_selection_menu: Option<bool>,
619 blame: Option<Model<GitBlame>>,
620 blame_subscription: Option<Subscription>,
621 custom_context_menu: Option<
622 Box<
623 dyn 'static
624 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
625 >,
626 >,
627 last_bounds: Option<Bounds<Pixels>>,
628 expect_bounds_change: Option<Bounds<Pixels>>,
629 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
630 tasks_update_task: Option<Task<()>>,
631 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
632 file_header_size: u32,
633 breadcrumb_header: Option<String>,
634 focused_block: Option<FocusedBlock>,
635 next_scroll_position: NextScrollCursorCenterTopBottom,
636 addons: HashMap<TypeId, Box<dyn Addon>>,
637 _scroll_cursor_center_top_bottom_task: Task<()>,
638}
639
640#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
641enum NextScrollCursorCenterTopBottom {
642 #[default]
643 Center,
644 Top,
645 Bottom,
646}
647
648impl NextScrollCursorCenterTopBottom {
649 fn next(&self) -> Self {
650 match self {
651 Self::Center => Self::Top,
652 Self::Top => Self::Bottom,
653 Self::Bottom => Self::Center,
654 }
655 }
656}
657
658#[derive(Clone)]
659pub struct EditorSnapshot {
660 pub mode: EditorMode,
661 show_gutter: bool,
662 show_line_numbers: Option<bool>,
663 show_git_diff_gutter: Option<bool>,
664 show_code_actions: Option<bool>,
665 show_runnables: Option<bool>,
666 render_git_blame_gutter: bool,
667 pub display_snapshot: DisplaySnapshot,
668 pub placeholder_text: Option<Arc<str>>,
669 is_focused: bool,
670 scroll_anchor: ScrollAnchor,
671 ongoing_scroll: OngoingScroll,
672 current_line_highlight: CurrentLineHighlight,
673 gutter_hovered: bool,
674}
675
676const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
677
678#[derive(Default, Debug, Clone, Copy)]
679pub struct GutterDimensions {
680 pub left_padding: Pixels,
681 pub right_padding: Pixels,
682 pub width: Pixels,
683 pub margin: Pixels,
684 pub git_blame_entries_width: Option<Pixels>,
685}
686
687impl GutterDimensions {
688 /// The full width of the space taken up by the gutter.
689 pub fn full_width(&self) -> Pixels {
690 self.margin + self.width
691 }
692
693 /// The width of the space reserved for the fold indicators,
694 /// use alongside 'justify_end' and `gutter_width` to
695 /// right align content with the line numbers
696 pub fn fold_area_width(&self) -> Pixels {
697 self.margin + self.right_padding
698 }
699}
700
701#[derive(Debug)]
702pub struct RemoteSelection {
703 pub replica_id: ReplicaId,
704 pub selection: Selection<Anchor>,
705 pub cursor_shape: CursorShape,
706 pub peer_id: PeerId,
707 pub line_mode: bool,
708 pub participant_index: Option<ParticipantIndex>,
709 pub user_name: Option<SharedString>,
710}
711
712#[derive(Clone, Debug)]
713struct SelectionHistoryEntry {
714 selections: Arc<[Selection<Anchor>]>,
715 select_next_state: Option<SelectNextState>,
716 select_prev_state: Option<SelectNextState>,
717 add_selections_state: Option<AddSelectionsState>,
718}
719
720enum SelectionHistoryMode {
721 Normal,
722 Undoing,
723 Redoing,
724}
725
726#[derive(Clone, PartialEq, Eq, Hash)]
727struct HoveredCursor {
728 replica_id: u16,
729 selection_id: usize,
730}
731
732impl Default for SelectionHistoryMode {
733 fn default() -> Self {
734 Self::Normal
735 }
736}
737
738#[derive(Default)]
739struct SelectionHistory {
740 #[allow(clippy::type_complexity)]
741 selections_by_transaction:
742 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
743 mode: SelectionHistoryMode,
744 undo_stack: VecDeque<SelectionHistoryEntry>,
745 redo_stack: VecDeque<SelectionHistoryEntry>,
746}
747
748impl SelectionHistory {
749 fn insert_transaction(
750 &mut self,
751 transaction_id: TransactionId,
752 selections: Arc<[Selection<Anchor>]>,
753 ) {
754 self.selections_by_transaction
755 .insert(transaction_id, (selections, None));
756 }
757
758 #[allow(clippy::type_complexity)]
759 fn transaction(
760 &self,
761 transaction_id: TransactionId,
762 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
763 self.selections_by_transaction.get(&transaction_id)
764 }
765
766 #[allow(clippy::type_complexity)]
767 fn transaction_mut(
768 &mut self,
769 transaction_id: TransactionId,
770 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
771 self.selections_by_transaction.get_mut(&transaction_id)
772 }
773
774 fn push(&mut self, entry: SelectionHistoryEntry) {
775 if !entry.selections.is_empty() {
776 match self.mode {
777 SelectionHistoryMode::Normal => {
778 self.push_undo(entry);
779 self.redo_stack.clear();
780 }
781 SelectionHistoryMode::Undoing => self.push_redo(entry),
782 SelectionHistoryMode::Redoing => self.push_undo(entry),
783 }
784 }
785 }
786
787 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
788 if self
789 .undo_stack
790 .back()
791 .map_or(true, |e| e.selections != entry.selections)
792 {
793 self.undo_stack.push_back(entry);
794 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
795 self.undo_stack.pop_front();
796 }
797 }
798 }
799
800 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
801 if self
802 .redo_stack
803 .back()
804 .map_or(true, |e| e.selections != entry.selections)
805 {
806 self.redo_stack.push_back(entry);
807 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
808 self.redo_stack.pop_front();
809 }
810 }
811 }
812}
813
814struct RowHighlight {
815 index: usize,
816 range: RangeInclusive<Anchor>,
817 color: Option<Hsla>,
818 should_autoscroll: bool,
819}
820
821#[derive(Clone, Debug)]
822struct AddSelectionsState {
823 above: bool,
824 stack: Vec<usize>,
825}
826
827#[derive(Clone)]
828struct SelectNextState {
829 query: AhoCorasick,
830 wordwise: bool,
831 done: bool,
832}
833
834impl std::fmt::Debug for SelectNextState {
835 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836 f.debug_struct(std::any::type_name::<Self>())
837 .field("wordwise", &self.wordwise)
838 .field("done", &self.done)
839 .finish()
840 }
841}
842
843#[derive(Debug)]
844struct AutocloseRegion {
845 selection_id: usize,
846 range: Range<Anchor>,
847 pair: BracketPair,
848}
849
850#[derive(Debug)]
851struct SnippetState {
852 ranges: Vec<Vec<Range<Anchor>>>,
853 active_index: usize,
854}
855
856#[doc(hidden)]
857pub struct RenameState {
858 pub range: Range<Anchor>,
859 pub old_name: Arc<str>,
860 pub editor: View<Editor>,
861 block_id: CustomBlockId,
862}
863
864struct InvalidationStack<T>(Vec<T>);
865
866struct RegisteredInlineCompletionProvider {
867 provider: Arc<dyn InlineCompletionProviderHandle>,
868 _subscription: Subscription,
869}
870
871enum ContextMenu {
872 Completions(CompletionsMenu),
873 CodeActions(CodeActionsMenu),
874}
875
876impl ContextMenu {
877 fn select_first(
878 &mut self,
879 project: Option<&Model<Project>>,
880 cx: &mut ViewContext<Editor>,
881 ) -> bool {
882 if self.visible() {
883 match self {
884 ContextMenu::Completions(menu) => menu.select_first(project, cx),
885 ContextMenu::CodeActions(menu) => menu.select_first(cx),
886 }
887 true
888 } else {
889 false
890 }
891 }
892
893 fn select_prev(
894 &mut self,
895 project: Option<&Model<Project>>,
896 cx: &mut ViewContext<Editor>,
897 ) -> bool {
898 if self.visible() {
899 match self {
900 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
901 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
902 }
903 true
904 } else {
905 false
906 }
907 }
908
909 fn select_next(
910 &mut self,
911 project: Option<&Model<Project>>,
912 cx: &mut ViewContext<Editor>,
913 ) -> bool {
914 if self.visible() {
915 match self {
916 ContextMenu::Completions(menu) => menu.select_next(project, cx),
917 ContextMenu::CodeActions(menu) => menu.select_next(cx),
918 }
919 true
920 } else {
921 false
922 }
923 }
924
925 fn select_last(
926 &mut self,
927 project: Option<&Model<Project>>,
928 cx: &mut ViewContext<Editor>,
929 ) -> bool {
930 if self.visible() {
931 match self {
932 ContextMenu::Completions(menu) => menu.select_last(project, cx),
933 ContextMenu::CodeActions(menu) => menu.select_last(cx),
934 }
935 true
936 } else {
937 false
938 }
939 }
940
941 fn visible(&self) -> bool {
942 match self {
943 ContextMenu::Completions(menu) => menu.visible(),
944 ContextMenu::CodeActions(menu) => menu.visible(),
945 }
946 }
947
948 fn render(
949 &self,
950 cursor_position: DisplayPoint,
951 style: &EditorStyle,
952 max_height: Pixels,
953 workspace: Option<WeakView<Workspace>>,
954 cx: &mut ViewContext<Editor>,
955 ) -> (ContextMenuOrigin, AnyElement) {
956 match self {
957 ContextMenu::Completions(menu) => (
958 ContextMenuOrigin::EditorPoint(cursor_position),
959 menu.render(style, max_height, workspace, cx),
960 ),
961 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
962 }
963 }
964}
965
966enum ContextMenuOrigin {
967 EditorPoint(DisplayPoint),
968 GutterIndicator(DisplayRow),
969}
970
971#[derive(Clone)]
972struct CompletionsMenu {
973 id: CompletionId,
974 sort_completions: bool,
975 initial_position: Anchor,
976 buffer: Model<Buffer>,
977 completions: Arc<RwLock<Box<[Completion]>>>,
978 match_candidates: Arc<[StringMatchCandidate]>,
979 matches: Arc<[StringMatch]>,
980 selected_item: usize,
981 scroll_handle: UniformListScrollHandle,
982 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
983}
984
985impl CompletionsMenu {
986 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
987 self.selected_item = 0;
988 self.scroll_handle.scroll_to_item(self.selected_item);
989 self.attempt_resolve_selected_completion_documentation(project, cx);
990 cx.notify();
991 }
992
993 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
994 if self.selected_item > 0 {
995 self.selected_item -= 1;
996 } else {
997 self.selected_item = self.matches.len() - 1;
998 }
999 self.scroll_handle.scroll_to_item(self.selected_item);
1000 self.attempt_resolve_selected_completion_documentation(project, cx);
1001 cx.notify();
1002 }
1003
1004 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1005 if self.selected_item + 1 < self.matches.len() {
1006 self.selected_item += 1;
1007 } else {
1008 self.selected_item = 0;
1009 }
1010 self.scroll_handle.scroll_to_item(self.selected_item);
1011 self.attempt_resolve_selected_completion_documentation(project, cx);
1012 cx.notify();
1013 }
1014
1015 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1016 self.selected_item = self.matches.len() - 1;
1017 self.scroll_handle.scroll_to_item(self.selected_item);
1018 self.attempt_resolve_selected_completion_documentation(project, cx);
1019 cx.notify();
1020 }
1021
1022 fn pre_resolve_completion_documentation(
1023 buffer: Model<Buffer>,
1024 completions: Arc<RwLock<Box<[Completion]>>>,
1025 matches: Arc<[StringMatch]>,
1026 editor: &Editor,
1027 cx: &mut ViewContext<Editor>,
1028 ) -> Task<()> {
1029 let settings = EditorSettings::get_global(cx);
1030 if !settings.show_completion_documentation {
1031 return Task::ready(());
1032 }
1033
1034 let Some(provider) = editor.completion_provider.as_ref() else {
1035 return Task::ready(());
1036 };
1037
1038 let resolve_task = provider.resolve_completions(
1039 buffer,
1040 matches.iter().map(|m| m.candidate_id).collect(),
1041 completions.clone(),
1042 cx,
1043 );
1044
1045 cx.spawn(move |this, mut cx| async move {
1046 if let Some(true) = resolve_task.await.log_err() {
1047 this.update(&mut cx, |_, cx| cx.notify()).ok();
1048 }
1049 })
1050 }
1051
1052 fn attempt_resolve_selected_completion_documentation(
1053 &mut self,
1054 project: Option<&Model<Project>>,
1055 cx: &mut ViewContext<Editor>,
1056 ) {
1057 let settings = EditorSettings::get_global(cx);
1058 if !settings.show_completion_documentation {
1059 return;
1060 }
1061
1062 let completion_index = self.matches[self.selected_item].candidate_id;
1063 let Some(project) = project else {
1064 return;
1065 };
1066
1067 let resolve_task = project.update(cx, |project, cx| {
1068 project.resolve_completions(
1069 self.buffer.clone(),
1070 vec![completion_index],
1071 self.completions.clone(),
1072 cx,
1073 )
1074 });
1075
1076 let delay_ms =
1077 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1078 let delay = Duration::from_millis(delay_ms);
1079
1080 self.selected_completion_documentation_resolve_debounce
1081 .lock()
1082 .fire_new(delay, cx, |_, cx| {
1083 cx.spawn(move |this, mut cx| async move {
1084 if let Some(true) = resolve_task.await.log_err() {
1085 this.update(&mut cx, |_, cx| cx.notify()).ok();
1086 }
1087 })
1088 });
1089 }
1090
1091 fn visible(&self) -> bool {
1092 !self.matches.is_empty()
1093 }
1094
1095 fn render(
1096 &self,
1097 style: &EditorStyle,
1098 max_height: Pixels,
1099 workspace: Option<WeakView<Workspace>>,
1100 cx: &mut ViewContext<Editor>,
1101 ) -> AnyElement {
1102 let settings = EditorSettings::get_global(cx);
1103 let show_completion_documentation = settings.show_completion_documentation;
1104
1105 let widest_completion_ix = self
1106 .matches
1107 .iter()
1108 .enumerate()
1109 .max_by_key(|(_, mat)| {
1110 let completions = self.completions.read();
1111 let completion = &completions[mat.candidate_id];
1112 let documentation = &completion.documentation;
1113
1114 let mut len = completion.label.text.chars().count();
1115 if let Some(Documentation::SingleLine(text)) = documentation {
1116 if show_completion_documentation {
1117 len += text.chars().count();
1118 }
1119 }
1120
1121 len
1122 })
1123 .map(|(ix, _)| ix);
1124
1125 let completions = self.completions.clone();
1126 let matches = self.matches.clone();
1127 let selected_item = self.selected_item;
1128 let style = style.clone();
1129
1130 let multiline_docs = if show_completion_documentation {
1131 let mat = &self.matches[selected_item];
1132 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1133 Some(Documentation::MultiLinePlainText(text)) => {
1134 Some(div().child(SharedString::from(text.clone())))
1135 }
1136 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1137 Some(div().child(render_parsed_markdown(
1138 "completions_markdown",
1139 parsed,
1140 &style,
1141 workspace,
1142 cx,
1143 )))
1144 }
1145 _ => None,
1146 };
1147 multiline_docs.map(|div| {
1148 div.id("multiline_docs")
1149 .max_h(max_height)
1150 .flex_1()
1151 .px_1p5()
1152 .py_1()
1153 .min_w(px(260.))
1154 .max_w(px(640.))
1155 .w(px(500.))
1156 .overflow_y_scroll()
1157 .occlude()
1158 })
1159 } else {
1160 None
1161 };
1162
1163 let list = uniform_list(
1164 cx.view().clone(),
1165 "completions",
1166 matches.len(),
1167 move |_editor, range, cx| {
1168 let start_ix = range.start;
1169 let completions_guard = completions.read();
1170
1171 matches[range]
1172 .iter()
1173 .enumerate()
1174 .map(|(ix, mat)| {
1175 let item_ix = start_ix + ix;
1176 let candidate_id = mat.candidate_id;
1177 let completion = &completions_guard[candidate_id];
1178
1179 let documentation = if show_completion_documentation {
1180 &completion.documentation
1181 } else {
1182 &None
1183 };
1184
1185 let highlights = gpui::combine_highlights(
1186 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1187 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1188 |(range, mut highlight)| {
1189 // Ignore font weight for syntax highlighting, as we'll use it
1190 // for fuzzy matches.
1191 highlight.font_weight = None;
1192
1193 if completion.lsp_completion.deprecated.unwrap_or(false) {
1194 highlight.strikethrough = Some(StrikethroughStyle {
1195 thickness: 1.0.into(),
1196 ..Default::default()
1197 });
1198 highlight.color = Some(cx.theme().colors().text_muted);
1199 }
1200
1201 (range, highlight)
1202 },
1203 ),
1204 );
1205 let completion_label = StyledText::new(completion.label.text.clone())
1206 .with_highlights(&style.text, highlights);
1207 let documentation_label =
1208 if let Some(Documentation::SingleLine(text)) = documentation {
1209 if text.trim().is_empty() {
1210 None
1211 } else {
1212 Some(
1213 Label::new(text.clone())
1214 .ml_4()
1215 .size(LabelSize::Small)
1216 .color(Color::Muted),
1217 )
1218 }
1219 } else {
1220 None
1221 };
1222
1223 div().min_w(px(220.)).max_w(px(540.)).child(
1224 ListItem::new(mat.candidate_id)
1225 .inset(true)
1226 .selected(item_ix == selected_item)
1227 .on_click(cx.listener(move |editor, _event, cx| {
1228 cx.stop_propagation();
1229 if let Some(task) = editor.confirm_completion(
1230 &ConfirmCompletion {
1231 item_ix: Some(item_ix),
1232 },
1233 cx,
1234 ) {
1235 task.detach_and_log_err(cx)
1236 }
1237 }))
1238 .child(h_flex().overflow_hidden().child(completion_label))
1239 .end_slot::<Label>(documentation_label),
1240 )
1241 })
1242 .collect()
1243 },
1244 )
1245 .occlude()
1246 .max_h(max_height)
1247 .track_scroll(self.scroll_handle.clone())
1248 .with_width_from_item(widest_completion_ix)
1249 .with_sizing_behavior(ListSizingBehavior::Infer);
1250
1251 Popover::new()
1252 .child(list)
1253 .when_some(multiline_docs, |popover, multiline_docs| {
1254 popover.aside(multiline_docs)
1255 })
1256 .into_any_element()
1257 }
1258
1259 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1260 let mut matches = if let Some(query) = query {
1261 fuzzy::match_strings(
1262 &self.match_candidates,
1263 query,
1264 query.chars().any(|c| c.is_uppercase()),
1265 100,
1266 &Default::default(),
1267 executor,
1268 )
1269 .await
1270 } else {
1271 self.match_candidates
1272 .iter()
1273 .enumerate()
1274 .map(|(candidate_id, candidate)| StringMatch {
1275 candidate_id,
1276 score: Default::default(),
1277 positions: Default::default(),
1278 string: candidate.string.clone(),
1279 })
1280 .collect()
1281 };
1282
1283 // Remove all candidates where the query's start does not match the start of any word in the candidate
1284 if let Some(query) = query {
1285 if let Some(query_start) = query.chars().next() {
1286 matches.retain(|string_match| {
1287 split_words(&string_match.string).any(|word| {
1288 // Check that the first codepoint of the word as lowercase matches the first
1289 // codepoint of the query as lowercase
1290 word.chars()
1291 .flat_map(|codepoint| codepoint.to_lowercase())
1292 .zip(query_start.to_lowercase())
1293 .all(|(word_cp, query_cp)| word_cp == query_cp)
1294 })
1295 });
1296 }
1297 }
1298
1299 let completions = self.completions.read();
1300 if self.sort_completions {
1301 matches.sort_unstable_by_key(|mat| {
1302 // We do want to strike a balance here between what the language server tells us
1303 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1304 // `Creat` and there is a local variable called `CreateComponent`).
1305 // So what we do is: we bucket all matches into two buckets
1306 // - Strong matches
1307 // - Weak matches
1308 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1309 // and the Weak matches are the rest.
1310 //
1311 // For the strong matches, we sort by the language-servers score first and for the weak
1312 // matches, we prefer our fuzzy finder first.
1313 //
1314 // The thinking behind that: it's useless to take the sort_text the language-server gives
1315 // us into account when it's obviously a bad match.
1316
1317 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1318 enum MatchScore<'a> {
1319 Strong {
1320 sort_text: Option<&'a str>,
1321 score: Reverse<OrderedFloat<f64>>,
1322 sort_key: (usize, &'a str),
1323 },
1324 Weak {
1325 score: Reverse<OrderedFloat<f64>>,
1326 sort_text: Option<&'a str>,
1327 sort_key: (usize, &'a str),
1328 },
1329 }
1330
1331 let completion = &completions[mat.candidate_id];
1332 let sort_key = completion.sort_key();
1333 let sort_text = completion.lsp_completion.sort_text.as_deref();
1334 let score = Reverse(OrderedFloat(mat.score));
1335
1336 if mat.score >= 0.2 {
1337 MatchScore::Strong {
1338 sort_text,
1339 score,
1340 sort_key,
1341 }
1342 } else {
1343 MatchScore::Weak {
1344 score,
1345 sort_text,
1346 sort_key,
1347 }
1348 }
1349 });
1350 }
1351
1352 for mat in &mut matches {
1353 let completion = &completions[mat.candidate_id];
1354 mat.string.clone_from(&completion.label.text);
1355 for position in &mut mat.positions {
1356 *position += completion.label.filter_range.start;
1357 }
1358 }
1359 drop(completions);
1360
1361 self.matches = matches.into();
1362 self.selected_item = 0;
1363 }
1364}
1365
1366struct AvailableCodeAction {
1367 excerpt_id: ExcerptId,
1368 action: CodeAction,
1369 provider: Arc<dyn CodeActionProvider>,
1370}
1371
1372#[derive(Clone)]
1373struct CodeActionContents {
1374 tasks: Option<Arc<ResolvedTasks>>,
1375 actions: Option<Arc<[AvailableCodeAction]>>,
1376}
1377
1378impl CodeActionContents {
1379 fn len(&self) -> usize {
1380 match (&self.tasks, &self.actions) {
1381 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1382 (Some(tasks), None) => tasks.templates.len(),
1383 (None, Some(actions)) => actions.len(),
1384 (None, None) => 0,
1385 }
1386 }
1387
1388 fn is_empty(&self) -> bool {
1389 match (&self.tasks, &self.actions) {
1390 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1391 (Some(tasks), None) => tasks.templates.is_empty(),
1392 (None, Some(actions)) => actions.is_empty(),
1393 (None, None) => true,
1394 }
1395 }
1396
1397 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1398 self.tasks
1399 .iter()
1400 .flat_map(|tasks| {
1401 tasks
1402 .templates
1403 .iter()
1404 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1405 })
1406 .chain(self.actions.iter().flat_map(|actions| {
1407 actions.iter().map(|available| CodeActionsItem::CodeAction {
1408 excerpt_id: available.excerpt_id,
1409 action: available.action.clone(),
1410 provider: available.provider.clone(),
1411 })
1412 }))
1413 }
1414 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1415 match (&self.tasks, &self.actions) {
1416 (Some(tasks), Some(actions)) => {
1417 if index < tasks.templates.len() {
1418 tasks
1419 .templates
1420 .get(index)
1421 .cloned()
1422 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1423 } else {
1424 actions.get(index - tasks.templates.len()).map(|available| {
1425 CodeActionsItem::CodeAction {
1426 excerpt_id: available.excerpt_id,
1427 action: available.action.clone(),
1428 provider: available.provider.clone(),
1429 }
1430 })
1431 }
1432 }
1433 (Some(tasks), None) => tasks
1434 .templates
1435 .get(index)
1436 .cloned()
1437 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1438 (None, Some(actions)) => {
1439 actions
1440 .get(index)
1441 .map(|available| CodeActionsItem::CodeAction {
1442 excerpt_id: available.excerpt_id,
1443 action: available.action.clone(),
1444 provider: available.provider.clone(),
1445 })
1446 }
1447 (None, None) => None,
1448 }
1449 }
1450}
1451
1452#[allow(clippy::large_enum_variant)]
1453#[derive(Clone)]
1454enum CodeActionsItem {
1455 Task(TaskSourceKind, ResolvedTask),
1456 CodeAction {
1457 excerpt_id: ExcerptId,
1458 action: CodeAction,
1459 provider: Arc<dyn CodeActionProvider>,
1460 },
1461}
1462
1463impl CodeActionsItem {
1464 fn as_task(&self) -> Option<&ResolvedTask> {
1465 let Self::Task(_, task) = self else {
1466 return None;
1467 };
1468 Some(task)
1469 }
1470 fn as_code_action(&self) -> Option<&CodeAction> {
1471 let Self::CodeAction { action, .. } = self else {
1472 return None;
1473 };
1474 Some(action)
1475 }
1476 fn label(&self) -> String {
1477 match self {
1478 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1479 Self::Task(_, task) => task.resolved_label.clone(),
1480 }
1481 }
1482}
1483
1484struct CodeActionsMenu {
1485 actions: CodeActionContents,
1486 buffer: Model<Buffer>,
1487 selected_item: usize,
1488 scroll_handle: UniformListScrollHandle,
1489 deployed_from_indicator: Option<DisplayRow>,
1490}
1491
1492impl CodeActionsMenu {
1493 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1494 self.selected_item = 0;
1495 self.scroll_handle.scroll_to_item(self.selected_item);
1496 cx.notify()
1497 }
1498
1499 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1500 if self.selected_item > 0 {
1501 self.selected_item -= 1;
1502 } else {
1503 self.selected_item = self.actions.len() - 1;
1504 }
1505 self.scroll_handle.scroll_to_item(self.selected_item);
1506 cx.notify();
1507 }
1508
1509 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1510 if self.selected_item + 1 < self.actions.len() {
1511 self.selected_item += 1;
1512 } else {
1513 self.selected_item = 0;
1514 }
1515 self.scroll_handle.scroll_to_item(self.selected_item);
1516 cx.notify();
1517 }
1518
1519 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1520 self.selected_item = self.actions.len() - 1;
1521 self.scroll_handle.scroll_to_item(self.selected_item);
1522 cx.notify()
1523 }
1524
1525 fn visible(&self) -> bool {
1526 !self.actions.is_empty()
1527 }
1528
1529 fn render(
1530 &self,
1531 cursor_position: DisplayPoint,
1532 _style: &EditorStyle,
1533 max_height: Pixels,
1534 cx: &mut ViewContext<Editor>,
1535 ) -> (ContextMenuOrigin, AnyElement) {
1536 let actions = self.actions.clone();
1537 let selected_item = self.selected_item;
1538 let element = uniform_list(
1539 cx.view().clone(),
1540 "code_actions_menu",
1541 self.actions.len(),
1542 move |_this, range, cx| {
1543 actions
1544 .iter()
1545 .skip(range.start)
1546 .take(range.end - range.start)
1547 .enumerate()
1548 .map(|(ix, action)| {
1549 let item_ix = range.start + ix;
1550 let selected = selected_item == item_ix;
1551 let colors = cx.theme().colors();
1552 div()
1553 .px_1()
1554 .rounded_md()
1555 .text_color(colors.text)
1556 .when(selected, |style| {
1557 style
1558 .bg(colors.element_active)
1559 .text_color(colors.text_accent)
1560 })
1561 .hover(|style| {
1562 style
1563 .bg(colors.element_hover)
1564 .text_color(colors.text_accent)
1565 })
1566 .whitespace_nowrap()
1567 .when_some(action.as_code_action(), |this, action| {
1568 this.on_mouse_down(
1569 MouseButton::Left,
1570 cx.listener(move |editor, _, cx| {
1571 cx.stop_propagation();
1572 if let Some(task) = editor.confirm_code_action(
1573 &ConfirmCodeAction {
1574 item_ix: Some(item_ix),
1575 },
1576 cx,
1577 ) {
1578 task.detach_and_log_err(cx)
1579 }
1580 }),
1581 )
1582 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1583 .child(SharedString::from(action.lsp_action.title.clone()))
1584 })
1585 .when_some(action.as_task(), |this, task| {
1586 this.on_mouse_down(
1587 MouseButton::Left,
1588 cx.listener(move |editor, _, cx| {
1589 cx.stop_propagation();
1590 if let Some(task) = editor.confirm_code_action(
1591 &ConfirmCodeAction {
1592 item_ix: Some(item_ix),
1593 },
1594 cx,
1595 ) {
1596 task.detach_and_log_err(cx)
1597 }
1598 }),
1599 )
1600 .child(SharedString::from(task.resolved_label.clone()))
1601 })
1602 })
1603 .collect()
1604 },
1605 )
1606 .elevation_1(cx)
1607 .p_1()
1608 .max_h(max_height)
1609 .occlude()
1610 .track_scroll(self.scroll_handle.clone())
1611 .with_width_from_item(
1612 self.actions
1613 .iter()
1614 .enumerate()
1615 .max_by_key(|(_, action)| match action {
1616 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1617 CodeActionsItem::CodeAction { action, .. } => {
1618 action.lsp_action.title.chars().count()
1619 }
1620 })
1621 .map(|(ix, _)| ix),
1622 )
1623 .with_sizing_behavior(ListSizingBehavior::Infer)
1624 .into_any_element();
1625
1626 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1627 ContextMenuOrigin::GutterIndicator(row)
1628 } else {
1629 ContextMenuOrigin::EditorPoint(cursor_position)
1630 };
1631
1632 (cursor_position, element)
1633 }
1634}
1635
1636#[derive(Debug)]
1637struct ActiveDiagnosticGroup {
1638 primary_range: Range<Anchor>,
1639 primary_message: String,
1640 group_id: usize,
1641 blocks: HashMap<CustomBlockId, Diagnostic>,
1642 is_valid: bool,
1643}
1644
1645#[derive(Serialize, Deserialize, Clone, Debug)]
1646pub struct ClipboardSelection {
1647 pub len: usize,
1648 pub is_entire_line: bool,
1649 pub first_line_indent: u32,
1650}
1651
1652#[derive(Debug)]
1653pub(crate) struct NavigationData {
1654 cursor_anchor: Anchor,
1655 cursor_position: Point,
1656 scroll_anchor: ScrollAnchor,
1657 scroll_top_row: u32,
1658}
1659
1660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1661enum GotoDefinitionKind {
1662 Symbol,
1663 Declaration,
1664 Type,
1665 Implementation,
1666}
1667
1668#[derive(Debug, Clone)]
1669enum InlayHintRefreshReason {
1670 Toggle(bool),
1671 SettingsChange(InlayHintSettings),
1672 NewLinesShown,
1673 BufferEdited(HashSet<Arc<Language>>),
1674 RefreshRequested,
1675 ExcerptsRemoved(Vec<ExcerptId>),
1676}
1677
1678impl InlayHintRefreshReason {
1679 fn description(&self) -> &'static str {
1680 match self {
1681 Self::Toggle(_) => "toggle",
1682 Self::SettingsChange(_) => "settings change",
1683 Self::NewLinesShown => "new lines shown",
1684 Self::BufferEdited(_) => "buffer edited",
1685 Self::RefreshRequested => "refresh requested",
1686 Self::ExcerptsRemoved(_) => "excerpts removed",
1687 }
1688 }
1689}
1690
1691pub(crate) struct FocusedBlock {
1692 id: BlockId,
1693 focus_handle: WeakFocusHandle,
1694}
1695
1696impl Editor {
1697 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1698 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1699 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1700 Self::new(
1701 EditorMode::SingleLine { auto_width: false },
1702 buffer,
1703 None,
1704 false,
1705 cx,
1706 )
1707 }
1708
1709 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1710 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1711 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1712 Self::new(EditorMode::Full, buffer, None, false, cx)
1713 }
1714
1715 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1716 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1717 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1718 Self::new(
1719 EditorMode::SingleLine { auto_width: true },
1720 buffer,
1721 None,
1722 false,
1723 cx,
1724 )
1725 }
1726
1727 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1728 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1729 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1730 Self::new(
1731 EditorMode::AutoHeight { max_lines },
1732 buffer,
1733 None,
1734 false,
1735 cx,
1736 )
1737 }
1738
1739 pub fn for_buffer(
1740 buffer: Model<Buffer>,
1741 project: Option<Model<Project>>,
1742 cx: &mut ViewContext<Self>,
1743 ) -> Self {
1744 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1745 Self::new(EditorMode::Full, buffer, project, false, cx)
1746 }
1747
1748 pub fn for_multibuffer(
1749 buffer: Model<MultiBuffer>,
1750 project: Option<Model<Project>>,
1751 show_excerpt_controls: bool,
1752 cx: &mut ViewContext<Self>,
1753 ) -> Self {
1754 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1755 }
1756
1757 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1758 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1759 let mut clone = Self::new(
1760 self.mode,
1761 self.buffer.clone(),
1762 self.project.clone(),
1763 show_excerpt_controls,
1764 cx,
1765 );
1766 self.display_map.update(cx, |display_map, cx| {
1767 let snapshot = display_map.snapshot(cx);
1768 clone.display_map.update(cx, |display_map, cx| {
1769 display_map.set_state(&snapshot, cx);
1770 });
1771 });
1772 clone.selections.clone_state(&self.selections);
1773 clone.scroll_manager.clone_state(&self.scroll_manager);
1774 clone.searchable = self.searchable;
1775 clone
1776 }
1777
1778 pub fn new(
1779 mode: EditorMode,
1780 buffer: Model<MultiBuffer>,
1781 project: Option<Model<Project>>,
1782 show_excerpt_controls: bool,
1783 cx: &mut ViewContext<Self>,
1784 ) -> Self {
1785 let style = cx.text_style();
1786 let font_size = style.font_size.to_pixels(cx.rem_size());
1787 let editor = cx.view().downgrade();
1788 let fold_placeholder = FoldPlaceholder {
1789 constrain_width: true,
1790 render: Arc::new(move |fold_id, fold_range, cx| {
1791 let editor = editor.clone();
1792 div()
1793 .id(fold_id)
1794 .bg(cx.theme().colors().ghost_element_background)
1795 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1796 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1797 .rounded_sm()
1798 .size_full()
1799 .cursor_pointer()
1800 .child("⋯")
1801 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1802 .on_click(move |_, cx| {
1803 editor
1804 .update(cx, |editor, cx| {
1805 editor.unfold_ranges(
1806 [fold_range.start..fold_range.end],
1807 true,
1808 false,
1809 cx,
1810 );
1811 cx.stop_propagation();
1812 })
1813 .ok();
1814 })
1815 .into_any()
1816 }),
1817 merge_adjacent: true,
1818 };
1819 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1820 let display_map = cx.new_model(|cx| {
1821 DisplayMap::new(
1822 buffer.clone(),
1823 style.font(),
1824 font_size,
1825 None,
1826 show_excerpt_controls,
1827 file_header_size,
1828 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1829 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1830 fold_placeholder,
1831 cx,
1832 )
1833 });
1834
1835 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1836
1837 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1838
1839 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1840 .then(|| language_settings::SoftWrap::PreferLine);
1841
1842 let mut project_subscriptions = Vec::new();
1843 if mode == EditorMode::Full {
1844 if let Some(project) = project.as_ref() {
1845 if buffer.read(cx).is_singleton() {
1846 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1847 cx.emit(EditorEvent::TitleChanged);
1848 }));
1849 }
1850 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1851 if let project::Event::RefreshInlayHints = event {
1852 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1853 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1854 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1855 let focus_handle = editor.focus_handle(cx);
1856 if focus_handle.is_focused(cx) {
1857 let snapshot = buffer.read(cx).snapshot();
1858 for (range, snippet) in snippet_edits {
1859 let editor_range =
1860 language::range_from_lsp(*range).to_offset(&snapshot);
1861 editor
1862 .insert_snippet(&[editor_range], snippet.clone(), cx)
1863 .ok();
1864 }
1865 }
1866 }
1867 }
1868 }));
1869 let task_inventory = project.read(cx).task_inventory().clone();
1870 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1871 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1872 }));
1873 }
1874 }
1875
1876 let inlay_hint_settings = inlay_hint_settings(
1877 selections.newest_anchor().head(),
1878 &buffer.read(cx).snapshot(cx),
1879 cx,
1880 );
1881 let focus_handle = cx.focus_handle();
1882 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1883 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1884 .detach();
1885 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1886 .detach();
1887 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1888
1889 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1890 Some(false)
1891 } else {
1892 None
1893 };
1894
1895 let mut code_action_providers = Vec::new();
1896 if let Some(project) = project.clone() {
1897 code_action_providers.push(Arc::new(project) as Arc<_>);
1898 }
1899
1900 let mut this = Self {
1901 focus_handle,
1902 show_cursor_when_unfocused: false,
1903 last_focused_descendant: None,
1904 buffer: buffer.clone(),
1905 display_map: display_map.clone(),
1906 selections,
1907 scroll_manager: ScrollManager::new(cx),
1908 columnar_selection_tail: None,
1909 add_selections_state: None,
1910 select_next_state: None,
1911 select_prev_state: None,
1912 selection_history: Default::default(),
1913 autoclose_regions: Default::default(),
1914 snippet_stack: Default::default(),
1915 select_larger_syntax_node_stack: Vec::new(),
1916 ime_transaction: Default::default(),
1917 active_diagnostics: None,
1918 soft_wrap_mode_override,
1919 completion_provider: project.clone().map(|project| Box::new(project) as _),
1920 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1921 project,
1922 blink_manager: blink_manager.clone(),
1923 show_local_selections: true,
1924 mode,
1925 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1926 show_gutter: mode == EditorMode::Full,
1927 show_line_numbers: None,
1928 use_relative_line_numbers: None,
1929 show_git_diff_gutter: None,
1930 show_code_actions: None,
1931 show_runnables: None,
1932 show_wrap_guides: None,
1933 show_indent_guides,
1934 placeholder_text: None,
1935 highlight_order: 0,
1936 highlighted_rows: HashMap::default(),
1937 background_highlights: Default::default(),
1938 gutter_highlights: TreeMap::default(),
1939 scrollbar_marker_state: ScrollbarMarkerState::default(),
1940 active_indent_guides_state: ActiveIndentGuidesState::default(),
1941 nav_history: None,
1942 context_menu: RwLock::new(None),
1943 mouse_context_menu: None,
1944 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1945 completion_tasks: Default::default(),
1946 signature_help_state: SignatureHelpState::default(),
1947 auto_signature_help: None,
1948 find_all_references_task_sources: Vec::new(),
1949 next_completion_id: 0,
1950 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1951 next_inlay_id: 0,
1952 code_action_providers,
1953 available_code_actions: Default::default(),
1954 code_actions_task: Default::default(),
1955 document_highlights_task: Default::default(),
1956 linked_editing_range_task: Default::default(),
1957 pending_rename: Default::default(),
1958 searchable: true,
1959 cursor_shape: EditorSettings::get_global(cx)
1960 .cursor_shape
1961 .unwrap_or_default(),
1962 current_line_highlight: None,
1963 autoindent_mode: Some(AutoindentMode::EachLine),
1964 collapse_matches: false,
1965 workspace: None,
1966 input_enabled: true,
1967 use_modal_editing: mode == EditorMode::Full,
1968 read_only: false,
1969 use_autoclose: true,
1970 use_auto_surround: true,
1971 auto_replace_emoji_shortcode: false,
1972 leader_peer_id: None,
1973 remote_id: None,
1974 hover_state: Default::default(),
1975 hovered_link_state: Default::default(),
1976 inline_completion_provider: None,
1977 active_inline_completion: None,
1978 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1979 expanded_hunks: ExpandedHunks::default(),
1980 gutter_hovered: false,
1981 pixel_position_of_newest_cursor: None,
1982 last_bounds: None,
1983 expect_bounds_change: None,
1984 gutter_dimensions: GutterDimensions::default(),
1985 style: None,
1986 show_cursor_names: false,
1987 hovered_cursors: Default::default(),
1988 next_editor_action_id: EditorActionId::default(),
1989 editor_actions: Rc::default(),
1990 show_inline_completions_override: None,
1991 enable_inline_completions: true,
1992 custom_context_menu: None,
1993 show_git_blame_gutter: false,
1994 show_git_blame_inline: false,
1995 show_selection_menu: None,
1996 show_git_blame_inline_delay_task: None,
1997 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1998 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1999 .session
2000 .restore_unsaved_buffers,
2001 blame: None,
2002 blame_subscription: None,
2003 file_header_size,
2004 tasks: Default::default(),
2005 _subscriptions: vec![
2006 cx.observe(&buffer, Self::on_buffer_changed),
2007 cx.subscribe(&buffer, Self::on_buffer_event),
2008 cx.observe(&display_map, Self::on_display_map_changed),
2009 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2010 cx.observe_global::<SettingsStore>(Self::settings_changed),
2011 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2012 cx.observe_window_activation(|editor, cx| {
2013 let active = cx.is_window_active();
2014 editor.blink_manager.update(cx, |blink_manager, cx| {
2015 if active {
2016 blink_manager.enable(cx);
2017 } else {
2018 blink_manager.disable(cx);
2019 }
2020 });
2021 }),
2022 ],
2023 tasks_update_task: None,
2024 linked_edit_ranges: Default::default(),
2025 previous_search_ranges: None,
2026 breadcrumb_header: None,
2027 focused_block: None,
2028 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2029 addons: HashMap::default(),
2030 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2031 };
2032 this.tasks_update_task = Some(this.refresh_runnables(cx));
2033 this._subscriptions.extend(project_subscriptions);
2034
2035 this.end_selection(cx);
2036 this.scroll_manager.show_scrollbar(cx);
2037
2038 if mode == EditorMode::Full {
2039 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2040 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2041
2042 if this.git_blame_inline_enabled {
2043 this.git_blame_inline_enabled = true;
2044 this.start_git_blame_inline(false, cx);
2045 }
2046 }
2047
2048 this.report_editor_event("open", None, cx);
2049 this
2050 }
2051
2052 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2053 self.mouse_context_menu
2054 .as_ref()
2055 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2056 }
2057
2058 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2059 let mut key_context = KeyContext::new_with_defaults();
2060 key_context.add("Editor");
2061 let mode = match self.mode {
2062 EditorMode::SingleLine { .. } => "single_line",
2063 EditorMode::AutoHeight { .. } => "auto_height",
2064 EditorMode::Full => "full",
2065 };
2066
2067 if EditorSettings::jupyter_enabled(cx) {
2068 key_context.add("jupyter");
2069 }
2070
2071 key_context.set("mode", mode);
2072 if self.pending_rename.is_some() {
2073 key_context.add("renaming");
2074 }
2075 if self.context_menu_visible() {
2076 match self.context_menu.read().as_ref() {
2077 Some(ContextMenu::Completions(_)) => {
2078 key_context.add("menu");
2079 key_context.add("showing_completions")
2080 }
2081 Some(ContextMenu::CodeActions(_)) => {
2082 key_context.add("menu");
2083 key_context.add("showing_code_actions")
2084 }
2085 None => {}
2086 }
2087 }
2088
2089 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2090 if !self.focus_handle(cx).contains_focused(cx)
2091 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2092 {
2093 for addon in self.addons.values() {
2094 addon.extend_key_context(&mut key_context, cx)
2095 }
2096 }
2097
2098 if let Some(extension) = self
2099 .buffer
2100 .read(cx)
2101 .as_singleton()
2102 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2103 {
2104 key_context.set("extension", extension.to_string());
2105 }
2106
2107 if self.has_active_inline_completion(cx) {
2108 key_context.add("copilot_suggestion");
2109 key_context.add("inline_completion");
2110 }
2111
2112 key_context
2113 }
2114
2115 pub fn new_file(
2116 workspace: &mut Workspace,
2117 _: &workspace::NewFile,
2118 cx: &mut ViewContext<Workspace>,
2119 ) {
2120 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2121 "Failed to create buffer",
2122 cx,
2123 |e, _| match e.error_code() {
2124 ErrorCode::RemoteUpgradeRequired => Some(format!(
2125 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2126 e.error_tag("required").unwrap_or("the latest version")
2127 )),
2128 _ => None,
2129 },
2130 );
2131 }
2132
2133 pub fn new_in_workspace(
2134 workspace: &mut Workspace,
2135 cx: &mut ViewContext<Workspace>,
2136 ) -> Task<Result<View<Editor>>> {
2137 let project = workspace.project().clone();
2138 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2139
2140 cx.spawn(|workspace, mut cx| async move {
2141 let buffer = create.await?;
2142 workspace.update(&mut cx, |workspace, cx| {
2143 let editor =
2144 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2145 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2146 editor
2147 })
2148 })
2149 }
2150
2151 fn new_file_vertical(
2152 workspace: &mut Workspace,
2153 _: &workspace::NewFileSplitVertical,
2154 cx: &mut ViewContext<Workspace>,
2155 ) {
2156 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2157 }
2158
2159 fn new_file_horizontal(
2160 workspace: &mut Workspace,
2161 _: &workspace::NewFileSplitHorizontal,
2162 cx: &mut ViewContext<Workspace>,
2163 ) {
2164 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2165 }
2166
2167 fn new_file_in_direction(
2168 workspace: &mut Workspace,
2169 direction: SplitDirection,
2170 cx: &mut ViewContext<Workspace>,
2171 ) {
2172 let project = workspace.project().clone();
2173 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2174
2175 cx.spawn(|workspace, mut cx| async move {
2176 let buffer = create.await?;
2177 workspace.update(&mut cx, move |workspace, cx| {
2178 workspace.split_item(
2179 direction,
2180 Box::new(
2181 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2182 ),
2183 cx,
2184 )
2185 })?;
2186 anyhow::Ok(())
2187 })
2188 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2189 ErrorCode::RemoteUpgradeRequired => Some(format!(
2190 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2191 e.error_tag("required").unwrap_or("the latest version")
2192 )),
2193 _ => None,
2194 });
2195 }
2196
2197 pub fn leader_peer_id(&self) -> Option<PeerId> {
2198 self.leader_peer_id
2199 }
2200
2201 pub fn buffer(&self) -> &Model<MultiBuffer> {
2202 &self.buffer
2203 }
2204
2205 pub fn workspace(&self) -> Option<View<Workspace>> {
2206 self.workspace.as_ref()?.0.upgrade()
2207 }
2208
2209 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2210 self.buffer().read(cx).title(cx)
2211 }
2212
2213 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2214 EditorSnapshot {
2215 mode: self.mode,
2216 show_gutter: self.show_gutter,
2217 show_line_numbers: self.show_line_numbers,
2218 show_git_diff_gutter: self.show_git_diff_gutter,
2219 show_code_actions: self.show_code_actions,
2220 show_runnables: self.show_runnables,
2221 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2222 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2223 scroll_anchor: self.scroll_manager.anchor(),
2224 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2225 placeholder_text: self.placeholder_text.clone(),
2226 is_focused: self.focus_handle.is_focused(cx),
2227 current_line_highlight: self
2228 .current_line_highlight
2229 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2230 gutter_hovered: self.gutter_hovered,
2231 }
2232 }
2233
2234 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2235 self.buffer.read(cx).language_at(point, cx)
2236 }
2237
2238 pub fn file_at<T: ToOffset>(
2239 &self,
2240 point: T,
2241 cx: &AppContext,
2242 ) -> Option<Arc<dyn language::File>> {
2243 self.buffer.read(cx).read(cx).file_at(point).cloned()
2244 }
2245
2246 pub fn active_excerpt(
2247 &self,
2248 cx: &AppContext,
2249 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2250 self.buffer
2251 .read(cx)
2252 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2253 }
2254
2255 pub fn mode(&self) -> EditorMode {
2256 self.mode
2257 }
2258
2259 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2260 self.collaboration_hub.as_deref()
2261 }
2262
2263 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2264 self.collaboration_hub = Some(hub);
2265 }
2266
2267 pub fn set_custom_context_menu(
2268 &mut self,
2269 f: impl 'static
2270 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2271 ) {
2272 self.custom_context_menu = Some(Box::new(f))
2273 }
2274
2275 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2276 self.completion_provider = Some(provider);
2277 }
2278
2279 pub fn set_inline_completion_provider<T>(
2280 &mut self,
2281 provider: Option<Model<T>>,
2282 cx: &mut ViewContext<Self>,
2283 ) where
2284 T: InlineCompletionProvider,
2285 {
2286 self.inline_completion_provider =
2287 provider.map(|provider| RegisteredInlineCompletionProvider {
2288 _subscription: cx.observe(&provider, |this, _, cx| {
2289 if this.focus_handle.is_focused(cx) {
2290 this.update_visible_inline_completion(cx);
2291 }
2292 }),
2293 provider: Arc::new(provider),
2294 });
2295 self.refresh_inline_completion(false, false, cx);
2296 }
2297
2298 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2299 self.placeholder_text.as_deref()
2300 }
2301
2302 pub fn set_placeholder_text(
2303 &mut self,
2304 placeholder_text: impl Into<Arc<str>>,
2305 cx: &mut ViewContext<Self>,
2306 ) {
2307 let placeholder_text = Some(placeholder_text.into());
2308 if self.placeholder_text != placeholder_text {
2309 self.placeholder_text = placeholder_text;
2310 cx.notify();
2311 }
2312 }
2313
2314 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2315 self.cursor_shape = cursor_shape;
2316
2317 // Disrupt blink for immediate user feedback that the cursor shape has changed
2318 self.blink_manager.update(cx, BlinkManager::show_cursor);
2319
2320 cx.notify();
2321 }
2322
2323 pub fn set_current_line_highlight(
2324 &mut self,
2325 current_line_highlight: Option<CurrentLineHighlight>,
2326 ) {
2327 self.current_line_highlight = current_line_highlight;
2328 }
2329
2330 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2331 self.collapse_matches = collapse_matches;
2332 }
2333
2334 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2335 if self.collapse_matches {
2336 return range.start..range.start;
2337 }
2338 range.clone()
2339 }
2340
2341 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2342 if self.display_map.read(cx).clip_at_line_ends != clip {
2343 self.display_map
2344 .update(cx, |map, _| map.clip_at_line_ends = clip);
2345 }
2346 }
2347
2348 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2349 self.input_enabled = input_enabled;
2350 }
2351
2352 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2353 self.enable_inline_completions = enabled;
2354 }
2355
2356 pub fn set_autoindent(&mut self, autoindent: bool) {
2357 if autoindent {
2358 self.autoindent_mode = Some(AutoindentMode::EachLine);
2359 } else {
2360 self.autoindent_mode = None;
2361 }
2362 }
2363
2364 pub fn read_only(&self, cx: &AppContext) -> bool {
2365 self.read_only || self.buffer.read(cx).read_only()
2366 }
2367
2368 pub fn set_read_only(&mut self, read_only: bool) {
2369 self.read_only = read_only;
2370 }
2371
2372 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2373 self.use_autoclose = autoclose;
2374 }
2375
2376 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2377 self.use_auto_surround = auto_surround;
2378 }
2379
2380 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2381 self.auto_replace_emoji_shortcode = auto_replace;
2382 }
2383
2384 pub fn toggle_inline_completions(
2385 &mut self,
2386 _: &ToggleInlineCompletions,
2387 cx: &mut ViewContext<Self>,
2388 ) {
2389 if self.show_inline_completions_override.is_some() {
2390 self.set_show_inline_completions(None, cx);
2391 } else {
2392 let cursor = self.selections.newest_anchor().head();
2393 if let Some((buffer, cursor_buffer_position)) =
2394 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2395 {
2396 let show_inline_completions =
2397 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2398 self.set_show_inline_completions(Some(show_inline_completions), cx);
2399 }
2400 }
2401 }
2402
2403 pub fn set_show_inline_completions(
2404 &mut self,
2405 show_inline_completions: Option<bool>,
2406 cx: &mut ViewContext<Self>,
2407 ) {
2408 self.show_inline_completions_override = show_inline_completions;
2409 self.refresh_inline_completion(false, true, cx);
2410 }
2411
2412 fn should_show_inline_completions(
2413 &self,
2414 buffer: &Model<Buffer>,
2415 buffer_position: language::Anchor,
2416 cx: &AppContext,
2417 ) -> bool {
2418 if let Some(provider) = self.inline_completion_provider() {
2419 if let Some(show_inline_completions) = self.show_inline_completions_override {
2420 show_inline_completions
2421 } else {
2422 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2423 }
2424 } else {
2425 false
2426 }
2427 }
2428
2429 pub fn set_use_modal_editing(&mut self, to: bool) {
2430 self.use_modal_editing = to;
2431 }
2432
2433 pub fn use_modal_editing(&self) -> bool {
2434 self.use_modal_editing
2435 }
2436
2437 fn selections_did_change(
2438 &mut self,
2439 local: bool,
2440 old_cursor_position: &Anchor,
2441 show_completions: bool,
2442 cx: &mut ViewContext<Self>,
2443 ) {
2444 cx.invalidate_character_coordinates();
2445
2446 // Copy selections to primary selection buffer
2447 #[cfg(target_os = "linux")]
2448 if local {
2449 let selections = self.selections.all::<usize>(cx);
2450 let buffer_handle = self.buffer.read(cx).read(cx);
2451
2452 let mut text = String::new();
2453 for (index, selection) in selections.iter().enumerate() {
2454 let text_for_selection = buffer_handle
2455 .text_for_range(selection.start..selection.end)
2456 .collect::<String>();
2457
2458 text.push_str(&text_for_selection);
2459 if index != selections.len() - 1 {
2460 text.push('\n');
2461 }
2462 }
2463
2464 if !text.is_empty() {
2465 cx.write_to_primary(ClipboardItem::new_string(text));
2466 }
2467 }
2468
2469 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2470 self.buffer.update(cx, |buffer, cx| {
2471 buffer.set_active_selections(
2472 &self.selections.disjoint_anchors(),
2473 self.selections.line_mode,
2474 self.cursor_shape,
2475 cx,
2476 )
2477 });
2478 }
2479 let display_map = self
2480 .display_map
2481 .update(cx, |display_map, cx| display_map.snapshot(cx));
2482 let buffer = &display_map.buffer_snapshot;
2483 self.add_selections_state = None;
2484 self.select_next_state = None;
2485 self.select_prev_state = None;
2486 self.select_larger_syntax_node_stack.clear();
2487 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2488 self.snippet_stack
2489 .invalidate(&self.selections.disjoint_anchors(), buffer);
2490 self.take_rename(false, cx);
2491
2492 let new_cursor_position = self.selections.newest_anchor().head();
2493
2494 self.push_to_nav_history(
2495 *old_cursor_position,
2496 Some(new_cursor_position.to_point(buffer)),
2497 cx,
2498 );
2499
2500 if local {
2501 let new_cursor_position = self.selections.newest_anchor().head();
2502 let mut context_menu = self.context_menu.write();
2503 let completion_menu = match context_menu.as_ref() {
2504 Some(ContextMenu::Completions(menu)) => Some(menu),
2505
2506 _ => {
2507 *context_menu = None;
2508 None
2509 }
2510 };
2511
2512 if let Some(completion_menu) = completion_menu {
2513 let cursor_position = new_cursor_position.to_offset(buffer);
2514 let (word_range, kind) =
2515 buffer.surrounding_word(completion_menu.initial_position, true);
2516 if kind == Some(CharKind::Word)
2517 && word_range.to_inclusive().contains(&cursor_position)
2518 {
2519 let mut completion_menu = completion_menu.clone();
2520 drop(context_menu);
2521
2522 let query = Self::completion_query(buffer, cursor_position);
2523 cx.spawn(move |this, mut cx| async move {
2524 completion_menu
2525 .filter(query.as_deref(), cx.background_executor().clone())
2526 .await;
2527
2528 this.update(&mut cx, |this, cx| {
2529 let mut context_menu = this.context_menu.write();
2530 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2531 return;
2532 };
2533
2534 if menu.id > completion_menu.id {
2535 return;
2536 }
2537
2538 *context_menu = Some(ContextMenu::Completions(completion_menu));
2539 drop(context_menu);
2540 cx.notify();
2541 })
2542 })
2543 .detach();
2544
2545 if show_completions {
2546 self.show_completions(&ShowCompletions { trigger: None }, cx);
2547 }
2548 } else {
2549 drop(context_menu);
2550 self.hide_context_menu(cx);
2551 }
2552 } else {
2553 drop(context_menu);
2554 }
2555
2556 hide_hover(self, cx);
2557
2558 if old_cursor_position.to_display_point(&display_map).row()
2559 != new_cursor_position.to_display_point(&display_map).row()
2560 {
2561 self.available_code_actions.take();
2562 }
2563 self.refresh_code_actions(cx);
2564 self.refresh_document_highlights(cx);
2565 refresh_matching_bracket_highlights(self, cx);
2566 self.discard_inline_completion(false, cx);
2567 linked_editing_ranges::refresh_linked_ranges(self, cx);
2568 if self.git_blame_inline_enabled {
2569 self.start_inline_blame_timer(cx);
2570 }
2571 }
2572
2573 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2574 cx.emit(EditorEvent::SelectionsChanged { local });
2575
2576 if self.selections.disjoint_anchors().len() == 1 {
2577 cx.emit(SearchEvent::ActiveMatchChanged)
2578 }
2579 cx.notify();
2580 }
2581
2582 pub fn change_selections<R>(
2583 &mut self,
2584 autoscroll: Option<Autoscroll>,
2585 cx: &mut ViewContext<Self>,
2586 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2587 ) -> R {
2588 self.change_selections_inner(autoscroll, true, cx, change)
2589 }
2590
2591 pub fn change_selections_inner<R>(
2592 &mut self,
2593 autoscroll: Option<Autoscroll>,
2594 request_completions: bool,
2595 cx: &mut ViewContext<Self>,
2596 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2597 ) -> R {
2598 let old_cursor_position = self.selections.newest_anchor().head();
2599 self.push_to_selection_history();
2600
2601 let (changed, result) = self.selections.change_with(cx, change);
2602
2603 if changed {
2604 if let Some(autoscroll) = autoscroll {
2605 self.request_autoscroll(autoscroll, cx);
2606 }
2607 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2608
2609 if self.should_open_signature_help_automatically(
2610 &old_cursor_position,
2611 self.signature_help_state.backspace_pressed(),
2612 cx,
2613 ) {
2614 self.show_signature_help(&ShowSignatureHelp, cx);
2615 }
2616 self.signature_help_state.set_backspace_pressed(false);
2617 }
2618
2619 result
2620 }
2621
2622 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2623 where
2624 I: IntoIterator<Item = (Range<S>, T)>,
2625 S: ToOffset,
2626 T: Into<Arc<str>>,
2627 {
2628 if self.read_only(cx) {
2629 return;
2630 }
2631
2632 self.buffer
2633 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2634 }
2635
2636 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2637 where
2638 I: IntoIterator<Item = (Range<S>, T)>,
2639 S: ToOffset,
2640 T: Into<Arc<str>>,
2641 {
2642 if self.read_only(cx) {
2643 return;
2644 }
2645
2646 self.buffer.update(cx, |buffer, cx| {
2647 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2648 });
2649 }
2650
2651 pub fn edit_with_block_indent<I, S, T>(
2652 &mut self,
2653 edits: I,
2654 original_indent_columns: Vec<u32>,
2655 cx: &mut ViewContext<Self>,
2656 ) where
2657 I: IntoIterator<Item = (Range<S>, T)>,
2658 S: ToOffset,
2659 T: Into<Arc<str>>,
2660 {
2661 if self.read_only(cx) {
2662 return;
2663 }
2664
2665 self.buffer.update(cx, |buffer, cx| {
2666 buffer.edit(
2667 edits,
2668 Some(AutoindentMode::Block {
2669 original_indent_columns,
2670 }),
2671 cx,
2672 )
2673 });
2674 }
2675
2676 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2677 self.hide_context_menu(cx);
2678
2679 match phase {
2680 SelectPhase::Begin {
2681 position,
2682 add,
2683 click_count,
2684 } => self.begin_selection(position, add, click_count, cx),
2685 SelectPhase::BeginColumnar {
2686 position,
2687 goal_column,
2688 reset,
2689 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2690 SelectPhase::Extend {
2691 position,
2692 click_count,
2693 } => self.extend_selection(position, click_count, cx),
2694 SelectPhase::Update {
2695 position,
2696 goal_column,
2697 scroll_delta,
2698 } => self.update_selection(position, goal_column, scroll_delta, cx),
2699 SelectPhase::End => self.end_selection(cx),
2700 }
2701 }
2702
2703 fn extend_selection(
2704 &mut self,
2705 position: DisplayPoint,
2706 click_count: usize,
2707 cx: &mut ViewContext<Self>,
2708 ) {
2709 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2710 let tail = self.selections.newest::<usize>(cx).tail();
2711 self.begin_selection(position, false, click_count, cx);
2712
2713 let position = position.to_offset(&display_map, Bias::Left);
2714 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2715
2716 let mut pending_selection = self
2717 .selections
2718 .pending_anchor()
2719 .expect("extend_selection not called with pending selection");
2720 if position >= tail {
2721 pending_selection.start = tail_anchor;
2722 } else {
2723 pending_selection.end = tail_anchor;
2724 pending_selection.reversed = true;
2725 }
2726
2727 let mut pending_mode = self.selections.pending_mode().unwrap();
2728 match &mut pending_mode {
2729 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2730 _ => {}
2731 }
2732
2733 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2734 s.set_pending(pending_selection, pending_mode)
2735 });
2736 }
2737
2738 fn begin_selection(
2739 &mut self,
2740 position: DisplayPoint,
2741 add: bool,
2742 click_count: usize,
2743 cx: &mut ViewContext<Self>,
2744 ) {
2745 if !self.focus_handle.is_focused(cx) {
2746 self.last_focused_descendant = None;
2747 cx.focus(&self.focus_handle);
2748 }
2749
2750 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2751 let buffer = &display_map.buffer_snapshot;
2752 let newest_selection = self.selections.newest_anchor().clone();
2753 let position = display_map.clip_point(position, Bias::Left);
2754
2755 let start;
2756 let end;
2757 let mode;
2758 let auto_scroll;
2759 match click_count {
2760 1 => {
2761 start = buffer.anchor_before(position.to_point(&display_map));
2762 end = start;
2763 mode = SelectMode::Character;
2764 auto_scroll = true;
2765 }
2766 2 => {
2767 let range = movement::surrounding_word(&display_map, position);
2768 start = buffer.anchor_before(range.start.to_point(&display_map));
2769 end = buffer.anchor_before(range.end.to_point(&display_map));
2770 mode = SelectMode::Word(start..end);
2771 auto_scroll = true;
2772 }
2773 3 => {
2774 let position = display_map
2775 .clip_point(position, Bias::Left)
2776 .to_point(&display_map);
2777 let line_start = display_map.prev_line_boundary(position).0;
2778 let next_line_start = buffer.clip_point(
2779 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2780 Bias::Left,
2781 );
2782 start = buffer.anchor_before(line_start);
2783 end = buffer.anchor_before(next_line_start);
2784 mode = SelectMode::Line(start..end);
2785 auto_scroll = true;
2786 }
2787 _ => {
2788 start = buffer.anchor_before(0);
2789 end = buffer.anchor_before(buffer.len());
2790 mode = SelectMode::All;
2791 auto_scroll = false;
2792 }
2793 }
2794
2795 let point_to_delete: Option<usize> = {
2796 let selected_points: Vec<Selection<Point>> =
2797 self.selections.disjoint_in_range(start..end, cx);
2798
2799 if !add || click_count > 1 {
2800 None
2801 } else if !selected_points.is_empty() {
2802 Some(selected_points[0].id)
2803 } else {
2804 let clicked_point_already_selected =
2805 self.selections.disjoint.iter().find(|selection| {
2806 selection.start.to_point(buffer) == start.to_point(buffer)
2807 || selection.end.to_point(buffer) == end.to_point(buffer)
2808 });
2809
2810 clicked_point_already_selected.map(|selection| selection.id)
2811 }
2812 };
2813
2814 let selections_count = self.selections.count();
2815
2816 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2817 if let Some(point_to_delete) = point_to_delete {
2818 s.delete(point_to_delete);
2819
2820 if selections_count == 1 {
2821 s.set_pending_anchor_range(start..end, mode);
2822 }
2823 } else {
2824 if !add {
2825 s.clear_disjoint();
2826 } else if click_count > 1 {
2827 s.delete(newest_selection.id)
2828 }
2829
2830 s.set_pending_anchor_range(start..end, mode);
2831 }
2832 });
2833 }
2834
2835 fn begin_columnar_selection(
2836 &mut self,
2837 position: DisplayPoint,
2838 goal_column: u32,
2839 reset: bool,
2840 cx: &mut ViewContext<Self>,
2841 ) {
2842 if !self.focus_handle.is_focused(cx) {
2843 self.last_focused_descendant = None;
2844 cx.focus(&self.focus_handle);
2845 }
2846
2847 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2848
2849 if reset {
2850 let pointer_position = display_map
2851 .buffer_snapshot
2852 .anchor_before(position.to_point(&display_map));
2853
2854 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2855 s.clear_disjoint();
2856 s.set_pending_anchor_range(
2857 pointer_position..pointer_position,
2858 SelectMode::Character,
2859 );
2860 });
2861 }
2862
2863 let tail = self.selections.newest::<Point>(cx).tail();
2864 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2865
2866 if !reset {
2867 self.select_columns(
2868 tail.to_display_point(&display_map),
2869 position,
2870 goal_column,
2871 &display_map,
2872 cx,
2873 );
2874 }
2875 }
2876
2877 fn update_selection(
2878 &mut self,
2879 position: DisplayPoint,
2880 goal_column: u32,
2881 scroll_delta: gpui::Point<f32>,
2882 cx: &mut ViewContext<Self>,
2883 ) {
2884 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2885
2886 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2887 let tail = tail.to_display_point(&display_map);
2888 self.select_columns(tail, position, goal_column, &display_map, cx);
2889 } else if let Some(mut pending) = self.selections.pending_anchor() {
2890 let buffer = self.buffer.read(cx).snapshot(cx);
2891 let head;
2892 let tail;
2893 let mode = self.selections.pending_mode().unwrap();
2894 match &mode {
2895 SelectMode::Character => {
2896 head = position.to_point(&display_map);
2897 tail = pending.tail().to_point(&buffer);
2898 }
2899 SelectMode::Word(original_range) => {
2900 let original_display_range = original_range.start.to_display_point(&display_map)
2901 ..original_range.end.to_display_point(&display_map);
2902 let original_buffer_range = original_display_range.start.to_point(&display_map)
2903 ..original_display_range.end.to_point(&display_map);
2904 if movement::is_inside_word(&display_map, position)
2905 || original_display_range.contains(&position)
2906 {
2907 let word_range = movement::surrounding_word(&display_map, position);
2908 if word_range.start < original_display_range.start {
2909 head = word_range.start.to_point(&display_map);
2910 } else {
2911 head = word_range.end.to_point(&display_map);
2912 }
2913 } else {
2914 head = position.to_point(&display_map);
2915 }
2916
2917 if head <= original_buffer_range.start {
2918 tail = original_buffer_range.end;
2919 } else {
2920 tail = original_buffer_range.start;
2921 }
2922 }
2923 SelectMode::Line(original_range) => {
2924 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2925
2926 let position = display_map
2927 .clip_point(position, Bias::Left)
2928 .to_point(&display_map);
2929 let line_start = display_map.prev_line_boundary(position).0;
2930 let next_line_start = buffer.clip_point(
2931 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2932 Bias::Left,
2933 );
2934
2935 if line_start < original_range.start {
2936 head = line_start
2937 } else {
2938 head = next_line_start
2939 }
2940
2941 if head <= original_range.start {
2942 tail = original_range.end;
2943 } else {
2944 tail = original_range.start;
2945 }
2946 }
2947 SelectMode::All => {
2948 return;
2949 }
2950 };
2951
2952 if head < tail {
2953 pending.start = buffer.anchor_before(head);
2954 pending.end = buffer.anchor_before(tail);
2955 pending.reversed = true;
2956 } else {
2957 pending.start = buffer.anchor_before(tail);
2958 pending.end = buffer.anchor_before(head);
2959 pending.reversed = false;
2960 }
2961
2962 self.change_selections(None, cx, |s| {
2963 s.set_pending(pending, mode);
2964 });
2965 } else {
2966 log::error!("update_selection dispatched with no pending selection");
2967 return;
2968 }
2969
2970 self.apply_scroll_delta(scroll_delta, cx);
2971 cx.notify();
2972 }
2973
2974 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2975 self.columnar_selection_tail.take();
2976 if self.selections.pending_anchor().is_some() {
2977 let selections = self.selections.all::<usize>(cx);
2978 self.change_selections(None, cx, |s| {
2979 s.select(selections);
2980 s.clear_pending();
2981 });
2982 }
2983 }
2984
2985 fn select_columns(
2986 &mut self,
2987 tail: DisplayPoint,
2988 head: DisplayPoint,
2989 goal_column: u32,
2990 display_map: &DisplaySnapshot,
2991 cx: &mut ViewContext<Self>,
2992 ) {
2993 let start_row = cmp::min(tail.row(), head.row());
2994 let end_row = cmp::max(tail.row(), head.row());
2995 let start_column = cmp::min(tail.column(), goal_column);
2996 let end_column = cmp::max(tail.column(), goal_column);
2997 let reversed = start_column < tail.column();
2998
2999 let selection_ranges = (start_row.0..=end_row.0)
3000 .map(DisplayRow)
3001 .filter_map(|row| {
3002 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3003 let start = display_map
3004 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3005 .to_point(display_map);
3006 let end = display_map
3007 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3008 .to_point(display_map);
3009 if reversed {
3010 Some(end..start)
3011 } else {
3012 Some(start..end)
3013 }
3014 } else {
3015 None
3016 }
3017 })
3018 .collect::<Vec<_>>();
3019
3020 self.change_selections(None, cx, |s| {
3021 s.select_ranges(selection_ranges);
3022 });
3023 cx.notify();
3024 }
3025
3026 pub fn has_pending_nonempty_selection(&self) -> bool {
3027 let pending_nonempty_selection = match self.selections.pending_anchor() {
3028 Some(Selection { start, end, .. }) => start != end,
3029 None => false,
3030 };
3031
3032 pending_nonempty_selection
3033 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3034 }
3035
3036 pub fn has_pending_selection(&self) -> bool {
3037 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3038 }
3039
3040 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3041 if self.clear_clicked_diff_hunks(cx) {
3042 cx.notify();
3043 return;
3044 }
3045 if self.dismiss_menus_and_popups(true, cx) {
3046 return;
3047 }
3048
3049 if self.mode == EditorMode::Full
3050 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3051 {
3052 return;
3053 }
3054
3055 cx.propagate();
3056 }
3057
3058 pub fn dismiss_menus_and_popups(
3059 &mut self,
3060 should_report_inline_completion_event: bool,
3061 cx: &mut ViewContext<Self>,
3062 ) -> bool {
3063 if self.take_rename(false, cx).is_some() {
3064 return true;
3065 }
3066
3067 if hide_hover(self, cx) {
3068 return true;
3069 }
3070
3071 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3072 return true;
3073 }
3074
3075 if self.hide_context_menu(cx).is_some() {
3076 return true;
3077 }
3078
3079 if self.mouse_context_menu.take().is_some() {
3080 return true;
3081 }
3082
3083 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3084 return true;
3085 }
3086
3087 if self.snippet_stack.pop().is_some() {
3088 return true;
3089 }
3090
3091 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3092 self.dismiss_diagnostics(cx);
3093 return true;
3094 }
3095
3096 false
3097 }
3098
3099 fn linked_editing_ranges_for(
3100 &self,
3101 selection: Range<text::Anchor>,
3102 cx: &AppContext,
3103 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3104 if self.linked_edit_ranges.is_empty() {
3105 return None;
3106 }
3107 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3108 selection.end.buffer_id.and_then(|end_buffer_id| {
3109 if selection.start.buffer_id != Some(end_buffer_id) {
3110 return None;
3111 }
3112 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3113 let snapshot = buffer.read(cx).snapshot();
3114 self.linked_edit_ranges
3115 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3116 .map(|ranges| (ranges, snapshot, buffer))
3117 })?;
3118 use text::ToOffset as TO;
3119 // find offset from the start of current range to current cursor position
3120 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3121
3122 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3123 let start_difference = start_offset - start_byte_offset;
3124 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3125 let end_difference = end_offset - start_byte_offset;
3126 // Current range has associated linked ranges.
3127 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3128 for range in linked_ranges.iter() {
3129 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3130 let end_offset = start_offset + end_difference;
3131 let start_offset = start_offset + start_difference;
3132 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3133 continue;
3134 }
3135 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3136 if s.start.buffer_id != selection.start.buffer_id
3137 || s.end.buffer_id != selection.end.buffer_id
3138 {
3139 return false;
3140 }
3141 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3142 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3143 }) {
3144 continue;
3145 }
3146 let start = buffer_snapshot.anchor_after(start_offset);
3147 let end = buffer_snapshot.anchor_after(end_offset);
3148 linked_edits
3149 .entry(buffer.clone())
3150 .or_default()
3151 .push(start..end);
3152 }
3153 Some(linked_edits)
3154 }
3155
3156 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3157 let text: Arc<str> = text.into();
3158
3159 if self.read_only(cx) {
3160 return;
3161 }
3162
3163 let selections = self.selections.all_adjusted(cx);
3164 let mut bracket_inserted = false;
3165 let mut edits = Vec::new();
3166 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3167 let mut new_selections = Vec::with_capacity(selections.len());
3168 let mut new_autoclose_regions = Vec::new();
3169 let snapshot = self.buffer.read(cx).read(cx);
3170
3171 for (selection, autoclose_region) in
3172 self.selections_with_autoclose_regions(selections, &snapshot)
3173 {
3174 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3175 // Determine if the inserted text matches the opening or closing
3176 // bracket of any of this language's bracket pairs.
3177 let mut bracket_pair = None;
3178 let mut is_bracket_pair_start = false;
3179 let mut is_bracket_pair_end = false;
3180 if !text.is_empty() {
3181 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3182 // and they are removing the character that triggered IME popup.
3183 for (pair, enabled) in scope.brackets() {
3184 if !pair.close && !pair.surround {
3185 continue;
3186 }
3187
3188 if enabled && pair.start.ends_with(text.as_ref()) {
3189 bracket_pair = Some(pair.clone());
3190 is_bracket_pair_start = true;
3191 break;
3192 }
3193 if pair.end.as_str() == text.as_ref() {
3194 bracket_pair = Some(pair.clone());
3195 is_bracket_pair_end = true;
3196 break;
3197 }
3198 }
3199 }
3200
3201 if let Some(bracket_pair) = bracket_pair {
3202 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3203 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3204 let auto_surround =
3205 self.use_auto_surround && snapshot_settings.use_auto_surround;
3206 if selection.is_empty() {
3207 if is_bracket_pair_start {
3208 let prefix_len = bracket_pair.start.len() - text.len();
3209
3210 // If the inserted text is a suffix of an opening bracket and the
3211 // selection is preceded by the rest of the opening bracket, then
3212 // insert the closing bracket.
3213 let following_text_allows_autoclose = snapshot
3214 .chars_at(selection.start)
3215 .next()
3216 .map_or(true, |c| scope.should_autoclose_before(c));
3217 let preceding_text_matches_prefix = prefix_len == 0
3218 || (selection.start.column >= (prefix_len as u32)
3219 && snapshot.contains_str_at(
3220 Point::new(
3221 selection.start.row,
3222 selection.start.column - (prefix_len as u32),
3223 ),
3224 &bracket_pair.start[..prefix_len],
3225 ));
3226
3227 if autoclose
3228 && bracket_pair.close
3229 && following_text_allows_autoclose
3230 && preceding_text_matches_prefix
3231 {
3232 let anchor = snapshot.anchor_before(selection.end);
3233 new_selections.push((selection.map(|_| anchor), text.len()));
3234 new_autoclose_regions.push((
3235 anchor,
3236 text.len(),
3237 selection.id,
3238 bracket_pair.clone(),
3239 ));
3240 edits.push((
3241 selection.range(),
3242 format!("{}{}", text, bracket_pair.end).into(),
3243 ));
3244 bracket_inserted = true;
3245 continue;
3246 }
3247 }
3248
3249 if let Some(region) = autoclose_region {
3250 // If the selection is followed by an auto-inserted closing bracket,
3251 // then don't insert that closing bracket again; just move the selection
3252 // past the closing bracket.
3253 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3254 && text.as_ref() == region.pair.end.as_str();
3255 if should_skip {
3256 let anchor = snapshot.anchor_after(selection.end);
3257 new_selections
3258 .push((selection.map(|_| anchor), region.pair.end.len()));
3259 continue;
3260 }
3261 }
3262
3263 let always_treat_brackets_as_autoclosed = snapshot
3264 .settings_at(selection.start, cx)
3265 .always_treat_brackets_as_autoclosed;
3266 if always_treat_brackets_as_autoclosed
3267 && is_bracket_pair_end
3268 && snapshot.contains_str_at(selection.end, text.as_ref())
3269 {
3270 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3271 // and the inserted text is a closing bracket and the selection is followed
3272 // by the closing bracket then move the selection past the closing bracket.
3273 let anchor = snapshot.anchor_after(selection.end);
3274 new_selections.push((selection.map(|_| anchor), text.len()));
3275 continue;
3276 }
3277 }
3278 // If an opening bracket is 1 character long and is typed while
3279 // text is selected, then surround that text with the bracket pair.
3280 else if auto_surround
3281 && bracket_pair.surround
3282 && is_bracket_pair_start
3283 && bracket_pair.start.chars().count() == 1
3284 {
3285 edits.push((selection.start..selection.start, text.clone()));
3286 edits.push((
3287 selection.end..selection.end,
3288 bracket_pair.end.as_str().into(),
3289 ));
3290 bracket_inserted = true;
3291 new_selections.push((
3292 Selection {
3293 id: selection.id,
3294 start: snapshot.anchor_after(selection.start),
3295 end: snapshot.anchor_before(selection.end),
3296 reversed: selection.reversed,
3297 goal: selection.goal,
3298 },
3299 0,
3300 ));
3301 continue;
3302 }
3303 }
3304 }
3305
3306 if self.auto_replace_emoji_shortcode
3307 && selection.is_empty()
3308 && text.as_ref().ends_with(':')
3309 {
3310 if let Some(possible_emoji_short_code) =
3311 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3312 {
3313 if !possible_emoji_short_code.is_empty() {
3314 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3315 let emoji_shortcode_start = Point::new(
3316 selection.start.row,
3317 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3318 );
3319
3320 // Remove shortcode from buffer
3321 edits.push((
3322 emoji_shortcode_start..selection.start,
3323 "".to_string().into(),
3324 ));
3325 new_selections.push((
3326 Selection {
3327 id: selection.id,
3328 start: snapshot.anchor_after(emoji_shortcode_start),
3329 end: snapshot.anchor_before(selection.start),
3330 reversed: selection.reversed,
3331 goal: selection.goal,
3332 },
3333 0,
3334 ));
3335
3336 // Insert emoji
3337 let selection_start_anchor = snapshot.anchor_after(selection.start);
3338 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3339 edits.push((selection.start..selection.end, emoji.to_string().into()));
3340
3341 continue;
3342 }
3343 }
3344 }
3345 }
3346
3347 // If not handling any auto-close operation, then just replace the selected
3348 // text with the given input and move the selection to the end of the
3349 // newly inserted text.
3350 let anchor = snapshot.anchor_after(selection.end);
3351 if !self.linked_edit_ranges.is_empty() {
3352 let start_anchor = snapshot.anchor_before(selection.start);
3353
3354 let is_word_char = text.chars().next().map_or(true, |char| {
3355 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3356 classifier.is_word(char)
3357 });
3358
3359 if is_word_char {
3360 if let Some(ranges) = self
3361 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3362 {
3363 for (buffer, edits) in ranges {
3364 linked_edits
3365 .entry(buffer.clone())
3366 .or_default()
3367 .extend(edits.into_iter().map(|range| (range, text.clone())));
3368 }
3369 }
3370 }
3371 }
3372
3373 new_selections.push((selection.map(|_| anchor), 0));
3374 edits.push((selection.start..selection.end, text.clone()));
3375 }
3376
3377 drop(snapshot);
3378
3379 self.transact(cx, |this, cx| {
3380 this.buffer.update(cx, |buffer, cx| {
3381 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3382 });
3383 for (buffer, edits) in linked_edits {
3384 buffer.update(cx, |buffer, cx| {
3385 let snapshot = buffer.snapshot();
3386 let edits = edits
3387 .into_iter()
3388 .map(|(range, text)| {
3389 use text::ToPoint as TP;
3390 let end_point = TP::to_point(&range.end, &snapshot);
3391 let start_point = TP::to_point(&range.start, &snapshot);
3392 (start_point..end_point, text)
3393 })
3394 .sorted_by_key(|(range, _)| range.start)
3395 .collect::<Vec<_>>();
3396 buffer.edit(edits, None, cx);
3397 })
3398 }
3399 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3400 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3401 let snapshot = this.buffer.read(cx).read(cx);
3402 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3403 .zip(new_selection_deltas)
3404 .map(|(selection, delta)| Selection {
3405 id: selection.id,
3406 start: selection.start + delta,
3407 end: selection.end + delta,
3408 reversed: selection.reversed,
3409 goal: SelectionGoal::None,
3410 })
3411 .collect::<Vec<_>>();
3412
3413 let mut i = 0;
3414 for (position, delta, selection_id, pair) in new_autoclose_regions {
3415 let position = position.to_offset(&snapshot) + delta;
3416 let start = snapshot.anchor_before(position);
3417 let end = snapshot.anchor_after(position);
3418 while let Some(existing_state) = this.autoclose_regions.get(i) {
3419 match existing_state.range.start.cmp(&start, &snapshot) {
3420 Ordering::Less => i += 1,
3421 Ordering::Greater => break,
3422 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3423 Ordering::Less => i += 1,
3424 Ordering::Equal => break,
3425 Ordering::Greater => break,
3426 },
3427 }
3428 }
3429 this.autoclose_regions.insert(
3430 i,
3431 AutocloseRegion {
3432 selection_id,
3433 range: start..end,
3434 pair,
3435 },
3436 );
3437 }
3438
3439 drop(snapshot);
3440 let had_active_inline_completion = this.has_active_inline_completion(cx);
3441 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3442 s.select(new_selections)
3443 });
3444
3445 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3446 if let Some(on_type_format_task) =
3447 this.trigger_on_type_formatting(text.to_string(), cx)
3448 {
3449 on_type_format_task.detach_and_log_err(cx);
3450 }
3451 }
3452
3453 let editor_settings = EditorSettings::get_global(cx);
3454 if bracket_inserted
3455 && (editor_settings.auto_signature_help
3456 || editor_settings.show_signature_help_after_edits)
3457 {
3458 this.show_signature_help(&ShowSignatureHelp, cx);
3459 }
3460
3461 let trigger_in_words = !had_active_inline_completion;
3462 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3463 linked_editing_ranges::refresh_linked_ranges(this, cx);
3464 this.refresh_inline_completion(true, false, cx);
3465 });
3466 }
3467
3468 fn find_possible_emoji_shortcode_at_position(
3469 snapshot: &MultiBufferSnapshot,
3470 position: Point,
3471 ) -> Option<String> {
3472 let mut chars = Vec::new();
3473 let mut found_colon = false;
3474 for char in snapshot.reversed_chars_at(position).take(100) {
3475 // Found a possible emoji shortcode in the middle of the buffer
3476 if found_colon {
3477 if char.is_whitespace() {
3478 chars.reverse();
3479 return Some(chars.iter().collect());
3480 }
3481 // If the previous character is not a whitespace, we are in the middle of a word
3482 // and we only want to complete the shortcode if the word is made up of other emojis
3483 let mut containing_word = String::new();
3484 for ch in snapshot
3485 .reversed_chars_at(position)
3486 .skip(chars.len() + 1)
3487 .take(100)
3488 {
3489 if ch.is_whitespace() {
3490 break;
3491 }
3492 containing_word.push(ch);
3493 }
3494 let containing_word = containing_word.chars().rev().collect::<String>();
3495 if util::word_consists_of_emojis(containing_word.as_str()) {
3496 chars.reverse();
3497 return Some(chars.iter().collect());
3498 }
3499 }
3500
3501 if char.is_whitespace() || !char.is_ascii() {
3502 return None;
3503 }
3504 if char == ':' {
3505 found_colon = true;
3506 } else {
3507 chars.push(char);
3508 }
3509 }
3510 // Found a possible emoji shortcode at the beginning of the buffer
3511 chars.reverse();
3512 Some(chars.iter().collect())
3513 }
3514
3515 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3516 self.transact(cx, |this, cx| {
3517 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3518 let selections = this.selections.all::<usize>(cx);
3519 let multi_buffer = this.buffer.read(cx);
3520 let buffer = multi_buffer.snapshot(cx);
3521 selections
3522 .iter()
3523 .map(|selection| {
3524 let start_point = selection.start.to_point(&buffer);
3525 let mut indent =
3526 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3527 indent.len = cmp::min(indent.len, start_point.column);
3528 let start = selection.start;
3529 let end = selection.end;
3530 let selection_is_empty = start == end;
3531 let language_scope = buffer.language_scope_at(start);
3532 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3533 &language_scope
3534 {
3535 let leading_whitespace_len = buffer
3536 .reversed_chars_at(start)
3537 .take_while(|c| c.is_whitespace() && *c != '\n')
3538 .map(|c| c.len_utf8())
3539 .sum::<usize>();
3540
3541 let trailing_whitespace_len = buffer
3542 .chars_at(end)
3543 .take_while(|c| c.is_whitespace() && *c != '\n')
3544 .map(|c| c.len_utf8())
3545 .sum::<usize>();
3546
3547 let insert_extra_newline =
3548 language.brackets().any(|(pair, enabled)| {
3549 let pair_start = pair.start.trim_end();
3550 let pair_end = pair.end.trim_start();
3551
3552 enabled
3553 && pair.newline
3554 && buffer.contains_str_at(
3555 end + trailing_whitespace_len,
3556 pair_end,
3557 )
3558 && buffer.contains_str_at(
3559 (start - leading_whitespace_len)
3560 .saturating_sub(pair_start.len()),
3561 pair_start,
3562 )
3563 });
3564
3565 // Comment extension on newline is allowed only for cursor selections
3566 let comment_delimiter = maybe!({
3567 if !selection_is_empty {
3568 return None;
3569 }
3570
3571 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3572 return None;
3573 }
3574
3575 let delimiters = language.line_comment_prefixes();
3576 let max_len_of_delimiter =
3577 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3578 let (snapshot, range) =
3579 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3580
3581 let mut index_of_first_non_whitespace = 0;
3582 let comment_candidate = snapshot
3583 .chars_for_range(range)
3584 .skip_while(|c| {
3585 let should_skip = c.is_whitespace();
3586 if should_skip {
3587 index_of_first_non_whitespace += 1;
3588 }
3589 should_skip
3590 })
3591 .take(max_len_of_delimiter)
3592 .collect::<String>();
3593 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3594 comment_candidate.starts_with(comment_prefix.as_ref())
3595 })?;
3596 let cursor_is_placed_after_comment_marker =
3597 index_of_first_non_whitespace + comment_prefix.len()
3598 <= start_point.column as usize;
3599 if cursor_is_placed_after_comment_marker {
3600 Some(comment_prefix.clone())
3601 } else {
3602 None
3603 }
3604 });
3605 (comment_delimiter, insert_extra_newline)
3606 } else {
3607 (None, false)
3608 };
3609
3610 let capacity_for_delimiter = comment_delimiter
3611 .as_deref()
3612 .map(str::len)
3613 .unwrap_or_default();
3614 let mut new_text =
3615 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3616 new_text.push('\n');
3617 new_text.extend(indent.chars());
3618 if let Some(delimiter) = &comment_delimiter {
3619 new_text.push_str(delimiter);
3620 }
3621 if insert_extra_newline {
3622 new_text = new_text.repeat(2);
3623 }
3624
3625 let anchor = buffer.anchor_after(end);
3626 let new_selection = selection.map(|_| anchor);
3627 (
3628 (start..end, new_text),
3629 (insert_extra_newline, new_selection),
3630 )
3631 })
3632 .unzip()
3633 };
3634
3635 this.edit_with_autoindent(edits, cx);
3636 let buffer = this.buffer.read(cx).snapshot(cx);
3637 let new_selections = selection_fixup_info
3638 .into_iter()
3639 .map(|(extra_newline_inserted, new_selection)| {
3640 let mut cursor = new_selection.end.to_point(&buffer);
3641 if extra_newline_inserted {
3642 cursor.row -= 1;
3643 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3644 }
3645 new_selection.map(|_| cursor)
3646 })
3647 .collect();
3648
3649 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3650 this.refresh_inline_completion(true, false, cx);
3651 });
3652 }
3653
3654 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3655 let buffer = self.buffer.read(cx);
3656 let snapshot = buffer.snapshot(cx);
3657
3658 let mut edits = Vec::new();
3659 let mut rows = Vec::new();
3660
3661 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3662 let cursor = selection.head();
3663 let row = cursor.row;
3664
3665 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3666
3667 let newline = "\n".to_string();
3668 edits.push((start_of_line..start_of_line, newline));
3669
3670 rows.push(row + rows_inserted as u32);
3671 }
3672
3673 self.transact(cx, |editor, cx| {
3674 editor.edit(edits, cx);
3675
3676 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3677 let mut index = 0;
3678 s.move_cursors_with(|map, _, _| {
3679 let row = rows[index];
3680 index += 1;
3681
3682 let point = Point::new(row, 0);
3683 let boundary = map.next_line_boundary(point).1;
3684 let clipped = map.clip_point(boundary, Bias::Left);
3685
3686 (clipped, SelectionGoal::None)
3687 });
3688 });
3689
3690 let mut indent_edits = Vec::new();
3691 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3692 for row in rows {
3693 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3694 for (row, indent) in indents {
3695 if indent.len == 0 {
3696 continue;
3697 }
3698
3699 let text = match indent.kind {
3700 IndentKind::Space => " ".repeat(indent.len as usize),
3701 IndentKind::Tab => "\t".repeat(indent.len as usize),
3702 };
3703 let point = Point::new(row.0, 0);
3704 indent_edits.push((point..point, text));
3705 }
3706 }
3707 editor.edit(indent_edits, cx);
3708 });
3709 }
3710
3711 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3712 let buffer = self.buffer.read(cx);
3713 let snapshot = buffer.snapshot(cx);
3714
3715 let mut edits = Vec::new();
3716 let mut rows = Vec::new();
3717 let mut rows_inserted = 0;
3718
3719 for selection in self.selections.all_adjusted(cx) {
3720 let cursor = selection.head();
3721 let row = cursor.row;
3722
3723 let point = Point::new(row + 1, 0);
3724 let start_of_line = snapshot.clip_point(point, Bias::Left);
3725
3726 let newline = "\n".to_string();
3727 edits.push((start_of_line..start_of_line, newline));
3728
3729 rows_inserted += 1;
3730 rows.push(row + rows_inserted);
3731 }
3732
3733 self.transact(cx, |editor, cx| {
3734 editor.edit(edits, cx);
3735
3736 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3737 let mut index = 0;
3738 s.move_cursors_with(|map, _, _| {
3739 let row = rows[index];
3740 index += 1;
3741
3742 let point = Point::new(row, 0);
3743 let boundary = map.next_line_boundary(point).1;
3744 let clipped = map.clip_point(boundary, Bias::Left);
3745
3746 (clipped, SelectionGoal::None)
3747 });
3748 });
3749
3750 let mut indent_edits = Vec::new();
3751 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3752 for row in rows {
3753 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3754 for (row, indent) in indents {
3755 if indent.len == 0 {
3756 continue;
3757 }
3758
3759 let text = match indent.kind {
3760 IndentKind::Space => " ".repeat(indent.len as usize),
3761 IndentKind::Tab => "\t".repeat(indent.len as usize),
3762 };
3763 let point = Point::new(row.0, 0);
3764 indent_edits.push((point..point, text));
3765 }
3766 }
3767 editor.edit(indent_edits, cx);
3768 });
3769 }
3770
3771 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3772 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3773 original_indent_columns: Vec::new(),
3774 });
3775 self.insert_with_autoindent_mode(text, autoindent, cx);
3776 }
3777
3778 fn insert_with_autoindent_mode(
3779 &mut self,
3780 text: &str,
3781 autoindent_mode: Option<AutoindentMode>,
3782 cx: &mut ViewContext<Self>,
3783 ) {
3784 if self.read_only(cx) {
3785 return;
3786 }
3787
3788 let text: Arc<str> = text.into();
3789 self.transact(cx, |this, cx| {
3790 let old_selections = this.selections.all_adjusted(cx);
3791 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3792 let anchors = {
3793 let snapshot = buffer.read(cx);
3794 old_selections
3795 .iter()
3796 .map(|s| {
3797 let anchor = snapshot.anchor_after(s.head());
3798 s.map(|_| anchor)
3799 })
3800 .collect::<Vec<_>>()
3801 };
3802 buffer.edit(
3803 old_selections
3804 .iter()
3805 .map(|s| (s.start..s.end, text.clone())),
3806 autoindent_mode,
3807 cx,
3808 );
3809 anchors
3810 });
3811
3812 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3813 s.select_anchors(selection_anchors);
3814 })
3815 });
3816 }
3817
3818 fn trigger_completion_on_input(
3819 &mut self,
3820 text: &str,
3821 trigger_in_words: bool,
3822 cx: &mut ViewContext<Self>,
3823 ) {
3824 if self.is_completion_trigger(text, trigger_in_words, cx) {
3825 self.show_completions(
3826 &ShowCompletions {
3827 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3828 },
3829 cx,
3830 );
3831 } else {
3832 self.hide_context_menu(cx);
3833 }
3834 }
3835
3836 fn is_completion_trigger(
3837 &self,
3838 text: &str,
3839 trigger_in_words: bool,
3840 cx: &mut ViewContext<Self>,
3841 ) -> bool {
3842 let position = self.selections.newest_anchor().head();
3843 let multibuffer = self.buffer.read(cx);
3844 let Some(buffer) = position
3845 .buffer_id
3846 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3847 else {
3848 return false;
3849 };
3850
3851 if let Some(completion_provider) = &self.completion_provider {
3852 completion_provider.is_completion_trigger(
3853 &buffer,
3854 position.text_anchor,
3855 text,
3856 trigger_in_words,
3857 cx,
3858 )
3859 } else {
3860 false
3861 }
3862 }
3863
3864 /// If any empty selections is touching the start of its innermost containing autoclose
3865 /// region, expand it to select the brackets.
3866 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3867 let selections = self.selections.all::<usize>(cx);
3868 let buffer = self.buffer.read(cx).read(cx);
3869 let new_selections = self
3870 .selections_with_autoclose_regions(selections, &buffer)
3871 .map(|(mut selection, region)| {
3872 if !selection.is_empty() {
3873 return selection;
3874 }
3875
3876 if let Some(region) = region {
3877 let mut range = region.range.to_offset(&buffer);
3878 if selection.start == range.start && range.start >= region.pair.start.len() {
3879 range.start -= region.pair.start.len();
3880 if buffer.contains_str_at(range.start, ®ion.pair.start)
3881 && buffer.contains_str_at(range.end, ®ion.pair.end)
3882 {
3883 range.end += region.pair.end.len();
3884 selection.start = range.start;
3885 selection.end = range.end;
3886
3887 return selection;
3888 }
3889 }
3890 }
3891
3892 let always_treat_brackets_as_autoclosed = buffer
3893 .settings_at(selection.start, cx)
3894 .always_treat_brackets_as_autoclosed;
3895
3896 if !always_treat_brackets_as_autoclosed {
3897 return selection;
3898 }
3899
3900 if let Some(scope) = buffer.language_scope_at(selection.start) {
3901 for (pair, enabled) in scope.brackets() {
3902 if !enabled || !pair.close {
3903 continue;
3904 }
3905
3906 if buffer.contains_str_at(selection.start, &pair.end) {
3907 let pair_start_len = pair.start.len();
3908 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3909 {
3910 selection.start -= pair_start_len;
3911 selection.end += pair.end.len();
3912
3913 return selection;
3914 }
3915 }
3916 }
3917 }
3918
3919 selection
3920 })
3921 .collect();
3922
3923 drop(buffer);
3924 self.change_selections(None, cx, |selections| selections.select(new_selections));
3925 }
3926
3927 /// Iterate the given selections, and for each one, find the smallest surrounding
3928 /// autoclose region. This uses the ordering of the selections and the autoclose
3929 /// regions to avoid repeated comparisons.
3930 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3931 &'a self,
3932 selections: impl IntoIterator<Item = Selection<D>>,
3933 buffer: &'a MultiBufferSnapshot,
3934 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3935 let mut i = 0;
3936 let mut regions = self.autoclose_regions.as_slice();
3937 selections.into_iter().map(move |selection| {
3938 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3939
3940 let mut enclosing = None;
3941 while let Some(pair_state) = regions.get(i) {
3942 if pair_state.range.end.to_offset(buffer) < range.start {
3943 regions = ®ions[i + 1..];
3944 i = 0;
3945 } else if pair_state.range.start.to_offset(buffer) > range.end {
3946 break;
3947 } else {
3948 if pair_state.selection_id == selection.id {
3949 enclosing = Some(pair_state);
3950 }
3951 i += 1;
3952 }
3953 }
3954
3955 (selection.clone(), enclosing)
3956 })
3957 }
3958
3959 /// Remove any autoclose regions that no longer contain their selection.
3960 fn invalidate_autoclose_regions(
3961 &mut self,
3962 mut selections: &[Selection<Anchor>],
3963 buffer: &MultiBufferSnapshot,
3964 ) {
3965 self.autoclose_regions.retain(|state| {
3966 let mut i = 0;
3967 while let Some(selection) = selections.get(i) {
3968 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3969 selections = &selections[1..];
3970 continue;
3971 }
3972 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3973 break;
3974 }
3975 if selection.id == state.selection_id {
3976 return true;
3977 } else {
3978 i += 1;
3979 }
3980 }
3981 false
3982 });
3983 }
3984
3985 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3986 let offset = position.to_offset(buffer);
3987 let (word_range, kind) = buffer.surrounding_word(offset, true);
3988 if offset > word_range.start && kind == Some(CharKind::Word) {
3989 Some(
3990 buffer
3991 .text_for_range(word_range.start..offset)
3992 .collect::<String>(),
3993 )
3994 } else {
3995 None
3996 }
3997 }
3998
3999 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4000 self.refresh_inlay_hints(
4001 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4002 cx,
4003 );
4004 }
4005
4006 pub fn inlay_hints_enabled(&self) -> bool {
4007 self.inlay_hint_cache.enabled
4008 }
4009
4010 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4011 if self.project.is_none() || self.mode != EditorMode::Full {
4012 return;
4013 }
4014
4015 let reason_description = reason.description();
4016 let ignore_debounce = matches!(
4017 reason,
4018 InlayHintRefreshReason::SettingsChange(_)
4019 | InlayHintRefreshReason::Toggle(_)
4020 | InlayHintRefreshReason::ExcerptsRemoved(_)
4021 );
4022 let (invalidate_cache, required_languages) = match reason {
4023 InlayHintRefreshReason::Toggle(enabled) => {
4024 self.inlay_hint_cache.enabled = enabled;
4025 if enabled {
4026 (InvalidationStrategy::RefreshRequested, None)
4027 } else {
4028 self.inlay_hint_cache.clear();
4029 self.splice_inlays(
4030 self.visible_inlay_hints(cx)
4031 .iter()
4032 .map(|inlay| inlay.id)
4033 .collect(),
4034 Vec::new(),
4035 cx,
4036 );
4037 return;
4038 }
4039 }
4040 InlayHintRefreshReason::SettingsChange(new_settings) => {
4041 match self.inlay_hint_cache.update_settings(
4042 &self.buffer,
4043 new_settings,
4044 self.visible_inlay_hints(cx),
4045 cx,
4046 ) {
4047 ControlFlow::Break(Some(InlaySplice {
4048 to_remove,
4049 to_insert,
4050 })) => {
4051 self.splice_inlays(to_remove, to_insert, cx);
4052 return;
4053 }
4054 ControlFlow::Break(None) => return,
4055 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4056 }
4057 }
4058 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4059 if let Some(InlaySplice {
4060 to_remove,
4061 to_insert,
4062 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4063 {
4064 self.splice_inlays(to_remove, to_insert, cx);
4065 }
4066 return;
4067 }
4068 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4069 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4070 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4071 }
4072 InlayHintRefreshReason::RefreshRequested => {
4073 (InvalidationStrategy::RefreshRequested, None)
4074 }
4075 };
4076
4077 if let Some(InlaySplice {
4078 to_remove,
4079 to_insert,
4080 }) = self.inlay_hint_cache.spawn_hint_refresh(
4081 reason_description,
4082 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4083 invalidate_cache,
4084 ignore_debounce,
4085 cx,
4086 ) {
4087 self.splice_inlays(to_remove, to_insert, cx);
4088 }
4089 }
4090
4091 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4092 self.display_map
4093 .read(cx)
4094 .current_inlays()
4095 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4096 .cloned()
4097 .collect()
4098 }
4099
4100 pub fn excerpts_for_inlay_hints_query(
4101 &self,
4102 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4103 cx: &mut ViewContext<Editor>,
4104 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4105 let Some(project) = self.project.as_ref() else {
4106 return HashMap::default();
4107 };
4108 let project = project.read(cx);
4109 let multi_buffer = self.buffer().read(cx);
4110 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4111 let multi_buffer_visible_start = self
4112 .scroll_manager
4113 .anchor()
4114 .anchor
4115 .to_point(&multi_buffer_snapshot);
4116 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4117 multi_buffer_visible_start
4118 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4119 Bias::Left,
4120 );
4121 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4122 multi_buffer
4123 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4124 .into_iter()
4125 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4126 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4127 let buffer = buffer_handle.read(cx);
4128 let buffer_file = project::File::from_dyn(buffer.file())?;
4129 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4130 let worktree_entry = buffer_worktree
4131 .read(cx)
4132 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4133 if worktree_entry.is_ignored {
4134 return None;
4135 }
4136
4137 let language = buffer.language()?;
4138 if let Some(restrict_to_languages) = restrict_to_languages {
4139 if !restrict_to_languages.contains(language) {
4140 return None;
4141 }
4142 }
4143 Some((
4144 excerpt_id,
4145 (
4146 buffer_handle,
4147 buffer.version().clone(),
4148 excerpt_visible_range,
4149 ),
4150 ))
4151 })
4152 .collect()
4153 }
4154
4155 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4156 TextLayoutDetails {
4157 text_system: cx.text_system().clone(),
4158 editor_style: self.style.clone().unwrap(),
4159 rem_size: cx.rem_size(),
4160 scroll_anchor: self.scroll_manager.anchor(),
4161 visible_rows: self.visible_line_count(),
4162 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4163 }
4164 }
4165
4166 fn splice_inlays(
4167 &self,
4168 to_remove: Vec<InlayId>,
4169 to_insert: Vec<Inlay>,
4170 cx: &mut ViewContext<Self>,
4171 ) {
4172 self.display_map.update(cx, |display_map, cx| {
4173 display_map.splice_inlays(to_remove, to_insert, cx);
4174 });
4175 cx.notify();
4176 }
4177
4178 fn trigger_on_type_formatting(
4179 &self,
4180 input: String,
4181 cx: &mut ViewContext<Self>,
4182 ) -> Option<Task<Result<()>>> {
4183 if input.len() != 1 {
4184 return None;
4185 }
4186
4187 let project = self.project.as_ref()?;
4188 let position = self.selections.newest_anchor().head();
4189 let (buffer, buffer_position) = self
4190 .buffer
4191 .read(cx)
4192 .text_anchor_for_position(position, cx)?;
4193
4194 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4195 // hence we do LSP request & edit on host side only — add formats to host's history.
4196 let push_to_lsp_host_history = true;
4197 // If this is not the host, append its history with new edits.
4198 let push_to_client_history = project.read(cx).is_via_collab();
4199
4200 let on_type_formatting = project.update(cx, |project, cx| {
4201 project.on_type_format(
4202 buffer.clone(),
4203 buffer_position,
4204 input,
4205 push_to_lsp_host_history,
4206 cx,
4207 )
4208 });
4209 Some(cx.spawn(|editor, mut cx| async move {
4210 if let Some(transaction) = on_type_formatting.await? {
4211 if push_to_client_history {
4212 buffer
4213 .update(&mut cx, |buffer, _| {
4214 buffer.push_transaction(transaction, Instant::now());
4215 })
4216 .ok();
4217 }
4218 editor.update(&mut cx, |editor, cx| {
4219 editor.refresh_document_highlights(cx);
4220 })?;
4221 }
4222 Ok(())
4223 }))
4224 }
4225
4226 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4227 if self.pending_rename.is_some() {
4228 return;
4229 }
4230
4231 let Some(provider) = self.completion_provider.as_ref() else {
4232 return;
4233 };
4234
4235 let position = self.selections.newest_anchor().head();
4236 let (buffer, buffer_position) =
4237 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4238 output
4239 } else {
4240 return;
4241 };
4242
4243 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4244 let is_followup_invoke = {
4245 let context_menu_state = self.context_menu.read();
4246 matches!(
4247 context_menu_state.deref(),
4248 Some(ContextMenu::Completions(_))
4249 )
4250 };
4251 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4252 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4253 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4254 CompletionTriggerKind::TRIGGER_CHARACTER
4255 }
4256
4257 _ => CompletionTriggerKind::INVOKED,
4258 };
4259 let completion_context = CompletionContext {
4260 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4261 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4262 Some(String::from(trigger))
4263 } else {
4264 None
4265 }
4266 }),
4267 trigger_kind,
4268 };
4269 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4270 let sort_completions = provider.sort_completions();
4271
4272 let id = post_inc(&mut self.next_completion_id);
4273 let task = cx.spawn(|this, mut cx| {
4274 async move {
4275 this.update(&mut cx, |this, _| {
4276 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4277 })?;
4278 let completions = completions.await.log_err();
4279 let menu = if let Some(completions) = completions {
4280 let mut menu = CompletionsMenu {
4281 id,
4282 sort_completions,
4283 initial_position: position,
4284 match_candidates: completions
4285 .iter()
4286 .enumerate()
4287 .map(|(id, completion)| {
4288 StringMatchCandidate::new(
4289 id,
4290 completion.label.text[completion.label.filter_range.clone()]
4291 .into(),
4292 )
4293 })
4294 .collect(),
4295 buffer: buffer.clone(),
4296 completions: Arc::new(RwLock::new(completions.into())),
4297 matches: Vec::new().into(),
4298 selected_item: 0,
4299 scroll_handle: UniformListScrollHandle::new(),
4300 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4301 DebouncedDelay::new(),
4302 )),
4303 };
4304 menu.filter(query.as_deref(), cx.background_executor().clone())
4305 .await;
4306
4307 if menu.matches.is_empty() {
4308 None
4309 } else {
4310 this.update(&mut cx, |editor, cx| {
4311 let completions = menu.completions.clone();
4312 let matches = menu.matches.clone();
4313
4314 let delay_ms = EditorSettings::get_global(cx)
4315 .completion_documentation_secondary_query_debounce;
4316 let delay = Duration::from_millis(delay_ms);
4317 editor
4318 .completion_documentation_pre_resolve_debounce
4319 .fire_new(delay, cx, |editor, cx| {
4320 CompletionsMenu::pre_resolve_completion_documentation(
4321 buffer,
4322 completions,
4323 matches,
4324 editor,
4325 cx,
4326 )
4327 });
4328 })
4329 .ok();
4330 Some(menu)
4331 }
4332 } else {
4333 None
4334 };
4335
4336 this.update(&mut cx, |this, cx| {
4337 let mut context_menu = this.context_menu.write();
4338 match context_menu.as_ref() {
4339 None => {}
4340
4341 Some(ContextMenu::Completions(prev_menu)) => {
4342 if prev_menu.id > id {
4343 return;
4344 }
4345 }
4346
4347 _ => return,
4348 }
4349
4350 if this.focus_handle.is_focused(cx) && menu.is_some() {
4351 let menu = menu.unwrap();
4352 *context_menu = Some(ContextMenu::Completions(menu));
4353 drop(context_menu);
4354 this.discard_inline_completion(false, cx);
4355 cx.notify();
4356 } else if this.completion_tasks.len() <= 1 {
4357 // If there are no more completion tasks and the last menu was
4358 // empty, we should hide it. If it was already hidden, we should
4359 // also show the copilot completion when available.
4360 drop(context_menu);
4361 if this.hide_context_menu(cx).is_none() {
4362 this.update_visible_inline_completion(cx);
4363 }
4364 }
4365 })?;
4366
4367 Ok::<_, anyhow::Error>(())
4368 }
4369 .log_err()
4370 });
4371
4372 self.completion_tasks.push((id, task));
4373 }
4374
4375 pub fn confirm_completion(
4376 &mut self,
4377 action: &ConfirmCompletion,
4378 cx: &mut ViewContext<Self>,
4379 ) -> Option<Task<Result<()>>> {
4380 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4381 }
4382
4383 pub fn compose_completion(
4384 &mut self,
4385 action: &ComposeCompletion,
4386 cx: &mut ViewContext<Self>,
4387 ) -> Option<Task<Result<()>>> {
4388 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4389 }
4390
4391 fn do_completion(
4392 &mut self,
4393 item_ix: Option<usize>,
4394 intent: CompletionIntent,
4395 cx: &mut ViewContext<Editor>,
4396 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4397 use language::ToOffset as _;
4398
4399 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4400 menu
4401 } else {
4402 return None;
4403 };
4404
4405 let mat = completions_menu
4406 .matches
4407 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4408 let buffer_handle = completions_menu.buffer;
4409 let completions = completions_menu.completions.read();
4410 let completion = completions.get(mat.candidate_id)?;
4411 cx.stop_propagation();
4412
4413 let snippet;
4414 let text;
4415
4416 if completion.is_snippet() {
4417 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4418 text = snippet.as_ref().unwrap().text.clone();
4419 } else {
4420 snippet = None;
4421 text = completion.new_text.clone();
4422 };
4423 let selections = self.selections.all::<usize>(cx);
4424 let buffer = buffer_handle.read(cx);
4425 let old_range = completion.old_range.to_offset(buffer);
4426 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4427
4428 let newest_selection = self.selections.newest_anchor();
4429 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4430 return None;
4431 }
4432
4433 let lookbehind = newest_selection
4434 .start
4435 .text_anchor
4436 .to_offset(buffer)
4437 .saturating_sub(old_range.start);
4438 let lookahead = old_range
4439 .end
4440 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4441 let mut common_prefix_len = old_text
4442 .bytes()
4443 .zip(text.bytes())
4444 .take_while(|(a, b)| a == b)
4445 .count();
4446
4447 let snapshot = self.buffer.read(cx).snapshot(cx);
4448 let mut range_to_replace: Option<Range<isize>> = None;
4449 let mut ranges = Vec::new();
4450 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4451 for selection in &selections {
4452 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4453 let start = selection.start.saturating_sub(lookbehind);
4454 let end = selection.end + lookahead;
4455 if selection.id == newest_selection.id {
4456 range_to_replace = Some(
4457 ((start + common_prefix_len) as isize - selection.start as isize)
4458 ..(end as isize - selection.start as isize),
4459 );
4460 }
4461 ranges.push(start + common_prefix_len..end);
4462 } else {
4463 common_prefix_len = 0;
4464 ranges.clear();
4465 ranges.extend(selections.iter().map(|s| {
4466 if s.id == newest_selection.id {
4467 range_to_replace = Some(
4468 old_range.start.to_offset_utf16(&snapshot).0 as isize
4469 - selection.start as isize
4470 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4471 - selection.start as isize,
4472 );
4473 old_range.clone()
4474 } else {
4475 s.start..s.end
4476 }
4477 }));
4478 break;
4479 }
4480 if !self.linked_edit_ranges.is_empty() {
4481 let start_anchor = snapshot.anchor_before(selection.head());
4482 let end_anchor = snapshot.anchor_after(selection.tail());
4483 if let Some(ranges) = self
4484 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4485 {
4486 for (buffer, edits) in ranges {
4487 linked_edits.entry(buffer.clone()).or_default().extend(
4488 edits
4489 .into_iter()
4490 .map(|range| (range, text[common_prefix_len..].to_owned())),
4491 );
4492 }
4493 }
4494 }
4495 }
4496 let text = &text[common_prefix_len..];
4497
4498 cx.emit(EditorEvent::InputHandled {
4499 utf16_range_to_replace: range_to_replace,
4500 text: text.into(),
4501 });
4502
4503 self.transact(cx, |this, cx| {
4504 if let Some(mut snippet) = snippet {
4505 snippet.text = text.to_string();
4506 for tabstop in snippet.tabstops.iter_mut().flatten() {
4507 tabstop.start -= common_prefix_len as isize;
4508 tabstop.end -= common_prefix_len as isize;
4509 }
4510
4511 this.insert_snippet(&ranges, snippet, cx).log_err();
4512 } else {
4513 this.buffer.update(cx, |buffer, cx| {
4514 buffer.edit(
4515 ranges.iter().map(|range| (range.clone(), text)),
4516 this.autoindent_mode.clone(),
4517 cx,
4518 );
4519 });
4520 }
4521 for (buffer, edits) in linked_edits {
4522 buffer.update(cx, |buffer, cx| {
4523 let snapshot = buffer.snapshot();
4524 let edits = edits
4525 .into_iter()
4526 .map(|(range, text)| {
4527 use text::ToPoint as TP;
4528 let end_point = TP::to_point(&range.end, &snapshot);
4529 let start_point = TP::to_point(&range.start, &snapshot);
4530 (start_point..end_point, text)
4531 })
4532 .sorted_by_key(|(range, _)| range.start)
4533 .collect::<Vec<_>>();
4534 buffer.edit(edits, None, cx);
4535 })
4536 }
4537
4538 this.refresh_inline_completion(true, false, cx);
4539 });
4540
4541 let show_new_completions_on_confirm = completion
4542 .confirm
4543 .as_ref()
4544 .map_or(false, |confirm| confirm(intent, cx));
4545 if show_new_completions_on_confirm {
4546 self.show_completions(&ShowCompletions { trigger: None }, cx);
4547 }
4548
4549 let provider = self.completion_provider.as_ref()?;
4550 let apply_edits = provider.apply_additional_edits_for_completion(
4551 buffer_handle,
4552 completion.clone(),
4553 true,
4554 cx,
4555 );
4556
4557 let editor_settings = EditorSettings::get_global(cx);
4558 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4559 // After the code completion is finished, users often want to know what signatures are needed.
4560 // so we should automatically call signature_help
4561 self.show_signature_help(&ShowSignatureHelp, cx);
4562 }
4563
4564 Some(cx.foreground_executor().spawn(async move {
4565 apply_edits.await?;
4566 Ok(())
4567 }))
4568 }
4569
4570 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4571 let mut context_menu = self.context_menu.write();
4572 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4573 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4574 // Toggle if we're selecting the same one
4575 *context_menu = None;
4576 cx.notify();
4577 return;
4578 } else {
4579 // Otherwise, clear it and start a new one
4580 *context_menu = None;
4581 cx.notify();
4582 }
4583 }
4584 drop(context_menu);
4585 let snapshot = self.snapshot(cx);
4586 let deployed_from_indicator = action.deployed_from_indicator;
4587 let mut task = self.code_actions_task.take();
4588 let action = action.clone();
4589 cx.spawn(|editor, mut cx| async move {
4590 while let Some(prev_task) = task {
4591 prev_task.await.log_err();
4592 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4593 }
4594
4595 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4596 if editor.focus_handle.is_focused(cx) {
4597 let multibuffer_point = action
4598 .deployed_from_indicator
4599 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4600 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4601 let (buffer, buffer_row) = snapshot
4602 .buffer_snapshot
4603 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4604 .and_then(|(buffer_snapshot, range)| {
4605 editor
4606 .buffer
4607 .read(cx)
4608 .buffer(buffer_snapshot.remote_id())
4609 .map(|buffer| (buffer, range.start.row))
4610 })?;
4611 let (_, code_actions) = editor
4612 .available_code_actions
4613 .clone()
4614 .and_then(|(location, code_actions)| {
4615 let snapshot = location.buffer.read(cx).snapshot();
4616 let point_range = location.range.to_point(&snapshot);
4617 let point_range = point_range.start.row..=point_range.end.row;
4618 if point_range.contains(&buffer_row) {
4619 Some((location, code_actions))
4620 } else {
4621 None
4622 }
4623 })
4624 .unzip();
4625 let buffer_id = buffer.read(cx).remote_id();
4626 let tasks = editor
4627 .tasks
4628 .get(&(buffer_id, buffer_row))
4629 .map(|t| Arc::new(t.to_owned()));
4630 if tasks.is_none() && code_actions.is_none() {
4631 return None;
4632 }
4633
4634 editor.completion_tasks.clear();
4635 editor.discard_inline_completion(false, cx);
4636 let task_context =
4637 tasks
4638 .as_ref()
4639 .zip(editor.project.clone())
4640 .map(|(tasks, project)| {
4641 let position = Point::new(buffer_row, tasks.column);
4642 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4643 let location = Location {
4644 buffer: buffer.clone(),
4645 range: range_start..range_start,
4646 };
4647 // Fill in the environmental variables from the tree-sitter captures
4648 let mut captured_task_variables = TaskVariables::default();
4649 for (capture_name, value) in tasks.extra_variables.clone() {
4650 captured_task_variables.insert(
4651 task::VariableName::Custom(capture_name.into()),
4652 value.clone(),
4653 );
4654 }
4655 project.update(cx, |project, cx| {
4656 project.task_context_for_location(
4657 captured_task_variables,
4658 location,
4659 cx,
4660 )
4661 })
4662 });
4663
4664 Some(cx.spawn(|editor, mut cx| async move {
4665 let task_context = match task_context {
4666 Some(task_context) => task_context.await,
4667 None => None,
4668 };
4669 let resolved_tasks =
4670 tasks.zip(task_context).map(|(tasks, task_context)| {
4671 Arc::new(ResolvedTasks {
4672 templates: tasks
4673 .templates
4674 .iter()
4675 .filter_map(|(kind, template)| {
4676 template
4677 .resolve_task(&kind.to_id_base(), &task_context)
4678 .map(|task| (kind.clone(), task))
4679 })
4680 .collect(),
4681 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4682 multibuffer_point.row,
4683 tasks.column,
4684 )),
4685 })
4686 });
4687 let spawn_straight_away = resolved_tasks
4688 .as_ref()
4689 .map_or(false, |tasks| tasks.templates.len() == 1)
4690 && code_actions
4691 .as_ref()
4692 .map_or(true, |actions| actions.is_empty());
4693 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4694 *editor.context_menu.write() =
4695 Some(ContextMenu::CodeActions(CodeActionsMenu {
4696 buffer,
4697 actions: CodeActionContents {
4698 tasks: resolved_tasks,
4699 actions: code_actions,
4700 },
4701 selected_item: Default::default(),
4702 scroll_handle: UniformListScrollHandle::default(),
4703 deployed_from_indicator,
4704 }));
4705 if spawn_straight_away {
4706 if let Some(task) = editor.confirm_code_action(
4707 &ConfirmCodeAction { item_ix: Some(0) },
4708 cx,
4709 ) {
4710 cx.notify();
4711 return task;
4712 }
4713 }
4714 cx.notify();
4715 Task::ready(Ok(()))
4716 }) {
4717 task.await
4718 } else {
4719 Ok(())
4720 }
4721 }))
4722 } else {
4723 Some(Task::ready(Ok(())))
4724 }
4725 })?;
4726 if let Some(task) = spawned_test_task {
4727 task.await?;
4728 }
4729
4730 Ok::<_, anyhow::Error>(())
4731 })
4732 .detach_and_log_err(cx);
4733 }
4734
4735 pub fn confirm_code_action(
4736 &mut self,
4737 action: &ConfirmCodeAction,
4738 cx: &mut ViewContext<Self>,
4739 ) -> Option<Task<Result<()>>> {
4740 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4741 menu
4742 } else {
4743 return None;
4744 };
4745 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4746 let action = actions_menu.actions.get(action_ix)?;
4747 let title = action.label();
4748 let buffer = actions_menu.buffer;
4749 let workspace = self.workspace()?;
4750
4751 match action {
4752 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4753 workspace.update(cx, |workspace, cx| {
4754 workspace::tasks::schedule_resolved_task(
4755 workspace,
4756 task_source_kind,
4757 resolved_task,
4758 false,
4759 cx,
4760 );
4761
4762 Some(Task::ready(Ok(())))
4763 })
4764 }
4765 CodeActionsItem::CodeAction {
4766 excerpt_id,
4767 action,
4768 provider,
4769 } => {
4770 let apply_code_action =
4771 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4772 let workspace = workspace.downgrade();
4773 Some(cx.spawn(|editor, cx| async move {
4774 let project_transaction = apply_code_action.await?;
4775 Self::open_project_transaction(
4776 &editor,
4777 workspace,
4778 project_transaction,
4779 title,
4780 cx,
4781 )
4782 .await
4783 }))
4784 }
4785 }
4786 }
4787
4788 pub async fn open_project_transaction(
4789 this: &WeakView<Editor>,
4790 workspace: WeakView<Workspace>,
4791 transaction: ProjectTransaction,
4792 title: String,
4793 mut cx: AsyncWindowContext,
4794 ) -> Result<()> {
4795 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4796 cx.update(|cx| {
4797 entries.sort_unstable_by_key(|(buffer, _)| {
4798 buffer.read(cx).file().map(|f| f.path().clone())
4799 });
4800 })?;
4801
4802 // If the project transaction's edits are all contained within this editor, then
4803 // avoid opening a new editor to display them.
4804
4805 if let Some((buffer, transaction)) = entries.first() {
4806 if entries.len() == 1 {
4807 let excerpt = this.update(&mut cx, |editor, cx| {
4808 editor
4809 .buffer()
4810 .read(cx)
4811 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4812 })?;
4813 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4814 if excerpted_buffer == *buffer {
4815 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4816 let excerpt_range = excerpt_range.to_offset(buffer);
4817 buffer
4818 .edited_ranges_for_transaction::<usize>(transaction)
4819 .all(|range| {
4820 excerpt_range.start <= range.start
4821 && excerpt_range.end >= range.end
4822 })
4823 })?;
4824
4825 if all_edits_within_excerpt {
4826 return Ok(());
4827 }
4828 }
4829 }
4830 }
4831 } else {
4832 return Ok(());
4833 }
4834
4835 let mut ranges_to_highlight = Vec::new();
4836 let excerpt_buffer = cx.new_model(|cx| {
4837 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4838 for (buffer_handle, transaction) in &entries {
4839 let buffer = buffer_handle.read(cx);
4840 ranges_to_highlight.extend(
4841 multibuffer.push_excerpts_with_context_lines(
4842 buffer_handle.clone(),
4843 buffer
4844 .edited_ranges_for_transaction::<usize>(transaction)
4845 .collect(),
4846 DEFAULT_MULTIBUFFER_CONTEXT,
4847 cx,
4848 ),
4849 );
4850 }
4851 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4852 multibuffer
4853 })?;
4854
4855 workspace.update(&mut cx, |workspace, cx| {
4856 let project = workspace.project().clone();
4857 let editor =
4858 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4859 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4860 editor.update(cx, |editor, cx| {
4861 editor.highlight_background::<Self>(
4862 &ranges_to_highlight,
4863 |theme| theme.editor_highlighted_line_background,
4864 cx,
4865 );
4866 });
4867 })?;
4868
4869 Ok(())
4870 }
4871
4872 pub fn push_code_action_provider(
4873 &mut self,
4874 provider: Arc<dyn CodeActionProvider>,
4875 cx: &mut ViewContext<Self>,
4876 ) {
4877 self.code_action_providers.push(provider);
4878 self.refresh_code_actions(cx);
4879 }
4880
4881 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4882 let buffer = self.buffer.read(cx);
4883 let newest_selection = self.selections.newest_anchor().clone();
4884 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4885 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4886 if start_buffer != end_buffer {
4887 return None;
4888 }
4889
4890 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4891 cx.background_executor()
4892 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4893 .await;
4894
4895 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4896 let providers = this.code_action_providers.clone();
4897 let tasks = this
4898 .code_action_providers
4899 .iter()
4900 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4901 .collect::<Vec<_>>();
4902 (providers, tasks)
4903 })?;
4904
4905 let mut actions = Vec::new();
4906 for (provider, provider_actions) in
4907 providers.into_iter().zip(future::join_all(tasks).await)
4908 {
4909 if let Some(provider_actions) = provider_actions.log_err() {
4910 actions.extend(provider_actions.into_iter().map(|action| {
4911 AvailableCodeAction {
4912 excerpt_id: newest_selection.start.excerpt_id,
4913 action,
4914 provider: provider.clone(),
4915 }
4916 }));
4917 }
4918 }
4919
4920 this.update(&mut cx, |this, cx| {
4921 this.available_code_actions = if actions.is_empty() {
4922 None
4923 } else {
4924 Some((
4925 Location {
4926 buffer: start_buffer,
4927 range: start..end,
4928 },
4929 actions.into(),
4930 ))
4931 };
4932 cx.notify();
4933 })
4934 }));
4935 None
4936 }
4937
4938 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4939 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4940 self.show_git_blame_inline = false;
4941
4942 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4943 cx.background_executor().timer(delay).await;
4944
4945 this.update(&mut cx, |this, cx| {
4946 this.show_git_blame_inline = true;
4947 cx.notify();
4948 })
4949 .log_err();
4950 }));
4951 }
4952 }
4953
4954 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4955 if self.pending_rename.is_some() {
4956 return None;
4957 }
4958
4959 let project = self.project.clone()?;
4960 let buffer = self.buffer.read(cx);
4961 let newest_selection = self.selections.newest_anchor().clone();
4962 let cursor_position = newest_selection.head();
4963 let (cursor_buffer, cursor_buffer_position) =
4964 buffer.text_anchor_for_position(cursor_position, cx)?;
4965 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4966 if cursor_buffer != tail_buffer {
4967 return None;
4968 }
4969
4970 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4971 cx.background_executor()
4972 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4973 .await;
4974
4975 let highlights = if let Some(highlights) = project
4976 .update(&mut cx, |project, cx| {
4977 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4978 })
4979 .log_err()
4980 {
4981 highlights.await.log_err()
4982 } else {
4983 None
4984 };
4985
4986 if let Some(highlights) = highlights {
4987 this.update(&mut cx, |this, cx| {
4988 if this.pending_rename.is_some() {
4989 return;
4990 }
4991
4992 let buffer_id = cursor_position.buffer_id;
4993 let buffer = this.buffer.read(cx);
4994 if !buffer
4995 .text_anchor_for_position(cursor_position, cx)
4996 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4997 {
4998 return;
4999 }
5000
5001 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5002 let mut write_ranges = Vec::new();
5003 let mut read_ranges = Vec::new();
5004 for highlight in highlights {
5005 for (excerpt_id, excerpt_range) in
5006 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5007 {
5008 let start = highlight
5009 .range
5010 .start
5011 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5012 let end = highlight
5013 .range
5014 .end
5015 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5016 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5017 continue;
5018 }
5019
5020 let range = Anchor {
5021 buffer_id,
5022 excerpt_id,
5023 text_anchor: start,
5024 }..Anchor {
5025 buffer_id,
5026 excerpt_id,
5027 text_anchor: end,
5028 };
5029 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5030 write_ranges.push(range);
5031 } else {
5032 read_ranges.push(range);
5033 }
5034 }
5035 }
5036
5037 this.highlight_background::<DocumentHighlightRead>(
5038 &read_ranges,
5039 |theme| theme.editor_document_highlight_read_background,
5040 cx,
5041 );
5042 this.highlight_background::<DocumentHighlightWrite>(
5043 &write_ranges,
5044 |theme| theme.editor_document_highlight_write_background,
5045 cx,
5046 );
5047 cx.notify();
5048 })
5049 .log_err();
5050 }
5051 }));
5052 None
5053 }
5054
5055 pub fn refresh_inline_completion(
5056 &mut self,
5057 debounce: bool,
5058 user_requested: bool,
5059 cx: &mut ViewContext<Self>,
5060 ) -> Option<()> {
5061 let provider = self.inline_completion_provider()?;
5062 let cursor = self.selections.newest_anchor().head();
5063 let (buffer, cursor_buffer_position) =
5064 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5065
5066 if !user_requested
5067 && (!self.enable_inline_completions
5068 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5069 {
5070 self.discard_inline_completion(false, cx);
5071 return None;
5072 }
5073
5074 self.update_visible_inline_completion(cx);
5075 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5076 Some(())
5077 }
5078
5079 fn cycle_inline_completion(
5080 &mut self,
5081 direction: Direction,
5082 cx: &mut ViewContext<Self>,
5083 ) -> Option<()> {
5084 let provider = self.inline_completion_provider()?;
5085 let cursor = self.selections.newest_anchor().head();
5086 let (buffer, cursor_buffer_position) =
5087 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5088 if !self.enable_inline_completions
5089 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5090 {
5091 return None;
5092 }
5093
5094 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5095 self.update_visible_inline_completion(cx);
5096
5097 Some(())
5098 }
5099
5100 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5101 if !self.has_active_inline_completion(cx) {
5102 self.refresh_inline_completion(false, true, cx);
5103 return;
5104 }
5105
5106 self.update_visible_inline_completion(cx);
5107 }
5108
5109 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5110 self.show_cursor_names(cx);
5111 }
5112
5113 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5114 self.show_cursor_names = true;
5115 cx.notify();
5116 cx.spawn(|this, mut cx| async move {
5117 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5118 this.update(&mut cx, |this, cx| {
5119 this.show_cursor_names = false;
5120 cx.notify()
5121 })
5122 .ok()
5123 })
5124 .detach();
5125 }
5126
5127 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5128 if self.has_active_inline_completion(cx) {
5129 self.cycle_inline_completion(Direction::Next, cx);
5130 } else {
5131 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5132 if is_copilot_disabled {
5133 cx.propagate();
5134 }
5135 }
5136 }
5137
5138 pub fn previous_inline_completion(
5139 &mut self,
5140 _: &PreviousInlineCompletion,
5141 cx: &mut ViewContext<Self>,
5142 ) {
5143 if self.has_active_inline_completion(cx) {
5144 self.cycle_inline_completion(Direction::Prev, cx);
5145 } else {
5146 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5147 if is_copilot_disabled {
5148 cx.propagate();
5149 }
5150 }
5151 }
5152
5153 pub fn accept_inline_completion(
5154 &mut self,
5155 _: &AcceptInlineCompletion,
5156 cx: &mut ViewContext<Self>,
5157 ) {
5158 let Some(completion) = self.take_active_inline_completion(cx) else {
5159 return;
5160 };
5161 if let Some(provider) = self.inline_completion_provider() {
5162 provider.accept(cx);
5163 }
5164
5165 cx.emit(EditorEvent::InputHandled {
5166 utf16_range_to_replace: None,
5167 text: completion.text.to_string().into(),
5168 });
5169
5170 if let Some(range) = completion.delete_range {
5171 self.change_selections(None, cx, |s| s.select_ranges([range]))
5172 }
5173 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5174 self.refresh_inline_completion(true, true, cx);
5175 cx.notify();
5176 }
5177
5178 pub fn accept_partial_inline_completion(
5179 &mut self,
5180 _: &AcceptPartialInlineCompletion,
5181 cx: &mut ViewContext<Self>,
5182 ) {
5183 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5184 if let Some(completion) = self.take_active_inline_completion(cx) {
5185 let mut partial_completion = completion
5186 .text
5187 .chars()
5188 .by_ref()
5189 .take_while(|c| c.is_alphabetic())
5190 .collect::<String>();
5191 if partial_completion.is_empty() {
5192 partial_completion = completion
5193 .text
5194 .chars()
5195 .by_ref()
5196 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5197 .collect::<String>();
5198 }
5199
5200 cx.emit(EditorEvent::InputHandled {
5201 utf16_range_to_replace: None,
5202 text: partial_completion.clone().into(),
5203 });
5204
5205 if let Some(range) = completion.delete_range {
5206 self.change_selections(None, cx, |s| s.select_ranges([range]))
5207 }
5208 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5209
5210 self.refresh_inline_completion(true, true, cx);
5211 cx.notify();
5212 }
5213 }
5214 }
5215
5216 fn discard_inline_completion(
5217 &mut self,
5218 should_report_inline_completion_event: bool,
5219 cx: &mut ViewContext<Self>,
5220 ) -> bool {
5221 if let Some(provider) = self.inline_completion_provider() {
5222 provider.discard(should_report_inline_completion_event, cx);
5223 }
5224
5225 self.take_active_inline_completion(cx).is_some()
5226 }
5227
5228 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5229 if let Some(completion) = self.active_inline_completion.as_ref() {
5230 let buffer = self.buffer.read(cx).read(cx);
5231 completion.position.is_valid(&buffer)
5232 } else {
5233 false
5234 }
5235 }
5236
5237 fn take_active_inline_completion(
5238 &mut self,
5239 cx: &mut ViewContext<Self>,
5240 ) -> Option<CompletionState> {
5241 let completion = self.active_inline_completion.take()?;
5242 let render_inlay_ids = completion.render_inlay_ids.clone();
5243 self.display_map.update(cx, |map, cx| {
5244 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5245 });
5246 let buffer = self.buffer.read(cx).read(cx);
5247
5248 if completion.position.is_valid(&buffer) {
5249 Some(completion)
5250 } else {
5251 None
5252 }
5253 }
5254
5255 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5256 let selection = self.selections.newest_anchor();
5257 let cursor = selection.head();
5258
5259 let excerpt_id = cursor.excerpt_id;
5260
5261 if self.context_menu.read().is_none()
5262 && self.completion_tasks.is_empty()
5263 && selection.start == selection.end
5264 {
5265 if let Some(provider) = self.inline_completion_provider() {
5266 if let Some((buffer, cursor_buffer_position)) =
5267 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5268 {
5269 if let Some(proposal) =
5270 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5271 {
5272 let mut to_remove = Vec::new();
5273 if let Some(completion) = self.active_inline_completion.take() {
5274 to_remove.extend(completion.render_inlay_ids.iter());
5275 }
5276
5277 let to_add = proposal
5278 .inlays
5279 .iter()
5280 .filter_map(|inlay| {
5281 let snapshot = self.buffer.read(cx).snapshot(cx);
5282 let id = post_inc(&mut self.next_inlay_id);
5283 match inlay {
5284 InlayProposal::Hint(position, hint) => {
5285 let position =
5286 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5287 Some(Inlay::hint(id, position, hint))
5288 }
5289 InlayProposal::Suggestion(position, text) => {
5290 let position =
5291 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5292 Some(Inlay::suggestion(id, position, text.clone()))
5293 }
5294 }
5295 })
5296 .collect_vec();
5297
5298 self.active_inline_completion = Some(CompletionState {
5299 position: cursor,
5300 text: proposal.text,
5301 delete_range: proposal.delete_range.and_then(|range| {
5302 let snapshot = self.buffer.read(cx).snapshot(cx);
5303 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5304 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5305 Some(start?..end?)
5306 }),
5307 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5308 });
5309
5310 self.display_map
5311 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5312
5313 cx.notify();
5314 return;
5315 }
5316 }
5317 }
5318 }
5319
5320 self.discard_inline_completion(false, cx);
5321 }
5322
5323 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5324 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5325 }
5326
5327 fn render_code_actions_indicator(
5328 &self,
5329 _style: &EditorStyle,
5330 row: DisplayRow,
5331 is_active: bool,
5332 cx: &mut ViewContext<Self>,
5333 ) -> Option<IconButton> {
5334 if self.available_code_actions.is_some() {
5335 Some(
5336 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5337 .shape(ui::IconButtonShape::Square)
5338 .icon_size(IconSize::XSmall)
5339 .icon_color(Color::Muted)
5340 .selected(is_active)
5341 .on_click(cx.listener(move |editor, _e, cx| {
5342 editor.focus(cx);
5343 editor.toggle_code_actions(
5344 &ToggleCodeActions {
5345 deployed_from_indicator: Some(row),
5346 },
5347 cx,
5348 );
5349 })),
5350 )
5351 } else {
5352 None
5353 }
5354 }
5355
5356 fn clear_tasks(&mut self) {
5357 self.tasks.clear()
5358 }
5359
5360 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5361 if self.tasks.insert(key, value).is_some() {
5362 // This case should hopefully be rare, but just in case...
5363 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5364 }
5365 }
5366
5367 fn render_run_indicator(
5368 &self,
5369 _style: &EditorStyle,
5370 is_active: bool,
5371 row: DisplayRow,
5372 cx: &mut ViewContext<Self>,
5373 ) -> IconButton {
5374 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5375 .shape(ui::IconButtonShape::Square)
5376 .icon_size(IconSize::XSmall)
5377 .icon_color(Color::Muted)
5378 .selected(is_active)
5379 .on_click(cx.listener(move |editor, _e, cx| {
5380 editor.focus(cx);
5381 editor.toggle_code_actions(
5382 &ToggleCodeActions {
5383 deployed_from_indicator: Some(row),
5384 },
5385 cx,
5386 );
5387 }))
5388 }
5389
5390 pub fn context_menu_visible(&self) -> bool {
5391 self.context_menu
5392 .read()
5393 .as_ref()
5394 .map_or(false, |menu| menu.visible())
5395 }
5396
5397 fn render_context_menu(
5398 &self,
5399 cursor_position: DisplayPoint,
5400 style: &EditorStyle,
5401 max_height: Pixels,
5402 cx: &mut ViewContext<Editor>,
5403 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5404 self.context_menu.read().as_ref().map(|menu| {
5405 menu.render(
5406 cursor_position,
5407 style,
5408 max_height,
5409 self.workspace.as_ref().map(|(w, _)| w.clone()),
5410 cx,
5411 )
5412 })
5413 }
5414
5415 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5416 cx.notify();
5417 self.completion_tasks.clear();
5418 let context_menu = self.context_menu.write().take();
5419 if context_menu.is_some() {
5420 self.update_visible_inline_completion(cx);
5421 }
5422 context_menu
5423 }
5424
5425 pub fn insert_snippet(
5426 &mut self,
5427 insertion_ranges: &[Range<usize>],
5428 snippet: Snippet,
5429 cx: &mut ViewContext<Self>,
5430 ) -> Result<()> {
5431 struct Tabstop<T> {
5432 is_end_tabstop: bool,
5433 ranges: Vec<Range<T>>,
5434 }
5435
5436 let tabstops = self.buffer.update(cx, |buffer, cx| {
5437 let snippet_text: Arc<str> = snippet.text.clone().into();
5438 buffer.edit(
5439 insertion_ranges
5440 .iter()
5441 .cloned()
5442 .map(|range| (range, snippet_text.clone())),
5443 Some(AutoindentMode::EachLine),
5444 cx,
5445 );
5446
5447 let snapshot = &*buffer.read(cx);
5448 let snippet = &snippet;
5449 snippet
5450 .tabstops
5451 .iter()
5452 .map(|tabstop| {
5453 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5454 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5455 });
5456 let mut tabstop_ranges = tabstop
5457 .iter()
5458 .flat_map(|tabstop_range| {
5459 let mut delta = 0_isize;
5460 insertion_ranges.iter().map(move |insertion_range| {
5461 let insertion_start = insertion_range.start as isize + delta;
5462 delta +=
5463 snippet.text.len() as isize - insertion_range.len() as isize;
5464
5465 let start = ((insertion_start + tabstop_range.start) as usize)
5466 .min(snapshot.len());
5467 let end = ((insertion_start + tabstop_range.end) as usize)
5468 .min(snapshot.len());
5469 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5470 })
5471 })
5472 .collect::<Vec<_>>();
5473 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5474
5475 Tabstop {
5476 is_end_tabstop,
5477 ranges: tabstop_ranges,
5478 }
5479 })
5480 .collect::<Vec<_>>()
5481 });
5482 if let Some(tabstop) = tabstops.first() {
5483 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5484 s.select_ranges(tabstop.ranges.iter().cloned());
5485 });
5486
5487 // If we're already at the last tabstop and it's at the end of the snippet,
5488 // we're done, we don't need to keep the state around.
5489 if !tabstop.is_end_tabstop {
5490 let ranges = tabstops
5491 .into_iter()
5492 .map(|tabstop| tabstop.ranges)
5493 .collect::<Vec<_>>();
5494 self.snippet_stack.push(SnippetState {
5495 active_index: 0,
5496 ranges,
5497 });
5498 }
5499
5500 // Check whether the just-entered snippet ends with an auto-closable bracket.
5501 if self.autoclose_regions.is_empty() {
5502 let snapshot = self.buffer.read(cx).snapshot(cx);
5503 for selection in &mut self.selections.all::<Point>(cx) {
5504 let selection_head = selection.head();
5505 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5506 continue;
5507 };
5508
5509 let mut bracket_pair = None;
5510 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5511 let prev_chars = snapshot
5512 .reversed_chars_at(selection_head)
5513 .collect::<String>();
5514 for (pair, enabled) in scope.brackets() {
5515 if enabled
5516 && pair.close
5517 && prev_chars.starts_with(pair.start.as_str())
5518 && next_chars.starts_with(pair.end.as_str())
5519 {
5520 bracket_pair = Some(pair.clone());
5521 break;
5522 }
5523 }
5524 if let Some(pair) = bracket_pair {
5525 let start = snapshot.anchor_after(selection_head);
5526 let end = snapshot.anchor_after(selection_head);
5527 self.autoclose_regions.push(AutocloseRegion {
5528 selection_id: selection.id,
5529 range: start..end,
5530 pair,
5531 });
5532 }
5533 }
5534 }
5535 }
5536 Ok(())
5537 }
5538
5539 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5540 self.move_to_snippet_tabstop(Bias::Right, cx)
5541 }
5542
5543 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5544 self.move_to_snippet_tabstop(Bias::Left, cx)
5545 }
5546
5547 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5548 if let Some(mut snippet) = self.snippet_stack.pop() {
5549 match bias {
5550 Bias::Left => {
5551 if snippet.active_index > 0 {
5552 snippet.active_index -= 1;
5553 } else {
5554 self.snippet_stack.push(snippet);
5555 return false;
5556 }
5557 }
5558 Bias::Right => {
5559 if snippet.active_index + 1 < snippet.ranges.len() {
5560 snippet.active_index += 1;
5561 } else {
5562 self.snippet_stack.push(snippet);
5563 return false;
5564 }
5565 }
5566 }
5567 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5568 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5569 s.select_anchor_ranges(current_ranges.iter().cloned())
5570 });
5571 // If snippet state is not at the last tabstop, push it back on the stack
5572 if snippet.active_index + 1 < snippet.ranges.len() {
5573 self.snippet_stack.push(snippet);
5574 }
5575 return true;
5576 }
5577 }
5578
5579 false
5580 }
5581
5582 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5583 self.transact(cx, |this, cx| {
5584 this.select_all(&SelectAll, cx);
5585 this.insert("", cx);
5586 });
5587 }
5588
5589 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5590 self.transact(cx, |this, cx| {
5591 this.select_autoclose_pair(cx);
5592 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5593 if !this.linked_edit_ranges.is_empty() {
5594 let selections = this.selections.all::<MultiBufferPoint>(cx);
5595 let snapshot = this.buffer.read(cx).snapshot(cx);
5596
5597 for selection in selections.iter() {
5598 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5599 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5600 if selection_start.buffer_id != selection_end.buffer_id {
5601 continue;
5602 }
5603 if let Some(ranges) =
5604 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5605 {
5606 for (buffer, entries) in ranges {
5607 linked_ranges.entry(buffer).or_default().extend(entries);
5608 }
5609 }
5610 }
5611 }
5612
5613 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5614 if !this.selections.line_mode {
5615 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5616 for selection in &mut selections {
5617 if selection.is_empty() {
5618 let old_head = selection.head();
5619 let mut new_head =
5620 movement::left(&display_map, old_head.to_display_point(&display_map))
5621 .to_point(&display_map);
5622 if let Some((buffer, line_buffer_range)) = display_map
5623 .buffer_snapshot
5624 .buffer_line_for_row(MultiBufferRow(old_head.row))
5625 {
5626 let indent_size =
5627 buffer.indent_size_for_line(line_buffer_range.start.row);
5628 let indent_len = match indent_size.kind {
5629 IndentKind::Space => {
5630 buffer.settings_at(line_buffer_range.start, cx).tab_size
5631 }
5632 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5633 };
5634 if old_head.column <= indent_size.len && old_head.column > 0 {
5635 let indent_len = indent_len.get();
5636 new_head = cmp::min(
5637 new_head,
5638 MultiBufferPoint::new(
5639 old_head.row,
5640 ((old_head.column - 1) / indent_len) * indent_len,
5641 ),
5642 );
5643 }
5644 }
5645
5646 selection.set_head(new_head, SelectionGoal::None);
5647 }
5648 }
5649 }
5650
5651 this.signature_help_state.set_backspace_pressed(true);
5652 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5653 this.insert("", cx);
5654 let empty_str: Arc<str> = Arc::from("");
5655 for (buffer, edits) in linked_ranges {
5656 let snapshot = buffer.read(cx).snapshot();
5657 use text::ToPoint as TP;
5658
5659 let edits = edits
5660 .into_iter()
5661 .map(|range| {
5662 let end_point = TP::to_point(&range.end, &snapshot);
5663 let mut start_point = TP::to_point(&range.start, &snapshot);
5664
5665 if end_point == start_point {
5666 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5667 .saturating_sub(1);
5668 start_point = TP::to_point(&offset, &snapshot);
5669 };
5670
5671 (start_point..end_point, empty_str.clone())
5672 })
5673 .sorted_by_key(|(range, _)| range.start)
5674 .collect::<Vec<_>>();
5675 buffer.update(cx, |this, cx| {
5676 this.edit(edits, None, cx);
5677 })
5678 }
5679 this.refresh_inline_completion(true, false, cx);
5680 linked_editing_ranges::refresh_linked_ranges(this, cx);
5681 });
5682 }
5683
5684 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5685 self.transact(cx, |this, cx| {
5686 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5687 let line_mode = s.line_mode;
5688 s.move_with(|map, selection| {
5689 if selection.is_empty() && !line_mode {
5690 let cursor = movement::right(map, selection.head());
5691 selection.end = cursor;
5692 selection.reversed = true;
5693 selection.goal = SelectionGoal::None;
5694 }
5695 })
5696 });
5697 this.insert("", cx);
5698 this.refresh_inline_completion(true, false, cx);
5699 });
5700 }
5701
5702 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5703 if self.move_to_prev_snippet_tabstop(cx) {
5704 return;
5705 }
5706
5707 self.outdent(&Outdent, cx);
5708 }
5709
5710 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5711 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5712 return;
5713 }
5714
5715 let mut selections = self.selections.all_adjusted(cx);
5716 let buffer = self.buffer.read(cx);
5717 let snapshot = buffer.snapshot(cx);
5718 let rows_iter = selections.iter().map(|s| s.head().row);
5719 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5720
5721 let mut edits = Vec::new();
5722 let mut prev_edited_row = 0;
5723 let mut row_delta = 0;
5724 for selection in &mut selections {
5725 if selection.start.row != prev_edited_row {
5726 row_delta = 0;
5727 }
5728 prev_edited_row = selection.end.row;
5729
5730 // If the selection is non-empty, then increase the indentation of the selected lines.
5731 if !selection.is_empty() {
5732 row_delta =
5733 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5734 continue;
5735 }
5736
5737 // If the selection is empty and the cursor is in the leading whitespace before the
5738 // suggested indentation, then auto-indent the line.
5739 let cursor = selection.head();
5740 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5741 if let Some(suggested_indent) =
5742 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5743 {
5744 if cursor.column < suggested_indent.len
5745 && cursor.column <= current_indent.len
5746 && current_indent.len <= suggested_indent.len
5747 {
5748 selection.start = Point::new(cursor.row, suggested_indent.len);
5749 selection.end = selection.start;
5750 if row_delta == 0 {
5751 edits.extend(Buffer::edit_for_indent_size_adjustment(
5752 cursor.row,
5753 current_indent,
5754 suggested_indent,
5755 ));
5756 row_delta = suggested_indent.len - current_indent.len;
5757 }
5758 continue;
5759 }
5760 }
5761
5762 // Otherwise, insert a hard or soft tab.
5763 let settings = buffer.settings_at(cursor, cx);
5764 let tab_size = if settings.hard_tabs {
5765 IndentSize::tab()
5766 } else {
5767 let tab_size = settings.tab_size.get();
5768 let char_column = snapshot
5769 .text_for_range(Point::new(cursor.row, 0)..cursor)
5770 .flat_map(str::chars)
5771 .count()
5772 + row_delta as usize;
5773 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5774 IndentSize::spaces(chars_to_next_tab_stop)
5775 };
5776 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5777 selection.end = selection.start;
5778 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5779 row_delta += tab_size.len;
5780 }
5781
5782 self.transact(cx, |this, cx| {
5783 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5784 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5785 this.refresh_inline_completion(true, false, cx);
5786 });
5787 }
5788
5789 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5790 if self.read_only(cx) {
5791 return;
5792 }
5793 let mut selections = self.selections.all::<Point>(cx);
5794 let mut prev_edited_row = 0;
5795 let mut row_delta = 0;
5796 let mut edits = Vec::new();
5797 let buffer = self.buffer.read(cx);
5798 let snapshot = buffer.snapshot(cx);
5799 for selection in &mut selections {
5800 if selection.start.row != prev_edited_row {
5801 row_delta = 0;
5802 }
5803 prev_edited_row = selection.end.row;
5804
5805 row_delta =
5806 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5807 }
5808
5809 self.transact(cx, |this, cx| {
5810 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5811 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5812 });
5813 }
5814
5815 fn indent_selection(
5816 buffer: &MultiBuffer,
5817 snapshot: &MultiBufferSnapshot,
5818 selection: &mut Selection<Point>,
5819 edits: &mut Vec<(Range<Point>, String)>,
5820 delta_for_start_row: u32,
5821 cx: &AppContext,
5822 ) -> u32 {
5823 let settings = buffer.settings_at(selection.start, cx);
5824 let tab_size = settings.tab_size.get();
5825 let indent_kind = if settings.hard_tabs {
5826 IndentKind::Tab
5827 } else {
5828 IndentKind::Space
5829 };
5830 let mut start_row = selection.start.row;
5831 let mut end_row = selection.end.row + 1;
5832
5833 // If a selection ends at the beginning of a line, don't indent
5834 // that last line.
5835 if selection.end.column == 0 && selection.end.row > selection.start.row {
5836 end_row -= 1;
5837 }
5838
5839 // Avoid re-indenting a row that has already been indented by a
5840 // previous selection, but still update this selection's column
5841 // to reflect that indentation.
5842 if delta_for_start_row > 0 {
5843 start_row += 1;
5844 selection.start.column += delta_for_start_row;
5845 if selection.end.row == selection.start.row {
5846 selection.end.column += delta_for_start_row;
5847 }
5848 }
5849
5850 let mut delta_for_end_row = 0;
5851 let has_multiple_rows = start_row + 1 != end_row;
5852 for row in start_row..end_row {
5853 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5854 let indent_delta = match (current_indent.kind, indent_kind) {
5855 (IndentKind::Space, IndentKind::Space) => {
5856 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5857 IndentSize::spaces(columns_to_next_tab_stop)
5858 }
5859 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5860 (_, IndentKind::Tab) => IndentSize::tab(),
5861 };
5862
5863 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5864 0
5865 } else {
5866 selection.start.column
5867 };
5868 let row_start = Point::new(row, start);
5869 edits.push((
5870 row_start..row_start,
5871 indent_delta.chars().collect::<String>(),
5872 ));
5873
5874 // Update this selection's endpoints to reflect the indentation.
5875 if row == selection.start.row {
5876 selection.start.column += indent_delta.len;
5877 }
5878 if row == selection.end.row {
5879 selection.end.column += indent_delta.len;
5880 delta_for_end_row = indent_delta.len;
5881 }
5882 }
5883
5884 if selection.start.row == selection.end.row {
5885 delta_for_start_row + delta_for_end_row
5886 } else {
5887 delta_for_end_row
5888 }
5889 }
5890
5891 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5892 if self.read_only(cx) {
5893 return;
5894 }
5895 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5896 let selections = self.selections.all::<Point>(cx);
5897 let mut deletion_ranges = Vec::new();
5898 let mut last_outdent = None;
5899 {
5900 let buffer = self.buffer.read(cx);
5901 let snapshot = buffer.snapshot(cx);
5902 for selection in &selections {
5903 let settings = buffer.settings_at(selection.start, cx);
5904 let tab_size = settings.tab_size.get();
5905 let mut rows = selection.spanned_rows(false, &display_map);
5906
5907 // Avoid re-outdenting a row that has already been outdented by a
5908 // previous selection.
5909 if let Some(last_row) = last_outdent {
5910 if last_row == rows.start {
5911 rows.start = rows.start.next_row();
5912 }
5913 }
5914 let has_multiple_rows = rows.len() > 1;
5915 for row in rows.iter_rows() {
5916 let indent_size = snapshot.indent_size_for_line(row);
5917 if indent_size.len > 0 {
5918 let deletion_len = match indent_size.kind {
5919 IndentKind::Space => {
5920 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5921 if columns_to_prev_tab_stop == 0 {
5922 tab_size
5923 } else {
5924 columns_to_prev_tab_stop
5925 }
5926 }
5927 IndentKind::Tab => 1,
5928 };
5929 let start = if has_multiple_rows
5930 || deletion_len > selection.start.column
5931 || indent_size.len < selection.start.column
5932 {
5933 0
5934 } else {
5935 selection.start.column - deletion_len
5936 };
5937 deletion_ranges.push(
5938 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5939 );
5940 last_outdent = Some(row);
5941 }
5942 }
5943 }
5944 }
5945
5946 self.transact(cx, |this, cx| {
5947 this.buffer.update(cx, |buffer, cx| {
5948 let empty_str: Arc<str> = Arc::default();
5949 buffer.edit(
5950 deletion_ranges
5951 .into_iter()
5952 .map(|range| (range, empty_str.clone())),
5953 None,
5954 cx,
5955 );
5956 });
5957 let selections = this.selections.all::<usize>(cx);
5958 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5959 });
5960 }
5961
5962 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5963 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5964 let selections = self.selections.all::<Point>(cx);
5965
5966 let mut new_cursors = Vec::new();
5967 let mut edit_ranges = Vec::new();
5968 let mut selections = selections.iter().peekable();
5969 while let Some(selection) = selections.next() {
5970 let mut rows = selection.spanned_rows(false, &display_map);
5971 let goal_display_column = selection.head().to_display_point(&display_map).column();
5972
5973 // Accumulate contiguous regions of rows that we want to delete.
5974 while let Some(next_selection) = selections.peek() {
5975 let next_rows = next_selection.spanned_rows(false, &display_map);
5976 if next_rows.start <= rows.end {
5977 rows.end = next_rows.end;
5978 selections.next().unwrap();
5979 } else {
5980 break;
5981 }
5982 }
5983
5984 let buffer = &display_map.buffer_snapshot;
5985 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5986 let edit_end;
5987 let cursor_buffer_row;
5988 if buffer.max_point().row >= rows.end.0 {
5989 // If there's a line after the range, delete the \n from the end of the row range
5990 // and position the cursor on the next line.
5991 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5992 cursor_buffer_row = rows.end;
5993 } else {
5994 // If there isn't a line after the range, delete the \n from the line before the
5995 // start of the row range and position the cursor there.
5996 edit_start = edit_start.saturating_sub(1);
5997 edit_end = buffer.len();
5998 cursor_buffer_row = rows.start.previous_row();
5999 }
6000
6001 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6002 *cursor.column_mut() =
6003 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6004
6005 new_cursors.push((
6006 selection.id,
6007 buffer.anchor_after(cursor.to_point(&display_map)),
6008 ));
6009 edit_ranges.push(edit_start..edit_end);
6010 }
6011
6012 self.transact(cx, |this, cx| {
6013 let buffer = this.buffer.update(cx, |buffer, cx| {
6014 let empty_str: Arc<str> = Arc::default();
6015 buffer.edit(
6016 edit_ranges
6017 .into_iter()
6018 .map(|range| (range, empty_str.clone())),
6019 None,
6020 cx,
6021 );
6022 buffer.snapshot(cx)
6023 });
6024 let new_selections = new_cursors
6025 .into_iter()
6026 .map(|(id, cursor)| {
6027 let cursor = cursor.to_point(&buffer);
6028 Selection {
6029 id,
6030 start: cursor,
6031 end: cursor,
6032 reversed: false,
6033 goal: SelectionGoal::None,
6034 }
6035 })
6036 .collect();
6037
6038 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6039 s.select(new_selections);
6040 });
6041 });
6042 }
6043
6044 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6045 if self.read_only(cx) {
6046 return;
6047 }
6048 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6049 for selection in self.selections.all::<Point>(cx) {
6050 let start = MultiBufferRow(selection.start.row);
6051 let end = if selection.start.row == selection.end.row {
6052 MultiBufferRow(selection.start.row + 1)
6053 } else {
6054 MultiBufferRow(selection.end.row)
6055 };
6056
6057 if let Some(last_row_range) = row_ranges.last_mut() {
6058 if start <= last_row_range.end {
6059 last_row_range.end = end;
6060 continue;
6061 }
6062 }
6063 row_ranges.push(start..end);
6064 }
6065
6066 let snapshot = self.buffer.read(cx).snapshot(cx);
6067 let mut cursor_positions = Vec::new();
6068 for row_range in &row_ranges {
6069 let anchor = snapshot.anchor_before(Point::new(
6070 row_range.end.previous_row().0,
6071 snapshot.line_len(row_range.end.previous_row()),
6072 ));
6073 cursor_positions.push(anchor..anchor);
6074 }
6075
6076 self.transact(cx, |this, cx| {
6077 for row_range in row_ranges.into_iter().rev() {
6078 for row in row_range.iter_rows().rev() {
6079 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6080 let next_line_row = row.next_row();
6081 let indent = snapshot.indent_size_for_line(next_line_row);
6082 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6083
6084 let replace = if snapshot.line_len(next_line_row) > indent.len {
6085 " "
6086 } else {
6087 ""
6088 };
6089
6090 this.buffer.update(cx, |buffer, cx| {
6091 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6092 });
6093 }
6094 }
6095
6096 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6097 s.select_anchor_ranges(cursor_positions)
6098 });
6099 });
6100 }
6101
6102 pub fn sort_lines_case_sensitive(
6103 &mut self,
6104 _: &SortLinesCaseSensitive,
6105 cx: &mut ViewContext<Self>,
6106 ) {
6107 self.manipulate_lines(cx, |lines| lines.sort())
6108 }
6109
6110 pub fn sort_lines_case_insensitive(
6111 &mut self,
6112 _: &SortLinesCaseInsensitive,
6113 cx: &mut ViewContext<Self>,
6114 ) {
6115 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6116 }
6117
6118 pub fn unique_lines_case_insensitive(
6119 &mut self,
6120 _: &UniqueLinesCaseInsensitive,
6121 cx: &mut ViewContext<Self>,
6122 ) {
6123 self.manipulate_lines(cx, |lines| {
6124 let mut seen = HashSet::default();
6125 lines.retain(|line| seen.insert(line.to_lowercase()));
6126 })
6127 }
6128
6129 pub fn unique_lines_case_sensitive(
6130 &mut self,
6131 _: &UniqueLinesCaseSensitive,
6132 cx: &mut ViewContext<Self>,
6133 ) {
6134 self.manipulate_lines(cx, |lines| {
6135 let mut seen = HashSet::default();
6136 lines.retain(|line| seen.insert(*line));
6137 })
6138 }
6139
6140 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6141 let mut revert_changes = HashMap::default();
6142 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6143 for hunk in hunks_for_rows(
6144 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6145 &multi_buffer_snapshot,
6146 ) {
6147 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6148 }
6149 if !revert_changes.is_empty() {
6150 self.transact(cx, |editor, cx| {
6151 editor.revert(revert_changes, cx);
6152 });
6153 }
6154 }
6155
6156 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6157 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6158 if !revert_changes.is_empty() {
6159 self.transact(cx, |editor, cx| {
6160 editor.revert(revert_changes, cx);
6161 });
6162 }
6163 }
6164
6165 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6166 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6167 let project_path = buffer.read(cx).project_path(cx)?;
6168 let project = self.project.as_ref()?.read(cx);
6169 let entry = project.entry_for_path(&project_path, cx)?;
6170 let abs_path = project.absolute_path(&project_path, cx)?;
6171 let parent = if entry.is_symlink {
6172 abs_path.canonicalize().ok()?
6173 } else {
6174 abs_path
6175 }
6176 .parent()?
6177 .to_path_buf();
6178 Some(parent)
6179 }) {
6180 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6181 }
6182 }
6183
6184 fn gather_revert_changes(
6185 &mut self,
6186 selections: &[Selection<Anchor>],
6187 cx: &mut ViewContext<'_, Editor>,
6188 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6189 let mut revert_changes = HashMap::default();
6190 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6191 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6192 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6193 }
6194 revert_changes
6195 }
6196
6197 pub fn prepare_revert_change(
6198 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6199 multi_buffer: &Model<MultiBuffer>,
6200 hunk: &MultiBufferDiffHunk,
6201 cx: &AppContext,
6202 ) -> Option<()> {
6203 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6204 let buffer = buffer.read(cx);
6205 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6206 let buffer_snapshot = buffer.snapshot();
6207 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6208 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6209 probe
6210 .0
6211 .start
6212 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6213 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6214 }) {
6215 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6216 Some(())
6217 } else {
6218 None
6219 }
6220 }
6221
6222 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6223 self.manipulate_lines(cx, |lines| lines.reverse())
6224 }
6225
6226 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6227 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6228 }
6229
6230 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6231 where
6232 Fn: FnMut(&mut Vec<&str>),
6233 {
6234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6235 let buffer = self.buffer.read(cx).snapshot(cx);
6236
6237 let mut edits = Vec::new();
6238
6239 let selections = self.selections.all::<Point>(cx);
6240 let mut selections = selections.iter().peekable();
6241 let mut contiguous_row_selections = Vec::new();
6242 let mut new_selections = Vec::new();
6243 let mut added_lines = 0;
6244 let mut removed_lines = 0;
6245
6246 while let Some(selection) = selections.next() {
6247 let (start_row, end_row) = consume_contiguous_rows(
6248 &mut contiguous_row_selections,
6249 selection,
6250 &display_map,
6251 &mut selections,
6252 );
6253
6254 let start_point = Point::new(start_row.0, 0);
6255 let end_point = Point::new(
6256 end_row.previous_row().0,
6257 buffer.line_len(end_row.previous_row()),
6258 );
6259 let text = buffer
6260 .text_for_range(start_point..end_point)
6261 .collect::<String>();
6262
6263 let mut lines = text.split('\n').collect_vec();
6264
6265 let lines_before = lines.len();
6266 callback(&mut lines);
6267 let lines_after = lines.len();
6268
6269 edits.push((start_point..end_point, lines.join("\n")));
6270
6271 // Selections must change based on added and removed line count
6272 let start_row =
6273 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6274 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6275 new_selections.push(Selection {
6276 id: selection.id,
6277 start: start_row,
6278 end: end_row,
6279 goal: SelectionGoal::None,
6280 reversed: selection.reversed,
6281 });
6282
6283 if lines_after > lines_before {
6284 added_lines += lines_after - lines_before;
6285 } else if lines_before > lines_after {
6286 removed_lines += lines_before - lines_after;
6287 }
6288 }
6289
6290 self.transact(cx, |this, cx| {
6291 let buffer = this.buffer.update(cx, |buffer, cx| {
6292 buffer.edit(edits, None, cx);
6293 buffer.snapshot(cx)
6294 });
6295
6296 // Recalculate offsets on newly edited buffer
6297 let new_selections = new_selections
6298 .iter()
6299 .map(|s| {
6300 let start_point = Point::new(s.start.0, 0);
6301 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6302 Selection {
6303 id: s.id,
6304 start: buffer.point_to_offset(start_point),
6305 end: buffer.point_to_offset(end_point),
6306 goal: s.goal,
6307 reversed: s.reversed,
6308 }
6309 })
6310 .collect();
6311
6312 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6313 s.select(new_selections);
6314 });
6315
6316 this.request_autoscroll(Autoscroll::fit(), cx);
6317 });
6318 }
6319
6320 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6321 self.manipulate_text(cx, |text| text.to_uppercase())
6322 }
6323
6324 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6325 self.manipulate_text(cx, |text| text.to_lowercase())
6326 }
6327
6328 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6329 self.manipulate_text(cx, |text| {
6330 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6331 // https://github.com/rutrum/convert-case/issues/16
6332 text.split('\n')
6333 .map(|line| line.to_case(Case::Title))
6334 .join("\n")
6335 })
6336 }
6337
6338 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6339 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6340 }
6341
6342 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6343 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6344 }
6345
6346 pub fn convert_to_upper_camel_case(
6347 &mut self,
6348 _: &ConvertToUpperCamelCase,
6349 cx: &mut ViewContext<Self>,
6350 ) {
6351 self.manipulate_text(cx, |text| {
6352 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6353 // https://github.com/rutrum/convert-case/issues/16
6354 text.split('\n')
6355 .map(|line| line.to_case(Case::UpperCamel))
6356 .join("\n")
6357 })
6358 }
6359
6360 pub fn convert_to_lower_camel_case(
6361 &mut self,
6362 _: &ConvertToLowerCamelCase,
6363 cx: &mut ViewContext<Self>,
6364 ) {
6365 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6366 }
6367
6368 pub fn convert_to_opposite_case(
6369 &mut self,
6370 _: &ConvertToOppositeCase,
6371 cx: &mut ViewContext<Self>,
6372 ) {
6373 self.manipulate_text(cx, |text| {
6374 text.chars()
6375 .fold(String::with_capacity(text.len()), |mut t, c| {
6376 if c.is_uppercase() {
6377 t.extend(c.to_lowercase());
6378 } else {
6379 t.extend(c.to_uppercase());
6380 }
6381 t
6382 })
6383 })
6384 }
6385
6386 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6387 where
6388 Fn: FnMut(&str) -> String,
6389 {
6390 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6391 let buffer = self.buffer.read(cx).snapshot(cx);
6392
6393 let mut new_selections = Vec::new();
6394 let mut edits = Vec::new();
6395 let mut selection_adjustment = 0i32;
6396
6397 for selection in self.selections.all::<usize>(cx) {
6398 let selection_is_empty = selection.is_empty();
6399
6400 let (start, end) = if selection_is_empty {
6401 let word_range = movement::surrounding_word(
6402 &display_map,
6403 selection.start.to_display_point(&display_map),
6404 );
6405 let start = word_range.start.to_offset(&display_map, Bias::Left);
6406 let end = word_range.end.to_offset(&display_map, Bias::Left);
6407 (start, end)
6408 } else {
6409 (selection.start, selection.end)
6410 };
6411
6412 let text = buffer.text_for_range(start..end).collect::<String>();
6413 let old_length = text.len() as i32;
6414 let text = callback(&text);
6415
6416 new_selections.push(Selection {
6417 start: (start as i32 - selection_adjustment) as usize,
6418 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6419 goal: SelectionGoal::None,
6420 ..selection
6421 });
6422
6423 selection_adjustment += old_length - text.len() as i32;
6424
6425 edits.push((start..end, text));
6426 }
6427
6428 self.transact(cx, |this, cx| {
6429 this.buffer.update(cx, |buffer, cx| {
6430 buffer.edit(edits, None, cx);
6431 });
6432
6433 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6434 s.select(new_selections);
6435 });
6436
6437 this.request_autoscroll(Autoscroll::fit(), cx);
6438 });
6439 }
6440
6441 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6442 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6443 let buffer = &display_map.buffer_snapshot;
6444 let selections = self.selections.all::<Point>(cx);
6445
6446 let mut edits = Vec::new();
6447 let mut selections_iter = selections.iter().peekable();
6448 while let Some(selection) = selections_iter.next() {
6449 // Avoid duplicating the same lines twice.
6450 let mut rows = selection.spanned_rows(false, &display_map);
6451
6452 while let Some(next_selection) = selections_iter.peek() {
6453 let next_rows = next_selection.spanned_rows(false, &display_map);
6454 if next_rows.start < rows.end {
6455 rows.end = next_rows.end;
6456 selections_iter.next().unwrap();
6457 } else {
6458 break;
6459 }
6460 }
6461
6462 // Copy the text from the selected row region and splice it either at the start
6463 // or end of the region.
6464 let start = Point::new(rows.start.0, 0);
6465 let end = Point::new(
6466 rows.end.previous_row().0,
6467 buffer.line_len(rows.end.previous_row()),
6468 );
6469 let text = buffer
6470 .text_for_range(start..end)
6471 .chain(Some("\n"))
6472 .collect::<String>();
6473 let insert_location = if upwards {
6474 Point::new(rows.end.0, 0)
6475 } else {
6476 start
6477 };
6478 edits.push((insert_location..insert_location, text));
6479 }
6480
6481 self.transact(cx, |this, cx| {
6482 this.buffer.update(cx, |buffer, cx| {
6483 buffer.edit(edits, None, cx);
6484 });
6485
6486 this.request_autoscroll(Autoscroll::fit(), cx);
6487 });
6488 }
6489
6490 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6491 self.duplicate_line(true, cx);
6492 }
6493
6494 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6495 self.duplicate_line(false, cx);
6496 }
6497
6498 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6499 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6500 let buffer = self.buffer.read(cx).snapshot(cx);
6501
6502 let mut edits = Vec::new();
6503 let mut unfold_ranges = Vec::new();
6504 let mut refold_ranges = Vec::new();
6505
6506 let selections = self.selections.all::<Point>(cx);
6507 let mut selections = selections.iter().peekable();
6508 let mut contiguous_row_selections = Vec::new();
6509 let mut new_selections = Vec::new();
6510
6511 while let Some(selection) = selections.next() {
6512 // Find all the selections that span a contiguous row range
6513 let (start_row, end_row) = consume_contiguous_rows(
6514 &mut contiguous_row_selections,
6515 selection,
6516 &display_map,
6517 &mut selections,
6518 );
6519
6520 // Move the text spanned by the row range to be before the line preceding the row range
6521 if start_row.0 > 0 {
6522 let range_to_move = Point::new(
6523 start_row.previous_row().0,
6524 buffer.line_len(start_row.previous_row()),
6525 )
6526 ..Point::new(
6527 end_row.previous_row().0,
6528 buffer.line_len(end_row.previous_row()),
6529 );
6530 let insertion_point = display_map
6531 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6532 .0;
6533
6534 // Don't move lines across excerpts
6535 if buffer
6536 .excerpt_boundaries_in_range((
6537 Bound::Excluded(insertion_point),
6538 Bound::Included(range_to_move.end),
6539 ))
6540 .next()
6541 .is_none()
6542 {
6543 let text = buffer
6544 .text_for_range(range_to_move.clone())
6545 .flat_map(|s| s.chars())
6546 .skip(1)
6547 .chain(['\n'])
6548 .collect::<String>();
6549
6550 edits.push((
6551 buffer.anchor_after(range_to_move.start)
6552 ..buffer.anchor_before(range_to_move.end),
6553 String::new(),
6554 ));
6555 let insertion_anchor = buffer.anchor_after(insertion_point);
6556 edits.push((insertion_anchor..insertion_anchor, text));
6557
6558 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6559
6560 // Move selections up
6561 new_selections.extend(contiguous_row_selections.drain(..).map(
6562 |mut selection| {
6563 selection.start.row -= row_delta;
6564 selection.end.row -= row_delta;
6565 selection
6566 },
6567 ));
6568
6569 // Move folds up
6570 unfold_ranges.push(range_to_move.clone());
6571 for fold in display_map.folds_in_range(
6572 buffer.anchor_before(range_to_move.start)
6573 ..buffer.anchor_after(range_to_move.end),
6574 ) {
6575 let mut start = fold.range.start.to_point(&buffer);
6576 let mut end = fold.range.end.to_point(&buffer);
6577 start.row -= row_delta;
6578 end.row -= row_delta;
6579 refold_ranges.push((start..end, fold.placeholder.clone()));
6580 }
6581 }
6582 }
6583
6584 // If we didn't move line(s), preserve the existing selections
6585 new_selections.append(&mut contiguous_row_selections);
6586 }
6587
6588 self.transact(cx, |this, cx| {
6589 this.unfold_ranges(unfold_ranges, true, true, cx);
6590 this.buffer.update(cx, |buffer, cx| {
6591 for (range, text) in edits {
6592 buffer.edit([(range, text)], None, cx);
6593 }
6594 });
6595 this.fold_ranges(refold_ranges, true, cx);
6596 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6597 s.select(new_selections);
6598 })
6599 });
6600 }
6601
6602 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6603 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6604 let buffer = self.buffer.read(cx).snapshot(cx);
6605
6606 let mut edits = Vec::new();
6607 let mut unfold_ranges = Vec::new();
6608 let mut refold_ranges = Vec::new();
6609
6610 let selections = self.selections.all::<Point>(cx);
6611 let mut selections = selections.iter().peekable();
6612 let mut contiguous_row_selections = Vec::new();
6613 let mut new_selections = Vec::new();
6614
6615 while let Some(selection) = selections.next() {
6616 // Find all the selections that span a contiguous row range
6617 let (start_row, end_row) = consume_contiguous_rows(
6618 &mut contiguous_row_selections,
6619 selection,
6620 &display_map,
6621 &mut selections,
6622 );
6623
6624 // Move the text spanned by the row range to be after the last line of the row range
6625 if end_row.0 <= buffer.max_point().row {
6626 let range_to_move =
6627 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6628 let insertion_point = display_map
6629 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6630 .0;
6631
6632 // Don't move lines across excerpt boundaries
6633 if buffer
6634 .excerpt_boundaries_in_range((
6635 Bound::Excluded(range_to_move.start),
6636 Bound::Included(insertion_point),
6637 ))
6638 .next()
6639 .is_none()
6640 {
6641 let mut text = String::from("\n");
6642 text.extend(buffer.text_for_range(range_to_move.clone()));
6643 text.pop(); // Drop trailing newline
6644 edits.push((
6645 buffer.anchor_after(range_to_move.start)
6646 ..buffer.anchor_before(range_to_move.end),
6647 String::new(),
6648 ));
6649 let insertion_anchor = buffer.anchor_after(insertion_point);
6650 edits.push((insertion_anchor..insertion_anchor, text));
6651
6652 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6653
6654 // Move selections down
6655 new_selections.extend(contiguous_row_selections.drain(..).map(
6656 |mut selection| {
6657 selection.start.row += row_delta;
6658 selection.end.row += row_delta;
6659 selection
6660 },
6661 ));
6662
6663 // Move folds down
6664 unfold_ranges.push(range_to_move.clone());
6665 for fold in display_map.folds_in_range(
6666 buffer.anchor_before(range_to_move.start)
6667 ..buffer.anchor_after(range_to_move.end),
6668 ) {
6669 let mut start = fold.range.start.to_point(&buffer);
6670 let mut end = fold.range.end.to_point(&buffer);
6671 start.row += row_delta;
6672 end.row += row_delta;
6673 refold_ranges.push((start..end, fold.placeholder.clone()));
6674 }
6675 }
6676 }
6677
6678 // If we didn't move line(s), preserve the existing selections
6679 new_selections.append(&mut contiguous_row_selections);
6680 }
6681
6682 self.transact(cx, |this, cx| {
6683 this.unfold_ranges(unfold_ranges, true, true, cx);
6684 this.buffer.update(cx, |buffer, cx| {
6685 for (range, text) in edits {
6686 buffer.edit([(range, text)], None, cx);
6687 }
6688 });
6689 this.fold_ranges(refold_ranges, true, cx);
6690 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6691 });
6692 }
6693
6694 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6695 let text_layout_details = &self.text_layout_details(cx);
6696 self.transact(cx, |this, cx| {
6697 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6698 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6699 let line_mode = s.line_mode;
6700 s.move_with(|display_map, selection| {
6701 if !selection.is_empty() || line_mode {
6702 return;
6703 }
6704
6705 let mut head = selection.head();
6706 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6707 if head.column() == display_map.line_len(head.row()) {
6708 transpose_offset = display_map
6709 .buffer_snapshot
6710 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6711 }
6712
6713 if transpose_offset == 0 {
6714 return;
6715 }
6716
6717 *head.column_mut() += 1;
6718 head = display_map.clip_point(head, Bias::Right);
6719 let goal = SelectionGoal::HorizontalPosition(
6720 display_map
6721 .x_for_display_point(head, text_layout_details)
6722 .into(),
6723 );
6724 selection.collapse_to(head, goal);
6725
6726 let transpose_start = display_map
6727 .buffer_snapshot
6728 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6729 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6730 let transpose_end = display_map
6731 .buffer_snapshot
6732 .clip_offset(transpose_offset + 1, Bias::Right);
6733 if let Some(ch) =
6734 display_map.buffer_snapshot.chars_at(transpose_start).next()
6735 {
6736 edits.push((transpose_start..transpose_offset, String::new()));
6737 edits.push((transpose_end..transpose_end, ch.to_string()));
6738 }
6739 }
6740 });
6741 edits
6742 });
6743 this.buffer
6744 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6745 let selections = this.selections.all::<usize>(cx);
6746 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6747 s.select(selections);
6748 });
6749 });
6750 }
6751
6752 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6753 self.rewrap_impl(true, cx)
6754 }
6755
6756 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6757 let buffer = self.buffer.read(cx).snapshot(cx);
6758 let selections = self.selections.all::<Point>(cx);
6759 let mut selections = selections.iter().peekable();
6760
6761 let mut edits = Vec::new();
6762 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6763
6764 while let Some(selection) = selections.next() {
6765 let mut start_row = selection.start.row;
6766 let mut end_row = selection.end.row;
6767
6768 // Skip selections that overlap with a range that has already been rewrapped.
6769 let selection_range = start_row..end_row;
6770 if rewrapped_row_ranges
6771 .iter()
6772 .any(|range| range.overlaps(&selection_range))
6773 {
6774 continue;
6775 }
6776
6777 let mut should_rewrap = !only_text;
6778
6779 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6780 match language_scope.language_name().0.as_ref() {
6781 "Markdown" | "Plain Text" => {
6782 should_rewrap = true;
6783 }
6784 _ => {}
6785 }
6786 }
6787
6788 // Since not all lines in the selection may be at the same indent
6789 // level, choose the indent size that is the most common between all
6790 // of the lines.
6791 //
6792 // If there is a tie, we use the deepest indent.
6793 let (indent_size, indent_end) = {
6794 let mut indent_size_occurrences = HashMap::default();
6795 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6796
6797 for row in start_row..=end_row {
6798 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6799 rows_by_indent_size.entry(indent).or_default().push(row);
6800 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6801 }
6802
6803 let indent_size = indent_size_occurrences
6804 .into_iter()
6805 .max_by_key(|(indent, count)| (*count, indent.len))
6806 .map(|(indent, _)| indent)
6807 .unwrap_or_default();
6808 let row = rows_by_indent_size[&indent_size][0];
6809 let indent_end = Point::new(row, indent_size.len);
6810
6811 (indent_size, indent_end)
6812 };
6813
6814 let mut line_prefix = indent_size.chars().collect::<String>();
6815
6816 if let Some(comment_prefix) =
6817 buffer
6818 .language_scope_at(selection.head())
6819 .and_then(|language| {
6820 language
6821 .line_comment_prefixes()
6822 .iter()
6823 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6824 .cloned()
6825 })
6826 {
6827 line_prefix.push_str(&comment_prefix);
6828 should_rewrap = true;
6829 }
6830
6831 if selection.is_empty() {
6832 'expand_upwards: while start_row > 0 {
6833 let prev_row = start_row - 1;
6834 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6835 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6836 {
6837 start_row = prev_row;
6838 } else {
6839 break 'expand_upwards;
6840 }
6841 }
6842
6843 'expand_downwards: while end_row < buffer.max_point().row {
6844 let next_row = end_row + 1;
6845 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6846 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6847 {
6848 end_row = next_row;
6849 } else {
6850 break 'expand_downwards;
6851 }
6852 }
6853 }
6854
6855 if !should_rewrap {
6856 continue;
6857 }
6858
6859 let start = Point::new(start_row, 0);
6860 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6861 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6862 let Some(lines_without_prefixes) = selection_text
6863 .lines()
6864 .map(|line| {
6865 line.strip_prefix(&line_prefix)
6866 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6867 .ok_or_else(|| {
6868 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6869 })
6870 })
6871 .collect::<Result<Vec<_>, _>>()
6872 .log_err()
6873 else {
6874 continue;
6875 };
6876
6877 let unwrapped_text = lines_without_prefixes.join(" ");
6878 let wrap_column = buffer
6879 .settings_at(Point::new(start_row, 0), cx)
6880 .preferred_line_length as usize;
6881 let mut wrapped_text = String::new();
6882 let mut current_line = line_prefix.clone();
6883 for word in unwrapped_text.split_whitespace() {
6884 if current_line.len() + word.len() >= wrap_column {
6885 wrapped_text.push_str(¤t_line);
6886 wrapped_text.push('\n');
6887 current_line.truncate(line_prefix.len());
6888 }
6889
6890 if current_line.len() > line_prefix.len() {
6891 current_line.push(' ');
6892 }
6893
6894 current_line.push_str(word);
6895 }
6896
6897 if !current_line.is_empty() {
6898 wrapped_text.push_str(¤t_line);
6899 }
6900
6901 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6902 let mut offset = start.to_offset(&buffer);
6903 let mut moved_since_edit = true;
6904
6905 for change in diff.iter_all_changes() {
6906 let value = change.value();
6907 match change.tag() {
6908 ChangeTag::Equal => {
6909 offset += value.len();
6910 moved_since_edit = true;
6911 }
6912 ChangeTag::Delete => {
6913 let start = buffer.anchor_after(offset);
6914 let end = buffer.anchor_before(offset + value.len());
6915
6916 if moved_since_edit {
6917 edits.push((start..end, String::new()));
6918 } else {
6919 edits.last_mut().unwrap().0.end = end;
6920 }
6921
6922 offset += value.len();
6923 moved_since_edit = false;
6924 }
6925 ChangeTag::Insert => {
6926 if moved_since_edit {
6927 let anchor = buffer.anchor_after(offset);
6928 edits.push((anchor..anchor, value.to_string()));
6929 } else {
6930 edits.last_mut().unwrap().1.push_str(value);
6931 }
6932
6933 moved_since_edit = false;
6934 }
6935 }
6936 }
6937
6938 rewrapped_row_ranges.push(start_row..=end_row);
6939 }
6940
6941 self.buffer
6942 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6943 }
6944
6945 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6946 let mut text = String::new();
6947 let buffer = self.buffer.read(cx).snapshot(cx);
6948 let mut selections = self.selections.all::<Point>(cx);
6949 let mut clipboard_selections = Vec::with_capacity(selections.len());
6950 {
6951 let max_point = buffer.max_point();
6952 let mut is_first = true;
6953 for selection in &mut selections {
6954 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6955 if is_entire_line {
6956 selection.start = Point::new(selection.start.row, 0);
6957 if !selection.is_empty() && selection.end.column == 0 {
6958 selection.end = cmp::min(max_point, selection.end);
6959 } else {
6960 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6961 }
6962 selection.goal = SelectionGoal::None;
6963 }
6964 if is_first {
6965 is_first = false;
6966 } else {
6967 text += "\n";
6968 }
6969 let mut len = 0;
6970 for chunk in buffer.text_for_range(selection.start..selection.end) {
6971 text.push_str(chunk);
6972 len += chunk.len();
6973 }
6974 clipboard_selections.push(ClipboardSelection {
6975 len,
6976 is_entire_line,
6977 first_line_indent: buffer
6978 .indent_size_for_line(MultiBufferRow(selection.start.row))
6979 .len,
6980 });
6981 }
6982 }
6983
6984 self.transact(cx, |this, cx| {
6985 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6986 s.select(selections);
6987 });
6988 this.insert("", cx);
6989 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6990 text,
6991 clipboard_selections,
6992 ));
6993 });
6994 }
6995
6996 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6997 let selections = self.selections.all::<Point>(cx);
6998 let buffer = self.buffer.read(cx).read(cx);
6999 let mut text = String::new();
7000
7001 let mut clipboard_selections = Vec::with_capacity(selections.len());
7002 {
7003 let max_point = buffer.max_point();
7004 let mut is_first = true;
7005 for selection in selections.iter() {
7006 let mut start = selection.start;
7007 let mut end = selection.end;
7008 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7009 if is_entire_line {
7010 start = Point::new(start.row, 0);
7011 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7012 }
7013 if is_first {
7014 is_first = false;
7015 } else {
7016 text += "\n";
7017 }
7018 let mut len = 0;
7019 for chunk in buffer.text_for_range(start..end) {
7020 text.push_str(chunk);
7021 len += chunk.len();
7022 }
7023 clipboard_selections.push(ClipboardSelection {
7024 len,
7025 is_entire_line,
7026 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7027 });
7028 }
7029 }
7030
7031 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7032 text,
7033 clipboard_selections,
7034 ));
7035 }
7036
7037 pub fn do_paste(
7038 &mut self,
7039 text: &String,
7040 clipboard_selections: Option<Vec<ClipboardSelection>>,
7041 handle_entire_lines: bool,
7042 cx: &mut ViewContext<Self>,
7043 ) {
7044 if self.read_only(cx) {
7045 return;
7046 }
7047
7048 let clipboard_text = Cow::Borrowed(text);
7049
7050 self.transact(cx, |this, cx| {
7051 if let Some(mut clipboard_selections) = clipboard_selections {
7052 let old_selections = this.selections.all::<usize>(cx);
7053 let all_selections_were_entire_line =
7054 clipboard_selections.iter().all(|s| s.is_entire_line);
7055 let first_selection_indent_column =
7056 clipboard_selections.first().map(|s| s.first_line_indent);
7057 if clipboard_selections.len() != old_selections.len() {
7058 clipboard_selections.drain(..);
7059 }
7060
7061 this.buffer.update(cx, |buffer, cx| {
7062 let snapshot = buffer.read(cx);
7063 let mut start_offset = 0;
7064 let mut edits = Vec::new();
7065 let mut original_indent_columns = Vec::new();
7066 for (ix, selection) in old_selections.iter().enumerate() {
7067 let to_insert;
7068 let entire_line;
7069 let original_indent_column;
7070 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7071 let end_offset = start_offset + clipboard_selection.len;
7072 to_insert = &clipboard_text[start_offset..end_offset];
7073 entire_line = clipboard_selection.is_entire_line;
7074 start_offset = end_offset + 1;
7075 original_indent_column = Some(clipboard_selection.first_line_indent);
7076 } else {
7077 to_insert = clipboard_text.as_str();
7078 entire_line = all_selections_were_entire_line;
7079 original_indent_column = first_selection_indent_column
7080 }
7081
7082 // If the corresponding selection was empty when this slice of the
7083 // clipboard text was written, then the entire line containing the
7084 // selection was copied. If this selection is also currently empty,
7085 // then paste the line before the current line of the buffer.
7086 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7087 let column = selection.start.to_point(&snapshot).column as usize;
7088 let line_start = selection.start - column;
7089 line_start..line_start
7090 } else {
7091 selection.range()
7092 };
7093
7094 edits.push((range, to_insert));
7095 original_indent_columns.extend(original_indent_column);
7096 }
7097 drop(snapshot);
7098
7099 buffer.edit(
7100 edits,
7101 Some(AutoindentMode::Block {
7102 original_indent_columns,
7103 }),
7104 cx,
7105 );
7106 });
7107
7108 let selections = this.selections.all::<usize>(cx);
7109 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7110 } else {
7111 this.insert(&clipboard_text, cx);
7112 }
7113 });
7114 }
7115
7116 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7117 if let Some(item) = cx.read_from_clipboard() {
7118 let entries = item.entries();
7119
7120 match entries.first() {
7121 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7122 // of all the pasted entries.
7123 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7124 .do_paste(
7125 clipboard_string.text(),
7126 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7127 true,
7128 cx,
7129 ),
7130 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7131 }
7132 }
7133 }
7134
7135 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7136 if self.read_only(cx) {
7137 return;
7138 }
7139
7140 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7141 if let Some((selections, _)) =
7142 self.selection_history.transaction(transaction_id).cloned()
7143 {
7144 self.change_selections(None, cx, |s| {
7145 s.select_anchors(selections.to_vec());
7146 });
7147 }
7148 self.request_autoscroll(Autoscroll::fit(), cx);
7149 self.unmark_text(cx);
7150 self.refresh_inline_completion(true, false, cx);
7151 cx.emit(EditorEvent::Edited { transaction_id });
7152 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7153 }
7154 }
7155
7156 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7157 if self.read_only(cx) {
7158 return;
7159 }
7160
7161 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7162 if let Some((_, Some(selections))) =
7163 self.selection_history.transaction(transaction_id).cloned()
7164 {
7165 self.change_selections(None, cx, |s| {
7166 s.select_anchors(selections.to_vec());
7167 });
7168 }
7169 self.request_autoscroll(Autoscroll::fit(), cx);
7170 self.unmark_text(cx);
7171 self.refresh_inline_completion(true, false, cx);
7172 cx.emit(EditorEvent::Edited { transaction_id });
7173 }
7174 }
7175
7176 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7177 self.buffer
7178 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7179 }
7180
7181 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7182 self.buffer
7183 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7184 }
7185
7186 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7187 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7188 let line_mode = s.line_mode;
7189 s.move_with(|map, selection| {
7190 let cursor = if selection.is_empty() && !line_mode {
7191 movement::left(map, selection.start)
7192 } else {
7193 selection.start
7194 };
7195 selection.collapse_to(cursor, SelectionGoal::None);
7196 });
7197 })
7198 }
7199
7200 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7201 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7202 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7203 })
7204 }
7205
7206 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 let cursor = if selection.is_empty() && !line_mode {
7211 movement::right(map, selection.end)
7212 } else {
7213 selection.end
7214 };
7215 selection.collapse_to(cursor, SelectionGoal::None)
7216 });
7217 })
7218 }
7219
7220 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7221 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7222 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7223 })
7224 }
7225
7226 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7227 if self.take_rename(true, cx).is_some() {
7228 return;
7229 }
7230
7231 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7232 cx.propagate();
7233 return;
7234 }
7235
7236 let text_layout_details = &self.text_layout_details(cx);
7237 let selection_count = self.selections.count();
7238 let first_selection = self.selections.first_anchor();
7239
7240 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7241 let line_mode = s.line_mode;
7242 s.move_with(|map, selection| {
7243 if !selection.is_empty() && !line_mode {
7244 selection.goal = SelectionGoal::None;
7245 }
7246 let (cursor, goal) = movement::up(
7247 map,
7248 selection.start,
7249 selection.goal,
7250 false,
7251 text_layout_details,
7252 );
7253 selection.collapse_to(cursor, goal);
7254 });
7255 });
7256
7257 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7258 {
7259 cx.propagate();
7260 }
7261 }
7262
7263 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7264 if self.take_rename(true, cx).is_some() {
7265 return;
7266 }
7267
7268 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7269 cx.propagate();
7270 return;
7271 }
7272
7273 let text_layout_details = &self.text_layout_details(cx);
7274
7275 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7276 let line_mode = s.line_mode;
7277 s.move_with(|map, selection| {
7278 if !selection.is_empty() && !line_mode {
7279 selection.goal = SelectionGoal::None;
7280 }
7281 let (cursor, goal) = movement::up_by_rows(
7282 map,
7283 selection.start,
7284 action.lines,
7285 selection.goal,
7286 false,
7287 text_layout_details,
7288 );
7289 selection.collapse_to(cursor, goal);
7290 });
7291 })
7292 }
7293
7294 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7295 if self.take_rename(true, cx).is_some() {
7296 return;
7297 }
7298
7299 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7300 cx.propagate();
7301 return;
7302 }
7303
7304 let text_layout_details = &self.text_layout_details(cx);
7305
7306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7307 let line_mode = s.line_mode;
7308 s.move_with(|map, selection| {
7309 if !selection.is_empty() && !line_mode {
7310 selection.goal = SelectionGoal::None;
7311 }
7312 let (cursor, goal) = movement::down_by_rows(
7313 map,
7314 selection.start,
7315 action.lines,
7316 selection.goal,
7317 false,
7318 text_layout_details,
7319 );
7320 selection.collapse_to(cursor, goal);
7321 });
7322 })
7323 }
7324
7325 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7326 let text_layout_details = &self.text_layout_details(cx);
7327 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7328 s.move_heads_with(|map, head, goal| {
7329 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7330 })
7331 })
7332 }
7333
7334 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7335 let text_layout_details = &self.text_layout_details(cx);
7336 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7337 s.move_heads_with(|map, head, goal| {
7338 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7339 })
7340 })
7341 }
7342
7343 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7344 let Some(row_count) = self.visible_row_count() else {
7345 return;
7346 };
7347
7348 let text_layout_details = &self.text_layout_details(cx);
7349
7350 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7351 s.move_heads_with(|map, head, goal| {
7352 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7353 })
7354 })
7355 }
7356
7357 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7358 if self.take_rename(true, cx).is_some() {
7359 return;
7360 }
7361
7362 if self
7363 .context_menu
7364 .write()
7365 .as_mut()
7366 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7367 .unwrap_or(false)
7368 {
7369 return;
7370 }
7371
7372 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7373 cx.propagate();
7374 return;
7375 }
7376
7377 let Some(row_count) = self.visible_row_count() else {
7378 return;
7379 };
7380
7381 let autoscroll = if action.center_cursor {
7382 Autoscroll::center()
7383 } else {
7384 Autoscroll::fit()
7385 };
7386
7387 let text_layout_details = &self.text_layout_details(cx);
7388
7389 self.change_selections(Some(autoscroll), cx, |s| {
7390 let line_mode = s.line_mode;
7391 s.move_with(|map, selection| {
7392 if !selection.is_empty() && !line_mode {
7393 selection.goal = SelectionGoal::None;
7394 }
7395 let (cursor, goal) = movement::up_by_rows(
7396 map,
7397 selection.end,
7398 row_count,
7399 selection.goal,
7400 false,
7401 text_layout_details,
7402 );
7403 selection.collapse_to(cursor, goal);
7404 });
7405 });
7406 }
7407
7408 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7409 let text_layout_details = &self.text_layout_details(cx);
7410 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7411 s.move_heads_with(|map, head, goal| {
7412 movement::up(map, head, goal, false, text_layout_details)
7413 })
7414 })
7415 }
7416
7417 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7418 self.take_rename(true, cx);
7419
7420 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7421 cx.propagate();
7422 return;
7423 }
7424
7425 let text_layout_details = &self.text_layout_details(cx);
7426 let selection_count = self.selections.count();
7427 let first_selection = self.selections.first_anchor();
7428
7429 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7430 let line_mode = s.line_mode;
7431 s.move_with(|map, selection| {
7432 if !selection.is_empty() && !line_mode {
7433 selection.goal = SelectionGoal::None;
7434 }
7435 let (cursor, goal) = movement::down(
7436 map,
7437 selection.end,
7438 selection.goal,
7439 false,
7440 text_layout_details,
7441 );
7442 selection.collapse_to(cursor, goal);
7443 });
7444 });
7445
7446 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7447 {
7448 cx.propagate();
7449 }
7450 }
7451
7452 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7453 let Some(row_count) = self.visible_row_count() else {
7454 return;
7455 };
7456
7457 let text_layout_details = &self.text_layout_details(cx);
7458
7459 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7460 s.move_heads_with(|map, head, goal| {
7461 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7462 })
7463 })
7464 }
7465
7466 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7467 if self.take_rename(true, cx).is_some() {
7468 return;
7469 }
7470
7471 if self
7472 .context_menu
7473 .write()
7474 .as_mut()
7475 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7476 .unwrap_or(false)
7477 {
7478 return;
7479 }
7480
7481 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7482 cx.propagate();
7483 return;
7484 }
7485
7486 let Some(row_count) = self.visible_row_count() else {
7487 return;
7488 };
7489
7490 let autoscroll = if action.center_cursor {
7491 Autoscroll::center()
7492 } else {
7493 Autoscroll::fit()
7494 };
7495
7496 let text_layout_details = &self.text_layout_details(cx);
7497 self.change_selections(Some(autoscroll), cx, |s| {
7498 let line_mode = s.line_mode;
7499 s.move_with(|map, selection| {
7500 if !selection.is_empty() && !line_mode {
7501 selection.goal = SelectionGoal::None;
7502 }
7503 let (cursor, goal) = movement::down_by_rows(
7504 map,
7505 selection.end,
7506 row_count,
7507 selection.goal,
7508 false,
7509 text_layout_details,
7510 );
7511 selection.collapse_to(cursor, goal);
7512 });
7513 });
7514 }
7515
7516 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7517 let text_layout_details = &self.text_layout_details(cx);
7518 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7519 s.move_heads_with(|map, head, goal| {
7520 movement::down(map, head, goal, false, text_layout_details)
7521 })
7522 });
7523 }
7524
7525 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7526 if let Some(context_menu) = self.context_menu.write().as_mut() {
7527 context_menu.select_first(self.project.as_ref(), cx);
7528 }
7529 }
7530
7531 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7532 if let Some(context_menu) = self.context_menu.write().as_mut() {
7533 context_menu.select_prev(self.project.as_ref(), cx);
7534 }
7535 }
7536
7537 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7538 if let Some(context_menu) = self.context_menu.write().as_mut() {
7539 context_menu.select_next(self.project.as_ref(), cx);
7540 }
7541 }
7542
7543 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7544 if let Some(context_menu) = self.context_menu.write().as_mut() {
7545 context_menu.select_last(self.project.as_ref(), cx);
7546 }
7547 }
7548
7549 pub fn move_to_previous_word_start(
7550 &mut self,
7551 _: &MoveToPreviousWordStart,
7552 cx: &mut ViewContext<Self>,
7553 ) {
7554 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7555 s.move_cursors_with(|map, head, _| {
7556 (
7557 movement::previous_word_start(map, head),
7558 SelectionGoal::None,
7559 )
7560 });
7561 })
7562 }
7563
7564 pub fn move_to_previous_subword_start(
7565 &mut self,
7566 _: &MoveToPreviousSubwordStart,
7567 cx: &mut ViewContext<Self>,
7568 ) {
7569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7570 s.move_cursors_with(|map, head, _| {
7571 (
7572 movement::previous_subword_start(map, head),
7573 SelectionGoal::None,
7574 )
7575 });
7576 })
7577 }
7578
7579 pub fn select_to_previous_word_start(
7580 &mut self,
7581 _: &SelectToPreviousWordStart,
7582 cx: &mut ViewContext<Self>,
7583 ) {
7584 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7585 s.move_heads_with(|map, head, _| {
7586 (
7587 movement::previous_word_start(map, head),
7588 SelectionGoal::None,
7589 )
7590 });
7591 })
7592 }
7593
7594 pub fn select_to_previous_subword_start(
7595 &mut self,
7596 _: &SelectToPreviousSubwordStart,
7597 cx: &mut ViewContext<Self>,
7598 ) {
7599 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7600 s.move_heads_with(|map, head, _| {
7601 (
7602 movement::previous_subword_start(map, head),
7603 SelectionGoal::None,
7604 )
7605 });
7606 })
7607 }
7608
7609 pub fn delete_to_previous_word_start(
7610 &mut self,
7611 action: &DeleteToPreviousWordStart,
7612 cx: &mut ViewContext<Self>,
7613 ) {
7614 self.transact(cx, |this, cx| {
7615 this.select_autoclose_pair(cx);
7616 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7617 let line_mode = s.line_mode;
7618 s.move_with(|map, selection| {
7619 if selection.is_empty() && !line_mode {
7620 let cursor = if action.ignore_newlines {
7621 movement::previous_word_start(map, selection.head())
7622 } else {
7623 movement::previous_word_start_or_newline(map, selection.head())
7624 };
7625 selection.set_head(cursor, SelectionGoal::None);
7626 }
7627 });
7628 });
7629 this.insert("", cx);
7630 });
7631 }
7632
7633 pub fn delete_to_previous_subword_start(
7634 &mut self,
7635 _: &DeleteToPreviousSubwordStart,
7636 cx: &mut ViewContext<Self>,
7637 ) {
7638 self.transact(cx, |this, cx| {
7639 this.select_autoclose_pair(cx);
7640 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7641 let line_mode = s.line_mode;
7642 s.move_with(|map, selection| {
7643 if selection.is_empty() && !line_mode {
7644 let cursor = movement::previous_subword_start(map, selection.head());
7645 selection.set_head(cursor, SelectionGoal::None);
7646 }
7647 });
7648 });
7649 this.insert("", cx);
7650 });
7651 }
7652
7653 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7654 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7655 s.move_cursors_with(|map, head, _| {
7656 (movement::next_word_end(map, head), SelectionGoal::None)
7657 });
7658 })
7659 }
7660
7661 pub fn move_to_next_subword_end(
7662 &mut self,
7663 _: &MoveToNextSubwordEnd,
7664 cx: &mut ViewContext<Self>,
7665 ) {
7666 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7667 s.move_cursors_with(|map, head, _| {
7668 (movement::next_subword_end(map, head), SelectionGoal::None)
7669 });
7670 })
7671 }
7672
7673 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7674 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7675 s.move_heads_with(|map, head, _| {
7676 (movement::next_word_end(map, head), SelectionGoal::None)
7677 });
7678 })
7679 }
7680
7681 pub fn select_to_next_subword_end(
7682 &mut self,
7683 _: &SelectToNextSubwordEnd,
7684 cx: &mut ViewContext<Self>,
7685 ) {
7686 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7687 s.move_heads_with(|map, head, _| {
7688 (movement::next_subword_end(map, head), SelectionGoal::None)
7689 });
7690 })
7691 }
7692
7693 pub fn delete_to_next_word_end(
7694 &mut self,
7695 action: &DeleteToNextWordEnd,
7696 cx: &mut ViewContext<Self>,
7697 ) {
7698 self.transact(cx, |this, cx| {
7699 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7700 let line_mode = s.line_mode;
7701 s.move_with(|map, selection| {
7702 if selection.is_empty() && !line_mode {
7703 let cursor = if action.ignore_newlines {
7704 movement::next_word_end(map, selection.head())
7705 } else {
7706 movement::next_word_end_or_newline(map, selection.head())
7707 };
7708 selection.set_head(cursor, SelectionGoal::None);
7709 }
7710 });
7711 });
7712 this.insert("", cx);
7713 });
7714 }
7715
7716 pub fn delete_to_next_subword_end(
7717 &mut self,
7718 _: &DeleteToNextSubwordEnd,
7719 cx: &mut ViewContext<Self>,
7720 ) {
7721 self.transact(cx, |this, cx| {
7722 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7723 s.move_with(|map, selection| {
7724 if selection.is_empty() {
7725 let cursor = movement::next_subword_end(map, selection.head());
7726 selection.set_head(cursor, SelectionGoal::None);
7727 }
7728 });
7729 });
7730 this.insert("", cx);
7731 });
7732 }
7733
7734 pub fn move_to_beginning_of_line(
7735 &mut self,
7736 action: &MoveToBeginningOfLine,
7737 cx: &mut ViewContext<Self>,
7738 ) {
7739 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7740 s.move_cursors_with(|map, head, _| {
7741 (
7742 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7743 SelectionGoal::None,
7744 )
7745 });
7746 })
7747 }
7748
7749 pub fn select_to_beginning_of_line(
7750 &mut self,
7751 action: &SelectToBeginningOfLine,
7752 cx: &mut ViewContext<Self>,
7753 ) {
7754 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7755 s.move_heads_with(|map, head, _| {
7756 (
7757 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7758 SelectionGoal::None,
7759 )
7760 });
7761 });
7762 }
7763
7764 pub fn delete_to_beginning_of_line(
7765 &mut self,
7766 _: &DeleteToBeginningOfLine,
7767 cx: &mut ViewContext<Self>,
7768 ) {
7769 self.transact(cx, |this, cx| {
7770 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7771 s.move_with(|_, selection| {
7772 selection.reversed = true;
7773 });
7774 });
7775
7776 this.select_to_beginning_of_line(
7777 &SelectToBeginningOfLine {
7778 stop_at_soft_wraps: false,
7779 },
7780 cx,
7781 );
7782 this.backspace(&Backspace, cx);
7783 });
7784 }
7785
7786 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7787 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7788 s.move_cursors_with(|map, head, _| {
7789 (
7790 movement::line_end(map, head, action.stop_at_soft_wraps),
7791 SelectionGoal::None,
7792 )
7793 });
7794 })
7795 }
7796
7797 pub fn select_to_end_of_line(
7798 &mut self,
7799 action: &SelectToEndOfLine,
7800 cx: &mut ViewContext<Self>,
7801 ) {
7802 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7803 s.move_heads_with(|map, head, _| {
7804 (
7805 movement::line_end(map, head, action.stop_at_soft_wraps),
7806 SelectionGoal::None,
7807 )
7808 });
7809 })
7810 }
7811
7812 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7813 self.transact(cx, |this, cx| {
7814 this.select_to_end_of_line(
7815 &SelectToEndOfLine {
7816 stop_at_soft_wraps: false,
7817 },
7818 cx,
7819 );
7820 this.delete(&Delete, cx);
7821 });
7822 }
7823
7824 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7825 self.transact(cx, |this, cx| {
7826 this.select_to_end_of_line(
7827 &SelectToEndOfLine {
7828 stop_at_soft_wraps: false,
7829 },
7830 cx,
7831 );
7832 this.cut(&Cut, cx);
7833 });
7834 }
7835
7836 pub fn move_to_start_of_paragraph(
7837 &mut self,
7838 _: &MoveToStartOfParagraph,
7839 cx: &mut ViewContext<Self>,
7840 ) {
7841 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7842 cx.propagate();
7843 return;
7844 }
7845
7846 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7847 s.move_with(|map, selection| {
7848 selection.collapse_to(
7849 movement::start_of_paragraph(map, selection.head(), 1),
7850 SelectionGoal::None,
7851 )
7852 });
7853 })
7854 }
7855
7856 pub fn move_to_end_of_paragraph(
7857 &mut self,
7858 _: &MoveToEndOfParagraph,
7859 cx: &mut ViewContext<Self>,
7860 ) {
7861 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7862 cx.propagate();
7863 return;
7864 }
7865
7866 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7867 s.move_with(|map, selection| {
7868 selection.collapse_to(
7869 movement::end_of_paragraph(map, selection.head(), 1),
7870 SelectionGoal::None,
7871 )
7872 });
7873 })
7874 }
7875
7876 pub fn select_to_start_of_paragraph(
7877 &mut self,
7878 _: &SelectToStartOfParagraph,
7879 cx: &mut ViewContext<Self>,
7880 ) {
7881 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7882 cx.propagate();
7883 return;
7884 }
7885
7886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7887 s.move_heads_with(|map, head, _| {
7888 (
7889 movement::start_of_paragraph(map, head, 1),
7890 SelectionGoal::None,
7891 )
7892 });
7893 })
7894 }
7895
7896 pub fn select_to_end_of_paragraph(
7897 &mut self,
7898 _: &SelectToEndOfParagraph,
7899 cx: &mut ViewContext<Self>,
7900 ) {
7901 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7902 cx.propagate();
7903 return;
7904 }
7905
7906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7907 s.move_heads_with(|map, head, _| {
7908 (
7909 movement::end_of_paragraph(map, head, 1),
7910 SelectionGoal::None,
7911 )
7912 });
7913 })
7914 }
7915
7916 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7917 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7918 cx.propagate();
7919 return;
7920 }
7921
7922 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7923 s.select_ranges(vec![0..0]);
7924 });
7925 }
7926
7927 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7928 let mut selection = self.selections.last::<Point>(cx);
7929 selection.set_head(Point::zero(), SelectionGoal::None);
7930
7931 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7932 s.select(vec![selection]);
7933 });
7934 }
7935
7936 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7937 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7938 cx.propagate();
7939 return;
7940 }
7941
7942 let cursor = self.buffer.read(cx).read(cx).len();
7943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 s.select_ranges(vec![cursor..cursor])
7945 });
7946 }
7947
7948 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7949 self.nav_history = nav_history;
7950 }
7951
7952 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7953 self.nav_history.as_ref()
7954 }
7955
7956 fn push_to_nav_history(
7957 &mut self,
7958 cursor_anchor: Anchor,
7959 new_position: Option<Point>,
7960 cx: &mut ViewContext<Self>,
7961 ) {
7962 if let Some(nav_history) = self.nav_history.as_mut() {
7963 let buffer = self.buffer.read(cx).read(cx);
7964 let cursor_position = cursor_anchor.to_point(&buffer);
7965 let scroll_state = self.scroll_manager.anchor();
7966 let scroll_top_row = scroll_state.top_row(&buffer);
7967 drop(buffer);
7968
7969 if let Some(new_position) = new_position {
7970 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7971 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7972 return;
7973 }
7974 }
7975
7976 nav_history.push(
7977 Some(NavigationData {
7978 cursor_anchor,
7979 cursor_position,
7980 scroll_anchor: scroll_state,
7981 scroll_top_row,
7982 }),
7983 cx,
7984 );
7985 }
7986 }
7987
7988 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7989 let buffer = self.buffer.read(cx).snapshot(cx);
7990 let mut selection = self.selections.first::<usize>(cx);
7991 selection.set_head(buffer.len(), SelectionGoal::None);
7992 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7993 s.select(vec![selection]);
7994 });
7995 }
7996
7997 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7998 let end = self.buffer.read(cx).read(cx).len();
7999 self.change_selections(None, cx, |s| {
8000 s.select_ranges(vec![0..end]);
8001 });
8002 }
8003
8004 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8005 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8006 let mut selections = self.selections.all::<Point>(cx);
8007 let max_point = display_map.buffer_snapshot.max_point();
8008 for selection in &mut selections {
8009 let rows = selection.spanned_rows(true, &display_map);
8010 selection.start = Point::new(rows.start.0, 0);
8011 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8012 selection.reversed = false;
8013 }
8014 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8015 s.select(selections);
8016 });
8017 }
8018
8019 pub fn split_selection_into_lines(
8020 &mut self,
8021 _: &SplitSelectionIntoLines,
8022 cx: &mut ViewContext<Self>,
8023 ) {
8024 let mut to_unfold = Vec::new();
8025 let mut new_selection_ranges = Vec::new();
8026 {
8027 let selections = self.selections.all::<Point>(cx);
8028 let buffer = self.buffer.read(cx).read(cx);
8029 for selection in selections {
8030 for row in selection.start.row..selection.end.row {
8031 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8032 new_selection_ranges.push(cursor..cursor);
8033 }
8034 new_selection_ranges.push(selection.end..selection.end);
8035 to_unfold.push(selection.start..selection.end);
8036 }
8037 }
8038 self.unfold_ranges(to_unfold, true, true, cx);
8039 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8040 s.select_ranges(new_selection_ranges);
8041 });
8042 }
8043
8044 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8045 self.add_selection(true, cx);
8046 }
8047
8048 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8049 self.add_selection(false, cx);
8050 }
8051
8052 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8053 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8054 let mut selections = self.selections.all::<Point>(cx);
8055 let text_layout_details = self.text_layout_details(cx);
8056 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8057 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8058 let range = oldest_selection.display_range(&display_map).sorted();
8059
8060 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8061 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8062 let positions = start_x.min(end_x)..start_x.max(end_x);
8063
8064 selections.clear();
8065 let mut stack = Vec::new();
8066 for row in range.start.row().0..=range.end.row().0 {
8067 if let Some(selection) = self.selections.build_columnar_selection(
8068 &display_map,
8069 DisplayRow(row),
8070 &positions,
8071 oldest_selection.reversed,
8072 &text_layout_details,
8073 ) {
8074 stack.push(selection.id);
8075 selections.push(selection);
8076 }
8077 }
8078
8079 if above {
8080 stack.reverse();
8081 }
8082
8083 AddSelectionsState { above, stack }
8084 });
8085
8086 let last_added_selection = *state.stack.last().unwrap();
8087 let mut new_selections = Vec::new();
8088 if above == state.above {
8089 let end_row = if above {
8090 DisplayRow(0)
8091 } else {
8092 display_map.max_point().row()
8093 };
8094
8095 'outer: for selection in selections {
8096 if selection.id == last_added_selection {
8097 let range = selection.display_range(&display_map).sorted();
8098 debug_assert_eq!(range.start.row(), range.end.row());
8099 let mut row = range.start.row();
8100 let positions =
8101 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8102 px(start)..px(end)
8103 } else {
8104 let start_x =
8105 display_map.x_for_display_point(range.start, &text_layout_details);
8106 let end_x =
8107 display_map.x_for_display_point(range.end, &text_layout_details);
8108 start_x.min(end_x)..start_x.max(end_x)
8109 };
8110
8111 while row != end_row {
8112 if above {
8113 row.0 -= 1;
8114 } else {
8115 row.0 += 1;
8116 }
8117
8118 if let Some(new_selection) = self.selections.build_columnar_selection(
8119 &display_map,
8120 row,
8121 &positions,
8122 selection.reversed,
8123 &text_layout_details,
8124 ) {
8125 state.stack.push(new_selection.id);
8126 if above {
8127 new_selections.push(new_selection);
8128 new_selections.push(selection);
8129 } else {
8130 new_selections.push(selection);
8131 new_selections.push(new_selection);
8132 }
8133
8134 continue 'outer;
8135 }
8136 }
8137 }
8138
8139 new_selections.push(selection);
8140 }
8141 } else {
8142 new_selections = selections;
8143 new_selections.retain(|s| s.id != last_added_selection);
8144 state.stack.pop();
8145 }
8146
8147 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8148 s.select(new_selections);
8149 });
8150 if state.stack.len() > 1 {
8151 self.add_selections_state = Some(state);
8152 }
8153 }
8154
8155 pub fn select_next_match_internal(
8156 &mut self,
8157 display_map: &DisplaySnapshot,
8158 replace_newest: bool,
8159 autoscroll: Option<Autoscroll>,
8160 cx: &mut ViewContext<Self>,
8161 ) -> Result<()> {
8162 fn select_next_match_ranges(
8163 this: &mut Editor,
8164 range: Range<usize>,
8165 replace_newest: bool,
8166 auto_scroll: Option<Autoscroll>,
8167 cx: &mut ViewContext<Editor>,
8168 ) {
8169 this.unfold_ranges([range.clone()], false, true, cx);
8170 this.change_selections(auto_scroll, cx, |s| {
8171 if replace_newest {
8172 s.delete(s.newest_anchor().id);
8173 }
8174 s.insert_range(range.clone());
8175 });
8176 }
8177
8178 let buffer = &display_map.buffer_snapshot;
8179 let mut selections = self.selections.all::<usize>(cx);
8180 if let Some(mut select_next_state) = self.select_next_state.take() {
8181 let query = &select_next_state.query;
8182 if !select_next_state.done {
8183 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8184 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8185 let mut next_selected_range = None;
8186
8187 let bytes_after_last_selection =
8188 buffer.bytes_in_range(last_selection.end..buffer.len());
8189 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8190 let query_matches = query
8191 .stream_find_iter(bytes_after_last_selection)
8192 .map(|result| (last_selection.end, result))
8193 .chain(
8194 query
8195 .stream_find_iter(bytes_before_first_selection)
8196 .map(|result| (0, result)),
8197 );
8198
8199 for (start_offset, query_match) in query_matches {
8200 let query_match = query_match.unwrap(); // can only fail due to I/O
8201 let offset_range =
8202 start_offset + query_match.start()..start_offset + query_match.end();
8203 let display_range = offset_range.start.to_display_point(display_map)
8204 ..offset_range.end.to_display_point(display_map);
8205
8206 if !select_next_state.wordwise
8207 || (!movement::is_inside_word(display_map, display_range.start)
8208 && !movement::is_inside_word(display_map, display_range.end))
8209 {
8210 // TODO: This is n^2, because we might check all the selections
8211 if !selections
8212 .iter()
8213 .any(|selection| selection.range().overlaps(&offset_range))
8214 {
8215 next_selected_range = Some(offset_range);
8216 break;
8217 }
8218 }
8219 }
8220
8221 if let Some(next_selected_range) = next_selected_range {
8222 select_next_match_ranges(
8223 self,
8224 next_selected_range,
8225 replace_newest,
8226 autoscroll,
8227 cx,
8228 );
8229 } else {
8230 select_next_state.done = true;
8231 }
8232 }
8233
8234 self.select_next_state = Some(select_next_state);
8235 } else {
8236 let mut only_carets = true;
8237 let mut same_text_selected = true;
8238 let mut selected_text = None;
8239
8240 let mut selections_iter = selections.iter().peekable();
8241 while let Some(selection) = selections_iter.next() {
8242 if selection.start != selection.end {
8243 only_carets = false;
8244 }
8245
8246 if same_text_selected {
8247 if selected_text.is_none() {
8248 selected_text =
8249 Some(buffer.text_for_range(selection.range()).collect::<String>());
8250 }
8251
8252 if let Some(next_selection) = selections_iter.peek() {
8253 if next_selection.range().len() == selection.range().len() {
8254 let next_selected_text = buffer
8255 .text_for_range(next_selection.range())
8256 .collect::<String>();
8257 if Some(next_selected_text) != selected_text {
8258 same_text_selected = false;
8259 selected_text = None;
8260 }
8261 } else {
8262 same_text_selected = false;
8263 selected_text = None;
8264 }
8265 }
8266 }
8267 }
8268
8269 if only_carets {
8270 for selection in &mut selections {
8271 let word_range = movement::surrounding_word(
8272 display_map,
8273 selection.start.to_display_point(display_map),
8274 );
8275 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8276 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8277 selection.goal = SelectionGoal::None;
8278 selection.reversed = false;
8279 select_next_match_ranges(
8280 self,
8281 selection.start..selection.end,
8282 replace_newest,
8283 autoscroll,
8284 cx,
8285 );
8286 }
8287
8288 if selections.len() == 1 {
8289 let selection = selections
8290 .last()
8291 .expect("ensured that there's only one selection");
8292 let query = buffer
8293 .text_for_range(selection.start..selection.end)
8294 .collect::<String>();
8295 let is_empty = query.is_empty();
8296 let select_state = SelectNextState {
8297 query: AhoCorasick::new(&[query])?,
8298 wordwise: true,
8299 done: is_empty,
8300 };
8301 self.select_next_state = Some(select_state);
8302 } else {
8303 self.select_next_state = None;
8304 }
8305 } else if let Some(selected_text) = selected_text {
8306 self.select_next_state = Some(SelectNextState {
8307 query: AhoCorasick::new(&[selected_text])?,
8308 wordwise: false,
8309 done: false,
8310 });
8311 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8312 }
8313 }
8314 Ok(())
8315 }
8316
8317 pub fn select_all_matches(
8318 &mut self,
8319 _action: &SelectAllMatches,
8320 cx: &mut ViewContext<Self>,
8321 ) -> Result<()> {
8322 self.push_to_selection_history();
8323 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8324
8325 self.select_next_match_internal(&display_map, false, None, cx)?;
8326 let Some(select_next_state) = self.select_next_state.as_mut() else {
8327 return Ok(());
8328 };
8329 if select_next_state.done {
8330 return Ok(());
8331 }
8332
8333 let mut new_selections = self.selections.all::<usize>(cx);
8334
8335 let buffer = &display_map.buffer_snapshot;
8336 let query_matches = select_next_state
8337 .query
8338 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8339
8340 for query_match in query_matches {
8341 let query_match = query_match.unwrap(); // can only fail due to I/O
8342 let offset_range = query_match.start()..query_match.end();
8343 let display_range = offset_range.start.to_display_point(&display_map)
8344 ..offset_range.end.to_display_point(&display_map);
8345
8346 if !select_next_state.wordwise
8347 || (!movement::is_inside_word(&display_map, display_range.start)
8348 && !movement::is_inside_word(&display_map, display_range.end))
8349 {
8350 self.selections.change_with(cx, |selections| {
8351 new_selections.push(Selection {
8352 id: selections.new_selection_id(),
8353 start: offset_range.start,
8354 end: offset_range.end,
8355 reversed: false,
8356 goal: SelectionGoal::None,
8357 });
8358 });
8359 }
8360 }
8361
8362 new_selections.sort_by_key(|selection| selection.start);
8363 let mut ix = 0;
8364 while ix + 1 < new_selections.len() {
8365 let current_selection = &new_selections[ix];
8366 let next_selection = &new_selections[ix + 1];
8367 if current_selection.range().overlaps(&next_selection.range()) {
8368 if current_selection.id < next_selection.id {
8369 new_selections.remove(ix + 1);
8370 } else {
8371 new_selections.remove(ix);
8372 }
8373 } else {
8374 ix += 1;
8375 }
8376 }
8377
8378 select_next_state.done = true;
8379 self.unfold_ranges(
8380 new_selections.iter().map(|selection| selection.range()),
8381 false,
8382 false,
8383 cx,
8384 );
8385 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8386 selections.select(new_selections)
8387 });
8388
8389 Ok(())
8390 }
8391
8392 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8393 self.push_to_selection_history();
8394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8395 self.select_next_match_internal(
8396 &display_map,
8397 action.replace_newest,
8398 Some(Autoscroll::newest()),
8399 cx,
8400 )?;
8401 Ok(())
8402 }
8403
8404 pub fn select_previous(
8405 &mut self,
8406 action: &SelectPrevious,
8407 cx: &mut ViewContext<Self>,
8408 ) -> Result<()> {
8409 self.push_to_selection_history();
8410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8411 let buffer = &display_map.buffer_snapshot;
8412 let mut selections = self.selections.all::<usize>(cx);
8413 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8414 let query = &select_prev_state.query;
8415 if !select_prev_state.done {
8416 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8417 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8418 let mut next_selected_range = None;
8419 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8420 let bytes_before_last_selection =
8421 buffer.reversed_bytes_in_range(0..last_selection.start);
8422 let bytes_after_first_selection =
8423 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8424 let query_matches = query
8425 .stream_find_iter(bytes_before_last_selection)
8426 .map(|result| (last_selection.start, result))
8427 .chain(
8428 query
8429 .stream_find_iter(bytes_after_first_selection)
8430 .map(|result| (buffer.len(), result)),
8431 );
8432 for (end_offset, query_match) in query_matches {
8433 let query_match = query_match.unwrap(); // can only fail due to I/O
8434 let offset_range =
8435 end_offset - query_match.end()..end_offset - query_match.start();
8436 let display_range = offset_range.start.to_display_point(&display_map)
8437 ..offset_range.end.to_display_point(&display_map);
8438
8439 if !select_prev_state.wordwise
8440 || (!movement::is_inside_word(&display_map, display_range.start)
8441 && !movement::is_inside_word(&display_map, display_range.end))
8442 {
8443 next_selected_range = Some(offset_range);
8444 break;
8445 }
8446 }
8447
8448 if let Some(next_selected_range) = next_selected_range {
8449 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8450 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8451 if action.replace_newest {
8452 s.delete(s.newest_anchor().id);
8453 }
8454 s.insert_range(next_selected_range);
8455 });
8456 } else {
8457 select_prev_state.done = true;
8458 }
8459 }
8460
8461 self.select_prev_state = Some(select_prev_state);
8462 } else {
8463 let mut only_carets = true;
8464 let mut same_text_selected = true;
8465 let mut selected_text = None;
8466
8467 let mut selections_iter = selections.iter().peekable();
8468 while let Some(selection) = selections_iter.next() {
8469 if selection.start != selection.end {
8470 only_carets = false;
8471 }
8472
8473 if same_text_selected {
8474 if selected_text.is_none() {
8475 selected_text =
8476 Some(buffer.text_for_range(selection.range()).collect::<String>());
8477 }
8478
8479 if let Some(next_selection) = selections_iter.peek() {
8480 if next_selection.range().len() == selection.range().len() {
8481 let next_selected_text = buffer
8482 .text_for_range(next_selection.range())
8483 .collect::<String>();
8484 if Some(next_selected_text) != selected_text {
8485 same_text_selected = false;
8486 selected_text = None;
8487 }
8488 } else {
8489 same_text_selected = false;
8490 selected_text = None;
8491 }
8492 }
8493 }
8494 }
8495
8496 if only_carets {
8497 for selection in &mut selections {
8498 let word_range = movement::surrounding_word(
8499 &display_map,
8500 selection.start.to_display_point(&display_map),
8501 );
8502 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8503 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8504 selection.goal = SelectionGoal::None;
8505 selection.reversed = false;
8506 }
8507 if selections.len() == 1 {
8508 let selection = selections
8509 .last()
8510 .expect("ensured that there's only one selection");
8511 let query = buffer
8512 .text_for_range(selection.start..selection.end)
8513 .collect::<String>();
8514 let is_empty = query.is_empty();
8515 let select_state = SelectNextState {
8516 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8517 wordwise: true,
8518 done: is_empty,
8519 };
8520 self.select_prev_state = Some(select_state);
8521 } else {
8522 self.select_prev_state = None;
8523 }
8524
8525 self.unfold_ranges(
8526 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8527 false,
8528 true,
8529 cx,
8530 );
8531 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8532 s.select(selections);
8533 });
8534 } else if let Some(selected_text) = selected_text {
8535 self.select_prev_state = Some(SelectNextState {
8536 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8537 wordwise: false,
8538 done: false,
8539 });
8540 self.select_previous(action, cx)?;
8541 }
8542 }
8543 Ok(())
8544 }
8545
8546 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8547 let text_layout_details = &self.text_layout_details(cx);
8548 self.transact(cx, |this, cx| {
8549 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8550 let mut edits = Vec::new();
8551 let mut selection_edit_ranges = Vec::new();
8552 let mut last_toggled_row = None;
8553 let snapshot = this.buffer.read(cx).read(cx);
8554 let empty_str: Arc<str> = Arc::default();
8555 let mut suffixes_inserted = Vec::new();
8556
8557 fn comment_prefix_range(
8558 snapshot: &MultiBufferSnapshot,
8559 row: MultiBufferRow,
8560 comment_prefix: &str,
8561 comment_prefix_whitespace: &str,
8562 ) -> Range<Point> {
8563 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8564
8565 let mut line_bytes = snapshot
8566 .bytes_in_range(start..snapshot.max_point())
8567 .flatten()
8568 .copied();
8569
8570 // If this line currently begins with the line comment prefix, then record
8571 // the range containing the prefix.
8572 if line_bytes
8573 .by_ref()
8574 .take(comment_prefix.len())
8575 .eq(comment_prefix.bytes())
8576 {
8577 // Include any whitespace that matches the comment prefix.
8578 let matching_whitespace_len = line_bytes
8579 .zip(comment_prefix_whitespace.bytes())
8580 .take_while(|(a, b)| a == b)
8581 .count() as u32;
8582 let end = Point::new(
8583 start.row,
8584 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8585 );
8586 start..end
8587 } else {
8588 start..start
8589 }
8590 }
8591
8592 fn comment_suffix_range(
8593 snapshot: &MultiBufferSnapshot,
8594 row: MultiBufferRow,
8595 comment_suffix: &str,
8596 comment_suffix_has_leading_space: bool,
8597 ) -> Range<Point> {
8598 let end = Point::new(row.0, snapshot.line_len(row));
8599 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8600
8601 let mut line_end_bytes = snapshot
8602 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8603 .flatten()
8604 .copied();
8605
8606 let leading_space_len = if suffix_start_column > 0
8607 && line_end_bytes.next() == Some(b' ')
8608 && comment_suffix_has_leading_space
8609 {
8610 1
8611 } else {
8612 0
8613 };
8614
8615 // If this line currently begins with the line comment prefix, then record
8616 // the range containing the prefix.
8617 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8618 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8619 start..end
8620 } else {
8621 end..end
8622 }
8623 }
8624
8625 // TODO: Handle selections that cross excerpts
8626 for selection in &mut selections {
8627 let start_column = snapshot
8628 .indent_size_for_line(MultiBufferRow(selection.start.row))
8629 .len;
8630 let language = if let Some(language) =
8631 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8632 {
8633 language
8634 } else {
8635 continue;
8636 };
8637
8638 selection_edit_ranges.clear();
8639
8640 // If multiple selections contain a given row, avoid processing that
8641 // row more than once.
8642 let mut start_row = MultiBufferRow(selection.start.row);
8643 if last_toggled_row == Some(start_row) {
8644 start_row = start_row.next_row();
8645 }
8646 let end_row =
8647 if selection.end.row > selection.start.row && selection.end.column == 0 {
8648 MultiBufferRow(selection.end.row - 1)
8649 } else {
8650 MultiBufferRow(selection.end.row)
8651 };
8652 last_toggled_row = Some(end_row);
8653
8654 if start_row > end_row {
8655 continue;
8656 }
8657
8658 // If the language has line comments, toggle those.
8659 let full_comment_prefixes = language.line_comment_prefixes();
8660 if !full_comment_prefixes.is_empty() {
8661 let first_prefix = full_comment_prefixes
8662 .first()
8663 .expect("prefixes is non-empty");
8664 let prefix_trimmed_lengths = full_comment_prefixes
8665 .iter()
8666 .map(|p| p.trim_end_matches(' ').len())
8667 .collect::<SmallVec<[usize; 4]>>();
8668
8669 let mut all_selection_lines_are_comments = true;
8670
8671 for row in start_row.0..=end_row.0 {
8672 let row = MultiBufferRow(row);
8673 if start_row < end_row && snapshot.is_line_blank(row) {
8674 continue;
8675 }
8676
8677 let prefix_range = full_comment_prefixes
8678 .iter()
8679 .zip(prefix_trimmed_lengths.iter().copied())
8680 .map(|(prefix, trimmed_prefix_len)| {
8681 comment_prefix_range(
8682 snapshot.deref(),
8683 row,
8684 &prefix[..trimmed_prefix_len],
8685 &prefix[trimmed_prefix_len..],
8686 )
8687 })
8688 .max_by_key(|range| range.end.column - range.start.column)
8689 .expect("prefixes is non-empty");
8690
8691 if prefix_range.is_empty() {
8692 all_selection_lines_are_comments = false;
8693 }
8694
8695 selection_edit_ranges.push(prefix_range);
8696 }
8697
8698 if all_selection_lines_are_comments {
8699 edits.extend(
8700 selection_edit_ranges
8701 .iter()
8702 .cloned()
8703 .map(|range| (range, empty_str.clone())),
8704 );
8705 } else {
8706 let min_column = selection_edit_ranges
8707 .iter()
8708 .map(|range| range.start.column)
8709 .min()
8710 .unwrap_or(0);
8711 edits.extend(selection_edit_ranges.iter().map(|range| {
8712 let position = Point::new(range.start.row, min_column);
8713 (position..position, first_prefix.clone())
8714 }));
8715 }
8716 } else if let Some((full_comment_prefix, comment_suffix)) =
8717 language.block_comment_delimiters()
8718 {
8719 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8720 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8721 let prefix_range = comment_prefix_range(
8722 snapshot.deref(),
8723 start_row,
8724 comment_prefix,
8725 comment_prefix_whitespace,
8726 );
8727 let suffix_range = comment_suffix_range(
8728 snapshot.deref(),
8729 end_row,
8730 comment_suffix.trim_start_matches(' '),
8731 comment_suffix.starts_with(' '),
8732 );
8733
8734 if prefix_range.is_empty() || suffix_range.is_empty() {
8735 edits.push((
8736 prefix_range.start..prefix_range.start,
8737 full_comment_prefix.clone(),
8738 ));
8739 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8740 suffixes_inserted.push((end_row, comment_suffix.len()));
8741 } else {
8742 edits.push((prefix_range, empty_str.clone()));
8743 edits.push((suffix_range, empty_str.clone()));
8744 }
8745 } else {
8746 continue;
8747 }
8748 }
8749
8750 drop(snapshot);
8751 this.buffer.update(cx, |buffer, cx| {
8752 buffer.edit(edits, None, cx);
8753 });
8754
8755 // Adjust selections so that they end before any comment suffixes that
8756 // were inserted.
8757 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8758 let mut selections = this.selections.all::<Point>(cx);
8759 let snapshot = this.buffer.read(cx).read(cx);
8760 for selection in &mut selections {
8761 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8762 match row.cmp(&MultiBufferRow(selection.end.row)) {
8763 Ordering::Less => {
8764 suffixes_inserted.next();
8765 continue;
8766 }
8767 Ordering::Greater => break,
8768 Ordering::Equal => {
8769 if selection.end.column == snapshot.line_len(row) {
8770 if selection.is_empty() {
8771 selection.start.column -= suffix_len as u32;
8772 }
8773 selection.end.column -= suffix_len as u32;
8774 }
8775 break;
8776 }
8777 }
8778 }
8779 }
8780
8781 drop(snapshot);
8782 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8783
8784 let selections = this.selections.all::<Point>(cx);
8785 let selections_on_single_row = selections.windows(2).all(|selections| {
8786 selections[0].start.row == selections[1].start.row
8787 && selections[0].end.row == selections[1].end.row
8788 && selections[0].start.row == selections[0].end.row
8789 });
8790 let selections_selecting = selections
8791 .iter()
8792 .any(|selection| selection.start != selection.end);
8793 let advance_downwards = action.advance_downwards
8794 && selections_on_single_row
8795 && !selections_selecting
8796 && !matches!(this.mode, EditorMode::SingleLine { .. });
8797
8798 if advance_downwards {
8799 let snapshot = this.buffer.read(cx).snapshot(cx);
8800
8801 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8802 s.move_cursors_with(|display_snapshot, display_point, _| {
8803 let mut point = display_point.to_point(display_snapshot);
8804 point.row += 1;
8805 point = snapshot.clip_point(point, Bias::Left);
8806 let display_point = point.to_display_point(display_snapshot);
8807 let goal = SelectionGoal::HorizontalPosition(
8808 display_snapshot
8809 .x_for_display_point(display_point, text_layout_details)
8810 .into(),
8811 );
8812 (display_point, goal)
8813 })
8814 });
8815 }
8816 });
8817 }
8818
8819 pub fn select_enclosing_symbol(
8820 &mut self,
8821 _: &SelectEnclosingSymbol,
8822 cx: &mut ViewContext<Self>,
8823 ) {
8824 let buffer = self.buffer.read(cx).snapshot(cx);
8825 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8826
8827 fn update_selection(
8828 selection: &Selection<usize>,
8829 buffer_snap: &MultiBufferSnapshot,
8830 ) -> Option<Selection<usize>> {
8831 let cursor = selection.head();
8832 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8833 for symbol in symbols.iter().rev() {
8834 let start = symbol.range.start.to_offset(buffer_snap);
8835 let end = symbol.range.end.to_offset(buffer_snap);
8836 let new_range = start..end;
8837 if start < selection.start || end > selection.end {
8838 return Some(Selection {
8839 id: selection.id,
8840 start: new_range.start,
8841 end: new_range.end,
8842 goal: SelectionGoal::None,
8843 reversed: selection.reversed,
8844 });
8845 }
8846 }
8847 None
8848 }
8849
8850 let mut selected_larger_symbol = false;
8851 let new_selections = old_selections
8852 .iter()
8853 .map(|selection| match update_selection(selection, &buffer) {
8854 Some(new_selection) => {
8855 if new_selection.range() != selection.range() {
8856 selected_larger_symbol = true;
8857 }
8858 new_selection
8859 }
8860 None => selection.clone(),
8861 })
8862 .collect::<Vec<_>>();
8863
8864 if selected_larger_symbol {
8865 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8866 s.select(new_selections);
8867 });
8868 }
8869 }
8870
8871 pub fn select_larger_syntax_node(
8872 &mut self,
8873 _: &SelectLargerSyntaxNode,
8874 cx: &mut ViewContext<Self>,
8875 ) {
8876 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8877 let buffer = self.buffer.read(cx).snapshot(cx);
8878 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8879
8880 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8881 let mut selected_larger_node = false;
8882 let new_selections = old_selections
8883 .iter()
8884 .map(|selection| {
8885 let old_range = selection.start..selection.end;
8886 let mut new_range = old_range.clone();
8887 while let Some(containing_range) =
8888 buffer.range_for_syntax_ancestor(new_range.clone())
8889 {
8890 new_range = containing_range;
8891 if !display_map.intersects_fold(new_range.start)
8892 && !display_map.intersects_fold(new_range.end)
8893 {
8894 break;
8895 }
8896 }
8897
8898 selected_larger_node |= new_range != old_range;
8899 Selection {
8900 id: selection.id,
8901 start: new_range.start,
8902 end: new_range.end,
8903 goal: SelectionGoal::None,
8904 reversed: selection.reversed,
8905 }
8906 })
8907 .collect::<Vec<_>>();
8908
8909 if selected_larger_node {
8910 stack.push(old_selections);
8911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8912 s.select(new_selections);
8913 });
8914 }
8915 self.select_larger_syntax_node_stack = stack;
8916 }
8917
8918 pub fn select_smaller_syntax_node(
8919 &mut self,
8920 _: &SelectSmallerSyntaxNode,
8921 cx: &mut ViewContext<Self>,
8922 ) {
8923 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8924 if let Some(selections) = stack.pop() {
8925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8926 s.select(selections.to_vec());
8927 });
8928 }
8929 self.select_larger_syntax_node_stack = stack;
8930 }
8931
8932 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8933 if !EditorSettings::get_global(cx).gutter.runnables {
8934 self.clear_tasks();
8935 return Task::ready(());
8936 }
8937 let project = self.project.clone();
8938 cx.spawn(|this, mut cx| async move {
8939 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8940 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8941 }) else {
8942 return;
8943 };
8944
8945 let Some(project) = project else {
8946 return;
8947 };
8948
8949 let hide_runnables = project
8950 .update(&mut cx, |project, cx| {
8951 // Do not display any test indicators in non-dev server remote projects.
8952 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8953 })
8954 .unwrap_or(true);
8955 if hide_runnables {
8956 return;
8957 }
8958 let new_rows =
8959 cx.background_executor()
8960 .spawn({
8961 let snapshot = display_snapshot.clone();
8962 async move {
8963 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8964 }
8965 })
8966 .await;
8967 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8968
8969 this.update(&mut cx, |this, _| {
8970 this.clear_tasks();
8971 for (key, value) in rows {
8972 this.insert_tasks(key, value);
8973 }
8974 })
8975 .ok();
8976 })
8977 }
8978 fn fetch_runnable_ranges(
8979 snapshot: &DisplaySnapshot,
8980 range: Range<Anchor>,
8981 ) -> Vec<language::RunnableRange> {
8982 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8983 }
8984
8985 fn runnable_rows(
8986 project: Model<Project>,
8987 snapshot: DisplaySnapshot,
8988 runnable_ranges: Vec<RunnableRange>,
8989 mut cx: AsyncWindowContext,
8990 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8991 runnable_ranges
8992 .into_iter()
8993 .filter_map(|mut runnable| {
8994 let tasks = cx
8995 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8996 .ok()?;
8997 if tasks.is_empty() {
8998 return None;
8999 }
9000
9001 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9002
9003 let row = snapshot
9004 .buffer_snapshot
9005 .buffer_line_for_row(MultiBufferRow(point.row))?
9006 .1
9007 .start
9008 .row;
9009
9010 let context_range =
9011 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9012 Some((
9013 (runnable.buffer_id, row),
9014 RunnableTasks {
9015 templates: tasks,
9016 offset: MultiBufferOffset(runnable.run_range.start),
9017 context_range,
9018 column: point.column,
9019 extra_variables: runnable.extra_captures,
9020 },
9021 ))
9022 })
9023 .collect()
9024 }
9025
9026 fn templates_with_tags(
9027 project: &Model<Project>,
9028 runnable: &mut Runnable,
9029 cx: &WindowContext<'_>,
9030 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9031 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9032 let (worktree_id, file) = project
9033 .buffer_for_id(runnable.buffer, cx)
9034 .and_then(|buffer| buffer.read(cx).file())
9035 .map(|file| (file.worktree_id(cx), file.clone()))
9036 .unzip();
9037
9038 (project.task_inventory().clone(), worktree_id, file)
9039 });
9040
9041 let inventory = inventory.read(cx);
9042 let tags = mem::take(&mut runnable.tags);
9043 let mut tags: Vec<_> = tags
9044 .into_iter()
9045 .flat_map(|tag| {
9046 let tag = tag.0.clone();
9047 inventory
9048 .list_tasks(
9049 file.clone(),
9050 Some(runnable.language.clone()),
9051 worktree_id,
9052 cx,
9053 )
9054 .into_iter()
9055 .filter(move |(_, template)| {
9056 template.tags.iter().any(|source_tag| source_tag == &tag)
9057 })
9058 })
9059 .sorted_by_key(|(kind, _)| kind.to_owned())
9060 .collect();
9061 if let Some((leading_tag_source, _)) = tags.first() {
9062 // Strongest source wins; if we have worktree tag binding, prefer that to
9063 // global and language bindings;
9064 // if we have a global binding, prefer that to language binding.
9065 let first_mismatch = tags
9066 .iter()
9067 .position(|(tag_source, _)| tag_source != leading_tag_source);
9068 if let Some(index) = first_mismatch {
9069 tags.truncate(index);
9070 }
9071 }
9072
9073 tags
9074 }
9075
9076 pub fn move_to_enclosing_bracket(
9077 &mut self,
9078 _: &MoveToEnclosingBracket,
9079 cx: &mut ViewContext<Self>,
9080 ) {
9081 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9082 s.move_offsets_with(|snapshot, selection| {
9083 let Some(enclosing_bracket_ranges) =
9084 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9085 else {
9086 return;
9087 };
9088
9089 let mut best_length = usize::MAX;
9090 let mut best_inside = false;
9091 let mut best_in_bracket_range = false;
9092 let mut best_destination = None;
9093 for (open, close) in enclosing_bracket_ranges {
9094 let close = close.to_inclusive();
9095 let length = close.end() - open.start;
9096 let inside = selection.start >= open.end && selection.end <= *close.start();
9097 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9098 || close.contains(&selection.head());
9099
9100 // If best is next to a bracket and current isn't, skip
9101 if !in_bracket_range && best_in_bracket_range {
9102 continue;
9103 }
9104
9105 // Prefer smaller lengths unless best is inside and current isn't
9106 if length > best_length && (best_inside || !inside) {
9107 continue;
9108 }
9109
9110 best_length = length;
9111 best_inside = inside;
9112 best_in_bracket_range = in_bracket_range;
9113 best_destination = Some(
9114 if close.contains(&selection.start) && close.contains(&selection.end) {
9115 if inside {
9116 open.end
9117 } else {
9118 open.start
9119 }
9120 } else if inside {
9121 *close.start()
9122 } else {
9123 *close.end()
9124 },
9125 );
9126 }
9127
9128 if let Some(destination) = best_destination {
9129 selection.collapse_to(destination, SelectionGoal::None);
9130 }
9131 })
9132 });
9133 }
9134
9135 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9136 self.end_selection(cx);
9137 self.selection_history.mode = SelectionHistoryMode::Undoing;
9138 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9139 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9140 self.select_next_state = entry.select_next_state;
9141 self.select_prev_state = entry.select_prev_state;
9142 self.add_selections_state = entry.add_selections_state;
9143 self.request_autoscroll(Autoscroll::newest(), cx);
9144 }
9145 self.selection_history.mode = SelectionHistoryMode::Normal;
9146 }
9147
9148 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9149 self.end_selection(cx);
9150 self.selection_history.mode = SelectionHistoryMode::Redoing;
9151 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9152 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9153 self.select_next_state = entry.select_next_state;
9154 self.select_prev_state = entry.select_prev_state;
9155 self.add_selections_state = entry.add_selections_state;
9156 self.request_autoscroll(Autoscroll::newest(), cx);
9157 }
9158 self.selection_history.mode = SelectionHistoryMode::Normal;
9159 }
9160
9161 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9162 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9163 }
9164
9165 pub fn expand_excerpts_down(
9166 &mut self,
9167 action: &ExpandExcerptsDown,
9168 cx: &mut ViewContext<Self>,
9169 ) {
9170 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9171 }
9172
9173 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9174 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9175 }
9176
9177 pub fn expand_excerpts_for_direction(
9178 &mut self,
9179 lines: u32,
9180 direction: ExpandExcerptDirection,
9181 cx: &mut ViewContext<Self>,
9182 ) {
9183 let selections = self.selections.disjoint_anchors();
9184
9185 let lines = if lines == 0 {
9186 EditorSettings::get_global(cx).expand_excerpt_lines
9187 } else {
9188 lines
9189 };
9190
9191 self.buffer.update(cx, |buffer, cx| {
9192 buffer.expand_excerpts(
9193 selections
9194 .iter()
9195 .map(|selection| selection.head().excerpt_id)
9196 .dedup(),
9197 lines,
9198 direction,
9199 cx,
9200 )
9201 })
9202 }
9203
9204 pub fn expand_excerpt(
9205 &mut self,
9206 excerpt: ExcerptId,
9207 direction: ExpandExcerptDirection,
9208 cx: &mut ViewContext<Self>,
9209 ) {
9210 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9211 self.buffer.update(cx, |buffer, cx| {
9212 buffer.expand_excerpts([excerpt], lines, direction, cx)
9213 })
9214 }
9215
9216 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9217 self.go_to_diagnostic_impl(Direction::Next, cx)
9218 }
9219
9220 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9221 self.go_to_diagnostic_impl(Direction::Prev, cx)
9222 }
9223
9224 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9225 let buffer = self.buffer.read(cx).snapshot(cx);
9226 let selection = self.selections.newest::<usize>(cx);
9227
9228 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9229 if direction == Direction::Next {
9230 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9231 let (group_id, jump_to) = popover.activation_info();
9232 if self.activate_diagnostics(group_id, cx) {
9233 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9234 let mut new_selection = s.newest_anchor().clone();
9235 new_selection.collapse_to(jump_to, SelectionGoal::None);
9236 s.select_anchors(vec![new_selection.clone()]);
9237 });
9238 }
9239 return;
9240 }
9241 }
9242
9243 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9244 active_diagnostics
9245 .primary_range
9246 .to_offset(&buffer)
9247 .to_inclusive()
9248 });
9249 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9250 if active_primary_range.contains(&selection.head()) {
9251 *active_primary_range.start()
9252 } else {
9253 selection.head()
9254 }
9255 } else {
9256 selection.head()
9257 };
9258 let snapshot = self.snapshot(cx);
9259 loop {
9260 let diagnostics = if direction == Direction::Prev {
9261 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9262 } else {
9263 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9264 }
9265 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9266 let group = diagnostics
9267 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9268 // be sorted in a stable way
9269 // skip until we are at current active diagnostic, if it exists
9270 .skip_while(|entry| {
9271 (match direction {
9272 Direction::Prev => entry.range.start >= search_start,
9273 Direction::Next => entry.range.start <= search_start,
9274 }) && self
9275 .active_diagnostics
9276 .as_ref()
9277 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9278 })
9279 .find_map(|entry| {
9280 if entry.diagnostic.is_primary
9281 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9282 && !entry.range.is_empty()
9283 // if we match with the active diagnostic, skip it
9284 && Some(entry.diagnostic.group_id)
9285 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9286 {
9287 Some((entry.range, entry.diagnostic.group_id))
9288 } else {
9289 None
9290 }
9291 });
9292
9293 if let Some((primary_range, group_id)) = group {
9294 if self.activate_diagnostics(group_id, cx) {
9295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9296 s.select(vec![Selection {
9297 id: selection.id,
9298 start: primary_range.start,
9299 end: primary_range.start,
9300 reversed: false,
9301 goal: SelectionGoal::None,
9302 }]);
9303 });
9304 }
9305 break;
9306 } else {
9307 // Cycle around to the start of the buffer, potentially moving back to the start of
9308 // the currently active diagnostic.
9309 active_primary_range.take();
9310 if direction == Direction::Prev {
9311 if search_start == buffer.len() {
9312 break;
9313 } else {
9314 search_start = buffer.len();
9315 }
9316 } else if search_start == 0 {
9317 break;
9318 } else {
9319 search_start = 0;
9320 }
9321 }
9322 }
9323 }
9324
9325 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9326 let snapshot = self
9327 .display_map
9328 .update(cx, |display_map, cx| display_map.snapshot(cx));
9329 let selection = self.selections.newest::<Point>(cx);
9330 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9331 }
9332
9333 fn go_to_hunk_after_position(
9334 &mut self,
9335 snapshot: &DisplaySnapshot,
9336 position: Point,
9337 cx: &mut ViewContext<'_, Editor>,
9338 ) -> Option<MultiBufferDiffHunk> {
9339 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9340 snapshot,
9341 position,
9342 false,
9343 snapshot
9344 .buffer_snapshot
9345 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9346 cx,
9347 ) {
9348 return Some(hunk);
9349 }
9350
9351 let wrapped_point = Point::zero();
9352 self.go_to_next_hunk_in_direction(
9353 snapshot,
9354 wrapped_point,
9355 true,
9356 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9357 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9358 ),
9359 cx,
9360 )
9361 }
9362
9363 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9364 let snapshot = self
9365 .display_map
9366 .update(cx, |display_map, cx| display_map.snapshot(cx));
9367 let selection = self.selections.newest::<Point>(cx);
9368
9369 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9370 }
9371
9372 fn go_to_hunk_before_position(
9373 &mut self,
9374 snapshot: &DisplaySnapshot,
9375 position: Point,
9376 cx: &mut ViewContext<'_, Editor>,
9377 ) -> Option<MultiBufferDiffHunk> {
9378 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9379 snapshot,
9380 position,
9381 false,
9382 snapshot
9383 .buffer_snapshot
9384 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9385 cx,
9386 ) {
9387 return Some(hunk);
9388 }
9389
9390 let wrapped_point = snapshot.buffer_snapshot.max_point();
9391 self.go_to_next_hunk_in_direction(
9392 snapshot,
9393 wrapped_point,
9394 true,
9395 snapshot
9396 .buffer_snapshot
9397 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9398 cx,
9399 )
9400 }
9401
9402 fn go_to_next_hunk_in_direction(
9403 &mut self,
9404 snapshot: &DisplaySnapshot,
9405 initial_point: Point,
9406 is_wrapped: bool,
9407 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9408 cx: &mut ViewContext<Editor>,
9409 ) -> Option<MultiBufferDiffHunk> {
9410 let display_point = initial_point.to_display_point(snapshot);
9411 let mut hunks = hunks
9412 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9413 .filter(|(display_hunk, _)| {
9414 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9415 })
9416 .dedup();
9417
9418 if let Some((display_hunk, hunk)) = hunks.next() {
9419 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9420 let row = display_hunk.start_display_row();
9421 let point = DisplayPoint::new(row, 0);
9422 s.select_display_ranges([point..point]);
9423 });
9424
9425 Some(hunk)
9426 } else {
9427 None
9428 }
9429 }
9430
9431 pub fn go_to_definition(
9432 &mut self,
9433 _: &GoToDefinition,
9434 cx: &mut ViewContext<Self>,
9435 ) -> Task<Result<Navigated>> {
9436 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9437 cx.spawn(|editor, mut cx| async move {
9438 if definition.await? == Navigated::Yes {
9439 return Ok(Navigated::Yes);
9440 }
9441 match editor.update(&mut cx, |editor, cx| {
9442 editor.find_all_references(&FindAllReferences, cx)
9443 })? {
9444 Some(references) => references.await,
9445 None => Ok(Navigated::No),
9446 }
9447 })
9448 }
9449
9450 pub fn go_to_declaration(
9451 &mut self,
9452 _: &GoToDeclaration,
9453 cx: &mut ViewContext<Self>,
9454 ) -> Task<Result<Navigated>> {
9455 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9456 }
9457
9458 pub fn go_to_declaration_split(
9459 &mut self,
9460 _: &GoToDeclaration,
9461 cx: &mut ViewContext<Self>,
9462 ) -> Task<Result<Navigated>> {
9463 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9464 }
9465
9466 pub fn go_to_implementation(
9467 &mut self,
9468 _: &GoToImplementation,
9469 cx: &mut ViewContext<Self>,
9470 ) -> Task<Result<Navigated>> {
9471 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9472 }
9473
9474 pub fn go_to_implementation_split(
9475 &mut self,
9476 _: &GoToImplementationSplit,
9477 cx: &mut ViewContext<Self>,
9478 ) -> Task<Result<Navigated>> {
9479 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9480 }
9481
9482 pub fn go_to_type_definition(
9483 &mut self,
9484 _: &GoToTypeDefinition,
9485 cx: &mut ViewContext<Self>,
9486 ) -> Task<Result<Navigated>> {
9487 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9488 }
9489
9490 pub fn go_to_definition_split(
9491 &mut self,
9492 _: &GoToDefinitionSplit,
9493 cx: &mut ViewContext<Self>,
9494 ) -> Task<Result<Navigated>> {
9495 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9496 }
9497
9498 pub fn go_to_type_definition_split(
9499 &mut self,
9500 _: &GoToTypeDefinitionSplit,
9501 cx: &mut ViewContext<Self>,
9502 ) -> Task<Result<Navigated>> {
9503 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9504 }
9505
9506 fn go_to_definition_of_kind(
9507 &mut self,
9508 kind: GotoDefinitionKind,
9509 split: bool,
9510 cx: &mut ViewContext<Self>,
9511 ) -> Task<Result<Navigated>> {
9512 let Some(workspace) = self.workspace() else {
9513 return Task::ready(Ok(Navigated::No));
9514 };
9515 let buffer = self.buffer.read(cx);
9516 let head = self.selections.newest::<usize>(cx).head();
9517 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9518 text_anchor
9519 } else {
9520 return Task::ready(Ok(Navigated::No));
9521 };
9522
9523 let project = workspace.read(cx).project().clone();
9524 let definitions = project.update(cx, |project, cx| match kind {
9525 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9526 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9527 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9528 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9529 });
9530
9531 cx.spawn(|editor, mut cx| async move {
9532 let definitions = definitions.await?;
9533 let navigated = editor
9534 .update(&mut cx, |editor, cx| {
9535 editor.navigate_to_hover_links(
9536 Some(kind),
9537 definitions
9538 .into_iter()
9539 .filter(|location| {
9540 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9541 })
9542 .map(HoverLink::Text)
9543 .collect::<Vec<_>>(),
9544 split,
9545 cx,
9546 )
9547 })?
9548 .await?;
9549 anyhow::Ok(navigated)
9550 })
9551 }
9552
9553 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9554 let position = self.selections.newest_anchor().head();
9555 let Some((buffer, buffer_position)) =
9556 self.buffer.read(cx).text_anchor_for_position(position, cx)
9557 else {
9558 return;
9559 };
9560
9561 cx.spawn(|editor, mut cx| async move {
9562 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9563 editor.update(&mut cx, |_, cx| {
9564 cx.open_url(&url);
9565 })
9566 } else {
9567 Ok(())
9568 }
9569 })
9570 .detach();
9571 }
9572
9573 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9574 let Some(workspace) = self.workspace() else {
9575 return;
9576 };
9577
9578 let position = self.selections.newest_anchor().head();
9579
9580 let Some((buffer, buffer_position)) =
9581 self.buffer.read(cx).text_anchor_for_position(position, cx)
9582 else {
9583 return;
9584 };
9585
9586 let Some(project) = self.project.clone() else {
9587 return;
9588 };
9589
9590 cx.spawn(|_, mut cx| async move {
9591 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9592
9593 if let Some((_, path)) = result {
9594 workspace
9595 .update(&mut cx, |workspace, cx| {
9596 workspace.open_resolved_path(path, cx)
9597 })?
9598 .await?;
9599 }
9600 anyhow::Ok(())
9601 })
9602 .detach();
9603 }
9604
9605 pub(crate) fn navigate_to_hover_links(
9606 &mut self,
9607 kind: Option<GotoDefinitionKind>,
9608 mut definitions: Vec<HoverLink>,
9609 split: bool,
9610 cx: &mut ViewContext<Editor>,
9611 ) -> Task<Result<Navigated>> {
9612 // If there is one definition, just open it directly
9613 if definitions.len() == 1 {
9614 let definition = definitions.pop().unwrap();
9615
9616 enum TargetTaskResult {
9617 Location(Option<Location>),
9618 AlreadyNavigated,
9619 }
9620
9621 let target_task = match definition {
9622 HoverLink::Text(link) => {
9623 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9624 }
9625 HoverLink::InlayHint(lsp_location, server_id) => {
9626 let computation = self.compute_target_location(lsp_location, server_id, cx);
9627 cx.background_executor().spawn(async move {
9628 let location = computation.await?;
9629 Ok(TargetTaskResult::Location(location))
9630 })
9631 }
9632 HoverLink::Url(url) => {
9633 cx.open_url(&url);
9634 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9635 }
9636 HoverLink::File(path) => {
9637 if let Some(workspace) = self.workspace() {
9638 cx.spawn(|_, mut cx| async move {
9639 workspace
9640 .update(&mut cx, |workspace, cx| {
9641 workspace.open_resolved_path(path, cx)
9642 })?
9643 .await
9644 .map(|_| TargetTaskResult::AlreadyNavigated)
9645 })
9646 } else {
9647 Task::ready(Ok(TargetTaskResult::Location(None)))
9648 }
9649 }
9650 };
9651 cx.spawn(|editor, mut cx| async move {
9652 let target = match target_task.await.context("target resolution task")? {
9653 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9654 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9655 TargetTaskResult::Location(Some(target)) => target,
9656 };
9657
9658 editor.update(&mut cx, |editor, cx| {
9659 let Some(workspace) = editor.workspace() else {
9660 return Navigated::No;
9661 };
9662 let pane = workspace.read(cx).active_pane().clone();
9663
9664 let range = target.range.to_offset(target.buffer.read(cx));
9665 let range = editor.range_for_match(&range);
9666
9667 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9668 let buffer = target.buffer.read(cx);
9669 let range = check_multiline_range(buffer, range);
9670 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9671 s.select_ranges([range]);
9672 });
9673 } else {
9674 cx.window_context().defer(move |cx| {
9675 let target_editor: View<Self> =
9676 workspace.update(cx, |workspace, cx| {
9677 let pane = if split {
9678 workspace.adjacent_pane(cx)
9679 } else {
9680 workspace.active_pane().clone()
9681 };
9682
9683 workspace.open_project_item(
9684 pane,
9685 target.buffer.clone(),
9686 true,
9687 true,
9688 cx,
9689 )
9690 });
9691 target_editor.update(cx, |target_editor, cx| {
9692 // When selecting a definition in a different buffer, disable the nav history
9693 // to avoid creating a history entry at the previous cursor location.
9694 pane.update(cx, |pane, _| pane.disable_history());
9695 let buffer = target.buffer.read(cx);
9696 let range = check_multiline_range(buffer, range);
9697 target_editor.change_selections(
9698 Some(Autoscroll::focused()),
9699 cx,
9700 |s| {
9701 s.select_ranges([range]);
9702 },
9703 );
9704 pane.update(cx, |pane, _| pane.enable_history());
9705 });
9706 });
9707 }
9708 Navigated::Yes
9709 })
9710 })
9711 } else if !definitions.is_empty() {
9712 cx.spawn(|editor, mut cx| async move {
9713 let (title, location_tasks, workspace) = editor
9714 .update(&mut cx, |editor, cx| {
9715 let tab_kind = match kind {
9716 Some(GotoDefinitionKind::Implementation) => "Implementations",
9717 _ => "Definitions",
9718 };
9719 let title = definitions
9720 .iter()
9721 .find_map(|definition| match definition {
9722 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9723 let buffer = origin.buffer.read(cx);
9724 format!(
9725 "{} for {}",
9726 tab_kind,
9727 buffer
9728 .text_for_range(origin.range.clone())
9729 .collect::<String>()
9730 )
9731 }),
9732 HoverLink::InlayHint(_, _) => None,
9733 HoverLink::Url(_) => None,
9734 HoverLink::File(_) => None,
9735 })
9736 .unwrap_or(tab_kind.to_string());
9737 let location_tasks = definitions
9738 .into_iter()
9739 .map(|definition| match definition {
9740 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9741 HoverLink::InlayHint(lsp_location, server_id) => {
9742 editor.compute_target_location(lsp_location, server_id, cx)
9743 }
9744 HoverLink::Url(_) => Task::ready(Ok(None)),
9745 HoverLink::File(_) => Task::ready(Ok(None)),
9746 })
9747 .collect::<Vec<_>>();
9748 (title, location_tasks, editor.workspace().clone())
9749 })
9750 .context("location tasks preparation")?;
9751
9752 let locations = future::join_all(location_tasks)
9753 .await
9754 .into_iter()
9755 .filter_map(|location| location.transpose())
9756 .collect::<Result<_>>()
9757 .context("location tasks")?;
9758
9759 let Some(workspace) = workspace else {
9760 return Ok(Navigated::No);
9761 };
9762 let opened = workspace
9763 .update(&mut cx, |workspace, cx| {
9764 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9765 })
9766 .ok();
9767
9768 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9769 })
9770 } else {
9771 Task::ready(Ok(Navigated::No))
9772 }
9773 }
9774
9775 fn compute_target_location(
9776 &self,
9777 lsp_location: lsp::Location,
9778 server_id: LanguageServerId,
9779 cx: &mut ViewContext<Editor>,
9780 ) -> Task<anyhow::Result<Option<Location>>> {
9781 let Some(project) = self.project.clone() else {
9782 return Task::Ready(Some(Ok(None)));
9783 };
9784
9785 cx.spawn(move |editor, mut cx| async move {
9786 let location_task = editor.update(&mut cx, |editor, cx| {
9787 project.update(cx, |project, cx| {
9788 let language_server_name =
9789 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9790 project
9791 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9792 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9793 });
9794 language_server_name.map(|language_server_name| {
9795 project.open_local_buffer_via_lsp(
9796 lsp_location.uri.clone(),
9797 server_id,
9798 language_server_name,
9799 cx,
9800 )
9801 })
9802 })
9803 })?;
9804 let location = match location_task {
9805 Some(task) => Some({
9806 let target_buffer_handle = task.await.context("open local buffer")?;
9807 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9808 let target_start = target_buffer
9809 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9810 let target_end = target_buffer
9811 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9812 target_buffer.anchor_after(target_start)
9813 ..target_buffer.anchor_before(target_end)
9814 })?;
9815 Location {
9816 buffer: target_buffer_handle,
9817 range,
9818 }
9819 }),
9820 None => None,
9821 };
9822 Ok(location)
9823 })
9824 }
9825
9826 pub fn find_all_references(
9827 &mut self,
9828 _: &FindAllReferences,
9829 cx: &mut ViewContext<Self>,
9830 ) -> Option<Task<Result<Navigated>>> {
9831 let multi_buffer = self.buffer.read(cx);
9832 let selection = self.selections.newest::<usize>(cx);
9833 let head = selection.head();
9834
9835 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9836 let head_anchor = multi_buffer_snapshot.anchor_at(
9837 head,
9838 if head < selection.tail() {
9839 Bias::Right
9840 } else {
9841 Bias::Left
9842 },
9843 );
9844
9845 match self
9846 .find_all_references_task_sources
9847 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9848 {
9849 Ok(_) => {
9850 log::info!(
9851 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9852 );
9853 return None;
9854 }
9855 Err(i) => {
9856 self.find_all_references_task_sources.insert(i, head_anchor);
9857 }
9858 }
9859
9860 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9861 let workspace = self.workspace()?;
9862 let project = workspace.read(cx).project().clone();
9863 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9864 Some(cx.spawn(|editor, mut cx| async move {
9865 let _cleanup = defer({
9866 let mut cx = cx.clone();
9867 move || {
9868 let _ = editor.update(&mut cx, |editor, _| {
9869 if let Ok(i) =
9870 editor
9871 .find_all_references_task_sources
9872 .binary_search_by(|anchor| {
9873 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9874 })
9875 {
9876 editor.find_all_references_task_sources.remove(i);
9877 }
9878 });
9879 }
9880 });
9881
9882 let locations = references.await?;
9883 if locations.is_empty() {
9884 return anyhow::Ok(Navigated::No);
9885 }
9886
9887 workspace.update(&mut cx, |workspace, cx| {
9888 let title = locations
9889 .first()
9890 .as_ref()
9891 .map(|location| {
9892 let buffer = location.buffer.read(cx);
9893 format!(
9894 "References to `{}`",
9895 buffer
9896 .text_for_range(location.range.clone())
9897 .collect::<String>()
9898 )
9899 })
9900 .unwrap();
9901 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9902 Navigated::Yes
9903 })
9904 }))
9905 }
9906
9907 /// Opens a multibuffer with the given project locations in it
9908 pub fn open_locations_in_multibuffer(
9909 workspace: &mut Workspace,
9910 mut locations: Vec<Location>,
9911 title: String,
9912 split: bool,
9913 cx: &mut ViewContext<Workspace>,
9914 ) {
9915 // If there are multiple definitions, open them in a multibuffer
9916 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9917 let mut locations = locations.into_iter().peekable();
9918 let mut ranges_to_highlight = Vec::new();
9919 let capability = workspace.project().read(cx).capability();
9920
9921 let excerpt_buffer = cx.new_model(|cx| {
9922 let mut multibuffer = MultiBuffer::new(capability);
9923 while let Some(location) = locations.next() {
9924 let buffer = location.buffer.read(cx);
9925 let mut ranges_for_buffer = Vec::new();
9926 let range = location.range.to_offset(buffer);
9927 ranges_for_buffer.push(range.clone());
9928
9929 while let Some(next_location) = locations.peek() {
9930 if next_location.buffer == location.buffer {
9931 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9932 locations.next();
9933 } else {
9934 break;
9935 }
9936 }
9937
9938 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9939 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9940 location.buffer.clone(),
9941 ranges_for_buffer,
9942 DEFAULT_MULTIBUFFER_CONTEXT,
9943 cx,
9944 ))
9945 }
9946
9947 multibuffer.with_title(title)
9948 });
9949
9950 let editor = cx.new_view(|cx| {
9951 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9952 });
9953 editor.update(cx, |editor, cx| {
9954 if let Some(first_range) = ranges_to_highlight.first() {
9955 editor.change_selections(None, cx, |selections| {
9956 selections.clear_disjoint();
9957 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9958 });
9959 }
9960 editor.highlight_background::<Self>(
9961 &ranges_to_highlight,
9962 |theme| theme.editor_highlighted_line_background,
9963 cx,
9964 );
9965 });
9966
9967 let item = Box::new(editor);
9968 let item_id = item.item_id();
9969
9970 if split {
9971 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9972 } else {
9973 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9974 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9975 pane.close_current_preview_item(cx)
9976 } else {
9977 None
9978 }
9979 });
9980 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9981 }
9982 workspace.active_pane().update(cx, |pane, cx| {
9983 pane.set_preview_item_id(Some(item_id), cx);
9984 });
9985 }
9986
9987 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9988 use language::ToOffset as _;
9989
9990 let project = self.project.clone()?;
9991 let selection = self.selections.newest_anchor().clone();
9992 let (cursor_buffer, cursor_buffer_position) = self
9993 .buffer
9994 .read(cx)
9995 .text_anchor_for_position(selection.head(), cx)?;
9996 let (tail_buffer, cursor_buffer_position_end) = self
9997 .buffer
9998 .read(cx)
9999 .text_anchor_for_position(selection.tail(), cx)?;
10000 if tail_buffer != cursor_buffer {
10001 return None;
10002 }
10003
10004 let snapshot = cursor_buffer.read(cx).snapshot();
10005 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10006 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10007 let prepare_rename = project.update(cx, |project, cx| {
10008 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10009 });
10010 drop(snapshot);
10011
10012 Some(cx.spawn(|this, mut cx| async move {
10013 let rename_range = if let Some(range) = prepare_rename.await? {
10014 Some(range)
10015 } else {
10016 this.update(&mut cx, |this, cx| {
10017 let buffer = this.buffer.read(cx).snapshot(cx);
10018 let mut buffer_highlights = this
10019 .document_highlights_for_position(selection.head(), &buffer)
10020 .filter(|highlight| {
10021 highlight.start.excerpt_id == selection.head().excerpt_id
10022 && highlight.end.excerpt_id == selection.head().excerpt_id
10023 });
10024 buffer_highlights
10025 .next()
10026 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10027 })?
10028 };
10029 if let Some(rename_range) = rename_range {
10030 this.update(&mut cx, |this, cx| {
10031 let snapshot = cursor_buffer.read(cx).snapshot();
10032 let rename_buffer_range = rename_range.to_offset(&snapshot);
10033 let cursor_offset_in_rename_range =
10034 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10035 let cursor_offset_in_rename_range_end =
10036 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10037
10038 this.take_rename(false, cx);
10039 let buffer = this.buffer.read(cx).read(cx);
10040 let cursor_offset = selection.head().to_offset(&buffer);
10041 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10042 let rename_end = rename_start + rename_buffer_range.len();
10043 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10044 let mut old_highlight_id = None;
10045 let old_name: Arc<str> = buffer
10046 .chunks(rename_start..rename_end, true)
10047 .map(|chunk| {
10048 if old_highlight_id.is_none() {
10049 old_highlight_id = chunk.syntax_highlight_id;
10050 }
10051 chunk.text
10052 })
10053 .collect::<String>()
10054 .into();
10055
10056 drop(buffer);
10057
10058 // Position the selection in the rename editor so that it matches the current selection.
10059 this.show_local_selections = false;
10060 let rename_editor = cx.new_view(|cx| {
10061 let mut editor = Editor::single_line(cx);
10062 editor.buffer.update(cx, |buffer, cx| {
10063 buffer.edit([(0..0, old_name.clone())], None, cx)
10064 });
10065 let rename_selection_range = match cursor_offset_in_rename_range
10066 .cmp(&cursor_offset_in_rename_range_end)
10067 {
10068 Ordering::Equal => {
10069 editor.select_all(&SelectAll, cx);
10070 return editor;
10071 }
10072 Ordering::Less => {
10073 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10074 }
10075 Ordering::Greater => {
10076 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10077 }
10078 };
10079 if rename_selection_range.end > old_name.len() {
10080 editor.select_all(&SelectAll, cx);
10081 } else {
10082 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10083 s.select_ranges([rename_selection_range]);
10084 });
10085 }
10086 editor
10087 });
10088 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10089 if e == &EditorEvent::Focused {
10090 cx.emit(EditorEvent::FocusedIn)
10091 }
10092 })
10093 .detach();
10094
10095 let write_highlights =
10096 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10097 let read_highlights =
10098 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10099 let ranges = write_highlights
10100 .iter()
10101 .flat_map(|(_, ranges)| ranges.iter())
10102 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10103 .cloned()
10104 .collect();
10105
10106 this.highlight_text::<Rename>(
10107 ranges,
10108 HighlightStyle {
10109 fade_out: Some(0.6),
10110 ..Default::default()
10111 },
10112 cx,
10113 );
10114 let rename_focus_handle = rename_editor.focus_handle(cx);
10115 cx.focus(&rename_focus_handle);
10116 let block_id = this.insert_blocks(
10117 [BlockProperties {
10118 style: BlockStyle::Flex,
10119 position: range.start,
10120 height: 1,
10121 render: Box::new({
10122 let rename_editor = rename_editor.clone();
10123 move |cx: &mut BlockContext| {
10124 let mut text_style = cx.editor_style.text.clone();
10125 if let Some(highlight_style) = old_highlight_id
10126 .and_then(|h| h.style(&cx.editor_style.syntax))
10127 {
10128 text_style = text_style.highlight(highlight_style);
10129 }
10130 div()
10131 .pl(cx.anchor_x)
10132 .child(EditorElement::new(
10133 &rename_editor,
10134 EditorStyle {
10135 background: cx.theme().system().transparent,
10136 local_player: cx.editor_style.local_player,
10137 text: text_style,
10138 scrollbar_width: cx.editor_style.scrollbar_width,
10139 syntax: cx.editor_style.syntax.clone(),
10140 status: cx.editor_style.status.clone(),
10141 inlay_hints_style: HighlightStyle {
10142 font_weight: Some(FontWeight::BOLD),
10143 ..make_inlay_hints_style(cx)
10144 },
10145 suggestions_style: HighlightStyle {
10146 color: Some(cx.theme().status().predictive),
10147 ..HighlightStyle::default()
10148 },
10149 ..EditorStyle::default()
10150 },
10151 ))
10152 .into_any_element()
10153 }
10154 }),
10155 disposition: BlockDisposition::Below,
10156 priority: 0,
10157 }],
10158 Some(Autoscroll::fit()),
10159 cx,
10160 )[0];
10161 this.pending_rename = Some(RenameState {
10162 range,
10163 old_name,
10164 editor: rename_editor,
10165 block_id,
10166 });
10167 })?;
10168 }
10169
10170 Ok(())
10171 }))
10172 }
10173
10174 pub fn confirm_rename(
10175 &mut self,
10176 _: &ConfirmRename,
10177 cx: &mut ViewContext<Self>,
10178 ) -> Option<Task<Result<()>>> {
10179 let rename = self.take_rename(false, cx)?;
10180 let workspace = self.workspace()?;
10181 let (start_buffer, start) = self
10182 .buffer
10183 .read(cx)
10184 .text_anchor_for_position(rename.range.start, cx)?;
10185 let (end_buffer, end) = self
10186 .buffer
10187 .read(cx)
10188 .text_anchor_for_position(rename.range.end, cx)?;
10189 if start_buffer != end_buffer {
10190 return None;
10191 }
10192
10193 let buffer = start_buffer;
10194 let range = start..end;
10195 let old_name = rename.old_name;
10196 let new_name = rename.editor.read(cx).text(cx);
10197
10198 let rename = workspace
10199 .read(cx)
10200 .project()
10201 .clone()
10202 .update(cx, |project, cx| {
10203 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10204 });
10205 let workspace = workspace.downgrade();
10206
10207 Some(cx.spawn(|editor, mut cx| async move {
10208 let project_transaction = rename.await?;
10209 Self::open_project_transaction(
10210 &editor,
10211 workspace,
10212 project_transaction,
10213 format!("Rename: {} → {}", old_name, new_name),
10214 cx.clone(),
10215 )
10216 .await?;
10217
10218 editor.update(&mut cx, |editor, cx| {
10219 editor.refresh_document_highlights(cx);
10220 })?;
10221 Ok(())
10222 }))
10223 }
10224
10225 fn take_rename(
10226 &mut self,
10227 moving_cursor: bool,
10228 cx: &mut ViewContext<Self>,
10229 ) -> Option<RenameState> {
10230 let rename = self.pending_rename.take()?;
10231 if rename.editor.focus_handle(cx).is_focused(cx) {
10232 cx.focus(&self.focus_handle);
10233 }
10234
10235 self.remove_blocks(
10236 [rename.block_id].into_iter().collect(),
10237 Some(Autoscroll::fit()),
10238 cx,
10239 );
10240 self.clear_highlights::<Rename>(cx);
10241 self.show_local_selections = true;
10242
10243 if moving_cursor {
10244 let rename_editor = rename.editor.read(cx);
10245 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10246
10247 // Update the selection to match the position of the selection inside
10248 // the rename editor.
10249 let snapshot = self.buffer.read(cx).read(cx);
10250 let rename_range = rename.range.to_offset(&snapshot);
10251 let cursor_in_editor = snapshot
10252 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10253 .min(rename_range.end);
10254 drop(snapshot);
10255
10256 self.change_selections(None, cx, |s| {
10257 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10258 });
10259 } else {
10260 self.refresh_document_highlights(cx);
10261 }
10262
10263 Some(rename)
10264 }
10265
10266 pub fn pending_rename(&self) -> Option<&RenameState> {
10267 self.pending_rename.as_ref()
10268 }
10269
10270 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10271 let project = match &self.project {
10272 Some(project) => project.clone(),
10273 None => return None,
10274 };
10275
10276 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10277 }
10278
10279 fn perform_format(
10280 &mut self,
10281 project: Model<Project>,
10282 trigger: FormatTrigger,
10283 cx: &mut ViewContext<Self>,
10284 ) -> Task<Result<()>> {
10285 let buffer = self.buffer().clone();
10286 let mut buffers = buffer.read(cx).all_buffers();
10287 if trigger == FormatTrigger::Save {
10288 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10289 }
10290
10291 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10292 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10293
10294 cx.spawn(|_, mut cx| async move {
10295 let transaction = futures::select_biased! {
10296 () = timeout => {
10297 log::warn!("timed out waiting for formatting");
10298 None
10299 }
10300 transaction = format.log_err().fuse() => transaction,
10301 };
10302
10303 buffer
10304 .update(&mut cx, |buffer, cx| {
10305 if let Some(transaction) = transaction {
10306 if !buffer.is_singleton() {
10307 buffer.push_transaction(&transaction.0, cx);
10308 }
10309 }
10310
10311 cx.notify();
10312 })
10313 .ok();
10314
10315 Ok(())
10316 })
10317 }
10318
10319 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10320 if let Some(project) = self.project.clone() {
10321 self.buffer.update(cx, |multi_buffer, cx| {
10322 project.update(cx, |project, cx| {
10323 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10324 });
10325 })
10326 }
10327 }
10328
10329 fn cancel_language_server_work(
10330 &mut self,
10331 _: &CancelLanguageServerWork,
10332 cx: &mut ViewContext<Self>,
10333 ) {
10334 if let Some(project) = self.project.clone() {
10335 self.buffer.update(cx, |multi_buffer, cx| {
10336 project.update(cx, |project, cx| {
10337 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10338 });
10339 })
10340 }
10341 }
10342
10343 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10344 cx.show_character_palette();
10345 }
10346
10347 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10348 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10349 let buffer = self.buffer.read(cx).snapshot(cx);
10350 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10351 let is_valid = buffer
10352 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10353 .any(|entry| {
10354 entry.diagnostic.is_primary
10355 && !entry.range.is_empty()
10356 && entry.range.start == primary_range_start
10357 && entry.diagnostic.message == active_diagnostics.primary_message
10358 });
10359
10360 if is_valid != active_diagnostics.is_valid {
10361 active_diagnostics.is_valid = is_valid;
10362 let mut new_styles = HashMap::default();
10363 for (block_id, diagnostic) in &active_diagnostics.blocks {
10364 new_styles.insert(
10365 *block_id,
10366 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10367 );
10368 }
10369 self.display_map.update(cx, |display_map, _cx| {
10370 display_map.replace_blocks(new_styles)
10371 });
10372 }
10373 }
10374 }
10375
10376 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10377 self.dismiss_diagnostics(cx);
10378 let snapshot = self.snapshot(cx);
10379 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10380 let buffer = self.buffer.read(cx).snapshot(cx);
10381
10382 let mut primary_range = None;
10383 let mut primary_message = None;
10384 let mut group_end = Point::zero();
10385 let diagnostic_group = buffer
10386 .diagnostic_group::<MultiBufferPoint>(group_id)
10387 .filter_map(|entry| {
10388 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10389 && (entry.range.start.row == entry.range.end.row
10390 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10391 {
10392 return None;
10393 }
10394 if entry.range.end > group_end {
10395 group_end = entry.range.end;
10396 }
10397 if entry.diagnostic.is_primary {
10398 primary_range = Some(entry.range.clone());
10399 primary_message = Some(entry.diagnostic.message.clone());
10400 }
10401 Some(entry)
10402 })
10403 .collect::<Vec<_>>();
10404 let primary_range = primary_range?;
10405 let primary_message = primary_message?;
10406 let primary_range =
10407 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10408
10409 let blocks = display_map
10410 .insert_blocks(
10411 diagnostic_group.iter().map(|entry| {
10412 let diagnostic = entry.diagnostic.clone();
10413 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10414 BlockProperties {
10415 style: BlockStyle::Fixed,
10416 position: buffer.anchor_after(entry.range.start),
10417 height: message_height,
10418 render: diagnostic_block_renderer(diagnostic, None, true, true),
10419 disposition: BlockDisposition::Below,
10420 priority: 0,
10421 }
10422 }),
10423 cx,
10424 )
10425 .into_iter()
10426 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10427 .collect();
10428
10429 Some(ActiveDiagnosticGroup {
10430 primary_range,
10431 primary_message,
10432 group_id,
10433 blocks,
10434 is_valid: true,
10435 })
10436 });
10437 self.active_diagnostics.is_some()
10438 }
10439
10440 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10441 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10442 self.display_map.update(cx, |display_map, cx| {
10443 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10444 });
10445 cx.notify();
10446 }
10447 }
10448
10449 pub fn set_selections_from_remote(
10450 &mut self,
10451 selections: Vec<Selection<Anchor>>,
10452 pending_selection: Option<Selection<Anchor>>,
10453 cx: &mut ViewContext<Self>,
10454 ) {
10455 let old_cursor_position = self.selections.newest_anchor().head();
10456 self.selections.change_with(cx, |s| {
10457 s.select_anchors(selections);
10458 if let Some(pending_selection) = pending_selection {
10459 s.set_pending(pending_selection, SelectMode::Character);
10460 } else {
10461 s.clear_pending();
10462 }
10463 });
10464 self.selections_did_change(false, &old_cursor_position, true, cx);
10465 }
10466
10467 fn push_to_selection_history(&mut self) {
10468 self.selection_history.push(SelectionHistoryEntry {
10469 selections: self.selections.disjoint_anchors(),
10470 select_next_state: self.select_next_state.clone(),
10471 select_prev_state: self.select_prev_state.clone(),
10472 add_selections_state: self.add_selections_state.clone(),
10473 });
10474 }
10475
10476 pub fn transact(
10477 &mut self,
10478 cx: &mut ViewContext<Self>,
10479 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10480 ) -> Option<TransactionId> {
10481 self.start_transaction_at(Instant::now(), cx);
10482 update(self, cx);
10483 self.end_transaction_at(Instant::now(), cx)
10484 }
10485
10486 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10487 self.end_selection(cx);
10488 if let Some(tx_id) = self
10489 .buffer
10490 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10491 {
10492 self.selection_history
10493 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10494 cx.emit(EditorEvent::TransactionBegun {
10495 transaction_id: tx_id,
10496 })
10497 }
10498 }
10499
10500 fn end_transaction_at(
10501 &mut self,
10502 now: Instant,
10503 cx: &mut ViewContext<Self>,
10504 ) -> Option<TransactionId> {
10505 if let Some(transaction_id) = self
10506 .buffer
10507 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10508 {
10509 if let Some((_, end_selections)) =
10510 self.selection_history.transaction_mut(transaction_id)
10511 {
10512 *end_selections = Some(self.selections.disjoint_anchors());
10513 } else {
10514 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10515 }
10516
10517 cx.emit(EditorEvent::Edited { transaction_id });
10518 Some(transaction_id)
10519 } else {
10520 None
10521 }
10522 }
10523
10524 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10525 let mut fold_ranges = Vec::new();
10526
10527 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10528
10529 let selections = self.selections.all_adjusted(cx);
10530 for selection in selections {
10531 let range = selection.range().sorted();
10532 let buffer_start_row = range.start.row;
10533
10534 for row in (0..=range.end.row).rev() {
10535 if let Some((foldable_range, fold_text)) =
10536 display_map.foldable_range(MultiBufferRow(row))
10537 {
10538 if foldable_range.end.row >= buffer_start_row {
10539 fold_ranges.push((foldable_range, fold_text));
10540 if row <= range.start.row {
10541 break;
10542 }
10543 }
10544 }
10545 }
10546 }
10547
10548 self.fold_ranges(fold_ranges, true, cx);
10549 }
10550
10551 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10552 let buffer_row = fold_at.buffer_row;
10553 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10554
10555 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10556 let autoscroll = self
10557 .selections
10558 .all::<Point>(cx)
10559 .iter()
10560 .any(|selection| fold_range.overlaps(&selection.range()));
10561
10562 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10563 }
10564 }
10565
10566 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10568 let buffer = &display_map.buffer_snapshot;
10569 let selections = self.selections.all::<Point>(cx);
10570 let ranges = selections
10571 .iter()
10572 .map(|s| {
10573 let range = s.display_range(&display_map).sorted();
10574 let mut start = range.start.to_point(&display_map);
10575 let mut end = range.end.to_point(&display_map);
10576 start.column = 0;
10577 end.column = buffer.line_len(MultiBufferRow(end.row));
10578 start..end
10579 })
10580 .collect::<Vec<_>>();
10581
10582 self.unfold_ranges(ranges, true, true, cx);
10583 }
10584
10585 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10586 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10587
10588 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10589 ..Point::new(
10590 unfold_at.buffer_row.0,
10591 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10592 );
10593
10594 let autoscroll = self
10595 .selections
10596 .all::<Point>(cx)
10597 .iter()
10598 .any(|selection| selection.range().overlaps(&intersection_range));
10599
10600 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10601 }
10602
10603 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10604 let selections = self.selections.all::<Point>(cx);
10605 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10606 let line_mode = self.selections.line_mode;
10607 let ranges = selections.into_iter().map(|s| {
10608 if line_mode {
10609 let start = Point::new(s.start.row, 0);
10610 let end = Point::new(
10611 s.end.row,
10612 display_map
10613 .buffer_snapshot
10614 .line_len(MultiBufferRow(s.end.row)),
10615 );
10616 (start..end, display_map.fold_placeholder.clone())
10617 } else {
10618 (s.start..s.end, display_map.fold_placeholder.clone())
10619 }
10620 });
10621 self.fold_ranges(ranges, true, cx);
10622 }
10623
10624 pub fn fold_ranges<T: ToOffset + Clone>(
10625 &mut self,
10626 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10627 auto_scroll: bool,
10628 cx: &mut ViewContext<Self>,
10629 ) {
10630 let mut fold_ranges = Vec::new();
10631 let mut buffers_affected = HashMap::default();
10632 let multi_buffer = self.buffer().read(cx);
10633 for (fold_range, fold_text) in ranges {
10634 if let Some((_, buffer, _)) =
10635 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10636 {
10637 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10638 };
10639 fold_ranges.push((fold_range, fold_text));
10640 }
10641
10642 let mut ranges = fold_ranges.into_iter().peekable();
10643 if ranges.peek().is_some() {
10644 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10645
10646 if auto_scroll {
10647 self.request_autoscroll(Autoscroll::fit(), cx);
10648 }
10649
10650 for buffer in buffers_affected.into_values() {
10651 self.sync_expanded_diff_hunks(buffer, cx);
10652 }
10653
10654 cx.notify();
10655
10656 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10657 // Clear diagnostics block when folding a range that contains it.
10658 let snapshot = self.snapshot(cx);
10659 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10660 drop(snapshot);
10661 self.active_diagnostics = Some(active_diagnostics);
10662 self.dismiss_diagnostics(cx);
10663 } else {
10664 self.active_diagnostics = Some(active_diagnostics);
10665 }
10666 }
10667
10668 self.scrollbar_marker_state.dirty = true;
10669 }
10670 }
10671
10672 pub fn unfold_ranges<T: ToOffset + Clone>(
10673 &mut self,
10674 ranges: impl IntoIterator<Item = Range<T>>,
10675 inclusive: bool,
10676 auto_scroll: bool,
10677 cx: &mut ViewContext<Self>,
10678 ) {
10679 let mut unfold_ranges = Vec::new();
10680 let mut buffers_affected = HashMap::default();
10681 let multi_buffer = self.buffer().read(cx);
10682 for range in ranges {
10683 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10684 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10685 };
10686 unfold_ranges.push(range);
10687 }
10688
10689 let mut ranges = unfold_ranges.into_iter().peekable();
10690 if ranges.peek().is_some() {
10691 self.display_map
10692 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10693 if auto_scroll {
10694 self.request_autoscroll(Autoscroll::fit(), cx);
10695 }
10696
10697 for buffer in buffers_affected.into_values() {
10698 self.sync_expanded_diff_hunks(buffer, cx);
10699 }
10700
10701 cx.notify();
10702 self.scrollbar_marker_state.dirty = true;
10703 self.active_indent_guides_state.dirty = true;
10704 }
10705 }
10706
10707 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10708 self.display_map.read(cx).fold_placeholder.clone()
10709 }
10710
10711 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10712 if hovered != self.gutter_hovered {
10713 self.gutter_hovered = hovered;
10714 cx.notify();
10715 }
10716 }
10717
10718 pub fn insert_blocks(
10719 &mut self,
10720 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10721 autoscroll: Option<Autoscroll>,
10722 cx: &mut ViewContext<Self>,
10723 ) -> Vec<CustomBlockId> {
10724 let blocks = self
10725 .display_map
10726 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10727 if let Some(autoscroll) = autoscroll {
10728 self.request_autoscroll(autoscroll, cx);
10729 }
10730 cx.notify();
10731 blocks
10732 }
10733
10734 pub fn resize_blocks(
10735 &mut self,
10736 heights: HashMap<CustomBlockId, u32>,
10737 autoscroll: Option<Autoscroll>,
10738 cx: &mut ViewContext<Self>,
10739 ) {
10740 self.display_map
10741 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10742 if let Some(autoscroll) = autoscroll {
10743 self.request_autoscroll(autoscroll, cx);
10744 }
10745 cx.notify();
10746 }
10747
10748 pub fn replace_blocks(
10749 &mut self,
10750 renderers: HashMap<CustomBlockId, RenderBlock>,
10751 autoscroll: Option<Autoscroll>,
10752 cx: &mut ViewContext<Self>,
10753 ) {
10754 self.display_map
10755 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10756 if let Some(autoscroll) = autoscroll {
10757 self.request_autoscroll(autoscroll, cx);
10758 }
10759 cx.notify();
10760 }
10761
10762 pub fn remove_blocks(
10763 &mut self,
10764 block_ids: HashSet<CustomBlockId>,
10765 autoscroll: Option<Autoscroll>,
10766 cx: &mut ViewContext<Self>,
10767 ) {
10768 self.display_map.update(cx, |display_map, cx| {
10769 display_map.remove_blocks(block_ids, cx)
10770 });
10771 if let Some(autoscroll) = autoscroll {
10772 self.request_autoscroll(autoscroll, cx);
10773 }
10774 cx.notify();
10775 }
10776
10777 pub fn row_for_block(
10778 &self,
10779 block_id: CustomBlockId,
10780 cx: &mut ViewContext<Self>,
10781 ) -> Option<DisplayRow> {
10782 self.display_map
10783 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10784 }
10785
10786 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10787 self.focused_block = Some(focused_block);
10788 }
10789
10790 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10791 self.focused_block.take()
10792 }
10793
10794 pub fn insert_creases(
10795 &mut self,
10796 creases: impl IntoIterator<Item = Crease>,
10797 cx: &mut ViewContext<Self>,
10798 ) -> Vec<CreaseId> {
10799 self.display_map
10800 .update(cx, |map, cx| map.insert_creases(creases, cx))
10801 }
10802
10803 pub fn remove_creases(
10804 &mut self,
10805 ids: impl IntoIterator<Item = CreaseId>,
10806 cx: &mut ViewContext<Self>,
10807 ) {
10808 self.display_map
10809 .update(cx, |map, cx| map.remove_creases(ids, cx));
10810 }
10811
10812 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10813 self.display_map
10814 .update(cx, |map, cx| map.snapshot(cx))
10815 .longest_row()
10816 }
10817
10818 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10819 self.display_map
10820 .update(cx, |map, cx| map.snapshot(cx))
10821 .max_point()
10822 }
10823
10824 pub fn text(&self, cx: &AppContext) -> String {
10825 self.buffer.read(cx).read(cx).text()
10826 }
10827
10828 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10829 let text = self.text(cx);
10830 let text = text.trim();
10831
10832 if text.is_empty() {
10833 return None;
10834 }
10835
10836 Some(text.to_string())
10837 }
10838
10839 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10840 self.transact(cx, |this, cx| {
10841 this.buffer
10842 .read(cx)
10843 .as_singleton()
10844 .expect("you can only call set_text on editors for singleton buffers")
10845 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10846 });
10847 }
10848
10849 pub fn display_text(&self, cx: &mut AppContext) -> String {
10850 self.display_map
10851 .update(cx, |map, cx| map.snapshot(cx))
10852 .text()
10853 }
10854
10855 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10856 let mut wrap_guides = smallvec::smallvec![];
10857
10858 if self.show_wrap_guides == Some(false) {
10859 return wrap_guides;
10860 }
10861
10862 let settings = self.buffer.read(cx).settings_at(0, cx);
10863 if settings.show_wrap_guides {
10864 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10865 wrap_guides.push((soft_wrap as usize, true));
10866 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10867 wrap_guides.push((soft_wrap as usize, true));
10868 }
10869 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10870 }
10871
10872 wrap_guides
10873 }
10874
10875 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10876 let settings = self.buffer.read(cx).settings_at(0, cx);
10877 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10878 match mode {
10879 language_settings::SoftWrap::None => SoftWrap::None,
10880 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10881 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10882 language_settings::SoftWrap::PreferredLineLength => {
10883 SoftWrap::Column(settings.preferred_line_length)
10884 }
10885 language_settings::SoftWrap::Bounded => {
10886 SoftWrap::Bounded(settings.preferred_line_length)
10887 }
10888 }
10889 }
10890
10891 pub fn set_soft_wrap_mode(
10892 &mut self,
10893 mode: language_settings::SoftWrap,
10894 cx: &mut ViewContext<Self>,
10895 ) {
10896 self.soft_wrap_mode_override = Some(mode);
10897 cx.notify();
10898 }
10899
10900 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10901 let rem_size = cx.rem_size();
10902 self.display_map.update(cx, |map, cx| {
10903 map.set_font(
10904 style.text.font(),
10905 style.text.font_size.to_pixels(rem_size),
10906 cx,
10907 )
10908 });
10909 self.style = Some(style);
10910 }
10911
10912 pub fn style(&self) -> Option<&EditorStyle> {
10913 self.style.as_ref()
10914 }
10915
10916 // Called by the element. This method is not designed to be called outside of the editor
10917 // element's layout code because it does not notify when rewrapping is computed synchronously.
10918 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10919 self.display_map
10920 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10921 }
10922
10923 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10924 if self.soft_wrap_mode_override.is_some() {
10925 self.soft_wrap_mode_override.take();
10926 } else {
10927 let soft_wrap = match self.soft_wrap_mode(cx) {
10928 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10929 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10930 language_settings::SoftWrap::PreferLine
10931 }
10932 };
10933 self.soft_wrap_mode_override = Some(soft_wrap);
10934 }
10935 cx.notify();
10936 }
10937
10938 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10939 let Some(workspace) = self.workspace() else {
10940 return;
10941 };
10942 let fs = workspace.read(cx).app_state().fs.clone();
10943 let current_show = TabBarSettings::get_global(cx).show;
10944 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10945 setting.show = Some(!current_show);
10946 });
10947 }
10948
10949 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10950 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10951 self.buffer
10952 .read(cx)
10953 .settings_at(0, cx)
10954 .indent_guides
10955 .enabled
10956 });
10957 self.show_indent_guides = Some(!currently_enabled);
10958 cx.notify();
10959 }
10960
10961 fn should_show_indent_guides(&self) -> Option<bool> {
10962 self.show_indent_guides
10963 }
10964
10965 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10966 let mut editor_settings = EditorSettings::get_global(cx).clone();
10967 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10968 EditorSettings::override_global(editor_settings, cx);
10969 }
10970
10971 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10972 self.use_relative_line_numbers
10973 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10974 }
10975
10976 pub fn toggle_relative_line_numbers(
10977 &mut self,
10978 _: &ToggleRelativeLineNumbers,
10979 cx: &mut ViewContext<Self>,
10980 ) {
10981 let is_relative = self.should_use_relative_line_numbers(cx);
10982 self.set_relative_line_number(Some(!is_relative), cx)
10983 }
10984
10985 pub fn set_relative_line_number(
10986 &mut self,
10987 is_relative: Option<bool>,
10988 cx: &mut ViewContext<Self>,
10989 ) {
10990 self.use_relative_line_numbers = is_relative;
10991 cx.notify();
10992 }
10993
10994 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10995 self.show_gutter = show_gutter;
10996 cx.notify();
10997 }
10998
10999 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11000 self.show_line_numbers = Some(show_line_numbers);
11001 cx.notify();
11002 }
11003
11004 pub fn set_show_git_diff_gutter(
11005 &mut self,
11006 show_git_diff_gutter: bool,
11007 cx: &mut ViewContext<Self>,
11008 ) {
11009 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11010 cx.notify();
11011 }
11012
11013 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11014 self.show_code_actions = Some(show_code_actions);
11015 cx.notify();
11016 }
11017
11018 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11019 self.show_runnables = Some(show_runnables);
11020 cx.notify();
11021 }
11022
11023 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11024 if self.display_map.read(cx).masked != masked {
11025 self.display_map.update(cx, |map, _| map.masked = masked);
11026 }
11027 cx.notify()
11028 }
11029
11030 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11031 self.show_wrap_guides = Some(show_wrap_guides);
11032 cx.notify();
11033 }
11034
11035 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11036 self.show_indent_guides = Some(show_indent_guides);
11037 cx.notify();
11038 }
11039
11040 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11041 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11042 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11043 if let Some(dir) = file.abs_path(cx).parent() {
11044 return Some(dir.to_owned());
11045 }
11046 }
11047
11048 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11049 return Some(project_path.path.to_path_buf());
11050 }
11051 }
11052
11053 None
11054 }
11055
11056 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11057 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11058 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11059 cx.reveal_path(&file.abs_path(cx));
11060 }
11061 }
11062 }
11063
11064 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11065 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11066 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11067 if let Some(path) = file.abs_path(cx).to_str() {
11068 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11069 }
11070 }
11071 }
11072 }
11073
11074 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11075 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11076 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11077 if let Some(path) = file.path().to_str() {
11078 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11079 }
11080 }
11081 }
11082 }
11083
11084 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11085 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11086
11087 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11088 self.start_git_blame(true, cx);
11089 }
11090
11091 cx.notify();
11092 }
11093
11094 pub fn toggle_git_blame_inline(
11095 &mut self,
11096 _: &ToggleGitBlameInline,
11097 cx: &mut ViewContext<Self>,
11098 ) {
11099 self.toggle_git_blame_inline_internal(true, cx);
11100 cx.notify();
11101 }
11102
11103 pub fn git_blame_inline_enabled(&self) -> bool {
11104 self.git_blame_inline_enabled
11105 }
11106
11107 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11108 self.show_selection_menu = self
11109 .show_selection_menu
11110 .map(|show_selections_menu| !show_selections_menu)
11111 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11112
11113 cx.notify();
11114 }
11115
11116 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11117 self.show_selection_menu
11118 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11119 }
11120
11121 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11122 if let Some(project) = self.project.as_ref() {
11123 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11124 return;
11125 };
11126
11127 if buffer.read(cx).file().is_none() {
11128 return;
11129 }
11130
11131 let focused = self.focus_handle(cx).contains_focused(cx);
11132
11133 let project = project.clone();
11134 let blame =
11135 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11136 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11137 self.blame = Some(blame);
11138 }
11139 }
11140
11141 fn toggle_git_blame_inline_internal(
11142 &mut self,
11143 user_triggered: bool,
11144 cx: &mut ViewContext<Self>,
11145 ) {
11146 if self.git_blame_inline_enabled {
11147 self.git_blame_inline_enabled = false;
11148 self.show_git_blame_inline = false;
11149 self.show_git_blame_inline_delay_task.take();
11150 } else {
11151 self.git_blame_inline_enabled = true;
11152 self.start_git_blame_inline(user_triggered, cx);
11153 }
11154
11155 cx.notify();
11156 }
11157
11158 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11159 self.start_git_blame(user_triggered, cx);
11160
11161 if ProjectSettings::get_global(cx)
11162 .git
11163 .inline_blame_delay()
11164 .is_some()
11165 {
11166 self.start_inline_blame_timer(cx);
11167 } else {
11168 self.show_git_blame_inline = true
11169 }
11170 }
11171
11172 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11173 self.blame.as_ref()
11174 }
11175
11176 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11177 self.show_git_blame_gutter && self.has_blame_entries(cx)
11178 }
11179
11180 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11181 self.show_git_blame_inline
11182 && self.focus_handle.is_focused(cx)
11183 && !self.newest_selection_head_on_empty_line(cx)
11184 && self.has_blame_entries(cx)
11185 }
11186
11187 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11188 self.blame()
11189 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11190 }
11191
11192 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11193 let cursor_anchor = self.selections.newest_anchor().head();
11194
11195 let snapshot = self.buffer.read(cx).snapshot(cx);
11196 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11197
11198 snapshot.line_len(buffer_row) == 0
11199 }
11200
11201 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11202 let (path, selection, repo) = maybe!({
11203 let project_handle = self.project.as_ref()?.clone();
11204 let project = project_handle.read(cx);
11205
11206 let selection = self.selections.newest::<Point>(cx);
11207 let selection_range = selection.range();
11208
11209 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11210 (buffer, selection_range.start.row..selection_range.end.row)
11211 } else {
11212 let buffer_ranges = self
11213 .buffer()
11214 .read(cx)
11215 .range_to_buffer_ranges(selection_range, cx);
11216
11217 let (buffer, range, _) = if selection.reversed {
11218 buffer_ranges.first()
11219 } else {
11220 buffer_ranges.last()
11221 }?;
11222
11223 let snapshot = buffer.read(cx).snapshot();
11224 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11225 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11226 (buffer.clone(), selection)
11227 };
11228
11229 let path = buffer
11230 .read(cx)
11231 .file()?
11232 .as_local()?
11233 .path()
11234 .to_str()?
11235 .to_string();
11236 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11237 Some((path, selection, repo))
11238 })
11239 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11240
11241 const REMOTE_NAME: &str = "origin";
11242 let origin_url = repo
11243 .remote_url(REMOTE_NAME)
11244 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11245 let sha = repo
11246 .head_sha()
11247 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11248
11249 let (provider, remote) =
11250 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11251 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11252
11253 Ok(provider.build_permalink(
11254 remote,
11255 BuildPermalinkParams {
11256 sha: &sha,
11257 path: &path,
11258 selection: Some(selection),
11259 },
11260 ))
11261 }
11262
11263 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11264 let permalink = self.get_permalink_to_line(cx);
11265
11266 match permalink {
11267 Ok(permalink) => {
11268 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11269 }
11270 Err(err) => {
11271 let message = format!("Failed to copy permalink: {err}");
11272
11273 Err::<(), anyhow::Error>(err).log_err();
11274
11275 if let Some(workspace) = self.workspace() {
11276 workspace.update(cx, |workspace, cx| {
11277 struct CopyPermalinkToLine;
11278
11279 workspace.show_toast(
11280 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11281 cx,
11282 )
11283 })
11284 }
11285 }
11286 }
11287 }
11288
11289 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11290 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11291 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11292 if let Some(path) = file.path().to_str() {
11293 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11294 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11295 }
11296 }
11297 }
11298 }
11299
11300 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11301 let permalink = self.get_permalink_to_line(cx);
11302
11303 match permalink {
11304 Ok(permalink) => {
11305 cx.open_url(permalink.as_ref());
11306 }
11307 Err(err) => {
11308 let message = format!("Failed to open permalink: {err}");
11309
11310 Err::<(), anyhow::Error>(err).log_err();
11311
11312 if let Some(workspace) = self.workspace() {
11313 workspace.update(cx, |workspace, cx| {
11314 struct OpenPermalinkToLine;
11315
11316 workspace.show_toast(
11317 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11318 cx,
11319 )
11320 })
11321 }
11322 }
11323 }
11324 }
11325
11326 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11327 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11328 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11329 pub fn highlight_rows<T: 'static>(
11330 &mut self,
11331 rows: RangeInclusive<Anchor>,
11332 color: Option<Hsla>,
11333 should_autoscroll: bool,
11334 cx: &mut ViewContext<Self>,
11335 ) {
11336 let snapshot = self.buffer().read(cx).snapshot(cx);
11337 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11338 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11339 highlight
11340 .range
11341 .start()
11342 .cmp(rows.start(), &snapshot)
11343 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11344 });
11345 match (color, existing_highlight_index) {
11346 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11347 ix,
11348 RowHighlight {
11349 index: post_inc(&mut self.highlight_order),
11350 range: rows,
11351 should_autoscroll,
11352 color,
11353 },
11354 ),
11355 (None, Ok(i)) => {
11356 row_highlights.remove(i);
11357 }
11358 }
11359 }
11360
11361 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11362 pub fn clear_row_highlights<T: 'static>(&mut self) {
11363 self.highlighted_rows.remove(&TypeId::of::<T>());
11364 }
11365
11366 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11367 pub fn highlighted_rows<T: 'static>(
11368 &self,
11369 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11370 Some(
11371 self.highlighted_rows
11372 .get(&TypeId::of::<T>())?
11373 .iter()
11374 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11375 )
11376 }
11377
11378 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11379 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11380 /// Allows to ignore certain kinds of highlights.
11381 pub fn highlighted_display_rows(
11382 &mut self,
11383 cx: &mut WindowContext,
11384 ) -> BTreeMap<DisplayRow, Hsla> {
11385 let snapshot = self.snapshot(cx);
11386 let mut used_highlight_orders = HashMap::default();
11387 self.highlighted_rows
11388 .iter()
11389 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11390 .fold(
11391 BTreeMap::<DisplayRow, Hsla>::new(),
11392 |mut unique_rows, highlight| {
11393 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11394 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11395 for row in start_row.0..=end_row.0 {
11396 let used_index =
11397 used_highlight_orders.entry(row).or_insert(highlight.index);
11398 if highlight.index >= *used_index {
11399 *used_index = highlight.index;
11400 match highlight.color {
11401 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11402 None => unique_rows.remove(&DisplayRow(row)),
11403 };
11404 }
11405 }
11406 unique_rows
11407 },
11408 )
11409 }
11410
11411 pub fn highlighted_display_row_for_autoscroll(
11412 &self,
11413 snapshot: &DisplaySnapshot,
11414 ) -> Option<DisplayRow> {
11415 self.highlighted_rows
11416 .values()
11417 .flat_map(|highlighted_rows| highlighted_rows.iter())
11418 .filter_map(|highlight| {
11419 if highlight.color.is_none() || !highlight.should_autoscroll {
11420 return None;
11421 }
11422 Some(highlight.range.start().to_display_point(snapshot).row())
11423 })
11424 .min()
11425 }
11426
11427 pub fn set_search_within_ranges(
11428 &mut self,
11429 ranges: &[Range<Anchor>],
11430 cx: &mut ViewContext<Self>,
11431 ) {
11432 self.highlight_background::<SearchWithinRange>(
11433 ranges,
11434 |colors| colors.editor_document_highlight_read_background,
11435 cx,
11436 )
11437 }
11438
11439 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11440 self.breadcrumb_header = Some(new_header);
11441 }
11442
11443 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11444 self.clear_background_highlights::<SearchWithinRange>(cx);
11445 }
11446
11447 pub fn highlight_background<T: 'static>(
11448 &mut self,
11449 ranges: &[Range<Anchor>],
11450 color_fetcher: fn(&ThemeColors) -> Hsla,
11451 cx: &mut ViewContext<Self>,
11452 ) {
11453 self.background_highlights
11454 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11455 self.scrollbar_marker_state.dirty = true;
11456 cx.notify();
11457 }
11458
11459 pub fn clear_background_highlights<T: 'static>(
11460 &mut self,
11461 cx: &mut ViewContext<Self>,
11462 ) -> Option<BackgroundHighlight> {
11463 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11464 if !text_highlights.1.is_empty() {
11465 self.scrollbar_marker_state.dirty = true;
11466 cx.notify();
11467 }
11468 Some(text_highlights)
11469 }
11470
11471 pub fn highlight_gutter<T: 'static>(
11472 &mut self,
11473 ranges: &[Range<Anchor>],
11474 color_fetcher: fn(&AppContext) -> Hsla,
11475 cx: &mut ViewContext<Self>,
11476 ) {
11477 self.gutter_highlights
11478 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11479 cx.notify();
11480 }
11481
11482 pub fn clear_gutter_highlights<T: 'static>(
11483 &mut self,
11484 cx: &mut ViewContext<Self>,
11485 ) -> Option<GutterHighlight> {
11486 cx.notify();
11487 self.gutter_highlights.remove(&TypeId::of::<T>())
11488 }
11489
11490 #[cfg(feature = "test-support")]
11491 pub fn all_text_background_highlights(
11492 &mut self,
11493 cx: &mut ViewContext<Self>,
11494 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11495 let snapshot = self.snapshot(cx);
11496 let buffer = &snapshot.buffer_snapshot;
11497 let start = buffer.anchor_before(0);
11498 let end = buffer.anchor_after(buffer.len());
11499 let theme = cx.theme().colors();
11500 self.background_highlights_in_range(start..end, &snapshot, theme)
11501 }
11502
11503 #[cfg(feature = "test-support")]
11504 pub fn search_background_highlights(
11505 &mut self,
11506 cx: &mut ViewContext<Self>,
11507 ) -> Vec<Range<Point>> {
11508 let snapshot = self.buffer().read(cx).snapshot(cx);
11509
11510 let highlights = self
11511 .background_highlights
11512 .get(&TypeId::of::<items::BufferSearchHighlights>());
11513
11514 if let Some((_color, ranges)) = highlights {
11515 ranges
11516 .iter()
11517 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11518 .collect_vec()
11519 } else {
11520 vec![]
11521 }
11522 }
11523
11524 fn document_highlights_for_position<'a>(
11525 &'a self,
11526 position: Anchor,
11527 buffer: &'a MultiBufferSnapshot,
11528 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11529 let read_highlights = self
11530 .background_highlights
11531 .get(&TypeId::of::<DocumentHighlightRead>())
11532 .map(|h| &h.1);
11533 let write_highlights = self
11534 .background_highlights
11535 .get(&TypeId::of::<DocumentHighlightWrite>())
11536 .map(|h| &h.1);
11537 let left_position = position.bias_left(buffer);
11538 let right_position = position.bias_right(buffer);
11539 read_highlights
11540 .into_iter()
11541 .chain(write_highlights)
11542 .flat_map(move |ranges| {
11543 let start_ix = match ranges.binary_search_by(|probe| {
11544 let cmp = probe.end.cmp(&left_position, buffer);
11545 if cmp.is_ge() {
11546 Ordering::Greater
11547 } else {
11548 Ordering::Less
11549 }
11550 }) {
11551 Ok(i) | Err(i) => i,
11552 };
11553
11554 ranges[start_ix..]
11555 .iter()
11556 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11557 })
11558 }
11559
11560 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11561 self.background_highlights
11562 .get(&TypeId::of::<T>())
11563 .map_or(false, |(_, highlights)| !highlights.is_empty())
11564 }
11565
11566 pub fn background_highlights_in_range(
11567 &self,
11568 search_range: Range<Anchor>,
11569 display_snapshot: &DisplaySnapshot,
11570 theme: &ThemeColors,
11571 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11572 let mut results = Vec::new();
11573 for (color_fetcher, ranges) in self.background_highlights.values() {
11574 let color = color_fetcher(theme);
11575 let start_ix = match ranges.binary_search_by(|probe| {
11576 let cmp = probe
11577 .end
11578 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11579 if cmp.is_gt() {
11580 Ordering::Greater
11581 } else {
11582 Ordering::Less
11583 }
11584 }) {
11585 Ok(i) | Err(i) => i,
11586 };
11587 for range in &ranges[start_ix..] {
11588 if range
11589 .start
11590 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11591 .is_ge()
11592 {
11593 break;
11594 }
11595
11596 let start = range.start.to_display_point(display_snapshot);
11597 let end = range.end.to_display_point(display_snapshot);
11598 results.push((start..end, color))
11599 }
11600 }
11601 results
11602 }
11603
11604 pub fn background_highlight_row_ranges<T: 'static>(
11605 &self,
11606 search_range: Range<Anchor>,
11607 display_snapshot: &DisplaySnapshot,
11608 count: usize,
11609 ) -> Vec<RangeInclusive<DisplayPoint>> {
11610 let mut results = Vec::new();
11611 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11612 return vec![];
11613 };
11614
11615 let start_ix = match ranges.binary_search_by(|probe| {
11616 let cmp = probe
11617 .end
11618 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11619 if cmp.is_gt() {
11620 Ordering::Greater
11621 } else {
11622 Ordering::Less
11623 }
11624 }) {
11625 Ok(i) | Err(i) => i,
11626 };
11627 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11628 if let (Some(start_display), Some(end_display)) = (start, end) {
11629 results.push(
11630 start_display.to_display_point(display_snapshot)
11631 ..=end_display.to_display_point(display_snapshot),
11632 );
11633 }
11634 };
11635 let mut start_row: Option<Point> = None;
11636 let mut end_row: Option<Point> = None;
11637 if ranges.len() > count {
11638 return Vec::new();
11639 }
11640 for range in &ranges[start_ix..] {
11641 if range
11642 .start
11643 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11644 .is_ge()
11645 {
11646 break;
11647 }
11648 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11649 if let Some(current_row) = &end_row {
11650 if end.row == current_row.row {
11651 continue;
11652 }
11653 }
11654 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11655 if start_row.is_none() {
11656 assert_eq!(end_row, None);
11657 start_row = Some(start);
11658 end_row = Some(end);
11659 continue;
11660 }
11661 if let Some(current_end) = end_row.as_mut() {
11662 if start.row > current_end.row + 1 {
11663 push_region(start_row, end_row);
11664 start_row = Some(start);
11665 end_row = Some(end);
11666 } else {
11667 // Merge two hunks.
11668 *current_end = end;
11669 }
11670 } else {
11671 unreachable!();
11672 }
11673 }
11674 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11675 push_region(start_row, end_row);
11676 results
11677 }
11678
11679 pub fn gutter_highlights_in_range(
11680 &self,
11681 search_range: Range<Anchor>,
11682 display_snapshot: &DisplaySnapshot,
11683 cx: &AppContext,
11684 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11685 let mut results = Vec::new();
11686 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11687 let color = color_fetcher(cx);
11688 let start_ix = match ranges.binary_search_by(|probe| {
11689 let cmp = probe
11690 .end
11691 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11692 if cmp.is_gt() {
11693 Ordering::Greater
11694 } else {
11695 Ordering::Less
11696 }
11697 }) {
11698 Ok(i) | Err(i) => i,
11699 };
11700 for range in &ranges[start_ix..] {
11701 if range
11702 .start
11703 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11704 .is_ge()
11705 {
11706 break;
11707 }
11708
11709 let start = range.start.to_display_point(display_snapshot);
11710 let end = range.end.to_display_point(display_snapshot);
11711 results.push((start..end, color))
11712 }
11713 }
11714 results
11715 }
11716
11717 /// Get the text ranges corresponding to the redaction query
11718 pub fn redacted_ranges(
11719 &self,
11720 search_range: Range<Anchor>,
11721 display_snapshot: &DisplaySnapshot,
11722 cx: &WindowContext,
11723 ) -> Vec<Range<DisplayPoint>> {
11724 display_snapshot
11725 .buffer_snapshot
11726 .redacted_ranges(search_range, |file| {
11727 if let Some(file) = file {
11728 file.is_private()
11729 && EditorSettings::get(
11730 Some(SettingsLocation {
11731 worktree_id: file.worktree_id(cx),
11732 path: file.path().as_ref(),
11733 }),
11734 cx,
11735 )
11736 .redact_private_values
11737 } else {
11738 false
11739 }
11740 })
11741 .map(|range| {
11742 range.start.to_display_point(display_snapshot)
11743 ..range.end.to_display_point(display_snapshot)
11744 })
11745 .collect()
11746 }
11747
11748 pub fn highlight_text<T: 'static>(
11749 &mut self,
11750 ranges: Vec<Range<Anchor>>,
11751 style: HighlightStyle,
11752 cx: &mut ViewContext<Self>,
11753 ) {
11754 self.display_map.update(cx, |map, _| {
11755 map.highlight_text(TypeId::of::<T>(), ranges, style)
11756 });
11757 cx.notify();
11758 }
11759
11760 pub(crate) fn highlight_inlays<T: 'static>(
11761 &mut self,
11762 highlights: Vec<InlayHighlight>,
11763 style: HighlightStyle,
11764 cx: &mut ViewContext<Self>,
11765 ) {
11766 self.display_map.update(cx, |map, _| {
11767 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11768 });
11769 cx.notify();
11770 }
11771
11772 pub fn text_highlights<'a, T: 'static>(
11773 &'a self,
11774 cx: &'a AppContext,
11775 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11776 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11777 }
11778
11779 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11780 let cleared = self
11781 .display_map
11782 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11783 if cleared {
11784 cx.notify();
11785 }
11786 }
11787
11788 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11789 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11790 && self.focus_handle.is_focused(cx)
11791 }
11792
11793 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11794 self.show_cursor_when_unfocused = is_enabled;
11795 cx.notify();
11796 }
11797
11798 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11799 cx.notify();
11800 }
11801
11802 fn on_buffer_event(
11803 &mut self,
11804 multibuffer: Model<MultiBuffer>,
11805 event: &multi_buffer::Event,
11806 cx: &mut ViewContext<Self>,
11807 ) {
11808 match event {
11809 multi_buffer::Event::Edited {
11810 singleton_buffer_edited,
11811 } => {
11812 self.scrollbar_marker_state.dirty = true;
11813 self.active_indent_guides_state.dirty = true;
11814 self.refresh_active_diagnostics(cx);
11815 self.refresh_code_actions(cx);
11816 if self.has_active_inline_completion(cx) {
11817 self.update_visible_inline_completion(cx);
11818 }
11819 cx.emit(EditorEvent::BufferEdited);
11820 cx.emit(SearchEvent::MatchesInvalidated);
11821 if *singleton_buffer_edited {
11822 if let Some(project) = &self.project {
11823 let project = project.read(cx);
11824 #[allow(clippy::mutable_key_type)]
11825 let languages_affected = multibuffer
11826 .read(cx)
11827 .all_buffers()
11828 .into_iter()
11829 .filter_map(|buffer| {
11830 let buffer = buffer.read(cx);
11831 let language = buffer.language()?;
11832 if project.is_local()
11833 && project.language_servers_for_buffer(buffer, cx).count() == 0
11834 {
11835 None
11836 } else {
11837 Some(language)
11838 }
11839 })
11840 .cloned()
11841 .collect::<HashSet<_>>();
11842 if !languages_affected.is_empty() {
11843 self.refresh_inlay_hints(
11844 InlayHintRefreshReason::BufferEdited(languages_affected),
11845 cx,
11846 );
11847 }
11848 }
11849 }
11850
11851 let Some(project) = &self.project else { return };
11852 let telemetry = project.read(cx).client().telemetry().clone();
11853 refresh_linked_ranges(self, cx);
11854 telemetry.log_edit_event("editor");
11855 }
11856 multi_buffer::Event::ExcerptsAdded {
11857 buffer,
11858 predecessor,
11859 excerpts,
11860 } => {
11861 self.tasks_update_task = Some(self.refresh_runnables(cx));
11862 cx.emit(EditorEvent::ExcerptsAdded {
11863 buffer: buffer.clone(),
11864 predecessor: *predecessor,
11865 excerpts: excerpts.clone(),
11866 });
11867 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11868 }
11869 multi_buffer::Event::ExcerptsRemoved { ids } => {
11870 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11871 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11872 }
11873 multi_buffer::Event::ExcerptsEdited { ids } => {
11874 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11875 }
11876 multi_buffer::Event::ExcerptsExpanded { ids } => {
11877 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11878 }
11879 multi_buffer::Event::Reparsed(buffer_id) => {
11880 self.tasks_update_task = Some(self.refresh_runnables(cx));
11881
11882 cx.emit(EditorEvent::Reparsed(*buffer_id));
11883 }
11884 multi_buffer::Event::LanguageChanged(buffer_id) => {
11885 linked_editing_ranges::refresh_linked_ranges(self, cx);
11886 cx.emit(EditorEvent::Reparsed(*buffer_id));
11887 cx.notify();
11888 }
11889 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11890 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11891 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11892 cx.emit(EditorEvent::TitleChanged)
11893 }
11894 multi_buffer::Event::DiffBaseChanged => {
11895 self.scrollbar_marker_state.dirty = true;
11896 cx.emit(EditorEvent::DiffBaseChanged);
11897 cx.notify();
11898 }
11899 multi_buffer::Event::DiffUpdated { buffer } => {
11900 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11901 cx.notify();
11902 }
11903 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11904 multi_buffer::Event::DiagnosticsUpdated => {
11905 self.refresh_active_diagnostics(cx);
11906 self.scrollbar_marker_state.dirty = true;
11907 cx.notify();
11908 }
11909 _ => {}
11910 };
11911 }
11912
11913 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11914 cx.notify();
11915 }
11916
11917 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11918 self.tasks_update_task = Some(self.refresh_runnables(cx));
11919 self.refresh_inline_completion(true, false, cx);
11920 self.refresh_inlay_hints(
11921 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11922 self.selections.newest_anchor().head(),
11923 &self.buffer.read(cx).snapshot(cx),
11924 cx,
11925 )),
11926 cx,
11927 );
11928 let editor_settings = EditorSettings::get_global(cx);
11929 if let Some(cursor_shape) = editor_settings.cursor_shape {
11930 self.cursor_shape = cursor_shape;
11931 }
11932 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11933 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11934
11935 let project_settings = ProjectSettings::get_global(cx);
11936 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11937
11938 if self.mode == EditorMode::Full {
11939 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11940 if self.git_blame_inline_enabled != inline_blame_enabled {
11941 self.toggle_git_blame_inline_internal(false, cx);
11942 }
11943 }
11944
11945 cx.notify();
11946 }
11947
11948 pub fn set_searchable(&mut self, searchable: bool) {
11949 self.searchable = searchable;
11950 }
11951
11952 pub fn searchable(&self) -> bool {
11953 self.searchable
11954 }
11955
11956 fn open_proposed_changes_editor(
11957 &mut self,
11958 _: &OpenProposedChangesEditor,
11959 cx: &mut ViewContext<Self>,
11960 ) {
11961 let Some(workspace) = self.workspace() else {
11962 cx.propagate();
11963 return;
11964 };
11965
11966 let buffer = self.buffer.read(cx);
11967 let mut new_selections_by_buffer = HashMap::default();
11968 for selection in self.selections.all::<usize>(cx) {
11969 for (buffer, mut range, _) in
11970 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11971 {
11972 if selection.reversed {
11973 mem::swap(&mut range.start, &mut range.end);
11974 }
11975 let mut range = range.to_point(buffer.read(cx));
11976 range.start.column = 0;
11977 range.end.column = buffer.read(cx).line_len(range.end.row);
11978 new_selections_by_buffer
11979 .entry(buffer)
11980 .or_insert(Vec::new())
11981 .push(range)
11982 }
11983 }
11984
11985 let proposed_changes_buffers = new_selections_by_buffer
11986 .into_iter()
11987 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
11988 .collect::<Vec<_>>();
11989 let proposed_changes_editor = cx.new_view(|cx| {
11990 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
11991 });
11992
11993 cx.window_context().defer(move |cx| {
11994 workspace.update(cx, |workspace, cx| {
11995 workspace.active_pane().update(cx, |pane, cx| {
11996 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
11997 });
11998 });
11999 });
12000 }
12001
12002 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12003 self.open_excerpts_common(true, cx)
12004 }
12005
12006 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12007 self.open_excerpts_common(false, cx)
12008 }
12009
12010 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12011 let buffer = self.buffer.read(cx);
12012 if buffer.is_singleton() {
12013 cx.propagate();
12014 return;
12015 }
12016
12017 let Some(workspace) = self.workspace() else {
12018 cx.propagate();
12019 return;
12020 };
12021
12022 let mut new_selections_by_buffer = HashMap::default();
12023 for selection in self.selections.all::<usize>(cx) {
12024 for (buffer, mut range, _) in
12025 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12026 {
12027 if selection.reversed {
12028 mem::swap(&mut range.start, &mut range.end);
12029 }
12030 new_selections_by_buffer
12031 .entry(buffer)
12032 .or_insert(Vec::new())
12033 .push(range)
12034 }
12035 }
12036
12037 // We defer the pane interaction because we ourselves are a workspace item
12038 // and activating a new item causes the pane to call a method on us reentrantly,
12039 // which panics if we're on the stack.
12040 cx.window_context().defer(move |cx| {
12041 workspace.update(cx, |workspace, cx| {
12042 let pane = if split {
12043 workspace.adjacent_pane(cx)
12044 } else {
12045 workspace.active_pane().clone()
12046 };
12047
12048 for (buffer, ranges) in new_selections_by_buffer {
12049 let editor =
12050 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12051 editor.update(cx, |editor, cx| {
12052 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12053 s.select_ranges(ranges);
12054 });
12055 });
12056 }
12057 })
12058 });
12059 }
12060
12061 fn jump(
12062 &mut self,
12063 path: ProjectPath,
12064 position: Point,
12065 anchor: language::Anchor,
12066 offset_from_top: u32,
12067 cx: &mut ViewContext<Self>,
12068 ) {
12069 let workspace = self.workspace();
12070 cx.spawn(|_, mut cx| async move {
12071 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12072 let editor = workspace.update(&mut cx, |workspace, cx| {
12073 // Reset the preview item id before opening the new item
12074 workspace.active_pane().update(cx, |pane, cx| {
12075 pane.set_preview_item_id(None, cx);
12076 });
12077 workspace.open_path_preview(path, None, true, true, cx)
12078 })?;
12079 let editor = editor
12080 .await?
12081 .downcast::<Editor>()
12082 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12083 .downgrade();
12084 editor.update(&mut cx, |editor, cx| {
12085 let buffer = editor
12086 .buffer()
12087 .read(cx)
12088 .as_singleton()
12089 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12090 let buffer = buffer.read(cx);
12091 let cursor = if buffer.can_resolve(&anchor) {
12092 language::ToPoint::to_point(&anchor, buffer)
12093 } else {
12094 buffer.clip_point(position, Bias::Left)
12095 };
12096
12097 let nav_history = editor.nav_history.take();
12098 editor.change_selections(
12099 Some(Autoscroll::top_relative(offset_from_top as usize)),
12100 cx,
12101 |s| {
12102 s.select_ranges([cursor..cursor]);
12103 },
12104 );
12105 editor.nav_history = nav_history;
12106
12107 anyhow::Ok(())
12108 })??;
12109
12110 anyhow::Ok(())
12111 })
12112 .detach_and_log_err(cx);
12113 }
12114
12115 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12116 let snapshot = self.buffer.read(cx).read(cx);
12117 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12118 Some(
12119 ranges
12120 .iter()
12121 .map(move |range| {
12122 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12123 })
12124 .collect(),
12125 )
12126 }
12127
12128 fn selection_replacement_ranges(
12129 &self,
12130 range: Range<OffsetUtf16>,
12131 cx: &AppContext,
12132 ) -> Vec<Range<OffsetUtf16>> {
12133 let selections = self.selections.all::<OffsetUtf16>(cx);
12134 let newest_selection = selections
12135 .iter()
12136 .max_by_key(|selection| selection.id)
12137 .unwrap();
12138 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12139 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12140 let snapshot = self.buffer.read(cx).read(cx);
12141 selections
12142 .into_iter()
12143 .map(|mut selection| {
12144 selection.start.0 =
12145 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12146 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12147 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12148 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12149 })
12150 .collect()
12151 }
12152
12153 fn report_editor_event(
12154 &self,
12155 operation: &'static str,
12156 file_extension: Option<String>,
12157 cx: &AppContext,
12158 ) {
12159 if cfg!(any(test, feature = "test-support")) {
12160 return;
12161 }
12162
12163 let Some(project) = &self.project else { return };
12164
12165 // If None, we are in a file without an extension
12166 let file = self
12167 .buffer
12168 .read(cx)
12169 .as_singleton()
12170 .and_then(|b| b.read(cx).file());
12171 let file_extension = file_extension.or(file
12172 .as_ref()
12173 .and_then(|file| Path::new(file.file_name(cx)).extension())
12174 .and_then(|e| e.to_str())
12175 .map(|a| a.to_string()));
12176
12177 let vim_mode = cx
12178 .global::<SettingsStore>()
12179 .raw_user_settings()
12180 .get("vim_mode")
12181 == Some(&serde_json::Value::Bool(true));
12182
12183 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12184 == language::language_settings::InlineCompletionProvider::Copilot;
12185 let copilot_enabled_for_language = self
12186 .buffer
12187 .read(cx)
12188 .settings_at(0, cx)
12189 .show_inline_completions;
12190
12191 let telemetry = project.read(cx).client().telemetry().clone();
12192 telemetry.report_editor_event(
12193 file_extension,
12194 vim_mode,
12195 operation,
12196 copilot_enabled,
12197 copilot_enabled_for_language,
12198 )
12199 }
12200
12201 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12202 /// with each line being an array of {text, highlight} objects.
12203 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12204 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12205 return;
12206 };
12207
12208 #[derive(Serialize)]
12209 struct Chunk<'a> {
12210 text: String,
12211 highlight: Option<&'a str>,
12212 }
12213
12214 let snapshot = buffer.read(cx).snapshot();
12215 let range = self
12216 .selected_text_range(false, cx)
12217 .and_then(|selection| {
12218 if selection.range.is_empty() {
12219 None
12220 } else {
12221 Some(selection.range)
12222 }
12223 })
12224 .unwrap_or_else(|| 0..snapshot.len());
12225
12226 let chunks = snapshot.chunks(range, true);
12227 let mut lines = Vec::new();
12228 let mut line: VecDeque<Chunk> = VecDeque::new();
12229
12230 let Some(style) = self.style.as_ref() else {
12231 return;
12232 };
12233
12234 for chunk in chunks {
12235 let highlight = chunk
12236 .syntax_highlight_id
12237 .and_then(|id| id.name(&style.syntax));
12238 let mut chunk_lines = chunk.text.split('\n').peekable();
12239 while let Some(text) = chunk_lines.next() {
12240 let mut merged_with_last_token = false;
12241 if let Some(last_token) = line.back_mut() {
12242 if last_token.highlight == highlight {
12243 last_token.text.push_str(text);
12244 merged_with_last_token = true;
12245 }
12246 }
12247
12248 if !merged_with_last_token {
12249 line.push_back(Chunk {
12250 text: text.into(),
12251 highlight,
12252 });
12253 }
12254
12255 if chunk_lines.peek().is_some() {
12256 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12257 line.pop_front();
12258 }
12259 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12260 line.pop_back();
12261 }
12262
12263 lines.push(mem::take(&mut line));
12264 }
12265 }
12266 }
12267
12268 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12269 return;
12270 };
12271 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12272 }
12273
12274 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12275 &self.inlay_hint_cache
12276 }
12277
12278 pub fn replay_insert_event(
12279 &mut self,
12280 text: &str,
12281 relative_utf16_range: Option<Range<isize>>,
12282 cx: &mut ViewContext<Self>,
12283 ) {
12284 if !self.input_enabled {
12285 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12286 return;
12287 }
12288 if let Some(relative_utf16_range) = relative_utf16_range {
12289 let selections = self.selections.all::<OffsetUtf16>(cx);
12290 self.change_selections(None, cx, |s| {
12291 let new_ranges = selections.into_iter().map(|range| {
12292 let start = OffsetUtf16(
12293 range
12294 .head()
12295 .0
12296 .saturating_add_signed(relative_utf16_range.start),
12297 );
12298 let end = OffsetUtf16(
12299 range
12300 .head()
12301 .0
12302 .saturating_add_signed(relative_utf16_range.end),
12303 );
12304 start..end
12305 });
12306 s.select_ranges(new_ranges);
12307 });
12308 }
12309
12310 self.handle_input(text, cx);
12311 }
12312
12313 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12314 let Some(project) = self.project.as_ref() else {
12315 return false;
12316 };
12317 let project = project.read(cx);
12318
12319 let mut supports = false;
12320 self.buffer().read(cx).for_each_buffer(|buffer| {
12321 if !supports {
12322 supports = project
12323 .language_servers_for_buffer(buffer.read(cx), cx)
12324 .any(
12325 |(_, server)| match server.capabilities().inlay_hint_provider {
12326 Some(lsp::OneOf::Left(enabled)) => enabled,
12327 Some(lsp::OneOf::Right(_)) => true,
12328 None => false,
12329 },
12330 )
12331 }
12332 });
12333 supports
12334 }
12335
12336 pub fn focus(&self, cx: &mut WindowContext) {
12337 cx.focus(&self.focus_handle)
12338 }
12339
12340 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12341 self.focus_handle.is_focused(cx)
12342 }
12343
12344 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12345 cx.emit(EditorEvent::Focused);
12346
12347 if let Some(descendant) = self
12348 .last_focused_descendant
12349 .take()
12350 .and_then(|descendant| descendant.upgrade())
12351 {
12352 cx.focus(&descendant);
12353 } else {
12354 if let Some(blame) = self.blame.as_ref() {
12355 blame.update(cx, GitBlame::focus)
12356 }
12357
12358 self.blink_manager.update(cx, BlinkManager::enable);
12359 self.show_cursor_names(cx);
12360 self.buffer.update(cx, |buffer, cx| {
12361 buffer.finalize_last_transaction(cx);
12362 if self.leader_peer_id.is_none() {
12363 buffer.set_active_selections(
12364 &self.selections.disjoint_anchors(),
12365 self.selections.line_mode,
12366 self.cursor_shape,
12367 cx,
12368 );
12369 }
12370 });
12371 }
12372 }
12373
12374 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12375 cx.emit(EditorEvent::FocusedIn)
12376 }
12377
12378 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12379 if event.blurred != self.focus_handle {
12380 self.last_focused_descendant = Some(event.blurred);
12381 }
12382 }
12383
12384 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12385 self.blink_manager.update(cx, BlinkManager::disable);
12386 self.buffer
12387 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12388
12389 if let Some(blame) = self.blame.as_ref() {
12390 blame.update(cx, GitBlame::blur)
12391 }
12392 if !self.hover_state.focused(cx) {
12393 hide_hover(self, cx);
12394 }
12395
12396 self.hide_context_menu(cx);
12397 cx.emit(EditorEvent::Blurred);
12398 cx.notify();
12399 }
12400
12401 pub fn register_action<A: Action>(
12402 &mut self,
12403 listener: impl Fn(&A, &mut WindowContext) + 'static,
12404 ) -> Subscription {
12405 let id = self.next_editor_action_id.post_inc();
12406 let listener = Arc::new(listener);
12407 self.editor_actions.borrow_mut().insert(
12408 id,
12409 Box::new(move |cx| {
12410 let cx = cx.window_context();
12411 let listener = listener.clone();
12412 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12413 let action = action.downcast_ref().unwrap();
12414 if phase == DispatchPhase::Bubble {
12415 listener(action, cx)
12416 }
12417 })
12418 }),
12419 );
12420
12421 let editor_actions = self.editor_actions.clone();
12422 Subscription::new(move || {
12423 editor_actions.borrow_mut().remove(&id);
12424 })
12425 }
12426
12427 pub fn file_header_size(&self) -> u32 {
12428 self.file_header_size
12429 }
12430
12431 pub fn revert(
12432 &mut self,
12433 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12434 cx: &mut ViewContext<Self>,
12435 ) {
12436 self.buffer().update(cx, |multi_buffer, cx| {
12437 for (buffer_id, changes) in revert_changes {
12438 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12439 buffer.update(cx, |buffer, cx| {
12440 buffer.edit(
12441 changes.into_iter().map(|(range, text)| {
12442 (range, text.to_string().map(Arc::<str>::from))
12443 }),
12444 None,
12445 cx,
12446 );
12447 });
12448 }
12449 }
12450 });
12451 self.change_selections(None, cx, |selections| selections.refresh());
12452 }
12453
12454 pub fn to_pixel_point(
12455 &mut self,
12456 source: multi_buffer::Anchor,
12457 editor_snapshot: &EditorSnapshot,
12458 cx: &mut ViewContext<Self>,
12459 ) -> Option<gpui::Point<Pixels>> {
12460 let source_point = source.to_display_point(editor_snapshot);
12461 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12462 }
12463
12464 pub fn display_to_pixel_point(
12465 &mut self,
12466 source: DisplayPoint,
12467 editor_snapshot: &EditorSnapshot,
12468 cx: &mut ViewContext<Self>,
12469 ) -> Option<gpui::Point<Pixels>> {
12470 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12471 let text_layout_details = self.text_layout_details(cx);
12472 let scroll_top = text_layout_details
12473 .scroll_anchor
12474 .scroll_position(editor_snapshot)
12475 .y;
12476
12477 if source.row().as_f32() < scroll_top.floor() {
12478 return None;
12479 }
12480 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12481 let source_y = line_height * (source.row().as_f32() - scroll_top);
12482 Some(gpui::Point::new(source_x, source_y))
12483 }
12484
12485 pub fn has_active_completions_menu(&self) -> bool {
12486 self.context_menu.read().as_ref().map_or(false, |menu| {
12487 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12488 })
12489 }
12490
12491 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12492 self.addons
12493 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12494 }
12495
12496 pub fn unregister_addon<T: Addon>(&mut self) {
12497 self.addons.remove(&std::any::TypeId::of::<T>());
12498 }
12499
12500 pub fn addon<T: Addon>(&self) -> Option<&T> {
12501 let type_id = std::any::TypeId::of::<T>();
12502 self.addons
12503 .get(&type_id)
12504 .and_then(|item| item.to_any().downcast_ref::<T>())
12505 }
12506}
12507
12508fn hunks_for_selections(
12509 multi_buffer_snapshot: &MultiBufferSnapshot,
12510 selections: &[Selection<Anchor>],
12511) -> Vec<MultiBufferDiffHunk> {
12512 let buffer_rows_for_selections = selections.iter().map(|selection| {
12513 let head = selection.head();
12514 let tail = selection.tail();
12515 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12516 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12517 if start > end {
12518 end..start
12519 } else {
12520 start..end
12521 }
12522 });
12523
12524 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12525}
12526
12527pub fn hunks_for_rows(
12528 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12529 multi_buffer_snapshot: &MultiBufferSnapshot,
12530) -> Vec<MultiBufferDiffHunk> {
12531 let mut hunks = Vec::new();
12532 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12533 HashMap::default();
12534 for selected_multi_buffer_rows in rows {
12535 let query_rows =
12536 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12537 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12538 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12539 // when the caret is just above or just below the deleted hunk.
12540 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12541 let related_to_selection = if allow_adjacent {
12542 hunk.row_range.overlaps(&query_rows)
12543 || hunk.row_range.start == query_rows.end
12544 || hunk.row_range.end == query_rows.start
12545 } else {
12546 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12547 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12548 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12549 || selected_multi_buffer_rows.end == hunk.row_range.start
12550 };
12551 if related_to_selection {
12552 if !processed_buffer_rows
12553 .entry(hunk.buffer_id)
12554 .or_default()
12555 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12556 {
12557 continue;
12558 }
12559 hunks.push(hunk);
12560 }
12561 }
12562 }
12563
12564 hunks
12565}
12566
12567pub trait CollaborationHub {
12568 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12569 fn user_participant_indices<'a>(
12570 &self,
12571 cx: &'a AppContext,
12572 ) -> &'a HashMap<u64, ParticipantIndex>;
12573 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12574}
12575
12576impl CollaborationHub for Model<Project> {
12577 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12578 self.read(cx).collaborators()
12579 }
12580
12581 fn user_participant_indices<'a>(
12582 &self,
12583 cx: &'a AppContext,
12584 ) -> &'a HashMap<u64, ParticipantIndex> {
12585 self.read(cx).user_store().read(cx).participant_indices()
12586 }
12587
12588 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12589 let this = self.read(cx);
12590 let user_ids = this.collaborators().values().map(|c| c.user_id);
12591 this.user_store().read_with(cx, |user_store, cx| {
12592 user_store.participant_names(user_ids, cx)
12593 })
12594 }
12595}
12596
12597pub trait CompletionProvider {
12598 fn completions(
12599 &self,
12600 buffer: &Model<Buffer>,
12601 buffer_position: text::Anchor,
12602 trigger: CompletionContext,
12603 cx: &mut ViewContext<Editor>,
12604 ) -> Task<Result<Vec<Completion>>>;
12605
12606 fn resolve_completions(
12607 &self,
12608 buffer: Model<Buffer>,
12609 completion_indices: Vec<usize>,
12610 completions: Arc<RwLock<Box<[Completion]>>>,
12611 cx: &mut ViewContext<Editor>,
12612 ) -> Task<Result<bool>>;
12613
12614 fn apply_additional_edits_for_completion(
12615 &self,
12616 buffer: Model<Buffer>,
12617 completion: Completion,
12618 push_to_history: bool,
12619 cx: &mut ViewContext<Editor>,
12620 ) -> Task<Result<Option<language::Transaction>>>;
12621
12622 fn is_completion_trigger(
12623 &self,
12624 buffer: &Model<Buffer>,
12625 position: language::Anchor,
12626 text: &str,
12627 trigger_in_words: bool,
12628 cx: &mut ViewContext<Editor>,
12629 ) -> bool;
12630
12631 fn sort_completions(&self) -> bool {
12632 true
12633 }
12634}
12635
12636pub trait CodeActionProvider {
12637 fn code_actions(
12638 &self,
12639 buffer: &Model<Buffer>,
12640 range: Range<text::Anchor>,
12641 cx: &mut WindowContext,
12642 ) -> Task<Result<Vec<CodeAction>>>;
12643
12644 fn apply_code_action(
12645 &self,
12646 buffer_handle: Model<Buffer>,
12647 action: CodeAction,
12648 excerpt_id: ExcerptId,
12649 push_to_history: bool,
12650 cx: &mut WindowContext,
12651 ) -> Task<Result<ProjectTransaction>>;
12652}
12653
12654impl CodeActionProvider for Model<Project> {
12655 fn code_actions(
12656 &self,
12657 buffer: &Model<Buffer>,
12658 range: Range<text::Anchor>,
12659 cx: &mut WindowContext,
12660 ) -> Task<Result<Vec<CodeAction>>> {
12661 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12662 }
12663
12664 fn apply_code_action(
12665 &self,
12666 buffer_handle: Model<Buffer>,
12667 action: CodeAction,
12668 _excerpt_id: ExcerptId,
12669 push_to_history: bool,
12670 cx: &mut WindowContext,
12671 ) -> Task<Result<ProjectTransaction>> {
12672 self.update(cx, |project, cx| {
12673 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12674 })
12675 }
12676}
12677
12678fn snippet_completions(
12679 project: &Project,
12680 buffer: &Model<Buffer>,
12681 buffer_position: text::Anchor,
12682 cx: &mut AppContext,
12683) -> Vec<Completion> {
12684 let language = buffer.read(cx).language_at(buffer_position);
12685 let language_name = language.as_ref().map(|language| language.lsp_id());
12686 let snippet_store = project.snippets().read(cx);
12687 let snippets = snippet_store.snippets_for(language_name, cx);
12688
12689 if snippets.is_empty() {
12690 return vec![];
12691 }
12692 let snapshot = buffer.read(cx).text_snapshot();
12693 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12694
12695 let mut lines = chunks.lines();
12696 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12697 return vec![];
12698 };
12699
12700 let scope = language.map(|language| language.default_scope());
12701 let classifier = CharClassifier::new(scope).for_completion(true);
12702 let mut last_word = line_at
12703 .chars()
12704 .rev()
12705 .take_while(|c| classifier.is_word(*c))
12706 .collect::<String>();
12707 last_word = last_word.chars().rev().collect();
12708 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12709 let to_lsp = |point: &text::Anchor| {
12710 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12711 point_to_lsp(end)
12712 };
12713 let lsp_end = to_lsp(&buffer_position);
12714 snippets
12715 .into_iter()
12716 .filter_map(|snippet| {
12717 let matching_prefix = snippet
12718 .prefix
12719 .iter()
12720 .find(|prefix| prefix.starts_with(&last_word))?;
12721 let start = as_offset - last_word.len();
12722 let start = snapshot.anchor_before(start);
12723 let range = start..buffer_position;
12724 let lsp_start = to_lsp(&start);
12725 let lsp_range = lsp::Range {
12726 start: lsp_start,
12727 end: lsp_end,
12728 };
12729 Some(Completion {
12730 old_range: range,
12731 new_text: snippet.body.clone(),
12732 label: CodeLabel {
12733 text: matching_prefix.clone(),
12734 runs: vec![],
12735 filter_range: 0..matching_prefix.len(),
12736 },
12737 server_id: LanguageServerId(usize::MAX),
12738 documentation: snippet.description.clone().map(Documentation::SingleLine),
12739 lsp_completion: lsp::CompletionItem {
12740 label: snippet.prefix.first().unwrap().clone(),
12741 kind: Some(CompletionItemKind::SNIPPET),
12742 label_details: snippet.description.as_ref().map(|description| {
12743 lsp::CompletionItemLabelDetails {
12744 detail: Some(description.clone()),
12745 description: None,
12746 }
12747 }),
12748 insert_text_format: Some(InsertTextFormat::SNIPPET),
12749 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12750 lsp::InsertReplaceEdit {
12751 new_text: snippet.body.clone(),
12752 insert: lsp_range,
12753 replace: lsp_range,
12754 },
12755 )),
12756 filter_text: Some(snippet.body.clone()),
12757 sort_text: Some(char::MAX.to_string()),
12758 ..Default::default()
12759 },
12760 confirm: None,
12761 })
12762 })
12763 .collect()
12764}
12765
12766impl CompletionProvider for Model<Project> {
12767 fn completions(
12768 &self,
12769 buffer: &Model<Buffer>,
12770 buffer_position: text::Anchor,
12771 options: CompletionContext,
12772 cx: &mut ViewContext<Editor>,
12773 ) -> Task<Result<Vec<Completion>>> {
12774 self.update(cx, |project, cx| {
12775 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12776 let project_completions = project.completions(buffer, buffer_position, options, cx);
12777 cx.background_executor().spawn(async move {
12778 let mut completions = project_completions.await?;
12779 //let snippets = snippets.into_iter().;
12780 completions.extend(snippets);
12781 Ok(completions)
12782 })
12783 })
12784 }
12785
12786 fn resolve_completions(
12787 &self,
12788 buffer: Model<Buffer>,
12789 completion_indices: Vec<usize>,
12790 completions: Arc<RwLock<Box<[Completion]>>>,
12791 cx: &mut ViewContext<Editor>,
12792 ) -> Task<Result<bool>> {
12793 self.update(cx, |project, cx| {
12794 project.resolve_completions(buffer, completion_indices, completions, cx)
12795 })
12796 }
12797
12798 fn apply_additional_edits_for_completion(
12799 &self,
12800 buffer: Model<Buffer>,
12801 completion: Completion,
12802 push_to_history: bool,
12803 cx: &mut ViewContext<Editor>,
12804 ) -> Task<Result<Option<language::Transaction>>> {
12805 self.update(cx, |project, cx| {
12806 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12807 })
12808 }
12809
12810 fn is_completion_trigger(
12811 &self,
12812 buffer: &Model<Buffer>,
12813 position: language::Anchor,
12814 text: &str,
12815 trigger_in_words: bool,
12816 cx: &mut ViewContext<Editor>,
12817 ) -> bool {
12818 if !EditorSettings::get_global(cx).show_completions_on_input {
12819 return false;
12820 }
12821
12822 let mut chars = text.chars();
12823 let char = if let Some(char) = chars.next() {
12824 char
12825 } else {
12826 return false;
12827 };
12828 if chars.next().is_some() {
12829 return false;
12830 }
12831
12832 let buffer = buffer.read(cx);
12833 let classifier = buffer
12834 .snapshot()
12835 .char_classifier_at(position)
12836 .for_completion(true);
12837 if trigger_in_words && classifier.is_word(char) {
12838 return true;
12839 }
12840
12841 buffer
12842 .completion_triggers()
12843 .iter()
12844 .any(|string| string == text)
12845 }
12846}
12847
12848fn inlay_hint_settings(
12849 location: Anchor,
12850 snapshot: &MultiBufferSnapshot,
12851 cx: &mut ViewContext<'_, Editor>,
12852) -> InlayHintSettings {
12853 let file = snapshot.file_at(location);
12854 let language = snapshot.language_at(location);
12855 let settings = all_language_settings(file, cx);
12856 settings
12857 .language(language.map(|l| l.name()).as_ref())
12858 .inlay_hints
12859}
12860
12861fn consume_contiguous_rows(
12862 contiguous_row_selections: &mut Vec<Selection<Point>>,
12863 selection: &Selection<Point>,
12864 display_map: &DisplaySnapshot,
12865 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12866) -> (MultiBufferRow, MultiBufferRow) {
12867 contiguous_row_selections.push(selection.clone());
12868 let start_row = MultiBufferRow(selection.start.row);
12869 let mut end_row = ending_row(selection, display_map);
12870
12871 while let Some(next_selection) = selections.peek() {
12872 if next_selection.start.row <= end_row.0 {
12873 end_row = ending_row(next_selection, display_map);
12874 contiguous_row_selections.push(selections.next().unwrap().clone());
12875 } else {
12876 break;
12877 }
12878 }
12879 (start_row, end_row)
12880}
12881
12882fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12883 if next_selection.end.column > 0 || next_selection.is_empty() {
12884 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12885 } else {
12886 MultiBufferRow(next_selection.end.row)
12887 }
12888}
12889
12890impl EditorSnapshot {
12891 pub fn remote_selections_in_range<'a>(
12892 &'a self,
12893 range: &'a Range<Anchor>,
12894 collaboration_hub: &dyn CollaborationHub,
12895 cx: &'a AppContext,
12896 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12897 let participant_names = collaboration_hub.user_names(cx);
12898 let participant_indices = collaboration_hub.user_participant_indices(cx);
12899 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12900 let collaborators_by_replica_id = collaborators_by_peer_id
12901 .iter()
12902 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12903 .collect::<HashMap<_, _>>();
12904 self.buffer_snapshot
12905 .selections_in_range(range, false)
12906 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12907 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12908 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12909 let user_name = participant_names.get(&collaborator.user_id).cloned();
12910 Some(RemoteSelection {
12911 replica_id,
12912 selection,
12913 cursor_shape,
12914 line_mode,
12915 participant_index,
12916 peer_id: collaborator.peer_id,
12917 user_name,
12918 })
12919 })
12920 }
12921
12922 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12923 self.display_snapshot.buffer_snapshot.language_at(position)
12924 }
12925
12926 pub fn is_focused(&self) -> bool {
12927 self.is_focused
12928 }
12929
12930 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12931 self.placeholder_text.as_ref()
12932 }
12933
12934 pub fn scroll_position(&self) -> gpui::Point<f32> {
12935 self.scroll_anchor.scroll_position(&self.display_snapshot)
12936 }
12937
12938 fn gutter_dimensions(
12939 &self,
12940 font_id: FontId,
12941 font_size: Pixels,
12942 em_width: Pixels,
12943 max_line_number_width: Pixels,
12944 cx: &AppContext,
12945 ) -> GutterDimensions {
12946 if !self.show_gutter {
12947 return GutterDimensions::default();
12948 }
12949 let descent = cx.text_system().descent(font_id, font_size);
12950
12951 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12952 matches!(
12953 ProjectSettings::get_global(cx).git.git_gutter,
12954 Some(GitGutterSetting::TrackedFiles)
12955 )
12956 });
12957 let gutter_settings = EditorSettings::get_global(cx).gutter;
12958 let show_line_numbers = self
12959 .show_line_numbers
12960 .unwrap_or(gutter_settings.line_numbers);
12961 let line_gutter_width = if show_line_numbers {
12962 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12963 let min_width_for_number_on_gutter = em_width * 4.0;
12964 max_line_number_width.max(min_width_for_number_on_gutter)
12965 } else {
12966 0.0.into()
12967 };
12968
12969 let show_code_actions = self
12970 .show_code_actions
12971 .unwrap_or(gutter_settings.code_actions);
12972
12973 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12974
12975 let git_blame_entries_width = self
12976 .render_git_blame_gutter
12977 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12978
12979 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12980 left_padding += if show_code_actions || show_runnables {
12981 em_width * 3.0
12982 } else if show_git_gutter && show_line_numbers {
12983 em_width * 2.0
12984 } else if show_git_gutter || show_line_numbers {
12985 em_width
12986 } else {
12987 px(0.)
12988 };
12989
12990 let right_padding = if gutter_settings.folds && show_line_numbers {
12991 em_width * 4.0
12992 } else if gutter_settings.folds {
12993 em_width * 3.0
12994 } else if show_line_numbers {
12995 em_width
12996 } else {
12997 px(0.)
12998 };
12999
13000 GutterDimensions {
13001 left_padding,
13002 right_padding,
13003 width: line_gutter_width + left_padding + right_padding,
13004 margin: -descent,
13005 git_blame_entries_width,
13006 }
13007 }
13008
13009 pub fn render_fold_toggle(
13010 &self,
13011 buffer_row: MultiBufferRow,
13012 row_contains_cursor: bool,
13013 editor: View<Editor>,
13014 cx: &mut WindowContext,
13015 ) -> Option<AnyElement> {
13016 let folded = self.is_line_folded(buffer_row);
13017
13018 if let Some(crease) = self
13019 .crease_snapshot
13020 .query_row(buffer_row, &self.buffer_snapshot)
13021 {
13022 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13023 if folded {
13024 editor.update(cx, |editor, cx| {
13025 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13026 });
13027 } else {
13028 editor.update(cx, |editor, cx| {
13029 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13030 });
13031 }
13032 });
13033
13034 Some((crease.render_toggle)(
13035 buffer_row,
13036 folded,
13037 toggle_callback,
13038 cx,
13039 ))
13040 } else if folded
13041 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13042 {
13043 Some(
13044 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13045 .selected(folded)
13046 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13047 if folded {
13048 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13049 } else {
13050 this.fold_at(&FoldAt { buffer_row }, cx);
13051 }
13052 }))
13053 .into_any_element(),
13054 )
13055 } else {
13056 None
13057 }
13058 }
13059
13060 pub fn render_crease_trailer(
13061 &self,
13062 buffer_row: MultiBufferRow,
13063 cx: &mut WindowContext,
13064 ) -> Option<AnyElement> {
13065 let folded = self.is_line_folded(buffer_row);
13066 let crease = self
13067 .crease_snapshot
13068 .query_row(buffer_row, &self.buffer_snapshot)?;
13069 Some((crease.render_trailer)(buffer_row, folded, cx))
13070 }
13071}
13072
13073impl Deref for EditorSnapshot {
13074 type Target = DisplaySnapshot;
13075
13076 fn deref(&self) -> &Self::Target {
13077 &self.display_snapshot
13078 }
13079}
13080
13081#[derive(Clone, Debug, PartialEq, Eq)]
13082pub enum EditorEvent {
13083 InputIgnored {
13084 text: Arc<str>,
13085 },
13086 InputHandled {
13087 utf16_range_to_replace: Option<Range<isize>>,
13088 text: Arc<str>,
13089 },
13090 ExcerptsAdded {
13091 buffer: Model<Buffer>,
13092 predecessor: ExcerptId,
13093 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13094 },
13095 ExcerptsRemoved {
13096 ids: Vec<ExcerptId>,
13097 },
13098 ExcerptsEdited {
13099 ids: Vec<ExcerptId>,
13100 },
13101 ExcerptsExpanded {
13102 ids: Vec<ExcerptId>,
13103 },
13104 BufferEdited,
13105 Edited {
13106 transaction_id: clock::Lamport,
13107 },
13108 Reparsed(BufferId),
13109 Focused,
13110 FocusedIn,
13111 Blurred,
13112 DirtyChanged,
13113 Saved,
13114 TitleChanged,
13115 DiffBaseChanged,
13116 SelectionsChanged {
13117 local: bool,
13118 },
13119 ScrollPositionChanged {
13120 local: bool,
13121 autoscroll: bool,
13122 },
13123 Closed,
13124 TransactionUndone {
13125 transaction_id: clock::Lamport,
13126 },
13127 TransactionBegun {
13128 transaction_id: clock::Lamport,
13129 },
13130}
13131
13132impl EventEmitter<EditorEvent> for Editor {}
13133
13134impl FocusableView for Editor {
13135 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13136 self.focus_handle.clone()
13137 }
13138}
13139
13140impl Render for Editor {
13141 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13142 let settings = ThemeSettings::get_global(cx);
13143
13144 let text_style = match self.mode {
13145 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13146 color: cx.theme().colors().editor_foreground,
13147 font_family: settings.ui_font.family.clone(),
13148 font_features: settings.ui_font.features.clone(),
13149 font_fallbacks: settings.ui_font.fallbacks.clone(),
13150 font_size: rems(0.875).into(),
13151 font_weight: settings.ui_font.weight,
13152 line_height: relative(settings.buffer_line_height.value()),
13153 ..Default::default()
13154 },
13155 EditorMode::Full => TextStyle {
13156 color: cx.theme().colors().editor_foreground,
13157 font_family: settings.buffer_font.family.clone(),
13158 font_features: settings.buffer_font.features.clone(),
13159 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13160 font_size: settings.buffer_font_size(cx).into(),
13161 font_weight: settings.buffer_font.weight,
13162 line_height: relative(settings.buffer_line_height.value()),
13163 ..Default::default()
13164 },
13165 };
13166
13167 let background = match self.mode {
13168 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13169 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13170 EditorMode::Full => cx.theme().colors().editor_background,
13171 };
13172
13173 EditorElement::new(
13174 cx.view(),
13175 EditorStyle {
13176 background,
13177 local_player: cx.theme().players().local(),
13178 text: text_style,
13179 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13180 syntax: cx.theme().syntax().clone(),
13181 status: cx.theme().status().clone(),
13182 inlay_hints_style: make_inlay_hints_style(cx),
13183 suggestions_style: HighlightStyle {
13184 color: Some(cx.theme().status().predictive),
13185 ..HighlightStyle::default()
13186 },
13187 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13188 },
13189 )
13190 }
13191}
13192
13193impl ViewInputHandler for Editor {
13194 fn text_for_range(
13195 &mut self,
13196 range_utf16: Range<usize>,
13197 cx: &mut ViewContext<Self>,
13198 ) -> Option<String> {
13199 Some(
13200 self.buffer
13201 .read(cx)
13202 .read(cx)
13203 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13204 .collect(),
13205 )
13206 }
13207
13208 fn selected_text_range(
13209 &mut self,
13210 ignore_disabled_input: bool,
13211 cx: &mut ViewContext<Self>,
13212 ) -> Option<UTF16Selection> {
13213 // Prevent the IME menu from appearing when holding down an alphabetic key
13214 // while input is disabled.
13215 if !ignore_disabled_input && !self.input_enabled {
13216 return None;
13217 }
13218
13219 let selection = self.selections.newest::<OffsetUtf16>(cx);
13220 let range = selection.range();
13221
13222 Some(UTF16Selection {
13223 range: range.start.0..range.end.0,
13224 reversed: selection.reversed,
13225 })
13226 }
13227
13228 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13229 let snapshot = self.buffer.read(cx).read(cx);
13230 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13231 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13232 }
13233
13234 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13235 self.clear_highlights::<InputComposition>(cx);
13236 self.ime_transaction.take();
13237 }
13238
13239 fn replace_text_in_range(
13240 &mut self,
13241 range_utf16: Option<Range<usize>>,
13242 text: &str,
13243 cx: &mut ViewContext<Self>,
13244 ) {
13245 if !self.input_enabled {
13246 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13247 return;
13248 }
13249
13250 self.transact(cx, |this, cx| {
13251 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13252 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13253 Some(this.selection_replacement_ranges(range_utf16, cx))
13254 } else {
13255 this.marked_text_ranges(cx)
13256 };
13257
13258 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13259 let newest_selection_id = this.selections.newest_anchor().id;
13260 this.selections
13261 .all::<OffsetUtf16>(cx)
13262 .iter()
13263 .zip(ranges_to_replace.iter())
13264 .find_map(|(selection, range)| {
13265 if selection.id == newest_selection_id {
13266 Some(
13267 (range.start.0 as isize - selection.head().0 as isize)
13268 ..(range.end.0 as isize - selection.head().0 as isize),
13269 )
13270 } else {
13271 None
13272 }
13273 })
13274 });
13275
13276 cx.emit(EditorEvent::InputHandled {
13277 utf16_range_to_replace: range_to_replace,
13278 text: text.into(),
13279 });
13280
13281 if let Some(new_selected_ranges) = new_selected_ranges {
13282 this.change_selections(None, cx, |selections| {
13283 selections.select_ranges(new_selected_ranges)
13284 });
13285 this.backspace(&Default::default(), cx);
13286 }
13287
13288 this.handle_input(text, cx);
13289 });
13290
13291 if let Some(transaction) = self.ime_transaction {
13292 self.buffer.update(cx, |buffer, cx| {
13293 buffer.group_until_transaction(transaction, cx);
13294 });
13295 }
13296
13297 self.unmark_text(cx);
13298 }
13299
13300 fn replace_and_mark_text_in_range(
13301 &mut self,
13302 range_utf16: Option<Range<usize>>,
13303 text: &str,
13304 new_selected_range_utf16: Option<Range<usize>>,
13305 cx: &mut ViewContext<Self>,
13306 ) {
13307 if !self.input_enabled {
13308 return;
13309 }
13310
13311 let transaction = self.transact(cx, |this, cx| {
13312 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13313 let snapshot = this.buffer.read(cx).read(cx);
13314 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13315 for marked_range in &mut marked_ranges {
13316 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13317 marked_range.start.0 += relative_range_utf16.start;
13318 marked_range.start =
13319 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13320 marked_range.end =
13321 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13322 }
13323 }
13324 Some(marked_ranges)
13325 } else if let Some(range_utf16) = range_utf16 {
13326 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13327 Some(this.selection_replacement_ranges(range_utf16, cx))
13328 } else {
13329 None
13330 };
13331
13332 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13333 let newest_selection_id = this.selections.newest_anchor().id;
13334 this.selections
13335 .all::<OffsetUtf16>(cx)
13336 .iter()
13337 .zip(ranges_to_replace.iter())
13338 .find_map(|(selection, range)| {
13339 if selection.id == newest_selection_id {
13340 Some(
13341 (range.start.0 as isize - selection.head().0 as isize)
13342 ..(range.end.0 as isize - selection.head().0 as isize),
13343 )
13344 } else {
13345 None
13346 }
13347 })
13348 });
13349
13350 cx.emit(EditorEvent::InputHandled {
13351 utf16_range_to_replace: range_to_replace,
13352 text: text.into(),
13353 });
13354
13355 if let Some(ranges) = ranges_to_replace {
13356 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13357 }
13358
13359 let marked_ranges = {
13360 let snapshot = this.buffer.read(cx).read(cx);
13361 this.selections
13362 .disjoint_anchors()
13363 .iter()
13364 .map(|selection| {
13365 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13366 })
13367 .collect::<Vec<_>>()
13368 };
13369
13370 if text.is_empty() {
13371 this.unmark_text(cx);
13372 } else {
13373 this.highlight_text::<InputComposition>(
13374 marked_ranges.clone(),
13375 HighlightStyle {
13376 underline: Some(UnderlineStyle {
13377 thickness: px(1.),
13378 color: None,
13379 wavy: false,
13380 }),
13381 ..Default::default()
13382 },
13383 cx,
13384 );
13385 }
13386
13387 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13388 let use_autoclose = this.use_autoclose;
13389 let use_auto_surround = this.use_auto_surround;
13390 this.set_use_autoclose(false);
13391 this.set_use_auto_surround(false);
13392 this.handle_input(text, cx);
13393 this.set_use_autoclose(use_autoclose);
13394 this.set_use_auto_surround(use_auto_surround);
13395
13396 if let Some(new_selected_range) = new_selected_range_utf16 {
13397 let snapshot = this.buffer.read(cx).read(cx);
13398 let new_selected_ranges = marked_ranges
13399 .into_iter()
13400 .map(|marked_range| {
13401 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13402 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13403 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13404 snapshot.clip_offset_utf16(new_start, Bias::Left)
13405 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13406 })
13407 .collect::<Vec<_>>();
13408
13409 drop(snapshot);
13410 this.change_selections(None, cx, |selections| {
13411 selections.select_ranges(new_selected_ranges)
13412 });
13413 }
13414 });
13415
13416 self.ime_transaction = self.ime_transaction.or(transaction);
13417 if let Some(transaction) = self.ime_transaction {
13418 self.buffer.update(cx, |buffer, cx| {
13419 buffer.group_until_transaction(transaction, cx);
13420 });
13421 }
13422
13423 if self.text_highlights::<InputComposition>(cx).is_none() {
13424 self.ime_transaction.take();
13425 }
13426 }
13427
13428 fn bounds_for_range(
13429 &mut self,
13430 range_utf16: Range<usize>,
13431 element_bounds: gpui::Bounds<Pixels>,
13432 cx: &mut ViewContext<Self>,
13433 ) -> Option<gpui::Bounds<Pixels>> {
13434 let text_layout_details = self.text_layout_details(cx);
13435 let style = &text_layout_details.editor_style;
13436 let font_id = cx.text_system().resolve_font(&style.text.font());
13437 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13438 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13439
13440 let em_width = cx
13441 .text_system()
13442 .typographic_bounds(font_id, font_size, 'm')
13443 .unwrap()
13444 .size
13445 .width;
13446
13447 let snapshot = self.snapshot(cx);
13448 let scroll_position = snapshot.scroll_position();
13449 let scroll_left = scroll_position.x * em_width;
13450
13451 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13452 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13453 + self.gutter_dimensions.width;
13454 let y = line_height * (start.row().as_f32() - scroll_position.y);
13455
13456 Some(Bounds {
13457 origin: element_bounds.origin + point(x, y),
13458 size: size(em_width, line_height),
13459 })
13460 }
13461}
13462
13463trait SelectionExt {
13464 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13465 fn spanned_rows(
13466 &self,
13467 include_end_if_at_line_start: bool,
13468 map: &DisplaySnapshot,
13469 ) -> Range<MultiBufferRow>;
13470}
13471
13472impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13473 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13474 let start = self
13475 .start
13476 .to_point(&map.buffer_snapshot)
13477 .to_display_point(map);
13478 let end = self
13479 .end
13480 .to_point(&map.buffer_snapshot)
13481 .to_display_point(map);
13482 if self.reversed {
13483 end..start
13484 } else {
13485 start..end
13486 }
13487 }
13488
13489 fn spanned_rows(
13490 &self,
13491 include_end_if_at_line_start: bool,
13492 map: &DisplaySnapshot,
13493 ) -> Range<MultiBufferRow> {
13494 let start = self.start.to_point(&map.buffer_snapshot);
13495 let mut end = self.end.to_point(&map.buffer_snapshot);
13496 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13497 end.row -= 1;
13498 }
13499
13500 let buffer_start = map.prev_line_boundary(start).0;
13501 let buffer_end = map.next_line_boundary(end).0;
13502 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13503 }
13504}
13505
13506impl<T: InvalidationRegion> InvalidationStack<T> {
13507 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13508 where
13509 S: Clone + ToOffset,
13510 {
13511 while let Some(region) = self.last() {
13512 let all_selections_inside_invalidation_ranges =
13513 if selections.len() == region.ranges().len() {
13514 selections
13515 .iter()
13516 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13517 .all(|(selection, invalidation_range)| {
13518 let head = selection.head().to_offset(buffer);
13519 invalidation_range.start <= head && invalidation_range.end >= head
13520 })
13521 } else {
13522 false
13523 };
13524
13525 if all_selections_inside_invalidation_ranges {
13526 break;
13527 } else {
13528 self.pop();
13529 }
13530 }
13531 }
13532}
13533
13534impl<T> Default for InvalidationStack<T> {
13535 fn default() -> Self {
13536 Self(Default::default())
13537 }
13538}
13539
13540impl<T> Deref for InvalidationStack<T> {
13541 type Target = Vec<T>;
13542
13543 fn deref(&self) -> &Self::Target {
13544 &self.0
13545 }
13546}
13547
13548impl<T> DerefMut for InvalidationStack<T> {
13549 fn deref_mut(&mut self) -> &mut Self::Target {
13550 &mut self.0
13551 }
13552}
13553
13554impl InvalidationRegion for SnippetState {
13555 fn ranges(&self) -> &[Range<Anchor>] {
13556 &self.ranges[self.active_index]
13557 }
13558}
13559
13560pub fn diagnostic_block_renderer(
13561 diagnostic: Diagnostic,
13562 max_message_rows: Option<u8>,
13563 allow_closing: bool,
13564 _is_valid: bool,
13565) -> RenderBlock {
13566 let (text_without_backticks, code_ranges) =
13567 highlight_diagnostic_message(&diagnostic, max_message_rows);
13568
13569 Box::new(move |cx: &mut BlockContext| {
13570 let group_id: SharedString = cx.block_id.to_string().into();
13571
13572 let mut text_style = cx.text_style().clone();
13573 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13574 let theme_settings = ThemeSettings::get_global(cx);
13575 text_style.font_family = theme_settings.buffer_font.family.clone();
13576 text_style.font_style = theme_settings.buffer_font.style;
13577 text_style.font_features = theme_settings.buffer_font.features.clone();
13578 text_style.font_weight = theme_settings.buffer_font.weight;
13579
13580 let multi_line_diagnostic = diagnostic.message.contains('\n');
13581
13582 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13583 if multi_line_diagnostic {
13584 v_flex()
13585 } else {
13586 h_flex()
13587 }
13588 .when(allow_closing, |div| {
13589 div.children(diagnostic.is_primary.then(|| {
13590 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13591 .icon_color(Color::Muted)
13592 .size(ButtonSize::Compact)
13593 .style(ButtonStyle::Transparent)
13594 .visible_on_hover(group_id.clone())
13595 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13596 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13597 }))
13598 })
13599 .child(
13600 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13601 .icon_color(Color::Muted)
13602 .size(ButtonSize::Compact)
13603 .style(ButtonStyle::Transparent)
13604 .visible_on_hover(group_id.clone())
13605 .on_click({
13606 let message = diagnostic.message.clone();
13607 move |_click, cx| {
13608 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13609 }
13610 })
13611 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13612 )
13613 };
13614
13615 let icon_size = buttons(&diagnostic, cx.block_id)
13616 .into_any_element()
13617 .layout_as_root(AvailableSpace::min_size(), cx);
13618
13619 h_flex()
13620 .id(cx.block_id)
13621 .group(group_id.clone())
13622 .relative()
13623 .size_full()
13624 .pl(cx.gutter_dimensions.width)
13625 .w(cx.max_width + cx.gutter_dimensions.width)
13626 .child(
13627 div()
13628 .flex()
13629 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13630 .flex_shrink(),
13631 )
13632 .child(buttons(&diagnostic, cx.block_id))
13633 .child(div().flex().flex_shrink_0().child(
13634 StyledText::new(text_without_backticks.clone()).with_highlights(
13635 &text_style,
13636 code_ranges.iter().map(|range| {
13637 (
13638 range.clone(),
13639 HighlightStyle {
13640 font_weight: Some(FontWeight::BOLD),
13641 ..Default::default()
13642 },
13643 )
13644 }),
13645 ),
13646 ))
13647 .into_any_element()
13648 })
13649}
13650
13651pub fn highlight_diagnostic_message(
13652 diagnostic: &Diagnostic,
13653 mut max_message_rows: Option<u8>,
13654) -> (SharedString, Vec<Range<usize>>) {
13655 let mut text_without_backticks = String::new();
13656 let mut code_ranges = Vec::new();
13657
13658 if let Some(source) = &diagnostic.source {
13659 text_without_backticks.push_str(source);
13660 code_ranges.push(0..source.len());
13661 text_without_backticks.push_str(": ");
13662 }
13663
13664 let mut prev_offset = 0;
13665 let mut in_code_block = false;
13666 let has_row_limit = max_message_rows.is_some();
13667 let mut newline_indices = diagnostic
13668 .message
13669 .match_indices('\n')
13670 .filter(|_| has_row_limit)
13671 .map(|(ix, _)| ix)
13672 .fuse()
13673 .peekable();
13674
13675 for (quote_ix, _) in diagnostic
13676 .message
13677 .match_indices('`')
13678 .chain([(diagnostic.message.len(), "")])
13679 {
13680 let mut first_newline_ix = None;
13681 let mut last_newline_ix = None;
13682 while let Some(newline_ix) = newline_indices.peek() {
13683 if *newline_ix < quote_ix {
13684 if first_newline_ix.is_none() {
13685 first_newline_ix = Some(*newline_ix);
13686 }
13687 last_newline_ix = Some(*newline_ix);
13688
13689 if let Some(rows_left) = &mut max_message_rows {
13690 if *rows_left == 0 {
13691 break;
13692 } else {
13693 *rows_left -= 1;
13694 }
13695 }
13696 let _ = newline_indices.next();
13697 } else {
13698 break;
13699 }
13700 }
13701 let prev_len = text_without_backticks.len();
13702 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13703 text_without_backticks.push_str(new_text);
13704 if in_code_block {
13705 code_ranges.push(prev_len..text_without_backticks.len());
13706 }
13707 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13708 in_code_block = !in_code_block;
13709 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13710 text_without_backticks.push_str("...");
13711 break;
13712 }
13713 }
13714
13715 (text_without_backticks.into(), code_ranges)
13716}
13717
13718fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13719 match severity {
13720 DiagnosticSeverity::ERROR => colors.error,
13721 DiagnosticSeverity::WARNING => colors.warning,
13722 DiagnosticSeverity::INFORMATION => colors.info,
13723 DiagnosticSeverity::HINT => colors.info,
13724 _ => colors.ignored,
13725 }
13726}
13727
13728pub fn styled_runs_for_code_label<'a>(
13729 label: &'a CodeLabel,
13730 syntax_theme: &'a theme::SyntaxTheme,
13731) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13732 let fade_out = HighlightStyle {
13733 fade_out: Some(0.35),
13734 ..Default::default()
13735 };
13736
13737 let mut prev_end = label.filter_range.end;
13738 label
13739 .runs
13740 .iter()
13741 .enumerate()
13742 .flat_map(move |(ix, (range, highlight_id))| {
13743 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13744 style
13745 } else {
13746 return Default::default();
13747 };
13748 let mut muted_style = style;
13749 muted_style.highlight(fade_out);
13750
13751 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13752 if range.start >= label.filter_range.end {
13753 if range.start > prev_end {
13754 runs.push((prev_end..range.start, fade_out));
13755 }
13756 runs.push((range.clone(), muted_style));
13757 } else if range.end <= label.filter_range.end {
13758 runs.push((range.clone(), style));
13759 } else {
13760 runs.push((range.start..label.filter_range.end, style));
13761 runs.push((label.filter_range.end..range.end, muted_style));
13762 }
13763 prev_end = cmp::max(prev_end, range.end);
13764
13765 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13766 runs.push((prev_end..label.text.len(), fade_out));
13767 }
13768
13769 runs
13770 })
13771}
13772
13773pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13774 let mut prev_index = 0;
13775 let mut prev_codepoint: Option<char> = None;
13776 text.char_indices()
13777 .chain([(text.len(), '\0')])
13778 .filter_map(move |(index, codepoint)| {
13779 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13780 let is_boundary = index == text.len()
13781 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13782 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13783 if is_boundary {
13784 let chunk = &text[prev_index..index];
13785 prev_index = index;
13786 Some(chunk)
13787 } else {
13788 None
13789 }
13790 })
13791}
13792
13793pub trait RangeToAnchorExt: Sized {
13794 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13795
13796 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13797 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13798 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13799 }
13800}
13801
13802impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13803 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13804 let start_offset = self.start.to_offset(snapshot);
13805 let end_offset = self.end.to_offset(snapshot);
13806 if start_offset == end_offset {
13807 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13808 } else {
13809 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13810 }
13811 }
13812}
13813
13814pub trait RowExt {
13815 fn as_f32(&self) -> f32;
13816
13817 fn next_row(&self) -> Self;
13818
13819 fn previous_row(&self) -> Self;
13820
13821 fn minus(&self, other: Self) -> u32;
13822}
13823
13824impl RowExt for DisplayRow {
13825 fn as_f32(&self) -> f32 {
13826 self.0 as f32
13827 }
13828
13829 fn next_row(&self) -> Self {
13830 Self(self.0 + 1)
13831 }
13832
13833 fn previous_row(&self) -> Self {
13834 Self(self.0.saturating_sub(1))
13835 }
13836
13837 fn minus(&self, other: Self) -> u32 {
13838 self.0 - other.0
13839 }
13840}
13841
13842impl RowExt for MultiBufferRow {
13843 fn as_f32(&self) -> f32 {
13844 self.0 as f32
13845 }
13846
13847 fn next_row(&self) -> Self {
13848 Self(self.0 + 1)
13849 }
13850
13851 fn previous_row(&self) -> Self {
13852 Self(self.0.saturating_sub(1))
13853 }
13854
13855 fn minus(&self, other: Self) -> u32 {
13856 self.0 - other.0
13857 }
13858}
13859
13860trait RowRangeExt {
13861 type Row;
13862
13863 fn len(&self) -> usize;
13864
13865 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13866}
13867
13868impl RowRangeExt for Range<MultiBufferRow> {
13869 type Row = MultiBufferRow;
13870
13871 fn len(&self) -> usize {
13872 (self.end.0 - self.start.0) as usize
13873 }
13874
13875 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13876 (self.start.0..self.end.0).map(MultiBufferRow)
13877 }
13878}
13879
13880impl RowRangeExt for Range<DisplayRow> {
13881 type Row = DisplayRow;
13882
13883 fn len(&self) -> usize {
13884 (self.end.0 - self.start.0) as usize
13885 }
13886
13887 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13888 (self.start.0..self.end.0).map(DisplayRow)
13889 }
13890}
13891
13892fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
13893 if hunk.diff_base_byte_range.is_empty() {
13894 DiffHunkStatus::Added
13895 } else if hunk.row_range.is_empty() {
13896 DiffHunkStatus::Removed
13897 } else {
13898 DiffHunkStatus::Modified
13899 }
13900}
13901
13902/// If select range has more than one line, we
13903/// just point the cursor to range.start.
13904fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13905 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13906 range
13907 } else {
13908 range.start..range.start
13909 }
13910}