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 debounced_delay;
19pub mod display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26mod hover_popover;
27mod hunk_diff;
28mod indent_guides;
29mod inlay_hint_cache;
30mod inline_completion_provider;
31pub mod items;
32mod linked_editing_ranges;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod rust_analyzer_ext;
37pub mod scroll;
38mod selections_collection;
39pub mod tasks;
40
41#[cfg(test)]
42mod editor_tests;
43mod signature_help;
44#[cfg(any(test, feature = "test-support"))]
45pub mod test;
46
47use ::git::diff::{DiffHunk, DiffHunkStatus};
48use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
49pub(crate) use actions::*;
50use aho_corasick::AhoCorasick;
51use anyhow::{anyhow, Context as _, Result};
52use blink_manager::BlinkManager;
53use client::{Collaborator, ParticipantIndex};
54use clock::ReplicaId;
55use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
56use convert_case::{Case, Casing};
57use debounced_delay::DebouncedDelay;
58use display_map::*;
59pub use display_map::{DisplayPoint, FoldPlaceholder};
60pub use editor_settings::{CurrentLineHighlight, EditorSettings};
61pub use editor_settings_controls::*;
62use element::LineWithInvisibles;
63pub use element::{
64 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
65};
66use futures::FutureExt;
67use fuzzy::{StringMatch, StringMatchCandidate};
68use git::blame::GitBlame;
69use git::diff_hunk_to_display;
70use gpui::{
71 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
72 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
73 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
74 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
75 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
76 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
77 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
78 WeakFocusHandle, WeakView, WindowContext,
79};
80use highlight_matching_bracket::refresh_matching_bracket_highlights;
81use hover_popover::{hide_hover, HoverState};
82use hunk_diff::ExpandedHunks;
83pub(crate) use hunk_diff::HoveredHunk;
84use indent_guides::ActiveIndentGuidesState;
85use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
86pub use inline_completion_provider::*;
87pub use items::MAX_TAB_TITLE_LEN;
88use itertools::Itertools;
89use language::{
90 char_kind,
91 language_settings::{self, all_language_settings, InlayHintSettings},
92 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
93 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
94 Point, Selection, SelectionGoal, TransactionId,
95};
96use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
97use linked_editing_ranges::refresh_linked_ranges;
98use task::{ResolvedTask, TaskTemplate, TaskVariables};
99
100use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
101pub use lsp::CompletionContext;
102use lsp::{
103 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
104 LanguageServerId,
105};
106use mouse_context_menu::MouseContextMenu;
107use movement::TextLayoutDetails;
108pub use multi_buffer::{
109 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
110 ToPoint,
111};
112use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
113use ordered_float::OrderedFloat;
114use parking_lot::{Mutex, RwLock};
115use project::project_settings::{GitGutterSetting, ProjectSettings};
116use project::{
117 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
118 ProjectTransaction, TaskSourceKind, WorktreeId,
119};
120use rand::prelude::*;
121use rpc::{proto::*, ErrorExt};
122use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
123use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
124use serde::{Deserialize, Serialize};
125use settings::{update_settings_file, Settings, SettingsStore};
126use smallvec::SmallVec;
127use snippet::Snippet;
128use std::{
129 any::TypeId,
130 borrow::Cow,
131 cell::RefCell,
132 cmp::{self, Ordering, Reverse},
133 mem,
134 num::NonZeroU32,
135 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
136 path::{Path, PathBuf},
137 rc::Rc,
138 sync::Arc,
139 time::{Duration, Instant},
140};
141pub use sum_tree::Bias;
142use sum_tree::TreeMap;
143use text::{BufferId, OffsetUtf16, Rope};
144use theme::{
145 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
146 ThemeColors, ThemeSettings,
147};
148use ui::{
149 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
150 ListItem, Popover, Tooltip,
151};
152use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
153use workspace::item::{ItemHandle, PreviewTabsSettings};
154use workspace::notifications::{DetachAndPromptErr, NotificationId};
155use workspace::{
156 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
157};
158use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
159
160use crate::hover_links::find_url;
161use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
162
163pub const FILE_HEADER_HEIGHT: u32 = 1;
164pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
165pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
166pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
167const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
168const MAX_LINE_LEN: usize = 1024;
169const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
170const MAX_SELECTION_HISTORY_LEN: usize = 1024;
171pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
172#[doc(hidden)]
173pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
174#[doc(hidden)]
175pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
176
177pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
178pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
179
180pub fn render_parsed_markdown(
181 element_id: impl Into<ElementId>,
182 parsed: &language::ParsedMarkdown,
183 editor_style: &EditorStyle,
184 workspace: Option<WeakView<Workspace>>,
185 cx: &mut WindowContext,
186) -> InteractiveText {
187 let code_span_background_color = cx
188 .theme()
189 .colors()
190 .editor_document_highlight_read_background;
191
192 let highlights = gpui::combine_highlights(
193 parsed.highlights.iter().filter_map(|(range, highlight)| {
194 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
195 Some((range.clone(), highlight))
196 }),
197 parsed
198 .regions
199 .iter()
200 .zip(&parsed.region_ranges)
201 .filter_map(|(region, range)| {
202 if region.code {
203 Some((
204 range.clone(),
205 HighlightStyle {
206 background_color: Some(code_span_background_color),
207 ..Default::default()
208 },
209 ))
210 } else {
211 None
212 }
213 }),
214 );
215
216 let mut links = Vec::new();
217 let mut link_ranges = Vec::new();
218 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
219 if let Some(link) = region.link.clone() {
220 links.push(link);
221 link_ranges.push(range.clone());
222 }
223 }
224
225 InteractiveText::new(
226 element_id,
227 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
228 )
229 .on_click(link_ranges, move |clicked_range_ix, cx| {
230 match &links[clicked_range_ix] {
231 markdown::Link::Web { url } => cx.open_url(url),
232 markdown::Link::Path { path } => {
233 if let Some(workspace) = &workspace {
234 _ = workspace.update(cx, |workspace, cx| {
235 workspace.open_abs_path(path.clone(), false, cx).detach();
236 });
237 }
238 }
239 }
240 })
241}
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
244pub(crate) enum InlayId {
245 Suggestion(usize),
246 Hint(usize),
247}
248
249impl InlayId {
250 fn id(&self) -> usize {
251 match self {
252 Self::Suggestion(id) => *id,
253 Self::Hint(id) => *id,
254 }
255 }
256}
257
258enum DiffRowHighlight {}
259enum DocumentHighlightRead {}
260enum DocumentHighlightWrite {}
261enum InputComposition {}
262
263#[derive(Copy, Clone, PartialEq, Eq)]
264pub enum Direction {
265 Prev,
266 Next,
267}
268
269pub fn init_settings(cx: &mut AppContext) {
270 EditorSettings::register(cx);
271}
272
273pub fn init(cx: &mut AppContext) {
274 init_settings(cx);
275
276 workspace::register_project_item::<Editor>(cx);
277 workspace::FollowableViewRegistry::register::<Editor>(cx);
278 workspace::register_serializable_item::<Editor>(cx);
279
280 cx.observe_new_views(
281 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
282 workspace.register_action(Editor::new_file);
283 workspace.register_action(Editor::new_file_in_direction);
284 },
285 )
286 .detach();
287
288 cx.on_action(move |_: &workspace::NewFile, cx| {
289 let app_state = workspace::AppState::global(cx);
290 if let Some(app_state) = app_state.upgrade() {
291 workspace::open_new(app_state, cx, |workspace, cx| {
292 Editor::new_file(workspace, &Default::default(), cx)
293 })
294 .detach();
295 }
296 });
297 cx.on_action(move |_: &workspace::NewWindow, cx| {
298 let app_state = workspace::AppState::global(cx);
299 if let Some(app_state) = app_state.upgrade() {
300 workspace::open_new(app_state, cx, |workspace, cx| {
301 Editor::new_file(workspace, &Default::default(), cx)
302 })
303 .detach();
304 }
305 });
306}
307
308pub struct SearchWithinRange;
309
310trait InvalidationRegion {
311 fn ranges(&self) -> &[Range<Anchor>];
312}
313
314#[derive(Clone, Debug, PartialEq)]
315pub enum SelectPhase {
316 Begin {
317 position: DisplayPoint,
318 add: bool,
319 click_count: usize,
320 },
321 BeginColumnar {
322 position: DisplayPoint,
323 reset: bool,
324 goal_column: u32,
325 },
326 Extend {
327 position: DisplayPoint,
328 click_count: usize,
329 },
330 Update {
331 position: DisplayPoint,
332 goal_column: u32,
333 scroll_delta: gpui::Point<f32>,
334 },
335 End,
336}
337
338#[derive(Clone, Debug)]
339pub enum SelectMode {
340 Character,
341 Word(Range<Anchor>),
342 Line(Range<Anchor>),
343 All,
344}
345
346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
347pub enum EditorMode {
348 SingleLine { auto_width: bool },
349 AutoHeight { max_lines: usize },
350 Full,
351}
352
353#[derive(Clone, Debug)]
354pub enum SoftWrap {
355 None,
356 PreferLine,
357 EditorWidth,
358 Column(u32),
359}
360
361#[derive(Clone)]
362pub struct EditorStyle {
363 pub background: Hsla,
364 pub local_player: PlayerColor,
365 pub text: TextStyle,
366 pub scrollbar_width: Pixels,
367 pub syntax: Arc<SyntaxTheme>,
368 pub status: StatusColors,
369 pub inlay_hints_style: HighlightStyle,
370 pub suggestions_style: HighlightStyle,
371}
372
373impl Default for EditorStyle {
374 fn default() -> Self {
375 Self {
376 background: Hsla::default(),
377 local_player: PlayerColor::default(),
378 text: TextStyle::default(),
379 scrollbar_width: Pixels::default(),
380 syntax: Default::default(),
381 // HACK: Status colors don't have a real default.
382 // We should look into removing the status colors from the editor
383 // style and retrieve them directly from the theme.
384 status: StatusColors::dark(),
385 inlay_hints_style: HighlightStyle::default(),
386 suggestions_style: HighlightStyle::default(),
387 }
388 }
389}
390
391type CompletionId = usize;
392
393#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
394struct EditorActionId(usize);
395
396impl EditorActionId {
397 pub fn post_inc(&mut self) -> Self {
398 let answer = self.0;
399
400 *self = Self(answer + 1);
401
402 Self(answer)
403 }
404}
405
406// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
407// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
408
409type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
410type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
411
412#[derive(Default)]
413struct ScrollbarMarkerState {
414 scrollbar_size: Size<Pixels>,
415 dirty: bool,
416 markers: Arc<[PaintQuad]>,
417 pending_refresh: Option<Task<Result<()>>>,
418}
419
420impl ScrollbarMarkerState {
421 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
422 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
423 }
424}
425
426#[derive(Clone, Debug)]
427struct RunnableTasks {
428 templates: Vec<(TaskSourceKind, TaskTemplate)>,
429 offset: MultiBufferOffset,
430 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
431 column: u32,
432 // Values of all named captures, including those starting with '_'
433 extra_variables: HashMap<String, String>,
434 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
435 context_range: Range<BufferOffset>,
436}
437
438#[derive(Clone)]
439struct ResolvedTasks {
440 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
441 position: Anchor,
442}
443#[derive(Copy, Clone, Debug)]
444struct MultiBufferOffset(usize);
445#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
446struct BufferOffset(usize);
447/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
448///
449/// See the [module level documentation](self) for more information.
450pub struct Editor {
451 focus_handle: FocusHandle,
452 last_focused_descendant: Option<WeakFocusHandle>,
453 /// The text buffer being edited
454 buffer: Model<MultiBuffer>,
455 /// Map of how text in the buffer should be displayed.
456 /// Handles soft wraps, folds, fake inlay text insertions, etc.
457 pub display_map: Model<DisplayMap>,
458 pub selections: SelectionsCollection,
459 pub scroll_manager: ScrollManager,
460 /// When inline assist editors are linked, they all render cursors because
461 /// typing enters text into each of them, even the ones that aren't focused.
462 pub(crate) show_cursor_when_unfocused: bool,
463 columnar_selection_tail: Option<Anchor>,
464 add_selections_state: Option<AddSelectionsState>,
465 select_next_state: Option<SelectNextState>,
466 select_prev_state: Option<SelectNextState>,
467 selection_history: SelectionHistory,
468 autoclose_regions: Vec<AutocloseRegion>,
469 snippet_stack: InvalidationStack<SnippetState>,
470 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
471 ime_transaction: Option<TransactionId>,
472 active_diagnostics: Option<ActiveDiagnosticGroup>,
473 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
474 project: Option<Model<Project>>,
475 completion_provider: Option<Box<dyn CompletionProvider>>,
476 collaboration_hub: Option<Box<dyn CollaborationHub>>,
477 blink_manager: Model<BlinkManager>,
478 show_cursor_names: bool,
479 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
480 pub show_local_selections: bool,
481 mode: EditorMode,
482 show_breadcrumbs: bool,
483 show_gutter: bool,
484 show_line_numbers: Option<bool>,
485 show_git_diff_gutter: Option<bool>,
486 show_code_actions: Option<bool>,
487 show_runnables: Option<bool>,
488 show_wrap_guides: Option<bool>,
489 show_indent_guides: Option<bool>,
490 placeholder_text: Option<Arc<str>>,
491 highlight_order: usize,
492 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
493 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
494 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
495 scrollbar_marker_state: ScrollbarMarkerState,
496 active_indent_guides_state: ActiveIndentGuidesState,
497 nav_history: Option<ItemNavHistory>,
498 context_menu: RwLock<Option<ContextMenu>>,
499 mouse_context_menu: Option<MouseContextMenu>,
500 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
501 signature_help_state: SignatureHelpState,
502 auto_signature_help: Option<bool>,
503 find_all_references_task_sources: Vec<Anchor>,
504 next_completion_id: CompletionId,
505 completion_documentation_pre_resolve_debounce: DebouncedDelay,
506 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
507 code_actions_task: Option<Task<()>>,
508 document_highlights_task: Option<Task<()>>,
509 linked_editing_range_task: Option<Task<Option<()>>>,
510 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
511 pending_rename: Option<RenameState>,
512 searchable: bool,
513 cursor_shape: CursorShape,
514 current_line_highlight: Option<CurrentLineHighlight>,
515 collapse_matches: bool,
516 autoindent_mode: Option<AutoindentMode>,
517 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
518 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
519 input_enabled: bool,
520 use_modal_editing: bool,
521 read_only: bool,
522 leader_peer_id: Option<PeerId>,
523 remote_id: Option<ViewId>,
524 hover_state: HoverState,
525 gutter_hovered: bool,
526 hovered_link_state: Option<HoveredLinkState>,
527 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
528 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
529 show_inline_completions: bool,
530 inlay_hint_cache: InlayHintCache,
531 expanded_hunks: ExpandedHunks,
532 next_inlay_id: usize,
533 _subscriptions: Vec<Subscription>,
534 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
535 gutter_dimensions: GutterDimensions,
536 pub vim_replace_map: HashMap<Range<usize>, String>,
537 style: Option<EditorStyle>,
538 next_editor_action_id: EditorActionId,
539 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
540 use_autoclose: bool,
541 use_auto_surround: bool,
542 auto_replace_emoji_shortcode: bool,
543 show_git_blame_gutter: bool,
544 show_git_blame_inline: bool,
545 show_git_blame_inline_delay_task: Option<Task<()>>,
546 git_blame_inline_enabled: bool,
547 serialize_dirty_buffers: bool,
548 show_selection_menu: Option<bool>,
549 blame: Option<Model<GitBlame>>,
550 blame_subscription: Option<Subscription>,
551 custom_context_menu: Option<
552 Box<
553 dyn 'static
554 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
555 >,
556 >,
557 last_bounds: Option<Bounds<Pixels>>,
558 expect_bounds_change: Option<Bounds<Pixels>>,
559 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
560 tasks_update_task: Option<Task<()>>,
561 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
562 file_header_size: u32,
563 breadcrumb_header: Option<String>,
564 focused_block: Option<FocusedBlock>,
565 next_scroll_position: NextScrollCursorCenterTopBottom,
566 _scroll_cursor_center_top_bottom_task: Task<()>,
567}
568
569#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
570enum NextScrollCursorCenterTopBottom {
571 #[default]
572 Center,
573 Top,
574 Bottom,
575}
576
577impl NextScrollCursorCenterTopBottom {
578 fn next(&self) -> Self {
579 match self {
580 Self::Center => Self::Top,
581 Self::Top => Self::Bottom,
582 Self::Bottom => Self::Center,
583 }
584 }
585}
586
587#[derive(Clone)]
588pub struct EditorSnapshot {
589 pub mode: EditorMode,
590 show_gutter: bool,
591 show_line_numbers: Option<bool>,
592 show_git_diff_gutter: Option<bool>,
593 show_code_actions: Option<bool>,
594 show_runnables: Option<bool>,
595 render_git_blame_gutter: bool,
596 pub display_snapshot: DisplaySnapshot,
597 pub placeholder_text: Option<Arc<str>>,
598 is_focused: bool,
599 scroll_anchor: ScrollAnchor,
600 ongoing_scroll: OngoingScroll,
601 current_line_highlight: CurrentLineHighlight,
602 gutter_hovered: bool,
603}
604
605const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
606
607#[derive(Default, Debug, Clone, Copy)]
608pub struct GutterDimensions {
609 pub left_padding: Pixels,
610 pub right_padding: Pixels,
611 pub width: Pixels,
612 pub margin: Pixels,
613 pub git_blame_entries_width: Option<Pixels>,
614}
615
616impl GutterDimensions {
617 /// The full width of the space taken up by the gutter.
618 pub fn full_width(&self) -> Pixels {
619 self.margin + self.width
620 }
621
622 /// The width of the space reserved for the fold indicators,
623 /// use alongside 'justify_end' and `gutter_width` to
624 /// right align content with the line numbers
625 pub fn fold_area_width(&self) -> Pixels {
626 self.margin + self.right_padding
627 }
628}
629
630#[derive(Debug)]
631pub struct RemoteSelection {
632 pub replica_id: ReplicaId,
633 pub selection: Selection<Anchor>,
634 pub cursor_shape: CursorShape,
635 pub peer_id: PeerId,
636 pub line_mode: bool,
637 pub participant_index: Option<ParticipantIndex>,
638 pub user_name: Option<SharedString>,
639}
640
641#[derive(Clone, Debug)]
642struct SelectionHistoryEntry {
643 selections: Arc<[Selection<Anchor>]>,
644 select_next_state: Option<SelectNextState>,
645 select_prev_state: Option<SelectNextState>,
646 add_selections_state: Option<AddSelectionsState>,
647}
648
649enum SelectionHistoryMode {
650 Normal,
651 Undoing,
652 Redoing,
653}
654
655#[derive(Clone, PartialEq, Eq, Hash)]
656struct HoveredCursor {
657 replica_id: u16,
658 selection_id: usize,
659}
660
661impl Default for SelectionHistoryMode {
662 fn default() -> Self {
663 Self::Normal
664 }
665}
666
667#[derive(Default)]
668struct SelectionHistory {
669 #[allow(clippy::type_complexity)]
670 selections_by_transaction:
671 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
672 mode: SelectionHistoryMode,
673 undo_stack: VecDeque<SelectionHistoryEntry>,
674 redo_stack: VecDeque<SelectionHistoryEntry>,
675}
676
677impl SelectionHistory {
678 fn insert_transaction(
679 &mut self,
680 transaction_id: TransactionId,
681 selections: Arc<[Selection<Anchor>]>,
682 ) {
683 self.selections_by_transaction
684 .insert(transaction_id, (selections, None));
685 }
686
687 #[allow(clippy::type_complexity)]
688 fn transaction(
689 &self,
690 transaction_id: TransactionId,
691 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
692 self.selections_by_transaction.get(&transaction_id)
693 }
694
695 #[allow(clippy::type_complexity)]
696 fn transaction_mut(
697 &mut self,
698 transaction_id: TransactionId,
699 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
700 self.selections_by_transaction.get_mut(&transaction_id)
701 }
702
703 fn push(&mut self, entry: SelectionHistoryEntry) {
704 if !entry.selections.is_empty() {
705 match self.mode {
706 SelectionHistoryMode::Normal => {
707 self.push_undo(entry);
708 self.redo_stack.clear();
709 }
710 SelectionHistoryMode::Undoing => self.push_redo(entry),
711 SelectionHistoryMode::Redoing => self.push_undo(entry),
712 }
713 }
714 }
715
716 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
717 if self
718 .undo_stack
719 .back()
720 .map_or(true, |e| e.selections != entry.selections)
721 {
722 self.undo_stack.push_back(entry);
723 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
724 self.undo_stack.pop_front();
725 }
726 }
727 }
728
729 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
730 if self
731 .redo_stack
732 .back()
733 .map_or(true, |e| e.selections != entry.selections)
734 {
735 self.redo_stack.push_back(entry);
736 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
737 self.redo_stack.pop_front();
738 }
739 }
740 }
741}
742
743struct RowHighlight {
744 index: usize,
745 range: RangeInclusive<Anchor>,
746 color: Option<Hsla>,
747 should_autoscroll: bool,
748}
749
750#[derive(Clone, Debug)]
751struct AddSelectionsState {
752 above: bool,
753 stack: Vec<usize>,
754}
755
756#[derive(Clone)]
757struct SelectNextState {
758 query: AhoCorasick,
759 wordwise: bool,
760 done: bool,
761}
762
763impl std::fmt::Debug for SelectNextState {
764 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
765 f.debug_struct(std::any::type_name::<Self>())
766 .field("wordwise", &self.wordwise)
767 .field("done", &self.done)
768 .finish()
769 }
770}
771
772#[derive(Debug)]
773struct AutocloseRegion {
774 selection_id: usize,
775 range: Range<Anchor>,
776 pair: BracketPair,
777}
778
779#[derive(Debug)]
780struct SnippetState {
781 ranges: Vec<Vec<Range<Anchor>>>,
782 active_index: usize,
783}
784
785#[doc(hidden)]
786pub struct RenameState {
787 pub range: Range<Anchor>,
788 pub old_name: Arc<str>,
789 pub editor: View<Editor>,
790 block_id: CustomBlockId,
791}
792
793struct InvalidationStack<T>(Vec<T>);
794
795struct RegisteredInlineCompletionProvider {
796 provider: Arc<dyn InlineCompletionProviderHandle>,
797 _subscription: Subscription,
798}
799
800enum ContextMenu {
801 Completions(CompletionsMenu),
802 CodeActions(CodeActionsMenu),
803}
804
805impl ContextMenu {
806 fn select_first(
807 &mut self,
808 project: Option<&Model<Project>>,
809 cx: &mut ViewContext<Editor>,
810 ) -> bool {
811 if self.visible() {
812 match self {
813 ContextMenu::Completions(menu) => menu.select_first(project, cx),
814 ContextMenu::CodeActions(menu) => menu.select_first(cx),
815 }
816 true
817 } else {
818 false
819 }
820 }
821
822 fn select_prev(
823 &mut self,
824 project: Option<&Model<Project>>,
825 cx: &mut ViewContext<Editor>,
826 ) -> bool {
827 if self.visible() {
828 match self {
829 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
830 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
831 }
832 true
833 } else {
834 false
835 }
836 }
837
838 fn select_next(
839 &mut self,
840 project: Option<&Model<Project>>,
841 cx: &mut ViewContext<Editor>,
842 ) -> bool {
843 if self.visible() {
844 match self {
845 ContextMenu::Completions(menu) => menu.select_next(project, cx),
846 ContextMenu::CodeActions(menu) => menu.select_next(cx),
847 }
848 true
849 } else {
850 false
851 }
852 }
853
854 fn select_last(
855 &mut self,
856 project: Option<&Model<Project>>,
857 cx: &mut ViewContext<Editor>,
858 ) -> bool {
859 if self.visible() {
860 match self {
861 ContextMenu::Completions(menu) => menu.select_last(project, cx),
862 ContextMenu::CodeActions(menu) => menu.select_last(cx),
863 }
864 true
865 } else {
866 false
867 }
868 }
869
870 fn visible(&self) -> bool {
871 match self {
872 ContextMenu::Completions(menu) => menu.visible(),
873 ContextMenu::CodeActions(menu) => menu.visible(),
874 }
875 }
876
877 fn render(
878 &self,
879 cursor_position: DisplayPoint,
880 style: &EditorStyle,
881 max_height: Pixels,
882 workspace: Option<WeakView<Workspace>>,
883 cx: &mut ViewContext<Editor>,
884 ) -> (ContextMenuOrigin, AnyElement) {
885 match self {
886 ContextMenu::Completions(menu) => (
887 ContextMenuOrigin::EditorPoint(cursor_position),
888 menu.render(style, max_height, workspace, cx),
889 ),
890 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
891 }
892 }
893}
894
895enum ContextMenuOrigin {
896 EditorPoint(DisplayPoint),
897 GutterIndicator(DisplayRow),
898}
899
900#[derive(Clone)]
901struct CompletionsMenu {
902 id: CompletionId,
903 initial_position: Anchor,
904 buffer: Model<Buffer>,
905 completions: Arc<RwLock<Box<[Completion]>>>,
906 match_candidates: Arc<[StringMatchCandidate]>,
907 matches: Arc<[StringMatch]>,
908 selected_item: usize,
909 scroll_handle: UniformListScrollHandle,
910 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
911}
912
913impl CompletionsMenu {
914 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
915 self.selected_item = 0;
916 self.scroll_handle.scroll_to_item(self.selected_item);
917 self.attempt_resolve_selected_completion_documentation(project, cx);
918 cx.notify();
919 }
920
921 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
922 if self.selected_item > 0 {
923 self.selected_item -= 1;
924 } else {
925 self.selected_item = self.matches.len() - 1;
926 }
927 self.scroll_handle.scroll_to_item(self.selected_item);
928 self.attempt_resolve_selected_completion_documentation(project, cx);
929 cx.notify();
930 }
931
932 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
933 if self.selected_item + 1 < self.matches.len() {
934 self.selected_item += 1;
935 } else {
936 self.selected_item = 0;
937 }
938 self.scroll_handle.scroll_to_item(self.selected_item);
939 self.attempt_resolve_selected_completion_documentation(project, cx);
940 cx.notify();
941 }
942
943 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
944 self.selected_item = self.matches.len() - 1;
945 self.scroll_handle.scroll_to_item(self.selected_item);
946 self.attempt_resolve_selected_completion_documentation(project, cx);
947 cx.notify();
948 }
949
950 fn pre_resolve_completion_documentation(
951 buffer: Model<Buffer>,
952 completions: Arc<RwLock<Box<[Completion]>>>,
953 matches: Arc<[StringMatch]>,
954 editor: &Editor,
955 cx: &mut ViewContext<Editor>,
956 ) -> Task<()> {
957 let settings = EditorSettings::get_global(cx);
958 if !settings.show_completion_documentation {
959 return Task::ready(());
960 }
961
962 let Some(provider) = editor.completion_provider.as_ref() else {
963 return Task::ready(());
964 };
965
966 let resolve_task = provider.resolve_completions(
967 buffer,
968 matches.iter().map(|m| m.candidate_id).collect(),
969 completions.clone(),
970 cx,
971 );
972
973 return cx.spawn(move |this, mut cx| async move {
974 if let Some(true) = resolve_task.await.log_err() {
975 this.update(&mut cx, |_, cx| cx.notify()).ok();
976 }
977 });
978 }
979
980 fn attempt_resolve_selected_completion_documentation(
981 &mut self,
982 project: Option<&Model<Project>>,
983 cx: &mut ViewContext<Editor>,
984 ) {
985 let settings = EditorSettings::get_global(cx);
986 if !settings.show_completion_documentation {
987 return;
988 }
989
990 let completion_index = self.matches[self.selected_item].candidate_id;
991 let Some(project) = project else {
992 return;
993 };
994
995 let resolve_task = project.update(cx, |project, cx| {
996 project.resolve_completions(
997 self.buffer.clone(),
998 vec![completion_index],
999 self.completions.clone(),
1000 cx,
1001 )
1002 });
1003
1004 let delay_ms =
1005 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1006 let delay = Duration::from_millis(delay_ms);
1007
1008 self.selected_completion_documentation_resolve_debounce
1009 .lock()
1010 .fire_new(delay, cx, |_, cx| {
1011 cx.spawn(move |this, mut cx| async move {
1012 if let Some(true) = resolve_task.await.log_err() {
1013 this.update(&mut cx, |_, cx| cx.notify()).ok();
1014 }
1015 })
1016 });
1017 }
1018
1019 fn visible(&self) -> bool {
1020 !self.matches.is_empty()
1021 }
1022
1023 fn render(
1024 &self,
1025 style: &EditorStyle,
1026 max_height: Pixels,
1027 workspace: Option<WeakView<Workspace>>,
1028 cx: &mut ViewContext<Editor>,
1029 ) -> AnyElement {
1030 let settings = EditorSettings::get_global(cx);
1031 let show_completion_documentation = settings.show_completion_documentation;
1032
1033 let widest_completion_ix = self
1034 .matches
1035 .iter()
1036 .enumerate()
1037 .max_by_key(|(_, mat)| {
1038 let completions = self.completions.read();
1039 let completion = &completions[mat.candidate_id];
1040 let documentation = &completion.documentation;
1041
1042 let mut len = completion.label.text.chars().count();
1043 if let Some(Documentation::SingleLine(text)) = documentation {
1044 if show_completion_documentation {
1045 len += text.chars().count();
1046 }
1047 }
1048
1049 len
1050 })
1051 .map(|(ix, _)| ix);
1052
1053 let completions = self.completions.clone();
1054 let matches = self.matches.clone();
1055 let selected_item = self.selected_item;
1056 let style = style.clone();
1057
1058 let multiline_docs = if show_completion_documentation {
1059 let mat = &self.matches[selected_item];
1060 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1061 Some(Documentation::MultiLinePlainText(text)) => {
1062 Some(div().child(SharedString::from(text.clone())))
1063 }
1064 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1065 Some(div().child(render_parsed_markdown(
1066 "completions_markdown",
1067 parsed,
1068 &style,
1069 workspace,
1070 cx,
1071 )))
1072 }
1073 _ => None,
1074 };
1075 multiline_docs.map(|div| {
1076 div.id("multiline_docs")
1077 .max_h(max_height)
1078 .flex_1()
1079 .px_1p5()
1080 .py_1()
1081 .min_w(px(260.))
1082 .max_w(px(640.))
1083 .w(px(500.))
1084 .overflow_y_scroll()
1085 .occlude()
1086 })
1087 } else {
1088 None
1089 };
1090
1091 let list = uniform_list(
1092 cx.view().clone(),
1093 "completions",
1094 matches.len(),
1095 move |_editor, range, cx| {
1096 let start_ix = range.start;
1097 let completions_guard = completions.read();
1098
1099 matches[range]
1100 .iter()
1101 .enumerate()
1102 .map(|(ix, mat)| {
1103 let item_ix = start_ix + ix;
1104 let candidate_id = mat.candidate_id;
1105 let completion = &completions_guard[candidate_id];
1106
1107 let documentation = if show_completion_documentation {
1108 &completion.documentation
1109 } else {
1110 &None
1111 };
1112
1113 let highlights = gpui::combine_highlights(
1114 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1115 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1116 |(range, mut highlight)| {
1117 // Ignore font weight for syntax highlighting, as we'll use it
1118 // for fuzzy matches.
1119 highlight.font_weight = None;
1120
1121 if completion.lsp_completion.deprecated.unwrap_or(false) {
1122 highlight.strikethrough = Some(StrikethroughStyle {
1123 thickness: 1.0.into(),
1124 ..Default::default()
1125 });
1126 highlight.color = Some(cx.theme().colors().text_muted);
1127 }
1128
1129 (range, highlight)
1130 },
1131 ),
1132 );
1133 let completion_label = StyledText::new(completion.label.text.clone())
1134 .with_highlights(&style.text, highlights);
1135 let documentation_label =
1136 if let Some(Documentation::SingleLine(text)) = documentation {
1137 if text.trim().is_empty() {
1138 None
1139 } else {
1140 Some(
1141 Label::new(text.clone())
1142 .ml_4()
1143 .size(LabelSize::Small)
1144 .color(Color::Muted),
1145 )
1146 }
1147 } else {
1148 None
1149 };
1150
1151 div().min_w(px(220.)).max_w(px(540.)).child(
1152 ListItem::new(mat.candidate_id)
1153 .inset(true)
1154 .selected(item_ix == selected_item)
1155 .on_click(cx.listener(move |editor, _event, cx| {
1156 cx.stop_propagation();
1157 if let Some(task) = editor.confirm_completion(
1158 &ConfirmCompletion {
1159 item_ix: Some(item_ix),
1160 },
1161 cx,
1162 ) {
1163 task.detach_and_log_err(cx)
1164 }
1165 }))
1166 .child(h_flex().overflow_hidden().child(completion_label))
1167 .end_slot::<Label>(documentation_label),
1168 )
1169 })
1170 .collect()
1171 },
1172 )
1173 .occlude()
1174 .max_h(max_height)
1175 .track_scroll(self.scroll_handle.clone())
1176 .with_width_from_item(widest_completion_ix)
1177 .with_sizing_behavior(ListSizingBehavior::Infer);
1178
1179 Popover::new()
1180 .child(list)
1181 .when_some(multiline_docs, |popover, multiline_docs| {
1182 popover.aside(multiline_docs)
1183 })
1184 .into_any_element()
1185 }
1186
1187 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1188 let mut matches = if let Some(query) = query {
1189 fuzzy::match_strings(
1190 &self.match_candidates,
1191 query,
1192 query.chars().any(|c| c.is_uppercase()),
1193 100,
1194 &Default::default(),
1195 executor,
1196 )
1197 .await
1198 } else {
1199 self.match_candidates
1200 .iter()
1201 .enumerate()
1202 .map(|(candidate_id, candidate)| StringMatch {
1203 candidate_id,
1204 score: Default::default(),
1205 positions: Default::default(),
1206 string: candidate.string.clone(),
1207 })
1208 .collect()
1209 };
1210
1211 // Remove all candidates where the query's start does not match the start of any word in the candidate
1212 if let Some(query) = query {
1213 if let Some(query_start) = query.chars().next() {
1214 matches.retain(|string_match| {
1215 split_words(&string_match.string).any(|word| {
1216 // Check that the first codepoint of the word as lowercase matches the first
1217 // codepoint of the query as lowercase
1218 word.chars()
1219 .flat_map(|codepoint| codepoint.to_lowercase())
1220 .zip(query_start.to_lowercase())
1221 .all(|(word_cp, query_cp)| word_cp == query_cp)
1222 })
1223 });
1224 }
1225 }
1226
1227 let completions = self.completions.read();
1228 matches.sort_unstable_by_key(|mat| {
1229 // We do want to strike a balance here between what the language server tells us
1230 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1231 // `Creat` and there is a local variable called `CreateComponent`).
1232 // So what we do is: we bucket all matches into two buckets
1233 // - Strong matches
1234 // - Weak matches
1235 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1236 // and the Weak matches are the rest.
1237 //
1238 // For the strong matches, we sort by the language-servers score first and for the weak
1239 // matches, we prefer our fuzzy finder first.
1240 //
1241 // The thinking behind that: it's useless to take the sort_text the language-server gives
1242 // us into account when it's obviously a bad match.
1243
1244 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1245 enum MatchScore<'a> {
1246 Strong {
1247 sort_text: Option<&'a str>,
1248 score: Reverse<OrderedFloat<f64>>,
1249 sort_key: (usize, &'a str),
1250 },
1251 Weak {
1252 score: Reverse<OrderedFloat<f64>>,
1253 sort_text: Option<&'a str>,
1254 sort_key: (usize, &'a str),
1255 },
1256 }
1257
1258 let completion = &completions[mat.candidate_id];
1259 let sort_key = completion.sort_key();
1260 let sort_text = completion.lsp_completion.sort_text.as_deref();
1261 let score = Reverse(OrderedFloat(mat.score));
1262
1263 if mat.score >= 0.2 {
1264 MatchScore::Strong {
1265 sort_text,
1266 score,
1267 sort_key,
1268 }
1269 } else {
1270 MatchScore::Weak {
1271 score,
1272 sort_text,
1273 sort_key,
1274 }
1275 }
1276 });
1277
1278 for mat in &mut matches {
1279 let completion = &completions[mat.candidate_id];
1280 mat.string.clone_from(&completion.label.text);
1281 for position in &mut mat.positions {
1282 *position += completion.label.filter_range.start;
1283 }
1284 }
1285 drop(completions);
1286
1287 self.matches = matches.into();
1288 self.selected_item = 0;
1289 }
1290}
1291
1292#[derive(Clone)]
1293struct CodeActionContents {
1294 tasks: Option<Arc<ResolvedTasks>>,
1295 actions: Option<Arc<[CodeAction]>>,
1296}
1297
1298impl CodeActionContents {
1299 fn len(&self) -> usize {
1300 match (&self.tasks, &self.actions) {
1301 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1302 (Some(tasks), None) => tasks.templates.len(),
1303 (None, Some(actions)) => actions.len(),
1304 (None, None) => 0,
1305 }
1306 }
1307
1308 fn is_empty(&self) -> bool {
1309 match (&self.tasks, &self.actions) {
1310 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1311 (Some(tasks), None) => tasks.templates.is_empty(),
1312 (None, Some(actions)) => actions.is_empty(),
1313 (None, None) => true,
1314 }
1315 }
1316
1317 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1318 self.tasks
1319 .iter()
1320 .flat_map(|tasks| {
1321 tasks
1322 .templates
1323 .iter()
1324 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1325 })
1326 .chain(self.actions.iter().flat_map(|actions| {
1327 actions
1328 .iter()
1329 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1330 }))
1331 }
1332 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1333 match (&self.tasks, &self.actions) {
1334 (Some(tasks), Some(actions)) => {
1335 if index < tasks.templates.len() {
1336 tasks
1337 .templates
1338 .get(index)
1339 .cloned()
1340 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1341 } else {
1342 actions
1343 .get(index - tasks.templates.len())
1344 .cloned()
1345 .map(CodeActionsItem::CodeAction)
1346 }
1347 }
1348 (Some(tasks), None) => tasks
1349 .templates
1350 .get(index)
1351 .cloned()
1352 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1353 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1354 (None, None) => None,
1355 }
1356 }
1357}
1358
1359#[allow(clippy::large_enum_variant)]
1360#[derive(Clone)]
1361enum CodeActionsItem {
1362 Task(TaskSourceKind, ResolvedTask),
1363 CodeAction(CodeAction),
1364}
1365
1366impl CodeActionsItem {
1367 fn as_task(&self) -> Option<&ResolvedTask> {
1368 let Self::Task(_, task) = self else {
1369 return None;
1370 };
1371 Some(task)
1372 }
1373 fn as_code_action(&self) -> Option<&CodeAction> {
1374 let Self::CodeAction(action) = self else {
1375 return None;
1376 };
1377 Some(action)
1378 }
1379 fn label(&self) -> String {
1380 match self {
1381 Self::CodeAction(action) => action.lsp_action.title.clone(),
1382 Self::Task(_, task) => task.resolved_label.clone(),
1383 }
1384 }
1385}
1386
1387struct CodeActionsMenu {
1388 actions: CodeActionContents,
1389 buffer: Model<Buffer>,
1390 selected_item: usize,
1391 scroll_handle: UniformListScrollHandle,
1392 deployed_from_indicator: Option<DisplayRow>,
1393}
1394
1395impl CodeActionsMenu {
1396 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1397 self.selected_item = 0;
1398 self.scroll_handle.scroll_to_item(self.selected_item);
1399 cx.notify()
1400 }
1401
1402 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1403 if self.selected_item > 0 {
1404 self.selected_item -= 1;
1405 } else {
1406 self.selected_item = self.actions.len() - 1;
1407 }
1408 self.scroll_handle.scroll_to_item(self.selected_item);
1409 cx.notify();
1410 }
1411
1412 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1413 if self.selected_item + 1 < self.actions.len() {
1414 self.selected_item += 1;
1415 } else {
1416 self.selected_item = 0;
1417 }
1418 self.scroll_handle.scroll_to_item(self.selected_item);
1419 cx.notify();
1420 }
1421
1422 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1423 self.selected_item = self.actions.len() - 1;
1424 self.scroll_handle.scroll_to_item(self.selected_item);
1425 cx.notify()
1426 }
1427
1428 fn visible(&self) -> bool {
1429 !self.actions.is_empty()
1430 }
1431
1432 fn render(
1433 &self,
1434 cursor_position: DisplayPoint,
1435 _style: &EditorStyle,
1436 max_height: Pixels,
1437 cx: &mut ViewContext<Editor>,
1438 ) -> (ContextMenuOrigin, AnyElement) {
1439 let actions = self.actions.clone();
1440 let selected_item = self.selected_item;
1441 let element = uniform_list(
1442 cx.view().clone(),
1443 "code_actions_menu",
1444 self.actions.len(),
1445 move |_this, range, cx| {
1446 actions
1447 .iter()
1448 .skip(range.start)
1449 .take(range.end - range.start)
1450 .enumerate()
1451 .map(|(ix, action)| {
1452 let item_ix = range.start + ix;
1453 let selected = selected_item == item_ix;
1454 let colors = cx.theme().colors();
1455 div()
1456 .px_2()
1457 .text_color(colors.text)
1458 .when(selected, |style| {
1459 style
1460 .bg(colors.element_active)
1461 .text_color(colors.text_accent)
1462 })
1463 .hover(|style| {
1464 style
1465 .bg(colors.element_hover)
1466 .text_color(colors.text_accent)
1467 })
1468 .whitespace_nowrap()
1469 .when_some(action.as_code_action(), |this, action| {
1470 this.on_mouse_down(
1471 MouseButton::Left,
1472 cx.listener(move |editor, _, cx| {
1473 cx.stop_propagation();
1474 if let Some(task) = editor.confirm_code_action(
1475 &ConfirmCodeAction {
1476 item_ix: Some(item_ix),
1477 },
1478 cx,
1479 ) {
1480 task.detach_and_log_err(cx)
1481 }
1482 }),
1483 )
1484 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1485 .child(SharedString::from(action.lsp_action.title.clone()))
1486 })
1487 .when_some(action.as_task(), |this, task| {
1488 this.on_mouse_down(
1489 MouseButton::Left,
1490 cx.listener(move |editor, _, cx| {
1491 cx.stop_propagation();
1492 if let Some(task) = editor.confirm_code_action(
1493 &ConfirmCodeAction {
1494 item_ix: Some(item_ix),
1495 },
1496 cx,
1497 ) {
1498 task.detach_and_log_err(cx)
1499 }
1500 }),
1501 )
1502 .child(SharedString::from(task.resolved_label.clone()))
1503 })
1504 })
1505 .collect()
1506 },
1507 )
1508 .elevation_1(cx)
1509 .px_2()
1510 .py_1()
1511 .max_h(max_height)
1512 .occlude()
1513 .track_scroll(self.scroll_handle.clone())
1514 .with_width_from_item(
1515 self.actions
1516 .iter()
1517 .enumerate()
1518 .max_by_key(|(_, action)| match action {
1519 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1520 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1521 })
1522 .map(|(ix, _)| ix),
1523 )
1524 .with_sizing_behavior(ListSizingBehavior::Infer)
1525 .into_any_element();
1526
1527 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1528 ContextMenuOrigin::GutterIndicator(row)
1529 } else {
1530 ContextMenuOrigin::EditorPoint(cursor_position)
1531 };
1532
1533 (cursor_position, element)
1534 }
1535}
1536
1537#[derive(Debug)]
1538struct ActiveDiagnosticGroup {
1539 primary_range: Range<Anchor>,
1540 primary_message: String,
1541 group_id: usize,
1542 blocks: HashMap<CustomBlockId, Diagnostic>,
1543 is_valid: bool,
1544}
1545
1546#[derive(Serialize, Deserialize, Clone, Debug)]
1547pub struct ClipboardSelection {
1548 pub len: usize,
1549 pub is_entire_line: bool,
1550 pub first_line_indent: u32,
1551}
1552
1553#[derive(Debug)]
1554pub(crate) struct NavigationData {
1555 cursor_anchor: Anchor,
1556 cursor_position: Point,
1557 scroll_anchor: ScrollAnchor,
1558 scroll_top_row: u32,
1559}
1560
1561enum GotoDefinitionKind {
1562 Symbol,
1563 Declaration,
1564 Type,
1565 Implementation,
1566}
1567
1568#[derive(Debug, Clone)]
1569enum InlayHintRefreshReason {
1570 Toggle(bool),
1571 SettingsChange(InlayHintSettings),
1572 NewLinesShown,
1573 BufferEdited(HashSet<Arc<Language>>),
1574 RefreshRequested,
1575 ExcerptsRemoved(Vec<ExcerptId>),
1576}
1577
1578impl InlayHintRefreshReason {
1579 fn description(&self) -> &'static str {
1580 match self {
1581 Self::Toggle(_) => "toggle",
1582 Self::SettingsChange(_) => "settings change",
1583 Self::NewLinesShown => "new lines shown",
1584 Self::BufferEdited(_) => "buffer edited",
1585 Self::RefreshRequested => "refresh requested",
1586 Self::ExcerptsRemoved(_) => "excerpts removed",
1587 }
1588 }
1589}
1590
1591pub(crate) struct FocusedBlock {
1592 id: BlockId,
1593 focus_handle: WeakFocusHandle,
1594}
1595
1596impl Editor {
1597 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1598 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1599 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1600 Self::new(
1601 EditorMode::SingleLine { auto_width: false },
1602 buffer,
1603 None,
1604 false,
1605 cx,
1606 )
1607 }
1608
1609 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1610 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1611 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1612 Self::new(EditorMode::Full, buffer, None, false, cx)
1613 }
1614
1615 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1616 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1617 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1618 Self::new(
1619 EditorMode::SingleLine { auto_width: true },
1620 buffer,
1621 None,
1622 false,
1623 cx,
1624 )
1625 }
1626
1627 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1628 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1629 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1630 Self::new(
1631 EditorMode::AutoHeight { max_lines },
1632 buffer,
1633 None,
1634 false,
1635 cx,
1636 )
1637 }
1638
1639 pub fn for_buffer(
1640 buffer: Model<Buffer>,
1641 project: Option<Model<Project>>,
1642 cx: &mut ViewContext<Self>,
1643 ) -> Self {
1644 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1645 Self::new(EditorMode::Full, buffer, project, false, cx)
1646 }
1647
1648 pub fn for_multibuffer(
1649 buffer: Model<MultiBuffer>,
1650 project: Option<Model<Project>>,
1651 show_excerpt_controls: bool,
1652 cx: &mut ViewContext<Self>,
1653 ) -> Self {
1654 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1655 }
1656
1657 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1658 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1659 let mut clone = Self::new(
1660 self.mode,
1661 self.buffer.clone(),
1662 self.project.clone(),
1663 show_excerpt_controls,
1664 cx,
1665 );
1666 self.display_map.update(cx, |display_map, cx| {
1667 let snapshot = display_map.snapshot(cx);
1668 clone.display_map.update(cx, |display_map, cx| {
1669 display_map.set_state(&snapshot, cx);
1670 });
1671 });
1672 clone.selections.clone_state(&self.selections);
1673 clone.scroll_manager.clone_state(&self.scroll_manager);
1674 clone.searchable = self.searchable;
1675 clone
1676 }
1677
1678 pub fn new(
1679 mode: EditorMode,
1680 buffer: Model<MultiBuffer>,
1681 project: Option<Model<Project>>,
1682 show_excerpt_controls: bool,
1683 cx: &mut ViewContext<Self>,
1684 ) -> Self {
1685 let style = cx.text_style();
1686 let font_size = style.font_size.to_pixels(cx.rem_size());
1687 let editor = cx.view().downgrade();
1688 let fold_placeholder = FoldPlaceholder {
1689 constrain_width: true,
1690 render: Arc::new(move |fold_id, fold_range, cx| {
1691 let editor = editor.clone();
1692 div()
1693 .id(fold_id)
1694 .bg(cx.theme().colors().ghost_element_background)
1695 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1696 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1697 .rounded_sm()
1698 .size_full()
1699 .cursor_pointer()
1700 .child("⋯")
1701 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1702 .on_click(move |_, cx| {
1703 editor
1704 .update(cx, |editor, cx| {
1705 editor.unfold_ranges(
1706 [fold_range.start..fold_range.end],
1707 true,
1708 false,
1709 cx,
1710 );
1711 cx.stop_propagation();
1712 })
1713 .ok();
1714 })
1715 .into_any()
1716 }),
1717 merge_adjacent: true,
1718 };
1719 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1720 let display_map = cx.new_model(|cx| {
1721 DisplayMap::new(
1722 buffer.clone(),
1723 style.font(),
1724 font_size,
1725 None,
1726 show_excerpt_controls,
1727 file_header_size,
1728 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1729 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1730 fold_placeholder,
1731 cx,
1732 )
1733 });
1734
1735 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1736
1737 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1738
1739 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1740 .then(|| language_settings::SoftWrap::PreferLine);
1741
1742 let mut project_subscriptions = Vec::new();
1743 if mode == EditorMode::Full {
1744 if let Some(project) = project.as_ref() {
1745 if buffer.read(cx).is_singleton() {
1746 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1747 cx.emit(EditorEvent::TitleChanged);
1748 }));
1749 }
1750 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1751 if let project::Event::RefreshInlayHints = event {
1752 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1753 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1754 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1755 let focus_handle = editor.focus_handle(cx);
1756 if focus_handle.is_focused(cx) {
1757 let snapshot = buffer.read(cx).snapshot();
1758 for (range, snippet) in snippet_edits {
1759 let editor_range =
1760 language::range_from_lsp(*range).to_offset(&snapshot);
1761 editor
1762 .insert_snippet(&[editor_range], snippet.clone(), cx)
1763 .ok();
1764 }
1765 }
1766 }
1767 }
1768 }));
1769 let task_inventory = project.read(cx).task_inventory().clone();
1770 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1771 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1772 }));
1773 }
1774 }
1775
1776 let inlay_hint_settings = inlay_hint_settings(
1777 selections.newest_anchor().head(),
1778 &buffer.read(cx).snapshot(cx),
1779 cx,
1780 );
1781 let focus_handle = cx.focus_handle();
1782 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1783 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1784 .detach();
1785 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1786 .detach();
1787 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1788
1789 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1790 Some(false)
1791 } else {
1792 None
1793 };
1794
1795 let mut this = Self {
1796 focus_handle,
1797 show_cursor_when_unfocused: false,
1798 last_focused_descendant: None,
1799 buffer: buffer.clone(),
1800 display_map: display_map.clone(),
1801 selections,
1802 scroll_manager: ScrollManager::new(cx),
1803 columnar_selection_tail: None,
1804 add_selections_state: None,
1805 select_next_state: None,
1806 select_prev_state: None,
1807 selection_history: Default::default(),
1808 autoclose_regions: Default::default(),
1809 snippet_stack: Default::default(),
1810 select_larger_syntax_node_stack: Vec::new(),
1811 ime_transaction: Default::default(),
1812 active_diagnostics: None,
1813 soft_wrap_mode_override,
1814 completion_provider: project.clone().map(|project| Box::new(project) as _),
1815 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1816 project,
1817 blink_manager: blink_manager.clone(),
1818 show_local_selections: true,
1819 mode,
1820 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1821 show_gutter: mode == EditorMode::Full,
1822 show_line_numbers: None,
1823 show_git_diff_gutter: None,
1824 show_code_actions: None,
1825 show_runnables: None,
1826 show_wrap_guides: None,
1827 show_indent_guides,
1828 placeholder_text: None,
1829 highlight_order: 0,
1830 highlighted_rows: HashMap::default(),
1831 background_highlights: Default::default(),
1832 gutter_highlights: TreeMap::default(),
1833 scrollbar_marker_state: ScrollbarMarkerState::default(),
1834 active_indent_guides_state: ActiveIndentGuidesState::default(),
1835 nav_history: None,
1836 context_menu: RwLock::new(None),
1837 mouse_context_menu: None,
1838 completion_tasks: Default::default(),
1839 signature_help_state: SignatureHelpState::default(),
1840 auto_signature_help: None,
1841 find_all_references_task_sources: Vec::new(),
1842 next_completion_id: 0,
1843 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1844 next_inlay_id: 0,
1845 available_code_actions: Default::default(),
1846 code_actions_task: Default::default(),
1847 document_highlights_task: Default::default(),
1848 linked_editing_range_task: Default::default(),
1849 pending_rename: Default::default(),
1850 searchable: true,
1851 cursor_shape: Default::default(),
1852 current_line_highlight: None,
1853 autoindent_mode: Some(AutoindentMode::EachLine),
1854 collapse_matches: false,
1855 workspace: None,
1856 keymap_context_layers: Default::default(),
1857 input_enabled: true,
1858 use_modal_editing: mode == EditorMode::Full,
1859 read_only: false,
1860 use_autoclose: true,
1861 use_auto_surround: true,
1862 auto_replace_emoji_shortcode: false,
1863 leader_peer_id: None,
1864 remote_id: None,
1865 hover_state: Default::default(),
1866 hovered_link_state: Default::default(),
1867 inline_completion_provider: None,
1868 active_inline_completion: None,
1869 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1870 expanded_hunks: ExpandedHunks::default(),
1871 gutter_hovered: false,
1872 pixel_position_of_newest_cursor: None,
1873 last_bounds: None,
1874 expect_bounds_change: None,
1875 gutter_dimensions: GutterDimensions::default(),
1876 style: None,
1877 show_cursor_names: false,
1878 hovered_cursors: Default::default(),
1879 next_editor_action_id: EditorActionId::default(),
1880 editor_actions: Rc::default(),
1881 vim_replace_map: Default::default(),
1882 show_inline_completions: mode == EditorMode::Full,
1883 custom_context_menu: None,
1884 show_git_blame_gutter: false,
1885 show_git_blame_inline: false,
1886 show_selection_menu: None,
1887 show_git_blame_inline_delay_task: None,
1888 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1889 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1890 .session
1891 .restore_unsaved_buffers,
1892 blame: None,
1893 blame_subscription: None,
1894 file_header_size,
1895 tasks: Default::default(),
1896 _subscriptions: vec![
1897 cx.observe(&buffer, Self::on_buffer_changed),
1898 cx.subscribe(&buffer, Self::on_buffer_event),
1899 cx.observe(&display_map, Self::on_display_map_changed),
1900 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1901 cx.observe_global::<SettingsStore>(Self::settings_changed),
1902 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1903 cx.observe_window_activation(|editor, cx| {
1904 let active = cx.is_window_active();
1905 editor.blink_manager.update(cx, |blink_manager, cx| {
1906 if active {
1907 blink_manager.enable(cx);
1908 } else {
1909 blink_manager.disable(cx);
1910 }
1911 });
1912 }),
1913 ],
1914 tasks_update_task: None,
1915 linked_edit_ranges: Default::default(),
1916 previous_search_ranges: None,
1917 breadcrumb_header: None,
1918 focused_block: None,
1919 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1920 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1921 };
1922 this.tasks_update_task = Some(this.refresh_runnables(cx));
1923 this._subscriptions.extend(project_subscriptions);
1924
1925 this.end_selection(cx);
1926 this.scroll_manager.show_scrollbar(cx);
1927
1928 if mode == EditorMode::Full {
1929 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1930 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1931
1932 if this.git_blame_inline_enabled {
1933 this.git_blame_inline_enabled = true;
1934 this.start_git_blame_inline(false, cx);
1935 }
1936 }
1937
1938 this.report_editor_event("open", None, cx);
1939 this
1940 }
1941
1942 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1943 self.mouse_context_menu
1944 .as_ref()
1945 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1946 }
1947
1948 fn key_context(&self, cx: &AppContext) -> KeyContext {
1949 let mut key_context = KeyContext::new_with_defaults();
1950 key_context.add("Editor");
1951 let mode = match self.mode {
1952 EditorMode::SingleLine { .. } => "single_line",
1953 EditorMode::AutoHeight { .. } => "auto_height",
1954 EditorMode::Full => "full",
1955 };
1956
1957 if EditorSettings::jupyter_enabled(cx) {
1958 key_context.add("jupyter");
1959 }
1960
1961 key_context.set("mode", mode);
1962 if self.pending_rename.is_some() {
1963 key_context.add("renaming");
1964 }
1965 if self.context_menu_visible() {
1966 match self.context_menu.read().as_ref() {
1967 Some(ContextMenu::Completions(_)) => {
1968 key_context.add("menu");
1969 key_context.add("showing_completions")
1970 }
1971 Some(ContextMenu::CodeActions(_)) => {
1972 key_context.add("menu");
1973 key_context.add("showing_code_actions")
1974 }
1975 None => {}
1976 }
1977 }
1978
1979 for layer in self.keymap_context_layers.values() {
1980 key_context.extend(layer);
1981 }
1982
1983 if let Some(extension) = self
1984 .buffer
1985 .read(cx)
1986 .as_singleton()
1987 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1988 {
1989 key_context.set("extension", extension.to_string());
1990 }
1991
1992 if self.has_active_inline_completion(cx) {
1993 key_context.add("copilot_suggestion");
1994 key_context.add("inline_completion");
1995 }
1996
1997 key_context
1998 }
1999
2000 pub fn new_file(
2001 workspace: &mut Workspace,
2002 _: &workspace::NewFile,
2003 cx: &mut ViewContext<Workspace>,
2004 ) {
2005 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2006 "Failed to create buffer",
2007 cx,
2008 |e, _| match e.error_code() {
2009 ErrorCode::RemoteUpgradeRequired => Some(format!(
2010 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2011 e.error_tag("required").unwrap_or("the latest version")
2012 )),
2013 _ => None,
2014 },
2015 );
2016 }
2017
2018 pub fn new_in_workspace(
2019 workspace: &mut Workspace,
2020 cx: &mut ViewContext<Workspace>,
2021 ) -> Task<Result<View<Editor>>> {
2022 let project = workspace.project().clone();
2023 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2024
2025 cx.spawn(|workspace, mut cx| async move {
2026 let buffer = create.await?;
2027 workspace.update(&mut cx, |workspace, cx| {
2028 let editor =
2029 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2030 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2031 editor
2032 })
2033 })
2034 }
2035
2036 pub fn new_file_in_direction(
2037 workspace: &mut Workspace,
2038 action: &workspace::NewFileInDirection,
2039 cx: &mut ViewContext<Workspace>,
2040 ) {
2041 let project = workspace.project().clone();
2042 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2043 let direction = action.0;
2044
2045 cx.spawn(|workspace, mut cx| async move {
2046 let buffer = create.await?;
2047 workspace.update(&mut cx, move |workspace, cx| {
2048 workspace.split_item(
2049 direction,
2050 Box::new(
2051 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2052 ),
2053 cx,
2054 )
2055 })?;
2056 anyhow::Ok(())
2057 })
2058 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2059 ErrorCode::RemoteUpgradeRequired => Some(format!(
2060 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2061 e.error_tag("required").unwrap_or("the latest version")
2062 )),
2063 _ => None,
2064 });
2065 }
2066
2067 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2068 self.buffer.read(cx).replica_id()
2069 }
2070
2071 pub fn leader_peer_id(&self) -> Option<PeerId> {
2072 self.leader_peer_id
2073 }
2074
2075 pub fn buffer(&self) -> &Model<MultiBuffer> {
2076 &self.buffer
2077 }
2078
2079 pub fn workspace(&self) -> Option<View<Workspace>> {
2080 self.workspace.as_ref()?.0.upgrade()
2081 }
2082
2083 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2084 self.buffer().read(cx).title(cx)
2085 }
2086
2087 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2088 EditorSnapshot {
2089 mode: self.mode,
2090 show_gutter: self.show_gutter,
2091 show_line_numbers: self.show_line_numbers,
2092 show_git_diff_gutter: self.show_git_diff_gutter,
2093 show_code_actions: self.show_code_actions,
2094 show_runnables: self.show_runnables,
2095 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2096 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2097 scroll_anchor: self.scroll_manager.anchor(),
2098 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2099 placeholder_text: self.placeholder_text.clone(),
2100 is_focused: self.focus_handle.is_focused(cx),
2101 current_line_highlight: self
2102 .current_line_highlight
2103 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2104 gutter_hovered: self.gutter_hovered,
2105 }
2106 }
2107
2108 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2109 self.buffer.read(cx).language_at(point, cx)
2110 }
2111
2112 pub fn file_at<T: ToOffset>(
2113 &self,
2114 point: T,
2115 cx: &AppContext,
2116 ) -> Option<Arc<dyn language::File>> {
2117 self.buffer.read(cx).read(cx).file_at(point).cloned()
2118 }
2119
2120 pub fn active_excerpt(
2121 &self,
2122 cx: &AppContext,
2123 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2124 self.buffer
2125 .read(cx)
2126 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2127 }
2128
2129 pub fn mode(&self) -> EditorMode {
2130 self.mode
2131 }
2132
2133 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2134 self.collaboration_hub.as_deref()
2135 }
2136
2137 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2138 self.collaboration_hub = Some(hub);
2139 }
2140
2141 pub fn set_custom_context_menu(
2142 &mut self,
2143 f: impl 'static
2144 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2145 ) {
2146 self.custom_context_menu = Some(Box::new(f))
2147 }
2148
2149 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2150 self.completion_provider = Some(provider);
2151 }
2152
2153 pub fn set_inline_completion_provider<T>(
2154 &mut self,
2155 provider: Option<Model<T>>,
2156 cx: &mut ViewContext<Self>,
2157 ) where
2158 T: InlineCompletionProvider,
2159 {
2160 self.inline_completion_provider =
2161 provider.map(|provider| RegisteredInlineCompletionProvider {
2162 _subscription: cx.observe(&provider, |this, _, cx| {
2163 if this.focus_handle.is_focused(cx) {
2164 this.update_visible_inline_completion(cx);
2165 }
2166 }),
2167 provider: Arc::new(provider),
2168 });
2169 self.refresh_inline_completion(false, cx);
2170 }
2171
2172 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2173 self.placeholder_text.as_deref()
2174 }
2175
2176 pub fn set_placeholder_text(
2177 &mut self,
2178 placeholder_text: impl Into<Arc<str>>,
2179 cx: &mut ViewContext<Self>,
2180 ) {
2181 let placeholder_text = Some(placeholder_text.into());
2182 if self.placeholder_text != placeholder_text {
2183 self.placeholder_text = placeholder_text;
2184 cx.notify();
2185 }
2186 }
2187
2188 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2189 self.cursor_shape = cursor_shape;
2190
2191 // Disrupt blink for immediate user feedback that the cursor shape has changed
2192 self.blink_manager.update(cx, BlinkManager::show_cursor);
2193
2194 cx.notify();
2195 }
2196
2197 pub fn set_current_line_highlight(
2198 &mut self,
2199 current_line_highlight: Option<CurrentLineHighlight>,
2200 ) {
2201 self.current_line_highlight = current_line_highlight;
2202 }
2203
2204 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2205 self.collapse_matches = collapse_matches;
2206 }
2207
2208 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2209 if self.collapse_matches {
2210 return range.start..range.start;
2211 }
2212 range.clone()
2213 }
2214
2215 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2216 if self.display_map.read(cx).clip_at_line_ends != clip {
2217 self.display_map
2218 .update(cx, |map, _| map.clip_at_line_ends = clip);
2219 }
2220 }
2221
2222 pub fn set_keymap_context_layer<Tag: 'static>(
2223 &mut self,
2224 context: KeyContext,
2225 cx: &mut ViewContext<Self>,
2226 ) {
2227 self.keymap_context_layers
2228 .insert(TypeId::of::<Tag>(), context);
2229 cx.notify();
2230 }
2231
2232 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2233 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2234 cx.notify();
2235 }
2236
2237 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2238 self.input_enabled = input_enabled;
2239 }
2240
2241 pub fn set_autoindent(&mut self, autoindent: bool) {
2242 if autoindent {
2243 self.autoindent_mode = Some(AutoindentMode::EachLine);
2244 } else {
2245 self.autoindent_mode = None;
2246 }
2247 }
2248
2249 pub fn read_only(&self, cx: &AppContext) -> bool {
2250 self.read_only || self.buffer.read(cx).read_only()
2251 }
2252
2253 pub fn set_read_only(&mut self, read_only: bool) {
2254 self.read_only = read_only;
2255 }
2256
2257 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2258 self.use_autoclose = autoclose;
2259 }
2260
2261 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2262 self.use_auto_surround = auto_surround;
2263 }
2264
2265 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2266 self.auto_replace_emoji_shortcode = auto_replace;
2267 }
2268
2269 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2270 self.show_inline_completions = show_inline_completions;
2271 }
2272
2273 pub fn set_use_modal_editing(&mut self, to: bool) {
2274 self.use_modal_editing = to;
2275 }
2276
2277 pub fn use_modal_editing(&self) -> bool {
2278 self.use_modal_editing
2279 }
2280
2281 fn selections_did_change(
2282 &mut self,
2283 local: bool,
2284 old_cursor_position: &Anchor,
2285 show_completions: bool,
2286 cx: &mut ViewContext<Self>,
2287 ) {
2288 // Copy selections to primary selection buffer
2289 #[cfg(target_os = "linux")]
2290 if local {
2291 let selections = self.selections.all::<usize>(cx);
2292 let buffer_handle = self.buffer.read(cx).read(cx);
2293
2294 let mut text = String::new();
2295 for (index, selection) in selections.iter().enumerate() {
2296 let text_for_selection = buffer_handle
2297 .text_for_range(selection.start..selection.end)
2298 .collect::<String>();
2299
2300 text.push_str(&text_for_selection);
2301 if index != selections.len() - 1 {
2302 text.push('\n');
2303 }
2304 }
2305
2306 if !text.is_empty() {
2307 cx.write_to_primary(ClipboardItem::new_string(text));
2308 }
2309 }
2310
2311 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2312 self.buffer.update(cx, |buffer, cx| {
2313 buffer.set_active_selections(
2314 &self.selections.disjoint_anchors(),
2315 self.selections.line_mode,
2316 self.cursor_shape,
2317 cx,
2318 )
2319 });
2320 }
2321 let display_map = self
2322 .display_map
2323 .update(cx, |display_map, cx| display_map.snapshot(cx));
2324 let buffer = &display_map.buffer_snapshot;
2325 self.add_selections_state = None;
2326 self.select_next_state = None;
2327 self.select_prev_state = None;
2328 self.select_larger_syntax_node_stack.clear();
2329 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2330 self.snippet_stack
2331 .invalidate(&self.selections.disjoint_anchors(), buffer);
2332 self.take_rename(false, cx);
2333
2334 let new_cursor_position = self.selections.newest_anchor().head();
2335
2336 self.push_to_nav_history(
2337 *old_cursor_position,
2338 Some(new_cursor_position.to_point(buffer)),
2339 cx,
2340 );
2341
2342 if local {
2343 let new_cursor_position = self.selections.newest_anchor().head();
2344 let mut context_menu = self.context_menu.write();
2345 let completion_menu = match context_menu.as_ref() {
2346 Some(ContextMenu::Completions(menu)) => Some(menu),
2347
2348 _ => {
2349 *context_menu = None;
2350 None
2351 }
2352 };
2353
2354 if let Some(completion_menu) = completion_menu {
2355 let cursor_position = new_cursor_position.to_offset(buffer);
2356 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2357 if kind == Some(CharKind::Word)
2358 && word_range.to_inclusive().contains(&cursor_position)
2359 {
2360 let mut completion_menu = completion_menu.clone();
2361 drop(context_menu);
2362
2363 let query = Self::completion_query(buffer, cursor_position);
2364 cx.spawn(move |this, mut cx| async move {
2365 completion_menu
2366 .filter(query.as_deref(), cx.background_executor().clone())
2367 .await;
2368
2369 this.update(&mut cx, |this, cx| {
2370 let mut context_menu = this.context_menu.write();
2371 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2372 return;
2373 };
2374
2375 if menu.id > completion_menu.id {
2376 return;
2377 }
2378
2379 *context_menu = Some(ContextMenu::Completions(completion_menu));
2380 drop(context_menu);
2381 cx.notify();
2382 })
2383 })
2384 .detach();
2385
2386 if show_completions {
2387 self.show_completions(&ShowCompletions { trigger: None }, cx);
2388 }
2389 } else {
2390 drop(context_menu);
2391 self.hide_context_menu(cx);
2392 }
2393 } else {
2394 drop(context_menu);
2395 }
2396
2397 hide_hover(self, cx);
2398
2399 if old_cursor_position.to_display_point(&display_map).row()
2400 != new_cursor_position.to_display_point(&display_map).row()
2401 {
2402 self.available_code_actions.take();
2403 }
2404 self.refresh_code_actions(cx);
2405 self.refresh_document_highlights(cx);
2406 refresh_matching_bracket_highlights(self, cx);
2407 self.discard_inline_completion(false, cx);
2408 linked_editing_ranges::refresh_linked_ranges(self, cx);
2409 if self.git_blame_inline_enabled {
2410 self.start_inline_blame_timer(cx);
2411 }
2412 }
2413
2414 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2415 cx.emit(EditorEvent::SelectionsChanged { local });
2416
2417 if self.selections.disjoint_anchors().len() == 1 {
2418 cx.emit(SearchEvent::ActiveMatchChanged)
2419 }
2420 cx.notify();
2421 }
2422
2423 pub fn change_selections<R>(
2424 &mut self,
2425 autoscroll: Option<Autoscroll>,
2426 cx: &mut ViewContext<Self>,
2427 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2428 ) -> R {
2429 self.change_selections_inner(autoscroll, true, cx, change)
2430 }
2431
2432 pub fn change_selections_inner<R>(
2433 &mut self,
2434 autoscroll: Option<Autoscroll>,
2435 request_completions: bool,
2436 cx: &mut ViewContext<Self>,
2437 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2438 ) -> R {
2439 let old_cursor_position = self.selections.newest_anchor().head();
2440 self.push_to_selection_history();
2441
2442 let (changed, result) = self.selections.change_with(cx, change);
2443
2444 if changed {
2445 if let Some(autoscroll) = autoscroll {
2446 self.request_autoscroll(autoscroll, cx);
2447 }
2448 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2449
2450 if self.should_open_signature_help_automatically(
2451 &old_cursor_position,
2452 self.signature_help_state.backspace_pressed(),
2453 cx,
2454 ) {
2455 self.show_signature_help(&ShowSignatureHelp, cx);
2456 }
2457 self.signature_help_state.set_backspace_pressed(false);
2458 }
2459
2460 result
2461 }
2462
2463 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2464 where
2465 I: IntoIterator<Item = (Range<S>, T)>,
2466 S: ToOffset,
2467 T: Into<Arc<str>>,
2468 {
2469 if self.read_only(cx) {
2470 return;
2471 }
2472
2473 self.buffer
2474 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2475 }
2476
2477 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2478 where
2479 I: IntoIterator<Item = (Range<S>, T)>,
2480 S: ToOffset,
2481 T: Into<Arc<str>>,
2482 {
2483 if self.read_only(cx) {
2484 return;
2485 }
2486
2487 self.buffer.update(cx, |buffer, cx| {
2488 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2489 });
2490 }
2491
2492 pub fn edit_with_block_indent<I, S, T>(
2493 &mut self,
2494 edits: I,
2495 original_indent_columns: Vec<u32>,
2496 cx: &mut ViewContext<Self>,
2497 ) where
2498 I: IntoIterator<Item = (Range<S>, T)>,
2499 S: ToOffset,
2500 T: Into<Arc<str>>,
2501 {
2502 if self.read_only(cx) {
2503 return;
2504 }
2505
2506 self.buffer.update(cx, |buffer, cx| {
2507 buffer.edit(
2508 edits,
2509 Some(AutoindentMode::Block {
2510 original_indent_columns,
2511 }),
2512 cx,
2513 )
2514 });
2515 }
2516
2517 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2518 self.hide_context_menu(cx);
2519
2520 match phase {
2521 SelectPhase::Begin {
2522 position,
2523 add,
2524 click_count,
2525 } => self.begin_selection(position, add, click_count, cx),
2526 SelectPhase::BeginColumnar {
2527 position,
2528 goal_column,
2529 reset,
2530 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2531 SelectPhase::Extend {
2532 position,
2533 click_count,
2534 } => self.extend_selection(position, click_count, cx),
2535 SelectPhase::Update {
2536 position,
2537 goal_column,
2538 scroll_delta,
2539 } => self.update_selection(position, goal_column, scroll_delta, cx),
2540 SelectPhase::End => self.end_selection(cx),
2541 }
2542 }
2543
2544 fn extend_selection(
2545 &mut self,
2546 position: DisplayPoint,
2547 click_count: usize,
2548 cx: &mut ViewContext<Self>,
2549 ) {
2550 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2551 let tail = self.selections.newest::<usize>(cx).tail();
2552 self.begin_selection(position, false, click_count, cx);
2553
2554 let position = position.to_offset(&display_map, Bias::Left);
2555 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2556
2557 let mut pending_selection = self
2558 .selections
2559 .pending_anchor()
2560 .expect("extend_selection not called with pending selection");
2561 if position >= tail {
2562 pending_selection.start = tail_anchor;
2563 } else {
2564 pending_selection.end = tail_anchor;
2565 pending_selection.reversed = true;
2566 }
2567
2568 let mut pending_mode = self.selections.pending_mode().unwrap();
2569 match &mut pending_mode {
2570 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2571 _ => {}
2572 }
2573
2574 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2575 s.set_pending(pending_selection, pending_mode)
2576 });
2577 }
2578
2579 fn begin_selection(
2580 &mut self,
2581 position: DisplayPoint,
2582 add: bool,
2583 click_count: usize,
2584 cx: &mut ViewContext<Self>,
2585 ) {
2586 if !self.focus_handle.is_focused(cx) {
2587 self.last_focused_descendant = None;
2588 cx.focus(&self.focus_handle);
2589 }
2590
2591 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2592 let buffer = &display_map.buffer_snapshot;
2593 let newest_selection = self.selections.newest_anchor().clone();
2594 let position = display_map.clip_point(position, Bias::Left);
2595
2596 let start;
2597 let end;
2598 let mode;
2599 let auto_scroll;
2600 match click_count {
2601 1 => {
2602 start = buffer.anchor_before(position.to_point(&display_map));
2603 end = start;
2604 mode = SelectMode::Character;
2605 auto_scroll = true;
2606 }
2607 2 => {
2608 let range = movement::surrounding_word(&display_map, position);
2609 start = buffer.anchor_before(range.start.to_point(&display_map));
2610 end = buffer.anchor_before(range.end.to_point(&display_map));
2611 mode = SelectMode::Word(start..end);
2612 auto_scroll = true;
2613 }
2614 3 => {
2615 let position = display_map
2616 .clip_point(position, Bias::Left)
2617 .to_point(&display_map);
2618 let line_start = display_map.prev_line_boundary(position).0;
2619 let next_line_start = buffer.clip_point(
2620 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2621 Bias::Left,
2622 );
2623 start = buffer.anchor_before(line_start);
2624 end = buffer.anchor_before(next_line_start);
2625 mode = SelectMode::Line(start..end);
2626 auto_scroll = true;
2627 }
2628 _ => {
2629 start = buffer.anchor_before(0);
2630 end = buffer.anchor_before(buffer.len());
2631 mode = SelectMode::All;
2632 auto_scroll = false;
2633 }
2634 }
2635
2636 let point_to_delete: Option<usize> = {
2637 let selected_points: Vec<Selection<Point>> =
2638 self.selections.disjoint_in_range(start..end, cx);
2639
2640 if !add || click_count > 1 {
2641 None
2642 } else if selected_points.len() > 0 {
2643 Some(selected_points[0].id)
2644 } else {
2645 let clicked_point_already_selected =
2646 self.selections.disjoint.iter().find(|selection| {
2647 selection.start.to_point(buffer) == start.to_point(buffer)
2648 || selection.end.to_point(buffer) == end.to_point(buffer)
2649 });
2650
2651 if let Some(selection) = clicked_point_already_selected {
2652 Some(selection.id)
2653 } else {
2654 None
2655 }
2656 }
2657 };
2658
2659 let selections_count = self.selections.count();
2660
2661 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2662 if let Some(point_to_delete) = point_to_delete {
2663 s.delete(point_to_delete);
2664
2665 if selections_count == 1 {
2666 s.set_pending_anchor_range(start..end, mode);
2667 }
2668 } else {
2669 if !add {
2670 s.clear_disjoint();
2671 } else if click_count > 1 {
2672 s.delete(newest_selection.id)
2673 }
2674
2675 s.set_pending_anchor_range(start..end, mode);
2676 }
2677 });
2678 }
2679
2680 fn begin_columnar_selection(
2681 &mut self,
2682 position: DisplayPoint,
2683 goal_column: u32,
2684 reset: bool,
2685 cx: &mut ViewContext<Self>,
2686 ) {
2687 if !self.focus_handle.is_focused(cx) {
2688 self.last_focused_descendant = None;
2689 cx.focus(&self.focus_handle);
2690 }
2691
2692 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2693
2694 if reset {
2695 let pointer_position = display_map
2696 .buffer_snapshot
2697 .anchor_before(position.to_point(&display_map));
2698
2699 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2700 s.clear_disjoint();
2701 s.set_pending_anchor_range(
2702 pointer_position..pointer_position,
2703 SelectMode::Character,
2704 );
2705 });
2706 }
2707
2708 let tail = self.selections.newest::<Point>(cx).tail();
2709 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2710
2711 if !reset {
2712 self.select_columns(
2713 tail.to_display_point(&display_map),
2714 position,
2715 goal_column,
2716 &display_map,
2717 cx,
2718 );
2719 }
2720 }
2721
2722 fn update_selection(
2723 &mut self,
2724 position: DisplayPoint,
2725 goal_column: u32,
2726 scroll_delta: gpui::Point<f32>,
2727 cx: &mut ViewContext<Self>,
2728 ) {
2729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2730
2731 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2732 let tail = tail.to_display_point(&display_map);
2733 self.select_columns(tail, position, goal_column, &display_map, cx);
2734 } else if let Some(mut pending) = self.selections.pending_anchor() {
2735 let buffer = self.buffer.read(cx).snapshot(cx);
2736 let head;
2737 let tail;
2738 let mode = self.selections.pending_mode().unwrap();
2739 match &mode {
2740 SelectMode::Character => {
2741 head = position.to_point(&display_map);
2742 tail = pending.tail().to_point(&buffer);
2743 }
2744 SelectMode::Word(original_range) => {
2745 let original_display_range = original_range.start.to_display_point(&display_map)
2746 ..original_range.end.to_display_point(&display_map);
2747 let original_buffer_range = original_display_range.start.to_point(&display_map)
2748 ..original_display_range.end.to_point(&display_map);
2749 if movement::is_inside_word(&display_map, position)
2750 || original_display_range.contains(&position)
2751 {
2752 let word_range = movement::surrounding_word(&display_map, position);
2753 if word_range.start < original_display_range.start {
2754 head = word_range.start.to_point(&display_map);
2755 } else {
2756 head = word_range.end.to_point(&display_map);
2757 }
2758 } else {
2759 head = position.to_point(&display_map);
2760 }
2761
2762 if head <= original_buffer_range.start {
2763 tail = original_buffer_range.end;
2764 } else {
2765 tail = original_buffer_range.start;
2766 }
2767 }
2768 SelectMode::Line(original_range) => {
2769 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2770
2771 let position = display_map
2772 .clip_point(position, Bias::Left)
2773 .to_point(&display_map);
2774 let line_start = display_map.prev_line_boundary(position).0;
2775 let next_line_start = buffer.clip_point(
2776 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2777 Bias::Left,
2778 );
2779
2780 if line_start < original_range.start {
2781 head = line_start
2782 } else {
2783 head = next_line_start
2784 }
2785
2786 if head <= original_range.start {
2787 tail = original_range.end;
2788 } else {
2789 tail = original_range.start;
2790 }
2791 }
2792 SelectMode::All => {
2793 return;
2794 }
2795 };
2796
2797 if head < tail {
2798 pending.start = buffer.anchor_before(head);
2799 pending.end = buffer.anchor_before(tail);
2800 pending.reversed = true;
2801 } else {
2802 pending.start = buffer.anchor_before(tail);
2803 pending.end = buffer.anchor_before(head);
2804 pending.reversed = false;
2805 }
2806
2807 self.change_selections(None, cx, |s| {
2808 s.set_pending(pending, mode);
2809 });
2810 } else {
2811 log::error!("update_selection dispatched with no pending selection");
2812 return;
2813 }
2814
2815 self.apply_scroll_delta(scroll_delta, cx);
2816 cx.notify();
2817 }
2818
2819 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2820 self.columnar_selection_tail.take();
2821 if self.selections.pending_anchor().is_some() {
2822 let selections = self.selections.all::<usize>(cx);
2823 self.change_selections(None, cx, |s| {
2824 s.select(selections);
2825 s.clear_pending();
2826 });
2827 }
2828 }
2829
2830 fn select_columns(
2831 &mut self,
2832 tail: DisplayPoint,
2833 head: DisplayPoint,
2834 goal_column: u32,
2835 display_map: &DisplaySnapshot,
2836 cx: &mut ViewContext<Self>,
2837 ) {
2838 let start_row = cmp::min(tail.row(), head.row());
2839 let end_row = cmp::max(tail.row(), head.row());
2840 let start_column = cmp::min(tail.column(), goal_column);
2841 let end_column = cmp::max(tail.column(), goal_column);
2842 let reversed = start_column < tail.column();
2843
2844 let selection_ranges = (start_row.0..=end_row.0)
2845 .map(DisplayRow)
2846 .filter_map(|row| {
2847 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2848 let start = display_map
2849 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2850 .to_point(display_map);
2851 let end = display_map
2852 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2853 .to_point(display_map);
2854 if reversed {
2855 Some(end..start)
2856 } else {
2857 Some(start..end)
2858 }
2859 } else {
2860 None
2861 }
2862 })
2863 .collect::<Vec<_>>();
2864
2865 self.change_selections(None, cx, |s| {
2866 s.select_ranges(selection_ranges);
2867 });
2868 cx.notify();
2869 }
2870
2871 pub fn has_pending_nonempty_selection(&self) -> bool {
2872 let pending_nonempty_selection = match self.selections.pending_anchor() {
2873 Some(Selection { start, end, .. }) => start != end,
2874 None => false,
2875 };
2876
2877 pending_nonempty_selection
2878 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2879 }
2880
2881 pub fn has_pending_selection(&self) -> bool {
2882 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2883 }
2884
2885 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2886 if self.clear_clicked_diff_hunks(cx) {
2887 cx.notify();
2888 return;
2889 }
2890 if self.dismiss_menus_and_popups(true, cx) {
2891 return;
2892 }
2893
2894 if self.mode == EditorMode::Full {
2895 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2896 return;
2897 }
2898 }
2899
2900 cx.propagate();
2901 }
2902
2903 pub fn dismiss_menus_and_popups(
2904 &mut self,
2905 should_report_inline_completion_event: bool,
2906 cx: &mut ViewContext<Self>,
2907 ) -> bool {
2908 if self.take_rename(false, cx).is_some() {
2909 return true;
2910 }
2911
2912 if hide_hover(self, cx) {
2913 return true;
2914 }
2915
2916 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2917 return true;
2918 }
2919
2920 if self.hide_context_menu(cx).is_some() {
2921 return true;
2922 }
2923
2924 if self.mouse_context_menu.take().is_some() {
2925 return true;
2926 }
2927
2928 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2929 return true;
2930 }
2931
2932 if self.snippet_stack.pop().is_some() {
2933 return true;
2934 }
2935
2936 if self.mode == EditorMode::Full {
2937 if self.active_diagnostics.is_some() {
2938 self.dismiss_diagnostics(cx);
2939 return true;
2940 }
2941 }
2942
2943 false
2944 }
2945
2946 fn linked_editing_ranges_for(
2947 &self,
2948 selection: Range<text::Anchor>,
2949 cx: &AppContext,
2950 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2951 if self.linked_edit_ranges.is_empty() {
2952 return None;
2953 }
2954 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2955 selection.end.buffer_id.and_then(|end_buffer_id| {
2956 if selection.start.buffer_id != Some(end_buffer_id) {
2957 return None;
2958 }
2959 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2960 let snapshot = buffer.read(cx).snapshot();
2961 self.linked_edit_ranges
2962 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2963 .map(|ranges| (ranges, snapshot, buffer))
2964 })?;
2965 use text::ToOffset as TO;
2966 // find offset from the start of current range to current cursor position
2967 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2968
2969 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2970 let start_difference = start_offset - start_byte_offset;
2971 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2972 let end_difference = end_offset - start_byte_offset;
2973 // Current range has associated linked ranges.
2974 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2975 for range in linked_ranges.iter() {
2976 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2977 let end_offset = start_offset + end_difference;
2978 let start_offset = start_offset + start_difference;
2979 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2980 continue;
2981 }
2982 let start = buffer_snapshot.anchor_after(start_offset);
2983 let end = buffer_snapshot.anchor_after(end_offset);
2984 linked_edits
2985 .entry(buffer.clone())
2986 .or_default()
2987 .push(start..end);
2988 }
2989 Some(linked_edits)
2990 }
2991
2992 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2993 let text: Arc<str> = text.into();
2994
2995 if self.read_only(cx) {
2996 return;
2997 }
2998
2999 let selections = self.selections.all_adjusted(cx);
3000 let mut bracket_inserted = false;
3001 let mut edits = Vec::new();
3002 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3003 let mut new_selections = Vec::with_capacity(selections.len());
3004 let mut new_autoclose_regions = Vec::new();
3005 let snapshot = self.buffer.read(cx).read(cx);
3006
3007 for (selection, autoclose_region) in
3008 self.selections_with_autoclose_regions(selections, &snapshot)
3009 {
3010 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3011 // Determine if the inserted text matches the opening or closing
3012 // bracket of any of this language's bracket pairs.
3013 let mut bracket_pair = None;
3014 let mut is_bracket_pair_start = false;
3015 let mut is_bracket_pair_end = false;
3016 if !text.is_empty() {
3017 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3018 // and they are removing the character that triggered IME popup.
3019 for (pair, enabled) in scope.brackets() {
3020 if !pair.close && !pair.surround {
3021 continue;
3022 }
3023
3024 if enabled && pair.start.ends_with(text.as_ref()) {
3025 bracket_pair = Some(pair.clone());
3026 is_bracket_pair_start = true;
3027 break;
3028 }
3029 if pair.end.as_str() == text.as_ref() {
3030 bracket_pair = Some(pair.clone());
3031 is_bracket_pair_end = true;
3032 break;
3033 }
3034 }
3035 }
3036
3037 if let Some(bracket_pair) = bracket_pair {
3038 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3039 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3040 let auto_surround =
3041 self.use_auto_surround && snapshot_settings.use_auto_surround;
3042 if selection.is_empty() {
3043 if is_bracket_pair_start {
3044 let prefix_len = bracket_pair.start.len() - text.len();
3045
3046 // If the inserted text is a suffix of an opening bracket and the
3047 // selection is preceded by the rest of the opening bracket, then
3048 // insert the closing bracket.
3049 let following_text_allows_autoclose = snapshot
3050 .chars_at(selection.start)
3051 .next()
3052 .map_or(true, |c| scope.should_autoclose_before(c));
3053 let preceding_text_matches_prefix = prefix_len == 0
3054 || (selection.start.column >= (prefix_len as u32)
3055 && snapshot.contains_str_at(
3056 Point::new(
3057 selection.start.row,
3058 selection.start.column - (prefix_len as u32),
3059 ),
3060 &bracket_pair.start[..prefix_len],
3061 ));
3062
3063 if autoclose
3064 && bracket_pair.close
3065 && following_text_allows_autoclose
3066 && preceding_text_matches_prefix
3067 {
3068 let anchor = snapshot.anchor_before(selection.end);
3069 new_selections.push((selection.map(|_| anchor), text.len()));
3070 new_autoclose_regions.push((
3071 anchor,
3072 text.len(),
3073 selection.id,
3074 bracket_pair.clone(),
3075 ));
3076 edits.push((
3077 selection.range(),
3078 format!("{}{}", text, bracket_pair.end).into(),
3079 ));
3080 bracket_inserted = true;
3081 continue;
3082 }
3083 }
3084
3085 if let Some(region) = autoclose_region {
3086 // If the selection is followed by an auto-inserted closing bracket,
3087 // then don't insert that closing bracket again; just move the selection
3088 // past the closing bracket.
3089 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3090 && text.as_ref() == region.pair.end.as_str();
3091 if should_skip {
3092 let anchor = snapshot.anchor_after(selection.end);
3093 new_selections
3094 .push((selection.map(|_| anchor), region.pair.end.len()));
3095 continue;
3096 }
3097 }
3098
3099 let always_treat_brackets_as_autoclosed = snapshot
3100 .settings_at(selection.start, cx)
3101 .always_treat_brackets_as_autoclosed;
3102 if always_treat_brackets_as_autoclosed
3103 && is_bracket_pair_end
3104 && snapshot.contains_str_at(selection.end, text.as_ref())
3105 {
3106 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3107 // and the inserted text is a closing bracket and the selection is followed
3108 // by the closing bracket then move the selection past the closing bracket.
3109 let anchor = snapshot.anchor_after(selection.end);
3110 new_selections.push((selection.map(|_| anchor), text.len()));
3111 continue;
3112 }
3113 }
3114 // If an opening bracket is 1 character long and is typed while
3115 // text is selected, then surround that text with the bracket pair.
3116 else if auto_surround
3117 && bracket_pair.surround
3118 && is_bracket_pair_start
3119 && bracket_pair.start.chars().count() == 1
3120 {
3121 edits.push((selection.start..selection.start, text.clone()));
3122 edits.push((
3123 selection.end..selection.end,
3124 bracket_pair.end.as_str().into(),
3125 ));
3126 bracket_inserted = true;
3127 new_selections.push((
3128 Selection {
3129 id: selection.id,
3130 start: snapshot.anchor_after(selection.start),
3131 end: snapshot.anchor_before(selection.end),
3132 reversed: selection.reversed,
3133 goal: selection.goal,
3134 },
3135 0,
3136 ));
3137 continue;
3138 }
3139 }
3140 }
3141
3142 if self.auto_replace_emoji_shortcode
3143 && selection.is_empty()
3144 && text.as_ref().ends_with(':')
3145 {
3146 if let Some(possible_emoji_short_code) =
3147 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3148 {
3149 if !possible_emoji_short_code.is_empty() {
3150 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3151 let emoji_shortcode_start = Point::new(
3152 selection.start.row,
3153 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3154 );
3155
3156 // Remove shortcode from buffer
3157 edits.push((
3158 emoji_shortcode_start..selection.start,
3159 "".to_string().into(),
3160 ));
3161 new_selections.push((
3162 Selection {
3163 id: selection.id,
3164 start: snapshot.anchor_after(emoji_shortcode_start),
3165 end: snapshot.anchor_before(selection.start),
3166 reversed: selection.reversed,
3167 goal: selection.goal,
3168 },
3169 0,
3170 ));
3171
3172 // Insert emoji
3173 let selection_start_anchor = snapshot.anchor_after(selection.start);
3174 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3175 edits.push((selection.start..selection.end, emoji.to_string().into()));
3176
3177 continue;
3178 }
3179 }
3180 }
3181 }
3182
3183 // If not handling any auto-close operation, then just replace the selected
3184 // text with the given input and move the selection to the end of the
3185 // newly inserted text.
3186 let anchor = snapshot.anchor_after(selection.end);
3187 if !self.linked_edit_ranges.is_empty() {
3188 let start_anchor = snapshot.anchor_before(selection.start);
3189
3190 let is_word_char = text.chars().next().map_or(true, |char| {
3191 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3192 let kind = char_kind(&scope, char);
3193
3194 kind == CharKind::Word
3195 });
3196
3197 if is_word_char {
3198 if let Some(ranges) = self
3199 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3200 {
3201 for (buffer, edits) in ranges {
3202 linked_edits
3203 .entry(buffer.clone())
3204 .or_default()
3205 .extend(edits.into_iter().map(|range| (range, text.clone())));
3206 }
3207 }
3208 }
3209 }
3210
3211 new_selections.push((selection.map(|_| anchor), 0));
3212 edits.push((selection.start..selection.end, text.clone()));
3213 }
3214
3215 drop(snapshot);
3216
3217 self.transact(cx, |this, cx| {
3218 this.buffer.update(cx, |buffer, cx| {
3219 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3220 });
3221 for (buffer, edits) in linked_edits {
3222 buffer.update(cx, |buffer, cx| {
3223 let snapshot = buffer.snapshot();
3224 let edits = edits
3225 .into_iter()
3226 .map(|(range, text)| {
3227 use text::ToPoint as TP;
3228 let end_point = TP::to_point(&range.end, &snapshot);
3229 let start_point = TP::to_point(&range.start, &snapshot);
3230 (start_point..end_point, text)
3231 })
3232 .sorted_by_key(|(range, _)| range.start)
3233 .collect::<Vec<_>>();
3234 buffer.edit(edits, None, cx);
3235 })
3236 }
3237 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3238 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3239 let snapshot = this.buffer.read(cx).read(cx);
3240 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3241 .zip(new_selection_deltas)
3242 .map(|(selection, delta)| Selection {
3243 id: selection.id,
3244 start: selection.start + delta,
3245 end: selection.end + delta,
3246 reversed: selection.reversed,
3247 goal: SelectionGoal::None,
3248 })
3249 .collect::<Vec<_>>();
3250
3251 let mut i = 0;
3252 for (position, delta, selection_id, pair) in new_autoclose_regions {
3253 let position = position.to_offset(&snapshot) + delta;
3254 let start = snapshot.anchor_before(position);
3255 let end = snapshot.anchor_after(position);
3256 while let Some(existing_state) = this.autoclose_regions.get(i) {
3257 match existing_state.range.start.cmp(&start, &snapshot) {
3258 Ordering::Less => i += 1,
3259 Ordering::Greater => break,
3260 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3261 Ordering::Less => i += 1,
3262 Ordering::Equal => break,
3263 Ordering::Greater => break,
3264 },
3265 }
3266 }
3267 this.autoclose_regions.insert(
3268 i,
3269 AutocloseRegion {
3270 selection_id,
3271 range: start..end,
3272 pair,
3273 },
3274 );
3275 }
3276
3277 drop(snapshot);
3278 let had_active_inline_completion = this.has_active_inline_completion(cx);
3279 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3280 s.select(new_selections)
3281 });
3282
3283 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3284 if let Some(on_type_format_task) =
3285 this.trigger_on_type_formatting(text.to_string(), cx)
3286 {
3287 on_type_format_task.detach_and_log_err(cx);
3288 }
3289 }
3290
3291 let editor_settings = EditorSettings::get_global(cx);
3292 if bracket_inserted
3293 && (editor_settings.auto_signature_help
3294 || editor_settings.show_signature_help_after_edits)
3295 {
3296 this.show_signature_help(&ShowSignatureHelp, cx);
3297 }
3298
3299 let trigger_in_words = !had_active_inline_completion;
3300 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3301 linked_editing_ranges::refresh_linked_ranges(this, cx);
3302 this.refresh_inline_completion(true, cx);
3303 });
3304 }
3305
3306 fn find_possible_emoji_shortcode_at_position(
3307 snapshot: &MultiBufferSnapshot,
3308 position: Point,
3309 ) -> Option<String> {
3310 let mut chars = Vec::new();
3311 let mut found_colon = false;
3312 for char in snapshot.reversed_chars_at(position).take(100) {
3313 // Found a possible emoji shortcode in the middle of the buffer
3314 if found_colon {
3315 if char.is_whitespace() {
3316 chars.reverse();
3317 return Some(chars.iter().collect());
3318 }
3319 // If the previous character is not a whitespace, we are in the middle of a word
3320 // and we only want to complete the shortcode if the word is made up of other emojis
3321 let mut containing_word = String::new();
3322 for ch in snapshot
3323 .reversed_chars_at(position)
3324 .skip(chars.len() + 1)
3325 .take(100)
3326 {
3327 if ch.is_whitespace() {
3328 break;
3329 }
3330 containing_word.push(ch);
3331 }
3332 let containing_word = containing_word.chars().rev().collect::<String>();
3333 if util::word_consists_of_emojis(containing_word.as_str()) {
3334 chars.reverse();
3335 return Some(chars.iter().collect());
3336 }
3337 }
3338
3339 if char.is_whitespace() || !char.is_ascii() {
3340 return None;
3341 }
3342 if char == ':' {
3343 found_colon = true;
3344 } else {
3345 chars.push(char);
3346 }
3347 }
3348 // Found a possible emoji shortcode at the beginning of the buffer
3349 chars.reverse();
3350 Some(chars.iter().collect())
3351 }
3352
3353 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3354 self.transact(cx, |this, cx| {
3355 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3356 let selections = this.selections.all::<usize>(cx);
3357 let multi_buffer = this.buffer.read(cx);
3358 let buffer = multi_buffer.snapshot(cx);
3359 selections
3360 .iter()
3361 .map(|selection| {
3362 let start_point = selection.start.to_point(&buffer);
3363 let mut indent =
3364 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3365 indent.len = cmp::min(indent.len, start_point.column);
3366 let start = selection.start;
3367 let end = selection.end;
3368 let selection_is_empty = start == end;
3369 let language_scope = buffer.language_scope_at(start);
3370 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3371 &language_scope
3372 {
3373 let leading_whitespace_len = buffer
3374 .reversed_chars_at(start)
3375 .take_while(|c| c.is_whitespace() && *c != '\n')
3376 .map(|c| c.len_utf8())
3377 .sum::<usize>();
3378
3379 let trailing_whitespace_len = buffer
3380 .chars_at(end)
3381 .take_while(|c| c.is_whitespace() && *c != '\n')
3382 .map(|c| c.len_utf8())
3383 .sum::<usize>();
3384
3385 let insert_extra_newline =
3386 language.brackets().any(|(pair, enabled)| {
3387 let pair_start = pair.start.trim_end();
3388 let pair_end = pair.end.trim_start();
3389
3390 enabled
3391 && pair.newline
3392 && buffer.contains_str_at(
3393 end + trailing_whitespace_len,
3394 pair_end,
3395 )
3396 && buffer.contains_str_at(
3397 (start - leading_whitespace_len)
3398 .saturating_sub(pair_start.len()),
3399 pair_start,
3400 )
3401 });
3402
3403 // Comment extension on newline is allowed only for cursor selections
3404 let comment_delimiter = maybe!({
3405 if !selection_is_empty {
3406 return None;
3407 }
3408
3409 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3410 return None;
3411 }
3412
3413 let delimiters = language.line_comment_prefixes();
3414 let max_len_of_delimiter =
3415 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3416 let (snapshot, range) =
3417 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3418
3419 let mut index_of_first_non_whitespace = 0;
3420 let comment_candidate = snapshot
3421 .chars_for_range(range)
3422 .skip_while(|c| {
3423 let should_skip = c.is_whitespace();
3424 if should_skip {
3425 index_of_first_non_whitespace += 1;
3426 }
3427 should_skip
3428 })
3429 .take(max_len_of_delimiter)
3430 .collect::<String>();
3431 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3432 comment_candidate.starts_with(comment_prefix.as_ref())
3433 })?;
3434 let cursor_is_placed_after_comment_marker =
3435 index_of_first_non_whitespace + comment_prefix.len()
3436 <= start_point.column as usize;
3437 if cursor_is_placed_after_comment_marker {
3438 Some(comment_prefix.clone())
3439 } else {
3440 None
3441 }
3442 });
3443 (comment_delimiter, insert_extra_newline)
3444 } else {
3445 (None, false)
3446 };
3447
3448 let capacity_for_delimiter = comment_delimiter
3449 .as_deref()
3450 .map(str::len)
3451 .unwrap_or_default();
3452 let mut new_text =
3453 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3454 new_text.push_str("\n");
3455 new_text.extend(indent.chars());
3456 if let Some(delimiter) = &comment_delimiter {
3457 new_text.push_str(&delimiter);
3458 }
3459 if insert_extra_newline {
3460 new_text = new_text.repeat(2);
3461 }
3462
3463 let anchor = buffer.anchor_after(end);
3464 let new_selection = selection.map(|_| anchor);
3465 (
3466 (start..end, new_text),
3467 (insert_extra_newline, new_selection),
3468 )
3469 })
3470 .unzip()
3471 };
3472
3473 this.edit_with_autoindent(edits, cx);
3474 let buffer = this.buffer.read(cx).snapshot(cx);
3475 let new_selections = selection_fixup_info
3476 .into_iter()
3477 .map(|(extra_newline_inserted, new_selection)| {
3478 let mut cursor = new_selection.end.to_point(&buffer);
3479 if extra_newline_inserted {
3480 cursor.row -= 1;
3481 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3482 }
3483 new_selection.map(|_| cursor)
3484 })
3485 .collect();
3486
3487 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3488 this.refresh_inline_completion(true, cx);
3489 });
3490 }
3491
3492 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3493 let buffer = self.buffer.read(cx);
3494 let snapshot = buffer.snapshot(cx);
3495
3496 let mut edits = Vec::new();
3497 let mut rows = Vec::new();
3498
3499 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3500 let cursor = selection.head();
3501 let row = cursor.row;
3502
3503 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3504
3505 let newline = "\n".to_string();
3506 edits.push((start_of_line..start_of_line, newline));
3507
3508 rows.push(row + rows_inserted as u32);
3509 }
3510
3511 self.transact(cx, |editor, cx| {
3512 editor.edit(edits, cx);
3513
3514 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3515 let mut index = 0;
3516 s.move_cursors_with(|map, _, _| {
3517 let row = rows[index];
3518 index += 1;
3519
3520 let point = Point::new(row, 0);
3521 let boundary = map.next_line_boundary(point).1;
3522 let clipped = map.clip_point(boundary, Bias::Left);
3523
3524 (clipped, SelectionGoal::None)
3525 });
3526 });
3527
3528 let mut indent_edits = Vec::new();
3529 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3530 for row in rows {
3531 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3532 for (row, indent) in indents {
3533 if indent.len == 0 {
3534 continue;
3535 }
3536
3537 let text = match indent.kind {
3538 IndentKind::Space => " ".repeat(indent.len as usize),
3539 IndentKind::Tab => "\t".repeat(indent.len as usize),
3540 };
3541 let point = Point::new(row.0, 0);
3542 indent_edits.push((point..point, text));
3543 }
3544 }
3545 editor.edit(indent_edits, cx);
3546 });
3547 }
3548
3549 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3550 let buffer = self.buffer.read(cx);
3551 let snapshot = buffer.snapshot(cx);
3552
3553 let mut edits = Vec::new();
3554 let mut rows = Vec::new();
3555 let mut rows_inserted = 0;
3556
3557 for selection in self.selections.all_adjusted(cx) {
3558 let cursor = selection.head();
3559 let row = cursor.row;
3560
3561 let point = Point::new(row + 1, 0);
3562 let start_of_line = snapshot.clip_point(point, Bias::Left);
3563
3564 let newline = "\n".to_string();
3565 edits.push((start_of_line..start_of_line, newline));
3566
3567 rows_inserted += 1;
3568 rows.push(row + rows_inserted);
3569 }
3570
3571 self.transact(cx, |editor, cx| {
3572 editor.edit(edits, cx);
3573
3574 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3575 let mut index = 0;
3576 s.move_cursors_with(|map, _, _| {
3577 let row = rows[index];
3578 index += 1;
3579
3580 let point = Point::new(row, 0);
3581 let boundary = map.next_line_boundary(point).1;
3582 let clipped = map.clip_point(boundary, Bias::Left);
3583
3584 (clipped, SelectionGoal::None)
3585 });
3586 });
3587
3588 let mut indent_edits = Vec::new();
3589 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3590 for row in rows {
3591 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3592 for (row, indent) in indents {
3593 if indent.len == 0 {
3594 continue;
3595 }
3596
3597 let text = match indent.kind {
3598 IndentKind::Space => " ".repeat(indent.len as usize),
3599 IndentKind::Tab => "\t".repeat(indent.len as usize),
3600 };
3601 let point = Point::new(row.0, 0);
3602 indent_edits.push((point..point, text));
3603 }
3604 }
3605 editor.edit(indent_edits, cx);
3606 });
3607 }
3608
3609 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3610 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3611 original_indent_columns: Vec::new(),
3612 });
3613 self.insert_with_autoindent_mode(text, autoindent, cx);
3614 }
3615
3616 fn insert_with_autoindent_mode(
3617 &mut self,
3618 text: &str,
3619 autoindent_mode: Option<AutoindentMode>,
3620 cx: &mut ViewContext<Self>,
3621 ) {
3622 if self.read_only(cx) {
3623 return;
3624 }
3625
3626 let text: Arc<str> = text.into();
3627 self.transact(cx, |this, cx| {
3628 let old_selections = this.selections.all_adjusted(cx);
3629 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3630 let anchors = {
3631 let snapshot = buffer.read(cx);
3632 old_selections
3633 .iter()
3634 .map(|s| {
3635 let anchor = snapshot.anchor_after(s.head());
3636 s.map(|_| anchor)
3637 })
3638 .collect::<Vec<_>>()
3639 };
3640 buffer.edit(
3641 old_selections
3642 .iter()
3643 .map(|s| (s.start..s.end, text.clone())),
3644 autoindent_mode,
3645 cx,
3646 );
3647 anchors
3648 });
3649
3650 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3651 s.select_anchors(selection_anchors);
3652 })
3653 });
3654 }
3655
3656 fn trigger_completion_on_input(
3657 &mut self,
3658 text: &str,
3659 trigger_in_words: bool,
3660 cx: &mut ViewContext<Self>,
3661 ) {
3662 if self.is_completion_trigger(text, trigger_in_words, cx) {
3663 self.show_completions(
3664 &ShowCompletions {
3665 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3666 },
3667 cx,
3668 );
3669 } else {
3670 self.hide_context_menu(cx);
3671 }
3672 }
3673
3674 fn is_completion_trigger(
3675 &self,
3676 text: &str,
3677 trigger_in_words: bool,
3678 cx: &mut ViewContext<Self>,
3679 ) -> bool {
3680 let position = self.selections.newest_anchor().head();
3681 let multibuffer = self.buffer.read(cx);
3682 let Some(buffer) = position
3683 .buffer_id
3684 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3685 else {
3686 return false;
3687 };
3688
3689 if let Some(completion_provider) = &self.completion_provider {
3690 completion_provider.is_completion_trigger(
3691 &buffer,
3692 position.text_anchor,
3693 text,
3694 trigger_in_words,
3695 cx,
3696 )
3697 } else {
3698 false
3699 }
3700 }
3701
3702 /// If any empty selections is touching the start of its innermost containing autoclose
3703 /// region, expand it to select the brackets.
3704 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3705 let selections = self.selections.all::<usize>(cx);
3706 let buffer = self.buffer.read(cx).read(cx);
3707 let new_selections = self
3708 .selections_with_autoclose_regions(selections, &buffer)
3709 .map(|(mut selection, region)| {
3710 if !selection.is_empty() {
3711 return selection;
3712 }
3713
3714 if let Some(region) = region {
3715 let mut range = region.range.to_offset(&buffer);
3716 if selection.start == range.start && range.start >= region.pair.start.len() {
3717 range.start -= region.pair.start.len();
3718 if buffer.contains_str_at(range.start, ®ion.pair.start)
3719 && buffer.contains_str_at(range.end, ®ion.pair.end)
3720 {
3721 range.end += region.pair.end.len();
3722 selection.start = range.start;
3723 selection.end = range.end;
3724
3725 return selection;
3726 }
3727 }
3728 }
3729
3730 let always_treat_brackets_as_autoclosed = buffer
3731 .settings_at(selection.start, cx)
3732 .always_treat_brackets_as_autoclosed;
3733
3734 if !always_treat_brackets_as_autoclosed {
3735 return selection;
3736 }
3737
3738 if let Some(scope) = buffer.language_scope_at(selection.start) {
3739 for (pair, enabled) in scope.brackets() {
3740 if !enabled || !pair.close {
3741 continue;
3742 }
3743
3744 if buffer.contains_str_at(selection.start, &pair.end) {
3745 let pair_start_len = pair.start.len();
3746 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3747 {
3748 selection.start -= pair_start_len;
3749 selection.end += pair.end.len();
3750
3751 return selection;
3752 }
3753 }
3754 }
3755 }
3756
3757 selection
3758 })
3759 .collect();
3760
3761 drop(buffer);
3762 self.change_selections(None, cx, |selections| selections.select(new_selections));
3763 }
3764
3765 /// Iterate the given selections, and for each one, find the smallest surrounding
3766 /// autoclose region. This uses the ordering of the selections and the autoclose
3767 /// regions to avoid repeated comparisons.
3768 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3769 &'a self,
3770 selections: impl IntoIterator<Item = Selection<D>>,
3771 buffer: &'a MultiBufferSnapshot,
3772 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3773 let mut i = 0;
3774 let mut regions = self.autoclose_regions.as_slice();
3775 selections.into_iter().map(move |selection| {
3776 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3777
3778 let mut enclosing = None;
3779 while let Some(pair_state) = regions.get(i) {
3780 if pair_state.range.end.to_offset(buffer) < range.start {
3781 regions = ®ions[i + 1..];
3782 i = 0;
3783 } else if pair_state.range.start.to_offset(buffer) > range.end {
3784 break;
3785 } else {
3786 if pair_state.selection_id == selection.id {
3787 enclosing = Some(pair_state);
3788 }
3789 i += 1;
3790 }
3791 }
3792
3793 (selection.clone(), enclosing)
3794 })
3795 }
3796
3797 /// Remove any autoclose regions that no longer contain their selection.
3798 fn invalidate_autoclose_regions(
3799 &mut self,
3800 mut selections: &[Selection<Anchor>],
3801 buffer: &MultiBufferSnapshot,
3802 ) {
3803 self.autoclose_regions.retain(|state| {
3804 let mut i = 0;
3805 while let Some(selection) = selections.get(i) {
3806 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3807 selections = &selections[1..];
3808 continue;
3809 }
3810 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3811 break;
3812 }
3813 if selection.id == state.selection_id {
3814 return true;
3815 } else {
3816 i += 1;
3817 }
3818 }
3819 false
3820 });
3821 }
3822
3823 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3824 let offset = position.to_offset(buffer);
3825 let (word_range, kind) = buffer.surrounding_word(offset);
3826 if offset > word_range.start && kind == Some(CharKind::Word) {
3827 Some(
3828 buffer
3829 .text_for_range(word_range.start..offset)
3830 .collect::<String>(),
3831 )
3832 } else {
3833 None
3834 }
3835 }
3836
3837 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3838 self.refresh_inlay_hints(
3839 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3840 cx,
3841 );
3842 }
3843
3844 pub fn inlay_hints_enabled(&self) -> bool {
3845 self.inlay_hint_cache.enabled
3846 }
3847
3848 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3849 if self.project.is_none() || self.mode != EditorMode::Full {
3850 return;
3851 }
3852
3853 let reason_description = reason.description();
3854 let ignore_debounce = matches!(
3855 reason,
3856 InlayHintRefreshReason::SettingsChange(_)
3857 | InlayHintRefreshReason::Toggle(_)
3858 | InlayHintRefreshReason::ExcerptsRemoved(_)
3859 );
3860 let (invalidate_cache, required_languages) = match reason {
3861 InlayHintRefreshReason::Toggle(enabled) => {
3862 self.inlay_hint_cache.enabled = enabled;
3863 if enabled {
3864 (InvalidationStrategy::RefreshRequested, None)
3865 } else {
3866 self.inlay_hint_cache.clear();
3867 self.splice_inlays(
3868 self.visible_inlay_hints(cx)
3869 .iter()
3870 .map(|inlay| inlay.id)
3871 .collect(),
3872 Vec::new(),
3873 cx,
3874 );
3875 return;
3876 }
3877 }
3878 InlayHintRefreshReason::SettingsChange(new_settings) => {
3879 match self.inlay_hint_cache.update_settings(
3880 &self.buffer,
3881 new_settings,
3882 self.visible_inlay_hints(cx),
3883 cx,
3884 ) {
3885 ControlFlow::Break(Some(InlaySplice {
3886 to_remove,
3887 to_insert,
3888 })) => {
3889 self.splice_inlays(to_remove, to_insert, cx);
3890 return;
3891 }
3892 ControlFlow::Break(None) => return,
3893 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3894 }
3895 }
3896 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3897 if let Some(InlaySplice {
3898 to_remove,
3899 to_insert,
3900 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3901 {
3902 self.splice_inlays(to_remove, to_insert, cx);
3903 }
3904 return;
3905 }
3906 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3907 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3908 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3909 }
3910 InlayHintRefreshReason::RefreshRequested => {
3911 (InvalidationStrategy::RefreshRequested, None)
3912 }
3913 };
3914
3915 if let Some(InlaySplice {
3916 to_remove,
3917 to_insert,
3918 }) = self.inlay_hint_cache.spawn_hint_refresh(
3919 reason_description,
3920 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3921 invalidate_cache,
3922 ignore_debounce,
3923 cx,
3924 ) {
3925 self.splice_inlays(to_remove, to_insert, cx);
3926 }
3927 }
3928
3929 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3930 self.display_map
3931 .read(cx)
3932 .current_inlays()
3933 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3934 .cloned()
3935 .collect()
3936 }
3937
3938 pub fn excerpts_for_inlay_hints_query(
3939 &self,
3940 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3941 cx: &mut ViewContext<Editor>,
3942 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3943 let Some(project) = self.project.as_ref() else {
3944 return HashMap::default();
3945 };
3946 let project = project.read(cx);
3947 let multi_buffer = self.buffer().read(cx);
3948 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3949 let multi_buffer_visible_start = self
3950 .scroll_manager
3951 .anchor()
3952 .anchor
3953 .to_point(&multi_buffer_snapshot);
3954 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3955 multi_buffer_visible_start
3956 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3957 Bias::Left,
3958 );
3959 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3960 multi_buffer
3961 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3962 .into_iter()
3963 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3964 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3965 let buffer = buffer_handle.read(cx);
3966 let buffer_file = project::File::from_dyn(buffer.file())?;
3967 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3968 let worktree_entry = buffer_worktree
3969 .read(cx)
3970 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3971 if worktree_entry.is_ignored {
3972 return None;
3973 }
3974
3975 let language = buffer.language()?;
3976 if let Some(restrict_to_languages) = restrict_to_languages {
3977 if !restrict_to_languages.contains(language) {
3978 return None;
3979 }
3980 }
3981 Some((
3982 excerpt_id,
3983 (
3984 buffer_handle,
3985 buffer.version().clone(),
3986 excerpt_visible_range,
3987 ),
3988 ))
3989 })
3990 .collect()
3991 }
3992
3993 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3994 TextLayoutDetails {
3995 text_system: cx.text_system().clone(),
3996 editor_style: self.style.clone().unwrap(),
3997 rem_size: cx.rem_size(),
3998 scroll_anchor: self.scroll_manager.anchor(),
3999 visible_rows: self.visible_line_count(),
4000 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4001 }
4002 }
4003
4004 fn splice_inlays(
4005 &self,
4006 to_remove: Vec<InlayId>,
4007 to_insert: Vec<Inlay>,
4008 cx: &mut ViewContext<Self>,
4009 ) {
4010 self.display_map.update(cx, |display_map, cx| {
4011 display_map.splice_inlays(to_remove, to_insert, cx);
4012 });
4013 cx.notify();
4014 }
4015
4016 fn trigger_on_type_formatting(
4017 &self,
4018 input: String,
4019 cx: &mut ViewContext<Self>,
4020 ) -> Option<Task<Result<()>>> {
4021 if input.len() != 1 {
4022 return None;
4023 }
4024
4025 let project = self.project.as_ref()?;
4026 let position = self.selections.newest_anchor().head();
4027 let (buffer, buffer_position) = self
4028 .buffer
4029 .read(cx)
4030 .text_anchor_for_position(position, cx)?;
4031
4032 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4033 // hence we do LSP request & edit on host side only — add formats to host's history.
4034 let push_to_lsp_host_history = true;
4035 // If this is not the host, append its history with new edits.
4036 let push_to_client_history = project.read(cx).is_remote();
4037
4038 let on_type_formatting = project.update(cx, |project, cx| {
4039 project.on_type_format(
4040 buffer.clone(),
4041 buffer_position,
4042 input,
4043 push_to_lsp_host_history,
4044 cx,
4045 )
4046 });
4047 Some(cx.spawn(|editor, mut cx| async move {
4048 if let Some(transaction) = on_type_formatting.await? {
4049 if push_to_client_history {
4050 buffer
4051 .update(&mut cx, |buffer, _| {
4052 buffer.push_transaction(transaction, Instant::now());
4053 })
4054 .ok();
4055 }
4056 editor.update(&mut cx, |editor, cx| {
4057 editor.refresh_document_highlights(cx);
4058 })?;
4059 }
4060 Ok(())
4061 }))
4062 }
4063
4064 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4065 if self.pending_rename.is_some() {
4066 return;
4067 }
4068
4069 let Some(provider) = self.completion_provider.as_ref() else {
4070 return;
4071 };
4072
4073 let position = self.selections.newest_anchor().head();
4074 let (buffer, buffer_position) =
4075 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4076 output
4077 } else {
4078 return;
4079 };
4080
4081 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4082 let is_followup_invoke = {
4083 let context_menu_state = self.context_menu.read();
4084 matches!(
4085 context_menu_state.deref(),
4086 Some(ContextMenu::Completions(_))
4087 )
4088 };
4089 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4090 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4091 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4092 CompletionTriggerKind::TRIGGER_CHARACTER
4093 }
4094
4095 _ => CompletionTriggerKind::INVOKED,
4096 };
4097 let completion_context = CompletionContext {
4098 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4099 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4100 Some(String::from(trigger))
4101 } else {
4102 None
4103 }
4104 }),
4105 trigger_kind,
4106 };
4107 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4108
4109 let id = post_inc(&mut self.next_completion_id);
4110 let task = cx.spawn(|this, mut cx| {
4111 async move {
4112 this.update(&mut cx, |this, _| {
4113 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4114 })?;
4115 let completions = completions.await.log_err();
4116 let menu = if let Some(completions) = completions {
4117 let mut menu = CompletionsMenu {
4118 id,
4119 initial_position: position,
4120 match_candidates: completions
4121 .iter()
4122 .enumerate()
4123 .map(|(id, completion)| {
4124 StringMatchCandidate::new(
4125 id,
4126 completion.label.text[completion.label.filter_range.clone()]
4127 .into(),
4128 )
4129 })
4130 .collect(),
4131 buffer: buffer.clone(),
4132 completions: Arc::new(RwLock::new(completions.into())),
4133 matches: Vec::new().into(),
4134 selected_item: 0,
4135 scroll_handle: UniformListScrollHandle::new(),
4136 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4137 DebouncedDelay::new(),
4138 )),
4139 };
4140 menu.filter(query.as_deref(), cx.background_executor().clone())
4141 .await;
4142
4143 if menu.matches.is_empty() {
4144 None
4145 } else {
4146 this.update(&mut cx, |editor, cx| {
4147 let completions = menu.completions.clone();
4148 let matches = menu.matches.clone();
4149
4150 let delay_ms = EditorSettings::get_global(cx)
4151 .completion_documentation_secondary_query_debounce;
4152 let delay = Duration::from_millis(delay_ms);
4153 editor
4154 .completion_documentation_pre_resolve_debounce
4155 .fire_new(delay, cx, |editor, cx| {
4156 CompletionsMenu::pre_resolve_completion_documentation(
4157 buffer,
4158 completions,
4159 matches,
4160 editor,
4161 cx,
4162 )
4163 });
4164 })
4165 .ok();
4166 Some(menu)
4167 }
4168 } else {
4169 None
4170 };
4171
4172 this.update(&mut cx, |this, cx| {
4173 let mut context_menu = this.context_menu.write();
4174 match context_menu.as_ref() {
4175 None => {}
4176
4177 Some(ContextMenu::Completions(prev_menu)) => {
4178 if prev_menu.id > id {
4179 return;
4180 }
4181 }
4182
4183 _ => return,
4184 }
4185
4186 if this.focus_handle.is_focused(cx) && menu.is_some() {
4187 let menu = menu.unwrap();
4188 *context_menu = Some(ContextMenu::Completions(menu));
4189 drop(context_menu);
4190 this.discard_inline_completion(false, cx);
4191 cx.notify();
4192 } else if this.completion_tasks.len() <= 1 {
4193 // If there are no more completion tasks and the last menu was
4194 // empty, we should hide it. If it was already hidden, we should
4195 // also show the copilot completion when available.
4196 drop(context_menu);
4197 if this.hide_context_menu(cx).is_none() {
4198 this.update_visible_inline_completion(cx);
4199 }
4200 }
4201 })?;
4202
4203 Ok::<_, anyhow::Error>(())
4204 }
4205 .log_err()
4206 });
4207
4208 self.completion_tasks.push((id, task));
4209 }
4210
4211 pub fn confirm_completion(
4212 &mut self,
4213 action: &ConfirmCompletion,
4214 cx: &mut ViewContext<Self>,
4215 ) -> Option<Task<Result<()>>> {
4216 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4217 }
4218
4219 pub fn compose_completion(
4220 &mut self,
4221 action: &ComposeCompletion,
4222 cx: &mut ViewContext<Self>,
4223 ) -> Option<Task<Result<()>>> {
4224 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4225 }
4226
4227 fn do_completion(
4228 &mut self,
4229 item_ix: Option<usize>,
4230 intent: CompletionIntent,
4231 cx: &mut ViewContext<Editor>,
4232 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4233 use language::ToOffset as _;
4234
4235 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4236 menu
4237 } else {
4238 return None;
4239 };
4240
4241 let mat = completions_menu
4242 .matches
4243 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4244 let buffer_handle = completions_menu.buffer;
4245 let completions = completions_menu.completions.read();
4246 let completion = completions.get(mat.candidate_id)?;
4247 cx.stop_propagation();
4248
4249 let snippet;
4250 let text;
4251
4252 if completion.is_snippet() {
4253 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4254 text = snippet.as_ref().unwrap().text.clone();
4255 } else {
4256 snippet = None;
4257 text = completion.new_text.clone();
4258 };
4259 let selections = self.selections.all::<usize>(cx);
4260 let buffer = buffer_handle.read(cx);
4261 let old_range = completion.old_range.to_offset(buffer);
4262 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4263
4264 let newest_selection = self.selections.newest_anchor();
4265 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4266 return None;
4267 }
4268
4269 let lookbehind = newest_selection
4270 .start
4271 .text_anchor
4272 .to_offset(buffer)
4273 .saturating_sub(old_range.start);
4274 let lookahead = old_range
4275 .end
4276 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4277 let mut common_prefix_len = old_text
4278 .bytes()
4279 .zip(text.bytes())
4280 .take_while(|(a, b)| a == b)
4281 .count();
4282
4283 let snapshot = self.buffer.read(cx).snapshot(cx);
4284 let mut range_to_replace: Option<Range<isize>> = None;
4285 let mut ranges = Vec::new();
4286 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4287 for selection in &selections {
4288 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4289 let start = selection.start.saturating_sub(lookbehind);
4290 let end = selection.end + lookahead;
4291 if selection.id == newest_selection.id {
4292 range_to_replace = Some(
4293 ((start + common_prefix_len) as isize - selection.start as isize)
4294 ..(end as isize - selection.start as isize),
4295 );
4296 }
4297 ranges.push(start + common_prefix_len..end);
4298 } else {
4299 common_prefix_len = 0;
4300 ranges.clear();
4301 ranges.extend(selections.iter().map(|s| {
4302 if s.id == newest_selection.id {
4303 range_to_replace = Some(
4304 old_range.start.to_offset_utf16(&snapshot).0 as isize
4305 - selection.start as isize
4306 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4307 - selection.start as isize,
4308 );
4309 old_range.clone()
4310 } else {
4311 s.start..s.end
4312 }
4313 }));
4314 break;
4315 }
4316 if !self.linked_edit_ranges.is_empty() {
4317 let start_anchor = snapshot.anchor_before(selection.head());
4318 let end_anchor = snapshot.anchor_after(selection.tail());
4319 if let Some(ranges) = self
4320 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4321 {
4322 for (buffer, edits) in ranges {
4323 linked_edits.entry(buffer.clone()).or_default().extend(
4324 edits
4325 .into_iter()
4326 .map(|range| (range, text[common_prefix_len..].to_owned())),
4327 );
4328 }
4329 }
4330 }
4331 }
4332 let text = &text[common_prefix_len..];
4333
4334 cx.emit(EditorEvent::InputHandled {
4335 utf16_range_to_replace: range_to_replace,
4336 text: text.into(),
4337 });
4338
4339 self.transact(cx, |this, cx| {
4340 if let Some(mut snippet) = snippet {
4341 snippet.text = text.to_string();
4342 for tabstop in snippet.tabstops.iter_mut().flatten() {
4343 tabstop.start -= common_prefix_len as isize;
4344 tabstop.end -= common_prefix_len as isize;
4345 }
4346
4347 this.insert_snippet(&ranges, snippet, cx).log_err();
4348 } else {
4349 this.buffer.update(cx, |buffer, cx| {
4350 buffer.edit(
4351 ranges.iter().map(|range| (range.clone(), text)),
4352 this.autoindent_mode.clone(),
4353 cx,
4354 );
4355 });
4356 }
4357 for (buffer, edits) in linked_edits {
4358 buffer.update(cx, |buffer, cx| {
4359 let snapshot = buffer.snapshot();
4360 let edits = edits
4361 .into_iter()
4362 .map(|(range, text)| {
4363 use text::ToPoint as TP;
4364 let end_point = TP::to_point(&range.end, &snapshot);
4365 let start_point = TP::to_point(&range.start, &snapshot);
4366 (start_point..end_point, text)
4367 })
4368 .sorted_by_key(|(range, _)| range.start)
4369 .collect::<Vec<_>>();
4370 buffer.edit(edits, None, cx);
4371 })
4372 }
4373
4374 this.refresh_inline_completion(true, cx);
4375 });
4376
4377 if let Some(confirm) = completion.confirm.as_ref() {
4378 (confirm)(intent, cx);
4379 }
4380
4381 if completion.show_new_completions_on_confirm {
4382 self.show_completions(&ShowCompletions { trigger: None }, cx);
4383 }
4384
4385 let provider = self.completion_provider.as_ref()?;
4386 let apply_edits = provider.apply_additional_edits_for_completion(
4387 buffer_handle,
4388 completion.clone(),
4389 true,
4390 cx,
4391 );
4392
4393 let editor_settings = EditorSettings::get_global(cx);
4394 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4395 // After the code completion is finished, users often want to know what signatures are needed.
4396 // so we should automatically call signature_help
4397 self.show_signature_help(&ShowSignatureHelp, cx);
4398 }
4399
4400 Some(cx.foreground_executor().spawn(async move {
4401 apply_edits.await?;
4402 Ok(())
4403 }))
4404 }
4405
4406 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4407 let mut context_menu = self.context_menu.write();
4408 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4409 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4410 // Toggle if we're selecting the same one
4411 *context_menu = None;
4412 cx.notify();
4413 return;
4414 } else {
4415 // Otherwise, clear it and start a new one
4416 *context_menu = None;
4417 cx.notify();
4418 }
4419 }
4420 drop(context_menu);
4421 let snapshot = self.snapshot(cx);
4422 let deployed_from_indicator = action.deployed_from_indicator;
4423 let mut task = self.code_actions_task.take();
4424 let action = action.clone();
4425 cx.spawn(|editor, mut cx| async move {
4426 while let Some(prev_task) = task {
4427 prev_task.await;
4428 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4429 }
4430
4431 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4432 if editor.focus_handle.is_focused(cx) {
4433 let multibuffer_point = action
4434 .deployed_from_indicator
4435 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4436 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4437 let (buffer, buffer_row) = snapshot
4438 .buffer_snapshot
4439 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4440 .and_then(|(buffer_snapshot, range)| {
4441 editor
4442 .buffer
4443 .read(cx)
4444 .buffer(buffer_snapshot.remote_id())
4445 .map(|buffer| (buffer, range.start.row))
4446 })?;
4447 let (_, code_actions) = editor
4448 .available_code_actions
4449 .clone()
4450 .and_then(|(location, code_actions)| {
4451 let snapshot = location.buffer.read(cx).snapshot();
4452 let point_range = location.range.to_point(&snapshot);
4453 let point_range = point_range.start.row..=point_range.end.row;
4454 if point_range.contains(&buffer_row) {
4455 Some((location, code_actions))
4456 } else {
4457 None
4458 }
4459 })
4460 .unzip();
4461 let buffer_id = buffer.read(cx).remote_id();
4462 let tasks = editor
4463 .tasks
4464 .get(&(buffer_id, buffer_row))
4465 .map(|t| Arc::new(t.to_owned()));
4466 if tasks.is_none() && code_actions.is_none() {
4467 return None;
4468 }
4469
4470 editor.completion_tasks.clear();
4471 editor.discard_inline_completion(false, cx);
4472 let task_context =
4473 tasks
4474 .as_ref()
4475 .zip(editor.project.clone())
4476 .map(|(tasks, project)| {
4477 let position = Point::new(buffer_row, tasks.column);
4478 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4479 let location = Location {
4480 buffer: buffer.clone(),
4481 range: range_start..range_start,
4482 };
4483 // Fill in the environmental variables from the tree-sitter captures
4484 let mut captured_task_variables = TaskVariables::default();
4485 for (capture_name, value) in tasks.extra_variables.clone() {
4486 captured_task_variables.insert(
4487 task::VariableName::Custom(capture_name.into()),
4488 value.clone(),
4489 );
4490 }
4491 project.update(cx, |project, cx| {
4492 project.task_context_for_location(
4493 captured_task_variables,
4494 location,
4495 cx,
4496 )
4497 })
4498 });
4499
4500 Some(cx.spawn(|editor, mut cx| async move {
4501 let task_context = match task_context {
4502 Some(task_context) => task_context.await,
4503 None => None,
4504 };
4505 let resolved_tasks =
4506 tasks.zip(task_context).map(|(tasks, task_context)| {
4507 Arc::new(ResolvedTasks {
4508 templates: tasks
4509 .templates
4510 .iter()
4511 .filter_map(|(kind, template)| {
4512 template
4513 .resolve_task(&kind.to_id_base(), &task_context)
4514 .map(|task| (kind.clone(), task))
4515 })
4516 .collect(),
4517 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4518 multibuffer_point.row,
4519 tasks.column,
4520 )),
4521 })
4522 });
4523 let spawn_straight_away = resolved_tasks
4524 .as_ref()
4525 .map_or(false, |tasks| tasks.templates.len() == 1)
4526 && code_actions
4527 .as_ref()
4528 .map_or(true, |actions| actions.is_empty());
4529 if let Some(task) = editor
4530 .update(&mut cx, |editor, cx| {
4531 *editor.context_menu.write() =
4532 Some(ContextMenu::CodeActions(CodeActionsMenu {
4533 buffer,
4534 actions: CodeActionContents {
4535 tasks: resolved_tasks,
4536 actions: code_actions,
4537 },
4538 selected_item: Default::default(),
4539 scroll_handle: UniformListScrollHandle::default(),
4540 deployed_from_indicator,
4541 }));
4542 if spawn_straight_away {
4543 if let Some(task) = editor.confirm_code_action(
4544 &ConfirmCodeAction { item_ix: Some(0) },
4545 cx,
4546 ) {
4547 cx.notify();
4548 return task;
4549 }
4550 }
4551 cx.notify();
4552 Task::ready(Ok(()))
4553 })
4554 .ok()
4555 {
4556 task.await
4557 } else {
4558 Ok(())
4559 }
4560 }))
4561 } else {
4562 Some(Task::ready(Ok(())))
4563 }
4564 })?;
4565 if let Some(task) = spawned_test_task {
4566 task.await?;
4567 }
4568
4569 Ok::<_, anyhow::Error>(())
4570 })
4571 .detach_and_log_err(cx);
4572 }
4573
4574 pub fn confirm_code_action(
4575 &mut self,
4576 action: &ConfirmCodeAction,
4577 cx: &mut ViewContext<Self>,
4578 ) -> Option<Task<Result<()>>> {
4579 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4580 menu
4581 } else {
4582 return None;
4583 };
4584 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4585 let action = actions_menu.actions.get(action_ix)?;
4586 let title = action.label();
4587 let buffer = actions_menu.buffer;
4588 let workspace = self.workspace()?;
4589
4590 match action {
4591 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4592 workspace.update(cx, |workspace, cx| {
4593 workspace::tasks::schedule_resolved_task(
4594 workspace,
4595 task_source_kind,
4596 resolved_task,
4597 false,
4598 cx,
4599 );
4600
4601 Some(Task::ready(Ok(())))
4602 })
4603 }
4604 CodeActionsItem::CodeAction(action) => {
4605 let apply_code_actions = workspace
4606 .read(cx)
4607 .project()
4608 .clone()
4609 .update(cx, |project, cx| {
4610 project.apply_code_action(buffer, action, true, cx)
4611 });
4612 let workspace = workspace.downgrade();
4613 Some(cx.spawn(|editor, cx| async move {
4614 let project_transaction = apply_code_actions.await?;
4615 Self::open_project_transaction(
4616 &editor,
4617 workspace,
4618 project_transaction,
4619 title,
4620 cx,
4621 )
4622 .await
4623 }))
4624 }
4625 }
4626 }
4627
4628 pub async fn open_project_transaction(
4629 this: &WeakView<Editor>,
4630 workspace: WeakView<Workspace>,
4631 transaction: ProjectTransaction,
4632 title: String,
4633 mut cx: AsyncWindowContext,
4634 ) -> Result<()> {
4635 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4636
4637 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4638 cx.update(|cx| {
4639 entries.sort_unstable_by_key(|(buffer, _)| {
4640 buffer.read(cx).file().map(|f| f.path().clone())
4641 });
4642 })?;
4643
4644 // If the project transaction's edits are all contained within this editor, then
4645 // avoid opening a new editor to display them.
4646
4647 if let Some((buffer, transaction)) = entries.first() {
4648 if entries.len() == 1 {
4649 let excerpt = this.update(&mut cx, |editor, cx| {
4650 editor
4651 .buffer()
4652 .read(cx)
4653 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4654 })?;
4655 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4656 if excerpted_buffer == *buffer {
4657 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4658 let excerpt_range = excerpt_range.to_offset(buffer);
4659 buffer
4660 .edited_ranges_for_transaction::<usize>(transaction)
4661 .all(|range| {
4662 excerpt_range.start <= range.start
4663 && excerpt_range.end >= range.end
4664 })
4665 })?;
4666
4667 if all_edits_within_excerpt {
4668 return Ok(());
4669 }
4670 }
4671 }
4672 }
4673 } else {
4674 return Ok(());
4675 }
4676
4677 let mut ranges_to_highlight = Vec::new();
4678 let excerpt_buffer = cx.new_model(|cx| {
4679 let mut multibuffer =
4680 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4681 for (buffer_handle, transaction) in &entries {
4682 let buffer = buffer_handle.read(cx);
4683 ranges_to_highlight.extend(
4684 multibuffer.push_excerpts_with_context_lines(
4685 buffer_handle.clone(),
4686 buffer
4687 .edited_ranges_for_transaction::<usize>(transaction)
4688 .collect(),
4689 DEFAULT_MULTIBUFFER_CONTEXT,
4690 cx,
4691 ),
4692 );
4693 }
4694 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4695 multibuffer
4696 })?;
4697
4698 workspace.update(&mut cx, |workspace, cx| {
4699 let project = workspace.project().clone();
4700 let editor =
4701 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4702 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4703 editor.update(cx, |editor, cx| {
4704 editor.highlight_background::<Self>(
4705 &ranges_to_highlight,
4706 |theme| theme.editor_highlighted_line_background,
4707 cx,
4708 );
4709 });
4710 })?;
4711
4712 Ok(())
4713 }
4714
4715 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4716 let project = self.project.clone()?;
4717 let buffer = self.buffer.read(cx);
4718 let newest_selection = self.selections.newest_anchor().clone();
4719 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4720 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4721 if start_buffer != end_buffer {
4722 return None;
4723 }
4724
4725 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4726 cx.background_executor()
4727 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4728 .await;
4729
4730 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4731 project.code_actions(&start_buffer, start..end, cx)
4732 }) {
4733 code_actions.await
4734 } else {
4735 Vec::new()
4736 };
4737
4738 this.update(&mut cx, |this, cx| {
4739 this.available_code_actions = if actions.is_empty() {
4740 None
4741 } else {
4742 Some((
4743 Location {
4744 buffer: start_buffer,
4745 range: start..end,
4746 },
4747 actions.into(),
4748 ))
4749 };
4750 cx.notify();
4751 })
4752 .log_err();
4753 }));
4754 None
4755 }
4756
4757 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4758 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4759 self.show_git_blame_inline = false;
4760
4761 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4762 cx.background_executor().timer(delay).await;
4763
4764 this.update(&mut cx, |this, cx| {
4765 this.show_git_blame_inline = true;
4766 cx.notify();
4767 })
4768 .log_err();
4769 }));
4770 }
4771 }
4772
4773 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4774 if self.pending_rename.is_some() {
4775 return None;
4776 }
4777
4778 let project = self.project.clone()?;
4779 let buffer = self.buffer.read(cx);
4780 let newest_selection = self.selections.newest_anchor().clone();
4781 let cursor_position = newest_selection.head();
4782 let (cursor_buffer, cursor_buffer_position) =
4783 buffer.text_anchor_for_position(cursor_position, cx)?;
4784 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4785 if cursor_buffer != tail_buffer {
4786 return None;
4787 }
4788
4789 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4790 cx.background_executor()
4791 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4792 .await;
4793
4794 let highlights = if let Some(highlights) = project
4795 .update(&mut cx, |project, cx| {
4796 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4797 })
4798 .log_err()
4799 {
4800 highlights.await.log_err()
4801 } else {
4802 None
4803 };
4804
4805 if let Some(highlights) = highlights {
4806 this.update(&mut cx, |this, cx| {
4807 if this.pending_rename.is_some() {
4808 return;
4809 }
4810
4811 let buffer_id = cursor_position.buffer_id;
4812 let buffer = this.buffer.read(cx);
4813 if !buffer
4814 .text_anchor_for_position(cursor_position, cx)
4815 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4816 {
4817 return;
4818 }
4819
4820 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4821 let mut write_ranges = Vec::new();
4822 let mut read_ranges = Vec::new();
4823 for highlight in highlights {
4824 for (excerpt_id, excerpt_range) in
4825 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4826 {
4827 let start = highlight
4828 .range
4829 .start
4830 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4831 let end = highlight
4832 .range
4833 .end
4834 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4835 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4836 continue;
4837 }
4838
4839 let range = Anchor {
4840 buffer_id,
4841 excerpt_id: excerpt_id,
4842 text_anchor: start,
4843 }..Anchor {
4844 buffer_id,
4845 excerpt_id,
4846 text_anchor: end,
4847 };
4848 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4849 write_ranges.push(range);
4850 } else {
4851 read_ranges.push(range);
4852 }
4853 }
4854 }
4855
4856 this.highlight_background::<DocumentHighlightRead>(
4857 &read_ranges,
4858 |theme| theme.editor_document_highlight_read_background,
4859 cx,
4860 );
4861 this.highlight_background::<DocumentHighlightWrite>(
4862 &write_ranges,
4863 |theme| theme.editor_document_highlight_write_background,
4864 cx,
4865 );
4866 cx.notify();
4867 })
4868 .log_err();
4869 }
4870 }));
4871 None
4872 }
4873
4874 fn refresh_inline_completion(
4875 &mut self,
4876 debounce: bool,
4877 cx: &mut ViewContext<Self>,
4878 ) -> Option<()> {
4879 let provider = self.inline_completion_provider()?;
4880 let cursor = self.selections.newest_anchor().head();
4881 let (buffer, cursor_buffer_position) =
4882 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4883 if !self.show_inline_completions
4884 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4885 {
4886 self.discard_inline_completion(false, cx);
4887 return None;
4888 }
4889
4890 self.update_visible_inline_completion(cx);
4891 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4892 Some(())
4893 }
4894
4895 fn cycle_inline_completion(
4896 &mut self,
4897 direction: Direction,
4898 cx: &mut ViewContext<Self>,
4899 ) -> Option<()> {
4900 let provider = self.inline_completion_provider()?;
4901 let cursor = self.selections.newest_anchor().head();
4902 let (buffer, cursor_buffer_position) =
4903 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4904 if !self.show_inline_completions
4905 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4906 {
4907 return None;
4908 }
4909
4910 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4911 self.update_visible_inline_completion(cx);
4912
4913 Some(())
4914 }
4915
4916 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4917 if !self.has_active_inline_completion(cx) {
4918 self.refresh_inline_completion(false, cx);
4919 return;
4920 }
4921
4922 self.update_visible_inline_completion(cx);
4923 }
4924
4925 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4926 self.show_cursor_names(cx);
4927 }
4928
4929 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4930 self.show_cursor_names = true;
4931 cx.notify();
4932 cx.spawn(|this, mut cx| async move {
4933 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4934 this.update(&mut cx, |this, cx| {
4935 this.show_cursor_names = false;
4936 cx.notify()
4937 })
4938 .ok()
4939 })
4940 .detach();
4941 }
4942
4943 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4944 if self.has_active_inline_completion(cx) {
4945 self.cycle_inline_completion(Direction::Next, cx);
4946 } else {
4947 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4948 if is_copilot_disabled {
4949 cx.propagate();
4950 }
4951 }
4952 }
4953
4954 pub fn previous_inline_completion(
4955 &mut self,
4956 _: &PreviousInlineCompletion,
4957 cx: &mut ViewContext<Self>,
4958 ) {
4959 if self.has_active_inline_completion(cx) {
4960 self.cycle_inline_completion(Direction::Prev, cx);
4961 } else {
4962 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4963 if is_copilot_disabled {
4964 cx.propagate();
4965 }
4966 }
4967 }
4968
4969 pub fn accept_inline_completion(
4970 &mut self,
4971 _: &AcceptInlineCompletion,
4972 cx: &mut ViewContext<Self>,
4973 ) {
4974 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4975 return;
4976 };
4977 if let Some(provider) = self.inline_completion_provider() {
4978 provider.accept(cx);
4979 }
4980
4981 cx.emit(EditorEvent::InputHandled {
4982 utf16_range_to_replace: None,
4983 text: completion.text.to_string().into(),
4984 });
4985
4986 if let Some(range) = delete_range {
4987 self.change_selections(None, cx, |s| s.select_ranges([range]))
4988 }
4989 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4990 self.refresh_inline_completion(true, cx);
4991 cx.notify();
4992 }
4993
4994 pub fn accept_partial_inline_completion(
4995 &mut self,
4996 _: &AcceptPartialInlineCompletion,
4997 cx: &mut ViewContext<Self>,
4998 ) {
4999 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5000 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5001 let mut partial_completion = completion
5002 .text
5003 .chars()
5004 .by_ref()
5005 .take_while(|c| c.is_alphabetic())
5006 .collect::<String>();
5007 if partial_completion.is_empty() {
5008 partial_completion = completion
5009 .text
5010 .chars()
5011 .by_ref()
5012 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5013 .collect::<String>();
5014 }
5015
5016 cx.emit(EditorEvent::InputHandled {
5017 utf16_range_to_replace: None,
5018 text: partial_completion.clone().into(),
5019 });
5020
5021 if let Some(range) = delete_range {
5022 self.change_selections(None, cx, |s| s.select_ranges([range]))
5023 }
5024 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5025
5026 self.refresh_inline_completion(true, cx);
5027 cx.notify();
5028 }
5029 }
5030 }
5031
5032 fn discard_inline_completion(
5033 &mut self,
5034 should_report_inline_completion_event: bool,
5035 cx: &mut ViewContext<Self>,
5036 ) -> bool {
5037 if let Some(provider) = self.inline_completion_provider() {
5038 provider.discard(should_report_inline_completion_event, cx);
5039 }
5040
5041 self.take_active_inline_completion(cx).is_some()
5042 }
5043
5044 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5045 if let Some(completion) = self.active_inline_completion.as_ref() {
5046 let buffer = self.buffer.read(cx).read(cx);
5047 completion.0.position.is_valid(&buffer)
5048 } else {
5049 false
5050 }
5051 }
5052
5053 fn take_active_inline_completion(
5054 &mut self,
5055 cx: &mut ViewContext<Self>,
5056 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5057 let completion = self.active_inline_completion.take()?;
5058 self.display_map.update(cx, |map, cx| {
5059 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5060 });
5061 let buffer = self.buffer.read(cx).read(cx);
5062
5063 if completion.0.position.is_valid(&buffer) {
5064 Some(completion)
5065 } else {
5066 None
5067 }
5068 }
5069
5070 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5071 let selection = self.selections.newest_anchor();
5072 let cursor = selection.head();
5073
5074 let excerpt_id = cursor.excerpt_id;
5075
5076 if self.context_menu.read().is_none()
5077 && self.completion_tasks.is_empty()
5078 && selection.start == selection.end
5079 {
5080 if let Some(provider) = self.inline_completion_provider() {
5081 if let Some((buffer, cursor_buffer_position)) =
5082 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5083 {
5084 if let Some((text, text_anchor_range)) =
5085 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5086 {
5087 let text = Rope::from(text);
5088 let mut to_remove = Vec::new();
5089 if let Some(completion) = self.active_inline_completion.take() {
5090 to_remove.push(completion.0.id);
5091 }
5092
5093 let completion_inlay =
5094 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5095
5096 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5097 let snapshot = self.buffer.read(cx).snapshot(cx);
5098 Some(
5099 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5100 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5101 )
5102 });
5103 self.active_inline_completion =
5104 Some((completion_inlay.clone(), multibuffer_anchor_range));
5105
5106 self.display_map.update(cx, move |map, cx| {
5107 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5108 });
5109 cx.notify();
5110 return;
5111 }
5112 }
5113 }
5114 }
5115
5116 self.discard_inline_completion(false, cx);
5117 }
5118
5119 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5120 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5121 }
5122
5123 fn render_code_actions_indicator(
5124 &self,
5125 _style: &EditorStyle,
5126 row: DisplayRow,
5127 is_active: bool,
5128 cx: &mut ViewContext<Self>,
5129 ) -> Option<IconButton> {
5130 if self.available_code_actions.is_some() {
5131 Some(
5132 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5133 .shape(ui::IconButtonShape::Square)
5134 .icon_size(IconSize::XSmall)
5135 .icon_color(Color::Muted)
5136 .selected(is_active)
5137 .on_click(cx.listener(move |editor, _e, cx| {
5138 editor.focus(cx);
5139 editor.toggle_code_actions(
5140 &ToggleCodeActions {
5141 deployed_from_indicator: Some(row),
5142 },
5143 cx,
5144 );
5145 })),
5146 )
5147 } else {
5148 None
5149 }
5150 }
5151
5152 fn clear_tasks(&mut self) {
5153 self.tasks.clear()
5154 }
5155
5156 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5157 if let Some(_) = self.tasks.insert(key, value) {
5158 // This case should hopefully be rare, but just in case...
5159 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5160 }
5161 }
5162
5163 fn render_run_indicator(
5164 &self,
5165 _style: &EditorStyle,
5166 is_active: bool,
5167 row: DisplayRow,
5168 cx: &mut ViewContext<Self>,
5169 ) -> IconButton {
5170 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5171 .shape(ui::IconButtonShape::Square)
5172 .icon_size(IconSize::XSmall)
5173 .icon_color(Color::Muted)
5174 .selected(is_active)
5175 .on_click(cx.listener(move |editor, _e, cx| {
5176 editor.focus(cx);
5177 editor.toggle_code_actions(
5178 &ToggleCodeActions {
5179 deployed_from_indicator: Some(row),
5180 },
5181 cx,
5182 );
5183 }))
5184 }
5185
5186 fn close_hunk_diff_button(
5187 &self,
5188 hunk: HoveredHunk,
5189 row: DisplayRow,
5190 cx: &mut ViewContext<Self>,
5191 ) -> IconButton {
5192 IconButton::new(
5193 ("close_hunk_diff_indicator", row.0 as usize),
5194 ui::IconName::Close,
5195 )
5196 .shape(ui::IconButtonShape::Square)
5197 .icon_size(IconSize::XSmall)
5198 .icon_color(Color::Muted)
5199 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5200 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5201 }
5202
5203 pub fn context_menu_visible(&self) -> bool {
5204 self.context_menu
5205 .read()
5206 .as_ref()
5207 .map_or(false, |menu| menu.visible())
5208 }
5209
5210 fn render_context_menu(
5211 &self,
5212 cursor_position: DisplayPoint,
5213 style: &EditorStyle,
5214 max_height: Pixels,
5215 cx: &mut ViewContext<Editor>,
5216 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5217 self.context_menu.read().as_ref().map(|menu| {
5218 menu.render(
5219 cursor_position,
5220 style,
5221 max_height,
5222 self.workspace.as_ref().map(|(w, _)| w.clone()),
5223 cx,
5224 )
5225 })
5226 }
5227
5228 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5229 cx.notify();
5230 self.completion_tasks.clear();
5231 let context_menu = self.context_menu.write().take();
5232 if context_menu.is_some() {
5233 self.update_visible_inline_completion(cx);
5234 }
5235 context_menu
5236 }
5237
5238 pub fn insert_snippet(
5239 &mut self,
5240 insertion_ranges: &[Range<usize>],
5241 snippet: Snippet,
5242 cx: &mut ViewContext<Self>,
5243 ) -> Result<()> {
5244 struct Tabstop<T> {
5245 is_end_tabstop: bool,
5246 ranges: Vec<Range<T>>,
5247 }
5248
5249 let tabstops = self.buffer.update(cx, |buffer, cx| {
5250 let snippet_text: Arc<str> = snippet.text.clone().into();
5251 buffer.edit(
5252 insertion_ranges
5253 .iter()
5254 .cloned()
5255 .map(|range| (range, snippet_text.clone())),
5256 Some(AutoindentMode::EachLine),
5257 cx,
5258 );
5259
5260 let snapshot = &*buffer.read(cx);
5261 let snippet = &snippet;
5262 snippet
5263 .tabstops
5264 .iter()
5265 .map(|tabstop| {
5266 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5267 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5268 });
5269 let mut tabstop_ranges = tabstop
5270 .iter()
5271 .flat_map(|tabstop_range| {
5272 let mut delta = 0_isize;
5273 insertion_ranges.iter().map(move |insertion_range| {
5274 let insertion_start = insertion_range.start as isize + delta;
5275 delta +=
5276 snippet.text.len() as isize - insertion_range.len() as isize;
5277
5278 let start = ((insertion_start + tabstop_range.start) as usize)
5279 .min(snapshot.len());
5280 let end = ((insertion_start + tabstop_range.end) as usize)
5281 .min(snapshot.len());
5282 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5283 })
5284 })
5285 .collect::<Vec<_>>();
5286 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5287
5288 Tabstop {
5289 is_end_tabstop,
5290 ranges: tabstop_ranges,
5291 }
5292 })
5293 .collect::<Vec<_>>()
5294 });
5295 if let Some(tabstop) = tabstops.first() {
5296 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5297 s.select_ranges(tabstop.ranges.iter().cloned());
5298 });
5299
5300 // If we're already at the last tabstop and it's at the end of the snippet,
5301 // we're done, we don't need to keep the state around.
5302 if !tabstop.is_end_tabstop {
5303 let ranges = tabstops
5304 .into_iter()
5305 .map(|tabstop| tabstop.ranges)
5306 .collect::<Vec<_>>();
5307 self.snippet_stack.push(SnippetState {
5308 active_index: 0,
5309 ranges,
5310 });
5311 }
5312
5313 // Check whether the just-entered snippet ends with an auto-closable bracket.
5314 if self.autoclose_regions.is_empty() {
5315 let snapshot = self.buffer.read(cx).snapshot(cx);
5316 for selection in &mut self.selections.all::<Point>(cx) {
5317 let selection_head = selection.head();
5318 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5319 continue;
5320 };
5321
5322 let mut bracket_pair = None;
5323 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5324 let prev_chars = snapshot
5325 .reversed_chars_at(selection_head)
5326 .collect::<String>();
5327 for (pair, enabled) in scope.brackets() {
5328 if enabled
5329 && pair.close
5330 && prev_chars.starts_with(pair.start.as_str())
5331 && next_chars.starts_with(pair.end.as_str())
5332 {
5333 bracket_pair = Some(pair.clone());
5334 break;
5335 }
5336 }
5337 if let Some(pair) = bracket_pair {
5338 let start = snapshot.anchor_after(selection_head);
5339 let end = snapshot.anchor_after(selection_head);
5340 self.autoclose_regions.push(AutocloseRegion {
5341 selection_id: selection.id,
5342 range: start..end,
5343 pair,
5344 });
5345 }
5346 }
5347 }
5348 }
5349 Ok(())
5350 }
5351
5352 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5353 self.move_to_snippet_tabstop(Bias::Right, cx)
5354 }
5355
5356 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5357 self.move_to_snippet_tabstop(Bias::Left, cx)
5358 }
5359
5360 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5361 if let Some(mut snippet) = self.snippet_stack.pop() {
5362 match bias {
5363 Bias::Left => {
5364 if snippet.active_index > 0 {
5365 snippet.active_index -= 1;
5366 } else {
5367 self.snippet_stack.push(snippet);
5368 return false;
5369 }
5370 }
5371 Bias::Right => {
5372 if snippet.active_index + 1 < snippet.ranges.len() {
5373 snippet.active_index += 1;
5374 } else {
5375 self.snippet_stack.push(snippet);
5376 return false;
5377 }
5378 }
5379 }
5380 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5381 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5382 s.select_anchor_ranges(current_ranges.iter().cloned())
5383 });
5384 // If snippet state is not at the last tabstop, push it back on the stack
5385 if snippet.active_index + 1 < snippet.ranges.len() {
5386 self.snippet_stack.push(snippet);
5387 }
5388 return true;
5389 }
5390 }
5391
5392 false
5393 }
5394
5395 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5396 self.transact(cx, |this, cx| {
5397 this.select_all(&SelectAll, cx);
5398 this.insert("", cx);
5399 });
5400 }
5401
5402 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5403 self.transact(cx, |this, cx| {
5404 this.select_autoclose_pair(cx);
5405 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5406 if !this.linked_edit_ranges.is_empty() {
5407 let selections = this.selections.all::<MultiBufferPoint>(cx);
5408 let snapshot = this.buffer.read(cx).snapshot(cx);
5409
5410 for selection in selections.iter() {
5411 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5412 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5413 if selection_start.buffer_id != selection_end.buffer_id {
5414 continue;
5415 }
5416 if let Some(ranges) =
5417 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5418 {
5419 for (buffer, entries) in ranges {
5420 linked_ranges.entry(buffer).or_default().extend(entries);
5421 }
5422 }
5423 }
5424 }
5425
5426 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5427 if !this.selections.line_mode {
5428 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5429 for selection in &mut selections {
5430 if selection.is_empty() {
5431 let old_head = selection.head();
5432 let mut new_head =
5433 movement::left(&display_map, old_head.to_display_point(&display_map))
5434 .to_point(&display_map);
5435 if let Some((buffer, line_buffer_range)) = display_map
5436 .buffer_snapshot
5437 .buffer_line_for_row(MultiBufferRow(old_head.row))
5438 {
5439 let indent_size =
5440 buffer.indent_size_for_line(line_buffer_range.start.row);
5441 let indent_len = match indent_size.kind {
5442 IndentKind::Space => {
5443 buffer.settings_at(line_buffer_range.start, cx).tab_size
5444 }
5445 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5446 };
5447 if old_head.column <= indent_size.len && old_head.column > 0 {
5448 let indent_len = indent_len.get();
5449 new_head = cmp::min(
5450 new_head,
5451 MultiBufferPoint::new(
5452 old_head.row,
5453 ((old_head.column - 1) / indent_len) * indent_len,
5454 ),
5455 );
5456 }
5457 }
5458
5459 selection.set_head(new_head, SelectionGoal::None);
5460 }
5461 }
5462 }
5463
5464 this.signature_help_state.set_backspace_pressed(true);
5465 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5466 this.insert("", cx);
5467 let empty_str: Arc<str> = Arc::from("");
5468 for (buffer, edits) in linked_ranges {
5469 let snapshot = buffer.read(cx).snapshot();
5470 use text::ToPoint as TP;
5471
5472 let edits = edits
5473 .into_iter()
5474 .map(|range| {
5475 let end_point = TP::to_point(&range.end, &snapshot);
5476 let mut start_point = TP::to_point(&range.start, &snapshot);
5477
5478 if end_point == start_point {
5479 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5480 .saturating_sub(1);
5481 start_point = TP::to_point(&offset, &snapshot);
5482 };
5483
5484 (start_point..end_point, empty_str.clone())
5485 })
5486 .sorted_by_key(|(range, _)| range.start)
5487 .collect::<Vec<_>>();
5488 buffer.update(cx, |this, cx| {
5489 this.edit(edits, None, cx);
5490 })
5491 }
5492 this.refresh_inline_completion(true, cx);
5493 linked_editing_ranges::refresh_linked_ranges(this, cx);
5494 });
5495 }
5496
5497 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5498 self.transact(cx, |this, cx| {
5499 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5500 let line_mode = s.line_mode;
5501 s.move_with(|map, selection| {
5502 if selection.is_empty() && !line_mode {
5503 let cursor = movement::right(map, selection.head());
5504 selection.end = cursor;
5505 selection.reversed = true;
5506 selection.goal = SelectionGoal::None;
5507 }
5508 })
5509 });
5510 this.insert("", cx);
5511 this.refresh_inline_completion(true, cx);
5512 });
5513 }
5514
5515 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5516 if self.move_to_prev_snippet_tabstop(cx) {
5517 return;
5518 }
5519
5520 self.outdent(&Outdent, cx);
5521 }
5522
5523 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5524 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5525 return;
5526 }
5527
5528 let mut selections = self.selections.all_adjusted(cx);
5529 let buffer = self.buffer.read(cx);
5530 let snapshot = buffer.snapshot(cx);
5531 let rows_iter = selections.iter().map(|s| s.head().row);
5532 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5533
5534 let mut edits = Vec::new();
5535 let mut prev_edited_row = 0;
5536 let mut row_delta = 0;
5537 for selection in &mut selections {
5538 if selection.start.row != prev_edited_row {
5539 row_delta = 0;
5540 }
5541 prev_edited_row = selection.end.row;
5542
5543 // If the selection is non-empty, then increase the indentation of the selected lines.
5544 if !selection.is_empty() {
5545 row_delta =
5546 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5547 continue;
5548 }
5549
5550 // If the selection is empty and the cursor is in the leading whitespace before the
5551 // suggested indentation, then auto-indent the line.
5552 let cursor = selection.head();
5553 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5554 if let Some(suggested_indent) =
5555 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5556 {
5557 if cursor.column < suggested_indent.len
5558 && cursor.column <= current_indent.len
5559 && current_indent.len <= suggested_indent.len
5560 {
5561 selection.start = Point::new(cursor.row, suggested_indent.len);
5562 selection.end = selection.start;
5563 if row_delta == 0 {
5564 edits.extend(Buffer::edit_for_indent_size_adjustment(
5565 cursor.row,
5566 current_indent,
5567 suggested_indent,
5568 ));
5569 row_delta = suggested_indent.len - current_indent.len;
5570 }
5571 continue;
5572 }
5573 }
5574
5575 // Otherwise, insert a hard or soft tab.
5576 let settings = buffer.settings_at(cursor, cx);
5577 let tab_size = if settings.hard_tabs {
5578 IndentSize::tab()
5579 } else {
5580 let tab_size = settings.tab_size.get();
5581 let char_column = snapshot
5582 .text_for_range(Point::new(cursor.row, 0)..cursor)
5583 .flat_map(str::chars)
5584 .count()
5585 + row_delta as usize;
5586 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5587 IndentSize::spaces(chars_to_next_tab_stop)
5588 };
5589 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5590 selection.end = selection.start;
5591 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5592 row_delta += tab_size.len;
5593 }
5594
5595 self.transact(cx, |this, cx| {
5596 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5597 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5598 this.refresh_inline_completion(true, cx);
5599 });
5600 }
5601
5602 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5603 if self.read_only(cx) {
5604 return;
5605 }
5606 let mut selections = self.selections.all::<Point>(cx);
5607 let mut prev_edited_row = 0;
5608 let mut row_delta = 0;
5609 let mut edits = Vec::new();
5610 let buffer = self.buffer.read(cx);
5611 let snapshot = buffer.snapshot(cx);
5612 for selection in &mut selections {
5613 if selection.start.row != prev_edited_row {
5614 row_delta = 0;
5615 }
5616 prev_edited_row = selection.end.row;
5617
5618 row_delta =
5619 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5620 }
5621
5622 self.transact(cx, |this, cx| {
5623 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5624 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5625 });
5626 }
5627
5628 fn indent_selection(
5629 buffer: &MultiBuffer,
5630 snapshot: &MultiBufferSnapshot,
5631 selection: &mut Selection<Point>,
5632 edits: &mut Vec<(Range<Point>, String)>,
5633 delta_for_start_row: u32,
5634 cx: &AppContext,
5635 ) -> u32 {
5636 let settings = buffer.settings_at(selection.start, cx);
5637 let tab_size = settings.tab_size.get();
5638 let indent_kind = if settings.hard_tabs {
5639 IndentKind::Tab
5640 } else {
5641 IndentKind::Space
5642 };
5643 let mut start_row = selection.start.row;
5644 let mut end_row = selection.end.row + 1;
5645
5646 // If a selection ends at the beginning of a line, don't indent
5647 // that last line.
5648 if selection.end.column == 0 && selection.end.row > selection.start.row {
5649 end_row -= 1;
5650 }
5651
5652 // Avoid re-indenting a row that has already been indented by a
5653 // previous selection, but still update this selection's column
5654 // to reflect that indentation.
5655 if delta_for_start_row > 0 {
5656 start_row += 1;
5657 selection.start.column += delta_for_start_row;
5658 if selection.end.row == selection.start.row {
5659 selection.end.column += delta_for_start_row;
5660 }
5661 }
5662
5663 let mut delta_for_end_row = 0;
5664 let has_multiple_rows = start_row + 1 != end_row;
5665 for row in start_row..end_row {
5666 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5667 let indent_delta = match (current_indent.kind, indent_kind) {
5668 (IndentKind::Space, IndentKind::Space) => {
5669 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5670 IndentSize::spaces(columns_to_next_tab_stop)
5671 }
5672 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5673 (_, IndentKind::Tab) => IndentSize::tab(),
5674 };
5675
5676 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5677 0
5678 } else {
5679 selection.start.column
5680 };
5681 let row_start = Point::new(row, start);
5682 edits.push((
5683 row_start..row_start,
5684 indent_delta.chars().collect::<String>(),
5685 ));
5686
5687 // Update this selection's endpoints to reflect the indentation.
5688 if row == selection.start.row {
5689 selection.start.column += indent_delta.len;
5690 }
5691 if row == selection.end.row {
5692 selection.end.column += indent_delta.len;
5693 delta_for_end_row = indent_delta.len;
5694 }
5695 }
5696
5697 if selection.start.row == selection.end.row {
5698 delta_for_start_row + delta_for_end_row
5699 } else {
5700 delta_for_end_row
5701 }
5702 }
5703
5704 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5705 if self.read_only(cx) {
5706 return;
5707 }
5708 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5709 let selections = self.selections.all::<Point>(cx);
5710 let mut deletion_ranges = Vec::new();
5711 let mut last_outdent = None;
5712 {
5713 let buffer = self.buffer.read(cx);
5714 let snapshot = buffer.snapshot(cx);
5715 for selection in &selections {
5716 let settings = buffer.settings_at(selection.start, cx);
5717 let tab_size = settings.tab_size.get();
5718 let mut rows = selection.spanned_rows(false, &display_map);
5719
5720 // Avoid re-outdenting a row that has already been outdented by a
5721 // previous selection.
5722 if let Some(last_row) = last_outdent {
5723 if last_row == rows.start {
5724 rows.start = rows.start.next_row();
5725 }
5726 }
5727 let has_multiple_rows = rows.len() > 1;
5728 for row in rows.iter_rows() {
5729 let indent_size = snapshot.indent_size_for_line(row);
5730 if indent_size.len > 0 {
5731 let deletion_len = match indent_size.kind {
5732 IndentKind::Space => {
5733 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5734 if columns_to_prev_tab_stop == 0 {
5735 tab_size
5736 } else {
5737 columns_to_prev_tab_stop
5738 }
5739 }
5740 IndentKind::Tab => 1,
5741 };
5742 let start = if has_multiple_rows
5743 || deletion_len > selection.start.column
5744 || indent_size.len < selection.start.column
5745 {
5746 0
5747 } else {
5748 selection.start.column - deletion_len
5749 };
5750 deletion_ranges.push(
5751 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5752 );
5753 last_outdent = Some(row);
5754 }
5755 }
5756 }
5757 }
5758
5759 self.transact(cx, |this, cx| {
5760 this.buffer.update(cx, |buffer, cx| {
5761 let empty_str: Arc<str> = Arc::default();
5762 buffer.edit(
5763 deletion_ranges
5764 .into_iter()
5765 .map(|range| (range, empty_str.clone())),
5766 None,
5767 cx,
5768 );
5769 });
5770 let selections = this.selections.all::<usize>(cx);
5771 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5772 });
5773 }
5774
5775 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5776 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5777 let selections = self.selections.all::<Point>(cx);
5778
5779 let mut new_cursors = Vec::new();
5780 let mut edit_ranges = Vec::new();
5781 let mut selections = selections.iter().peekable();
5782 while let Some(selection) = selections.next() {
5783 let mut rows = selection.spanned_rows(false, &display_map);
5784 let goal_display_column = selection.head().to_display_point(&display_map).column();
5785
5786 // Accumulate contiguous regions of rows that we want to delete.
5787 while let Some(next_selection) = selections.peek() {
5788 let next_rows = next_selection.spanned_rows(false, &display_map);
5789 if next_rows.start <= rows.end {
5790 rows.end = next_rows.end;
5791 selections.next().unwrap();
5792 } else {
5793 break;
5794 }
5795 }
5796
5797 let buffer = &display_map.buffer_snapshot;
5798 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5799 let edit_end;
5800 let cursor_buffer_row;
5801 if buffer.max_point().row >= rows.end.0 {
5802 // If there's a line after the range, delete the \n from the end of the row range
5803 // and position the cursor on the next line.
5804 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5805 cursor_buffer_row = rows.end;
5806 } else {
5807 // If there isn't a line after the range, delete the \n from the line before the
5808 // start of the row range and position the cursor there.
5809 edit_start = edit_start.saturating_sub(1);
5810 edit_end = buffer.len();
5811 cursor_buffer_row = rows.start.previous_row();
5812 }
5813
5814 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5815 *cursor.column_mut() =
5816 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5817
5818 new_cursors.push((
5819 selection.id,
5820 buffer.anchor_after(cursor.to_point(&display_map)),
5821 ));
5822 edit_ranges.push(edit_start..edit_end);
5823 }
5824
5825 self.transact(cx, |this, cx| {
5826 let buffer = this.buffer.update(cx, |buffer, cx| {
5827 let empty_str: Arc<str> = Arc::default();
5828 buffer.edit(
5829 edit_ranges
5830 .into_iter()
5831 .map(|range| (range, empty_str.clone())),
5832 None,
5833 cx,
5834 );
5835 buffer.snapshot(cx)
5836 });
5837 let new_selections = new_cursors
5838 .into_iter()
5839 .map(|(id, cursor)| {
5840 let cursor = cursor.to_point(&buffer);
5841 Selection {
5842 id,
5843 start: cursor,
5844 end: cursor,
5845 reversed: false,
5846 goal: SelectionGoal::None,
5847 }
5848 })
5849 .collect();
5850
5851 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5852 s.select(new_selections);
5853 });
5854 });
5855 }
5856
5857 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5858 if self.read_only(cx) {
5859 return;
5860 }
5861 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5862 for selection in self.selections.all::<Point>(cx) {
5863 let start = MultiBufferRow(selection.start.row);
5864 let end = if selection.start.row == selection.end.row {
5865 MultiBufferRow(selection.start.row + 1)
5866 } else {
5867 MultiBufferRow(selection.end.row)
5868 };
5869
5870 if let Some(last_row_range) = row_ranges.last_mut() {
5871 if start <= last_row_range.end {
5872 last_row_range.end = end;
5873 continue;
5874 }
5875 }
5876 row_ranges.push(start..end);
5877 }
5878
5879 let snapshot = self.buffer.read(cx).snapshot(cx);
5880 let mut cursor_positions = Vec::new();
5881 for row_range in &row_ranges {
5882 let anchor = snapshot.anchor_before(Point::new(
5883 row_range.end.previous_row().0,
5884 snapshot.line_len(row_range.end.previous_row()),
5885 ));
5886 cursor_positions.push(anchor..anchor);
5887 }
5888
5889 self.transact(cx, |this, cx| {
5890 for row_range in row_ranges.into_iter().rev() {
5891 for row in row_range.iter_rows().rev() {
5892 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5893 let next_line_row = row.next_row();
5894 let indent = snapshot.indent_size_for_line(next_line_row);
5895 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5896
5897 let replace = if snapshot.line_len(next_line_row) > indent.len {
5898 " "
5899 } else {
5900 ""
5901 };
5902
5903 this.buffer.update(cx, |buffer, cx| {
5904 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5905 });
5906 }
5907 }
5908
5909 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5910 s.select_anchor_ranges(cursor_positions)
5911 });
5912 });
5913 }
5914
5915 pub fn sort_lines_case_sensitive(
5916 &mut self,
5917 _: &SortLinesCaseSensitive,
5918 cx: &mut ViewContext<Self>,
5919 ) {
5920 self.manipulate_lines(cx, |lines| lines.sort())
5921 }
5922
5923 pub fn sort_lines_case_insensitive(
5924 &mut self,
5925 _: &SortLinesCaseInsensitive,
5926 cx: &mut ViewContext<Self>,
5927 ) {
5928 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5929 }
5930
5931 pub fn unique_lines_case_insensitive(
5932 &mut self,
5933 _: &UniqueLinesCaseInsensitive,
5934 cx: &mut ViewContext<Self>,
5935 ) {
5936 self.manipulate_lines(cx, |lines| {
5937 let mut seen = HashSet::default();
5938 lines.retain(|line| seen.insert(line.to_lowercase()));
5939 })
5940 }
5941
5942 pub fn unique_lines_case_sensitive(
5943 &mut self,
5944 _: &UniqueLinesCaseSensitive,
5945 cx: &mut ViewContext<Self>,
5946 ) {
5947 self.manipulate_lines(cx, |lines| {
5948 let mut seen = HashSet::default();
5949 lines.retain(|line| seen.insert(*line));
5950 })
5951 }
5952
5953 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5954 let mut revert_changes = HashMap::default();
5955 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5956 for hunk in hunks_for_rows(
5957 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
5958 &multi_buffer_snapshot,
5959 ) {
5960 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
5961 }
5962 if !revert_changes.is_empty() {
5963 self.transact(cx, |editor, cx| {
5964 editor.revert(revert_changes, cx);
5965 });
5966 }
5967 }
5968
5969 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5970 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5971 if !revert_changes.is_empty() {
5972 self.transact(cx, |editor, cx| {
5973 editor.revert(revert_changes, cx);
5974 });
5975 }
5976 }
5977
5978 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5979 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5980 let project_path = buffer.read(cx).project_path(cx)?;
5981 let project = self.project.as_ref()?.read(cx);
5982 let entry = project.entry_for_path(&project_path, cx)?;
5983 let abs_path = project.absolute_path(&project_path, cx)?;
5984 let parent = if entry.is_symlink {
5985 abs_path.canonicalize().ok()?
5986 } else {
5987 abs_path
5988 }
5989 .parent()?
5990 .to_path_buf();
5991 Some(parent)
5992 }) {
5993 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5994 }
5995 }
5996
5997 fn gather_revert_changes(
5998 &mut self,
5999 selections: &[Selection<Anchor>],
6000 cx: &mut ViewContext<'_, Editor>,
6001 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6002 let mut revert_changes = HashMap::default();
6003 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6004 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6005 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6006 }
6007 revert_changes
6008 }
6009
6010 pub fn prepare_revert_change(
6011 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6012 multi_buffer: &Model<MultiBuffer>,
6013 hunk: &DiffHunk<MultiBufferRow>,
6014 cx: &AppContext,
6015 ) -> Option<()> {
6016 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6017 let buffer = buffer.read(cx);
6018 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6019 let buffer_snapshot = buffer.snapshot();
6020 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6021 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6022 probe
6023 .0
6024 .start
6025 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6026 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6027 }) {
6028 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6029 Some(())
6030 } else {
6031 None
6032 }
6033 }
6034
6035 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6036 self.manipulate_lines(cx, |lines| lines.reverse())
6037 }
6038
6039 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6040 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6041 }
6042
6043 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6044 where
6045 Fn: FnMut(&mut Vec<&str>),
6046 {
6047 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6048 let buffer = self.buffer.read(cx).snapshot(cx);
6049
6050 let mut edits = Vec::new();
6051
6052 let selections = self.selections.all::<Point>(cx);
6053 let mut selections = selections.iter().peekable();
6054 let mut contiguous_row_selections = Vec::new();
6055 let mut new_selections = Vec::new();
6056 let mut added_lines = 0;
6057 let mut removed_lines = 0;
6058
6059 while let Some(selection) = selections.next() {
6060 let (start_row, end_row) = consume_contiguous_rows(
6061 &mut contiguous_row_selections,
6062 selection,
6063 &display_map,
6064 &mut selections,
6065 );
6066
6067 let start_point = Point::new(start_row.0, 0);
6068 let end_point = Point::new(
6069 end_row.previous_row().0,
6070 buffer.line_len(end_row.previous_row()),
6071 );
6072 let text = buffer
6073 .text_for_range(start_point..end_point)
6074 .collect::<String>();
6075
6076 let mut lines = text.split('\n').collect_vec();
6077
6078 let lines_before = lines.len();
6079 callback(&mut lines);
6080 let lines_after = lines.len();
6081
6082 edits.push((start_point..end_point, lines.join("\n")));
6083
6084 // Selections must change based on added and removed line count
6085 let start_row =
6086 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6087 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6088 new_selections.push(Selection {
6089 id: selection.id,
6090 start: start_row,
6091 end: end_row,
6092 goal: SelectionGoal::None,
6093 reversed: selection.reversed,
6094 });
6095
6096 if lines_after > lines_before {
6097 added_lines += lines_after - lines_before;
6098 } else if lines_before > lines_after {
6099 removed_lines += lines_before - lines_after;
6100 }
6101 }
6102
6103 self.transact(cx, |this, cx| {
6104 let buffer = this.buffer.update(cx, |buffer, cx| {
6105 buffer.edit(edits, None, cx);
6106 buffer.snapshot(cx)
6107 });
6108
6109 // Recalculate offsets on newly edited buffer
6110 let new_selections = new_selections
6111 .iter()
6112 .map(|s| {
6113 let start_point = Point::new(s.start.0, 0);
6114 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6115 Selection {
6116 id: s.id,
6117 start: buffer.point_to_offset(start_point),
6118 end: buffer.point_to_offset(end_point),
6119 goal: s.goal,
6120 reversed: s.reversed,
6121 }
6122 })
6123 .collect();
6124
6125 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6126 s.select(new_selections);
6127 });
6128
6129 this.request_autoscroll(Autoscroll::fit(), cx);
6130 });
6131 }
6132
6133 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6134 self.manipulate_text(cx, |text| text.to_uppercase())
6135 }
6136
6137 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6138 self.manipulate_text(cx, |text| text.to_lowercase())
6139 }
6140
6141 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6142 self.manipulate_text(cx, |text| {
6143 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6144 // https://github.com/rutrum/convert-case/issues/16
6145 text.split('\n')
6146 .map(|line| line.to_case(Case::Title))
6147 .join("\n")
6148 })
6149 }
6150
6151 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6152 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6153 }
6154
6155 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6156 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6157 }
6158
6159 pub fn convert_to_upper_camel_case(
6160 &mut self,
6161 _: &ConvertToUpperCamelCase,
6162 cx: &mut ViewContext<Self>,
6163 ) {
6164 self.manipulate_text(cx, |text| {
6165 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6166 // https://github.com/rutrum/convert-case/issues/16
6167 text.split('\n')
6168 .map(|line| line.to_case(Case::UpperCamel))
6169 .join("\n")
6170 })
6171 }
6172
6173 pub fn convert_to_lower_camel_case(
6174 &mut self,
6175 _: &ConvertToLowerCamelCase,
6176 cx: &mut ViewContext<Self>,
6177 ) {
6178 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6179 }
6180
6181 pub fn convert_to_opposite_case(
6182 &mut self,
6183 _: &ConvertToOppositeCase,
6184 cx: &mut ViewContext<Self>,
6185 ) {
6186 self.manipulate_text(cx, |text| {
6187 text.chars()
6188 .fold(String::with_capacity(text.len()), |mut t, c| {
6189 if c.is_uppercase() {
6190 t.extend(c.to_lowercase());
6191 } else {
6192 t.extend(c.to_uppercase());
6193 }
6194 t
6195 })
6196 })
6197 }
6198
6199 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6200 where
6201 Fn: FnMut(&str) -> String,
6202 {
6203 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6204 let buffer = self.buffer.read(cx).snapshot(cx);
6205
6206 let mut new_selections = Vec::new();
6207 let mut edits = Vec::new();
6208 let mut selection_adjustment = 0i32;
6209
6210 for selection in self.selections.all::<usize>(cx) {
6211 let selection_is_empty = selection.is_empty();
6212
6213 let (start, end) = if selection_is_empty {
6214 let word_range = movement::surrounding_word(
6215 &display_map,
6216 selection.start.to_display_point(&display_map),
6217 );
6218 let start = word_range.start.to_offset(&display_map, Bias::Left);
6219 let end = word_range.end.to_offset(&display_map, Bias::Left);
6220 (start, end)
6221 } else {
6222 (selection.start, selection.end)
6223 };
6224
6225 let text = buffer.text_for_range(start..end).collect::<String>();
6226 let old_length = text.len() as i32;
6227 let text = callback(&text);
6228
6229 new_selections.push(Selection {
6230 start: (start as i32 - selection_adjustment) as usize,
6231 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6232 goal: SelectionGoal::None,
6233 ..selection
6234 });
6235
6236 selection_adjustment += old_length - text.len() as i32;
6237
6238 edits.push((start..end, text));
6239 }
6240
6241 self.transact(cx, |this, cx| {
6242 this.buffer.update(cx, |buffer, cx| {
6243 buffer.edit(edits, None, cx);
6244 });
6245
6246 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6247 s.select(new_selections);
6248 });
6249
6250 this.request_autoscroll(Autoscroll::fit(), cx);
6251 });
6252 }
6253
6254 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6255 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6256 let buffer = &display_map.buffer_snapshot;
6257 let selections = self.selections.all::<Point>(cx);
6258
6259 let mut edits = Vec::new();
6260 let mut selections_iter = selections.iter().peekable();
6261 while let Some(selection) = selections_iter.next() {
6262 // Avoid duplicating the same lines twice.
6263 let mut rows = selection.spanned_rows(false, &display_map);
6264
6265 while let Some(next_selection) = selections_iter.peek() {
6266 let next_rows = next_selection.spanned_rows(false, &display_map);
6267 if next_rows.start < rows.end {
6268 rows.end = next_rows.end;
6269 selections_iter.next().unwrap();
6270 } else {
6271 break;
6272 }
6273 }
6274
6275 // Copy the text from the selected row region and splice it either at the start
6276 // or end of the region.
6277 let start = Point::new(rows.start.0, 0);
6278 let end = Point::new(
6279 rows.end.previous_row().0,
6280 buffer.line_len(rows.end.previous_row()),
6281 );
6282 let text = buffer
6283 .text_for_range(start..end)
6284 .chain(Some("\n"))
6285 .collect::<String>();
6286 let insert_location = if upwards {
6287 Point::new(rows.end.0, 0)
6288 } else {
6289 start
6290 };
6291 edits.push((insert_location..insert_location, text));
6292 }
6293
6294 self.transact(cx, |this, cx| {
6295 this.buffer.update(cx, |buffer, cx| {
6296 buffer.edit(edits, None, cx);
6297 });
6298
6299 this.request_autoscroll(Autoscroll::fit(), cx);
6300 });
6301 }
6302
6303 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6304 self.duplicate_line(true, cx);
6305 }
6306
6307 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6308 self.duplicate_line(false, cx);
6309 }
6310
6311 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6312 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6313 let buffer = self.buffer.read(cx).snapshot(cx);
6314
6315 let mut edits = Vec::new();
6316 let mut unfold_ranges = Vec::new();
6317 let mut refold_ranges = Vec::new();
6318
6319 let selections = self.selections.all::<Point>(cx);
6320 let mut selections = selections.iter().peekable();
6321 let mut contiguous_row_selections = Vec::new();
6322 let mut new_selections = Vec::new();
6323
6324 while let Some(selection) = selections.next() {
6325 // Find all the selections that span a contiguous row range
6326 let (start_row, end_row) = consume_contiguous_rows(
6327 &mut contiguous_row_selections,
6328 selection,
6329 &display_map,
6330 &mut selections,
6331 );
6332
6333 // Move the text spanned by the row range to be before the line preceding the row range
6334 if start_row.0 > 0 {
6335 let range_to_move = Point::new(
6336 start_row.previous_row().0,
6337 buffer.line_len(start_row.previous_row()),
6338 )
6339 ..Point::new(
6340 end_row.previous_row().0,
6341 buffer.line_len(end_row.previous_row()),
6342 );
6343 let insertion_point = display_map
6344 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6345 .0;
6346
6347 // Don't move lines across excerpts
6348 if buffer
6349 .excerpt_boundaries_in_range((
6350 Bound::Excluded(insertion_point),
6351 Bound::Included(range_to_move.end),
6352 ))
6353 .next()
6354 .is_none()
6355 {
6356 let text = buffer
6357 .text_for_range(range_to_move.clone())
6358 .flat_map(|s| s.chars())
6359 .skip(1)
6360 .chain(['\n'])
6361 .collect::<String>();
6362
6363 edits.push((
6364 buffer.anchor_after(range_to_move.start)
6365 ..buffer.anchor_before(range_to_move.end),
6366 String::new(),
6367 ));
6368 let insertion_anchor = buffer.anchor_after(insertion_point);
6369 edits.push((insertion_anchor..insertion_anchor, text));
6370
6371 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6372
6373 // Move selections up
6374 new_selections.extend(contiguous_row_selections.drain(..).map(
6375 |mut selection| {
6376 selection.start.row -= row_delta;
6377 selection.end.row -= row_delta;
6378 selection
6379 },
6380 ));
6381
6382 // Move folds up
6383 unfold_ranges.push(range_to_move.clone());
6384 for fold in display_map.folds_in_range(
6385 buffer.anchor_before(range_to_move.start)
6386 ..buffer.anchor_after(range_to_move.end),
6387 ) {
6388 let mut start = fold.range.start.to_point(&buffer);
6389 let mut end = fold.range.end.to_point(&buffer);
6390 start.row -= row_delta;
6391 end.row -= row_delta;
6392 refold_ranges.push((start..end, fold.placeholder.clone()));
6393 }
6394 }
6395 }
6396
6397 // If we didn't move line(s), preserve the existing selections
6398 new_selections.append(&mut contiguous_row_selections);
6399 }
6400
6401 self.transact(cx, |this, cx| {
6402 this.unfold_ranges(unfold_ranges, true, true, cx);
6403 this.buffer.update(cx, |buffer, cx| {
6404 for (range, text) in edits {
6405 buffer.edit([(range, text)], None, cx);
6406 }
6407 });
6408 this.fold_ranges(refold_ranges, true, cx);
6409 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6410 s.select(new_selections);
6411 })
6412 });
6413 }
6414
6415 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6416 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6417 let buffer = self.buffer.read(cx).snapshot(cx);
6418
6419 let mut edits = Vec::new();
6420 let mut unfold_ranges = Vec::new();
6421 let mut refold_ranges = Vec::new();
6422
6423 let selections = self.selections.all::<Point>(cx);
6424 let mut selections = selections.iter().peekable();
6425 let mut contiguous_row_selections = Vec::new();
6426 let mut new_selections = Vec::new();
6427
6428 while let Some(selection) = selections.next() {
6429 // Find all the selections that span a contiguous row range
6430 let (start_row, end_row) = consume_contiguous_rows(
6431 &mut contiguous_row_selections,
6432 selection,
6433 &display_map,
6434 &mut selections,
6435 );
6436
6437 // Move the text spanned by the row range to be after the last line of the row range
6438 if end_row.0 <= buffer.max_point().row {
6439 let range_to_move =
6440 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6441 let insertion_point = display_map
6442 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6443 .0;
6444
6445 // Don't move lines across excerpt boundaries
6446 if buffer
6447 .excerpt_boundaries_in_range((
6448 Bound::Excluded(range_to_move.start),
6449 Bound::Included(insertion_point),
6450 ))
6451 .next()
6452 .is_none()
6453 {
6454 let mut text = String::from("\n");
6455 text.extend(buffer.text_for_range(range_to_move.clone()));
6456 text.pop(); // Drop trailing newline
6457 edits.push((
6458 buffer.anchor_after(range_to_move.start)
6459 ..buffer.anchor_before(range_to_move.end),
6460 String::new(),
6461 ));
6462 let insertion_anchor = buffer.anchor_after(insertion_point);
6463 edits.push((insertion_anchor..insertion_anchor, text));
6464
6465 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6466
6467 // Move selections down
6468 new_selections.extend(contiguous_row_selections.drain(..).map(
6469 |mut selection| {
6470 selection.start.row += row_delta;
6471 selection.end.row += row_delta;
6472 selection
6473 },
6474 ));
6475
6476 // Move folds down
6477 unfold_ranges.push(range_to_move.clone());
6478 for fold in display_map.folds_in_range(
6479 buffer.anchor_before(range_to_move.start)
6480 ..buffer.anchor_after(range_to_move.end),
6481 ) {
6482 let mut start = fold.range.start.to_point(&buffer);
6483 let mut end = fold.range.end.to_point(&buffer);
6484 start.row += row_delta;
6485 end.row += row_delta;
6486 refold_ranges.push((start..end, fold.placeholder.clone()));
6487 }
6488 }
6489 }
6490
6491 // If we didn't move line(s), preserve the existing selections
6492 new_selections.append(&mut contiguous_row_selections);
6493 }
6494
6495 self.transact(cx, |this, cx| {
6496 this.unfold_ranges(unfold_ranges, true, true, cx);
6497 this.buffer.update(cx, |buffer, cx| {
6498 for (range, text) in edits {
6499 buffer.edit([(range, text)], None, cx);
6500 }
6501 });
6502 this.fold_ranges(refold_ranges, true, cx);
6503 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6504 });
6505 }
6506
6507 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6508 let text_layout_details = &self.text_layout_details(cx);
6509 self.transact(cx, |this, cx| {
6510 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6511 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6512 let line_mode = s.line_mode;
6513 s.move_with(|display_map, selection| {
6514 if !selection.is_empty() || line_mode {
6515 return;
6516 }
6517
6518 let mut head = selection.head();
6519 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6520 if head.column() == display_map.line_len(head.row()) {
6521 transpose_offset = display_map
6522 .buffer_snapshot
6523 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6524 }
6525
6526 if transpose_offset == 0 {
6527 return;
6528 }
6529
6530 *head.column_mut() += 1;
6531 head = display_map.clip_point(head, Bias::Right);
6532 let goal = SelectionGoal::HorizontalPosition(
6533 display_map
6534 .x_for_display_point(head, &text_layout_details)
6535 .into(),
6536 );
6537 selection.collapse_to(head, goal);
6538
6539 let transpose_start = display_map
6540 .buffer_snapshot
6541 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6542 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6543 let transpose_end = display_map
6544 .buffer_snapshot
6545 .clip_offset(transpose_offset + 1, Bias::Right);
6546 if let Some(ch) =
6547 display_map.buffer_snapshot.chars_at(transpose_start).next()
6548 {
6549 edits.push((transpose_start..transpose_offset, String::new()));
6550 edits.push((transpose_end..transpose_end, ch.to_string()));
6551 }
6552 }
6553 });
6554 edits
6555 });
6556 this.buffer
6557 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6558 let selections = this.selections.all::<usize>(cx);
6559 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6560 s.select(selections);
6561 });
6562 });
6563 }
6564
6565 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6566 let mut text = String::new();
6567 let buffer = self.buffer.read(cx).snapshot(cx);
6568 let mut selections = self.selections.all::<Point>(cx);
6569 let mut clipboard_selections = Vec::with_capacity(selections.len());
6570 {
6571 let max_point = buffer.max_point();
6572 let mut is_first = true;
6573 for selection in &mut selections {
6574 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6575 if is_entire_line {
6576 selection.start = Point::new(selection.start.row, 0);
6577 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6578 selection.goal = SelectionGoal::None;
6579 }
6580 if is_first {
6581 is_first = false;
6582 } else {
6583 text += "\n";
6584 }
6585 let mut len = 0;
6586 for chunk in buffer.text_for_range(selection.start..selection.end) {
6587 text.push_str(chunk);
6588 len += chunk.len();
6589 }
6590 clipboard_selections.push(ClipboardSelection {
6591 len,
6592 is_entire_line,
6593 first_line_indent: buffer
6594 .indent_size_for_line(MultiBufferRow(selection.start.row))
6595 .len,
6596 });
6597 }
6598 }
6599
6600 self.transact(cx, |this, cx| {
6601 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6602 s.select(selections);
6603 });
6604 this.insert("", cx);
6605 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6606 text,
6607 clipboard_selections,
6608 ));
6609 });
6610 }
6611
6612 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6613 let selections = self.selections.all::<Point>(cx);
6614 let buffer = self.buffer.read(cx).read(cx);
6615 let mut text = String::new();
6616
6617 let mut clipboard_selections = Vec::with_capacity(selections.len());
6618 {
6619 let max_point = buffer.max_point();
6620 let mut is_first = true;
6621 for selection in selections.iter() {
6622 let mut start = selection.start;
6623 let mut end = selection.end;
6624 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6625 if is_entire_line {
6626 start = Point::new(start.row, 0);
6627 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6628 }
6629 if is_first {
6630 is_first = false;
6631 } else {
6632 text += "\n";
6633 }
6634 let mut len = 0;
6635 for chunk in buffer.text_for_range(start..end) {
6636 text.push_str(chunk);
6637 len += chunk.len();
6638 }
6639 clipboard_selections.push(ClipboardSelection {
6640 len,
6641 is_entire_line,
6642 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6643 });
6644 }
6645 }
6646
6647 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6648 text,
6649 clipboard_selections,
6650 ));
6651 }
6652
6653 pub fn do_paste(
6654 &mut self,
6655 text: &String,
6656 clipboard_selections: Option<Vec<ClipboardSelection>>,
6657 handle_entire_lines: bool,
6658 cx: &mut ViewContext<Self>,
6659 ) {
6660 if self.read_only(cx) {
6661 return;
6662 }
6663
6664 let clipboard_text = Cow::Borrowed(text);
6665
6666 self.transact(cx, |this, cx| {
6667 if let Some(mut clipboard_selections) = clipboard_selections {
6668 let old_selections = this.selections.all::<usize>(cx);
6669 let all_selections_were_entire_line =
6670 clipboard_selections.iter().all(|s| s.is_entire_line);
6671 let first_selection_indent_column =
6672 clipboard_selections.first().map(|s| s.first_line_indent);
6673 if clipboard_selections.len() != old_selections.len() {
6674 clipboard_selections.drain(..);
6675 }
6676
6677 this.buffer.update(cx, |buffer, cx| {
6678 let snapshot = buffer.read(cx);
6679 let mut start_offset = 0;
6680 let mut edits = Vec::new();
6681 let mut original_indent_columns = Vec::new();
6682 for (ix, selection) in old_selections.iter().enumerate() {
6683 let to_insert;
6684 let entire_line;
6685 let original_indent_column;
6686 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6687 let end_offset = start_offset + clipboard_selection.len;
6688 to_insert = &clipboard_text[start_offset..end_offset];
6689 entire_line = clipboard_selection.is_entire_line;
6690 start_offset = end_offset + 1;
6691 original_indent_column = Some(clipboard_selection.first_line_indent);
6692 } else {
6693 to_insert = clipboard_text.as_str();
6694 entire_line = all_selections_were_entire_line;
6695 original_indent_column = first_selection_indent_column
6696 }
6697
6698 // If the corresponding selection was empty when this slice of the
6699 // clipboard text was written, then the entire line containing the
6700 // selection was copied. If this selection is also currently empty,
6701 // then paste the line before the current line of the buffer.
6702 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6703 let column = selection.start.to_point(&snapshot).column as usize;
6704 let line_start = selection.start - column;
6705 line_start..line_start
6706 } else {
6707 selection.range()
6708 };
6709
6710 edits.push((range, to_insert));
6711 original_indent_columns.extend(original_indent_column);
6712 }
6713 drop(snapshot);
6714
6715 buffer.edit(
6716 edits,
6717 Some(AutoindentMode::Block {
6718 original_indent_columns,
6719 }),
6720 cx,
6721 );
6722 });
6723
6724 let selections = this.selections.all::<usize>(cx);
6725 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6726 } else {
6727 this.insert(&clipboard_text, cx);
6728 }
6729 });
6730 }
6731
6732 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6733 if let Some(item) = cx.read_from_clipboard() {
6734 let entries = item.entries();
6735
6736 match entries.first() {
6737 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6738 // of all the pasted entries.
6739 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6740 .do_paste(
6741 clipboard_string.text(),
6742 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6743 true,
6744 cx,
6745 ),
6746 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6747 }
6748 }
6749 }
6750
6751 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6752 if self.read_only(cx) {
6753 return;
6754 }
6755
6756 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6757 if let Some((selections, _)) =
6758 self.selection_history.transaction(transaction_id).cloned()
6759 {
6760 self.change_selections(None, cx, |s| {
6761 s.select_anchors(selections.to_vec());
6762 });
6763 }
6764 self.request_autoscroll(Autoscroll::fit(), cx);
6765 self.unmark_text(cx);
6766 self.refresh_inline_completion(true, cx);
6767 cx.emit(EditorEvent::Edited { transaction_id });
6768 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6769 }
6770 }
6771
6772 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6773 if self.read_only(cx) {
6774 return;
6775 }
6776
6777 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6778 if let Some((_, Some(selections))) =
6779 self.selection_history.transaction(transaction_id).cloned()
6780 {
6781 self.change_selections(None, cx, |s| {
6782 s.select_anchors(selections.to_vec());
6783 });
6784 }
6785 self.request_autoscroll(Autoscroll::fit(), cx);
6786 self.unmark_text(cx);
6787 self.refresh_inline_completion(true, cx);
6788 cx.emit(EditorEvent::Edited { transaction_id });
6789 }
6790 }
6791
6792 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6793 self.buffer
6794 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6795 }
6796
6797 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6798 self.buffer
6799 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6800 }
6801
6802 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6803 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6804 let line_mode = s.line_mode;
6805 s.move_with(|map, selection| {
6806 let cursor = if selection.is_empty() && !line_mode {
6807 movement::left(map, selection.start)
6808 } else {
6809 selection.start
6810 };
6811 selection.collapse_to(cursor, SelectionGoal::None);
6812 });
6813 })
6814 }
6815
6816 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6817 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6818 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6819 })
6820 }
6821
6822 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6823 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6824 let line_mode = s.line_mode;
6825 s.move_with(|map, selection| {
6826 let cursor = if selection.is_empty() && !line_mode {
6827 movement::right(map, selection.end)
6828 } else {
6829 selection.end
6830 };
6831 selection.collapse_to(cursor, SelectionGoal::None)
6832 });
6833 })
6834 }
6835
6836 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6837 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6838 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6839 })
6840 }
6841
6842 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6843 if self.take_rename(true, cx).is_some() {
6844 return;
6845 }
6846
6847 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6848 cx.propagate();
6849 return;
6850 }
6851
6852 let text_layout_details = &self.text_layout_details(cx);
6853 let selection_count = self.selections.count();
6854 let first_selection = self.selections.first_anchor();
6855
6856 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6857 let line_mode = s.line_mode;
6858 s.move_with(|map, selection| {
6859 if !selection.is_empty() && !line_mode {
6860 selection.goal = SelectionGoal::None;
6861 }
6862 let (cursor, goal) = movement::up(
6863 map,
6864 selection.start,
6865 selection.goal,
6866 false,
6867 &text_layout_details,
6868 );
6869 selection.collapse_to(cursor, goal);
6870 });
6871 });
6872
6873 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6874 {
6875 cx.propagate();
6876 }
6877 }
6878
6879 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6880 if self.take_rename(true, cx).is_some() {
6881 return;
6882 }
6883
6884 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6885 cx.propagate();
6886 return;
6887 }
6888
6889 let text_layout_details = &self.text_layout_details(cx);
6890
6891 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6892 let line_mode = s.line_mode;
6893 s.move_with(|map, selection| {
6894 if !selection.is_empty() && !line_mode {
6895 selection.goal = SelectionGoal::None;
6896 }
6897 let (cursor, goal) = movement::up_by_rows(
6898 map,
6899 selection.start,
6900 action.lines,
6901 selection.goal,
6902 false,
6903 &text_layout_details,
6904 );
6905 selection.collapse_to(cursor, goal);
6906 });
6907 })
6908 }
6909
6910 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6911 if self.take_rename(true, cx).is_some() {
6912 return;
6913 }
6914
6915 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6916 cx.propagate();
6917 return;
6918 }
6919
6920 let text_layout_details = &self.text_layout_details(cx);
6921
6922 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6923 let line_mode = s.line_mode;
6924 s.move_with(|map, selection| {
6925 if !selection.is_empty() && !line_mode {
6926 selection.goal = SelectionGoal::None;
6927 }
6928 let (cursor, goal) = movement::down_by_rows(
6929 map,
6930 selection.start,
6931 action.lines,
6932 selection.goal,
6933 false,
6934 &text_layout_details,
6935 );
6936 selection.collapse_to(cursor, goal);
6937 });
6938 })
6939 }
6940
6941 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6942 let text_layout_details = &self.text_layout_details(cx);
6943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6944 s.move_heads_with(|map, head, goal| {
6945 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6946 })
6947 })
6948 }
6949
6950 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6951 let text_layout_details = &self.text_layout_details(cx);
6952 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6953 s.move_heads_with(|map, head, goal| {
6954 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6955 })
6956 })
6957 }
6958
6959 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6960 let Some(row_count) = self.visible_row_count() else {
6961 return;
6962 };
6963
6964 let text_layout_details = &self.text_layout_details(cx);
6965
6966 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6967 s.move_heads_with(|map, head, goal| {
6968 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6969 })
6970 })
6971 }
6972
6973 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6974 if self.take_rename(true, cx).is_some() {
6975 return;
6976 }
6977
6978 if self
6979 .context_menu
6980 .write()
6981 .as_mut()
6982 .map(|menu| menu.select_first(self.project.as_ref(), cx))
6983 .unwrap_or(false)
6984 {
6985 return;
6986 }
6987
6988 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6989 cx.propagate();
6990 return;
6991 }
6992
6993 let Some(row_count) = self.visible_row_count() else {
6994 return;
6995 };
6996
6997 let autoscroll = if action.center_cursor {
6998 Autoscroll::center()
6999 } else {
7000 Autoscroll::fit()
7001 };
7002
7003 let text_layout_details = &self.text_layout_details(cx);
7004
7005 self.change_selections(Some(autoscroll), cx, |s| {
7006 let line_mode = s.line_mode;
7007 s.move_with(|map, selection| {
7008 if !selection.is_empty() && !line_mode {
7009 selection.goal = SelectionGoal::None;
7010 }
7011 let (cursor, goal) = movement::up_by_rows(
7012 map,
7013 selection.end,
7014 row_count,
7015 selection.goal,
7016 false,
7017 &text_layout_details,
7018 );
7019 selection.collapse_to(cursor, goal);
7020 });
7021 });
7022 }
7023
7024 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7025 let text_layout_details = &self.text_layout_details(cx);
7026 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7027 s.move_heads_with(|map, head, goal| {
7028 movement::up(map, head, goal, false, &text_layout_details)
7029 })
7030 })
7031 }
7032
7033 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7034 self.take_rename(true, cx);
7035
7036 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7037 cx.propagate();
7038 return;
7039 }
7040
7041 let text_layout_details = &self.text_layout_details(cx);
7042 let selection_count = self.selections.count();
7043 let first_selection = self.selections.first_anchor();
7044
7045 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7046 let line_mode = s.line_mode;
7047 s.move_with(|map, selection| {
7048 if !selection.is_empty() && !line_mode {
7049 selection.goal = SelectionGoal::None;
7050 }
7051 let (cursor, goal) = movement::down(
7052 map,
7053 selection.end,
7054 selection.goal,
7055 false,
7056 &text_layout_details,
7057 );
7058 selection.collapse_to(cursor, goal);
7059 });
7060 });
7061
7062 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7063 {
7064 cx.propagate();
7065 }
7066 }
7067
7068 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7069 let Some(row_count) = self.visible_row_count() else {
7070 return;
7071 };
7072
7073 let text_layout_details = &self.text_layout_details(cx);
7074
7075 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7076 s.move_heads_with(|map, head, goal| {
7077 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7078 })
7079 })
7080 }
7081
7082 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7083 if self.take_rename(true, cx).is_some() {
7084 return;
7085 }
7086
7087 if self
7088 .context_menu
7089 .write()
7090 .as_mut()
7091 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7092 .unwrap_or(false)
7093 {
7094 return;
7095 }
7096
7097 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7098 cx.propagate();
7099 return;
7100 }
7101
7102 let Some(row_count) = self.visible_row_count() else {
7103 return;
7104 };
7105
7106 let autoscroll = if action.center_cursor {
7107 Autoscroll::center()
7108 } else {
7109 Autoscroll::fit()
7110 };
7111
7112 let text_layout_details = &self.text_layout_details(cx);
7113 self.change_selections(Some(autoscroll), cx, |s| {
7114 let line_mode = s.line_mode;
7115 s.move_with(|map, selection| {
7116 if !selection.is_empty() && !line_mode {
7117 selection.goal = SelectionGoal::None;
7118 }
7119 let (cursor, goal) = movement::down_by_rows(
7120 map,
7121 selection.end,
7122 row_count,
7123 selection.goal,
7124 false,
7125 &text_layout_details,
7126 );
7127 selection.collapse_to(cursor, goal);
7128 });
7129 });
7130 }
7131
7132 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7133 let text_layout_details = &self.text_layout_details(cx);
7134 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7135 s.move_heads_with(|map, head, goal| {
7136 movement::down(map, head, goal, false, &text_layout_details)
7137 })
7138 });
7139 }
7140
7141 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7142 if let Some(context_menu) = self.context_menu.write().as_mut() {
7143 context_menu.select_first(self.project.as_ref(), cx);
7144 }
7145 }
7146
7147 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7148 if let Some(context_menu) = self.context_menu.write().as_mut() {
7149 context_menu.select_prev(self.project.as_ref(), cx);
7150 }
7151 }
7152
7153 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7154 if let Some(context_menu) = self.context_menu.write().as_mut() {
7155 context_menu.select_next(self.project.as_ref(), cx);
7156 }
7157 }
7158
7159 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7160 if let Some(context_menu) = self.context_menu.write().as_mut() {
7161 context_menu.select_last(self.project.as_ref(), cx);
7162 }
7163 }
7164
7165 pub fn move_to_previous_word_start(
7166 &mut self,
7167 _: &MoveToPreviousWordStart,
7168 cx: &mut ViewContext<Self>,
7169 ) {
7170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7171 s.move_cursors_with(|map, head, _| {
7172 (
7173 movement::previous_word_start(map, head),
7174 SelectionGoal::None,
7175 )
7176 });
7177 })
7178 }
7179
7180 pub fn move_to_previous_subword_start(
7181 &mut self,
7182 _: &MoveToPreviousSubwordStart,
7183 cx: &mut ViewContext<Self>,
7184 ) {
7185 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7186 s.move_cursors_with(|map, head, _| {
7187 (
7188 movement::previous_subword_start(map, head),
7189 SelectionGoal::None,
7190 )
7191 });
7192 })
7193 }
7194
7195 pub fn select_to_previous_word_start(
7196 &mut self,
7197 _: &SelectToPreviousWordStart,
7198 cx: &mut ViewContext<Self>,
7199 ) {
7200 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7201 s.move_heads_with(|map, head, _| {
7202 (
7203 movement::previous_word_start(map, head),
7204 SelectionGoal::None,
7205 )
7206 });
7207 })
7208 }
7209
7210 pub fn select_to_previous_subword_start(
7211 &mut self,
7212 _: &SelectToPreviousSubwordStart,
7213 cx: &mut ViewContext<Self>,
7214 ) {
7215 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7216 s.move_heads_with(|map, head, _| {
7217 (
7218 movement::previous_subword_start(map, head),
7219 SelectionGoal::None,
7220 )
7221 });
7222 })
7223 }
7224
7225 pub fn delete_to_previous_word_start(
7226 &mut self,
7227 _: &DeleteToPreviousWordStart,
7228 cx: &mut ViewContext<Self>,
7229 ) {
7230 self.transact(cx, |this, cx| {
7231 this.select_autoclose_pair(cx);
7232 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7233 let line_mode = s.line_mode;
7234 s.move_with(|map, selection| {
7235 if selection.is_empty() && !line_mode {
7236 let cursor = movement::previous_word_start(map, selection.head());
7237 selection.set_head(cursor, SelectionGoal::None);
7238 }
7239 });
7240 });
7241 this.insert("", cx);
7242 });
7243 }
7244
7245 pub fn delete_to_previous_subword_start(
7246 &mut self,
7247 _: &DeleteToPreviousSubwordStart,
7248 cx: &mut ViewContext<Self>,
7249 ) {
7250 self.transact(cx, |this, cx| {
7251 this.select_autoclose_pair(cx);
7252 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7253 let line_mode = s.line_mode;
7254 s.move_with(|map, selection| {
7255 if selection.is_empty() && !line_mode {
7256 let cursor = movement::previous_subword_start(map, selection.head());
7257 selection.set_head(cursor, SelectionGoal::None);
7258 }
7259 });
7260 });
7261 this.insert("", cx);
7262 });
7263 }
7264
7265 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7266 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7267 s.move_cursors_with(|map, head, _| {
7268 (movement::next_word_end(map, head), SelectionGoal::None)
7269 });
7270 })
7271 }
7272
7273 pub fn move_to_next_subword_end(
7274 &mut self,
7275 _: &MoveToNextSubwordEnd,
7276 cx: &mut ViewContext<Self>,
7277 ) {
7278 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7279 s.move_cursors_with(|map, head, _| {
7280 (movement::next_subword_end(map, head), SelectionGoal::None)
7281 });
7282 })
7283 }
7284
7285 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7287 s.move_heads_with(|map, head, _| {
7288 (movement::next_word_end(map, head), SelectionGoal::None)
7289 });
7290 })
7291 }
7292
7293 pub fn select_to_next_subword_end(
7294 &mut self,
7295 _: &SelectToNextSubwordEnd,
7296 cx: &mut ViewContext<Self>,
7297 ) {
7298 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7299 s.move_heads_with(|map, head, _| {
7300 (movement::next_subword_end(map, head), SelectionGoal::None)
7301 });
7302 })
7303 }
7304
7305 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7306 self.transact(cx, |this, cx| {
7307 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7308 let line_mode = s.line_mode;
7309 s.move_with(|map, selection| {
7310 if selection.is_empty() && !line_mode {
7311 let cursor = movement::next_word_end(map, selection.head());
7312 selection.set_head(cursor, SelectionGoal::None);
7313 }
7314 });
7315 });
7316 this.insert("", cx);
7317 });
7318 }
7319
7320 pub fn delete_to_next_subword_end(
7321 &mut self,
7322 _: &DeleteToNextSubwordEnd,
7323 cx: &mut ViewContext<Self>,
7324 ) {
7325 self.transact(cx, |this, cx| {
7326 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7327 s.move_with(|map, selection| {
7328 if selection.is_empty() {
7329 let cursor = movement::next_subword_end(map, selection.head());
7330 selection.set_head(cursor, SelectionGoal::None);
7331 }
7332 });
7333 });
7334 this.insert("", cx);
7335 });
7336 }
7337
7338 pub fn move_to_beginning_of_line(
7339 &mut self,
7340 action: &MoveToBeginningOfLine,
7341 cx: &mut ViewContext<Self>,
7342 ) {
7343 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7344 s.move_cursors_with(|map, head, _| {
7345 (
7346 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7347 SelectionGoal::None,
7348 )
7349 });
7350 })
7351 }
7352
7353 pub fn select_to_beginning_of_line(
7354 &mut self,
7355 action: &SelectToBeginningOfLine,
7356 cx: &mut ViewContext<Self>,
7357 ) {
7358 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7359 s.move_heads_with(|map, head, _| {
7360 (
7361 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7362 SelectionGoal::None,
7363 )
7364 });
7365 });
7366 }
7367
7368 pub fn delete_to_beginning_of_line(
7369 &mut self,
7370 _: &DeleteToBeginningOfLine,
7371 cx: &mut ViewContext<Self>,
7372 ) {
7373 self.transact(cx, |this, cx| {
7374 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7375 s.move_with(|_, selection| {
7376 selection.reversed = true;
7377 });
7378 });
7379
7380 this.select_to_beginning_of_line(
7381 &SelectToBeginningOfLine {
7382 stop_at_soft_wraps: false,
7383 },
7384 cx,
7385 );
7386 this.backspace(&Backspace, cx);
7387 });
7388 }
7389
7390 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7391 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7392 s.move_cursors_with(|map, head, _| {
7393 (
7394 movement::line_end(map, head, action.stop_at_soft_wraps),
7395 SelectionGoal::None,
7396 )
7397 });
7398 })
7399 }
7400
7401 pub fn select_to_end_of_line(
7402 &mut self,
7403 action: &SelectToEndOfLine,
7404 cx: &mut ViewContext<Self>,
7405 ) {
7406 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7407 s.move_heads_with(|map, head, _| {
7408 (
7409 movement::line_end(map, head, action.stop_at_soft_wraps),
7410 SelectionGoal::None,
7411 )
7412 });
7413 })
7414 }
7415
7416 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7417 self.transact(cx, |this, cx| {
7418 this.select_to_end_of_line(
7419 &SelectToEndOfLine {
7420 stop_at_soft_wraps: false,
7421 },
7422 cx,
7423 );
7424 this.delete(&Delete, cx);
7425 });
7426 }
7427
7428 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7429 self.transact(cx, |this, cx| {
7430 this.select_to_end_of_line(
7431 &SelectToEndOfLine {
7432 stop_at_soft_wraps: false,
7433 },
7434 cx,
7435 );
7436 this.cut(&Cut, cx);
7437 });
7438 }
7439
7440 pub fn move_to_start_of_paragraph(
7441 &mut self,
7442 _: &MoveToStartOfParagraph,
7443 cx: &mut ViewContext<Self>,
7444 ) {
7445 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7446 cx.propagate();
7447 return;
7448 }
7449
7450 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7451 s.move_with(|map, selection| {
7452 selection.collapse_to(
7453 movement::start_of_paragraph(map, selection.head(), 1),
7454 SelectionGoal::None,
7455 )
7456 });
7457 })
7458 }
7459
7460 pub fn move_to_end_of_paragraph(
7461 &mut self,
7462 _: &MoveToEndOfParagraph,
7463 cx: &mut ViewContext<Self>,
7464 ) {
7465 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7466 cx.propagate();
7467 return;
7468 }
7469
7470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7471 s.move_with(|map, selection| {
7472 selection.collapse_to(
7473 movement::end_of_paragraph(map, selection.head(), 1),
7474 SelectionGoal::None,
7475 )
7476 });
7477 })
7478 }
7479
7480 pub fn select_to_start_of_paragraph(
7481 &mut self,
7482 _: &SelectToStartOfParagraph,
7483 cx: &mut ViewContext<Self>,
7484 ) {
7485 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7486 cx.propagate();
7487 return;
7488 }
7489
7490 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7491 s.move_heads_with(|map, head, _| {
7492 (
7493 movement::start_of_paragraph(map, head, 1),
7494 SelectionGoal::None,
7495 )
7496 });
7497 })
7498 }
7499
7500 pub fn select_to_end_of_paragraph(
7501 &mut self,
7502 _: &SelectToEndOfParagraph,
7503 cx: &mut ViewContext<Self>,
7504 ) {
7505 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7506 cx.propagate();
7507 return;
7508 }
7509
7510 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7511 s.move_heads_with(|map, head, _| {
7512 (
7513 movement::end_of_paragraph(map, head, 1),
7514 SelectionGoal::None,
7515 )
7516 });
7517 })
7518 }
7519
7520 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7521 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7522 cx.propagate();
7523 return;
7524 }
7525
7526 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7527 s.select_ranges(vec![0..0]);
7528 });
7529 }
7530
7531 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7532 let mut selection = self.selections.last::<Point>(cx);
7533 selection.set_head(Point::zero(), SelectionGoal::None);
7534
7535 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7536 s.select(vec![selection]);
7537 });
7538 }
7539
7540 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7541 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7542 cx.propagate();
7543 return;
7544 }
7545
7546 let cursor = self.buffer.read(cx).read(cx).len();
7547 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7548 s.select_ranges(vec![cursor..cursor])
7549 });
7550 }
7551
7552 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7553 self.nav_history = nav_history;
7554 }
7555
7556 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7557 self.nav_history.as_ref()
7558 }
7559
7560 fn push_to_nav_history(
7561 &mut self,
7562 cursor_anchor: Anchor,
7563 new_position: Option<Point>,
7564 cx: &mut ViewContext<Self>,
7565 ) {
7566 if let Some(nav_history) = self.nav_history.as_mut() {
7567 let buffer = self.buffer.read(cx).read(cx);
7568 let cursor_position = cursor_anchor.to_point(&buffer);
7569 let scroll_state = self.scroll_manager.anchor();
7570 let scroll_top_row = scroll_state.top_row(&buffer);
7571 drop(buffer);
7572
7573 if let Some(new_position) = new_position {
7574 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7575 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7576 return;
7577 }
7578 }
7579
7580 nav_history.push(
7581 Some(NavigationData {
7582 cursor_anchor,
7583 cursor_position,
7584 scroll_anchor: scroll_state,
7585 scroll_top_row,
7586 }),
7587 cx,
7588 );
7589 }
7590 }
7591
7592 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7593 let buffer = self.buffer.read(cx).snapshot(cx);
7594 let mut selection = self.selections.first::<usize>(cx);
7595 selection.set_head(buffer.len(), SelectionGoal::None);
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.select(vec![selection]);
7598 });
7599 }
7600
7601 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7602 let end = self.buffer.read(cx).read(cx).len();
7603 self.change_selections(None, cx, |s| {
7604 s.select_ranges(vec![0..end]);
7605 });
7606 }
7607
7608 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7610 let mut selections = self.selections.all::<Point>(cx);
7611 let max_point = display_map.buffer_snapshot.max_point();
7612 for selection in &mut selections {
7613 let rows = selection.spanned_rows(true, &display_map);
7614 selection.start = Point::new(rows.start.0, 0);
7615 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7616 selection.reversed = false;
7617 }
7618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7619 s.select(selections);
7620 });
7621 }
7622
7623 pub fn split_selection_into_lines(
7624 &mut self,
7625 _: &SplitSelectionIntoLines,
7626 cx: &mut ViewContext<Self>,
7627 ) {
7628 let mut to_unfold = Vec::new();
7629 let mut new_selection_ranges = Vec::new();
7630 {
7631 let selections = self.selections.all::<Point>(cx);
7632 let buffer = self.buffer.read(cx).read(cx);
7633 for selection in selections {
7634 for row in selection.start.row..selection.end.row {
7635 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7636 new_selection_ranges.push(cursor..cursor);
7637 }
7638 new_selection_ranges.push(selection.end..selection.end);
7639 to_unfold.push(selection.start..selection.end);
7640 }
7641 }
7642 self.unfold_ranges(to_unfold, true, true, cx);
7643 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7644 s.select_ranges(new_selection_ranges);
7645 });
7646 }
7647
7648 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7649 self.add_selection(true, cx);
7650 }
7651
7652 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7653 self.add_selection(false, cx);
7654 }
7655
7656 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7658 let mut selections = self.selections.all::<Point>(cx);
7659 let text_layout_details = self.text_layout_details(cx);
7660 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7661 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7662 let range = oldest_selection.display_range(&display_map).sorted();
7663
7664 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7665 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7666 let positions = start_x.min(end_x)..start_x.max(end_x);
7667
7668 selections.clear();
7669 let mut stack = Vec::new();
7670 for row in range.start.row().0..=range.end.row().0 {
7671 if let Some(selection) = self.selections.build_columnar_selection(
7672 &display_map,
7673 DisplayRow(row),
7674 &positions,
7675 oldest_selection.reversed,
7676 &text_layout_details,
7677 ) {
7678 stack.push(selection.id);
7679 selections.push(selection);
7680 }
7681 }
7682
7683 if above {
7684 stack.reverse();
7685 }
7686
7687 AddSelectionsState { above, stack }
7688 });
7689
7690 let last_added_selection = *state.stack.last().unwrap();
7691 let mut new_selections = Vec::new();
7692 if above == state.above {
7693 let end_row = if above {
7694 DisplayRow(0)
7695 } else {
7696 display_map.max_point().row()
7697 };
7698
7699 'outer: for selection in selections {
7700 if selection.id == last_added_selection {
7701 let range = selection.display_range(&display_map).sorted();
7702 debug_assert_eq!(range.start.row(), range.end.row());
7703 let mut row = range.start.row();
7704 let positions =
7705 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7706 px(start)..px(end)
7707 } else {
7708 let start_x =
7709 display_map.x_for_display_point(range.start, &text_layout_details);
7710 let end_x =
7711 display_map.x_for_display_point(range.end, &text_layout_details);
7712 start_x.min(end_x)..start_x.max(end_x)
7713 };
7714
7715 while row != end_row {
7716 if above {
7717 row.0 -= 1;
7718 } else {
7719 row.0 += 1;
7720 }
7721
7722 if let Some(new_selection) = self.selections.build_columnar_selection(
7723 &display_map,
7724 row,
7725 &positions,
7726 selection.reversed,
7727 &text_layout_details,
7728 ) {
7729 state.stack.push(new_selection.id);
7730 if above {
7731 new_selections.push(new_selection);
7732 new_selections.push(selection);
7733 } else {
7734 new_selections.push(selection);
7735 new_selections.push(new_selection);
7736 }
7737
7738 continue 'outer;
7739 }
7740 }
7741 }
7742
7743 new_selections.push(selection);
7744 }
7745 } else {
7746 new_selections = selections;
7747 new_selections.retain(|s| s.id != last_added_selection);
7748 state.stack.pop();
7749 }
7750
7751 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7752 s.select(new_selections);
7753 });
7754 if state.stack.len() > 1 {
7755 self.add_selections_state = Some(state);
7756 }
7757 }
7758
7759 pub fn select_next_match_internal(
7760 &mut self,
7761 display_map: &DisplaySnapshot,
7762 replace_newest: bool,
7763 autoscroll: Option<Autoscroll>,
7764 cx: &mut ViewContext<Self>,
7765 ) -> Result<()> {
7766 fn select_next_match_ranges(
7767 this: &mut Editor,
7768 range: Range<usize>,
7769 replace_newest: bool,
7770 auto_scroll: Option<Autoscroll>,
7771 cx: &mut ViewContext<Editor>,
7772 ) {
7773 this.unfold_ranges([range.clone()], false, true, cx);
7774 this.change_selections(auto_scroll, cx, |s| {
7775 if replace_newest {
7776 s.delete(s.newest_anchor().id);
7777 }
7778 s.insert_range(range.clone());
7779 });
7780 }
7781
7782 let buffer = &display_map.buffer_snapshot;
7783 let mut selections = self.selections.all::<usize>(cx);
7784 if let Some(mut select_next_state) = self.select_next_state.take() {
7785 let query = &select_next_state.query;
7786 if !select_next_state.done {
7787 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7788 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7789 let mut next_selected_range = None;
7790
7791 let bytes_after_last_selection =
7792 buffer.bytes_in_range(last_selection.end..buffer.len());
7793 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7794 let query_matches = query
7795 .stream_find_iter(bytes_after_last_selection)
7796 .map(|result| (last_selection.end, result))
7797 .chain(
7798 query
7799 .stream_find_iter(bytes_before_first_selection)
7800 .map(|result| (0, result)),
7801 );
7802
7803 for (start_offset, query_match) in query_matches {
7804 let query_match = query_match.unwrap(); // can only fail due to I/O
7805 let offset_range =
7806 start_offset + query_match.start()..start_offset + query_match.end();
7807 let display_range = offset_range.start.to_display_point(&display_map)
7808 ..offset_range.end.to_display_point(&display_map);
7809
7810 if !select_next_state.wordwise
7811 || (!movement::is_inside_word(&display_map, display_range.start)
7812 && !movement::is_inside_word(&display_map, display_range.end))
7813 {
7814 // TODO: This is n^2, because we might check all the selections
7815 if !selections
7816 .iter()
7817 .any(|selection| selection.range().overlaps(&offset_range))
7818 {
7819 next_selected_range = Some(offset_range);
7820 break;
7821 }
7822 }
7823 }
7824
7825 if let Some(next_selected_range) = next_selected_range {
7826 select_next_match_ranges(
7827 self,
7828 next_selected_range,
7829 replace_newest,
7830 autoscroll,
7831 cx,
7832 );
7833 } else {
7834 select_next_state.done = true;
7835 }
7836 }
7837
7838 self.select_next_state = Some(select_next_state);
7839 } else {
7840 let mut only_carets = true;
7841 let mut same_text_selected = true;
7842 let mut selected_text = None;
7843
7844 let mut selections_iter = selections.iter().peekable();
7845 while let Some(selection) = selections_iter.next() {
7846 if selection.start != selection.end {
7847 only_carets = false;
7848 }
7849
7850 if same_text_selected {
7851 if selected_text.is_none() {
7852 selected_text =
7853 Some(buffer.text_for_range(selection.range()).collect::<String>());
7854 }
7855
7856 if let Some(next_selection) = selections_iter.peek() {
7857 if next_selection.range().len() == selection.range().len() {
7858 let next_selected_text = buffer
7859 .text_for_range(next_selection.range())
7860 .collect::<String>();
7861 if Some(next_selected_text) != selected_text {
7862 same_text_selected = false;
7863 selected_text = None;
7864 }
7865 } else {
7866 same_text_selected = false;
7867 selected_text = None;
7868 }
7869 }
7870 }
7871 }
7872
7873 if only_carets {
7874 for selection in &mut selections {
7875 let word_range = movement::surrounding_word(
7876 &display_map,
7877 selection.start.to_display_point(&display_map),
7878 );
7879 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7880 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7881 selection.goal = SelectionGoal::None;
7882 selection.reversed = false;
7883 select_next_match_ranges(
7884 self,
7885 selection.start..selection.end,
7886 replace_newest,
7887 autoscroll,
7888 cx,
7889 );
7890 }
7891
7892 if selections.len() == 1 {
7893 let selection = selections
7894 .last()
7895 .expect("ensured that there's only one selection");
7896 let query = buffer
7897 .text_for_range(selection.start..selection.end)
7898 .collect::<String>();
7899 let is_empty = query.is_empty();
7900 let select_state = SelectNextState {
7901 query: AhoCorasick::new(&[query])?,
7902 wordwise: true,
7903 done: is_empty,
7904 };
7905 self.select_next_state = Some(select_state);
7906 } else {
7907 self.select_next_state = None;
7908 }
7909 } else if let Some(selected_text) = selected_text {
7910 self.select_next_state = Some(SelectNextState {
7911 query: AhoCorasick::new(&[selected_text])?,
7912 wordwise: false,
7913 done: false,
7914 });
7915 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7916 }
7917 }
7918 Ok(())
7919 }
7920
7921 pub fn select_all_matches(
7922 &mut self,
7923 _action: &SelectAllMatches,
7924 cx: &mut ViewContext<Self>,
7925 ) -> Result<()> {
7926 self.push_to_selection_history();
7927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7928
7929 self.select_next_match_internal(&display_map, false, None, cx)?;
7930 let Some(select_next_state) = self.select_next_state.as_mut() else {
7931 return Ok(());
7932 };
7933 if select_next_state.done {
7934 return Ok(());
7935 }
7936
7937 let mut new_selections = self.selections.all::<usize>(cx);
7938
7939 let buffer = &display_map.buffer_snapshot;
7940 let query_matches = select_next_state
7941 .query
7942 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7943
7944 for query_match in query_matches {
7945 let query_match = query_match.unwrap(); // can only fail due to I/O
7946 let offset_range = query_match.start()..query_match.end();
7947 let display_range = offset_range.start.to_display_point(&display_map)
7948 ..offset_range.end.to_display_point(&display_map);
7949
7950 if !select_next_state.wordwise
7951 || (!movement::is_inside_word(&display_map, display_range.start)
7952 && !movement::is_inside_word(&display_map, display_range.end))
7953 {
7954 self.selections.change_with(cx, |selections| {
7955 new_selections.push(Selection {
7956 id: selections.new_selection_id(),
7957 start: offset_range.start,
7958 end: offset_range.end,
7959 reversed: false,
7960 goal: SelectionGoal::None,
7961 });
7962 });
7963 }
7964 }
7965
7966 new_selections.sort_by_key(|selection| selection.start);
7967 let mut ix = 0;
7968 while ix + 1 < new_selections.len() {
7969 let current_selection = &new_selections[ix];
7970 let next_selection = &new_selections[ix + 1];
7971 if current_selection.range().overlaps(&next_selection.range()) {
7972 if current_selection.id < next_selection.id {
7973 new_selections.remove(ix + 1);
7974 } else {
7975 new_selections.remove(ix);
7976 }
7977 } else {
7978 ix += 1;
7979 }
7980 }
7981
7982 select_next_state.done = true;
7983 self.unfold_ranges(
7984 new_selections.iter().map(|selection| selection.range()),
7985 false,
7986 false,
7987 cx,
7988 );
7989 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7990 selections.select(new_selections)
7991 });
7992
7993 Ok(())
7994 }
7995
7996 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7997 self.push_to_selection_history();
7998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7999 self.select_next_match_internal(
8000 &display_map,
8001 action.replace_newest,
8002 Some(Autoscroll::newest()),
8003 cx,
8004 )?;
8005 Ok(())
8006 }
8007
8008 pub fn select_previous(
8009 &mut self,
8010 action: &SelectPrevious,
8011 cx: &mut ViewContext<Self>,
8012 ) -> Result<()> {
8013 self.push_to_selection_history();
8014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8015 let buffer = &display_map.buffer_snapshot;
8016 let mut selections = self.selections.all::<usize>(cx);
8017 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8018 let query = &select_prev_state.query;
8019 if !select_prev_state.done {
8020 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8021 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8022 let mut next_selected_range = None;
8023 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8024 let bytes_before_last_selection =
8025 buffer.reversed_bytes_in_range(0..last_selection.start);
8026 let bytes_after_first_selection =
8027 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8028 let query_matches = query
8029 .stream_find_iter(bytes_before_last_selection)
8030 .map(|result| (last_selection.start, result))
8031 .chain(
8032 query
8033 .stream_find_iter(bytes_after_first_selection)
8034 .map(|result| (buffer.len(), result)),
8035 );
8036 for (end_offset, query_match) in query_matches {
8037 let query_match = query_match.unwrap(); // can only fail due to I/O
8038 let offset_range =
8039 end_offset - query_match.end()..end_offset - query_match.start();
8040 let display_range = offset_range.start.to_display_point(&display_map)
8041 ..offset_range.end.to_display_point(&display_map);
8042
8043 if !select_prev_state.wordwise
8044 || (!movement::is_inside_word(&display_map, display_range.start)
8045 && !movement::is_inside_word(&display_map, display_range.end))
8046 {
8047 next_selected_range = Some(offset_range);
8048 break;
8049 }
8050 }
8051
8052 if let Some(next_selected_range) = next_selected_range {
8053 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8054 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8055 if action.replace_newest {
8056 s.delete(s.newest_anchor().id);
8057 }
8058 s.insert_range(next_selected_range);
8059 });
8060 } else {
8061 select_prev_state.done = true;
8062 }
8063 }
8064
8065 self.select_prev_state = Some(select_prev_state);
8066 } else {
8067 let mut only_carets = true;
8068 let mut same_text_selected = true;
8069 let mut selected_text = None;
8070
8071 let mut selections_iter = selections.iter().peekable();
8072 while let Some(selection) = selections_iter.next() {
8073 if selection.start != selection.end {
8074 only_carets = false;
8075 }
8076
8077 if same_text_selected {
8078 if selected_text.is_none() {
8079 selected_text =
8080 Some(buffer.text_for_range(selection.range()).collect::<String>());
8081 }
8082
8083 if let Some(next_selection) = selections_iter.peek() {
8084 if next_selection.range().len() == selection.range().len() {
8085 let next_selected_text = buffer
8086 .text_for_range(next_selection.range())
8087 .collect::<String>();
8088 if Some(next_selected_text) != selected_text {
8089 same_text_selected = false;
8090 selected_text = None;
8091 }
8092 } else {
8093 same_text_selected = false;
8094 selected_text = None;
8095 }
8096 }
8097 }
8098 }
8099
8100 if only_carets {
8101 for selection in &mut selections {
8102 let word_range = movement::surrounding_word(
8103 &display_map,
8104 selection.start.to_display_point(&display_map),
8105 );
8106 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8107 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8108 selection.goal = SelectionGoal::None;
8109 selection.reversed = false;
8110 }
8111 if selections.len() == 1 {
8112 let selection = selections
8113 .last()
8114 .expect("ensured that there's only one selection");
8115 let query = buffer
8116 .text_for_range(selection.start..selection.end)
8117 .collect::<String>();
8118 let is_empty = query.is_empty();
8119 let select_state = SelectNextState {
8120 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8121 wordwise: true,
8122 done: is_empty,
8123 };
8124 self.select_prev_state = Some(select_state);
8125 } else {
8126 self.select_prev_state = None;
8127 }
8128
8129 self.unfold_ranges(
8130 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8131 false,
8132 true,
8133 cx,
8134 );
8135 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8136 s.select(selections);
8137 });
8138 } else if let Some(selected_text) = selected_text {
8139 self.select_prev_state = Some(SelectNextState {
8140 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8141 wordwise: false,
8142 done: false,
8143 });
8144 self.select_previous(action, cx)?;
8145 }
8146 }
8147 Ok(())
8148 }
8149
8150 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8151 let text_layout_details = &self.text_layout_details(cx);
8152 self.transact(cx, |this, cx| {
8153 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8154 let mut edits = Vec::new();
8155 let mut selection_edit_ranges = Vec::new();
8156 let mut last_toggled_row = None;
8157 let snapshot = this.buffer.read(cx).read(cx);
8158 let empty_str: Arc<str> = Arc::default();
8159 let mut suffixes_inserted = Vec::new();
8160
8161 fn comment_prefix_range(
8162 snapshot: &MultiBufferSnapshot,
8163 row: MultiBufferRow,
8164 comment_prefix: &str,
8165 comment_prefix_whitespace: &str,
8166 ) -> Range<Point> {
8167 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8168
8169 let mut line_bytes = snapshot
8170 .bytes_in_range(start..snapshot.max_point())
8171 .flatten()
8172 .copied();
8173
8174 // If this line currently begins with the line comment prefix, then record
8175 // the range containing the prefix.
8176 if line_bytes
8177 .by_ref()
8178 .take(comment_prefix.len())
8179 .eq(comment_prefix.bytes())
8180 {
8181 // Include any whitespace that matches the comment prefix.
8182 let matching_whitespace_len = line_bytes
8183 .zip(comment_prefix_whitespace.bytes())
8184 .take_while(|(a, b)| a == b)
8185 .count() as u32;
8186 let end = Point::new(
8187 start.row,
8188 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8189 );
8190 start..end
8191 } else {
8192 start..start
8193 }
8194 }
8195
8196 fn comment_suffix_range(
8197 snapshot: &MultiBufferSnapshot,
8198 row: MultiBufferRow,
8199 comment_suffix: &str,
8200 comment_suffix_has_leading_space: bool,
8201 ) -> Range<Point> {
8202 let end = Point::new(row.0, snapshot.line_len(row));
8203 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8204
8205 let mut line_end_bytes = snapshot
8206 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8207 .flatten()
8208 .copied();
8209
8210 let leading_space_len = if suffix_start_column > 0
8211 && line_end_bytes.next() == Some(b' ')
8212 && comment_suffix_has_leading_space
8213 {
8214 1
8215 } else {
8216 0
8217 };
8218
8219 // If this line currently begins with the line comment prefix, then record
8220 // the range containing the prefix.
8221 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8222 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8223 start..end
8224 } else {
8225 end..end
8226 }
8227 }
8228
8229 // TODO: Handle selections that cross excerpts
8230 for selection in &mut selections {
8231 let start_column = snapshot
8232 .indent_size_for_line(MultiBufferRow(selection.start.row))
8233 .len;
8234 let language = if let Some(language) =
8235 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8236 {
8237 language
8238 } else {
8239 continue;
8240 };
8241
8242 selection_edit_ranges.clear();
8243
8244 // If multiple selections contain a given row, avoid processing that
8245 // row more than once.
8246 let mut start_row = MultiBufferRow(selection.start.row);
8247 if last_toggled_row == Some(start_row) {
8248 start_row = start_row.next_row();
8249 }
8250 let end_row =
8251 if selection.end.row > selection.start.row && selection.end.column == 0 {
8252 MultiBufferRow(selection.end.row - 1)
8253 } else {
8254 MultiBufferRow(selection.end.row)
8255 };
8256 last_toggled_row = Some(end_row);
8257
8258 if start_row > end_row {
8259 continue;
8260 }
8261
8262 // If the language has line comments, toggle those.
8263 let full_comment_prefixes = language.line_comment_prefixes();
8264 if !full_comment_prefixes.is_empty() {
8265 let first_prefix = full_comment_prefixes
8266 .first()
8267 .expect("prefixes is non-empty");
8268 let prefix_trimmed_lengths = full_comment_prefixes
8269 .iter()
8270 .map(|p| p.trim_end_matches(' ').len())
8271 .collect::<SmallVec<[usize; 4]>>();
8272
8273 let mut all_selection_lines_are_comments = true;
8274
8275 for row in start_row.0..=end_row.0 {
8276 let row = MultiBufferRow(row);
8277 if start_row < end_row && snapshot.is_line_blank(row) {
8278 continue;
8279 }
8280
8281 let prefix_range = full_comment_prefixes
8282 .iter()
8283 .zip(prefix_trimmed_lengths.iter().copied())
8284 .map(|(prefix, trimmed_prefix_len)| {
8285 comment_prefix_range(
8286 snapshot.deref(),
8287 row,
8288 &prefix[..trimmed_prefix_len],
8289 &prefix[trimmed_prefix_len..],
8290 )
8291 })
8292 .max_by_key(|range| range.end.column - range.start.column)
8293 .expect("prefixes is non-empty");
8294
8295 if prefix_range.is_empty() {
8296 all_selection_lines_are_comments = false;
8297 }
8298
8299 selection_edit_ranges.push(prefix_range);
8300 }
8301
8302 if all_selection_lines_are_comments {
8303 edits.extend(
8304 selection_edit_ranges
8305 .iter()
8306 .cloned()
8307 .map(|range| (range, empty_str.clone())),
8308 );
8309 } else {
8310 let min_column = selection_edit_ranges
8311 .iter()
8312 .map(|range| range.start.column)
8313 .min()
8314 .unwrap_or(0);
8315 edits.extend(selection_edit_ranges.iter().map(|range| {
8316 let position = Point::new(range.start.row, min_column);
8317 (position..position, first_prefix.clone())
8318 }));
8319 }
8320 } else if let Some((full_comment_prefix, comment_suffix)) =
8321 language.block_comment_delimiters()
8322 {
8323 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8324 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8325 let prefix_range = comment_prefix_range(
8326 snapshot.deref(),
8327 start_row,
8328 comment_prefix,
8329 comment_prefix_whitespace,
8330 );
8331 let suffix_range = comment_suffix_range(
8332 snapshot.deref(),
8333 end_row,
8334 comment_suffix.trim_start_matches(' '),
8335 comment_suffix.starts_with(' '),
8336 );
8337
8338 if prefix_range.is_empty() || suffix_range.is_empty() {
8339 edits.push((
8340 prefix_range.start..prefix_range.start,
8341 full_comment_prefix.clone(),
8342 ));
8343 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8344 suffixes_inserted.push((end_row, comment_suffix.len()));
8345 } else {
8346 edits.push((prefix_range, empty_str.clone()));
8347 edits.push((suffix_range, empty_str.clone()));
8348 }
8349 } else {
8350 continue;
8351 }
8352 }
8353
8354 drop(snapshot);
8355 this.buffer.update(cx, |buffer, cx| {
8356 buffer.edit(edits, None, cx);
8357 });
8358
8359 // Adjust selections so that they end before any comment suffixes that
8360 // were inserted.
8361 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8362 let mut selections = this.selections.all::<Point>(cx);
8363 let snapshot = this.buffer.read(cx).read(cx);
8364 for selection in &mut selections {
8365 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8366 match row.cmp(&MultiBufferRow(selection.end.row)) {
8367 Ordering::Less => {
8368 suffixes_inserted.next();
8369 continue;
8370 }
8371 Ordering::Greater => break,
8372 Ordering::Equal => {
8373 if selection.end.column == snapshot.line_len(row) {
8374 if selection.is_empty() {
8375 selection.start.column -= suffix_len as u32;
8376 }
8377 selection.end.column -= suffix_len as u32;
8378 }
8379 break;
8380 }
8381 }
8382 }
8383 }
8384
8385 drop(snapshot);
8386 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8387
8388 let selections = this.selections.all::<Point>(cx);
8389 let selections_on_single_row = selections.windows(2).all(|selections| {
8390 selections[0].start.row == selections[1].start.row
8391 && selections[0].end.row == selections[1].end.row
8392 && selections[0].start.row == selections[0].end.row
8393 });
8394 let selections_selecting = selections
8395 .iter()
8396 .any(|selection| selection.start != selection.end);
8397 let advance_downwards = action.advance_downwards
8398 && selections_on_single_row
8399 && !selections_selecting
8400 && !matches!(this.mode, EditorMode::SingleLine { .. });
8401
8402 if advance_downwards {
8403 let snapshot = this.buffer.read(cx).snapshot(cx);
8404
8405 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8406 s.move_cursors_with(|display_snapshot, display_point, _| {
8407 let mut point = display_point.to_point(display_snapshot);
8408 point.row += 1;
8409 point = snapshot.clip_point(point, Bias::Left);
8410 let display_point = point.to_display_point(display_snapshot);
8411 let goal = SelectionGoal::HorizontalPosition(
8412 display_snapshot
8413 .x_for_display_point(display_point, &text_layout_details)
8414 .into(),
8415 );
8416 (display_point, goal)
8417 })
8418 });
8419 }
8420 });
8421 }
8422
8423 pub fn select_enclosing_symbol(
8424 &mut self,
8425 _: &SelectEnclosingSymbol,
8426 cx: &mut ViewContext<Self>,
8427 ) {
8428 let buffer = self.buffer.read(cx).snapshot(cx);
8429 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8430
8431 fn update_selection(
8432 selection: &Selection<usize>,
8433 buffer_snap: &MultiBufferSnapshot,
8434 ) -> Option<Selection<usize>> {
8435 let cursor = selection.head();
8436 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8437 for symbol in symbols.iter().rev() {
8438 let start = symbol.range.start.to_offset(&buffer_snap);
8439 let end = symbol.range.end.to_offset(&buffer_snap);
8440 let new_range = start..end;
8441 if start < selection.start || end > selection.end {
8442 return Some(Selection {
8443 id: selection.id,
8444 start: new_range.start,
8445 end: new_range.end,
8446 goal: SelectionGoal::None,
8447 reversed: selection.reversed,
8448 });
8449 }
8450 }
8451 None
8452 }
8453
8454 let mut selected_larger_symbol = false;
8455 let new_selections = old_selections
8456 .iter()
8457 .map(|selection| match update_selection(selection, &buffer) {
8458 Some(new_selection) => {
8459 if new_selection.range() != selection.range() {
8460 selected_larger_symbol = true;
8461 }
8462 new_selection
8463 }
8464 None => selection.clone(),
8465 })
8466 .collect::<Vec<_>>();
8467
8468 if selected_larger_symbol {
8469 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8470 s.select(new_selections);
8471 });
8472 }
8473 }
8474
8475 pub fn select_larger_syntax_node(
8476 &mut self,
8477 _: &SelectLargerSyntaxNode,
8478 cx: &mut ViewContext<Self>,
8479 ) {
8480 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8481 let buffer = self.buffer.read(cx).snapshot(cx);
8482 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8483
8484 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8485 let mut selected_larger_node = false;
8486 let new_selections = old_selections
8487 .iter()
8488 .map(|selection| {
8489 let old_range = selection.start..selection.end;
8490 let mut new_range = old_range.clone();
8491 while let Some(containing_range) =
8492 buffer.range_for_syntax_ancestor(new_range.clone())
8493 {
8494 new_range = containing_range;
8495 if !display_map.intersects_fold(new_range.start)
8496 && !display_map.intersects_fold(new_range.end)
8497 {
8498 break;
8499 }
8500 }
8501
8502 selected_larger_node |= new_range != old_range;
8503 Selection {
8504 id: selection.id,
8505 start: new_range.start,
8506 end: new_range.end,
8507 goal: SelectionGoal::None,
8508 reversed: selection.reversed,
8509 }
8510 })
8511 .collect::<Vec<_>>();
8512
8513 if selected_larger_node {
8514 stack.push(old_selections);
8515 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8516 s.select(new_selections);
8517 });
8518 }
8519 self.select_larger_syntax_node_stack = stack;
8520 }
8521
8522 pub fn select_smaller_syntax_node(
8523 &mut self,
8524 _: &SelectSmallerSyntaxNode,
8525 cx: &mut ViewContext<Self>,
8526 ) {
8527 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8528 if let Some(selections) = stack.pop() {
8529 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8530 s.select(selections.to_vec());
8531 });
8532 }
8533 self.select_larger_syntax_node_stack = stack;
8534 }
8535
8536 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8537 if !EditorSettings::get_global(cx).gutter.runnables {
8538 self.clear_tasks();
8539 return Task::ready(());
8540 }
8541 let project = self.project.clone();
8542 cx.spawn(|this, mut cx| async move {
8543 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8544 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8545 }) else {
8546 return;
8547 };
8548
8549 let Some(project) = project else {
8550 return;
8551 };
8552
8553 let hide_runnables = project
8554 .update(&mut cx, |project, cx| {
8555 // Do not display any test indicators in non-dev server remote projects.
8556 project.is_remote() && project.ssh_connection_string(cx).is_none()
8557 })
8558 .unwrap_or(true);
8559 if hide_runnables {
8560 return;
8561 }
8562 let new_rows =
8563 cx.background_executor()
8564 .spawn({
8565 let snapshot = display_snapshot.clone();
8566 async move {
8567 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8568 }
8569 })
8570 .await;
8571 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8572
8573 this.update(&mut cx, |this, _| {
8574 this.clear_tasks();
8575 for (key, value) in rows {
8576 this.insert_tasks(key, value);
8577 }
8578 })
8579 .ok();
8580 })
8581 }
8582 fn fetch_runnable_ranges(
8583 snapshot: &DisplaySnapshot,
8584 range: Range<Anchor>,
8585 ) -> Vec<language::RunnableRange> {
8586 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8587 }
8588
8589 fn runnable_rows(
8590 project: Model<Project>,
8591 snapshot: DisplaySnapshot,
8592 runnable_ranges: Vec<RunnableRange>,
8593 mut cx: AsyncWindowContext,
8594 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8595 runnable_ranges
8596 .into_iter()
8597 .filter_map(|mut runnable| {
8598 let tasks = cx
8599 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8600 .ok()?;
8601 if tasks.is_empty() {
8602 return None;
8603 }
8604
8605 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8606
8607 let row = snapshot
8608 .buffer_snapshot
8609 .buffer_line_for_row(MultiBufferRow(point.row))?
8610 .1
8611 .start
8612 .row;
8613
8614 let context_range =
8615 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8616 Some((
8617 (runnable.buffer_id, row),
8618 RunnableTasks {
8619 templates: tasks,
8620 offset: MultiBufferOffset(runnable.run_range.start),
8621 context_range,
8622 column: point.column,
8623 extra_variables: runnable.extra_captures,
8624 },
8625 ))
8626 })
8627 .collect()
8628 }
8629
8630 fn templates_with_tags(
8631 project: &Model<Project>,
8632 runnable: &mut Runnable,
8633 cx: &WindowContext<'_>,
8634 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8635 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8636 let (worktree_id, file) = project
8637 .buffer_for_id(runnable.buffer, cx)
8638 .and_then(|buffer| buffer.read(cx).file())
8639 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8640 .unzip();
8641
8642 (project.task_inventory().clone(), worktree_id, file)
8643 });
8644
8645 let inventory = inventory.read(cx);
8646 let tags = mem::take(&mut runnable.tags);
8647 let mut tags: Vec<_> = tags
8648 .into_iter()
8649 .flat_map(|tag| {
8650 let tag = tag.0.clone();
8651 inventory
8652 .list_tasks(
8653 file.clone(),
8654 Some(runnable.language.clone()),
8655 worktree_id,
8656 cx,
8657 )
8658 .into_iter()
8659 .filter(move |(_, template)| {
8660 template.tags.iter().any(|source_tag| source_tag == &tag)
8661 })
8662 })
8663 .sorted_by_key(|(kind, _)| kind.to_owned())
8664 .collect();
8665 if let Some((leading_tag_source, _)) = tags.first() {
8666 // Strongest source wins; if we have worktree tag binding, prefer that to
8667 // global and language bindings;
8668 // if we have a global binding, prefer that to language binding.
8669 let first_mismatch = tags
8670 .iter()
8671 .position(|(tag_source, _)| tag_source != leading_tag_source);
8672 if let Some(index) = first_mismatch {
8673 tags.truncate(index);
8674 }
8675 }
8676
8677 tags
8678 }
8679
8680 pub fn move_to_enclosing_bracket(
8681 &mut self,
8682 _: &MoveToEnclosingBracket,
8683 cx: &mut ViewContext<Self>,
8684 ) {
8685 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8686 s.move_offsets_with(|snapshot, selection| {
8687 let Some(enclosing_bracket_ranges) =
8688 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8689 else {
8690 return;
8691 };
8692
8693 let mut best_length = usize::MAX;
8694 let mut best_inside = false;
8695 let mut best_in_bracket_range = false;
8696 let mut best_destination = None;
8697 for (open, close) in enclosing_bracket_ranges {
8698 let close = close.to_inclusive();
8699 let length = close.end() - open.start;
8700 let inside = selection.start >= open.end && selection.end <= *close.start();
8701 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8702 || close.contains(&selection.head());
8703
8704 // If best is next to a bracket and current isn't, skip
8705 if !in_bracket_range && best_in_bracket_range {
8706 continue;
8707 }
8708
8709 // Prefer smaller lengths unless best is inside and current isn't
8710 if length > best_length && (best_inside || !inside) {
8711 continue;
8712 }
8713
8714 best_length = length;
8715 best_inside = inside;
8716 best_in_bracket_range = in_bracket_range;
8717 best_destination = Some(
8718 if close.contains(&selection.start) && close.contains(&selection.end) {
8719 if inside {
8720 open.end
8721 } else {
8722 open.start
8723 }
8724 } else {
8725 if inside {
8726 *close.start()
8727 } else {
8728 *close.end()
8729 }
8730 },
8731 );
8732 }
8733
8734 if let Some(destination) = best_destination {
8735 selection.collapse_to(destination, SelectionGoal::None);
8736 }
8737 })
8738 });
8739 }
8740
8741 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8742 self.end_selection(cx);
8743 self.selection_history.mode = SelectionHistoryMode::Undoing;
8744 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8745 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8746 self.select_next_state = entry.select_next_state;
8747 self.select_prev_state = entry.select_prev_state;
8748 self.add_selections_state = entry.add_selections_state;
8749 self.request_autoscroll(Autoscroll::newest(), cx);
8750 }
8751 self.selection_history.mode = SelectionHistoryMode::Normal;
8752 }
8753
8754 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8755 self.end_selection(cx);
8756 self.selection_history.mode = SelectionHistoryMode::Redoing;
8757 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8758 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8759 self.select_next_state = entry.select_next_state;
8760 self.select_prev_state = entry.select_prev_state;
8761 self.add_selections_state = entry.add_selections_state;
8762 self.request_autoscroll(Autoscroll::newest(), cx);
8763 }
8764 self.selection_history.mode = SelectionHistoryMode::Normal;
8765 }
8766
8767 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8768 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8769 }
8770
8771 pub fn expand_excerpts_down(
8772 &mut self,
8773 action: &ExpandExcerptsDown,
8774 cx: &mut ViewContext<Self>,
8775 ) {
8776 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8777 }
8778
8779 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8780 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8781 }
8782
8783 pub fn expand_excerpts_for_direction(
8784 &mut self,
8785 lines: u32,
8786 direction: ExpandExcerptDirection,
8787 cx: &mut ViewContext<Self>,
8788 ) {
8789 let selections = self.selections.disjoint_anchors();
8790
8791 let lines = if lines == 0 {
8792 EditorSettings::get_global(cx).expand_excerpt_lines
8793 } else {
8794 lines
8795 };
8796
8797 self.buffer.update(cx, |buffer, cx| {
8798 buffer.expand_excerpts(
8799 selections
8800 .into_iter()
8801 .map(|selection| selection.head().excerpt_id)
8802 .dedup(),
8803 lines,
8804 direction,
8805 cx,
8806 )
8807 })
8808 }
8809
8810 pub fn expand_excerpt(
8811 &mut self,
8812 excerpt: ExcerptId,
8813 direction: ExpandExcerptDirection,
8814 cx: &mut ViewContext<Self>,
8815 ) {
8816 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8817 self.buffer.update(cx, |buffer, cx| {
8818 buffer.expand_excerpts([excerpt], lines, direction, cx)
8819 })
8820 }
8821
8822 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8823 self.go_to_diagnostic_impl(Direction::Next, cx)
8824 }
8825
8826 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8827 self.go_to_diagnostic_impl(Direction::Prev, cx)
8828 }
8829
8830 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8831 let buffer = self.buffer.read(cx).snapshot(cx);
8832 let selection = self.selections.newest::<usize>(cx);
8833
8834 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8835 if direction == Direction::Next {
8836 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8837 let (group_id, jump_to) = popover.activation_info();
8838 if self.activate_diagnostics(group_id, cx) {
8839 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8840 let mut new_selection = s.newest_anchor().clone();
8841 new_selection.collapse_to(jump_to, SelectionGoal::None);
8842 s.select_anchors(vec![new_selection.clone()]);
8843 });
8844 }
8845 return;
8846 }
8847 }
8848
8849 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8850 active_diagnostics
8851 .primary_range
8852 .to_offset(&buffer)
8853 .to_inclusive()
8854 });
8855 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8856 if active_primary_range.contains(&selection.head()) {
8857 *active_primary_range.start()
8858 } else {
8859 selection.head()
8860 }
8861 } else {
8862 selection.head()
8863 };
8864 let snapshot = self.snapshot(cx);
8865 loop {
8866 let diagnostics = if direction == Direction::Prev {
8867 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8868 } else {
8869 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8870 }
8871 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8872 let group = diagnostics
8873 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8874 // be sorted in a stable way
8875 // skip until we are at current active diagnostic, if it exists
8876 .skip_while(|entry| {
8877 (match direction {
8878 Direction::Prev => entry.range.start >= search_start,
8879 Direction::Next => entry.range.start <= search_start,
8880 }) && self
8881 .active_diagnostics
8882 .as_ref()
8883 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8884 })
8885 .find_map(|entry| {
8886 if entry.diagnostic.is_primary
8887 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8888 && !entry.range.is_empty()
8889 // if we match with the active diagnostic, skip it
8890 && Some(entry.diagnostic.group_id)
8891 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8892 {
8893 Some((entry.range, entry.diagnostic.group_id))
8894 } else {
8895 None
8896 }
8897 });
8898
8899 if let Some((primary_range, group_id)) = group {
8900 if self.activate_diagnostics(group_id, cx) {
8901 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8902 s.select(vec![Selection {
8903 id: selection.id,
8904 start: primary_range.start,
8905 end: primary_range.start,
8906 reversed: false,
8907 goal: SelectionGoal::None,
8908 }]);
8909 });
8910 }
8911 break;
8912 } else {
8913 // Cycle around to the start of the buffer, potentially moving back to the start of
8914 // the currently active diagnostic.
8915 active_primary_range.take();
8916 if direction == Direction::Prev {
8917 if search_start == buffer.len() {
8918 break;
8919 } else {
8920 search_start = buffer.len();
8921 }
8922 } else if search_start == 0 {
8923 break;
8924 } else {
8925 search_start = 0;
8926 }
8927 }
8928 }
8929 }
8930
8931 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8932 let snapshot = self
8933 .display_map
8934 .update(cx, |display_map, cx| display_map.snapshot(cx));
8935 let selection = self.selections.newest::<Point>(cx);
8936
8937 if !self.seek_in_direction(
8938 &snapshot,
8939 selection.head(),
8940 false,
8941 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8942 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8943 ),
8944 cx,
8945 ) {
8946 let wrapped_point = Point::zero();
8947 self.seek_in_direction(
8948 &snapshot,
8949 wrapped_point,
8950 true,
8951 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8952 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8953 ),
8954 cx,
8955 );
8956 }
8957 }
8958
8959 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8960 let snapshot = self
8961 .display_map
8962 .update(cx, |display_map, cx| display_map.snapshot(cx));
8963 let selection = self.selections.newest::<Point>(cx);
8964
8965 if !self.seek_in_direction(
8966 &snapshot,
8967 selection.head(),
8968 false,
8969 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8970 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8971 ),
8972 cx,
8973 ) {
8974 let wrapped_point = snapshot.buffer_snapshot.max_point();
8975 self.seek_in_direction(
8976 &snapshot,
8977 wrapped_point,
8978 true,
8979 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8980 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8981 ),
8982 cx,
8983 );
8984 }
8985 }
8986
8987 fn seek_in_direction(
8988 &mut self,
8989 snapshot: &DisplaySnapshot,
8990 initial_point: Point,
8991 is_wrapped: bool,
8992 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8993 cx: &mut ViewContext<Editor>,
8994 ) -> bool {
8995 let display_point = initial_point.to_display_point(snapshot);
8996 let mut hunks = hunks
8997 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8998 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
8999 .dedup();
9000
9001 if let Some(hunk) = hunks.next() {
9002 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9003 let row = hunk.start_display_row();
9004 let point = DisplayPoint::new(row, 0);
9005 s.select_display_ranges([point..point]);
9006 });
9007
9008 true
9009 } else {
9010 false
9011 }
9012 }
9013
9014 pub fn go_to_definition(
9015 &mut self,
9016 _: &GoToDefinition,
9017 cx: &mut ViewContext<Self>,
9018 ) -> Task<Result<bool>> {
9019 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
9020 }
9021
9022 pub fn go_to_declaration(
9023 &mut self,
9024 _: &GoToDeclaration,
9025 cx: &mut ViewContext<Self>,
9026 ) -> Task<Result<bool>> {
9027 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9028 }
9029
9030 pub fn go_to_declaration_split(
9031 &mut self,
9032 _: &GoToDeclaration,
9033 cx: &mut ViewContext<Self>,
9034 ) -> Task<Result<bool>> {
9035 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9036 }
9037
9038 pub fn go_to_implementation(
9039 &mut self,
9040 _: &GoToImplementation,
9041 cx: &mut ViewContext<Self>,
9042 ) -> Task<Result<bool>> {
9043 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9044 }
9045
9046 pub fn go_to_implementation_split(
9047 &mut self,
9048 _: &GoToImplementationSplit,
9049 cx: &mut ViewContext<Self>,
9050 ) -> Task<Result<bool>> {
9051 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9052 }
9053
9054 pub fn go_to_type_definition(
9055 &mut self,
9056 _: &GoToTypeDefinition,
9057 cx: &mut ViewContext<Self>,
9058 ) -> Task<Result<bool>> {
9059 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9060 }
9061
9062 pub fn go_to_definition_split(
9063 &mut self,
9064 _: &GoToDefinitionSplit,
9065 cx: &mut ViewContext<Self>,
9066 ) -> Task<Result<bool>> {
9067 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9068 }
9069
9070 pub fn go_to_type_definition_split(
9071 &mut self,
9072 _: &GoToTypeDefinitionSplit,
9073 cx: &mut ViewContext<Self>,
9074 ) -> Task<Result<bool>> {
9075 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9076 }
9077
9078 fn go_to_definition_of_kind(
9079 &mut self,
9080 kind: GotoDefinitionKind,
9081 split: bool,
9082 cx: &mut ViewContext<Self>,
9083 ) -> Task<Result<bool>> {
9084 let Some(workspace) = self.workspace() else {
9085 return Task::ready(Ok(false));
9086 };
9087 let buffer = self.buffer.read(cx);
9088 let head = self.selections.newest::<usize>(cx).head();
9089 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9090 text_anchor
9091 } else {
9092 return Task::ready(Ok(false));
9093 };
9094
9095 let project = workspace.read(cx).project().clone();
9096 let definitions = project.update(cx, |project, cx| match kind {
9097 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9098 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9099 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9100 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9101 });
9102
9103 cx.spawn(|editor, mut cx| async move {
9104 let definitions = definitions.await?;
9105 let navigated = editor
9106 .update(&mut cx, |editor, cx| {
9107 editor.navigate_to_hover_links(
9108 Some(kind),
9109 definitions
9110 .into_iter()
9111 .filter(|location| {
9112 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9113 })
9114 .map(HoverLink::Text)
9115 .collect::<Vec<_>>(),
9116 split,
9117 cx,
9118 )
9119 })?
9120 .await?;
9121 anyhow::Ok(navigated)
9122 })
9123 }
9124
9125 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9126 let position = self.selections.newest_anchor().head();
9127 let Some((buffer, buffer_position)) =
9128 self.buffer.read(cx).text_anchor_for_position(position, cx)
9129 else {
9130 return;
9131 };
9132
9133 cx.spawn(|editor, mut cx| async move {
9134 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9135 editor.update(&mut cx, |_, cx| {
9136 cx.open_url(&url);
9137 })
9138 } else {
9139 Ok(())
9140 }
9141 })
9142 .detach();
9143 }
9144
9145 pub(crate) fn navigate_to_hover_links(
9146 &mut self,
9147 kind: Option<GotoDefinitionKind>,
9148 mut definitions: Vec<HoverLink>,
9149 split: bool,
9150 cx: &mut ViewContext<Editor>,
9151 ) -> Task<Result<bool>> {
9152 // If there is one definition, just open it directly
9153 if definitions.len() == 1 {
9154 let definition = definitions.pop().unwrap();
9155 let target_task = match definition {
9156 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9157 HoverLink::InlayHint(lsp_location, server_id) => {
9158 self.compute_target_location(lsp_location, server_id, cx)
9159 }
9160 HoverLink::Url(url) => {
9161 cx.open_url(&url);
9162 Task::ready(Ok(None))
9163 }
9164 };
9165 cx.spawn(|editor, mut cx| async move {
9166 let target = target_task.await.context("target resolution task")?;
9167 if let Some(target) = target {
9168 editor.update(&mut cx, |editor, cx| {
9169 let Some(workspace) = editor.workspace() else {
9170 return false;
9171 };
9172 let pane = workspace.read(cx).active_pane().clone();
9173
9174 let range = target.range.to_offset(target.buffer.read(cx));
9175 let range = editor.range_for_match(&range);
9176
9177 /// If select range has more than one line, we
9178 /// just point the cursor to range.start.
9179 fn check_multiline_range(
9180 buffer: &Buffer,
9181 range: Range<usize>,
9182 ) -> Range<usize> {
9183 if buffer.offset_to_point(range.start).row
9184 == buffer.offset_to_point(range.end).row
9185 {
9186 range
9187 } else {
9188 range.start..range.start
9189 }
9190 }
9191
9192 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9193 let buffer = target.buffer.read(cx);
9194 let range = check_multiline_range(buffer, range);
9195 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9196 s.select_ranges([range]);
9197 });
9198 } else {
9199 cx.window_context().defer(move |cx| {
9200 let target_editor: View<Self> =
9201 workspace.update(cx, |workspace, cx| {
9202 let pane = if split {
9203 workspace.adjacent_pane(cx)
9204 } else {
9205 workspace.active_pane().clone()
9206 };
9207
9208 workspace.open_project_item(
9209 pane,
9210 target.buffer.clone(),
9211 true,
9212 true,
9213 cx,
9214 )
9215 });
9216 target_editor.update(cx, |target_editor, cx| {
9217 // When selecting a definition in a different buffer, disable the nav history
9218 // to avoid creating a history entry at the previous cursor location.
9219 pane.update(cx, |pane, _| pane.disable_history());
9220 let buffer = target.buffer.read(cx);
9221 let range = check_multiline_range(buffer, range);
9222 target_editor.change_selections(
9223 Some(Autoscroll::focused()),
9224 cx,
9225 |s| {
9226 s.select_ranges([range]);
9227 },
9228 );
9229 pane.update(cx, |pane, _| pane.enable_history());
9230 });
9231 });
9232 }
9233 true
9234 })
9235 } else {
9236 Ok(false)
9237 }
9238 })
9239 } else if !definitions.is_empty() {
9240 let replica_id = self.replica_id(cx);
9241 cx.spawn(|editor, mut cx| async move {
9242 let (title, location_tasks, workspace) = editor
9243 .update(&mut cx, |editor, cx| {
9244 let tab_kind = match kind {
9245 Some(GotoDefinitionKind::Implementation) => "Implementations",
9246 _ => "Definitions",
9247 };
9248 let title = definitions
9249 .iter()
9250 .find_map(|definition| match definition {
9251 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9252 let buffer = origin.buffer.read(cx);
9253 format!(
9254 "{} for {}",
9255 tab_kind,
9256 buffer
9257 .text_for_range(origin.range.clone())
9258 .collect::<String>()
9259 )
9260 }),
9261 HoverLink::InlayHint(_, _) => None,
9262 HoverLink::Url(_) => None,
9263 })
9264 .unwrap_or(tab_kind.to_string());
9265 let location_tasks = definitions
9266 .into_iter()
9267 .map(|definition| match definition {
9268 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9269 HoverLink::InlayHint(lsp_location, server_id) => {
9270 editor.compute_target_location(lsp_location, server_id, cx)
9271 }
9272 HoverLink::Url(_) => Task::ready(Ok(None)),
9273 })
9274 .collect::<Vec<_>>();
9275 (title, location_tasks, editor.workspace().clone())
9276 })
9277 .context("location tasks preparation")?;
9278
9279 let locations = futures::future::join_all(location_tasks)
9280 .await
9281 .into_iter()
9282 .filter_map(|location| location.transpose())
9283 .collect::<Result<_>>()
9284 .context("location tasks")?;
9285
9286 let Some(workspace) = workspace else {
9287 return Ok(false);
9288 };
9289 let opened = workspace
9290 .update(&mut cx, |workspace, cx| {
9291 Self::open_locations_in_multibuffer(
9292 workspace, locations, replica_id, title, split, cx,
9293 )
9294 })
9295 .ok();
9296
9297 anyhow::Ok(opened.is_some())
9298 })
9299 } else {
9300 Task::ready(Ok(false))
9301 }
9302 }
9303
9304 fn compute_target_location(
9305 &self,
9306 lsp_location: lsp::Location,
9307 server_id: LanguageServerId,
9308 cx: &mut ViewContext<Editor>,
9309 ) -> Task<anyhow::Result<Option<Location>>> {
9310 let Some(project) = self.project.clone() else {
9311 return Task::Ready(Some(Ok(None)));
9312 };
9313
9314 cx.spawn(move |editor, mut cx| async move {
9315 let location_task = editor.update(&mut cx, |editor, cx| {
9316 project.update(cx, |project, cx| {
9317 let language_server_name =
9318 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9319 project
9320 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9321 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9322 });
9323 language_server_name.map(|language_server_name| {
9324 project.open_local_buffer_via_lsp(
9325 lsp_location.uri.clone(),
9326 server_id,
9327 language_server_name,
9328 cx,
9329 )
9330 })
9331 })
9332 })?;
9333 let location = match location_task {
9334 Some(task) => Some({
9335 let target_buffer_handle = task.await.context("open local buffer")?;
9336 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9337 let target_start = target_buffer
9338 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9339 let target_end = target_buffer
9340 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9341 target_buffer.anchor_after(target_start)
9342 ..target_buffer.anchor_before(target_end)
9343 })?;
9344 Location {
9345 buffer: target_buffer_handle,
9346 range,
9347 }
9348 }),
9349 None => None,
9350 };
9351 Ok(location)
9352 })
9353 }
9354
9355 pub fn find_all_references(
9356 &mut self,
9357 _: &FindAllReferences,
9358 cx: &mut ViewContext<Self>,
9359 ) -> Option<Task<Result<()>>> {
9360 let multi_buffer = self.buffer.read(cx);
9361 let selection = self.selections.newest::<usize>(cx);
9362 let head = selection.head();
9363
9364 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9365 let head_anchor = multi_buffer_snapshot.anchor_at(
9366 head,
9367 if head < selection.tail() {
9368 Bias::Right
9369 } else {
9370 Bias::Left
9371 },
9372 );
9373
9374 match self
9375 .find_all_references_task_sources
9376 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9377 {
9378 Ok(_) => {
9379 log::info!(
9380 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9381 );
9382 return None;
9383 }
9384 Err(i) => {
9385 self.find_all_references_task_sources.insert(i, head_anchor);
9386 }
9387 }
9388
9389 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9390 let replica_id = self.replica_id(cx);
9391 let workspace = self.workspace()?;
9392 let project = workspace.read(cx).project().clone();
9393 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9394 Some(cx.spawn(|editor, mut cx| async move {
9395 let _cleanup = defer({
9396 let mut cx = cx.clone();
9397 move || {
9398 let _ = editor.update(&mut cx, |editor, _| {
9399 if let Ok(i) =
9400 editor
9401 .find_all_references_task_sources
9402 .binary_search_by(|anchor| {
9403 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9404 })
9405 {
9406 editor.find_all_references_task_sources.remove(i);
9407 }
9408 });
9409 }
9410 });
9411
9412 let locations = references.await?;
9413 if locations.is_empty() {
9414 return anyhow::Ok(());
9415 }
9416
9417 workspace.update(&mut cx, |workspace, cx| {
9418 let title = locations
9419 .first()
9420 .as_ref()
9421 .map(|location| {
9422 let buffer = location.buffer.read(cx);
9423 format!(
9424 "References to `{}`",
9425 buffer
9426 .text_for_range(location.range.clone())
9427 .collect::<String>()
9428 )
9429 })
9430 .unwrap();
9431 Self::open_locations_in_multibuffer(
9432 workspace, locations, replica_id, title, false, cx,
9433 );
9434 })
9435 }))
9436 }
9437
9438 /// Opens a multibuffer with the given project locations in it
9439 pub fn open_locations_in_multibuffer(
9440 workspace: &mut Workspace,
9441 mut locations: Vec<Location>,
9442 replica_id: ReplicaId,
9443 title: String,
9444 split: bool,
9445 cx: &mut ViewContext<Workspace>,
9446 ) {
9447 // If there are multiple definitions, open them in a multibuffer
9448 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9449 let mut locations = locations.into_iter().peekable();
9450 let mut ranges_to_highlight = Vec::new();
9451 let capability = workspace.project().read(cx).capability();
9452
9453 let excerpt_buffer = cx.new_model(|cx| {
9454 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9455 while let Some(location) = locations.next() {
9456 let buffer = location.buffer.read(cx);
9457 let mut ranges_for_buffer = Vec::new();
9458 let range = location.range.to_offset(buffer);
9459 ranges_for_buffer.push(range.clone());
9460
9461 while let Some(next_location) = locations.peek() {
9462 if next_location.buffer == location.buffer {
9463 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9464 locations.next();
9465 } else {
9466 break;
9467 }
9468 }
9469
9470 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9471 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9472 location.buffer.clone(),
9473 ranges_for_buffer,
9474 DEFAULT_MULTIBUFFER_CONTEXT,
9475 cx,
9476 ))
9477 }
9478
9479 multibuffer.with_title(title)
9480 });
9481
9482 let editor = cx.new_view(|cx| {
9483 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9484 });
9485 editor.update(cx, |editor, cx| {
9486 if let Some(first_range) = ranges_to_highlight.first() {
9487 editor.change_selections(None, cx, |selections| {
9488 selections.clear_disjoint();
9489 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9490 });
9491 }
9492 editor.highlight_background::<Self>(
9493 &ranges_to_highlight,
9494 |theme| theme.editor_highlighted_line_background,
9495 cx,
9496 );
9497 });
9498
9499 let item = Box::new(editor);
9500 let item_id = item.item_id();
9501
9502 if split {
9503 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9504 } else {
9505 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9506 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9507 pane.close_current_preview_item(cx)
9508 } else {
9509 None
9510 }
9511 });
9512 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9513 }
9514 workspace.active_pane().update(cx, |pane, cx| {
9515 pane.set_preview_item_id(Some(item_id), cx);
9516 });
9517 }
9518
9519 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9520 use language::ToOffset as _;
9521
9522 let project = self.project.clone()?;
9523 let selection = self.selections.newest_anchor().clone();
9524 let (cursor_buffer, cursor_buffer_position) = self
9525 .buffer
9526 .read(cx)
9527 .text_anchor_for_position(selection.head(), cx)?;
9528 let (tail_buffer, cursor_buffer_position_end) = self
9529 .buffer
9530 .read(cx)
9531 .text_anchor_for_position(selection.tail(), cx)?;
9532 if tail_buffer != cursor_buffer {
9533 return None;
9534 }
9535
9536 let snapshot = cursor_buffer.read(cx).snapshot();
9537 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9538 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9539 let prepare_rename = project.update(cx, |project, cx| {
9540 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9541 });
9542 drop(snapshot);
9543
9544 Some(cx.spawn(|this, mut cx| async move {
9545 let rename_range = if let Some(range) = prepare_rename.await? {
9546 Some(range)
9547 } else {
9548 this.update(&mut cx, |this, cx| {
9549 let buffer = this.buffer.read(cx).snapshot(cx);
9550 let mut buffer_highlights = this
9551 .document_highlights_for_position(selection.head(), &buffer)
9552 .filter(|highlight| {
9553 highlight.start.excerpt_id == selection.head().excerpt_id
9554 && highlight.end.excerpt_id == selection.head().excerpt_id
9555 });
9556 buffer_highlights
9557 .next()
9558 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9559 })?
9560 };
9561 if let Some(rename_range) = rename_range {
9562 this.update(&mut cx, |this, cx| {
9563 let snapshot = cursor_buffer.read(cx).snapshot();
9564 let rename_buffer_range = rename_range.to_offset(&snapshot);
9565 let cursor_offset_in_rename_range =
9566 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9567 let cursor_offset_in_rename_range_end =
9568 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9569
9570 this.take_rename(false, cx);
9571 let buffer = this.buffer.read(cx).read(cx);
9572 let cursor_offset = selection.head().to_offset(&buffer);
9573 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9574 let rename_end = rename_start + rename_buffer_range.len();
9575 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9576 let mut old_highlight_id = None;
9577 let old_name: Arc<str> = buffer
9578 .chunks(rename_start..rename_end, true)
9579 .map(|chunk| {
9580 if old_highlight_id.is_none() {
9581 old_highlight_id = chunk.syntax_highlight_id;
9582 }
9583 chunk.text
9584 })
9585 .collect::<String>()
9586 .into();
9587
9588 drop(buffer);
9589
9590 // Position the selection in the rename editor so that it matches the current selection.
9591 this.show_local_selections = false;
9592 let rename_editor = cx.new_view(|cx| {
9593 let mut editor = Editor::single_line(cx);
9594 editor.buffer.update(cx, |buffer, cx| {
9595 buffer.edit([(0..0, old_name.clone())], None, cx)
9596 });
9597 let rename_selection_range = match cursor_offset_in_rename_range
9598 .cmp(&cursor_offset_in_rename_range_end)
9599 {
9600 Ordering::Equal => {
9601 editor.select_all(&SelectAll, cx);
9602 return editor;
9603 }
9604 Ordering::Less => {
9605 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9606 }
9607 Ordering::Greater => {
9608 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9609 }
9610 };
9611 if rename_selection_range.end > old_name.len() {
9612 editor.select_all(&SelectAll, cx);
9613 } else {
9614 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9615 s.select_ranges([rename_selection_range]);
9616 });
9617 }
9618 editor
9619 });
9620 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9621 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9622 _ => {}
9623 })
9624 .detach();
9625
9626 let write_highlights =
9627 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9628 let read_highlights =
9629 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9630 let ranges = write_highlights
9631 .iter()
9632 .flat_map(|(_, ranges)| ranges.iter())
9633 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9634 .cloned()
9635 .collect();
9636
9637 this.highlight_text::<Rename>(
9638 ranges,
9639 HighlightStyle {
9640 fade_out: Some(0.6),
9641 ..Default::default()
9642 },
9643 cx,
9644 );
9645 let rename_focus_handle = rename_editor.focus_handle(cx);
9646 cx.focus(&rename_focus_handle);
9647 let block_id = this.insert_blocks(
9648 [BlockProperties {
9649 style: BlockStyle::Flex,
9650 position: range.start,
9651 height: 1,
9652 render: Box::new({
9653 let rename_editor = rename_editor.clone();
9654 move |cx: &mut BlockContext| {
9655 let mut text_style = cx.editor_style.text.clone();
9656 if let Some(highlight_style) = old_highlight_id
9657 .and_then(|h| h.style(&cx.editor_style.syntax))
9658 {
9659 text_style = text_style.highlight(highlight_style);
9660 }
9661 div()
9662 .pl(cx.anchor_x)
9663 .child(EditorElement::new(
9664 &rename_editor,
9665 EditorStyle {
9666 background: cx.theme().system().transparent,
9667 local_player: cx.editor_style.local_player,
9668 text: text_style,
9669 scrollbar_width: cx.editor_style.scrollbar_width,
9670 syntax: cx.editor_style.syntax.clone(),
9671 status: cx.editor_style.status.clone(),
9672 inlay_hints_style: HighlightStyle {
9673 color: Some(cx.theme().status().hint),
9674 font_weight: Some(FontWeight::BOLD),
9675 ..HighlightStyle::default()
9676 },
9677 suggestions_style: HighlightStyle {
9678 color: Some(cx.theme().status().predictive),
9679 ..HighlightStyle::default()
9680 },
9681 },
9682 ))
9683 .into_any_element()
9684 }
9685 }),
9686 disposition: BlockDisposition::Below,
9687 priority: 0,
9688 }],
9689 Some(Autoscroll::fit()),
9690 cx,
9691 )[0];
9692 this.pending_rename = Some(RenameState {
9693 range,
9694 old_name,
9695 editor: rename_editor,
9696 block_id,
9697 });
9698 })?;
9699 }
9700
9701 Ok(())
9702 }))
9703 }
9704
9705 pub fn confirm_rename(
9706 &mut self,
9707 _: &ConfirmRename,
9708 cx: &mut ViewContext<Self>,
9709 ) -> Option<Task<Result<()>>> {
9710 let rename = self.take_rename(false, cx)?;
9711 let workspace = self.workspace()?;
9712 let (start_buffer, start) = self
9713 .buffer
9714 .read(cx)
9715 .text_anchor_for_position(rename.range.start, cx)?;
9716 let (end_buffer, end) = self
9717 .buffer
9718 .read(cx)
9719 .text_anchor_for_position(rename.range.end, cx)?;
9720 if start_buffer != end_buffer {
9721 return None;
9722 }
9723
9724 let buffer = start_buffer;
9725 let range = start..end;
9726 let old_name = rename.old_name;
9727 let new_name = rename.editor.read(cx).text(cx);
9728
9729 let rename = workspace
9730 .read(cx)
9731 .project()
9732 .clone()
9733 .update(cx, |project, cx| {
9734 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9735 });
9736 let workspace = workspace.downgrade();
9737
9738 Some(cx.spawn(|editor, mut cx| async move {
9739 let project_transaction = rename.await?;
9740 Self::open_project_transaction(
9741 &editor,
9742 workspace,
9743 project_transaction,
9744 format!("Rename: {} → {}", old_name, new_name),
9745 cx.clone(),
9746 )
9747 .await?;
9748
9749 editor.update(&mut cx, |editor, cx| {
9750 editor.refresh_document_highlights(cx);
9751 })?;
9752 Ok(())
9753 }))
9754 }
9755
9756 fn take_rename(
9757 &mut self,
9758 moving_cursor: bool,
9759 cx: &mut ViewContext<Self>,
9760 ) -> Option<RenameState> {
9761 let rename = self.pending_rename.take()?;
9762 if rename.editor.focus_handle(cx).is_focused(cx) {
9763 cx.focus(&self.focus_handle);
9764 }
9765
9766 self.remove_blocks(
9767 [rename.block_id].into_iter().collect(),
9768 Some(Autoscroll::fit()),
9769 cx,
9770 );
9771 self.clear_highlights::<Rename>(cx);
9772 self.show_local_selections = true;
9773
9774 if moving_cursor {
9775 let rename_editor = rename.editor.read(cx);
9776 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9777
9778 // Update the selection to match the position of the selection inside
9779 // the rename editor.
9780 let snapshot = self.buffer.read(cx).read(cx);
9781 let rename_range = rename.range.to_offset(&snapshot);
9782 let cursor_in_editor = snapshot
9783 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9784 .min(rename_range.end);
9785 drop(snapshot);
9786
9787 self.change_selections(None, cx, |s| {
9788 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9789 });
9790 } else {
9791 self.refresh_document_highlights(cx);
9792 }
9793
9794 Some(rename)
9795 }
9796
9797 pub fn pending_rename(&self) -> Option<&RenameState> {
9798 self.pending_rename.as_ref()
9799 }
9800
9801 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9802 let project = match &self.project {
9803 Some(project) => project.clone(),
9804 None => return None,
9805 };
9806
9807 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9808 }
9809
9810 fn perform_format(
9811 &mut self,
9812 project: Model<Project>,
9813 trigger: FormatTrigger,
9814 cx: &mut ViewContext<Self>,
9815 ) -> Task<Result<()>> {
9816 let buffer = self.buffer().clone();
9817 let mut buffers = buffer.read(cx).all_buffers();
9818 if trigger == FormatTrigger::Save {
9819 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9820 }
9821
9822 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9823 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9824
9825 cx.spawn(|_, mut cx| async move {
9826 let transaction = futures::select_biased! {
9827 () = timeout => {
9828 log::warn!("timed out waiting for formatting");
9829 None
9830 }
9831 transaction = format.log_err().fuse() => transaction,
9832 };
9833
9834 buffer
9835 .update(&mut cx, |buffer, cx| {
9836 if let Some(transaction) = transaction {
9837 if !buffer.is_singleton() {
9838 buffer.push_transaction(&transaction.0, cx);
9839 }
9840 }
9841
9842 cx.notify();
9843 })
9844 .ok();
9845
9846 Ok(())
9847 })
9848 }
9849
9850 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9851 if let Some(project) = self.project.clone() {
9852 self.buffer.update(cx, |multi_buffer, cx| {
9853 project.update(cx, |project, cx| {
9854 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9855 });
9856 })
9857 }
9858 }
9859
9860 fn cancel_language_server_work(
9861 &mut self,
9862 _: &CancelLanguageServerWork,
9863 cx: &mut ViewContext<Self>,
9864 ) {
9865 if let Some(project) = self.project.clone() {
9866 self.buffer.update(cx, |multi_buffer, cx| {
9867 project.update(cx, |project, cx| {
9868 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9869 });
9870 })
9871 }
9872 }
9873
9874 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9875 cx.show_character_palette();
9876 }
9877
9878 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9879 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9880 let buffer = self.buffer.read(cx).snapshot(cx);
9881 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9882 let is_valid = buffer
9883 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9884 .any(|entry| {
9885 entry.diagnostic.is_primary
9886 && !entry.range.is_empty()
9887 && entry.range.start == primary_range_start
9888 && entry.diagnostic.message == active_diagnostics.primary_message
9889 });
9890
9891 if is_valid != active_diagnostics.is_valid {
9892 active_diagnostics.is_valid = is_valid;
9893 let mut new_styles = HashMap::default();
9894 for (block_id, diagnostic) in &active_diagnostics.blocks {
9895 new_styles.insert(
9896 *block_id,
9897 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9898 );
9899 }
9900 self.display_map.update(cx, |display_map, _cx| {
9901 display_map.replace_blocks(new_styles)
9902 });
9903 }
9904 }
9905 }
9906
9907 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9908 self.dismiss_diagnostics(cx);
9909 let snapshot = self.snapshot(cx);
9910 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9911 let buffer = self.buffer.read(cx).snapshot(cx);
9912
9913 let mut primary_range = None;
9914 let mut primary_message = None;
9915 let mut group_end = Point::zero();
9916 let diagnostic_group = buffer
9917 .diagnostic_group::<MultiBufferPoint>(group_id)
9918 .filter_map(|entry| {
9919 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9920 && (entry.range.start.row == entry.range.end.row
9921 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9922 {
9923 return None;
9924 }
9925 if entry.range.end > group_end {
9926 group_end = entry.range.end;
9927 }
9928 if entry.diagnostic.is_primary {
9929 primary_range = Some(entry.range.clone());
9930 primary_message = Some(entry.diagnostic.message.clone());
9931 }
9932 Some(entry)
9933 })
9934 .collect::<Vec<_>>();
9935 let primary_range = primary_range?;
9936 let primary_message = primary_message?;
9937 let primary_range =
9938 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9939
9940 let blocks = display_map
9941 .insert_blocks(
9942 diagnostic_group.iter().map(|entry| {
9943 let diagnostic = entry.diagnostic.clone();
9944 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
9945 BlockProperties {
9946 style: BlockStyle::Fixed,
9947 position: buffer.anchor_after(entry.range.start),
9948 height: message_height,
9949 render: diagnostic_block_renderer(diagnostic, None, true, true),
9950 disposition: BlockDisposition::Below,
9951 priority: 0,
9952 }
9953 }),
9954 cx,
9955 )
9956 .into_iter()
9957 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9958 .collect();
9959
9960 Some(ActiveDiagnosticGroup {
9961 primary_range,
9962 primary_message,
9963 group_id,
9964 blocks,
9965 is_valid: true,
9966 })
9967 });
9968 self.active_diagnostics.is_some()
9969 }
9970
9971 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9972 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9973 self.display_map.update(cx, |display_map, cx| {
9974 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9975 });
9976 cx.notify();
9977 }
9978 }
9979
9980 pub fn set_selections_from_remote(
9981 &mut self,
9982 selections: Vec<Selection<Anchor>>,
9983 pending_selection: Option<Selection<Anchor>>,
9984 cx: &mut ViewContext<Self>,
9985 ) {
9986 let old_cursor_position = self.selections.newest_anchor().head();
9987 self.selections.change_with(cx, |s| {
9988 s.select_anchors(selections);
9989 if let Some(pending_selection) = pending_selection {
9990 s.set_pending(pending_selection, SelectMode::Character);
9991 } else {
9992 s.clear_pending();
9993 }
9994 });
9995 self.selections_did_change(false, &old_cursor_position, true, cx);
9996 }
9997
9998 fn push_to_selection_history(&mut self) {
9999 self.selection_history.push(SelectionHistoryEntry {
10000 selections: self.selections.disjoint_anchors(),
10001 select_next_state: self.select_next_state.clone(),
10002 select_prev_state: self.select_prev_state.clone(),
10003 add_selections_state: self.add_selections_state.clone(),
10004 });
10005 }
10006
10007 pub fn transact(
10008 &mut self,
10009 cx: &mut ViewContext<Self>,
10010 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10011 ) -> Option<TransactionId> {
10012 self.start_transaction_at(Instant::now(), cx);
10013 update(self, cx);
10014 self.end_transaction_at(Instant::now(), cx)
10015 }
10016
10017 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10018 self.end_selection(cx);
10019 if let Some(tx_id) = self
10020 .buffer
10021 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10022 {
10023 self.selection_history
10024 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10025 cx.emit(EditorEvent::TransactionBegun {
10026 transaction_id: tx_id,
10027 })
10028 }
10029 }
10030
10031 fn end_transaction_at(
10032 &mut self,
10033 now: Instant,
10034 cx: &mut ViewContext<Self>,
10035 ) -> Option<TransactionId> {
10036 if let Some(transaction_id) = self
10037 .buffer
10038 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10039 {
10040 if let Some((_, end_selections)) =
10041 self.selection_history.transaction_mut(transaction_id)
10042 {
10043 *end_selections = Some(self.selections.disjoint_anchors());
10044 } else {
10045 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10046 }
10047
10048 cx.emit(EditorEvent::Edited { transaction_id });
10049 Some(transaction_id)
10050 } else {
10051 None
10052 }
10053 }
10054
10055 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10056 let mut fold_ranges = Vec::new();
10057
10058 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10059
10060 let selections = self.selections.all_adjusted(cx);
10061 for selection in selections {
10062 let range = selection.range().sorted();
10063 let buffer_start_row = range.start.row;
10064
10065 for row in (0..=range.end.row).rev() {
10066 if let Some((foldable_range, fold_text)) =
10067 display_map.foldable_range(MultiBufferRow(row))
10068 {
10069 if foldable_range.end.row >= buffer_start_row {
10070 fold_ranges.push((foldable_range, fold_text));
10071 if row <= range.start.row {
10072 break;
10073 }
10074 }
10075 }
10076 }
10077 }
10078
10079 self.fold_ranges(fold_ranges, true, cx);
10080 }
10081
10082 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10083 let buffer_row = fold_at.buffer_row;
10084 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10085
10086 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10087 let autoscroll = self
10088 .selections
10089 .all::<Point>(cx)
10090 .iter()
10091 .any(|selection| fold_range.overlaps(&selection.range()));
10092
10093 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10094 }
10095 }
10096
10097 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10098 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10099 let buffer = &display_map.buffer_snapshot;
10100 let selections = self.selections.all::<Point>(cx);
10101 let ranges = selections
10102 .iter()
10103 .map(|s| {
10104 let range = s.display_range(&display_map).sorted();
10105 let mut start = range.start.to_point(&display_map);
10106 let mut end = range.end.to_point(&display_map);
10107 start.column = 0;
10108 end.column = buffer.line_len(MultiBufferRow(end.row));
10109 start..end
10110 })
10111 .collect::<Vec<_>>();
10112
10113 self.unfold_ranges(ranges, true, true, cx);
10114 }
10115
10116 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10118
10119 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10120 ..Point::new(
10121 unfold_at.buffer_row.0,
10122 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10123 );
10124
10125 let autoscroll = self
10126 .selections
10127 .all::<Point>(cx)
10128 .iter()
10129 .any(|selection| selection.range().overlaps(&intersection_range));
10130
10131 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10132 }
10133
10134 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10135 let selections = self.selections.all::<Point>(cx);
10136 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10137 let line_mode = self.selections.line_mode;
10138 let ranges = selections.into_iter().map(|s| {
10139 if line_mode {
10140 let start = Point::new(s.start.row, 0);
10141 let end = Point::new(
10142 s.end.row,
10143 display_map
10144 .buffer_snapshot
10145 .line_len(MultiBufferRow(s.end.row)),
10146 );
10147 (start..end, display_map.fold_placeholder.clone())
10148 } else {
10149 (s.start..s.end, display_map.fold_placeholder.clone())
10150 }
10151 });
10152 self.fold_ranges(ranges, true, cx);
10153 }
10154
10155 pub fn fold_ranges<T: ToOffset + Clone>(
10156 &mut self,
10157 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10158 auto_scroll: bool,
10159 cx: &mut ViewContext<Self>,
10160 ) {
10161 let mut fold_ranges = Vec::new();
10162 let mut buffers_affected = HashMap::default();
10163 let multi_buffer = self.buffer().read(cx);
10164 for (fold_range, fold_text) in ranges {
10165 if let Some((_, buffer, _)) =
10166 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10167 {
10168 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10169 };
10170 fold_ranges.push((fold_range, fold_text));
10171 }
10172
10173 let mut ranges = fold_ranges.into_iter().peekable();
10174 if ranges.peek().is_some() {
10175 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10176
10177 if auto_scroll {
10178 self.request_autoscroll(Autoscroll::fit(), cx);
10179 }
10180
10181 for buffer in buffers_affected.into_values() {
10182 self.sync_expanded_diff_hunks(buffer, cx);
10183 }
10184
10185 cx.notify();
10186
10187 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10188 // Clear diagnostics block when folding a range that contains it.
10189 let snapshot = self.snapshot(cx);
10190 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10191 drop(snapshot);
10192 self.active_diagnostics = Some(active_diagnostics);
10193 self.dismiss_diagnostics(cx);
10194 } else {
10195 self.active_diagnostics = Some(active_diagnostics);
10196 }
10197 }
10198
10199 self.scrollbar_marker_state.dirty = true;
10200 }
10201 }
10202
10203 pub fn unfold_ranges<T: ToOffset + Clone>(
10204 &mut self,
10205 ranges: impl IntoIterator<Item = Range<T>>,
10206 inclusive: bool,
10207 auto_scroll: bool,
10208 cx: &mut ViewContext<Self>,
10209 ) {
10210 let mut unfold_ranges = Vec::new();
10211 let mut buffers_affected = HashMap::default();
10212 let multi_buffer = self.buffer().read(cx);
10213 for range in ranges {
10214 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10215 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10216 };
10217 unfold_ranges.push(range);
10218 }
10219
10220 let mut ranges = unfold_ranges.into_iter().peekable();
10221 if ranges.peek().is_some() {
10222 self.display_map
10223 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10224 if auto_scroll {
10225 self.request_autoscroll(Autoscroll::fit(), cx);
10226 }
10227
10228 for buffer in buffers_affected.into_values() {
10229 self.sync_expanded_diff_hunks(buffer, cx);
10230 }
10231
10232 cx.notify();
10233 self.scrollbar_marker_state.dirty = true;
10234 self.active_indent_guides_state.dirty = true;
10235 }
10236 }
10237
10238 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10239 if hovered != self.gutter_hovered {
10240 self.gutter_hovered = hovered;
10241 cx.notify();
10242 }
10243 }
10244
10245 pub fn insert_blocks(
10246 &mut self,
10247 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10248 autoscroll: Option<Autoscroll>,
10249 cx: &mut ViewContext<Self>,
10250 ) -> Vec<CustomBlockId> {
10251 let blocks = self
10252 .display_map
10253 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10254 if let Some(autoscroll) = autoscroll {
10255 self.request_autoscroll(autoscroll, cx);
10256 }
10257 cx.notify();
10258 blocks
10259 }
10260
10261 pub fn resize_blocks(
10262 &mut self,
10263 heights: HashMap<CustomBlockId, u32>,
10264 autoscroll: Option<Autoscroll>,
10265 cx: &mut ViewContext<Self>,
10266 ) {
10267 self.display_map
10268 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10269 if let Some(autoscroll) = autoscroll {
10270 self.request_autoscroll(autoscroll, cx);
10271 }
10272 cx.notify();
10273 }
10274
10275 pub fn replace_blocks(
10276 &mut self,
10277 renderers: HashMap<CustomBlockId, RenderBlock>,
10278 autoscroll: Option<Autoscroll>,
10279 cx: &mut ViewContext<Self>,
10280 ) {
10281 self.display_map
10282 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10283 if let Some(autoscroll) = autoscroll {
10284 self.request_autoscroll(autoscroll, cx);
10285 }
10286 cx.notify();
10287 }
10288
10289 pub fn remove_blocks(
10290 &mut self,
10291 block_ids: HashSet<CustomBlockId>,
10292 autoscroll: Option<Autoscroll>,
10293 cx: &mut ViewContext<Self>,
10294 ) {
10295 self.display_map.update(cx, |display_map, cx| {
10296 display_map.remove_blocks(block_ids, cx)
10297 });
10298 if let Some(autoscroll) = autoscroll {
10299 self.request_autoscroll(autoscroll, cx);
10300 }
10301 cx.notify();
10302 }
10303
10304 pub fn row_for_block(
10305 &self,
10306 block_id: CustomBlockId,
10307 cx: &mut ViewContext<Self>,
10308 ) -> Option<DisplayRow> {
10309 self.display_map
10310 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10311 }
10312
10313 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10314 self.focused_block = Some(focused_block);
10315 }
10316
10317 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10318 self.focused_block.take()
10319 }
10320
10321 pub fn insert_creases(
10322 &mut self,
10323 creases: impl IntoIterator<Item = Crease>,
10324 cx: &mut ViewContext<Self>,
10325 ) -> Vec<CreaseId> {
10326 self.display_map
10327 .update(cx, |map, cx| map.insert_creases(creases, cx))
10328 }
10329
10330 pub fn remove_creases(
10331 &mut self,
10332 ids: impl IntoIterator<Item = CreaseId>,
10333 cx: &mut ViewContext<Self>,
10334 ) {
10335 self.display_map
10336 .update(cx, |map, cx| map.remove_creases(ids, cx));
10337 }
10338
10339 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10340 self.display_map
10341 .update(cx, |map, cx| map.snapshot(cx))
10342 .longest_row()
10343 }
10344
10345 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10346 self.display_map
10347 .update(cx, |map, cx| map.snapshot(cx))
10348 .max_point()
10349 }
10350
10351 pub fn text(&self, cx: &AppContext) -> String {
10352 self.buffer.read(cx).read(cx).text()
10353 }
10354
10355 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10356 let text = self.text(cx);
10357 let text = text.trim();
10358
10359 if text.is_empty() {
10360 return None;
10361 }
10362
10363 Some(text.to_string())
10364 }
10365
10366 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10367 self.transact(cx, |this, cx| {
10368 this.buffer
10369 .read(cx)
10370 .as_singleton()
10371 .expect("you can only call set_text on editors for singleton buffers")
10372 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10373 });
10374 }
10375
10376 pub fn display_text(&self, cx: &mut AppContext) -> String {
10377 self.display_map
10378 .update(cx, |map, cx| map.snapshot(cx))
10379 .text()
10380 }
10381
10382 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10383 let mut wrap_guides = smallvec::smallvec![];
10384
10385 if self.show_wrap_guides == Some(false) {
10386 return wrap_guides;
10387 }
10388
10389 let settings = self.buffer.read(cx).settings_at(0, cx);
10390 if settings.show_wrap_guides {
10391 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10392 wrap_guides.push((soft_wrap as usize, true));
10393 }
10394 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10395 }
10396
10397 wrap_guides
10398 }
10399
10400 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10401 let settings = self.buffer.read(cx).settings_at(0, cx);
10402 let mode = self
10403 .soft_wrap_mode_override
10404 .unwrap_or_else(|| settings.soft_wrap);
10405 match mode {
10406 language_settings::SoftWrap::None => SoftWrap::None,
10407 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10408 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10409 language_settings::SoftWrap::PreferredLineLength => {
10410 SoftWrap::Column(settings.preferred_line_length)
10411 }
10412 }
10413 }
10414
10415 pub fn set_soft_wrap_mode(
10416 &mut self,
10417 mode: language_settings::SoftWrap,
10418 cx: &mut ViewContext<Self>,
10419 ) {
10420 self.soft_wrap_mode_override = Some(mode);
10421 cx.notify();
10422 }
10423
10424 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10425 let rem_size = cx.rem_size();
10426 self.display_map.update(cx, |map, cx| {
10427 map.set_font(
10428 style.text.font(),
10429 style.text.font_size.to_pixels(rem_size),
10430 cx,
10431 )
10432 });
10433 self.style = Some(style);
10434 }
10435
10436 pub fn style(&self) -> Option<&EditorStyle> {
10437 self.style.as_ref()
10438 }
10439
10440 // Called by the element. This method is not designed to be called outside of the editor
10441 // element's layout code because it does not notify when rewrapping is computed synchronously.
10442 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10443 self.display_map
10444 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10445 }
10446
10447 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10448 if self.soft_wrap_mode_override.is_some() {
10449 self.soft_wrap_mode_override.take();
10450 } else {
10451 let soft_wrap = match self.soft_wrap_mode(cx) {
10452 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10453 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10454 language_settings::SoftWrap::PreferLine
10455 }
10456 };
10457 self.soft_wrap_mode_override = Some(soft_wrap);
10458 }
10459 cx.notify();
10460 }
10461
10462 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10463 let Some(workspace) = self.workspace() else {
10464 return;
10465 };
10466 let fs = workspace.read(cx).app_state().fs.clone();
10467 let current_show = TabBarSettings::get_global(cx).show;
10468 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10469 setting.show = Some(!current_show);
10470 });
10471 }
10472
10473 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10474 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10475 self.buffer
10476 .read(cx)
10477 .settings_at(0, cx)
10478 .indent_guides
10479 .enabled
10480 });
10481 self.show_indent_guides = Some(!currently_enabled);
10482 cx.notify();
10483 }
10484
10485 fn should_show_indent_guides(&self) -> Option<bool> {
10486 self.show_indent_guides
10487 }
10488
10489 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10490 let mut editor_settings = EditorSettings::get_global(cx).clone();
10491 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10492 EditorSettings::override_global(editor_settings, cx);
10493 }
10494
10495 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10496 self.show_gutter = show_gutter;
10497 cx.notify();
10498 }
10499
10500 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10501 self.show_line_numbers = Some(show_line_numbers);
10502 cx.notify();
10503 }
10504
10505 pub fn set_show_git_diff_gutter(
10506 &mut self,
10507 show_git_diff_gutter: bool,
10508 cx: &mut ViewContext<Self>,
10509 ) {
10510 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10511 cx.notify();
10512 }
10513
10514 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10515 self.show_code_actions = Some(show_code_actions);
10516 cx.notify();
10517 }
10518
10519 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10520 self.show_runnables = Some(show_runnables);
10521 cx.notify();
10522 }
10523
10524 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10525 if self.display_map.read(cx).masked != masked {
10526 self.display_map.update(cx, |map, _| map.masked = masked);
10527 }
10528 cx.notify()
10529 }
10530
10531 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10532 self.show_wrap_guides = Some(show_wrap_guides);
10533 cx.notify();
10534 }
10535
10536 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10537 self.show_indent_guides = Some(show_indent_guides);
10538 cx.notify();
10539 }
10540
10541 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10542 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10543 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10544 if let Some(dir) = file.abs_path(cx).parent() {
10545 return Some(dir.to_owned());
10546 }
10547 }
10548
10549 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10550 return Some(project_path.path.to_path_buf());
10551 }
10552 }
10553
10554 None
10555 }
10556
10557 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10558 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10559 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10560 cx.reveal_path(&file.abs_path(cx));
10561 }
10562 }
10563 }
10564
10565 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10566 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10567 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10568 if let Some(path) = file.abs_path(cx).to_str() {
10569 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10570 }
10571 }
10572 }
10573 }
10574
10575 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10576 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10577 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10578 if let Some(path) = file.path().to_str() {
10579 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10580 }
10581 }
10582 }
10583 }
10584
10585 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10586 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10587
10588 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10589 self.start_git_blame(true, cx);
10590 }
10591
10592 cx.notify();
10593 }
10594
10595 pub fn toggle_git_blame_inline(
10596 &mut self,
10597 _: &ToggleGitBlameInline,
10598 cx: &mut ViewContext<Self>,
10599 ) {
10600 self.toggle_git_blame_inline_internal(true, cx);
10601 cx.notify();
10602 }
10603
10604 pub fn git_blame_inline_enabled(&self) -> bool {
10605 self.git_blame_inline_enabled
10606 }
10607
10608 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10609 self.show_selection_menu = self
10610 .show_selection_menu
10611 .map(|show_selections_menu| !show_selections_menu)
10612 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10613
10614 cx.notify();
10615 }
10616
10617 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10618 self.show_selection_menu
10619 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10620 }
10621
10622 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10623 if let Some(project) = self.project.as_ref() {
10624 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10625 return;
10626 };
10627
10628 if buffer.read(cx).file().is_none() {
10629 return;
10630 }
10631
10632 let focused = self.focus_handle(cx).contains_focused(cx);
10633
10634 let project = project.clone();
10635 let blame =
10636 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10637 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10638 self.blame = Some(blame);
10639 }
10640 }
10641
10642 fn toggle_git_blame_inline_internal(
10643 &mut self,
10644 user_triggered: bool,
10645 cx: &mut ViewContext<Self>,
10646 ) {
10647 if self.git_blame_inline_enabled {
10648 self.git_blame_inline_enabled = false;
10649 self.show_git_blame_inline = false;
10650 self.show_git_blame_inline_delay_task.take();
10651 } else {
10652 self.git_blame_inline_enabled = true;
10653 self.start_git_blame_inline(user_triggered, cx);
10654 }
10655
10656 cx.notify();
10657 }
10658
10659 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10660 self.start_git_blame(user_triggered, cx);
10661
10662 if ProjectSettings::get_global(cx)
10663 .git
10664 .inline_blame_delay()
10665 .is_some()
10666 {
10667 self.start_inline_blame_timer(cx);
10668 } else {
10669 self.show_git_blame_inline = true
10670 }
10671 }
10672
10673 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10674 self.blame.as_ref()
10675 }
10676
10677 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10678 self.show_git_blame_gutter && self.has_blame_entries(cx)
10679 }
10680
10681 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10682 self.show_git_blame_inline
10683 && self.focus_handle.is_focused(cx)
10684 && !self.newest_selection_head_on_empty_line(cx)
10685 && self.has_blame_entries(cx)
10686 }
10687
10688 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10689 self.blame()
10690 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10691 }
10692
10693 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10694 let cursor_anchor = self.selections.newest_anchor().head();
10695
10696 let snapshot = self.buffer.read(cx).snapshot(cx);
10697 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10698
10699 snapshot.line_len(buffer_row) == 0
10700 }
10701
10702 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10703 let (path, selection, repo) = maybe!({
10704 let project_handle = self.project.as_ref()?.clone();
10705 let project = project_handle.read(cx);
10706
10707 let selection = self.selections.newest::<Point>(cx);
10708 let selection_range = selection.range();
10709
10710 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10711 (buffer, selection_range.start.row..selection_range.end.row)
10712 } else {
10713 let buffer_ranges = self
10714 .buffer()
10715 .read(cx)
10716 .range_to_buffer_ranges(selection_range, cx);
10717
10718 let (buffer, range, _) = if selection.reversed {
10719 buffer_ranges.first()
10720 } else {
10721 buffer_ranges.last()
10722 }?;
10723
10724 let snapshot = buffer.read(cx).snapshot();
10725 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10726 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10727 (buffer.clone(), selection)
10728 };
10729
10730 let path = buffer
10731 .read(cx)
10732 .file()?
10733 .as_local()?
10734 .path()
10735 .to_str()?
10736 .to_string();
10737 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10738 Some((path, selection, repo))
10739 })
10740 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10741
10742 const REMOTE_NAME: &str = "origin";
10743 let origin_url = repo
10744 .remote_url(REMOTE_NAME)
10745 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10746 let sha = repo
10747 .head_sha()
10748 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10749
10750 let (provider, remote) =
10751 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10752 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10753
10754 Ok(provider.build_permalink(
10755 remote,
10756 BuildPermalinkParams {
10757 sha: &sha,
10758 path: &path,
10759 selection: Some(selection),
10760 },
10761 ))
10762 }
10763
10764 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10765 let permalink = self.get_permalink_to_line(cx);
10766
10767 match permalink {
10768 Ok(permalink) => {
10769 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10770 }
10771 Err(err) => {
10772 let message = format!("Failed to copy permalink: {err}");
10773
10774 Err::<(), anyhow::Error>(err).log_err();
10775
10776 if let Some(workspace) = self.workspace() {
10777 workspace.update(cx, |workspace, cx| {
10778 struct CopyPermalinkToLine;
10779
10780 workspace.show_toast(
10781 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10782 cx,
10783 )
10784 })
10785 }
10786 }
10787 }
10788 }
10789
10790 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10791 let permalink = self.get_permalink_to_line(cx);
10792
10793 match permalink {
10794 Ok(permalink) => {
10795 cx.open_url(permalink.as_ref());
10796 }
10797 Err(err) => {
10798 let message = format!("Failed to open permalink: {err}");
10799
10800 Err::<(), anyhow::Error>(err).log_err();
10801
10802 if let Some(workspace) = self.workspace() {
10803 workspace.update(cx, |workspace, cx| {
10804 struct OpenPermalinkToLine;
10805
10806 workspace.show_toast(
10807 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10808 cx,
10809 )
10810 })
10811 }
10812 }
10813 }
10814 }
10815
10816 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10817 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10818 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10819 pub fn highlight_rows<T: 'static>(
10820 &mut self,
10821 rows: RangeInclusive<Anchor>,
10822 color: Option<Hsla>,
10823 should_autoscroll: bool,
10824 cx: &mut ViewContext<Self>,
10825 ) {
10826 let snapshot = self.buffer().read(cx).snapshot(cx);
10827 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10828 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10829 highlight
10830 .range
10831 .start()
10832 .cmp(&rows.start(), &snapshot)
10833 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10834 });
10835 match (color, existing_highlight_index) {
10836 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10837 ix,
10838 RowHighlight {
10839 index: post_inc(&mut self.highlight_order),
10840 range: rows,
10841 should_autoscroll,
10842 color,
10843 },
10844 ),
10845 (None, Ok(i)) => {
10846 row_highlights.remove(i);
10847 }
10848 }
10849 }
10850
10851 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10852 pub fn clear_row_highlights<T: 'static>(&mut self) {
10853 self.highlighted_rows.remove(&TypeId::of::<T>());
10854 }
10855
10856 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10857 pub fn highlighted_rows<T: 'static>(
10858 &self,
10859 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10860 Some(
10861 self.highlighted_rows
10862 .get(&TypeId::of::<T>())?
10863 .iter()
10864 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10865 )
10866 }
10867
10868 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10869 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10870 /// Allows to ignore certain kinds of highlights.
10871 pub fn highlighted_display_rows(
10872 &mut self,
10873 cx: &mut WindowContext,
10874 ) -> BTreeMap<DisplayRow, Hsla> {
10875 let snapshot = self.snapshot(cx);
10876 let mut used_highlight_orders = HashMap::default();
10877 self.highlighted_rows
10878 .iter()
10879 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10880 .fold(
10881 BTreeMap::<DisplayRow, Hsla>::new(),
10882 |mut unique_rows, highlight| {
10883 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10884 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10885 for row in start_row.0..=end_row.0 {
10886 let used_index =
10887 used_highlight_orders.entry(row).or_insert(highlight.index);
10888 if highlight.index >= *used_index {
10889 *used_index = highlight.index;
10890 match highlight.color {
10891 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10892 None => unique_rows.remove(&DisplayRow(row)),
10893 };
10894 }
10895 }
10896 unique_rows
10897 },
10898 )
10899 }
10900
10901 pub fn highlighted_display_row_for_autoscroll(
10902 &self,
10903 snapshot: &DisplaySnapshot,
10904 ) -> Option<DisplayRow> {
10905 self.highlighted_rows
10906 .values()
10907 .flat_map(|highlighted_rows| highlighted_rows.iter())
10908 .filter_map(|highlight| {
10909 if highlight.color.is_none() || !highlight.should_autoscroll {
10910 return None;
10911 }
10912 Some(highlight.range.start().to_display_point(&snapshot).row())
10913 })
10914 .min()
10915 }
10916
10917 pub fn set_search_within_ranges(
10918 &mut self,
10919 ranges: &[Range<Anchor>],
10920 cx: &mut ViewContext<Self>,
10921 ) {
10922 self.highlight_background::<SearchWithinRange>(
10923 ranges,
10924 |colors| colors.editor_document_highlight_read_background,
10925 cx,
10926 )
10927 }
10928
10929 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10930 self.breadcrumb_header = Some(new_header);
10931 }
10932
10933 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10934 self.clear_background_highlights::<SearchWithinRange>(cx);
10935 }
10936
10937 pub fn highlight_background<T: 'static>(
10938 &mut self,
10939 ranges: &[Range<Anchor>],
10940 color_fetcher: fn(&ThemeColors) -> Hsla,
10941 cx: &mut ViewContext<Self>,
10942 ) {
10943 self.background_highlights
10944 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10945 self.scrollbar_marker_state.dirty = true;
10946 cx.notify();
10947 }
10948
10949 pub fn clear_background_highlights<T: 'static>(
10950 &mut self,
10951 cx: &mut ViewContext<Self>,
10952 ) -> Option<BackgroundHighlight> {
10953 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10954 if !text_highlights.1.is_empty() {
10955 self.scrollbar_marker_state.dirty = true;
10956 cx.notify();
10957 }
10958 Some(text_highlights)
10959 }
10960
10961 pub fn highlight_gutter<T: 'static>(
10962 &mut self,
10963 ranges: &[Range<Anchor>],
10964 color_fetcher: fn(&AppContext) -> Hsla,
10965 cx: &mut ViewContext<Self>,
10966 ) {
10967 self.gutter_highlights
10968 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10969 cx.notify();
10970 }
10971
10972 pub fn clear_gutter_highlights<T: 'static>(
10973 &mut self,
10974 cx: &mut ViewContext<Self>,
10975 ) -> Option<GutterHighlight> {
10976 cx.notify();
10977 self.gutter_highlights.remove(&TypeId::of::<T>())
10978 }
10979
10980 #[cfg(feature = "test-support")]
10981 pub fn all_text_background_highlights(
10982 &mut self,
10983 cx: &mut ViewContext<Self>,
10984 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10985 let snapshot = self.snapshot(cx);
10986 let buffer = &snapshot.buffer_snapshot;
10987 let start = buffer.anchor_before(0);
10988 let end = buffer.anchor_after(buffer.len());
10989 let theme = cx.theme().colors();
10990 self.background_highlights_in_range(start..end, &snapshot, theme)
10991 }
10992
10993 #[cfg(feature = "test-support")]
10994 pub fn search_background_highlights(
10995 &mut self,
10996 cx: &mut ViewContext<Self>,
10997 ) -> Vec<Range<Point>> {
10998 let snapshot = self.buffer().read(cx).snapshot(cx);
10999
11000 let highlights = self
11001 .background_highlights
11002 .get(&TypeId::of::<items::BufferSearchHighlights>());
11003
11004 if let Some((_color, ranges)) = highlights {
11005 ranges
11006 .iter()
11007 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11008 .collect_vec()
11009 } else {
11010 vec![]
11011 }
11012 }
11013
11014 fn document_highlights_for_position<'a>(
11015 &'a self,
11016 position: Anchor,
11017 buffer: &'a MultiBufferSnapshot,
11018 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11019 let read_highlights = self
11020 .background_highlights
11021 .get(&TypeId::of::<DocumentHighlightRead>())
11022 .map(|h| &h.1);
11023 let write_highlights = self
11024 .background_highlights
11025 .get(&TypeId::of::<DocumentHighlightWrite>())
11026 .map(|h| &h.1);
11027 let left_position = position.bias_left(buffer);
11028 let right_position = position.bias_right(buffer);
11029 read_highlights
11030 .into_iter()
11031 .chain(write_highlights)
11032 .flat_map(move |ranges| {
11033 let start_ix = match ranges.binary_search_by(|probe| {
11034 let cmp = probe.end.cmp(&left_position, buffer);
11035 if cmp.is_ge() {
11036 Ordering::Greater
11037 } else {
11038 Ordering::Less
11039 }
11040 }) {
11041 Ok(i) | Err(i) => i,
11042 };
11043
11044 ranges[start_ix..]
11045 .iter()
11046 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11047 })
11048 }
11049
11050 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11051 self.background_highlights
11052 .get(&TypeId::of::<T>())
11053 .map_or(false, |(_, highlights)| !highlights.is_empty())
11054 }
11055
11056 pub fn background_highlights_in_range(
11057 &self,
11058 search_range: Range<Anchor>,
11059 display_snapshot: &DisplaySnapshot,
11060 theme: &ThemeColors,
11061 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11062 let mut results = Vec::new();
11063 for (color_fetcher, ranges) in self.background_highlights.values() {
11064 let color = color_fetcher(theme);
11065 let start_ix = match ranges.binary_search_by(|probe| {
11066 let cmp = probe
11067 .end
11068 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11069 if cmp.is_gt() {
11070 Ordering::Greater
11071 } else {
11072 Ordering::Less
11073 }
11074 }) {
11075 Ok(i) | Err(i) => i,
11076 };
11077 for range in &ranges[start_ix..] {
11078 if range
11079 .start
11080 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11081 .is_ge()
11082 {
11083 break;
11084 }
11085
11086 let start = range.start.to_display_point(&display_snapshot);
11087 let end = range.end.to_display_point(&display_snapshot);
11088 results.push((start..end, color))
11089 }
11090 }
11091 results
11092 }
11093
11094 pub fn background_highlight_row_ranges<T: 'static>(
11095 &self,
11096 search_range: Range<Anchor>,
11097 display_snapshot: &DisplaySnapshot,
11098 count: usize,
11099 ) -> Vec<RangeInclusive<DisplayPoint>> {
11100 let mut results = Vec::new();
11101 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11102 return vec![];
11103 };
11104
11105 let start_ix = match ranges.binary_search_by(|probe| {
11106 let cmp = probe
11107 .end
11108 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11109 if cmp.is_gt() {
11110 Ordering::Greater
11111 } else {
11112 Ordering::Less
11113 }
11114 }) {
11115 Ok(i) | Err(i) => i,
11116 };
11117 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11118 if let (Some(start_display), Some(end_display)) = (start, end) {
11119 results.push(
11120 start_display.to_display_point(display_snapshot)
11121 ..=end_display.to_display_point(display_snapshot),
11122 );
11123 }
11124 };
11125 let mut start_row: Option<Point> = None;
11126 let mut end_row: Option<Point> = None;
11127 if ranges.len() > count {
11128 return Vec::new();
11129 }
11130 for range in &ranges[start_ix..] {
11131 if range
11132 .start
11133 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11134 .is_ge()
11135 {
11136 break;
11137 }
11138 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11139 if let Some(current_row) = &end_row {
11140 if end.row == current_row.row {
11141 continue;
11142 }
11143 }
11144 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11145 if start_row.is_none() {
11146 assert_eq!(end_row, None);
11147 start_row = Some(start);
11148 end_row = Some(end);
11149 continue;
11150 }
11151 if let Some(current_end) = end_row.as_mut() {
11152 if start.row > current_end.row + 1 {
11153 push_region(start_row, end_row);
11154 start_row = Some(start);
11155 end_row = Some(end);
11156 } else {
11157 // Merge two hunks.
11158 *current_end = end;
11159 }
11160 } else {
11161 unreachable!();
11162 }
11163 }
11164 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11165 push_region(start_row, end_row);
11166 results
11167 }
11168
11169 pub fn gutter_highlights_in_range(
11170 &self,
11171 search_range: Range<Anchor>,
11172 display_snapshot: &DisplaySnapshot,
11173 cx: &AppContext,
11174 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11175 let mut results = Vec::new();
11176 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11177 let color = color_fetcher(cx);
11178 let start_ix = match ranges.binary_search_by(|probe| {
11179 let cmp = probe
11180 .end
11181 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11182 if cmp.is_gt() {
11183 Ordering::Greater
11184 } else {
11185 Ordering::Less
11186 }
11187 }) {
11188 Ok(i) | Err(i) => i,
11189 };
11190 for range in &ranges[start_ix..] {
11191 if range
11192 .start
11193 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11194 .is_ge()
11195 {
11196 break;
11197 }
11198
11199 let start = range.start.to_display_point(&display_snapshot);
11200 let end = range.end.to_display_point(&display_snapshot);
11201 results.push((start..end, color))
11202 }
11203 }
11204 results
11205 }
11206
11207 /// Get the text ranges corresponding to the redaction query
11208 pub fn redacted_ranges(
11209 &self,
11210 search_range: Range<Anchor>,
11211 display_snapshot: &DisplaySnapshot,
11212 cx: &WindowContext,
11213 ) -> Vec<Range<DisplayPoint>> {
11214 display_snapshot
11215 .buffer_snapshot
11216 .redacted_ranges(search_range, |file| {
11217 if let Some(file) = file {
11218 file.is_private()
11219 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11220 } else {
11221 false
11222 }
11223 })
11224 .map(|range| {
11225 range.start.to_display_point(display_snapshot)
11226 ..range.end.to_display_point(display_snapshot)
11227 })
11228 .collect()
11229 }
11230
11231 pub fn highlight_text<T: 'static>(
11232 &mut self,
11233 ranges: Vec<Range<Anchor>>,
11234 style: HighlightStyle,
11235 cx: &mut ViewContext<Self>,
11236 ) {
11237 self.display_map.update(cx, |map, _| {
11238 map.highlight_text(TypeId::of::<T>(), ranges, style)
11239 });
11240 cx.notify();
11241 }
11242
11243 pub(crate) fn highlight_inlays<T: 'static>(
11244 &mut self,
11245 highlights: Vec<InlayHighlight>,
11246 style: HighlightStyle,
11247 cx: &mut ViewContext<Self>,
11248 ) {
11249 self.display_map.update(cx, |map, _| {
11250 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11251 });
11252 cx.notify();
11253 }
11254
11255 pub fn text_highlights<'a, T: 'static>(
11256 &'a self,
11257 cx: &'a AppContext,
11258 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11259 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11260 }
11261
11262 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11263 let cleared = self
11264 .display_map
11265 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11266 if cleared {
11267 cx.notify();
11268 }
11269 }
11270
11271 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11272 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11273 && self.focus_handle.is_focused(cx)
11274 }
11275
11276 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11277 self.show_cursor_when_unfocused = is_enabled;
11278 cx.notify();
11279 }
11280
11281 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11282 cx.notify();
11283 }
11284
11285 fn on_buffer_event(
11286 &mut self,
11287 multibuffer: Model<MultiBuffer>,
11288 event: &multi_buffer::Event,
11289 cx: &mut ViewContext<Self>,
11290 ) {
11291 match event {
11292 multi_buffer::Event::Edited {
11293 singleton_buffer_edited,
11294 } => {
11295 self.scrollbar_marker_state.dirty = true;
11296 self.active_indent_guides_state.dirty = true;
11297 self.refresh_active_diagnostics(cx);
11298 self.refresh_code_actions(cx);
11299 if self.has_active_inline_completion(cx) {
11300 self.update_visible_inline_completion(cx);
11301 }
11302 cx.emit(EditorEvent::BufferEdited);
11303 cx.emit(SearchEvent::MatchesInvalidated);
11304 if *singleton_buffer_edited {
11305 if let Some(project) = &self.project {
11306 let project = project.read(cx);
11307 #[allow(clippy::mutable_key_type)]
11308 let languages_affected = multibuffer
11309 .read(cx)
11310 .all_buffers()
11311 .into_iter()
11312 .filter_map(|buffer| {
11313 let buffer = buffer.read(cx);
11314 let language = buffer.language()?;
11315 if project.is_local()
11316 && project.language_servers_for_buffer(buffer, cx).count() == 0
11317 {
11318 None
11319 } else {
11320 Some(language)
11321 }
11322 })
11323 .cloned()
11324 .collect::<HashSet<_>>();
11325 if !languages_affected.is_empty() {
11326 self.refresh_inlay_hints(
11327 InlayHintRefreshReason::BufferEdited(languages_affected),
11328 cx,
11329 );
11330 }
11331 }
11332 }
11333
11334 let Some(project) = &self.project else { return };
11335 let telemetry = project.read(cx).client().telemetry().clone();
11336 refresh_linked_ranges(self, cx);
11337 telemetry.log_edit_event("editor");
11338 }
11339 multi_buffer::Event::ExcerptsAdded {
11340 buffer,
11341 predecessor,
11342 excerpts,
11343 } => {
11344 self.tasks_update_task = Some(self.refresh_runnables(cx));
11345 cx.emit(EditorEvent::ExcerptsAdded {
11346 buffer: buffer.clone(),
11347 predecessor: *predecessor,
11348 excerpts: excerpts.clone(),
11349 });
11350 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11351 }
11352 multi_buffer::Event::ExcerptsRemoved { ids } => {
11353 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11354 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11355 }
11356 multi_buffer::Event::ExcerptsEdited { ids } => {
11357 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11358 }
11359 multi_buffer::Event::ExcerptsExpanded { ids } => {
11360 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11361 }
11362 multi_buffer::Event::Reparsed(buffer_id) => {
11363 self.tasks_update_task = Some(self.refresh_runnables(cx));
11364
11365 cx.emit(EditorEvent::Reparsed(*buffer_id));
11366 }
11367 multi_buffer::Event::LanguageChanged(buffer_id) => {
11368 linked_editing_ranges::refresh_linked_ranges(self, cx);
11369 cx.emit(EditorEvent::Reparsed(*buffer_id));
11370 cx.notify();
11371 }
11372 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11373 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11374 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11375 cx.emit(EditorEvent::TitleChanged)
11376 }
11377 multi_buffer::Event::DiffBaseChanged => {
11378 self.scrollbar_marker_state.dirty = true;
11379 cx.emit(EditorEvent::DiffBaseChanged);
11380 cx.notify();
11381 }
11382 multi_buffer::Event::DiffUpdated { buffer } => {
11383 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11384 cx.notify();
11385 }
11386 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11387 multi_buffer::Event::DiagnosticsUpdated => {
11388 self.refresh_active_diagnostics(cx);
11389 self.scrollbar_marker_state.dirty = true;
11390 cx.notify();
11391 }
11392 _ => {}
11393 };
11394 }
11395
11396 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11397 cx.notify();
11398 }
11399
11400 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11401 self.tasks_update_task = Some(self.refresh_runnables(cx));
11402 self.refresh_inline_completion(true, cx);
11403 self.refresh_inlay_hints(
11404 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11405 self.selections.newest_anchor().head(),
11406 &self.buffer.read(cx).snapshot(cx),
11407 cx,
11408 )),
11409 cx,
11410 );
11411 let editor_settings = EditorSettings::get_global(cx);
11412 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11413 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11414
11415 let project_settings = ProjectSettings::get_global(cx);
11416 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11417
11418 if self.mode == EditorMode::Full {
11419 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11420 if self.git_blame_inline_enabled != inline_blame_enabled {
11421 self.toggle_git_blame_inline_internal(false, cx);
11422 }
11423 }
11424
11425 cx.notify();
11426 }
11427
11428 pub fn set_searchable(&mut self, searchable: bool) {
11429 self.searchable = searchable;
11430 }
11431
11432 pub fn searchable(&self) -> bool {
11433 self.searchable
11434 }
11435
11436 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11437 self.open_excerpts_common(true, cx)
11438 }
11439
11440 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11441 self.open_excerpts_common(false, cx)
11442 }
11443
11444 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11445 let buffer = self.buffer.read(cx);
11446 if buffer.is_singleton() {
11447 cx.propagate();
11448 return;
11449 }
11450
11451 let Some(workspace) = self.workspace() else {
11452 cx.propagate();
11453 return;
11454 };
11455
11456 let mut new_selections_by_buffer = HashMap::default();
11457 for selection in self.selections.all::<usize>(cx) {
11458 for (buffer, mut range, _) in
11459 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11460 {
11461 if selection.reversed {
11462 mem::swap(&mut range.start, &mut range.end);
11463 }
11464 new_selections_by_buffer
11465 .entry(buffer)
11466 .or_insert(Vec::new())
11467 .push(range)
11468 }
11469 }
11470
11471 // We defer the pane interaction because we ourselves are a workspace item
11472 // and activating a new item causes the pane to call a method on us reentrantly,
11473 // which panics if we're on the stack.
11474 cx.window_context().defer(move |cx| {
11475 workspace.update(cx, |workspace, cx| {
11476 let pane = if split {
11477 workspace.adjacent_pane(cx)
11478 } else {
11479 workspace.active_pane().clone()
11480 };
11481
11482 for (buffer, ranges) in new_selections_by_buffer {
11483 let editor =
11484 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11485 editor.update(cx, |editor, cx| {
11486 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11487 s.select_ranges(ranges);
11488 });
11489 });
11490 }
11491 })
11492 });
11493 }
11494
11495 fn jump(
11496 &mut self,
11497 path: ProjectPath,
11498 position: Point,
11499 anchor: language::Anchor,
11500 offset_from_top: u32,
11501 cx: &mut ViewContext<Self>,
11502 ) {
11503 let workspace = self.workspace();
11504 cx.spawn(|_, mut cx| async move {
11505 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11506 let editor = workspace.update(&mut cx, |workspace, cx| {
11507 // Reset the preview item id before opening the new item
11508 workspace.active_pane().update(cx, |pane, cx| {
11509 pane.set_preview_item_id(None, cx);
11510 });
11511 workspace.open_path_preview(path, None, true, true, cx)
11512 })?;
11513 let editor = editor
11514 .await?
11515 .downcast::<Editor>()
11516 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11517 .downgrade();
11518 editor.update(&mut cx, |editor, cx| {
11519 let buffer = editor
11520 .buffer()
11521 .read(cx)
11522 .as_singleton()
11523 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11524 let buffer = buffer.read(cx);
11525 let cursor = if buffer.can_resolve(&anchor) {
11526 language::ToPoint::to_point(&anchor, buffer)
11527 } else {
11528 buffer.clip_point(position, Bias::Left)
11529 };
11530
11531 let nav_history = editor.nav_history.take();
11532 editor.change_selections(
11533 Some(Autoscroll::top_relative(offset_from_top as usize)),
11534 cx,
11535 |s| {
11536 s.select_ranges([cursor..cursor]);
11537 },
11538 );
11539 editor.nav_history = nav_history;
11540
11541 anyhow::Ok(())
11542 })??;
11543
11544 anyhow::Ok(())
11545 })
11546 .detach_and_log_err(cx);
11547 }
11548
11549 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11550 let snapshot = self.buffer.read(cx).read(cx);
11551 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11552 Some(
11553 ranges
11554 .iter()
11555 .map(move |range| {
11556 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11557 })
11558 .collect(),
11559 )
11560 }
11561
11562 fn selection_replacement_ranges(
11563 &self,
11564 range: Range<OffsetUtf16>,
11565 cx: &AppContext,
11566 ) -> Vec<Range<OffsetUtf16>> {
11567 let selections = self.selections.all::<OffsetUtf16>(cx);
11568 let newest_selection = selections
11569 .iter()
11570 .max_by_key(|selection| selection.id)
11571 .unwrap();
11572 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11573 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11574 let snapshot = self.buffer.read(cx).read(cx);
11575 selections
11576 .into_iter()
11577 .map(|mut selection| {
11578 selection.start.0 =
11579 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11580 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11581 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11582 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11583 })
11584 .collect()
11585 }
11586
11587 fn report_editor_event(
11588 &self,
11589 operation: &'static str,
11590 file_extension: Option<String>,
11591 cx: &AppContext,
11592 ) {
11593 if cfg!(any(test, feature = "test-support")) {
11594 return;
11595 }
11596
11597 let Some(project) = &self.project else { return };
11598
11599 // If None, we are in a file without an extension
11600 let file = self
11601 .buffer
11602 .read(cx)
11603 .as_singleton()
11604 .and_then(|b| b.read(cx).file());
11605 let file_extension = file_extension.or(file
11606 .as_ref()
11607 .and_then(|file| Path::new(file.file_name(cx)).extension())
11608 .and_then(|e| e.to_str())
11609 .map(|a| a.to_string()));
11610
11611 let vim_mode = cx
11612 .global::<SettingsStore>()
11613 .raw_user_settings()
11614 .get("vim_mode")
11615 == Some(&serde_json::Value::Bool(true));
11616
11617 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11618 == language::language_settings::InlineCompletionProvider::Copilot;
11619 let copilot_enabled_for_language = self
11620 .buffer
11621 .read(cx)
11622 .settings_at(0, cx)
11623 .show_inline_completions;
11624
11625 let telemetry = project.read(cx).client().telemetry().clone();
11626 telemetry.report_editor_event(
11627 file_extension,
11628 vim_mode,
11629 operation,
11630 copilot_enabled,
11631 copilot_enabled_for_language,
11632 )
11633 }
11634
11635 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11636 /// with each line being an array of {text, highlight} objects.
11637 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11638 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11639 return;
11640 };
11641
11642 #[derive(Serialize)]
11643 struct Chunk<'a> {
11644 text: String,
11645 highlight: Option<&'a str>,
11646 }
11647
11648 let snapshot = buffer.read(cx).snapshot();
11649 let range = self
11650 .selected_text_range(cx)
11651 .and_then(|selected_range| {
11652 if selected_range.is_empty() {
11653 None
11654 } else {
11655 Some(selected_range)
11656 }
11657 })
11658 .unwrap_or_else(|| 0..snapshot.len());
11659
11660 let chunks = snapshot.chunks(range, true);
11661 let mut lines = Vec::new();
11662 let mut line: VecDeque<Chunk> = VecDeque::new();
11663
11664 let Some(style) = self.style.as_ref() else {
11665 return;
11666 };
11667
11668 for chunk in chunks {
11669 let highlight = chunk
11670 .syntax_highlight_id
11671 .and_then(|id| id.name(&style.syntax));
11672 let mut chunk_lines = chunk.text.split('\n').peekable();
11673 while let Some(text) = chunk_lines.next() {
11674 let mut merged_with_last_token = false;
11675 if let Some(last_token) = line.back_mut() {
11676 if last_token.highlight == highlight {
11677 last_token.text.push_str(text);
11678 merged_with_last_token = true;
11679 }
11680 }
11681
11682 if !merged_with_last_token {
11683 line.push_back(Chunk {
11684 text: text.into(),
11685 highlight,
11686 });
11687 }
11688
11689 if chunk_lines.peek().is_some() {
11690 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11691 line.pop_front();
11692 }
11693 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11694 line.pop_back();
11695 }
11696
11697 lines.push(mem::take(&mut line));
11698 }
11699 }
11700 }
11701
11702 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11703 return;
11704 };
11705 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11706 }
11707
11708 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11709 &self.inlay_hint_cache
11710 }
11711
11712 pub fn replay_insert_event(
11713 &mut self,
11714 text: &str,
11715 relative_utf16_range: Option<Range<isize>>,
11716 cx: &mut ViewContext<Self>,
11717 ) {
11718 if !self.input_enabled {
11719 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11720 return;
11721 }
11722 if let Some(relative_utf16_range) = relative_utf16_range {
11723 let selections = self.selections.all::<OffsetUtf16>(cx);
11724 self.change_selections(None, cx, |s| {
11725 let new_ranges = selections.into_iter().map(|range| {
11726 let start = OffsetUtf16(
11727 range
11728 .head()
11729 .0
11730 .saturating_add_signed(relative_utf16_range.start),
11731 );
11732 let end = OffsetUtf16(
11733 range
11734 .head()
11735 .0
11736 .saturating_add_signed(relative_utf16_range.end),
11737 );
11738 start..end
11739 });
11740 s.select_ranges(new_ranges);
11741 });
11742 }
11743
11744 self.handle_input(text, cx);
11745 }
11746
11747 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11748 let Some(project) = self.project.as_ref() else {
11749 return false;
11750 };
11751 let project = project.read(cx);
11752
11753 let mut supports = false;
11754 self.buffer().read(cx).for_each_buffer(|buffer| {
11755 if !supports {
11756 supports = project
11757 .language_servers_for_buffer(buffer.read(cx), cx)
11758 .any(
11759 |(_, server)| match server.capabilities().inlay_hint_provider {
11760 Some(lsp::OneOf::Left(enabled)) => enabled,
11761 Some(lsp::OneOf::Right(_)) => true,
11762 None => false,
11763 },
11764 )
11765 }
11766 });
11767 supports
11768 }
11769
11770 pub fn focus(&self, cx: &mut WindowContext) {
11771 cx.focus(&self.focus_handle)
11772 }
11773
11774 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11775 self.focus_handle.is_focused(cx)
11776 }
11777
11778 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11779 cx.emit(EditorEvent::Focused);
11780
11781 if let Some(descendant) = self
11782 .last_focused_descendant
11783 .take()
11784 .and_then(|descendant| descendant.upgrade())
11785 {
11786 cx.focus(&descendant);
11787 } else {
11788 if let Some(blame) = self.blame.as_ref() {
11789 blame.update(cx, GitBlame::focus)
11790 }
11791
11792 self.blink_manager.update(cx, BlinkManager::enable);
11793 self.show_cursor_names(cx);
11794 self.buffer.update(cx, |buffer, cx| {
11795 buffer.finalize_last_transaction(cx);
11796 if self.leader_peer_id.is_none() {
11797 buffer.set_active_selections(
11798 &self.selections.disjoint_anchors(),
11799 self.selections.line_mode,
11800 self.cursor_shape,
11801 cx,
11802 );
11803 }
11804 });
11805 }
11806 }
11807
11808 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11809 cx.emit(EditorEvent::FocusedIn)
11810 }
11811
11812 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11813 if event.blurred != self.focus_handle {
11814 self.last_focused_descendant = Some(event.blurred);
11815 }
11816 }
11817
11818 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11819 self.blink_manager.update(cx, BlinkManager::disable);
11820 self.buffer
11821 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11822
11823 if let Some(blame) = self.blame.as_ref() {
11824 blame.update(cx, GitBlame::blur)
11825 }
11826 if !self.hover_state.focused(cx) {
11827 hide_hover(self, cx);
11828 }
11829
11830 self.hide_context_menu(cx);
11831 cx.emit(EditorEvent::Blurred);
11832 cx.notify();
11833 }
11834
11835 pub fn register_action<A: Action>(
11836 &mut self,
11837 listener: impl Fn(&A, &mut WindowContext) + 'static,
11838 ) -> Subscription {
11839 let id = self.next_editor_action_id.post_inc();
11840 let listener = Arc::new(listener);
11841 self.editor_actions.borrow_mut().insert(
11842 id,
11843 Box::new(move |cx| {
11844 let _view = cx.view().clone();
11845 let cx = cx.window_context();
11846 let listener = listener.clone();
11847 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11848 let action = action.downcast_ref().unwrap();
11849 if phase == DispatchPhase::Bubble {
11850 listener(action, cx)
11851 }
11852 })
11853 }),
11854 );
11855
11856 let editor_actions = self.editor_actions.clone();
11857 Subscription::new(move || {
11858 editor_actions.borrow_mut().remove(&id);
11859 })
11860 }
11861
11862 pub fn file_header_size(&self) -> u32 {
11863 self.file_header_size
11864 }
11865
11866 pub fn revert(
11867 &mut self,
11868 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11869 cx: &mut ViewContext<Self>,
11870 ) {
11871 self.buffer().update(cx, |multi_buffer, cx| {
11872 for (buffer_id, changes) in revert_changes {
11873 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11874 buffer.update(cx, |buffer, cx| {
11875 buffer.edit(
11876 changes.into_iter().map(|(range, text)| {
11877 (range, text.to_string().map(Arc::<str>::from))
11878 }),
11879 None,
11880 cx,
11881 );
11882 });
11883 }
11884 }
11885 });
11886 self.change_selections(None, cx, |selections| selections.refresh());
11887 }
11888
11889 pub fn to_pixel_point(
11890 &mut self,
11891 source: multi_buffer::Anchor,
11892 editor_snapshot: &EditorSnapshot,
11893 cx: &mut ViewContext<Self>,
11894 ) -> Option<gpui::Point<Pixels>> {
11895 let source_point = source.to_display_point(editor_snapshot);
11896 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11897 }
11898
11899 pub fn display_to_pixel_point(
11900 &mut self,
11901 source: DisplayPoint,
11902 editor_snapshot: &EditorSnapshot,
11903 cx: &mut ViewContext<Self>,
11904 ) -> Option<gpui::Point<Pixels>> {
11905 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11906 let text_layout_details = self.text_layout_details(cx);
11907 let scroll_top = text_layout_details
11908 .scroll_anchor
11909 .scroll_position(editor_snapshot)
11910 .y;
11911
11912 if source.row().as_f32() < scroll_top.floor() {
11913 return None;
11914 }
11915 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11916 let source_y = line_height * (source.row().as_f32() - scroll_top);
11917 Some(gpui::Point::new(source_x, source_y))
11918 }
11919
11920 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11921 let bounds = self.last_bounds?;
11922 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11923 }
11924}
11925
11926fn hunks_for_selections(
11927 multi_buffer_snapshot: &MultiBufferSnapshot,
11928 selections: &[Selection<Anchor>],
11929) -> Vec<DiffHunk<MultiBufferRow>> {
11930 let buffer_rows_for_selections = selections.iter().map(|selection| {
11931 let head = selection.head();
11932 let tail = selection.tail();
11933 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11934 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11935 if start > end {
11936 end..start
11937 } else {
11938 start..end
11939 }
11940 });
11941
11942 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11943}
11944
11945pub fn hunks_for_rows(
11946 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11947 multi_buffer_snapshot: &MultiBufferSnapshot,
11948) -> Vec<DiffHunk<MultiBufferRow>> {
11949 let mut hunks = Vec::new();
11950 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11951 HashMap::default();
11952 for selected_multi_buffer_rows in rows {
11953 let query_rows =
11954 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11955 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11956 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11957 // when the caret is just above or just below the deleted hunk.
11958 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11959 let related_to_selection = if allow_adjacent {
11960 hunk.associated_range.overlaps(&query_rows)
11961 || hunk.associated_range.start == query_rows.end
11962 || hunk.associated_range.end == query_rows.start
11963 } else {
11964 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11965 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11966 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11967 || selected_multi_buffer_rows.end == hunk.associated_range.start
11968 };
11969 if related_to_selection {
11970 if !processed_buffer_rows
11971 .entry(hunk.buffer_id)
11972 .or_default()
11973 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11974 {
11975 continue;
11976 }
11977 hunks.push(hunk);
11978 }
11979 }
11980 }
11981
11982 hunks
11983}
11984
11985pub trait CollaborationHub {
11986 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11987 fn user_participant_indices<'a>(
11988 &self,
11989 cx: &'a AppContext,
11990 ) -> &'a HashMap<u64, ParticipantIndex>;
11991 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11992}
11993
11994impl CollaborationHub for Model<Project> {
11995 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11996 self.read(cx).collaborators()
11997 }
11998
11999 fn user_participant_indices<'a>(
12000 &self,
12001 cx: &'a AppContext,
12002 ) -> &'a HashMap<u64, ParticipantIndex> {
12003 self.read(cx).user_store().read(cx).participant_indices()
12004 }
12005
12006 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12007 let this = self.read(cx);
12008 let user_ids = this.collaborators().values().map(|c| c.user_id);
12009 this.user_store().read_with(cx, |user_store, cx| {
12010 user_store.participant_names(user_ids, cx)
12011 })
12012 }
12013}
12014
12015pub trait CompletionProvider {
12016 fn completions(
12017 &self,
12018 buffer: &Model<Buffer>,
12019 buffer_position: text::Anchor,
12020 trigger: CompletionContext,
12021 cx: &mut ViewContext<Editor>,
12022 ) -> Task<Result<Vec<Completion>>>;
12023
12024 fn resolve_completions(
12025 &self,
12026 buffer: Model<Buffer>,
12027 completion_indices: Vec<usize>,
12028 completions: Arc<RwLock<Box<[Completion]>>>,
12029 cx: &mut ViewContext<Editor>,
12030 ) -> Task<Result<bool>>;
12031
12032 fn apply_additional_edits_for_completion(
12033 &self,
12034 buffer: Model<Buffer>,
12035 completion: Completion,
12036 push_to_history: bool,
12037 cx: &mut ViewContext<Editor>,
12038 ) -> Task<Result<Option<language::Transaction>>>;
12039
12040 fn is_completion_trigger(
12041 &self,
12042 buffer: &Model<Buffer>,
12043 position: language::Anchor,
12044 text: &str,
12045 trigger_in_words: bool,
12046 cx: &mut ViewContext<Editor>,
12047 ) -> bool;
12048}
12049
12050fn snippet_completions(
12051 project: &Project,
12052 buffer: &Model<Buffer>,
12053 buffer_position: text::Anchor,
12054 cx: &mut AppContext,
12055) -> Vec<Completion> {
12056 let language = buffer.read(cx).language_at(buffer_position);
12057 let language_name = language.as_ref().map(|language| language.lsp_id());
12058 let snippet_store = project.snippets().read(cx);
12059 let snippets = snippet_store.snippets_for(language_name, cx);
12060
12061 if snippets.is_empty() {
12062 return vec![];
12063 }
12064 let snapshot = buffer.read(cx).text_snapshot();
12065 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12066
12067 let mut lines = chunks.lines();
12068 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12069 return vec![];
12070 };
12071
12072 let scope = language.map(|language| language.default_scope());
12073 let mut last_word = line_at
12074 .chars()
12075 .rev()
12076 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12077 .collect::<String>();
12078 last_word = last_word.chars().rev().collect();
12079 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12080 let to_lsp = |point: &text::Anchor| {
12081 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12082 point_to_lsp(end)
12083 };
12084 let lsp_end = to_lsp(&buffer_position);
12085 snippets
12086 .into_iter()
12087 .filter_map(|snippet| {
12088 let matching_prefix = snippet
12089 .prefix
12090 .iter()
12091 .find(|prefix| prefix.starts_with(&last_word))?;
12092 let start = as_offset - last_word.len();
12093 let start = snapshot.anchor_before(start);
12094 let range = start..buffer_position;
12095 let lsp_start = to_lsp(&start);
12096 let lsp_range = lsp::Range {
12097 start: lsp_start,
12098 end: lsp_end,
12099 };
12100 Some(Completion {
12101 old_range: range,
12102 new_text: snippet.body.clone(),
12103 label: CodeLabel {
12104 text: matching_prefix.clone(),
12105 runs: vec![],
12106 filter_range: 0..matching_prefix.len(),
12107 },
12108 server_id: LanguageServerId(usize::MAX),
12109 documentation: snippet
12110 .description
12111 .clone()
12112 .map(|description| Documentation::SingleLine(description)),
12113 lsp_completion: lsp::CompletionItem {
12114 label: snippet.prefix.first().unwrap().clone(),
12115 kind: Some(CompletionItemKind::SNIPPET),
12116 label_details: snippet.description.as_ref().map(|description| {
12117 lsp::CompletionItemLabelDetails {
12118 detail: Some(description.clone()),
12119 description: None,
12120 }
12121 }),
12122 insert_text_format: Some(InsertTextFormat::SNIPPET),
12123 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12124 lsp::InsertReplaceEdit {
12125 new_text: snippet.body.clone(),
12126 insert: lsp_range,
12127 replace: lsp_range,
12128 },
12129 )),
12130 filter_text: Some(snippet.body.clone()),
12131 sort_text: Some(char::MAX.to_string()),
12132 ..Default::default()
12133 },
12134 confirm: None,
12135 show_new_completions_on_confirm: false,
12136 })
12137 })
12138 .collect()
12139}
12140
12141impl CompletionProvider for Model<Project> {
12142 fn completions(
12143 &self,
12144 buffer: &Model<Buffer>,
12145 buffer_position: text::Anchor,
12146 options: CompletionContext,
12147 cx: &mut ViewContext<Editor>,
12148 ) -> Task<Result<Vec<Completion>>> {
12149 self.update(cx, |project, cx| {
12150 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12151 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12152 cx.background_executor().spawn(async move {
12153 let mut completions = project_completions.await?;
12154 //let snippets = snippets.into_iter().;
12155 completions.extend(snippets);
12156 Ok(completions)
12157 })
12158 })
12159 }
12160
12161 fn resolve_completions(
12162 &self,
12163 buffer: Model<Buffer>,
12164 completion_indices: Vec<usize>,
12165 completions: Arc<RwLock<Box<[Completion]>>>,
12166 cx: &mut ViewContext<Editor>,
12167 ) -> Task<Result<bool>> {
12168 self.update(cx, |project, cx| {
12169 project.resolve_completions(buffer, completion_indices, completions, cx)
12170 })
12171 }
12172
12173 fn apply_additional_edits_for_completion(
12174 &self,
12175 buffer: Model<Buffer>,
12176 completion: Completion,
12177 push_to_history: bool,
12178 cx: &mut ViewContext<Editor>,
12179 ) -> Task<Result<Option<language::Transaction>>> {
12180 self.update(cx, |project, cx| {
12181 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12182 })
12183 }
12184
12185 fn is_completion_trigger(
12186 &self,
12187 buffer: &Model<Buffer>,
12188 position: language::Anchor,
12189 text: &str,
12190 trigger_in_words: bool,
12191 cx: &mut ViewContext<Editor>,
12192 ) -> bool {
12193 if !EditorSettings::get_global(cx).show_completions_on_input {
12194 return false;
12195 }
12196
12197 let mut chars = text.chars();
12198 let char = if let Some(char) = chars.next() {
12199 char
12200 } else {
12201 return false;
12202 };
12203 if chars.next().is_some() {
12204 return false;
12205 }
12206
12207 let buffer = buffer.read(cx);
12208 let scope = buffer.snapshot().language_scope_at(position);
12209 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12210 return true;
12211 }
12212
12213 buffer
12214 .completion_triggers()
12215 .iter()
12216 .any(|string| string == text)
12217 }
12218}
12219
12220fn inlay_hint_settings(
12221 location: Anchor,
12222 snapshot: &MultiBufferSnapshot,
12223 cx: &mut ViewContext<'_, Editor>,
12224) -> InlayHintSettings {
12225 let file = snapshot.file_at(location);
12226 let language = snapshot.language_at(location);
12227 let settings = all_language_settings(file, cx);
12228 settings
12229 .language(language.map(|l| l.name()).as_deref())
12230 .inlay_hints
12231}
12232
12233fn consume_contiguous_rows(
12234 contiguous_row_selections: &mut Vec<Selection<Point>>,
12235 selection: &Selection<Point>,
12236 display_map: &DisplaySnapshot,
12237 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12238) -> (MultiBufferRow, MultiBufferRow) {
12239 contiguous_row_selections.push(selection.clone());
12240 let start_row = MultiBufferRow(selection.start.row);
12241 let mut end_row = ending_row(selection, display_map);
12242
12243 while let Some(next_selection) = selections.peek() {
12244 if next_selection.start.row <= end_row.0 {
12245 end_row = ending_row(next_selection, display_map);
12246 contiguous_row_selections.push(selections.next().unwrap().clone());
12247 } else {
12248 break;
12249 }
12250 }
12251 (start_row, end_row)
12252}
12253
12254fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12255 if next_selection.end.column > 0 || next_selection.is_empty() {
12256 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12257 } else {
12258 MultiBufferRow(next_selection.end.row)
12259 }
12260}
12261
12262impl EditorSnapshot {
12263 pub fn remote_selections_in_range<'a>(
12264 &'a self,
12265 range: &'a Range<Anchor>,
12266 collaboration_hub: &dyn CollaborationHub,
12267 cx: &'a AppContext,
12268 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12269 let participant_names = collaboration_hub.user_names(cx);
12270 let participant_indices = collaboration_hub.user_participant_indices(cx);
12271 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12272 let collaborators_by_replica_id = collaborators_by_peer_id
12273 .iter()
12274 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12275 .collect::<HashMap<_, _>>();
12276 self.buffer_snapshot
12277 .selections_in_range(range, false)
12278 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12279 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12280 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12281 let user_name = participant_names.get(&collaborator.user_id).cloned();
12282 Some(RemoteSelection {
12283 replica_id,
12284 selection,
12285 cursor_shape,
12286 line_mode,
12287 participant_index,
12288 peer_id: collaborator.peer_id,
12289 user_name,
12290 })
12291 })
12292 }
12293
12294 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12295 self.display_snapshot.buffer_snapshot.language_at(position)
12296 }
12297
12298 pub fn is_focused(&self) -> bool {
12299 self.is_focused
12300 }
12301
12302 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12303 self.placeholder_text.as_ref()
12304 }
12305
12306 pub fn scroll_position(&self) -> gpui::Point<f32> {
12307 self.scroll_anchor.scroll_position(&self.display_snapshot)
12308 }
12309
12310 fn gutter_dimensions(
12311 &self,
12312 font_id: FontId,
12313 font_size: Pixels,
12314 em_width: Pixels,
12315 max_line_number_width: Pixels,
12316 cx: &AppContext,
12317 ) -> GutterDimensions {
12318 if !self.show_gutter {
12319 return GutterDimensions::default();
12320 }
12321 let descent = cx.text_system().descent(font_id, font_size);
12322
12323 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12324 matches!(
12325 ProjectSettings::get_global(cx).git.git_gutter,
12326 Some(GitGutterSetting::TrackedFiles)
12327 )
12328 });
12329 let gutter_settings = EditorSettings::get_global(cx).gutter;
12330 let show_line_numbers = self
12331 .show_line_numbers
12332 .unwrap_or(gutter_settings.line_numbers);
12333 let line_gutter_width = if show_line_numbers {
12334 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12335 let min_width_for_number_on_gutter = em_width * 4.0;
12336 max_line_number_width.max(min_width_for_number_on_gutter)
12337 } else {
12338 0.0.into()
12339 };
12340
12341 let show_code_actions = self
12342 .show_code_actions
12343 .unwrap_or(gutter_settings.code_actions);
12344
12345 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12346
12347 let git_blame_entries_width = self
12348 .render_git_blame_gutter
12349 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12350
12351 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12352 left_padding += if show_code_actions || show_runnables {
12353 em_width * 3.0
12354 } else if show_git_gutter && show_line_numbers {
12355 em_width * 2.0
12356 } else if show_git_gutter || show_line_numbers {
12357 em_width
12358 } else {
12359 px(0.)
12360 };
12361
12362 let right_padding = if gutter_settings.folds && show_line_numbers {
12363 em_width * 4.0
12364 } else if gutter_settings.folds {
12365 em_width * 3.0
12366 } else if show_line_numbers {
12367 em_width
12368 } else {
12369 px(0.)
12370 };
12371
12372 GutterDimensions {
12373 left_padding,
12374 right_padding,
12375 width: line_gutter_width + left_padding + right_padding,
12376 margin: -descent,
12377 git_blame_entries_width,
12378 }
12379 }
12380
12381 pub fn render_fold_toggle(
12382 &self,
12383 buffer_row: MultiBufferRow,
12384 row_contains_cursor: bool,
12385 editor: View<Editor>,
12386 cx: &mut WindowContext,
12387 ) -> Option<AnyElement> {
12388 let folded = self.is_line_folded(buffer_row);
12389
12390 if let Some(crease) = self
12391 .crease_snapshot
12392 .query_row(buffer_row, &self.buffer_snapshot)
12393 {
12394 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12395 if folded {
12396 editor.update(cx, |editor, cx| {
12397 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12398 });
12399 } else {
12400 editor.update(cx, |editor, cx| {
12401 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12402 });
12403 }
12404 });
12405
12406 Some((crease.render_toggle)(
12407 buffer_row,
12408 folded,
12409 toggle_callback,
12410 cx,
12411 ))
12412 } else if folded
12413 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12414 {
12415 Some(
12416 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12417 .selected(folded)
12418 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12419 if folded {
12420 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12421 } else {
12422 this.fold_at(&FoldAt { buffer_row }, cx);
12423 }
12424 }))
12425 .into_any_element(),
12426 )
12427 } else {
12428 None
12429 }
12430 }
12431
12432 pub fn render_crease_trailer(
12433 &self,
12434 buffer_row: MultiBufferRow,
12435 cx: &mut WindowContext,
12436 ) -> Option<AnyElement> {
12437 let folded = self.is_line_folded(buffer_row);
12438 let crease = self
12439 .crease_snapshot
12440 .query_row(buffer_row, &self.buffer_snapshot)?;
12441 Some((crease.render_trailer)(buffer_row, folded, cx))
12442 }
12443}
12444
12445impl Deref for EditorSnapshot {
12446 type Target = DisplaySnapshot;
12447
12448 fn deref(&self) -> &Self::Target {
12449 &self.display_snapshot
12450 }
12451}
12452
12453#[derive(Clone, Debug, PartialEq, Eq)]
12454pub enum EditorEvent {
12455 InputIgnored {
12456 text: Arc<str>,
12457 },
12458 InputHandled {
12459 utf16_range_to_replace: Option<Range<isize>>,
12460 text: Arc<str>,
12461 },
12462 ExcerptsAdded {
12463 buffer: Model<Buffer>,
12464 predecessor: ExcerptId,
12465 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12466 },
12467 ExcerptsRemoved {
12468 ids: Vec<ExcerptId>,
12469 },
12470 ExcerptsEdited {
12471 ids: Vec<ExcerptId>,
12472 },
12473 ExcerptsExpanded {
12474 ids: Vec<ExcerptId>,
12475 },
12476 BufferEdited,
12477 Edited {
12478 transaction_id: clock::Lamport,
12479 },
12480 Reparsed(BufferId),
12481 Focused,
12482 FocusedIn,
12483 Blurred,
12484 DirtyChanged,
12485 Saved,
12486 TitleChanged,
12487 DiffBaseChanged,
12488 SelectionsChanged {
12489 local: bool,
12490 },
12491 ScrollPositionChanged {
12492 local: bool,
12493 autoscroll: bool,
12494 },
12495 Closed,
12496 TransactionUndone {
12497 transaction_id: clock::Lamport,
12498 },
12499 TransactionBegun {
12500 transaction_id: clock::Lamport,
12501 },
12502}
12503
12504impl EventEmitter<EditorEvent> for Editor {}
12505
12506impl FocusableView for Editor {
12507 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12508 self.focus_handle.clone()
12509 }
12510}
12511
12512impl Render for Editor {
12513 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12514 let settings = ThemeSettings::get_global(cx);
12515
12516 let text_style = match self.mode {
12517 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12518 color: cx.theme().colors().editor_foreground,
12519 font_family: settings.ui_font.family.clone(),
12520 font_features: settings.ui_font.features.clone(),
12521 font_fallbacks: settings.ui_font.fallbacks.clone(),
12522 font_size: rems(0.875).into(),
12523 font_weight: settings.ui_font.weight,
12524 line_height: relative(settings.buffer_line_height.value()),
12525 ..Default::default()
12526 },
12527 EditorMode::Full => TextStyle {
12528 color: cx.theme().colors().editor_foreground,
12529 font_family: settings.buffer_font.family.clone(),
12530 font_features: settings.buffer_font.features.clone(),
12531 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12532 font_size: settings.buffer_font_size(cx).into(),
12533 font_weight: settings.buffer_font.weight,
12534 line_height: relative(settings.buffer_line_height.value()),
12535 ..Default::default()
12536 },
12537 };
12538
12539 let background = match self.mode {
12540 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12541 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12542 EditorMode::Full => cx.theme().colors().editor_background,
12543 };
12544
12545 EditorElement::new(
12546 cx.view(),
12547 EditorStyle {
12548 background,
12549 local_player: cx.theme().players().local(),
12550 text: text_style,
12551 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12552 syntax: cx.theme().syntax().clone(),
12553 status: cx.theme().status().clone(),
12554 inlay_hints_style: HighlightStyle {
12555 color: Some(cx.theme().status().hint),
12556 ..HighlightStyle::default()
12557 },
12558 suggestions_style: HighlightStyle {
12559 color: Some(cx.theme().status().predictive),
12560 ..HighlightStyle::default()
12561 },
12562 },
12563 )
12564 }
12565}
12566
12567impl ViewInputHandler for Editor {
12568 fn text_for_range(
12569 &mut self,
12570 range_utf16: Range<usize>,
12571 cx: &mut ViewContext<Self>,
12572 ) -> Option<String> {
12573 Some(
12574 self.buffer
12575 .read(cx)
12576 .read(cx)
12577 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12578 .collect(),
12579 )
12580 }
12581
12582 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12583 // Prevent the IME menu from appearing when holding down an alphabetic key
12584 // while input is disabled.
12585 if !self.input_enabled {
12586 return None;
12587 }
12588
12589 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12590 Some(range.start.0..range.end.0)
12591 }
12592
12593 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12594 let snapshot = self.buffer.read(cx).read(cx);
12595 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12596 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12597 }
12598
12599 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12600 self.clear_highlights::<InputComposition>(cx);
12601 self.ime_transaction.take();
12602 }
12603
12604 fn replace_text_in_range(
12605 &mut self,
12606 range_utf16: Option<Range<usize>>,
12607 text: &str,
12608 cx: &mut ViewContext<Self>,
12609 ) {
12610 if !self.input_enabled {
12611 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12612 return;
12613 }
12614
12615 self.transact(cx, |this, cx| {
12616 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12617 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12618 Some(this.selection_replacement_ranges(range_utf16, cx))
12619 } else {
12620 this.marked_text_ranges(cx)
12621 };
12622
12623 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12624 let newest_selection_id = this.selections.newest_anchor().id;
12625 this.selections
12626 .all::<OffsetUtf16>(cx)
12627 .iter()
12628 .zip(ranges_to_replace.iter())
12629 .find_map(|(selection, range)| {
12630 if selection.id == newest_selection_id {
12631 Some(
12632 (range.start.0 as isize - selection.head().0 as isize)
12633 ..(range.end.0 as isize - selection.head().0 as isize),
12634 )
12635 } else {
12636 None
12637 }
12638 })
12639 });
12640
12641 cx.emit(EditorEvent::InputHandled {
12642 utf16_range_to_replace: range_to_replace,
12643 text: text.into(),
12644 });
12645
12646 if let Some(new_selected_ranges) = new_selected_ranges {
12647 this.change_selections(None, cx, |selections| {
12648 selections.select_ranges(new_selected_ranges)
12649 });
12650 this.backspace(&Default::default(), cx);
12651 }
12652
12653 this.handle_input(text, cx);
12654 });
12655
12656 if let Some(transaction) = self.ime_transaction {
12657 self.buffer.update(cx, |buffer, cx| {
12658 buffer.group_until_transaction(transaction, cx);
12659 });
12660 }
12661
12662 self.unmark_text(cx);
12663 }
12664
12665 fn replace_and_mark_text_in_range(
12666 &mut self,
12667 range_utf16: Option<Range<usize>>,
12668 text: &str,
12669 new_selected_range_utf16: Option<Range<usize>>,
12670 cx: &mut ViewContext<Self>,
12671 ) {
12672 if !self.input_enabled {
12673 return;
12674 }
12675
12676 let transaction = self.transact(cx, |this, cx| {
12677 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12678 let snapshot = this.buffer.read(cx).read(cx);
12679 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12680 for marked_range in &mut marked_ranges {
12681 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12682 marked_range.start.0 += relative_range_utf16.start;
12683 marked_range.start =
12684 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12685 marked_range.end =
12686 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12687 }
12688 }
12689 Some(marked_ranges)
12690 } else if let Some(range_utf16) = range_utf16 {
12691 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12692 Some(this.selection_replacement_ranges(range_utf16, cx))
12693 } else {
12694 None
12695 };
12696
12697 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12698 let newest_selection_id = this.selections.newest_anchor().id;
12699 this.selections
12700 .all::<OffsetUtf16>(cx)
12701 .iter()
12702 .zip(ranges_to_replace.iter())
12703 .find_map(|(selection, range)| {
12704 if selection.id == newest_selection_id {
12705 Some(
12706 (range.start.0 as isize - selection.head().0 as isize)
12707 ..(range.end.0 as isize - selection.head().0 as isize),
12708 )
12709 } else {
12710 None
12711 }
12712 })
12713 });
12714
12715 cx.emit(EditorEvent::InputHandled {
12716 utf16_range_to_replace: range_to_replace,
12717 text: text.into(),
12718 });
12719
12720 if let Some(ranges) = ranges_to_replace {
12721 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12722 }
12723
12724 let marked_ranges = {
12725 let snapshot = this.buffer.read(cx).read(cx);
12726 this.selections
12727 .disjoint_anchors()
12728 .iter()
12729 .map(|selection| {
12730 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12731 })
12732 .collect::<Vec<_>>()
12733 };
12734
12735 if text.is_empty() {
12736 this.unmark_text(cx);
12737 } else {
12738 this.highlight_text::<InputComposition>(
12739 marked_ranges.clone(),
12740 HighlightStyle {
12741 underline: Some(UnderlineStyle {
12742 thickness: px(1.),
12743 color: None,
12744 wavy: false,
12745 }),
12746 ..Default::default()
12747 },
12748 cx,
12749 );
12750 }
12751
12752 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12753 let use_autoclose = this.use_autoclose;
12754 let use_auto_surround = this.use_auto_surround;
12755 this.set_use_autoclose(false);
12756 this.set_use_auto_surround(false);
12757 this.handle_input(text, cx);
12758 this.set_use_autoclose(use_autoclose);
12759 this.set_use_auto_surround(use_auto_surround);
12760
12761 if let Some(new_selected_range) = new_selected_range_utf16 {
12762 let snapshot = this.buffer.read(cx).read(cx);
12763 let new_selected_ranges = marked_ranges
12764 .into_iter()
12765 .map(|marked_range| {
12766 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12767 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12768 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12769 snapshot.clip_offset_utf16(new_start, Bias::Left)
12770 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12771 })
12772 .collect::<Vec<_>>();
12773
12774 drop(snapshot);
12775 this.change_selections(None, cx, |selections| {
12776 selections.select_ranges(new_selected_ranges)
12777 });
12778 }
12779 });
12780
12781 self.ime_transaction = self.ime_transaction.or(transaction);
12782 if let Some(transaction) = self.ime_transaction {
12783 self.buffer.update(cx, |buffer, cx| {
12784 buffer.group_until_transaction(transaction, cx);
12785 });
12786 }
12787
12788 if self.text_highlights::<InputComposition>(cx).is_none() {
12789 self.ime_transaction.take();
12790 }
12791 }
12792
12793 fn bounds_for_range(
12794 &mut self,
12795 range_utf16: Range<usize>,
12796 element_bounds: gpui::Bounds<Pixels>,
12797 cx: &mut ViewContext<Self>,
12798 ) -> Option<gpui::Bounds<Pixels>> {
12799 let text_layout_details = self.text_layout_details(cx);
12800 let style = &text_layout_details.editor_style;
12801 let font_id = cx.text_system().resolve_font(&style.text.font());
12802 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12803 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12804
12805 let em_width = cx
12806 .text_system()
12807 .typographic_bounds(font_id, font_size, 'm')
12808 .unwrap()
12809 .size
12810 .width;
12811
12812 let snapshot = self.snapshot(cx);
12813 let scroll_position = snapshot.scroll_position();
12814 let scroll_left = scroll_position.x * em_width;
12815
12816 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12817 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12818 + self.gutter_dimensions.width;
12819 let y = line_height * (start.row().as_f32() - scroll_position.y);
12820
12821 Some(Bounds {
12822 origin: element_bounds.origin + point(x, y),
12823 size: size(em_width, line_height),
12824 })
12825 }
12826}
12827
12828trait SelectionExt {
12829 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12830 fn spanned_rows(
12831 &self,
12832 include_end_if_at_line_start: bool,
12833 map: &DisplaySnapshot,
12834 ) -> Range<MultiBufferRow>;
12835}
12836
12837impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12838 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12839 let start = self
12840 .start
12841 .to_point(&map.buffer_snapshot)
12842 .to_display_point(map);
12843 let end = self
12844 .end
12845 .to_point(&map.buffer_snapshot)
12846 .to_display_point(map);
12847 if self.reversed {
12848 end..start
12849 } else {
12850 start..end
12851 }
12852 }
12853
12854 fn spanned_rows(
12855 &self,
12856 include_end_if_at_line_start: bool,
12857 map: &DisplaySnapshot,
12858 ) -> Range<MultiBufferRow> {
12859 let start = self.start.to_point(&map.buffer_snapshot);
12860 let mut end = self.end.to_point(&map.buffer_snapshot);
12861 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12862 end.row -= 1;
12863 }
12864
12865 let buffer_start = map.prev_line_boundary(start).0;
12866 let buffer_end = map.next_line_boundary(end).0;
12867 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12868 }
12869}
12870
12871impl<T: InvalidationRegion> InvalidationStack<T> {
12872 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12873 where
12874 S: Clone + ToOffset,
12875 {
12876 while let Some(region) = self.last() {
12877 let all_selections_inside_invalidation_ranges =
12878 if selections.len() == region.ranges().len() {
12879 selections
12880 .iter()
12881 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12882 .all(|(selection, invalidation_range)| {
12883 let head = selection.head().to_offset(buffer);
12884 invalidation_range.start <= head && invalidation_range.end >= head
12885 })
12886 } else {
12887 false
12888 };
12889
12890 if all_selections_inside_invalidation_ranges {
12891 break;
12892 } else {
12893 self.pop();
12894 }
12895 }
12896 }
12897}
12898
12899impl<T> Default for InvalidationStack<T> {
12900 fn default() -> Self {
12901 Self(Default::default())
12902 }
12903}
12904
12905impl<T> Deref for InvalidationStack<T> {
12906 type Target = Vec<T>;
12907
12908 fn deref(&self) -> &Self::Target {
12909 &self.0
12910 }
12911}
12912
12913impl<T> DerefMut for InvalidationStack<T> {
12914 fn deref_mut(&mut self) -> &mut Self::Target {
12915 &mut self.0
12916 }
12917}
12918
12919impl InvalidationRegion for SnippetState {
12920 fn ranges(&self) -> &[Range<Anchor>] {
12921 &self.ranges[self.active_index]
12922 }
12923}
12924
12925pub fn diagnostic_block_renderer(
12926 diagnostic: Diagnostic,
12927 max_message_rows: Option<u8>,
12928 allow_closing: bool,
12929 _is_valid: bool,
12930) -> RenderBlock {
12931 let (text_without_backticks, code_ranges) =
12932 highlight_diagnostic_message(&diagnostic, max_message_rows);
12933
12934 Box::new(move |cx: &mut BlockContext| {
12935 let group_id: SharedString = cx.block_id.to_string().into();
12936
12937 let mut text_style = cx.text_style().clone();
12938 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12939 let theme_settings = ThemeSettings::get_global(cx);
12940 text_style.font_family = theme_settings.buffer_font.family.clone();
12941 text_style.font_style = theme_settings.buffer_font.style;
12942 text_style.font_features = theme_settings.buffer_font.features.clone();
12943 text_style.font_weight = theme_settings.buffer_font.weight;
12944
12945 let multi_line_diagnostic = diagnostic.message.contains('\n');
12946
12947 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12948 if multi_line_diagnostic {
12949 v_flex()
12950 } else {
12951 h_flex()
12952 }
12953 .when(allow_closing, |div| {
12954 div.children(diagnostic.is_primary.then(|| {
12955 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12956 .icon_color(Color::Muted)
12957 .size(ButtonSize::Compact)
12958 .style(ButtonStyle::Transparent)
12959 .visible_on_hover(group_id.clone())
12960 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12961 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12962 }))
12963 })
12964 .child(
12965 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12966 .icon_color(Color::Muted)
12967 .size(ButtonSize::Compact)
12968 .style(ButtonStyle::Transparent)
12969 .visible_on_hover(group_id.clone())
12970 .on_click({
12971 let message = diagnostic.message.clone();
12972 move |_click, cx| {
12973 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
12974 }
12975 })
12976 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12977 )
12978 };
12979
12980 let icon_size = buttons(&diagnostic, cx.block_id)
12981 .into_any_element()
12982 .layout_as_root(AvailableSpace::min_size(), cx);
12983
12984 h_flex()
12985 .id(cx.block_id)
12986 .group(group_id.clone())
12987 .relative()
12988 .size_full()
12989 .pl(cx.gutter_dimensions.width)
12990 .w(cx.max_width + cx.gutter_dimensions.width)
12991 .child(
12992 div()
12993 .flex()
12994 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12995 .flex_shrink(),
12996 )
12997 .child(buttons(&diagnostic, cx.block_id))
12998 .child(div().flex().flex_shrink_0().child(
12999 StyledText::new(text_without_backticks.clone()).with_highlights(
13000 &text_style,
13001 code_ranges.iter().map(|range| {
13002 (
13003 range.clone(),
13004 HighlightStyle {
13005 font_weight: Some(FontWeight::BOLD),
13006 ..Default::default()
13007 },
13008 )
13009 }),
13010 ),
13011 ))
13012 .into_any_element()
13013 })
13014}
13015
13016pub fn highlight_diagnostic_message(
13017 diagnostic: &Diagnostic,
13018 mut max_message_rows: Option<u8>,
13019) -> (SharedString, Vec<Range<usize>>) {
13020 let mut text_without_backticks = String::new();
13021 let mut code_ranges = Vec::new();
13022
13023 if let Some(source) = &diagnostic.source {
13024 text_without_backticks.push_str(&source);
13025 code_ranges.push(0..source.len());
13026 text_without_backticks.push_str(": ");
13027 }
13028
13029 let mut prev_offset = 0;
13030 let mut in_code_block = false;
13031 let has_row_limit = max_message_rows.is_some();
13032 let mut newline_indices = diagnostic
13033 .message
13034 .match_indices('\n')
13035 .filter(|_| has_row_limit)
13036 .map(|(ix, _)| ix)
13037 .fuse()
13038 .peekable();
13039
13040 for (quote_ix, _) in diagnostic
13041 .message
13042 .match_indices('`')
13043 .chain([(diagnostic.message.len(), "")])
13044 {
13045 let mut first_newline_ix = None;
13046 let mut last_newline_ix = None;
13047 while let Some(newline_ix) = newline_indices.peek() {
13048 if *newline_ix < quote_ix {
13049 if first_newline_ix.is_none() {
13050 first_newline_ix = Some(*newline_ix);
13051 }
13052 last_newline_ix = Some(*newline_ix);
13053
13054 if let Some(rows_left) = &mut max_message_rows {
13055 if *rows_left == 0 {
13056 break;
13057 } else {
13058 *rows_left -= 1;
13059 }
13060 }
13061 let _ = newline_indices.next();
13062 } else {
13063 break;
13064 }
13065 }
13066 let prev_len = text_without_backticks.len();
13067 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13068 text_without_backticks.push_str(new_text);
13069 if in_code_block {
13070 code_ranges.push(prev_len..text_without_backticks.len());
13071 }
13072 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13073 in_code_block = !in_code_block;
13074 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13075 text_without_backticks.push_str("...");
13076 break;
13077 }
13078 }
13079
13080 (text_without_backticks.into(), code_ranges)
13081}
13082
13083fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13084 match severity {
13085 DiagnosticSeverity::ERROR => colors.error,
13086 DiagnosticSeverity::WARNING => colors.warning,
13087 DiagnosticSeverity::INFORMATION => colors.info,
13088 DiagnosticSeverity::HINT => colors.info,
13089 _ => colors.ignored,
13090 }
13091}
13092
13093pub fn styled_runs_for_code_label<'a>(
13094 label: &'a CodeLabel,
13095 syntax_theme: &'a theme::SyntaxTheme,
13096) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13097 let fade_out = HighlightStyle {
13098 fade_out: Some(0.35),
13099 ..Default::default()
13100 };
13101
13102 let mut prev_end = label.filter_range.end;
13103 label
13104 .runs
13105 .iter()
13106 .enumerate()
13107 .flat_map(move |(ix, (range, highlight_id))| {
13108 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13109 style
13110 } else {
13111 return Default::default();
13112 };
13113 let mut muted_style = style;
13114 muted_style.highlight(fade_out);
13115
13116 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13117 if range.start >= label.filter_range.end {
13118 if range.start > prev_end {
13119 runs.push((prev_end..range.start, fade_out));
13120 }
13121 runs.push((range.clone(), muted_style));
13122 } else if range.end <= label.filter_range.end {
13123 runs.push((range.clone(), style));
13124 } else {
13125 runs.push((range.start..label.filter_range.end, style));
13126 runs.push((label.filter_range.end..range.end, muted_style));
13127 }
13128 prev_end = cmp::max(prev_end, range.end);
13129
13130 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13131 runs.push((prev_end..label.text.len(), fade_out));
13132 }
13133
13134 runs
13135 })
13136}
13137
13138pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13139 let mut prev_index = 0;
13140 let mut prev_codepoint: Option<char> = None;
13141 text.char_indices()
13142 .chain([(text.len(), '\0')])
13143 .filter_map(move |(index, codepoint)| {
13144 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13145 let is_boundary = index == text.len()
13146 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13147 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13148 if is_boundary {
13149 let chunk = &text[prev_index..index];
13150 prev_index = index;
13151 Some(chunk)
13152 } else {
13153 None
13154 }
13155 })
13156}
13157
13158pub trait RangeToAnchorExt: Sized {
13159 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13160
13161 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13162 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13163 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13164 }
13165}
13166
13167impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13168 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13169 let start_offset = self.start.to_offset(snapshot);
13170 let end_offset = self.end.to_offset(snapshot);
13171 if start_offset == end_offset {
13172 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13173 } else {
13174 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13175 }
13176 }
13177}
13178
13179pub trait RowExt {
13180 fn as_f32(&self) -> f32;
13181
13182 fn next_row(&self) -> Self;
13183
13184 fn previous_row(&self) -> Self;
13185
13186 fn minus(&self, other: Self) -> u32;
13187}
13188
13189impl RowExt for DisplayRow {
13190 fn as_f32(&self) -> f32 {
13191 self.0 as f32
13192 }
13193
13194 fn next_row(&self) -> Self {
13195 Self(self.0 + 1)
13196 }
13197
13198 fn previous_row(&self) -> Self {
13199 Self(self.0.saturating_sub(1))
13200 }
13201
13202 fn minus(&self, other: Self) -> u32 {
13203 self.0 - other.0
13204 }
13205}
13206
13207impl RowExt for MultiBufferRow {
13208 fn as_f32(&self) -> f32 {
13209 self.0 as f32
13210 }
13211
13212 fn next_row(&self) -> Self {
13213 Self(self.0 + 1)
13214 }
13215
13216 fn previous_row(&self) -> Self {
13217 Self(self.0.saturating_sub(1))
13218 }
13219
13220 fn minus(&self, other: Self) -> u32 {
13221 self.0 - other.0
13222 }
13223}
13224
13225trait RowRangeExt {
13226 type Row;
13227
13228 fn len(&self) -> usize;
13229
13230 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13231}
13232
13233impl RowRangeExt for Range<MultiBufferRow> {
13234 type Row = MultiBufferRow;
13235
13236 fn len(&self) -> usize {
13237 (self.end.0 - self.start.0) as usize
13238 }
13239
13240 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13241 (self.start.0..self.end.0).map(MultiBufferRow)
13242 }
13243}
13244
13245impl RowRangeExt for Range<DisplayRow> {
13246 type Row = DisplayRow;
13247
13248 fn len(&self) -> usize {
13249 (self.end.0 - self.start.0) as usize
13250 }
13251
13252 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13253 (self.start.0..self.end.0).map(DisplayRow)
13254 }
13255}
13256
13257fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13258 if hunk.diff_base_byte_range.is_empty() {
13259 DiffHunkStatus::Added
13260 } else if hunk.associated_range.is_empty() {
13261 DiffHunkStatus::Removed
13262 } else {
13263 DiffHunkStatus::Modified
13264 }
13265}