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 blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
84 ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
85 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
86 InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
87 Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
88 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
89 WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
103 HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
104 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109pub use proposed_changes_editor::{
110 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
111};
112use similar::{ChangeTag, TextDiff};
113use std::iter::Peekable;
114use task::{ResolvedTask, TaskTemplate, TaskVariables};
115
116use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
117pub use lsp::CompletionContext;
118use lsp::{
119 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
120 LanguageServerId, LanguageServerName,
121};
122
123use language::BufferSnapshot;
124use movement::TextLayoutDetails;
125pub use multi_buffer::{
126 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
127 ToOffset, ToPoint,
128};
129use multi_buffer::{
130 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
131 ToOffsetUtf16,
132};
133use project::{
134 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
135 project_settings::{GitGutterSetting, ProjectSettings},
136 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
137 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
138};
139use rand::prelude::*;
140use rpc::{proto::*, ErrorExt};
141use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
142use selections_collection::{
143 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
144};
145use serde::{Deserialize, Serialize};
146use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
147use smallvec::SmallVec;
148use snippet::Snippet;
149use std::{
150 any::TypeId,
151 borrow::Cow,
152 cell::RefCell,
153 cmp::{self, Ordering, Reverse},
154 mem,
155 num::NonZeroU32,
156 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
157 path::{Path, PathBuf},
158 rc::Rc,
159 sync::Arc,
160 time::{Duration, Instant},
161};
162pub use sum_tree::Bias;
163use sum_tree::TreeMap;
164use text::{BufferId, OffsetUtf16, Rope};
165use theme::{
166 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
167 ThemeColors, ThemeSettings,
168};
169use ui::{
170 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
171 Tooltip,
172};
173use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
174use workspace::item::{ItemHandle, PreviewTabsSettings};
175use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
176use workspace::{
177 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
178};
179use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
180
181use crate::hover_links::{find_url, find_url_from_range};
182use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
183
184pub const FILE_HEADER_HEIGHT: u32 = 2;
185pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
186pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
187pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
188const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
189const MAX_LINE_LEN: usize = 1024;
190const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
191const MAX_SELECTION_HISTORY_LEN: usize = 1024;
192pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
193#[doc(hidden)]
194pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
195
196pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
197pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
198
199pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
200pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
201
202pub fn render_parsed_markdown(
203 element_id: impl Into<ElementId>,
204 parsed: &language::ParsedMarkdown,
205 editor_style: &EditorStyle,
206 workspace: Option<WeakEntity<Workspace>>,
207 cx: &mut App,
208) -> InteractiveText {
209 let code_span_background_color = cx
210 .theme()
211 .colors()
212 .editor_document_highlight_read_background;
213
214 let highlights = gpui::combine_highlights(
215 parsed.highlights.iter().filter_map(|(range, highlight)| {
216 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
217 Some((range.clone(), highlight))
218 }),
219 parsed
220 .regions
221 .iter()
222 .zip(&parsed.region_ranges)
223 .filter_map(|(region, range)| {
224 if region.code {
225 Some((
226 range.clone(),
227 HighlightStyle {
228 background_color: Some(code_span_background_color),
229 ..Default::default()
230 },
231 ))
232 } else {
233 None
234 }
235 }),
236 );
237
238 let mut links = Vec::new();
239 let mut link_ranges = Vec::new();
240 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
241 if let Some(link) = region.link.clone() {
242 links.push(link);
243 link_ranges.push(range.clone());
244 }
245 }
246
247 InteractiveText::new(
248 element_id,
249 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
250 )
251 .on_click(
252 link_ranges,
253 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
254 markdown::Link::Web { url } => cx.open_url(url),
255 markdown::Link::Path { path } => {
256 if let Some(workspace) = &workspace {
257 _ = workspace.update(cx, |workspace, cx| {
258 workspace
259 .open_abs_path(path.clone(), false, window, cx)
260 .detach();
261 });
262 }
263 }
264 },
265 )
266}
267
268#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
269pub enum InlayId {
270 InlineCompletion(usize),
271 Hint(usize),
272}
273
274impl InlayId {
275 fn id(&self) -> usize {
276 match self {
277 Self::InlineCompletion(id) => *id,
278 Self::Hint(id) => *id,
279 }
280 }
281}
282
283enum DocumentHighlightRead {}
284enum DocumentHighlightWrite {}
285enum InputComposition {}
286enum SelectedTextHighlight {}
287
288#[derive(Debug, Copy, Clone, PartialEq, Eq)]
289pub enum Navigated {
290 Yes,
291 No,
292}
293
294impl Navigated {
295 pub fn from_bool(yes: bool) -> Navigated {
296 if yes {
297 Navigated::Yes
298 } else {
299 Navigated::No
300 }
301 }
302}
303
304pub fn init_settings(cx: &mut App) {
305 EditorSettings::register(cx);
306}
307
308pub fn init(cx: &mut App) {
309 init_settings(cx);
310
311 workspace::register_project_item::<Editor>(cx);
312 workspace::FollowableViewRegistry::register::<Editor>(cx);
313 workspace::register_serializable_item::<Editor>(cx);
314
315 cx.observe_new(
316 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
317 workspace.register_action(Editor::new_file);
318 workspace.register_action(Editor::new_file_vertical);
319 workspace.register_action(Editor::new_file_horizontal);
320 workspace.register_action(Editor::cancel_language_server_work);
321 },
322 )
323 .detach();
324
325 cx.on_action(move |_: &workspace::NewFile, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(
329 Default::default(),
330 app_state,
331 cx,
332 |workspace, window, cx| {
333 Editor::new_file(workspace, &Default::default(), window, cx)
334 },
335 )
336 .detach();
337 }
338 });
339 cx.on_action(move |_: &workspace::NewWindow, cx| {
340 let app_state = workspace::AppState::global(cx);
341 if let Some(app_state) = app_state.upgrade() {
342 workspace::open_new(
343 Default::default(),
344 app_state,
345 cx,
346 |workspace, window, cx| {
347 cx.activate(true);
348 Editor::new_file(workspace, &Default::default(), window, cx)
349 },
350 )
351 .detach();
352 }
353 });
354}
355
356pub struct SearchWithinRange;
357
358trait InvalidationRegion {
359 fn ranges(&self) -> &[Range<Anchor>];
360}
361
362#[derive(Clone, Debug, PartialEq)]
363pub enum SelectPhase {
364 Begin {
365 position: DisplayPoint,
366 add: bool,
367 click_count: usize,
368 },
369 BeginColumnar {
370 position: DisplayPoint,
371 reset: bool,
372 goal_column: u32,
373 },
374 Extend {
375 position: DisplayPoint,
376 click_count: usize,
377 },
378 Update {
379 position: DisplayPoint,
380 goal_column: u32,
381 scroll_delta: gpui::Point<f32>,
382 },
383 End,
384}
385
386#[derive(Clone, Debug)]
387pub enum SelectMode {
388 Character,
389 Word(Range<Anchor>),
390 Line(Range<Anchor>),
391 All,
392}
393
394#[derive(Copy, Clone, PartialEq, Eq, Debug)]
395pub enum EditorMode {
396 SingleLine { auto_width: bool },
397 AutoHeight { max_lines: usize },
398 Full,
399}
400
401#[derive(Copy, Clone, Debug)]
402pub enum SoftWrap {
403 /// Prefer not to wrap at all.
404 ///
405 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
406 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
407 GitDiff,
408 /// Prefer a single line generally, unless an overly long line is encountered.
409 None,
410 /// Soft wrap lines that exceed the editor width.
411 EditorWidth,
412 /// Soft wrap lines at the preferred line length.
413 Column(u32),
414 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
415 Bounded(u32),
416}
417
418#[derive(Clone)]
419pub struct EditorStyle {
420 pub background: Hsla,
421 pub local_player: PlayerColor,
422 pub text: TextStyle,
423 pub scrollbar_width: Pixels,
424 pub syntax: Arc<SyntaxTheme>,
425 pub status: StatusColors,
426 pub inlay_hints_style: HighlightStyle,
427 pub inline_completion_styles: InlineCompletionStyles,
428 pub unnecessary_code_fade: f32,
429}
430
431impl Default for EditorStyle {
432 fn default() -> Self {
433 Self {
434 background: Hsla::default(),
435 local_player: PlayerColor::default(),
436 text: TextStyle::default(),
437 scrollbar_width: Pixels::default(),
438 syntax: Default::default(),
439 // HACK: Status colors don't have a real default.
440 // We should look into removing the status colors from the editor
441 // style and retrieve them directly from the theme.
442 status: StatusColors::dark(),
443 inlay_hints_style: HighlightStyle::default(),
444 inline_completion_styles: InlineCompletionStyles {
445 insertion: HighlightStyle::default(),
446 whitespace: HighlightStyle::default(),
447 },
448 unnecessary_code_fade: Default::default(),
449 }
450 }
451}
452
453pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
454 let show_background = language_settings::language_settings(None, None, cx)
455 .inlay_hints
456 .show_background;
457
458 HighlightStyle {
459 color: Some(cx.theme().status().hint),
460 background_color: show_background.then(|| cx.theme().status().hint_background),
461 ..HighlightStyle::default()
462 }
463}
464
465pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
466 InlineCompletionStyles {
467 insertion: HighlightStyle {
468 color: Some(cx.theme().status().predictive),
469 ..HighlightStyle::default()
470 },
471 whitespace: HighlightStyle {
472 background_color: Some(cx.theme().status().created_background),
473 ..HighlightStyle::default()
474 },
475 }
476}
477
478type CompletionId = usize;
479
480pub(crate) enum EditDisplayMode {
481 TabAccept,
482 DiffPopover,
483 Inline,
484}
485
486enum InlineCompletion {
487 Edit {
488 edits: Vec<(Range<Anchor>, String)>,
489 edit_preview: Option<EditPreview>,
490 display_mode: EditDisplayMode,
491 snapshot: BufferSnapshot,
492 },
493 Move {
494 target: Anchor,
495 snapshot: BufferSnapshot,
496 },
497}
498
499struct InlineCompletionState {
500 inlay_ids: Vec<InlayId>,
501 completion: InlineCompletion,
502 completion_id: Option<SharedString>,
503 invalidation_range: Range<Anchor>,
504}
505
506enum EditPredictionSettings {
507 Disabled,
508 Enabled {
509 show_in_menu: bool,
510 preview_requires_modifier: bool,
511 },
512}
513
514enum InlineCompletionHighlight {}
515
516pub enum MenuInlineCompletionsPolicy {
517 Never,
518 ByProvider,
519}
520
521pub enum EditPredictionPreview {
522 /// Modifier is not pressed
523 Inactive,
524 /// Modifier pressed
525 Active {
526 previous_scroll_position: Option<ScrollAnchor>,
527 },
528}
529
530#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
531struct EditorActionId(usize);
532
533impl EditorActionId {
534 pub fn post_inc(&mut self) -> Self {
535 let answer = self.0;
536
537 *self = Self(answer + 1);
538
539 Self(answer)
540 }
541}
542
543// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
544// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
545
546type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
547type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
548
549#[derive(Default)]
550struct ScrollbarMarkerState {
551 scrollbar_size: Size<Pixels>,
552 dirty: bool,
553 markers: Arc<[PaintQuad]>,
554 pending_refresh: Option<Task<Result<()>>>,
555}
556
557impl ScrollbarMarkerState {
558 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
559 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
560 }
561}
562
563#[derive(Clone, Debug)]
564struct RunnableTasks {
565 templates: Vec<(TaskSourceKind, TaskTemplate)>,
566 offset: MultiBufferOffset,
567 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
568 column: u32,
569 // Values of all named captures, including those starting with '_'
570 extra_variables: HashMap<String, String>,
571 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
572 context_range: Range<BufferOffset>,
573}
574
575impl RunnableTasks {
576 fn resolve<'a>(
577 &'a self,
578 cx: &'a task::TaskContext,
579 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
580 self.templates.iter().filter_map(|(kind, template)| {
581 template
582 .resolve_task(&kind.to_id_base(), cx)
583 .map(|task| (kind.clone(), task))
584 })
585 }
586}
587
588#[derive(Clone)]
589struct ResolvedTasks {
590 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
591 position: Anchor,
592}
593#[derive(Copy, Clone, Debug)]
594struct MultiBufferOffset(usize);
595#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
596struct BufferOffset(usize);
597
598// Addons allow storing per-editor state in other crates (e.g. Vim)
599pub trait Addon: 'static {
600 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
601
602 fn render_buffer_header_controls(
603 &self,
604 _: &ExcerptInfo,
605 _: &Window,
606 _: &App,
607 ) -> Option<AnyElement> {
608 None
609 }
610
611 fn to_any(&self) -> &dyn std::any::Any;
612}
613
614#[derive(Debug, Copy, Clone, PartialEq, Eq)]
615pub enum IsVimMode {
616 Yes,
617 No,
618}
619
620/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
621///
622/// See the [module level documentation](self) for more information.
623pub struct Editor {
624 focus_handle: FocusHandle,
625 last_focused_descendant: Option<WeakFocusHandle>,
626 /// The text buffer being edited
627 buffer: Entity<MultiBuffer>,
628 /// Map of how text in the buffer should be displayed.
629 /// Handles soft wraps, folds, fake inlay text insertions, etc.
630 pub display_map: Entity<DisplayMap>,
631 pub selections: SelectionsCollection,
632 pub scroll_manager: ScrollManager,
633 /// When inline assist editors are linked, they all render cursors because
634 /// typing enters text into each of them, even the ones that aren't focused.
635 pub(crate) show_cursor_when_unfocused: bool,
636 columnar_selection_tail: Option<Anchor>,
637 add_selections_state: Option<AddSelectionsState>,
638 select_next_state: Option<SelectNextState>,
639 select_prev_state: Option<SelectNextState>,
640 selection_history: SelectionHistory,
641 autoclose_regions: Vec<AutocloseRegion>,
642 snippet_stack: InvalidationStack<SnippetState>,
643 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
644 ime_transaction: Option<TransactionId>,
645 active_diagnostics: Option<ActiveDiagnosticGroup>,
646 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
647
648 // TODO: make this a access method
649 pub project: Option<Entity<Project>>,
650 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
651 completion_provider: Option<Box<dyn CompletionProvider>>,
652 collaboration_hub: Option<Box<dyn CollaborationHub>>,
653 blink_manager: Entity<BlinkManager>,
654 show_cursor_names: bool,
655 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
656 pub show_local_selections: bool,
657 mode: EditorMode,
658 show_breadcrumbs: bool,
659 show_gutter: bool,
660 show_scrollbars: bool,
661 show_line_numbers: Option<bool>,
662 use_relative_line_numbers: Option<bool>,
663 show_git_diff_gutter: Option<bool>,
664 show_code_actions: Option<bool>,
665 show_runnables: Option<bool>,
666 show_wrap_guides: Option<bool>,
667 show_indent_guides: Option<bool>,
668 placeholder_text: Option<Arc<str>>,
669 highlight_order: usize,
670 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
671 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
672 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
673 scrollbar_marker_state: ScrollbarMarkerState,
674 active_indent_guides_state: ActiveIndentGuidesState,
675 nav_history: Option<ItemNavHistory>,
676 context_menu: RefCell<Option<CodeContextMenu>>,
677 mouse_context_menu: Option<MouseContextMenu>,
678 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
679 signature_help_state: SignatureHelpState,
680 auto_signature_help: Option<bool>,
681 find_all_references_task_sources: Vec<Anchor>,
682 next_completion_id: CompletionId,
683 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
684 code_actions_task: Option<Task<Result<()>>>,
685 selection_highlight_task: Option<Task<()>>,
686 document_highlights_task: Option<Task<()>>,
687 linked_editing_range_task: Option<Task<Option<()>>>,
688 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
689 pending_rename: Option<RenameState>,
690 searchable: bool,
691 cursor_shape: CursorShape,
692 current_line_highlight: Option<CurrentLineHighlight>,
693 collapse_matches: bool,
694 autoindent_mode: Option<AutoindentMode>,
695 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
696 input_enabled: bool,
697 use_modal_editing: bool,
698 read_only: bool,
699 leader_peer_id: Option<PeerId>,
700 remote_id: Option<ViewId>,
701 hover_state: HoverState,
702 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
703 gutter_hovered: bool,
704 hovered_link_state: Option<HoveredLinkState>,
705 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
706 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
707 active_inline_completion: Option<InlineCompletionState>,
708 /// Used to prevent flickering as the user types while the menu is open
709 stale_inline_completion_in_menu: Option<InlineCompletionState>,
710 edit_prediction_settings: EditPredictionSettings,
711 inline_completions_hidden_for_vim_mode: bool,
712 show_inline_completions_override: Option<bool>,
713 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
714 edit_prediction_preview: EditPredictionPreview,
715 edit_prediction_cursor_on_leading_whitespace: bool,
716 edit_prediction_requires_modifier_in_leading_space: bool,
717 inlay_hint_cache: InlayHintCache,
718 next_inlay_id: usize,
719 _subscriptions: Vec<Subscription>,
720 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
721 gutter_dimensions: GutterDimensions,
722 style: Option<EditorStyle>,
723 text_style_refinement: Option<TextStyleRefinement>,
724 next_editor_action_id: EditorActionId,
725 editor_actions:
726 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
727 use_autoclose: bool,
728 use_auto_surround: bool,
729 auto_replace_emoji_shortcode: bool,
730 show_git_blame_gutter: bool,
731 show_git_blame_inline: bool,
732 show_git_blame_inline_delay_task: Option<Task<()>>,
733 distinguish_unstaged_diff_hunks: bool,
734 git_blame_inline_enabled: bool,
735 serialize_dirty_buffers: bool,
736 show_selection_menu: Option<bool>,
737 blame: Option<Entity<GitBlame>>,
738 blame_subscription: Option<Subscription>,
739 custom_context_menu: Option<
740 Box<
741 dyn 'static
742 + Fn(
743 &mut Self,
744 DisplayPoint,
745 &mut Window,
746 &mut Context<Self>,
747 ) -> Option<Entity<ui::ContextMenu>>,
748 >,
749 >,
750 last_bounds: Option<Bounds<Pixels>>,
751 last_position_map: Option<Rc<PositionMap>>,
752 expect_bounds_change: Option<Bounds<Pixels>>,
753 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
754 tasks_update_task: Option<Task<()>>,
755 in_project_search: bool,
756 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
757 breadcrumb_header: Option<String>,
758 focused_block: Option<FocusedBlock>,
759 next_scroll_position: NextScrollCursorCenterTopBottom,
760 addons: HashMap<TypeId, Box<dyn Addon>>,
761 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
762 load_diff_task: Option<Shared<Task<()>>>,
763 selection_mark_mode: bool,
764 toggle_fold_multiple_buffers: Task<()>,
765 _scroll_cursor_center_top_bottom_task: Task<()>,
766}
767
768#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
769enum NextScrollCursorCenterTopBottom {
770 #[default]
771 Center,
772 Top,
773 Bottom,
774}
775
776impl NextScrollCursorCenterTopBottom {
777 fn next(&self) -> Self {
778 match self {
779 Self::Center => Self::Top,
780 Self::Top => Self::Bottom,
781 Self::Bottom => Self::Center,
782 }
783 }
784}
785
786#[derive(Clone)]
787pub struct EditorSnapshot {
788 pub mode: EditorMode,
789 show_gutter: bool,
790 show_line_numbers: Option<bool>,
791 show_git_diff_gutter: Option<bool>,
792 show_code_actions: Option<bool>,
793 show_runnables: Option<bool>,
794 git_blame_gutter_max_author_length: Option<usize>,
795 pub display_snapshot: DisplaySnapshot,
796 pub placeholder_text: Option<Arc<str>>,
797 is_focused: bool,
798 scroll_anchor: ScrollAnchor,
799 ongoing_scroll: OngoingScroll,
800 current_line_highlight: CurrentLineHighlight,
801 gutter_hovered: bool,
802}
803
804const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
805
806#[derive(Default, Debug, Clone, Copy)]
807pub struct GutterDimensions {
808 pub left_padding: Pixels,
809 pub right_padding: Pixels,
810 pub width: Pixels,
811 pub margin: Pixels,
812 pub git_blame_entries_width: Option<Pixels>,
813}
814
815impl GutterDimensions {
816 /// The full width of the space taken up by the gutter.
817 pub fn full_width(&self) -> Pixels {
818 self.margin + self.width
819 }
820
821 /// The width of the space reserved for the fold indicators,
822 /// use alongside 'justify_end' and `gutter_width` to
823 /// right align content with the line numbers
824 pub fn fold_area_width(&self) -> Pixels {
825 self.margin + self.right_padding
826 }
827}
828
829#[derive(Debug)]
830pub struct RemoteSelection {
831 pub replica_id: ReplicaId,
832 pub selection: Selection<Anchor>,
833 pub cursor_shape: CursorShape,
834 pub peer_id: PeerId,
835 pub line_mode: bool,
836 pub participant_index: Option<ParticipantIndex>,
837 pub user_name: Option<SharedString>,
838}
839
840#[derive(Clone, Debug)]
841struct SelectionHistoryEntry {
842 selections: Arc<[Selection<Anchor>]>,
843 select_next_state: Option<SelectNextState>,
844 select_prev_state: Option<SelectNextState>,
845 add_selections_state: Option<AddSelectionsState>,
846}
847
848enum SelectionHistoryMode {
849 Normal,
850 Undoing,
851 Redoing,
852}
853
854#[derive(Clone, PartialEq, Eq, Hash)]
855struct HoveredCursor {
856 replica_id: u16,
857 selection_id: usize,
858}
859
860impl Default for SelectionHistoryMode {
861 fn default() -> Self {
862 Self::Normal
863 }
864}
865
866#[derive(Default)]
867struct SelectionHistory {
868 #[allow(clippy::type_complexity)]
869 selections_by_transaction:
870 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
871 mode: SelectionHistoryMode,
872 undo_stack: VecDeque<SelectionHistoryEntry>,
873 redo_stack: VecDeque<SelectionHistoryEntry>,
874}
875
876impl SelectionHistory {
877 fn insert_transaction(
878 &mut self,
879 transaction_id: TransactionId,
880 selections: Arc<[Selection<Anchor>]>,
881 ) {
882 self.selections_by_transaction
883 .insert(transaction_id, (selections, None));
884 }
885
886 #[allow(clippy::type_complexity)]
887 fn transaction(
888 &self,
889 transaction_id: TransactionId,
890 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
891 self.selections_by_transaction.get(&transaction_id)
892 }
893
894 #[allow(clippy::type_complexity)]
895 fn transaction_mut(
896 &mut self,
897 transaction_id: TransactionId,
898 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
899 self.selections_by_transaction.get_mut(&transaction_id)
900 }
901
902 fn push(&mut self, entry: SelectionHistoryEntry) {
903 if !entry.selections.is_empty() {
904 match self.mode {
905 SelectionHistoryMode::Normal => {
906 self.push_undo(entry);
907 self.redo_stack.clear();
908 }
909 SelectionHistoryMode::Undoing => self.push_redo(entry),
910 SelectionHistoryMode::Redoing => self.push_undo(entry),
911 }
912 }
913 }
914
915 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
916 if self
917 .undo_stack
918 .back()
919 .map_or(true, |e| e.selections != entry.selections)
920 {
921 self.undo_stack.push_back(entry);
922 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
923 self.undo_stack.pop_front();
924 }
925 }
926 }
927
928 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
929 if self
930 .redo_stack
931 .back()
932 .map_or(true, |e| e.selections != entry.selections)
933 {
934 self.redo_stack.push_back(entry);
935 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
936 self.redo_stack.pop_front();
937 }
938 }
939 }
940}
941
942struct RowHighlight {
943 index: usize,
944 range: Range<Anchor>,
945 color: Hsla,
946 should_autoscroll: bool,
947}
948
949#[derive(Clone, Debug)]
950struct AddSelectionsState {
951 above: bool,
952 stack: Vec<usize>,
953}
954
955#[derive(Clone)]
956struct SelectNextState {
957 query: AhoCorasick,
958 wordwise: bool,
959 done: bool,
960}
961
962impl std::fmt::Debug for SelectNextState {
963 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
964 f.debug_struct(std::any::type_name::<Self>())
965 .field("wordwise", &self.wordwise)
966 .field("done", &self.done)
967 .finish()
968 }
969}
970
971#[derive(Debug)]
972struct AutocloseRegion {
973 selection_id: usize,
974 range: Range<Anchor>,
975 pair: BracketPair,
976}
977
978#[derive(Debug)]
979struct SnippetState {
980 ranges: Vec<Vec<Range<Anchor>>>,
981 active_index: usize,
982 choices: Vec<Option<Vec<String>>>,
983}
984
985#[doc(hidden)]
986pub struct RenameState {
987 pub range: Range<Anchor>,
988 pub old_name: Arc<str>,
989 pub editor: Entity<Editor>,
990 block_id: CustomBlockId,
991}
992
993struct InvalidationStack<T>(Vec<T>);
994
995struct RegisteredInlineCompletionProvider {
996 provider: Arc<dyn InlineCompletionProviderHandle>,
997 _subscription: Subscription,
998}
999
1000#[derive(Debug)]
1001struct ActiveDiagnosticGroup {
1002 primary_range: Range<Anchor>,
1003 primary_message: String,
1004 group_id: usize,
1005 blocks: HashMap<CustomBlockId, Diagnostic>,
1006 is_valid: bool,
1007}
1008
1009#[derive(Serialize, Deserialize, Clone, Debug)]
1010pub struct ClipboardSelection {
1011 pub len: usize,
1012 pub is_entire_line: bool,
1013 pub first_line_indent: u32,
1014}
1015
1016#[derive(Debug)]
1017pub(crate) struct NavigationData {
1018 cursor_anchor: Anchor,
1019 cursor_position: Point,
1020 scroll_anchor: ScrollAnchor,
1021 scroll_top_row: u32,
1022}
1023
1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1025pub enum GotoDefinitionKind {
1026 Symbol,
1027 Declaration,
1028 Type,
1029 Implementation,
1030}
1031
1032#[derive(Debug, Clone)]
1033enum InlayHintRefreshReason {
1034 Toggle(bool),
1035 SettingsChange(InlayHintSettings),
1036 NewLinesShown,
1037 BufferEdited(HashSet<Arc<Language>>),
1038 RefreshRequested,
1039 ExcerptsRemoved(Vec<ExcerptId>),
1040}
1041
1042impl InlayHintRefreshReason {
1043 fn description(&self) -> &'static str {
1044 match self {
1045 Self::Toggle(_) => "toggle",
1046 Self::SettingsChange(_) => "settings change",
1047 Self::NewLinesShown => "new lines shown",
1048 Self::BufferEdited(_) => "buffer edited",
1049 Self::RefreshRequested => "refresh requested",
1050 Self::ExcerptsRemoved(_) => "excerpts removed",
1051 }
1052 }
1053}
1054
1055pub enum FormatTarget {
1056 Buffers,
1057 Ranges(Vec<Range<MultiBufferPoint>>),
1058}
1059
1060pub(crate) struct FocusedBlock {
1061 id: BlockId,
1062 focus_handle: WeakFocusHandle,
1063}
1064
1065#[derive(Clone)]
1066enum JumpData {
1067 MultiBufferRow {
1068 row: MultiBufferRow,
1069 line_offset_from_top: u32,
1070 },
1071 MultiBufferPoint {
1072 excerpt_id: ExcerptId,
1073 position: Point,
1074 anchor: text::Anchor,
1075 line_offset_from_top: u32,
1076 },
1077}
1078
1079pub enum MultibufferSelectionMode {
1080 First,
1081 All,
1082}
1083
1084impl Editor {
1085 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1086 let buffer = cx.new(|cx| Buffer::local("", cx));
1087 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1088 Self::new(
1089 EditorMode::SingleLine { auto_width: false },
1090 buffer,
1091 None,
1092 false,
1093 window,
1094 cx,
1095 )
1096 }
1097
1098 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1099 let buffer = cx.new(|cx| Buffer::local("", cx));
1100 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1101 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1102 }
1103
1104 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1105 let buffer = cx.new(|cx| Buffer::local("", cx));
1106 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1107 Self::new(
1108 EditorMode::SingleLine { auto_width: true },
1109 buffer,
1110 None,
1111 false,
1112 window,
1113 cx,
1114 )
1115 }
1116
1117 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1118 let buffer = cx.new(|cx| Buffer::local("", cx));
1119 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1120 Self::new(
1121 EditorMode::AutoHeight { max_lines },
1122 buffer,
1123 None,
1124 false,
1125 window,
1126 cx,
1127 )
1128 }
1129
1130 pub fn for_buffer(
1131 buffer: Entity<Buffer>,
1132 project: Option<Entity<Project>>,
1133 window: &mut Window,
1134 cx: &mut Context<Self>,
1135 ) -> Self {
1136 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1137 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1138 }
1139
1140 pub fn for_multibuffer(
1141 buffer: Entity<MultiBuffer>,
1142 project: Option<Entity<Project>>,
1143 show_excerpt_controls: bool,
1144 window: &mut Window,
1145 cx: &mut Context<Self>,
1146 ) -> Self {
1147 Self::new(
1148 EditorMode::Full,
1149 buffer,
1150 project,
1151 show_excerpt_controls,
1152 window,
1153 cx,
1154 )
1155 }
1156
1157 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1158 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1159 let mut clone = Self::new(
1160 self.mode,
1161 self.buffer.clone(),
1162 self.project.clone(),
1163 show_excerpt_controls,
1164 window,
1165 cx,
1166 );
1167 self.display_map.update(cx, |display_map, cx| {
1168 let snapshot = display_map.snapshot(cx);
1169 clone.display_map.update(cx, |display_map, cx| {
1170 display_map.set_state(&snapshot, cx);
1171 });
1172 });
1173 clone.selections.clone_state(&self.selections);
1174 clone.scroll_manager.clone_state(&self.scroll_manager);
1175 clone.searchable = self.searchable;
1176 clone
1177 }
1178
1179 pub fn new(
1180 mode: EditorMode,
1181 buffer: Entity<MultiBuffer>,
1182 project: Option<Entity<Project>>,
1183 show_excerpt_controls: bool,
1184 window: &mut Window,
1185 cx: &mut Context<Self>,
1186 ) -> Self {
1187 let style = window.text_style();
1188 let font_size = style.font_size.to_pixels(window.rem_size());
1189 let editor = cx.entity().downgrade();
1190 let fold_placeholder = FoldPlaceholder {
1191 constrain_width: true,
1192 render: Arc::new(move |fold_id, fold_range, _, cx| {
1193 let editor = editor.clone();
1194 div()
1195 .id(fold_id)
1196 .bg(cx.theme().colors().ghost_element_background)
1197 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1198 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1199 .rounded_sm()
1200 .size_full()
1201 .cursor_pointer()
1202 .child("⋯")
1203 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1204 .on_click(move |_, _window, cx| {
1205 editor
1206 .update(cx, |editor, cx| {
1207 editor.unfold_ranges(
1208 &[fold_range.start..fold_range.end],
1209 true,
1210 false,
1211 cx,
1212 );
1213 cx.stop_propagation();
1214 })
1215 .ok();
1216 })
1217 .into_any()
1218 }),
1219 merge_adjacent: true,
1220 ..Default::default()
1221 };
1222 let display_map = cx.new(|cx| {
1223 DisplayMap::new(
1224 buffer.clone(),
1225 style.font(),
1226 font_size,
1227 None,
1228 show_excerpt_controls,
1229 FILE_HEADER_HEIGHT,
1230 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1231 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1232 fold_placeholder,
1233 cx,
1234 )
1235 });
1236
1237 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1238
1239 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1240
1241 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1242 .then(|| language_settings::SoftWrap::None);
1243
1244 let mut project_subscriptions = Vec::new();
1245 if mode == EditorMode::Full {
1246 if let Some(project) = project.as_ref() {
1247 if buffer.read(cx).is_singleton() {
1248 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1249 cx.emit(EditorEvent::TitleChanged);
1250 }));
1251 }
1252 project_subscriptions.push(cx.subscribe_in(
1253 project,
1254 window,
1255 |editor, _, event, window, cx| {
1256 if let project::Event::RefreshInlayHints = event {
1257 editor
1258 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1259 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1260 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1261 let focus_handle = editor.focus_handle(cx);
1262 if focus_handle.is_focused(window) {
1263 let snapshot = buffer.read(cx).snapshot();
1264 for (range, snippet) in snippet_edits {
1265 let editor_range =
1266 language::range_from_lsp(*range).to_offset(&snapshot);
1267 editor
1268 .insert_snippet(
1269 &[editor_range],
1270 snippet.clone(),
1271 window,
1272 cx,
1273 )
1274 .ok();
1275 }
1276 }
1277 }
1278 }
1279 },
1280 ));
1281 if let Some(task_inventory) = project
1282 .read(cx)
1283 .task_store()
1284 .read(cx)
1285 .task_inventory()
1286 .cloned()
1287 {
1288 project_subscriptions.push(cx.observe_in(
1289 &task_inventory,
1290 window,
1291 |editor, _, window, cx| {
1292 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1293 },
1294 ));
1295 }
1296 }
1297 }
1298
1299 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1300
1301 let inlay_hint_settings =
1302 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1303 let focus_handle = cx.focus_handle();
1304 cx.on_focus(&focus_handle, window, Self::handle_focus)
1305 .detach();
1306 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1307 .detach();
1308 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1309 .detach();
1310 cx.on_blur(&focus_handle, window, Self::handle_blur)
1311 .detach();
1312
1313 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1314 Some(false)
1315 } else {
1316 None
1317 };
1318
1319 let mut code_action_providers = Vec::new();
1320 let mut load_uncommitted_diff = None;
1321 if let Some(project) = project.clone() {
1322 load_uncommitted_diff = Some(
1323 get_uncommitted_diff_for_buffer(
1324 &project,
1325 buffer.read(cx).all_buffers(),
1326 buffer.clone(),
1327 cx,
1328 )
1329 .shared(),
1330 );
1331 code_action_providers.push(Rc::new(project) as Rc<_>);
1332 }
1333
1334 let mut this = Self {
1335 focus_handle,
1336 show_cursor_when_unfocused: false,
1337 last_focused_descendant: None,
1338 buffer: buffer.clone(),
1339 display_map: display_map.clone(),
1340 selections,
1341 scroll_manager: ScrollManager::new(cx),
1342 columnar_selection_tail: None,
1343 add_selections_state: None,
1344 select_next_state: None,
1345 select_prev_state: None,
1346 selection_history: Default::default(),
1347 autoclose_regions: Default::default(),
1348 snippet_stack: Default::default(),
1349 select_larger_syntax_node_stack: Vec::new(),
1350 ime_transaction: Default::default(),
1351 active_diagnostics: None,
1352 soft_wrap_mode_override,
1353 completion_provider: project.clone().map(|project| Box::new(project) as _),
1354 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1355 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1356 project,
1357 blink_manager: blink_manager.clone(),
1358 show_local_selections: true,
1359 show_scrollbars: true,
1360 mode,
1361 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1362 show_gutter: mode == EditorMode::Full,
1363 show_line_numbers: None,
1364 use_relative_line_numbers: None,
1365 show_git_diff_gutter: None,
1366 show_code_actions: None,
1367 show_runnables: None,
1368 show_wrap_guides: None,
1369 show_indent_guides,
1370 placeholder_text: None,
1371 highlight_order: 0,
1372 highlighted_rows: HashMap::default(),
1373 background_highlights: Default::default(),
1374 gutter_highlights: TreeMap::default(),
1375 scrollbar_marker_state: ScrollbarMarkerState::default(),
1376 active_indent_guides_state: ActiveIndentGuidesState::default(),
1377 nav_history: None,
1378 context_menu: RefCell::new(None),
1379 mouse_context_menu: None,
1380 completion_tasks: Default::default(),
1381 signature_help_state: SignatureHelpState::default(),
1382 auto_signature_help: None,
1383 find_all_references_task_sources: Vec::new(),
1384 next_completion_id: 0,
1385 next_inlay_id: 0,
1386 code_action_providers,
1387 available_code_actions: Default::default(),
1388 code_actions_task: Default::default(),
1389 selection_highlight_task: Default::default(),
1390 document_highlights_task: Default::default(),
1391 linked_editing_range_task: Default::default(),
1392 pending_rename: Default::default(),
1393 searchable: true,
1394 cursor_shape: EditorSettings::get_global(cx)
1395 .cursor_shape
1396 .unwrap_or_default(),
1397 current_line_highlight: None,
1398 autoindent_mode: Some(AutoindentMode::EachLine),
1399 collapse_matches: false,
1400 workspace: None,
1401 input_enabled: true,
1402 use_modal_editing: mode == EditorMode::Full,
1403 read_only: false,
1404 use_autoclose: true,
1405 use_auto_surround: true,
1406 auto_replace_emoji_shortcode: false,
1407 leader_peer_id: None,
1408 remote_id: None,
1409 hover_state: Default::default(),
1410 pending_mouse_down: None,
1411 hovered_link_state: Default::default(),
1412 edit_prediction_provider: None,
1413 active_inline_completion: None,
1414 stale_inline_completion_in_menu: None,
1415 edit_prediction_preview: EditPredictionPreview::Inactive,
1416 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1417
1418 gutter_hovered: false,
1419 pixel_position_of_newest_cursor: None,
1420 last_bounds: None,
1421 last_position_map: None,
1422 expect_bounds_change: None,
1423 gutter_dimensions: GutterDimensions::default(),
1424 style: None,
1425 show_cursor_names: false,
1426 hovered_cursors: Default::default(),
1427 next_editor_action_id: EditorActionId::default(),
1428 editor_actions: Rc::default(),
1429 inline_completions_hidden_for_vim_mode: false,
1430 show_inline_completions_override: None,
1431 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1432 edit_prediction_settings: EditPredictionSettings::Disabled,
1433 edit_prediction_cursor_on_leading_whitespace: false,
1434 edit_prediction_requires_modifier_in_leading_space: true,
1435 custom_context_menu: None,
1436 show_git_blame_gutter: false,
1437 show_git_blame_inline: false,
1438 distinguish_unstaged_diff_hunks: false,
1439 show_selection_menu: None,
1440 show_git_blame_inline_delay_task: None,
1441 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1442 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1443 .session
1444 .restore_unsaved_buffers,
1445 blame: None,
1446 blame_subscription: None,
1447 tasks: Default::default(),
1448 _subscriptions: vec![
1449 cx.observe(&buffer, Self::on_buffer_changed),
1450 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1451 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1452 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1453 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1454 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1455 cx.observe_window_activation(window, |editor, window, cx| {
1456 let active = window.is_window_active();
1457 editor.blink_manager.update(cx, |blink_manager, cx| {
1458 if active {
1459 blink_manager.enable(cx);
1460 } else {
1461 blink_manager.disable(cx);
1462 }
1463 });
1464 }),
1465 ],
1466 tasks_update_task: None,
1467 linked_edit_ranges: Default::default(),
1468 in_project_search: false,
1469 previous_search_ranges: None,
1470 breadcrumb_header: None,
1471 focused_block: None,
1472 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1473 addons: HashMap::default(),
1474 registered_buffers: HashMap::default(),
1475 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1476 selection_mark_mode: false,
1477 toggle_fold_multiple_buffers: Task::ready(()),
1478 text_style_refinement: None,
1479 load_diff_task: load_uncommitted_diff,
1480 };
1481 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1482 this._subscriptions.extend(project_subscriptions);
1483
1484 this.end_selection(window, cx);
1485 this.scroll_manager.show_scrollbar(window, cx);
1486
1487 if mode == EditorMode::Full {
1488 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1489 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1490
1491 if this.git_blame_inline_enabled {
1492 this.git_blame_inline_enabled = true;
1493 this.start_git_blame_inline(false, window, cx);
1494 }
1495
1496 if let Some(buffer) = buffer.read(cx).as_singleton() {
1497 if let Some(project) = this.project.as_ref() {
1498 let handle = project.update(cx, |project, cx| {
1499 project.register_buffer_with_language_servers(&buffer, cx)
1500 });
1501 this.registered_buffers
1502 .insert(buffer.read(cx).remote_id(), handle);
1503 }
1504 }
1505 }
1506
1507 this.report_editor_event("Editor Opened", None, cx);
1508 this
1509 }
1510
1511 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1512 self.mouse_context_menu
1513 .as_ref()
1514 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1515 }
1516
1517 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1518 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1519 }
1520
1521 fn key_context_internal(
1522 &self,
1523 has_active_edit_prediction: bool,
1524 window: &Window,
1525 cx: &App,
1526 ) -> KeyContext {
1527 let mut key_context = KeyContext::new_with_defaults();
1528 key_context.add("Editor");
1529 let mode = match self.mode {
1530 EditorMode::SingleLine { .. } => "single_line",
1531 EditorMode::AutoHeight { .. } => "auto_height",
1532 EditorMode::Full => "full",
1533 };
1534
1535 if EditorSettings::jupyter_enabled(cx) {
1536 key_context.add("jupyter");
1537 }
1538
1539 key_context.set("mode", mode);
1540 if self.pending_rename.is_some() {
1541 key_context.add("renaming");
1542 }
1543
1544 match self.context_menu.borrow().as_ref() {
1545 Some(CodeContextMenu::Completions(_)) => {
1546 key_context.add("menu");
1547 key_context.add("showing_completions");
1548 }
1549 Some(CodeContextMenu::CodeActions(_)) => {
1550 key_context.add("menu");
1551 key_context.add("showing_code_actions")
1552 }
1553 None => {}
1554 }
1555
1556 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1557 if !self.focus_handle(cx).contains_focused(window, cx)
1558 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1559 {
1560 for addon in self.addons.values() {
1561 addon.extend_key_context(&mut key_context, cx)
1562 }
1563 }
1564
1565 if let Some(extension) = self
1566 .buffer
1567 .read(cx)
1568 .as_singleton()
1569 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1570 {
1571 key_context.set("extension", extension.to_string());
1572 }
1573
1574 if has_active_edit_prediction {
1575 if self.edit_prediction_in_conflict() {
1576 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1577 } else {
1578 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1579 key_context.add("copilot_suggestion");
1580 }
1581 }
1582
1583 if self.selection_mark_mode {
1584 key_context.add("selection_mode");
1585 }
1586
1587 key_context
1588 }
1589
1590 pub fn edit_prediction_in_conflict(&self) -> bool {
1591 if !self.show_edit_predictions_in_menu() {
1592 return false;
1593 }
1594
1595 let showing_completions = self
1596 .context_menu
1597 .borrow()
1598 .as_ref()
1599 .map_or(false, |context| {
1600 matches!(context, CodeContextMenu::Completions(_))
1601 });
1602
1603 showing_completions
1604 || self.edit_prediction_requires_modifier()
1605 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1606 // bindings to insert tab characters.
1607 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1608 }
1609
1610 pub fn accept_edit_prediction_keybind(
1611 &self,
1612 window: &Window,
1613 cx: &App,
1614 ) -> AcceptEditPredictionBinding {
1615 let key_context = self.key_context_internal(true, window, cx);
1616 let in_conflict = self.edit_prediction_in_conflict();
1617
1618 AcceptEditPredictionBinding(
1619 window
1620 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1621 .into_iter()
1622 .filter(|binding| {
1623 !in_conflict
1624 || binding
1625 .keystrokes()
1626 .first()
1627 .map_or(false, |keystroke| keystroke.modifiers.modified())
1628 })
1629 .rev()
1630 .min_by_key(|binding| {
1631 binding
1632 .keystrokes()
1633 .first()
1634 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1635 }),
1636 )
1637 }
1638
1639 pub fn new_file(
1640 workspace: &mut Workspace,
1641 _: &workspace::NewFile,
1642 window: &mut Window,
1643 cx: &mut Context<Workspace>,
1644 ) {
1645 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1646 "Failed to create buffer",
1647 window,
1648 cx,
1649 |e, _, _| match e.error_code() {
1650 ErrorCode::RemoteUpgradeRequired => Some(format!(
1651 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1652 e.error_tag("required").unwrap_or("the latest version")
1653 )),
1654 _ => None,
1655 },
1656 );
1657 }
1658
1659 pub fn new_in_workspace(
1660 workspace: &mut Workspace,
1661 window: &mut Window,
1662 cx: &mut Context<Workspace>,
1663 ) -> Task<Result<Entity<Editor>>> {
1664 let project = workspace.project().clone();
1665 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1666
1667 cx.spawn_in(window, |workspace, mut cx| async move {
1668 let buffer = create.await?;
1669 workspace.update_in(&mut cx, |workspace, window, cx| {
1670 let editor =
1671 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1672 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1673 editor
1674 })
1675 })
1676 }
1677
1678 fn new_file_vertical(
1679 workspace: &mut Workspace,
1680 _: &workspace::NewFileSplitVertical,
1681 window: &mut Window,
1682 cx: &mut Context<Workspace>,
1683 ) {
1684 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1685 }
1686
1687 fn new_file_horizontal(
1688 workspace: &mut Workspace,
1689 _: &workspace::NewFileSplitHorizontal,
1690 window: &mut Window,
1691 cx: &mut Context<Workspace>,
1692 ) {
1693 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1694 }
1695
1696 fn new_file_in_direction(
1697 workspace: &mut Workspace,
1698 direction: SplitDirection,
1699 window: &mut Window,
1700 cx: &mut Context<Workspace>,
1701 ) {
1702 let project = workspace.project().clone();
1703 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1704
1705 cx.spawn_in(window, |workspace, mut cx| async move {
1706 let buffer = create.await?;
1707 workspace.update_in(&mut cx, move |workspace, window, cx| {
1708 workspace.split_item(
1709 direction,
1710 Box::new(
1711 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1712 ),
1713 window,
1714 cx,
1715 )
1716 })?;
1717 anyhow::Ok(())
1718 })
1719 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1720 match e.error_code() {
1721 ErrorCode::RemoteUpgradeRequired => Some(format!(
1722 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1723 e.error_tag("required").unwrap_or("the latest version")
1724 )),
1725 _ => None,
1726 }
1727 });
1728 }
1729
1730 pub fn leader_peer_id(&self) -> Option<PeerId> {
1731 self.leader_peer_id
1732 }
1733
1734 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1735 &self.buffer
1736 }
1737
1738 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1739 self.workspace.as_ref()?.0.upgrade()
1740 }
1741
1742 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1743 self.buffer().read(cx).title(cx)
1744 }
1745
1746 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1747 let git_blame_gutter_max_author_length = self
1748 .render_git_blame_gutter(cx)
1749 .then(|| {
1750 if let Some(blame) = self.blame.as_ref() {
1751 let max_author_length =
1752 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1753 Some(max_author_length)
1754 } else {
1755 None
1756 }
1757 })
1758 .flatten();
1759
1760 EditorSnapshot {
1761 mode: self.mode,
1762 show_gutter: self.show_gutter,
1763 show_line_numbers: self.show_line_numbers,
1764 show_git_diff_gutter: self.show_git_diff_gutter,
1765 show_code_actions: self.show_code_actions,
1766 show_runnables: self.show_runnables,
1767 git_blame_gutter_max_author_length,
1768 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1769 scroll_anchor: self.scroll_manager.anchor(),
1770 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1771 placeholder_text: self.placeholder_text.clone(),
1772 is_focused: self.focus_handle.is_focused(window),
1773 current_line_highlight: self
1774 .current_line_highlight
1775 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1776 gutter_hovered: self.gutter_hovered,
1777 }
1778 }
1779
1780 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1781 self.buffer.read(cx).language_at(point, cx)
1782 }
1783
1784 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1785 self.buffer.read(cx).read(cx).file_at(point).cloned()
1786 }
1787
1788 pub fn active_excerpt(
1789 &self,
1790 cx: &App,
1791 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1792 self.buffer
1793 .read(cx)
1794 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1795 }
1796
1797 pub fn mode(&self) -> EditorMode {
1798 self.mode
1799 }
1800
1801 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1802 self.collaboration_hub.as_deref()
1803 }
1804
1805 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1806 self.collaboration_hub = Some(hub);
1807 }
1808
1809 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1810 self.in_project_search = in_project_search;
1811 }
1812
1813 pub fn set_custom_context_menu(
1814 &mut self,
1815 f: impl 'static
1816 + Fn(
1817 &mut Self,
1818 DisplayPoint,
1819 &mut Window,
1820 &mut Context<Self>,
1821 ) -> Option<Entity<ui::ContextMenu>>,
1822 ) {
1823 self.custom_context_menu = Some(Box::new(f))
1824 }
1825
1826 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1827 self.completion_provider = provider;
1828 }
1829
1830 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1831 self.semantics_provider.clone()
1832 }
1833
1834 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1835 self.semantics_provider = provider;
1836 }
1837
1838 pub fn set_edit_prediction_provider<T>(
1839 &mut self,
1840 provider: Option<Entity<T>>,
1841 window: &mut Window,
1842 cx: &mut Context<Self>,
1843 ) where
1844 T: EditPredictionProvider,
1845 {
1846 self.edit_prediction_provider =
1847 provider.map(|provider| RegisteredInlineCompletionProvider {
1848 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1849 if this.focus_handle.is_focused(window) {
1850 this.update_visible_inline_completion(window, cx);
1851 }
1852 }),
1853 provider: Arc::new(provider),
1854 });
1855 self.refresh_inline_completion(false, false, window, cx);
1856 }
1857
1858 pub fn placeholder_text(&self) -> Option<&str> {
1859 self.placeholder_text.as_deref()
1860 }
1861
1862 pub fn set_placeholder_text(
1863 &mut self,
1864 placeholder_text: impl Into<Arc<str>>,
1865 cx: &mut Context<Self>,
1866 ) {
1867 let placeholder_text = Some(placeholder_text.into());
1868 if self.placeholder_text != placeholder_text {
1869 self.placeholder_text = placeholder_text;
1870 cx.notify();
1871 }
1872 }
1873
1874 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1875 self.cursor_shape = cursor_shape;
1876
1877 // Disrupt blink for immediate user feedback that the cursor shape has changed
1878 self.blink_manager.update(cx, BlinkManager::show_cursor);
1879
1880 cx.notify();
1881 }
1882
1883 pub fn set_current_line_highlight(
1884 &mut self,
1885 current_line_highlight: Option<CurrentLineHighlight>,
1886 ) {
1887 self.current_line_highlight = current_line_highlight;
1888 }
1889
1890 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1891 self.collapse_matches = collapse_matches;
1892 }
1893
1894 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1895 let buffers = self.buffer.read(cx).all_buffers();
1896 let Some(project) = self.project.as_ref() else {
1897 return;
1898 };
1899 project.update(cx, |project, cx| {
1900 for buffer in buffers {
1901 self.registered_buffers
1902 .entry(buffer.read(cx).remote_id())
1903 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1904 }
1905 })
1906 }
1907
1908 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1909 if self.collapse_matches {
1910 return range.start..range.start;
1911 }
1912 range.clone()
1913 }
1914
1915 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1916 if self.display_map.read(cx).clip_at_line_ends != clip {
1917 self.display_map
1918 .update(cx, |map, _| map.clip_at_line_ends = clip);
1919 }
1920 }
1921
1922 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1923 self.input_enabled = input_enabled;
1924 }
1925
1926 pub fn set_inline_completions_hidden_for_vim_mode(
1927 &mut self,
1928 hidden: bool,
1929 window: &mut Window,
1930 cx: &mut Context<Self>,
1931 ) {
1932 if hidden != self.inline_completions_hidden_for_vim_mode {
1933 self.inline_completions_hidden_for_vim_mode = hidden;
1934 if hidden {
1935 self.update_visible_inline_completion(window, cx);
1936 } else {
1937 self.refresh_inline_completion(true, false, window, cx);
1938 }
1939 }
1940 }
1941
1942 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1943 self.menu_inline_completions_policy = value;
1944 }
1945
1946 pub fn set_autoindent(&mut self, autoindent: bool) {
1947 if autoindent {
1948 self.autoindent_mode = Some(AutoindentMode::EachLine);
1949 } else {
1950 self.autoindent_mode = None;
1951 }
1952 }
1953
1954 pub fn read_only(&self, cx: &App) -> bool {
1955 self.read_only || self.buffer.read(cx).read_only()
1956 }
1957
1958 pub fn set_read_only(&mut self, read_only: bool) {
1959 self.read_only = read_only;
1960 }
1961
1962 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1963 self.use_autoclose = autoclose;
1964 }
1965
1966 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1967 self.use_auto_surround = auto_surround;
1968 }
1969
1970 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1971 self.auto_replace_emoji_shortcode = auto_replace;
1972 }
1973
1974 pub fn toggle_inline_completions(
1975 &mut self,
1976 _: &ToggleEditPrediction,
1977 window: &mut Window,
1978 cx: &mut Context<Self>,
1979 ) {
1980 if self.show_inline_completions_override.is_some() {
1981 self.set_show_edit_predictions(None, window, cx);
1982 } else {
1983 let show_edit_predictions = !self.edit_predictions_enabled();
1984 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1985 }
1986 }
1987
1988 pub fn set_show_edit_predictions(
1989 &mut self,
1990 show_edit_predictions: Option<bool>,
1991 window: &mut Window,
1992 cx: &mut Context<Self>,
1993 ) {
1994 self.show_inline_completions_override = show_edit_predictions;
1995 self.refresh_inline_completion(false, true, window, cx);
1996 }
1997
1998 fn inline_completions_disabled_in_scope(
1999 &self,
2000 buffer: &Entity<Buffer>,
2001 buffer_position: language::Anchor,
2002 cx: &App,
2003 ) -> bool {
2004 let snapshot = buffer.read(cx).snapshot();
2005 let settings = snapshot.settings_at(buffer_position, cx);
2006
2007 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2008 return false;
2009 };
2010
2011 scope.override_name().map_or(false, |scope_name| {
2012 settings
2013 .edit_predictions_disabled_in
2014 .iter()
2015 .any(|s| s == scope_name)
2016 })
2017 }
2018
2019 pub fn set_use_modal_editing(&mut self, to: bool) {
2020 self.use_modal_editing = to;
2021 }
2022
2023 pub fn use_modal_editing(&self) -> bool {
2024 self.use_modal_editing
2025 }
2026
2027 fn selections_did_change(
2028 &mut self,
2029 local: bool,
2030 old_cursor_position: &Anchor,
2031 show_completions: bool,
2032 window: &mut Window,
2033 cx: &mut Context<Self>,
2034 ) {
2035 window.invalidate_character_coordinates();
2036
2037 // Copy selections to primary selection buffer
2038 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2039 if local {
2040 let selections = self.selections.all::<usize>(cx);
2041 let buffer_handle = self.buffer.read(cx).read(cx);
2042
2043 let mut text = String::new();
2044 for (index, selection) in selections.iter().enumerate() {
2045 let text_for_selection = buffer_handle
2046 .text_for_range(selection.start..selection.end)
2047 .collect::<String>();
2048
2049 text.push_str(&text_for_selection);
2050 if index != selections.len() - 1 {
2051 text.push('\n');
2052 }
2053 }
2054
2055 if !text.is_empty() {
2056 cx.write_to_primary(ClipboardItem::new_string(text));
2057 }
2058 }
2059
2060 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2061 self.buffer.update(cx, |buffer, cx| {
2062 buffer.set_active_selections(
2063 &self.selections.disjoint_anchors(),
2064 self.selections.line_mode,
2065 self.cursor_shape,
2066 cx,
2067 )
2068 });
2069 }
2070 let display_map = self
2071 .display_map
2072 .update(cx, |display_map, cx| display_map.snapshot(cx));
2073 let buffer = &display_map.buffer_snapshot;
2074 self.add_selections_state = None;
2075 self.select_next_state = None;
2076 self.select_prev_state = None;
2077 self.select_larger_syntax_node_stack.clear();
2078 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2079 self.snippet_stack
2080 .invalidate(&self.selections.disjoint_anchors(), buffer);
2081 self.take_rename(false, window, cx);
2082
2083 let new_cursor_position = self.selections.newest_anchor().head();
2084
2085 self.push_to_nav_history(
2086 *old_cursor_position,
2087 Some(new_cursor_position.to_point(buffer)),
2088 cx,
2089 );
2090
2091 if local {
2092 let new_cursor_position = self.selections.newest_anchor().head();
2093 let mut context_menu = self.context_menu.borrow_mut();
2094 let completion_menu = match context_menu.as_ref() {
2095 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2096 _ => {
2097 *context_menu = None;
2098 None
2099 }
2100 };
2101 if let Some(buffer_id) = new_cursor_position.buffer_id {
2102 if !self.registered_buffers.contains_key(&buffer_id) {
2103 if let Some(project) = self.project.as_ref() {
2104 project.update(cx, |project, cx| {
2105 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2106 return;
2107 };
2108 self.registered_buffers.insert(
2109 buffer_id,
2110 project.register_buffer_with_language_servers(&buffer, cx),
2111 );
2112 })
2113 }
2114 }
2115 }
2116
2117 if let Some(completion_menu) = completion_menu {
2118 let cursor_position = new_cursor_position.to_offset(buffer);
2119 let (word_range, kind) =
2120 buffer.surrounding_word(completion_menu.initial_position, true);
2121 if kind == Some(CharKind::Word)
2122 && word_range.to_inclusive().contains(&cursor_position)
2123 {
2124 let mut completion_menu = completion_menu.clone();
2125 drop(context_menu);
2126
2127 let query = Self::completion_query(buffer, cursor_position);
2128 cx.spawn(move |this, mut cx| async move {
2129 completion_menu
2130 .filter(query.as_deref(), cx.background_executor().clone())
2131 .await;
2132
2133 this.update(&mut cx, |this, cx| {
2134 let mut context_menu = this.context_menu.borrow_mut();
2135 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2136 else {
2137 return;
2138 };
2139
2140 if menu.id > completion_menu.id {
2141 return;
2142 }
2143
2144 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2145 drop(context_menu);
2146 cx.notify();
2147 })
2148 })
2149 .detach();
2150
2151 if show_completions {
2152 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2153 }
2154 } else {
2155 drop(context_menu);
2156 self.hide_context_menu(window, cx);
2157 }
2158 } else {
2159 drop(context_menu);
2160 }
2161
2162 hide_hover(self, cx);
2163
2164 if old_cursor_position.to_display_point(&display_map).row()
2165 != new_cursor_position.to_display_point(&display_map).row()
2166 {
2167 self.available_code_actions.take();
2168 }
2169 self.refresh_code_actions(window, cx);
2170 self.refresh_document_highlights(cx);
2171 self.refresh_selected_text_highlights(window, cx);
2172 refresh_matching_bracket_highlights(self, window, cx);
2173 self.update_visible_inline_completion(window, cx);
2174 self.edit_prediction_requires_modifier_in_leading_space = true;
2175 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2176 if self.git_blame_inline_enabled {
2177 self.start_inline_blame_timer(window, cx);
2178 }
2179 }
2180
2181 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2182 cx.emit(EditorEvent::SelectionsChanged { local });
2183
2184 if self.selections.disjoint_anchors().len() == 1 {
2185 cx.emit(SearchEvent::ActiveMatchChanged)
2186 }
2187 cx.notify();
2188 }
2189
2190 pub fn change_selections<R>(
2191 &mut self,
2192 autoscroll: Option<Autoscroll>,
2193 window: &mut Window,
2194 cx: &mut Context<Self>,
2195 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2196 ) -> R {
2197 self.change_selections_inner(autoscroll, true, window, cx, change)
2198 }
2199
2200 pub fn change_selections_inner<R>(
2201 &mut self,
2202 autoscroll: Option<Autoscroll>,
2203 request_completions: bool,
2204 window: &mut Window,
2205 cx: &mut Context<Self>,
2206 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2207 ) -> R {
2208 let old_cursor_position = self.selections.newest_anchor().head();
2209 self.push_to_selection_history();
2210
2211 let (changed, result) = self.selections.change_with(cx, change);
2212
2213 if changed {
2214 if let Some(autoscroll) = autoscroll {
2215 self.request_autoscroll(autoscroll, cx);
2216 }
2217 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2218
2219 if self.should_open_signature_help_automatically(
2220 &old_cursor_position,
2221 self.signature_help_state.backspace_pressed(),
2222 cx,
2223 ) {
2224 self.show_signature_help(&ShowSignatureHelp, window, cx);
2225 }
2226 self.signature_help_state.set_backspace_pressed(false);
2227 }
2228
2229 result
2230 }
2231
2232 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2233 where
2234 I: IntoIterator<Item = (Range<S>, T)>,
2235 S: ToOffset,
2236 T: Into<Arc<str>>,
2237 {
2238 if self.read_only(cx) {
2239 return;
2240 }
2241
2242 self.buffer
2243 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2244 }
2245
2246 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2247 where
2248 I: IntoIterator<Item = (Range<S>, T)>,
2249 S: ToOffset,
2250 T: Into<Arc<str>>,
2251 {
2252 if self.read_only(cx) {
2253 return;
2254 }
2255
2256 self.buffer.update(cx, |buffer, cx| {
2257 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2258 });
2259 }
2260
2261 pub fn edit_with_block_indent<I, S, T>(
2262 &mut self,
2263 edits: I,
2264 original_indent_columns: Vec<u32>,
2265 cx: &mut Context<Self>,
2266 ) where
2267 I: IntoIterator<Item = (Range<S>, T)>,
2268 S: ToOffset,
2269 T: Into<Arc<str>>,
2270 {
2271 if self.read_only(cx) {
2272 return;
2273 }
2274
2275 self.buffer.update(cx, |buffer, cx| {
2276 buffer.edit(
2277 edits,
2278 Some(AutoindentMode::Block {
2279 original_indent_columns,
2280 }),
2281 cx,
2282 )
2283 });
2284 }
2285
2286 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2287 self.hide_context_menu(window, cx);
2288
2289 match phase {
2290 SelectPhase::Begin {
2291 position,
2292 add,
2293 click_count,
2294 } => self.begin_selection(position, add, click_count, window, cx),
2295 SelectPhase::BeginColumnar {
2296 position,
2297 goal_column,
2298 reset,
2299 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2300 SelectPhase::Extend {
2301 position,
2302 click_count,
2303 } => self.extend_selection(position, click_count, window, cx),
2304 SelectPhase::Update {
2305 position,
2306 goal_column,
2307 scroll_delta,
2308 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2309 SelectPhase::End => self.end_selection(window, cx),
2310 }
2311 }
2312
2313 fn extend_selection(
2314 &mut self,
2315 position: DisplayPoint,
2316 click_count: usize,
2317 window: &mut Window,
2318 cx: &mut Context<Self>,
2319 ) {
2320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2321 let tail = self.selections.newest::<usize>(cx).tail();
2322 self.begin_selection(position, false, click_count, window, cx);
2323
2324 let position = position.to_offset(&display_map, Bias::Left);
2325 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2326
2327 let mut pending_selection = self
2328 .selections
2329 .pending_anchor()
2330 .expect("extend_selection not called with pending selection");
2331 if position >= tail {
2332 pending_selection.start = tail_anchor;
2333 } else {
2334 pending_selection.end = tail_anchor;
2335 pending_selection.reversed = true;
2336 }
2337
2338 let mut pending_mode = self.selections.pending_mode().unwrap();
2339 match &mut pending_mode {
2340 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2341 _ => {}
2342 }
2343
2344 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2345 s.set_pending(pending_selection, pending_mode)
2346 });
2347 }
2348
2349 fn begin_selection(
2350 &mut self,
2351 position: DisplayPoint,
2352 add: bool,
2353 click_count: usize,
2354 window: &mut Window,
2355 cx: &mut Context<Self>,
2356 ) {
2357 if !self.focus_handle.is_focused(window) {
2358 self.last_focused_descendant = None;
2359 window.focus(&self.focus_handle);
2360 }
2361
2362 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2363 let buffer = &display_map.buffer_snapshot;
2364 let newest_selection = self.selections.newest_anchor().clone();
2365 let position = display_map.clip_point(position, Bias::Left);
2366
2367 let start;
2368 let end;
2369 let mode;
2370 let mut auto_scroll;
2371 match click_count {
2372 1 => {
2373 start = buffer.anchor_before(position.to_point(&display_map));
2374 end = start;
2375 mode = SelectMode::Character;
2376 auto_scroll = true;
2377 }
2378 2 => {
2379 let range = movement::surrounding_word(&display_map, position);
2380 start = buffer.anchor_before(range.start.to_point(&display_map));
2381 end = buffer.anchor_before(range.end.to_point(&display_map));
2382 mode = SelectMode::Word(start..end);
2383 auto_scroll = true;
2384 }
2385 3 => {
2386 let position = display_map
2387 .clip_point(position, Bias::Left)
2388 .to_point(&display_map);
2389 let line_start = display_map.prev_line_boundary(position).0;
2390 let next_line_start = buffer.clip_point(
2391 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2392 Bias::Left,
2393 );
2394 start = buffer.anchor_before(line_start);
2395 end = buffer.anchor_before(next_line_start);
2396 mode = SelectMode::Line(start..end);
2397 auto_scroll = true;
2398 }
2399 _ => {
2400 start = buffer.anchor_before(0);
2401 end = buffer.anchor_before(buffer.len());
2402 mode = SelectMode::All;
2403 auto_scroll = false;
2404 }
2405 }
2406 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2407
2408 let point_to_delete: Option<usize> = {
2409 let selected_points: Vec<Selection<Point>> =
2410 self.selections.disjoint_in_range(start..end, cx);
2411
2412 if !add || click_count > 1 {
2413 None
2414 } else if !selected_points.is_empty() {
2415 Some(selected_points[0].id)
2416 } else {
2417 let clicked_point_already_selected =
2418 self.selections.disjoint.iter().find(|selection| {
2419 selection.start.to_point(buffer) == start.to_point(buffer)
2420 || selection.end.to_point(buffer) == end.to_point(buffer)
2421 });
2422
2423 clicked_point_already_selected.map(|selection| selection.id)
2424 }
2425 };
2426
2427 let selections_count = self.selections.count();
2428
2429 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2430 if let Some(point_to_delete) = point_to_delete {
2431 s.delete(point_to_delete);
2432
2433 if selections_count == 1 {
2434 s.set_pending_anchor_range(start..end, mode);
2435 }
2436 } else {
2437 if !add {
2438 s.clear_disjoint();
2439 } else if click_count > 1 {
2440 s.delete(newest_selection.id)
2441 }
2442
2443 s.set_pending_anchor_range(start..end, mode);
2444 }
2445 });
2446 }
2447
2448 fn begin_columnar_selection(
2449 &mut self,
2450 position: DisplayPoint,
2451 goal_column: u32,
2452 reset: bool,
2453 window: &mut Window,
2454 cx: &mut Context<Self>,
2455 ) {
2456 if !self.focus_handle.is_focused(window) {
2457 self.last_focused_descendant = None;
2458 window.focus(&self.focus_handle);
2459 }
2460
2461 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2462
2463 if reset {
2464 let pointer_position = display_map
2465 .buffer_snapshot
2466 .anchor_before(position.to_point(&display_map));
2467
2468 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2469 s.clear_disjoint();
2470 s.set_pending_anchor_range(
2471 pointer_position..pointer_position,
2472 SelectMode::Character,
2473 );
2474 });
2475 }
2476
2477 let tail = self.selections.newest::<Point>(cx).tail();
2478 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2479
2480 if !reset {
2481 self.select_columns(
2482 tail.to_display_point(&display_map),
2483 position,
2484 goal_column,
2485 &display_map,
2486 window,
2487 cx,
2488 );
2489 }
2490 }
2491
2492 fn update_selection(
2493 &mut self,
2494 position: DisplayPoint,
2495 goal_column: u32,
2496 scroll_delta: gpui::Point<f32>,
2497 window: &mut Window,
2498 cx: &mut Context<Self>,
2499 ) {
2500 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2501
2502 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2503 let tail = tail.to_display_point(&display_map);
2504 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2505 } else if let Some(mut pending) = self.selections.pending_anchor() {
2506 let buffer = self.buffer.read(cx).snapshot(cx);
2507 let head;
2508 let tail;
2509 let mode = self.selections.pending_mode().unwrap();
2510 match &mode {
2511 SelectMode::Character => {
2512 head = position.to_point(&display_map);
2513 tail = pending.tail().to_point(&buffer);
2514 }
2515 SelectMode::Word(original_range) => {
2516 let original_display_range = original_range.start.to_display_point(&display_map)
2517 ..original_range.end.to_display_point(&display_map);
2518 let original_buffer_range = original_display_range.start.to_point(&display_map)
2519 ..original_display_range.end.to_point(&display_map);
2520 if movement::is_inside_word(&display_map, position)
2521 || original_display_range.contains(&position)
2522 {
2523 let word_range = movement::surrounding_word(&display_map, position);
2524 if word_range.start < original_display_range.start {
2525 head = word_range.start.to_point(&display_map);
2526 } else {
2527 head = word_range.end.to_point(&display_map);
2528 }
2529 } else {
2530 head = position.to_point(&display_map);
2531 }
2532
2533 if head <= original_buffer_range.start {
2534 tail = original_buffer_range.end;
2535 } else {
2536 tail = original_buffer_range.start;
2537 }
2538 }
2539 SelectMode::Line(original_range) => {
2540 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2541
2542 let position = display_map
2543 .clip_point(position, Bias::Left)
2544 .to_point(&display_map);
2545 let line_start = display_map.prev_line_boundary(position).0;
2546 let next_line_start = buffer.clip_point(
2547 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2548 Bias::Left,
2549 );
2550
2551 if line_start < original_range.start {
2552 head = line_start
2553 } else {
2554 head = next_line_start
2555 }
2556
2557 if head <= original_range.start {
2558 tail = original_range.end;
2559 } else {
2560 tail = original_range.start;
2561 }
2562 }
2563 SelectMode::All => {
2564 return;
2565 }
2566 };
2567
2568 if head < tail {
2569 pending.start = buffer.anchor_before(head);
2570 pending.end = buffer.anchor_before(tail);
2571 pending.reversed = true;
2572 } else {
2573 pending.start = buffer.anchor_before(tail);
2574 pending.end = buffer.anchor_before(head);
2575 pending.reversed = false;
2576 }
2577
2578 self.change_selections(None, window, cx, |s| {
2579 s.set_pending(pending, mode);
2580 });
2581 } else {
2582 log::error!("update_selection dispatched with no pending selection");
2583 return;
2584 }
2585
2586 self.apply_scroll_delta(scroll_delta, window, cx);
2587 cx.notify();
2588 }
2589
2590 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2591 self.columnar_selection_tail.take();
2592 if self.selections.pending_anchor().is_some() {
2593 let selections = self.selections.all::<usize>(cx);
2594 self.change_selections(None, window, cx, |s| {
2595 s.select(selections);
2596 s.clear_pending();
2597 });
2598 }
2599 }
2600
2601 fn select_columns(
2602 &mut self,
2603 tail: DisplayPoint,
2604 head: DisplayPoint,
2605 goal_column: u32,
2606 display_map: &DisplaySnapshot,
2607 window: &mut Window,
2608 cx: &mut Context<Self>,
2609 ) {
2610 let start_row = cmp::min(tail.row(), head.row());
2611 let end_row = cmp::max(tail.row(), head.row());
2612 let start_column = cmp::min(tail.column(), goal_column);
2613 let end_column = cmp::max(tail.column(), goal_column);
2614 let reversed = start_column < tail.column();
2615
2616 let selection_ranges = (start_row.0..=end_row.0)
2617 .map(DisplayRow)
2618 .filter_map(|row| {
2619 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2620 let start = display_map
2621 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2622 .to_point(display_map);
2623 let end = display_map
2624 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2625 .to_point(display_map);
2626 if reversed {
2627 Some(end..start)
2628 } else {
2629 Some(start..end)
2630 }
2631 } else {
2632 None
2633 }
2634 })
2635 .collect::<Vec<_>>();
2636
2637 self.change_selections(None, window, cx, |s| {
2638 s.select_ranges(selection_ranges);
2639 });
2640 cx.notify();
2641 }
2642
2643 pub fn has_pending_nonempty_selection(&self) -> bool {
2644 let pending_nonempty_selection = match self.selections.pending_anchor() {
2645 Some(Selection { start, end, .. }) => start != end,
2646 None => false,
2647 };
2648
2649 pending_nonempty_selection
2650 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2651 }
2652
2653 pub fn has_pending_selection(&self) -> bool {
2654 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2655 }
2656
2657 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2658 self.selection_mark_mode = false;
2659
2660 if self.clear_expanded_diff_hunks(cx) {
2661 cx.notify();
2662 return;
2663 }
2664 if self.dismiss_menus_and_popups(true, window, cx) {
2665 return;
2666 }
2667
2668 if self.mode == EditorMode::Full
2669 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2670 {
2671 return;
2672 }
2673
2674 cx.propagate();
2675 }
2676
2677 pub fn dismiss_menus_and_popups(
2678 &mut self,
2679 is_user_requested: bool,
2680 window: &mut Window,
2681 cx: &mut Context<Self>,
2682 ) -> bool {
2683 if self.take_rename(false, window, cx).is_some() {
2684 return true;
2685 }
2686
2687 if hide_hover(self, cx) {
2688 return true;
2689 }
2690
2691 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2692 return true;
2693 }
2694
2695 if self.hide_context_menu(window, cx).is_some() {
2696 return true;
2697 }
2698
2699 if self.mouse_context_menu.take().is_some() {
2700 return true;
2701 }
2702
2703 if is_user_requested && self.discard_inline_completion(true, cx) {
2704 return true;
2705 }
2706
2707 if self.snippet_stack.pop().is_some() {
2708 return true;
2709 }
2710
2711 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2712 self.dismiss_diagnostics(cx);
2713 return true;
2714 }
2715
2716 false
2717 }
2718
2719 fn linked_editing_ranges_for(
2720 &self,
2721 selection: Range<text::Anchor>,
2722 cx: &App,
2723 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2724 if self.linked_edit_ranges.is_empty() {
2725 return None;
2726 }
2727 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2728 selection.end.buffer_id.and_then(|end_buffer_id| {
2729 if selection.start.buffer_id != Some(end_buffer_id) {
2730 return None;
2731 }
2732 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2733 let snapshot = buffer.read(cx).snapshot();
2734 self.linked_edit_ranges
2735 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2736 .map(|ranges| (ranges, snapshot, buffer))
2737 })?;
2738 use text::ToOffset as TO;
2739 // find offset from the start of current range to current cursor position
2740 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2741
2742 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2743 let start_difference = start_offset - start_byte_offset;
2744 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2745 let end_difference = end_offset - start_byte_offset;
2746 // Current range has associated linked ranges.
2747 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2748 for range in linked_ranges.iter() {
2749 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2750 let end_offset = start_offset + end_difference;
2751 let start_offset = start_offset + start_difference;
2752 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2753 continue;
2754 }
2755 if self.selections.disjoint_anchor_ranges().any(|s| {
2756 if s.start.buffer_id != selection.start.buffer_id
2757 || s.end.buffer_id != selection.end.buffer_id
2758 {
2759 return false;
2760 }
2761 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2762 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2763 }) {
2764 continue;
2765 }
2766 let start = buffer_snapshot.anchor_after(start_offset);
2767 let end = buffer_snapshot.anchor_after(end_offset);
2768 linked_edits
2769 .entry(buffer.clone())
2770 .or_default()
2771 .push(start..end);
2772 }
2773 Some(linked_edits)
2774 }
2775
2776 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2777 let text: Arc<str> = text.into();
2778
2779 if self.read_only(cx) {
2780 return;
2781 }
2782
2783 let selections = self.selections.all_adjusted(cx);
2784 let mut bracket_inserted = false;
2785 let mut edits = Vec::new();
2786 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2787 let mut new_selections = Vec::with_capacity(selections.len());
2788 let mut new_autoclose_regions = Vec::new();
2789 let snapshot = self.buffer.read(cx).read(cx);
2790
2791 for (selection, autoclose_region) in
2792 self.selections_with_autoclose_regions(selections, &snapshot)
2793 {
2794 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2795 // Determine if the inserted text matches the opening or closing
2796 // bracket of any of this language's bracket pairs.
2797 let mut bracket_pair = None;
2798 let mut is_bracket_pair_start = false;
2799 let mut is_bracket_pair_end = false;
2800 if !text.is_empty() {
2801 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2802 // and they are removing the character that triggered IME popup.
2803 for (pair, enabled) in scope.brackets() {
2804 if !pair.close && !pair.surround {
2805 continue;
2806 }
2807
2808 if enabled && pair.start.ends_with(text.as_ref()) {
2809 let prefix_len = pair.start.len() - text.len();
2810 let preceding_text_matches_prefix = prefix_len == 0
2811 || (selection.start.column >= (prefix_len as u32)
2812 && snapshot.contains_str_at(
2813 Point::new(
2814 selection.start.row,
2815 selection.start.column - (prefix_len as u32),
2816 ),
2817 &pair.start[..prefix_len],
2818 ));
2819 if preceding_text_matches_prefix {
2820 bracket_pair = Some(pair.clone());
2821 is_bracket_pair_start = true;
2822 break;
2823 }
2824 }
2825 if pair.end.as_str() == text.as_ref() {
2826 bracket_pair = Some(pair.clone());
2827 is_bracket_pair_end = true;
2828 break;
2829 }
2830 }
2831 }
2832
2833 if let Some(bracket_pair) = bracket_pair {
2834 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2835 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2836 let auto_surround =
2837 self.use_auto_surround && snapshot_settings.use_auto_surround;
2838 if selection.is_empty() {
2839 if is_bracket_pair_start {
2840 // If the inserted text is a suffix of an opening bracket and the
2841 // selection is preceded by the rest of the opening bracket, then
2842 // insert the closing bracket.
2843 let following_text_allows_autoclose = snapshot
2844 .chars_at(selection.start)
2845 .next()
2846 .map_or(true, |c| scope.should_autoclose_before(c));
2847
2848 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2849 && bracket_pair.start.len() == 1
2850 {
2851 let target = bracket_pair.start.chars().next().unwrap();
2852 let current_line_count = snapshot
2853 .reversed_chars_at(selection.start)
2854 .take_while(|&c| c != '\n')
2855 .filter(|&c| c == target)
2856 .count();
2857 current_line_count % 2 == 1
2858 } else {
2859 false
2860 };
2861
2862 if autoclose
2863 && bracket_pair.close
2864 && following_text_allows_autoclose
2865 && !is_closing_quote
2866 {
2867 let anchor = snapshot.anchor_before(selection.end);
2868 new_selections.push((selection.map(|_| anchor), text.len()));
2869 new_autoclose_regions.push((
2870 anchor,
2871 text.len(),
2872 selection.id,
2873 bracket_pair.clone(),
2874 ));
2875 edits.push((
2876 selection.range(),
2877 format!("{}{}", text, bracket_pair.end).into(),
2878 ));
2879 bracket_inserted = true;
2880 continue;
2881 }
2882 }
2883
2884 if let Some(region) = autoclose_region {
2885 // If the selection is followed by an auto-inserted closing bracket,
2886 // then don't insert that closing bracket again; just move the selection
2887 // past the closing bracket.
2888 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2889 && text.as_ref() == region.pair.end.as_str();
2890 if should_skip {
2891 let anchor = snapshot.anchor_after(selection.end);
2892 new_selections
2893 .push((selection.map(|_| anchor), region.pair.end.len()));
2894 continue;
2895 }
2896 }
2897
2898 let always_treat_brackets_as_autoclosed = snapshot
2899 .settings_at(selection.start, cx)
2900 .always_treat_brackets_as_autoclosed;
2901 if always_treat_brackets_as_autoclosed
2902 && is_bracket_pair_end
2903 && snapshot.contains_str_at(selection.end, text.as_ref())
2904 {
2905 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2906 // and the inserted text is a closing bracket and the selection is followed
2907 // by the closing bracket then move the selection past the closing bracket.
2908 let anchor = snapshot.anchor_after(selection.end);
2909 new_selections.push((selection.map(|_| anchor), text.len()));
2910 continue;
2911 }
2912 }
2913 // If an opening bracket is 1 character long and is typed while
2914 // text is selected, then surround that text with the bracket pair.
2915 else if auto_surround
2916 && bracket_pair.surround
2917 && is_bracket_pair_start
2918 && bracket_pair.start.chars().count() == 1
2919 {
2920 edits.push((selection.start..selection.start, text.clone()));
2921 edits.push((
2922 selection.end..selection.end,
2923 bracket_pair.end.as_str().into(),
2924 ));
2925 bracket_inserted = true;
2926 new_selections.push((
2927 Selection {
2928 id: selection.id,
2929 start: snapshot.anchor_after(selection.start),
2930 end: snapshot.anchor_before(selection.end),
2931 reversed: selection.reversed,
2932 goal: selection.goal,
2933 },
2934 0,
2935 ));
2936 continue;
2937 }
2938 }
2939 }
2940
2941 if self.auto_replace_emoji_shortcode
2942 && selection.is_empty()
2943 && text.as_ref().ends_with(':')
2944 {
2945 if let Some(possible_emoji_short_code) =
2946 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2947 {
2948 if !possible_emoji_short_code.is_empty() {
2949 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2950 let emoji_shortcode_start = Point::new(
2951 selection.start.row,
2952 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2953 );
2954
2955 // Remove shortcode from buffer
2956 edits.push((
2957 emoji_shortcode_start..selection.start,
2958 "".to_string().into(),
2959 ));
2960 new_selections.push((
2961 Selection {
2962 id: selection.id,
2963 start: snapshot.anchor_after(emoji_shortcode_start),
2964 end: snapshot.anchor_before(selection.start),
2965 reversed: selection.reversed,
2966 goal: selection.goal,
2967 },
2968 0,
2969 ));
2970
2971 // Insert emoji
2972 let selection_start_anchor = snapshot.anchor_after(selection.start);
2973 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2974 edits.push((selection.start..selection.end, emoji.to_string().into()));
2975
2976 continue;
2977 }
2978 }
2979 }
2980 }
2981
2982 // If not handling any auto-close operation, then just replace the selected
2983 // text with the given input and move the selection to the end of the
2984 // newly inserted text.
2985 let anchor = snapshot.anchor_after(selection.end);
2986 if !self.linked_edit_ranges.is_empty() {
2987 let start_anchor = snapshot.anchor_before(selection.start);
2988
2989 let is_word_char = text.chars().next().map_or(true, |char| {
2990 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2991 classifier.is_word(char)
2992 });
2993
2994 if is_word_char {
2995 if let Some(ranges) = self
2996 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2997 {
2998 for (buffer, edits) in ranges {
2999 linked_edits
3000 .entry(buffer.clone())
3001 .or_default()
3002 .extend(edits.into_iter().map(|range| (range, text.clone())));
3003 }
3004 }
3005 }
3006 }
3007
3008 new_selections.push((selection.map(|_| anchor), 0));
3009 edits.push((selection.start..selection.end, text.clone()));
3010 }
3011
3012 drop(snapshot);
3013
3014 self.transact(window, cx, |this, window, cx| {
3015 this.buffer.update(cx, |buffer, cx| {
3016 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3017 });
3018 for (buffer, edits) in linked_edits {
3019 buffer.update(cx, |buffer, cx| {
3020 let snapshot = buffer.snapshot();
3021 let edits = edits
3022 .into_iter()
3023 .map(|(range, text)| {
3024 use text::ToPoint as TP;
3025 let end_point = TP::to_point(&range.end, &snapshot);
3026 let start_point = TP::to_point(&range.start, &snapshot);
3027 (start_point..end_point, text)
3028 })
3029 .sorted_by_key(|(range, _)| range.start)
3030 .collect::<Vec<_>>();
3031 buffer.edit(edits, None, cx);
3032 })
3033 }
3034 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3035 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3036 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3037 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3038 .zip(new_selection_deltas)
3039 .map(|(selection, delta)| Selection {
3040 id: selection.id,
3041 start: selection.start + delta,
3042 end: selection.end + delta,
3043 reversed: selection.reversed,
3044 goal: SelectionGoal::None,
3045 })
3046 .collect::<Vec<_>>();
3047
3048 let mut i = 0;
3049 for (position, delta, selection_id, pair) in new_autoclose_regions {
3050 let position = position.to_offset(&map.buffer_snapshot) + delta;
3051 let start = map.buffer_snapshot.anchor_before(position);
3052 let end = map.buffer_snapshot.anchor_after(position);
3053 while let Some(existing_state) = this.autoclose_regions.get(i) {
3054 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3055 Ordering::Less => i += 1,
3056 Ordering::Greater => break,
3057 Ordering::Equal => {
3058 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3059 Ordering::Less => i += 1,
3060 Ordering::Equal => break,
3061 Ordering::Greater => break,
3062 }
3063 }
3064 }
3065 }
3066 this.autoclose_regions.insert(
3067 i,
3068 AutocloseRegion {
3069 selection_id,
3070 range: start..end,
3071 pair,
3072 },
3073 );
3074 }
3075
3076 let had_active_inline_completion = this.has_active_inline_completion();
3077 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3078 s.select(new_selections)
3079 });
3080
3081 if !bracket_inserted {
3082 if let Some(on_type_format_task) =
3083 this.trigger_on_type_formatting(text.to_string(), window, cx)
3084 {
3085 on_type_format_task.detach_and_log_err(cx);
3086 }
3087 }
3088
3089 let editor_settings = EditorSettings::get_global(cx);
3090 if bracket_inserted
3091 && (editor_settings.auto_signature_help
3092 || editor_settings.show_signature_help_after_edits)
3093 {
3094 this.show_signature_help(&ShowSignatureHelp, window, cx);
3095 }
3096
3097 let trigger_in_words =
3098 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3099 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3100 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3101 this.refresh_inline_completion(true, false, window, cx);
3102 });
3103 }
3104
3105 fn find_possible_emoji_shortcode_at_position(
3106 snapshot: &MultiBufferSnapshot,
3107 position: Point,
3108 ) -> Option<String> {
3109 let mut chars = Vec::new();
3110 let mut found_colon = false;
3111 for char in snapshot.reversed_chars_at(position).take(100) {
3112 // Found a possible emoji shortcode in the middle of the buffer
3113 if found_colon {
3114 if char.is_whitespace() {
3115 chars.reverse();
3116 return Some(chars.iter().collect());
3117 }
3118 // If the previous character is not a whitespace, we are in the middle of a word
3119 // and we only want to complete the shortcode if the word is made up of other emojis
3120 let mut containing_word = String::new();
3121 for ch in snapshot
3122 .reversed_chars_at(position)
3123 .skip(chars.len() + 1)
3124 .take(100)
3125 {
3126 if ch.is_whitespace() {
3127 break;
3128 }
3129 containing_word.push(ch);
3130 }
3131 let containing_word = containing_word.chars().rev().collect::<String>();
3132 if util::word_consists_of_emojis(containing_word.as_str()) {
3133 chars.reverse();
3134 return Some(chars.iter().collect());
3135 }
3136 }
3137
3138 if char.is_whitespace() || !char.is_ascii() {
3139 return None;
3140 }
3141 if char == ':' {
3142 found_colon = true;
3143 } else {
3144 chars.push(char);
3145 }
3146 }
3147 // Found a possible emoji shortcode at the beginning of the buffer
3148 chars.reverse();
3149 Some(chars.iter().collect())
3150 }
3151
3152 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3153 self.transact(window, cx, |this, window, cx| {
3154 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3155 let selections = this.selections.all::<usize>(cx);
3156 let multi_buffer = this.buffer.read(cx);
3157 let buffer = multi_buffer.snapshot(cx);
3158 selections
3159 .iter()
3160 .map(|selection| {
3161 let start_point = selection.start.to_point(&buffer);
3162 let mut indent =
3163 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3164 indent.len = cmp::min(indent.len, start_point.column);
3165 let start = selection.start;
3166 let end = selection.end;
3167 let selection_is_empty = start == end;
3168 let language_scope = buffer.language_scope_at(start);
3169 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3170 &language_scope
3171 {
3172 let leading_whitespace_len = buffer
3173 .reversed_chars_at(start)
3174 .take_while(|c| c.is_whitespace() && *c != '\n')
3175 .map(|c| c.len_utf8())
3176 .sum::<usize>();
3177
3178 let trailing_whitespace_len = buffer
3179 .chars_at(end)
3180 .take_while(|c| c.is_whitespace() && *c != '\n')
3181 .map(|c| c.len_utf8())
3182 .sum::<usize>();
3183
3184 let insert_extra_newline =
3185 language.brackets().any(|(pair, enabled)| {
3186 let pair_start = pair.start.trim_end();
3187 let pair_end = pair.end.trim_start();
3188
3189 enabled
3190 && pair.newline
3191 && buffer.contains_str_at(
3192 end + trailing_whitespace_len,
3193 pair_end,
3194 )
3195 && buffer.contains_str_at(
3196 (start - leading_whitespace_len)
3197 .saturating_sub(pair_start.len()),
3198 pair_start,
3199 )
3200 });
3201
3202 // Comment extension on newline is allowed only for cursor selections
3203 let comment_delimiter = maybe!({
3204 if !selection_is_empty {
3205 return None;
3206 }
3207
3208 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3209 return None;
3210 }
3211
3212 let delimiters = language.line_comment_prefixes();
3213 let max_len_of_delimiter =
3214 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3215 let (snapshot, range) =
3216 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3217
3218 let mut index_of_first_non_whitespace = 0;
3219 let comment_candidate = snapshot
3220 .chars_for_range(range)
3221 .skip_while(|c| {
3222 let should_skip = c.is_whitespace();
3223 if should_skip {
3224 index_of_first_non_whitespace += 1;
3225 }
3226 should_skip
3227 })
3228 .take(max_len_of_delimiter)
3229 .collect::<String>();
3230 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3231 comment_candidate.starts_with(comment_prefix.as_ref())
3232 })?;
3233 let cursor_is_placed_after_comment_marker =
3234 index_of_first_non_whitespace + comment_prefix.len()
3235 <= start_point.column as usize;
3236 if cursor_is_placed_after_comment_marker {
3237 Some(comment_prefix.clone())
3238 } else {
3239 None
3240 }
3241 });
3242 (comment_delimiter, insert_extra_newline)
3243 } else {
3244 (None, false)
3245 };
3246
3247 let capacity_for_delimiter = comment_delimiter
3248 .as_deref()
3249 .map(str::len)
3250 .unwrap_or_default();
3251 let mut new_text =
3252 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3253 new_text.push('\n');
3254 new_text.extend(indent.chars());
3255 if let Some(delimiter) = &comment_delimiter {
3256 new_text.push_str(delimiter);
3257 }
3258 if insert_extra_newline {
3259 new_text = new_text.repeat(2);
3260 }
3261
3262 let anchor = buffer.anchor_after(end);
3263 let new_selection = selection.map(|_| anchor);
3264 (
3265 (start..end, new_text),
3266 (insert_extra_newline, new_selection),
3267 )
3268 })
3269 .unzip()
3270 };
3271
3272 this.edit_with_autoindent(edits, cx);
3273 let buffer = this.buffer.read(cx).snapshot(cx);
3274 let new_selections = selection_fixup_info
3275 .into_iter()
3276 .map(|(extra_newline_inserted, new_selection)| {
3277 let mut cursor = new_selection.end.to_point(&buffer);
3278 if extra_newline_inserted {
3279 cursor.row -= 1;
3280 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3281 }
3282 new_selection.map(|_| cursor)
3283 })
3284 .collect();
3285
3286 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3287 s.select(new_selections)
3288 });
3289 this.refresh_inline_completion(true, false, window, cx);
3290 });
3291 }
3292
3293 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3294 let buffer = self.buffer.read(cx);
3295 let snapshot = buffer.snapshot(cx);
3296
3297 let mut edits = Vec::new();
3298 let mut rows = Vec::new();
3299
3300 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3301 let cursor = selection.head();
3302 let row = cursor.row;
3303
3304 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3305
3306 let newline = "\n".to_string();
3307 edits.push((start_of_line..start_of_line, newline));
3308
3309 rows.push(row + rows_inserted as u32);
3310 }
3311
3312 self.transact(window, cx, |editor, window, cx| {
3313 editor.edit(edits, cx);
3314
3315 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3316 let mut index = 0;
3317 s.move_cursors_with(|map, _, _| {
3318 let row = rows[index];
3319 index += 1;
3320
3321 let point = Point::new(row, 0);
3322 let boundary = map.next_line_boundary(point).1;
3323 let clipped = map.clip_point(boundary, Bias::Left);
3324
3325 (clipped, SelectionGoal::None)
3326 });
3327 });
3328
3329 let mut indent_edits = Vec::new();
3330 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3331 for row in rows {
3332 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3333 for (row, indent) in indents {
3334 if indent.len == 0 {
3335 continue;
3336 }
3337
3338 let text = match indent.kind {
3339 IndentKind::Space => " ".repeat(indent.len as usize),
3340 IndentKind::Tab => "\t".repeat(indent.len as usize),
3341 };
3342 let point = Point::new(row.0, 0);
3343 indent_edits.push((point..point, text));
3344 }
3345 }
3346 editor.edit(indent_edits, cx);
3347 });
3348 }
3349
3350 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3351 let buffer = self.buffer.read(cx);
3352 let snapshot = buffer.snapshot(cx);
3353
3354 let mut edits = Vec::new();
3355 let mut rows = Vec::new();
3356 let mut rows_inserted = 0;
3357
3358 for selection in self.selections.all_adjusted(cx) {
3359 let cursor = selection.head();
3360 let row = cursor.row;
3361
3362 let point = Point::new(row + 1, 0);
3363 let start_of_line = snapshot.clip_point(point, Bias::Left);
3364
3365 let newline = "\n".to_string();
3366 edits.push((start_of_line..start_of_line, newline));
3367
3368 rows_inserted += 1;
3369 rows.push(row + rows_inserted);
3370 }
3371
3372 self.transact(window, cx, |editor, window, cx| {
3373 editor.edit(edits, cx);
3374
3375 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3376 let mut index = 0;
3377 s.move_cursors_with(|map, _, _| {
3378 let row = rows[index];
3379 index += 1;
3380
3381 let point = Point::new(row, 0);
3382 let boundary = map.next_line_boundary(point).1;
3383 let clipped = map.clip_point(boundary, Bias::Left);
3384
3385 (clipped, SelectionGoal::None)
3386 });
3387 });
3388
3389 let mut indent_edits = Vec::new();
3390 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3391 for row in rows {
3392 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3393 for (row, indent) in indents {
3394 if indent.len == 0 {
3395 continue;
3396 }
3397
3398 let text = match indent.kind {
3399 IndentKind::Space => " ".repeat(indent.len as usize),
3400 IndentKind::Tab => "\t".repeat(indent.len as usize),
3401 };
3402 let point = Point::new(row.0, 0);
3403 indent_edits.push((point..point, text));
3404 }
3405 }
3406 editor.edit(indent_edits, cx);
3407 });
3408 }
3409
3410 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3411 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3412 original_indent_columns: Vec::new(),
3413 });
3414 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3415 }
3416
3417 fn insert_with_autoindent_mode(
3418 &mut self,
3419 text: &str,
3420 autoindent_mode: Option<AutoindentMode>,
3421 window: &mut Window,
3422 cx: &mut Context<Self>,
3423 ) {
3424 if self.read_only(cx) {
3425 return;
3426 }
3427
3428 let text: Arc<str> = text.into();
3429 self.transact(window, cx, |this, window, cx| {
3430 let old_selections = this.selections.all_adjusted(cx);
3431 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3432 let anchors = {
3433 let snapshot = buffer.read(cx);
3434 old_selections
3435 .iter()
3436 .map(|s| {
3437 let anchor = snapshot.anchor_after(s.head());
3438 s.map(|_| anchor)
3439 })
3440 .collect::<Vec<_>>()
3441 };
3442 buffer.edit(
3443 old_selections
3444 .iter()
3445 .map(|s| (s.start..s.end, text.clone())),
3446 autoindent_mode,
3447 cx,
3448 );
3449 anchors
3450 });
3451
3452 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3453 s.select_anchors(selection_anchors);
3454 });
3455
3456 cx.notify();
3457 });
3458 }
3459
3460 fn trigger_completion_on_input(
3461 &mut self,
3462 text: &str,
3463 trigger_in_words: bool,
3464 window: &mut Window,
3465 cx: &mut Context<Self>,
3466 ) {
3467 if self.is_completion_trigger(text, trigger_in_words, cx) {
3468 self.show_completions(
3469 &ShowCompletions {
3470 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3471 },
3472 window,
3473 cx,
3474 );
3475 } else {
3476 self.hide_context_menu(window, cx);
3477 }
3478 }
3479
3480 fn is_completion_trigger(
3481 &self,
3482 text: &str,
3483 trigger_in_words: bool,
3484 cx: &mut Context<Self>,
3485 ) -> bool {
3486 let position = self.selections.newest_anchor().head();
3487 let multibuffer = self.buffer.read(cx);
3488 let Some(buffer) = position
3489 .buffer_id
3490 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3491 else {
3492 return false;
3493 };
3494
3495 if let Some(completion_provider) = &self.completion_provider {
3496 completion_provider.is_completion_trigger(
3497 &buffer,
3498 position.text_anchor,
3499 text,
3500 trigger_in_words,
3501 cx,
3502 )
3503 } else {
3504 false
3505 }
3506 }
3507
3508 /// If any empty selections is touching the start of its innermost containing autoclose
3509 /// region, expand it to select the brackets.
3510 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3511 let selections = self.selections.all::<usize>(cx);
3512 let buffer = self.buffer.read(cx).read(cx);
3513 let new_selections = self
3514 .selections_with_autoclose_regions(selections, &buffer)
3515 .map(|(mut selection, region)| {
3516 if !selection.is_empty() {
3517 return selection;
3518 }
3519
3520 if let Some(region) = region {
3521 let mut range = region.range.to_offset(&buffer);
3522 if selection.start == range.start && range.start >= region.pair.start.len() {
3523 range.start -= region.pair.start.len();
3524 if buffer.contains_str_at(range.start, ®ion.pair.start)
3525 && buffer.contains_str_at(range.end, ®ion.pair.end)
3526 {
3527 range.end += region.pair.end.len();
3528 selection.start = range.start;
3529 selection.end = range.end;
3530
3531 return selection;
3532 }
3533 }
3534 }
3535
3536 let always_treat_brackets_as_autoclosed = buffer
3537 .settings_at(selection.start, cx)
3538 .always_treat_brackets_as_autoclosed;
3539
3540 if !always_treat_brackets_as_autoclosed {
3541 return selection;
3542 }
3543
3544 if let Some(scope) = buffer.language_scope_at(selection.start) {
3545 for (pair, enabled) in scope.brackets() {
3546 if !enabled || !pair.close {
3547 continue;
3548 }
3549
3550 if buffer.contains_str_at(selection.start, &pair.end) {
3551 let pair_start_len = pair.start.len();
3552 if buffer.contains_str_at(
3553 selection.start.saturating_sub(pair_start_len),
3554 &pair.start,
3555 ) {
3556 selection.start -= pair_start_len;
3557 selection.end += pair.end.len();
3558
3559 return selection;
3560 }
3561 }
3562 }
3563 }
3564
3565 selection
3566 })
3567 .collect();
3568
3569 drop(buffer);
3570 self.change_selections(None, window, cx, |selections| {
3571 selections.select(new_selections)
3572 });
3573 }
3574
3575 /// Iterate the given selections, and for each one, find the smallest surrounding
3576 /// autoclose region. This uses the ordering of the selections and the autoclose
3577 /// regions to avoid repeated comparisons.
3578 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3579 &'a self,
3580 selections: impl IntoIterator<Item = Selection<D>>,
3581 buffer: &'a MultiBufferSnapshot,
3582 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3583 let mut i = 0;
3584 let mut regions = self.autoclose_regions.as_slice();
3585 selections.into_iter().map(move |selection| {
3586 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3587
3588 let mut enclosing = None;
3589 while let Some(pair_state) = regions.get(i) {
3590 if pair_state.range.end.to_offset(buffer) < range.start {
3591 regions = ®ions[i + 1..];
3592 i = 0;
3593 } else if pair_state.range.start.to_offset(buffer) > range.end {
3594 break;
3595 } else {
3596 if pair_state.selection_id == selection.id {
3597 enclosing = Some(pair_state);
3598 }
3599 i += 1;
3600 }
3601 }
3602
3603 (selection, enclosing)
3604 })
3605 }
3606
3607 /// Remove any autoclose regions that no longer contain their selection.
3608 fn invalidate_autoclose_regions(
3609 &mut self,
3610 mut selections: &[Selection<Anchor>],
3611 buffer: &MultiBufferSnapshot,
3612 ) {
3613 self.autoclose_regions.retain(|state| {
3614 let mut i = 0;
3615 while let Some(selection) = selections.get(i) {
3616 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3617 selections = &selections[1..];
3618 continue;
3619 }
3620 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3621 break;
3622 }
3623 if selection.id == state.selection_id {
3624 return true;
3625 } else {
3626 i += 1;
3627 }
3628 }
3629 false
3630 });
3631 }
3632
3633 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3634 let offset = position.to_offset(buffer);
3635 let (word_range, kind) = buffer.surrounding_word(offset, true);
3636 if offset > word_range.start && kind == Some(CharKind::Word) {
3637 Some(
3638 buffer
3639 .text_for_range(word_range.start..offset)
3640 .collect::<String>(),
3641 )
3642 } else {
3643 None
3644 }
3645 }
3646
3647 pub fn toggle_inlay_hints(
3648 &mut self,
3649 _: &ToggleInlayHints,
3650 _: &mut Window,
3651 cx: &mut Context<Self>,
3652 ) {
3653 self.refresh_inlay_hints(
3654 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3655 cx,
3656 );
3657 }
3658
3659 pub fn inlay_hints_enabled(&self) -> bool {
3660 self.inlay_hint_cache.enabled
3661 }
3662
3663 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3664 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3665 return;
3666 }
3667
3668 let reason_description = reason.description();
3669 let ignore_debounce = matches!(
3670 reason,
3671 InlayHintRefreshReason::SettingsChange(_)
3672 | InlayHintRefreshReason::Toggle(_)
3673 | InlayHintRefreshReason::ExcerptsRemoved(_)
3674 );
3675 let (invalidate_cache, required_languages) = match reason {
3676 InlayHintRefreshReason::Toggle(enabled) => {
3677 self.inlay_hint_cache.enabled = enabled;
3678 if enabled {
3679 (InvalidationStrategy::RefreshRequested, None)
3680 } else {
3681 self.inlay_hint_cache.clear();
3682 self.splice_inlays(
3683 &self
3684 .visible_inlay_hints(cx)
3685 .iter()
3686 .map(|inlay| inlay.id)
3687 .collect::<Vec<InlayId>>(),
3688 Vec::new(),
3689 cx,
3690 );
3691 return;
3692 }
3693 }
3694 InlayHintRefreshReason::SettingsChange(new_settings) => {
3695 match self.inlay_hint_cache.update_settings(
3696 &self.buffer,
3697 new_settings,
3698 self.visible_inlay_hints(cx),
3699 cx,
3700 ) {
3701 ControlFlow::Break(Some(InlaySplice {
3702 to_remove,
3703 to_insert,
3704 })) => {
3705 self.splice_inlays(&to_remove, to_insert, cx);
3706 return;
3707 }
3708 ControlFlow::Break(None) => return,
3709 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3710 }
3711 }
3712 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3713 if let Some(InlaySplice {
3714 to_remove,
3715 to_insert,
3716 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3717 {
3718 self.splice_inlays(&to_remove, to_insert, cx);
3719 }
3720 return;
3721 }
3722 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3723 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3724 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3725 }
3726 InlayHintRefreshReason::RefreshRequested => {
3727 (InvalidationStrategy::RefreshRequested, None)
3728 }
3729 };
3730
3731 if let Some(InlaySplice {
3732 to_remove,
3733 to_insert,
3734 }) = self.inlay_hint_cache.spawn_hint_refresh(
3735 reason_description,
3736 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3737 invalidate_cache,
3738 ignore_debounce,
3739 cx,
3740 ) {
3741 self.splice_inlays(&to_remove, to_insert, cx);
3742 }
3743 }
3744
3745 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3746 self.display_map
3747 .read(cx)
3748 .current_inlays()
3749 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3750 .cloned()
3751 .collect()
3752 }
3753
3754 pub fn excerpts_for_inlay_hints_query(
3755 &self,
3756 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3757 cx: &mut Context<Editor>,
3758 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3759 let Some(project) = self.project.as_ref() else {
3760 return HashMap::default();
3761 };
3762 let project = project.read(cx);
3763 let multi_buffer = self.buffer().read(cx);
3764 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3765 let multi_buffer_visible_start = self
3766 .scroll_manager
3767 .anchor()
3768 .anchor
3769 .to_point(&multi_buffer_snapshot);
3770 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3771 multi_buffer_visible_start
3772 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3773 Bias::Left,
3774 );
3775 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3776 multi_buffer_snapshot
3777 .range_to_buffer_ranges(multi_buffer_visible_range)
3778 .into_iter()
3779 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3780 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3781 let buffer_file = project::File::from_dyn(buffer.file())?;
3782 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3783 let worktree_entry = buffer_worktree
3784 .read(cx)
3785 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3786 if worktree_entry.is_ignored {
3787 return None;
3788 }
3789
3790 let language = buffer.language()?;
3791 if let Some(restrict_to_languages) = restrict_to_languages {
3792 if !restrict_to_languages.contains(language) {
3793 return None;
3794 }
3795 }
3796 Some((
3797 excerpt_id,
3798 (
3799 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3800 buffer.version().clone(),
3801 excerpt_visible_range,
3802 ),
3803 ))
3804 })
3805 .collect()
3806 }
3807
3808 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3809 TextLayoutDetails {
3810 text_system: window.text_system().clone(),
3811 editor_style: self.style.clone().unwrap(),
3812 rem_size: window.rem_size(),
3813 scroll_anchor: self.scroll_manager.anchor(),
3814 visible_rows: self.visible_line_count(),
3815 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3816 }
3817 }
3818
3819 pub fn splice_inlays(
3820 &self,
3821 to_remove: &[InlayId],
3822 to_insert: Vec<Inlay>,
3823 cx: &mut Context<Self>,
3824 ) {
3825 self.display_map.update(cx, |display_map, cx| {
3826 display_map.splice_inlays(to_remove, to_insert, cx)
3827 });
3828 cx.notify();
3829 }
3830
3831 fn trigger_on_type_formatting(
3832 &self,
3833 input: String,
3834 window: &mut Window,
3835 cx: &mut Context<Self>,
3836 ) -> Option<Task<Result<()>>> {
3837 if input.len() != 1 {
3838 return None;
3839 }
3840
3841 let project = self.project.as_ref()?;
3842 let position = self.selections.newest_anchor().head();
3843 let (buffer, buffer_position) = self
3844 .buffer
3845 .read(cx)
3846 .text_anchor_for_position(position, cx)?;
3847
3848 let settings = language_settings::language_settings(
3849 buffer
3850 .read(cx)
3851 .language_at(buffer_position)
3852 .map(|l| l.name()),
3853 buffer.read(cx).file(),
3854 cx,
3855 );
3856 if !settings.use_on_type_format {
3857 return None;
3858 }
3859
3860 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3861 // hence we do LSP request & edit on host side only — add formats to host's history.
3862 let push_to_lsp_host_history = true;
3863 // If this is not the host, append its history with new edits.
3864 let push_to_client_history = project.read(cx).is_via_collab();
3865
3866 let on_type_formatting = project.update(cx, |project, cx| {
3867 project.on_type_format(
3868 buffer.clone(),
3869 buffer_position,
3870 input,
3871 push_to_lsp_host_history,
3872 cx,
3873 )
3874 });
3875 Some(cx.spawn_in(window, |editor, mut cx| async move {
3876 if let Some(transaction) = on_type_formatting.await? {
3877 if push_to_client_history {
3878 buffer
3879 .update(&mut cx, |buffer, _| {
3880 buffer.push_transaction(transaction, Instant::now());
3881 })
3882 .ok();
3883 }
3884 editor.update(&mut cx, |editor, cx| {
3885 editor.refresh_document_highlights(cx);
3886 })?;
3887 }
3888 Ok(())
3889 }))
3890 }
3891
3892 pub fn show_completions(
3893 &mut self,
3894 options: &ShowCompletions,
3895 window: &mut Window,
3896 cx: &mut Context<Self>,
3897 ) {
3898 if self.pending_rename.is_some() {
3899 return;
3900 }
3901
3902 let Some(provider) = self.completion_provider.as_ref() else {
3903 return;
3904 };
3905
3906 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3907 return;
3908 }
3909
3910 let position = self.selections.newest_anchor().head();
3911 if position.diff_base_anchor.is_some() {
3912 return;
3913 }
3914 let (buffer, buffer_position) =
3915 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3916 output
3917 } else {
3918 return;
3919 };
3920 let show_completion_documentation = buffer
3921 .read(cx)
3922 .snapshot()
3923 .settings_at(buffer_position, cx)
3924 .show_completion_documentation;
3925
3926 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3927
3928 let trigger_kind = match &options.trigger {
3929 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3930 CompletionTriggerKind::TRIGGER_CHARACTER
3931 }
3932 _ => CompletionTriggerKind::INVOKED,
3933 };
3934 let completion_context = CompletionContext {
3935 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3936 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3937 Some(String::from(trigger))
3938 } else {
3939 None
3940 }
3941 }),
3942 trigger_kind,
3943 };
3944 let completions =
3945 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3946 let sort_completions = provider.sort_completions();
3947
3948 let id = post_inc(&mut self.next_completion_id);
3949 let task = cx.spawn_in(window, |editor, mut cx| {
3950 async move {
3951 editor.update(&mut cx, |this, _| {
3952 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3953 })?;
3954 let completions = completions.await.log_err();
3955 let menu = if let Some(completions) = completions {
3956 let mut menu = CompletionsMenu::new(
3957 id,
3958 sort_completions,
3959 show_completion_documentation,
3960 position,
3961 buffer.clone(),
3962 completions.into(),
3963 );
3964
3965 menu.filter(query.as_deref(), cx.background_executor().clone())
3966 .await;
3967
3968 menu.visible().then_some(menu)
3969 } else {
3970 None
3971 };
3972
3973 editor.update_in(&mut cx, |editor, window, cx| {
3974 match editor.context_menu.borrow().as_ref() {
3975 None => {}
3976 Some(CodeContextMenu::Completions(prev_menu)) => {
3977 if prev_menu.id > id {
3978 return;
3979 }
3980 }
3981 _ => return,
3982 }
3983
3984 if editor.focus_handle.is_focused(window) && menu.is_some() {
3985 let mut menu = menu.unwrap();
3986 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3987
3988 *editor.context_menu.borrow_mut() =
3989 Some(CodeContextMenu::Completions(menu));
3990
3991 if editor.show_edit_predictions_in_menu() {
3992 editor.update_visible_inline_completion(window, cx);
3993 } else {
3994 editor.discard_inline_completion(false, cx);
3995 }
3996
3997 cx.notify();
3998 } else if editor.completion_tasks.len() <= 1 {
3999 // If there are no more completion tasks and the last menu was
4000 // empty, we should hide it.
4001 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4002 // If it was already hidden and we don't show inline
4003 // completions in the menu, we should also show the
4004 // inline-completion when available.
4005 if was_hidden && editor.show_edit_predictions_in_menu() {
4006 editor.update_visible_inline_completion(window, cx);
4007 }
4008 }
4009 })?;
4010
4011 Ok::<_, anyhow::Error>(())
4012 }
4013 .log_err()
4014 });
4015
4016 self.completion_tasks.push((id, task));
4017 }
4018
4019 pub fn confirm_completion(
4020 &mut self,
4021 action: &ConfirmCompletion,
4022 window: &mut Window,
4023 cx: &mut Context<Self>,
4024 ) -> Option<Task<Result<()>>> {
4025 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4026 }
4027
4028 pub fn compose_completion(
4029 &mut self,
4030 action: &ComposeCompletion,
4031 window: &mut Window,
4032 cx: &mut Context<Self>,
4033 ) -> Option<Task<Result<()>>> {
4034 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4035 }
4036
4037 fn do_completion(
4038 &mut self,
4039 item_ix: Option<usize>,
4040 intent: CompletionIntent,
4041 window: &mut Window,
4042 cx: &mut Context<Editor>,
4043 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4044 use language::ToOffset as _;
4045
4046 let completions_menu =
4047 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4048 menu
4049 } else {
4050 return None;
4051 };
4052
4053 let entries = completions_menu.entries.borrow();
4054 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4055 if self.show_edit_predictions_in_menu() {
4056 self.discard_inline_completion(true, cx);
4057 }
4058 let candidate_id = mat.candidate_id;
4059 drop(entries);
4060
4061 let buffer_handle = completions_menu.buffer;
4062 let completion = completions_menu
4063 .completions
4064 .borrow()
4065 .get(candidate_id)?
4066 .clone();
4067 cx.stop_propagation();
4068
4069 let snippet;
4070 let text;
4071
4072 if completion.is_snippet() {
4073 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4074 text = snippet.as_ref().unwrap().text.clone();
4075 } else {
4076 snippet = None;
4077 text = completion.new_text.clone();
4078 };
4079 let selections = self.selections.all::<usize>(cx);
4080 let buffer = buffer_handle.read(cx);
4081 let old_range = completion.old_range.to_offset(buffer);
4082 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4083
4084 let newest_selection = self.selections.newest_anchor();
4085 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4086 return None;
4087 }
4088
4089 let lookbehind = newest_selection
4090 .start
4091 .text_anchor
4092 .to_offset(buffer)
4093 .saturating_sub(old_range.start);
4094 let lookahead = old_range
4095 .end
4096 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4097 let mut common_prefix_len = old_text
4098 .bytes()
4099 .zip(text.bytes())
4100 .take_while(|(a, b)| a == b)
4101 .count();
4102
4103 let snapshot = self.buffer.read(cx).snapshot(cx);
4104 let mut range_to_replace: Option<Range<isize>> = None;
4105 let mut ranges = Vec::new();
4106 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4107 for selection in &selections {
4108 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4109 let start = selection.start.saturating_sub(lookbehind);
4110 let end = selection.end + lookahead;
4111 if selection.id == newest_selection.id {
4112 range_to_replace = Some(
4113 ((start + common_prefix_len) as isize - selection.start as isize)
4114 ..(end as isize - selection.start as isize),
4115 );
4116 }
4117 ranges.push(start + common_prefix_len..end);
4118 } else {
4119 common_prefix_len = 0;
4120 ranges.clear();
4121 ranges.extend(selections.iter().map(|s| {
4122 if s.id == newest_selection.id {
4123 range_to_replace = Some(
4124 old_range.start.to_offset_utf16(&snapshot).0 as isize
4125 - selection.start as isize
4126 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4127 - selection.start as isize,
4128 );
4129 old_range.clone()
4130 } else {
4131 s.start..s.end
4132 }
4133 }));
4134 break;
4135 }
4136 if !self.linked_edit_ranges.is_empty() {
4137 let start_anchor = snapshot.anchor_before(selection.head());
4138 let end_anchor = snapshot.anchor_after(selection.tail());
4139 if let Some(ranges) = self
4140 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4141 {
4142 for (buffer, edits) in ranges {
4143 linked_edits.entry(buffer.clone()).or_default().extend(
4144 edits
4145 .into_iter()
4146 .map(|range| (range, text[common_prefix_len..].to_owned())),
4147 );
4148 }
4149 }
4150 }
4151 }
4152 let text = &text[common_prefix_len..];
4153
4154 cx.emit(EditorEvent::InputHandled {
4155 utf16_range_to_replace: range_to_replace,
4156 text: text.into(),
4157 });
4158
4159 self.transact(window, cx, |this, window, cx| {
4160 if let Some(mut snippet) = snippet {
4161 snippet.text = text.to_string();
4162 for tabstop in snippet
4163 .tabstops
4164 .iter_mut()
4165 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4166 {
4167 tabstop.start -= common_prefix_len as isize;
4168 tabstop.end -= common_prefix_len as isize;
4169 }
4170
4171 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4172 } else {
4173 this.buffer.update(cx, |buffer, cx| {
4174 buffer.edit(
4175 ranges.iter().map(|range| (range.clone(), text)),
4176 this.autoindent_mode.clone(),
4177 cx,
4178 );
4179 });
4180 }
4181 for (buffer, edits) in linked_edits {
4182 buffer.update(cx, |buffer, cx| {
4183 let snapshot = buffer.snapshot();
4184 let edits = edits
4185 .into_iter()
4186 .map(|(range, text)| {
4187 use text::ToPoint as TP;
4188 let end_point = TP::to_point(&range.end, &snapshot);
4189 let start_point = TP::to_point(&range.start, &snapshot);
4190 (start_point..end_point, text)
4191 })
4192 .sorted_by_key(|(range, _)| range.start)
4193 .collect::<Vec<_>>();
4194 buffer.edit(edits, None, cx);
4195 })
4196 }
4197
4198 this.refresh_inline_completion(true, false, window, cx);
4199 });
4200
4201 let show_new_completions_on_confirm = completion
4202 .confirm
4203 .as_ref()
4204 .map_or(false, |confirm| confirm(intent, window, cx));
4205 if show_new_completions_on_confirm {
4206 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4207 }
4208
4209 let provider = self.completion_provider.as_ref()?;
4210 drop(completion);
4211 let apply_edits = provider.apply_additional_edits_for_completion(
4212 buffer_handle,
4213 completions_menu.completions.clone(),
4214 candidate_id,
4215 true,
4216 cx,
4217 );
4218
4219 let editor_settings = EditorSettings::get_global(cx);
4220 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4221 // After the code completion is finished, users often want to know what signatures are needed.
4222 // so we should automatically call signature_help
4223 self.show_signature_help(&ShowSignatureHelp, window, cx);
4224 }
4225
4226 Some(cx.foreground_executor().spawn(async move {
4227 apply_edits.await?;
4228 Ok(())
4229 }))
4230 }
4231
4232 pub fn toggle_code_actions(
4233 &mut self,
4234 action: &ToggleCodeActions,
4235 window: &mut Window,
4236 cx: &mut Context<Self>,
4237 ) {
4238 let mut context_menu = self.context_menu.borrow_mut();
4239 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4240 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4241 // Toggle if we're selecting the same one
4242 *context_menu = None;
4243 cx.notify();
4244 return;
4245 } else {
4246 // Otherwise, clear it and start a new one
4247 *context_menu = None;
4248 cx.notify();
4249 }
4250 }
4251 drop(context_menu);
4252 let snapshot = self.snapshot(window, cx);
4253 let deployed_from_indicator = action.deployed_from_indicator;
4254 let mut task = self.code_actions_task.take();
4255 let action = action.clone();
4256 cx.spawn_in(window, |editor, mut cx| async move {
4257 while let Some(prev_task) = task {
4258 prev_task.await.log_err();
4259 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4260 }
4261
4262 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4263 if editor.focus_handle.is_focused(window) {
4264 let multibuffer_point = action
4265 .deployed_from_indicator
4266 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4267 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4268 let (buffer, buffer_row) = snapshot
4269 .buffer_snapshot
4270 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4271 .and_then(|(buffer_snapshot, range)| {
4272 editor
4273 .buffer
4274 .read(cx)
4275 .buffer(buffer_snapshot.remote_id())
4276 .map(|buffer| (buffer, range.start.row))
4277 })?;
4278 let (_, code_actions) = editor
4279 .available_code_actions
4280 .clone()
4281 .and_then(|(location, code_actions)| {
4282 let snapshot = location.buffer.read(cx).snapshot();
4283 let point_range = location.range.to_point(&snapshot);
4284 let point_range = point_range.start.row..=point_range.end.row;
4285 if point_range.contains(&buffer_row) {
4286 Some((location, code_actions))
4287 } else {
4288 None
4289 }
4290 })
4291 .unzip();
4292 let buffer_id = buffer.read(cx).remote_id();
4293 let tasks = editor
4294 .tasks
4295 .get(&(buffer_id, buffer_row))
4296 .map(|t| Arc::new(t.to_owned()));
4297 if tasks.is_none() && code_actions.is_none() {
4298 return None;
4299 }
4300
4301 editor.completion_tasks.clear();
4302 editor.discard_inline_completion(false, cx);
4303 let task_context =
4304 tasks
4305 .as_ref()
4306 .zip(editor.project.clone())
4307 .map(|(tasks, project)| {
4308 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4309 });
4310
4311 Some(cx.spawn_in(window, |editor, mut cx| async move {
4312 let task_context = match task_context {
4313 Some(task_context) => task_context.await,
4314 None => None,
4315 };
4316 let resolved_tasks =
4317 tasks.zip(task_context).map(|(tasks, task_context)| {
4318 Rc::new(ResolvedTasks {
4319 templates: tasks.resolve(&task_context).collect(),
4320 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4321 multibuffer_point.row,
4322 tasks.column,
4323 )),
4324 })
4325 });
4326 let spawn_straight_away = resolved_tasks
4327 .as_ref()
4328 .map_or(false, |tasks| tasks.templates.len() == 1)
4329 && code_actions
4330 .as_ref()
4331 .map_or(true, |actions| actions.is_empty());
4332 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4333 *editor.context_menu.borrow_mut() =
4334 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4335 buffer,
4336 actions: CodeActionContents {
4337 tasks: resolved_tasks,
4338 actions: code_actions,
4339 },
4340 selected_item: Default::default(),
4341 scroll_handle: UniformListScrollHandle::default(),
4342 deployed_from_indicator,
4343 }));
4344 if spawn_straight_away {
4345 if let Some(task) = editor.confirm_code_action(
4346 &ConfirmCodeAction { item_ix: Some(0) },
4347 window,
4348 cx,
4349 ) {
4350 cx.notify();
4351 return task;
4352 }
4353 }
4354 cx.notify();
4355 Task::ready(Ok(()))
4356 }) {
4357 task.await
4358 } else {
4359 Ok(())
4360 }
4361 }))
4362 } else {
4363 Some(Task::ready(Ok(())))
4364 }
4365 })?;
4366 if let Some(task) = spawned_test_task {
4367 task.await?;
4368 }
4369
4370 Ok::<_, anyhow::Error>(())
4371 })
4372 .detach_and_log_err(cx);
4373 }
4374
4375 pub fn confirm_code_action(
4376 &mut self,
4377 action: &ConfirmCodeAction,
4378 window: &mut Window,
4379 cx: &mut Context<Self>,
4380 ) -> Option<Task<Result<()>>> {
4381 let actions_menu =
4382 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4383 menu
4384 } else {
4385 return None;
4386 };
4387 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4388 let action = actions_menu.actions.get(action_ix)?;
4389 let title = action.label();
4390 let buffer = actions_menu.buffer;
4391 let workspace = self.workspace()?;
4392
4393 match action {
4394 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4395 workspace.update(cx, |workspace, cx| {
4396 workspace::tasks::schedule_resolved_task(
4397 workspace,
4398 task_source_kind,
4399 resolved_task,
4400 false,
4401 cx,
4402 );
4403
4404 Some(Task::ready(Ok(())))
4405 })
4406 }
4407 CodeActionsItem::CodeAction {
4408 excerpt_id,
4409 action,
4410 provider,
4411 } => {
4412 let apply_code_action =
4413 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4414 let workspace = workspace.downgrade();
4415 Some(cx.spawn_in(window, |editor, cx| async move {
4416 let project_transaction = apply_code_action.await?;
4417 Self::open_project_transaction(
4418 &editor,
4419 workspace,
4420 project_transaction,
4421 title,
4422 cx,
4423 )
4424 .await
4425 }))
4426 }
4427 }
4428 }
4429
4430 pub async fn open_project_transaction(
4431 this: &WeakEntity<Editor>,
4432 workspace: WeakEntity<Workspace>,
4433 transaction: ProjectTransaction,
4434 title: String,
4435 mut cx: AsyncWindowContext,
4436 ) -> Result<()> {
4437 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4438 cx.update(|_, cx| {
4439 entries.sort_unstable_by_key(|(buffer, _)| {
4440 buffer.read(cx).file().map(|f| f.path().clone())
4441 });
4442 })?;
4443
4444 // If the project transaction's edits are all contained within this editor, then
4445 // avoid opening a new editor to display them.
4446
4447 if let Some((buffer, transaction)) = entries.first() {
4448 if entries.len() == 1 {
4449 let excerpt = this.update(&mut cx, |editor, cx| {
4450 editor
4451 .buffer()
4452 .read(cx)
4453 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4454 })?;
4455 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4456 if excerpted_buffer == *buffer {
4457 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4458 let excerpt_range = excerpt_range.to_offset(buffer);
4459 buffer
4460 .edited_ranges_for_transaction::<usize>(transaction)
4461 .all(|range| {
4462 excerpt_range.start <= range.start
4463 && excerpt_range.end >= range.end
4464 })
4465 })?;
4466
4467 if all_edits_within_excerpt {
4468 return Ok(());
4469 }
4470 }
4471 }
4472 }
4473 } else {
4474 return Ok(());
4475 }
4476
4477 let mut ranges_to_highlight = Vec::new();
4478 let excerpt_buffer = cx.new(|cx| {
4479 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4480 for (buffer_handle, transaction) in &entries {
4481 let buffer = buffer_handle.read(cx);
4482 ranges_to_highlight.extend(
4483 multibuffer.push_excerpts_with_context_lines(
4484 buffer_handle.clone(),
4485 buffer
4486 .edited_ranges_for_transaction::<usize>(transaction)
4487 .collect(),
4488 DEFAULT_MULTIBUFFER_CONTEXT,
4489 cx,
4490 ),
4491 );
4492 }
4493 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4494 multibuffer
4495 })?;
4496
4497 workspace.update_in(&mut cx, |workspace, window, cx| {
4498 let project = workspace.project().clone();
4499 let editor = cx
4500 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4501 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4502 editor.update(cx, |editor, cx| {
4503 editor.highlight_background::<Self>(
4504 &ranges_to_highlight,
4505 |theme| theme.editor_highlighted_line_background,
4506 cx,
4507 );
4508 });
4509 })?;
4510
4511 Ok(())
4512 }
4513
4514 pub fn clear_code_action_providers(&mut self) {
4515 self.code_action_providers.clear();
4516 self.available_code_actions.take();
4517 }
4518
4519 pub fn add_code_action_provider(
4520 &mut self,
4521 provider: Rc<dyn CodeActionProvider>,
4522 window: &mut Window,
4523 cx: &mut Context<Self>,
4524 ) {
4525 if self
4526 .code_action_providers
4527 .iter()
4528 .any(|existing_provider| existing_provider.id() == provider.id())
4529 {
4530 return;
4531 }
4532
4533 self.code_action_providers.push(provider);
4534 self.refresh_code_actions(window, cx);
4535 }
4536
4537 pub fn remove_code_action_provider(
4538 &mut self,
4539 id: Arc<str>,
4540 window: &mut Window,
4541 cx: &mut Context<Self>,
4542 ) {
4543 self.code_action_providers
4544 .retain(|provider| provider.id() != id);
4545 self.refresh_code_actions(window, cx);
4546 }
4547
4548 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4549 let buffer = self.buffer.read(cx);
4550 let newest_selection = self.selections.newest_anchor().clone();
4551 if newest_selection.head().diff_base_anchor.is_some() {
4552 return None;
4553 }
4554 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4555 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4556 if start_buffer != end_buffer {
4557 return None;
4558 }
4559
4560 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4561 cx.background_executor()
4562 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4563 .await;
4564
4565 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4566 let providers = this.code_action_providers.clone();
4567 let tasks = this
4568 .code_action_providers
4569 .iter()
4570 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4571 .collect::<Vec<_>>();
4572 (providers, tasks)
4573 })?;
4574
4575 let mut actions = Vec::new();
4576 for (provider, provider_actions) in
4577 providers.into_iter().zip(future::join_all(tasks).await)
4578 {
4579 if let Some(provider_actions) = provider_actions.log_err() {
4580 actions.extend(provider_actions.into_iter().map(|action| {
4581 AvailableCodeAction {
4582 excerpt_id: newest_selection.start.excerpt_id,
4583 action,
4584 provider: provider.clone(),
4585 }
4586 }));
4587 }
4588 }
4589
4590 this.update(&mut cx, |this, cx| {
4591 this.available_code_actions = if actions.is_empty() {
4592 None
4593 } else {
4594 Some((
4595 Location {
4596 buffer: start_buffer,
4597 range: start..end,
4598 },
4599 actions.into(),
4600 ))
4601 };
4602 cx.notify();
4603 })
4604 }));
4605 None
4606 }
4607
4608 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4609 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4610 self.show_git_blame_inline = false;
4611
4612 self.show_git_blame_inline_delay_task =
4613 Some(cx.spawn_in(window, |this, mut cx| async move {
4614 cx.background_executor().timer(delay).await;
4615
4616 this.update(&mut cx, |this, cx| {
4617 this.show_git_blame_inline = true;
4618 cx.notify();
4619 })
4620 .log_err();
4621 }));
4622 }
4623 }
4624
4625 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4626 if self.pending_rename.is_some() {
4627 return None;
4628 }
4629
4630 let provider = self.semantics_provider.clone()?;
4631 let buffer = self.buffer.read(cx);
4632 let newest_selection = self.selections.newest_anchor().clone();
4633 let cursor_position = newest_selection.head();
4634 let (cursor_buffer, cursor_buffer_position) =
4635 buffer.text_anchor_for_position(cursor_position, cx)?;
4636 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4637 if cursor_buffer != tail_buffer {
4638 return None;
4639 }
4640 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4641 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4642 cx.background_executor()
4643 .timer(Duration::from_millis(debounce))
4644 .await;
4645
4646 let highlights = if let Some(highlights) = cx
4647 .update(|cx| {
4648 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4649 })
4650 .ok()
4651 .flatten()
4652 {
4653 highlights.await.log_err()
4654 } else {
4655 None
4656 };
4657
4658 if let Some(highlights) = highlights {
4659 this.update(&mut cx, |this, cx| {
4660 if this.pending_rename.is_some() {
4661 return;
4662 }
4663
4664 let buffer_id = cursor_position.buffer_id;
4665 let buffer = this.buffer.read(cx);
4666 if !buffer
4667 .text_anchor_for_position(cursor_position, cx)
4668 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4669 {
4670 return;
4671 }
4672
4673 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4674 let mut write_ranges = Vec::new();
4675 let mut read_ranges = Vec::new();
4676 for highlight in highlights {
4677 for (excerpt_id, excerpt_range) in
4678 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4679 {
4680 let start = highlight
4681 .range
4682 .start
4683 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4684 let end = highlight
4685 .range
4686 .end
4687 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4688 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4689 continue;
4690 }
4691
4692 let range = Anchor {
4693 buffer_id,
4694 excerpt_id,
4695 text_anchor: start,
4696 diff_base_anchor: None,
4697 }..Anchor {
4698 buffer_id,
4699 excerpt_id,
4700 text_anchor: end,
4701 diff_base_anchor: None,
4702 };
4703 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4704 write_ranges.push(range);
4705 } else {
4706 read_ranges.push(range);
4707 }
4708 }
4709 }
4710
4711 this.highlight_background::<DocumentHighlightRead>(
4712 &read_ranges,
4713 |theme| theme.editor_document_highlight_read_background,
4714 cx,
4715 );
4716 this.highlight_background::<DocumentHighlightWrite>(
4717 &write_ranges,
4718 |theme| theme.editor_document_highlight_write_background,
4719 cx,
4720 );
4721 cx.notify();
4722 })
4723 .log_err();
4724 }
4725 }));
4726 None
4727 }
4728
4729 pub fn refresh_selected_text_highlights(
4730 &mut self,
4731 window: &mut Window,
4732 cx: &mut Context<Editor>,
4733 ) {
4734 self.selection_highlight_task.take();
4735 if !EditorSettings::get_global(cx).selection_highlight {
4736 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4737 return;
4738 }
4739 if self.selections.count() != 1 || self.selections.line_mode {
4740 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4741 return;
4742 }
4743 let selection = self.selections.newest::<Point>(cx);
4744 if selection.is_empty() || selection.start.row != selection.end.row {
4745 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4746 return;
4747 }
4748 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4749 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4750 cx.background_executor()
4751 .timer(Duration::from_millis(debounce))
4752 .await;
4753 let Some(matches_task) = editor
4754 .read_with(&mut cx, |editor, cx| {
4755 let buffer = editor.buffer().read(cx).snapshot(cx);
4756 cx.background_executor().spawn(async move {
4757 let mut ranges = Vec::new();
4758 let buffer_ranges =
4759 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
4760 let query = buffer.text_for_range(selection.range()).collect::<String>();
4761 for range in buffer_ranges {
4762 for (search_buffer, search_range, excerpt_id) in
4763 buffer.range_to_buffer_ranges(range)
4764 {
4765 ranges.extend(
4766 project::search::SearchQuery::text(
4767 query.clone(),
4768 false,
4769 false,
4770 false,
4771 Default::default(),
4772 Default::default(),
4773 None,
4774 )
4775 .unwrap()
4776 .search(search_buffer, Some(search_range.clone()))
4777 .await
4778 .into_iter()
4779 .map(|match_range| {
4780 let start = search_buffer
4781 .anchor_after(search_range.start + match_range.start);
4782 let end = search_buffer
4783 .anchor_before(search_range.start + match_range.end);
4784 Anchor::range_in_buffer(
4785 excerpt_id,
4786 search_buffer.remote_id(),
4787 start..end,
4788 )
4789 }),
4790 );
4791 }
4792 }
4793 ranges
4794 })
4795 })
4796 .log_err()
4797 else {
4798 return;
4799 };
4800 let matches = matches_task.await;
4801 editor
4802 .update_in(&mut cx, |editor, _, cx| {
4803 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4804 if !matches.is_empty() {
4805 editor.highlight_background::<SelectedTextHighlight>(
4806 &matches,
4807 |theme| theme.editor_document_highlight_bracket_background,
4808 cx,
4809 )
4810 }
4811 })
4812 .log_err();
4813 }));
4814 }
4815
4816 pub fn refresh_inline_completion(
4817 &mut self,
4818 debounce: bool,
4819 user_requested: bool,
4820 window: &mut Window,
4821 cx: &mut Context<Self>,
4822 ) -> Option<()> {
4823 let provider = self.edit_prediction_provider()?;
4824 let cursor = self.selections.newest_anchor().head();
4825 let (buffer, cursor_buffer_position) =
4826 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4827
4828 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4829 self.discard_inline_completion(false, cx);
4830 return None;
4831 }
4832
4833 if !user_requested
4834 && (!self.should_show_edit_predictions()
4835 || !self.is_focused(window)
4836 || buffer.read(cx).is_empty())
4837 {
4838 self.discard_inline_completion(false, cx);
4839 return None;
4840 }
4841
4842 self.update_visible_inline_completion(window, cx);
4843 provider.refresh(
4844 self.project.clone(),
4845 buffer,
4846 cursor_buffer_position,
4847 debounce,
4848 cx,
4849 );
4850 Some(())
4851 }
4852
4853 fn show_edit_predictions_in_menu(&self) -> bool {
4854 match self.edit_prediction_settings {
4855 EditPredictionSettings::Disabled => false,
4856 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4857 }
4858 }
4859
4860 pub fn edit_predictions_enabled(&self) -> bool {
4861 match self.edit_prediction_settings {
4862 EditPredictionSettings::Disabled => false,
4863 EditPredictionSettings::Enabled { .. } => true,
4864 }
4865 }
4866
4867 fn edit_prediction_requires_modifier(&self) -> bool {
4868 match self.edit_prediction_settings {
4869 EditPredictionSettings::Disabled => false,
4870 EditPredictionSettings::Enabled {
4871 preview_requires_modifier,
4872 ..
4873 } => preview_requires_modifier,
4874 }
4875 }
4876
4877 fn edit_prediction_settings_at_position(
4878 &self,
4879 buffer: &Entity<Buffer>,
4880 buffer_position: language::Anchor,
4881 cx: &App,
4882 ) -> EditPredictionSettings {
4883 if self.mode != EditorMode::Full
4884 || !self.show_inline_completions_override.unwrap_or(true)
4885 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4886 {
4887 return EditPredictionSettings::Disabled;
4888 }
4889
4890 let buffer = buffer.read(cx);
4891
4892 let file = buffer.file();
4893
4894 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4895 return EditPredictionSettings::Disabled;
4896 };
4897
4898 let by_provider = matches!(
4899 self.menu_inline_completions_policy,
4900 MenuInlineCompletionsPolicy::ByProvider
4901 );
4902
4903 let show_in_menu = by_provider
4904 && self
4905 .edit_prediction_provider
4906 .as_ref()
4907 .map_or(false, |provider| {
4908 provider.provider.show_completions_in_menu()
4909 });
4910
4911 let preview_requires_modifier =
4912 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4913
4914 EditPredictionSettings::Enabled {
4915 show_in_menu,
4916 preview_requires_modifier,
4917 }
4918 }
4919
4920 fn should_show_edit_predictions(&self) -> bool {
4921 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4922 }
4923
4924 pub fn edit_prediction_preview_is_active(&self) -> bool {
4925 matches!(
4926 self.edit_prediction_preview,
4927 EditPredictionPreview::Active { .. }
4928 )
4929 }
4930
4931 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4932 let cursor = self.selections.newest_anchor().head();
4933 if let Some((buffer, cursor_position)) =
4934 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4935 {
4936 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4937 } else {
4938 false
4939 }
4940 }
4941
4942 fn inline_completions_enabled_in_buffer(
4943 &self,
4944 buffer: &Entity<Buffer>,
4945 buffer_position: language::Anchor,
4946 cx: &App,
4947 ) -> bool {
4948 maybe!({
4949 let provider = self.edit_prediction_provider()?;
4950 if !provider.is_enabled(&buffer, buffer_position, cx) {
4951 return Some(false);
4952 }
4953 let buffer = buffer.read(cx);
4954 let Some(file) = buffer.file() else {
4955 return Some(true);
4956 };
4957 let settings = all_language_settings(Some(file), cx);
4958 Some(settings.inline_completions_enabled_for_path(file.path()))
4959 })
4960 .unwrap_or(false)
4961 }
4962
4963 fn cycle_inline_completion(
4964 &mut self,
4965 direction: Direction,
4966 window: &mut Window,
4967 cx: &mut Context<Self>,
4968 ) -> Option<()> {
4969 let provider = self.edit_prediction_provider()?;
4970 let cursor = self.selections.newest_anchor().head();
4971 let (buffer, cursor_buffer_position) =
4972 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4973 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4974 return None;
4975 }
4976
4977 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4978 self.update_visible_inline_completion(window, cx);
4979
4980 Some(())
4981 }
4982
4983 pub fn show_inline_completion(
4984 &mut self,
4985 _: &ShowEditPrediction,
4986 window: &mut Window,
4987 cx: &mut Context<Self>,
4988 ) {
4989 if !self.has_active_inline_completion() {
4990 self.refresh_inline_completion(false, true, window, cx);
4991 return;
4992 }
4993
4994 self.update_visible_inline_completion(window, cx);
4995 }
4996
4997 pub fn display_cursor_names(
4998 &mut self,
4999 _: &DisplayCursorNames,
5000 window: &mut Window,
5001 cx: &mut Context<Self>,
5002 ) {
5003 self.show_cursor_names(window, cx);
5004 }
5005
5006 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5007 self.show_cursor_names = true;
5008 cx.notify();
5009 cx.spawn_in(window, |this, mut cx| async move {
5010 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5011 this.update(&mut cx, |this, cx| {
5012 this.show_cursor_names = false;
5013 cx.notify()
5014 })
5015 .ok()
5016 })
5017 .detach();
5018 }
5019
5020 pub fn next_edit_prediction(
5021 &mut self,
5022 _: &NextEditPrediction,
5023 window: &mut Window,
5024 cx: &mut Context<Self>,
5025 ) {
5026 if self.has_active_inline_completion() {
5027 self.cycle_inline_completion(Direction::Next, window, cx);
5028 } else {
5029 let is_copilot_disabled = self
5030 .refresh_inline_completion(false, true, window, cx)
5031 .is_none();
5032 if is_copilot_disabled {
5033 cx.propagate();
5034 }
5035 }
5036 }
5037
5038 pub fn previous_edit_prediction(
5039 &mut self,
5040 _: &PreviousEditPrediction,
5041 window: &mut Window,
5042 cx: &mut Context<Self>,
5043 ) {
5044 if self.has_active_inline_completion() {
5045 self.cycle_inline_completion(Direction::Prev, window, cx);
5046 } else {
5047 let is_copilot_disabled = self
5048 .refresh_inline_completion(false, true, window, cx)
5049 .is_none();
5050 if is_copilot_disabled {
5051 cx.propagate();
5052 }
5053 }
5054 }
5055
5056 pub fn accept_edit_prediction(
5057 &mut self,
5058 _: &AcceptEditPrediction,
5059 window: &mut Window,
5060 cx: &mut Context<Self>,
5061 ) {
5062 if self.show_edit_predictions_in_menu() {
5063 self.hide_context_menu(window, cx);
5064 }
5065
5066 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5067 return;
5068 };
5069
5070 self.report_inline_completion_event(
5071 active_inline_completion.completion_id.clone(),
5072 true,
5073 cx,
5074 );
5075
5076 match &active_inline_completion.completion {
5077 InlineCompletion::Move { target, .. } => {
5078 let target = *target;
5079
5080 if let Some(position_map) = &self.last_position_map {
5081 if position_map
5082 .visible_row_range
5083 .contains(&target.to_display_point(&position_map.snapshot).row())
5084 || !self.edit_prediction_requires_modifier()
5085 {
5086 // Note that this is also done in vim's handler of the Tab action.
5087 self.change_selections(
5088 Some(Autoscroll::newest()),
5089 window,
5090 cx,
5091 |selections| {
5092 selections.select_anchor_ranges([target..target]);
5093 },
5094 );
5095 self.clear_row_highlights::<EditPredictionPreview>();
5096
5097 self.edit_prediction_preview = EditPredictionPreview::Active {
5098 previous_scroll_position: None,
5099 };
5100 } else {
5101 self.edit_prediction_preview = EditPredictionPreview::Active {
5102 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5103 };
5104 self.highlight_rows::<EditPredictionPreview>(
5105 target..target,
5106 cx.theme().colors().editor_highlighted_line_background,
5107 true,
5108 cx,
5109 );
5110 self.request_autoscroll(Autoscroll::fit(), cx);
5111 }
5112 }
5113 }
5114 InlineCompletion::Edit { edits, .. } => {
5115 if let Some(provider) = self.edit_prediction_provider() {
5116 provider.accept(cx);
5117 }
5118
5119 let snapshot = self.buffer.read(cx).snapshot(cx);
5120 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5121
5122 self.buffer.update(cx, |buffer, cx| {
5123 buffer.edit(edits.iter().cloned(), None, cx)
5124 });
5125
5126 self.change_selections(None, window, cx, |s| {
5127 s.select_anchor_ranges([last_edit_end..last_edit_end])
5128 });
5129
5130 self.update_visible_inline_completion(window, cx);
5131 if self.active_inline_completion.is_none() {
5132 self.refresh_inline_completion(true, true, window, cx);
5133 }
5134
5135 cx.notify();
5136 }
5137 }
5138
5139 self.edit_prediction_requires_modifier_in_leading_space = false;
5140 }
5141
5142 pub fn accept_partial_inline_completion(
5143 &mut self,
5144 _: &AcceptPartialEditPrediction,
5145 window: &mut Window,
5146 cx: &mut Context<Self>,
5147 ) {
5148 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5149 return;
5150 };
5151 if self.selections.count() != 1 {
5152 return;
5153 }
5154
5155 self.report_inline_completion_event(
5156 active_inline_completion.completion_id.clone(),
5157 true,
5158 cx,
5159 );
5160
5161 match &active_inline_completion.completion {
5162 InlineCompletion::Move { target, .. } => {
5163 let target = *target;
5164 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5165 selections.select_anchor_ranges([target..target]);
5166 });
5167 }
5168 InlineCompletion::Edit { edits, .. } => {
5169 // Find an insertion that starts at the cursor position.
5170 let snapshot = self.buffer.read(cx).snapshot(cx);
5171 let cursor_offset = self.selections.newest::<usize>(cx).head();
5172 let insertion = edits.iter().find_map(|(range, text)| {
5173 let range = range.to_offset(&snapshot);
5174 if range.is_empty() && range.start == cursor_offset {
5175 Some(text)
5176 } else {
5177 None
5178 }
5179 });
5180
5181 if let Some(text) = insertion {
5182 let mut partial_completion = text
5183 .chars()
5184 .by_ref()
5185 .take_while(|c| c.is_alphabetic())
5186 .collect::<String>();
5187 if partial_completion.is_empty() {
5188 partial_completion = text
5189 .chars()
5190 .by_ref()
5191 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5192 .collect::<String>();
5193 }
5194
5195 cx.emit(EditorEvent::InputHandled {
5196 utf16_range_to_replace: None,
5197 text: partial_completion.clone().into(),
5198 });
5199
5200 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5201
5202 self.refresh_inline_completion(true, true, window, cx);
5203 cx.notify();
5204 } else {
5205 self.accept_edit_prediction(&Default::default(), window, cx);
5206 }
5207 }
5208 }
5209 }
5210
5211 fn discard_inline_completion(
5212 &mut self,
5213 should_report_inline_completion_event: bool,
5214 cx: &mut Context<Self>,
5215 ) -> bool {
5216 if should_report_inline_completion_event {
5217 let completion_id = self
5218 .active_inline_completion
5219 .as_ref()
5220 .and_then(|active_completion| active_completion.completion_id.clone());
5221
5222 self.report_inline_completion_event(completion_id, false, cx);
5223 }
5224
5225 if let Some(provider) = self.edit_prediction_provider() {
5226 provider.discard(cx);
5227 }
5228
5229 self.take_active_inline_completion(cx)
5230 }
5231
5232 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5233 let Some(provider) = self.edit_prediction_provider() else {
5234 return;
5235 };
5236
5237 let Some((_, buffer, _)) = self
5238 .buffer
5239 .read(cx)
5240 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5241 else {
5242 return;
5243 };
5244
5245 let extension = buffer
5246 .read(cx)
5247 .file()
5248 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5249
5250 let event_type = match accepted {
5251 true => "Edit Prediction Accepted",
5252 false => "Edit Prediction Discarded",
5253 };
5254 telemetry::event!(
5255 event_type,
5256 provider = provider.name(),
5257 prediction_id = id,
5258 suggestion_accepted = accepted,
5259 file_extension = extension,
5260 );
5261 }
5262
5263 pub fn has_active_inline_completion(&self) -> bool {
5264 self.active_inline_completion.is_some()
5265 }
5266
5267 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5268 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5269 return false;
5270 };
5271
5272 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5273 self.clear_highlights::<InlineCompletionHighlight>(cx);
5274 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5275 true
5276 }
5277
5278 /// Returns true when we're displaying the edit prediction popover below the cursor
5279 /// like we are not previewing and the LSP autocomplete menu is visible
5280 /// or we are in `when_holding_modifier` mode.
5281 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5282 if self.edit_prediction_preview_is_active()
5283 || !self.show_edit_predictions_in_menu()
5284 || !self.edit_predictions_enabled()
5285 {
5286 return false;
5287 }
5288
5289 if self.has_visible_completions_menu() {
5290 return true;
5291 }
5292
5293 has_completion && self.edit_prediction_requires_modifier()
5294 }
5295
5296 fn handle_modifiers_changed(
5297 &mut self,
5298 modifiers: Modifiers,
5299 position_map: &PositionMap,
5300 window: &mut Window,
5301 cx: &mut Context<Self>,
5302 ) {
5303 if self.show_edit_predictions_in_menu() {
5304 self.update_edit_prediction_preview(&modifiers, window, cx);
5305 }
5306
5307 let mouse_position = window.mouse_position();
5308 if !position_map.text_hitbox.is_hovered(window) {
5309 return;
5310 }
5311
5312 self.update_hovered_link(
5313 position_map.point_for_position(mouse_position),
5314 &position_map.snapshot,
5315 modifiers,
5316 window,
5317 cx,
5318 )
5319 }
5320
5321 fn update_edit_prediction_preview(
5322 &mut self,
5323 modifiers: &Modifiers,
5324 window: &mut Window,
5325 cx: &mut Context<Self>,
5326 ) {
5327 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5328 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5329 return;
5330 };
5331
5332 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5333 if matches!(
5334 self.edit_prediction_preview,
5335 EditPredictionPreview::Inactive
5336 ) {
5337 self.edit_prediction_preview = EditPredictionPreview::Active {
5338 previous_scroll_position: None,
5339 };
5340
5341 self.update_visible_inline_completion(window, cx);
5342 cx.notify();
5343 }
5344 } else if let EditPredictionPreview::Active {
5345 previous_scroll_position,
5346 } = self.edit_prediction_preview
5347 {
5348 if let (Some(previous_scroll_position), Some(position_map)) =
5349 (previous_scroll_position, self.last_position_map.as_ref())
5350 {
5351 self.set_scroll_position(
5352 previous_scroll_position
5353 .scroll_position(&position_map.snapshot.display_snapshot),
5354 window,
5355 cx,
5356 );
5357 }
5358
5359 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5360 self.clear_row_highlights::<EditPredictionPreview>();
5361 self.update_visible_inline_completion(window, cx);
5362 cx.notify();
5363 }
5364 }
5365
5366 fn update_visible_inline_completion(
5367 &mut self,
5368 _window: &mut Window,
5369 cx: &mut Context<Self>,
5370 ) -> Option<()> {
5371 let selection = self.selections.newest_anchor();
5372 let cursor = selection.head();
5373 let multibuffer = self.buffer.read(cx).snapshot(cx);
5374 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5375 let excerpt_id = cursor.excerpt_id;
5376
5377 let show_in_menu = self.show_edit_predictions_in_menu();
5378 let completions_menu_has_precedence = !show_in_menu
5379 && (self.context_menu.borrow().is_some()
5380 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5381
5382 if completions_menu_has_precedence
5383 || !offset_selection.is_empty()
5384 || self
5385 .active_inline_completion
5386 .as_ref()
5387 .map_or(false, |completion| {
5388 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5389 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5390 !invalidation_range.contains(&offset_selection.head())
5391 })
5392 {
5393 self.discard_inline_completion(false, cx);
5394 return None;
5395 }
5396
5397 self.take_active_inline_completion(cx);
5398 let Some(provider) = self.edit_prediction_provider() else {
5399 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5400 return None;
5401 };
5402
5403 let (buffer, cursor_buffer_position) =
5404 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5405
5406 self.edit_prediction_settings =
5407 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5408
5409 self.edit_prediction_cursor_on_leading_whitespace =
5410 multibuffer.is_line_whitespace_upto(cursor);
5411
5412 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5413 let edits = inline_completion
5414 .edits
5415 .into_iter()
5416 .flat_map(|(range, new_text)| {
5417 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5418 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5419 Some((start..end, new_text))
5420 })
5421 .collect::<Vec<_>>();
5422 if edits.is_empty() {
5423 return None;
5424 }
5425
5426 let first_edit_start = edits.first().unwrap().0.start;
5427 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5428 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5429
5430 let last_edit_end = edits.last().unwrap().0.end;
5431 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5432 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5433
5434 let cursor_row = cursor.to_point(&multibuffer).row;
5435
5436 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5437
5438 let mut inlay_ids = Vec::new();
5439 let invalidation_row_range;
5440 let move_invalidation_row_range = if cursor_row < edit_start_row {
5441 Some(cursor_row..edit_end_row)
5442 } else if cursor_row > edit_end_row {
5443 Some(edit_start_row..cursor_row)
5444 } else {
5445 None
5446 };
5447 let is_move =
5448 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5449 let completion = if is_move {
5450 invalidation_row_range =
5451 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5452 let target = first_edit_start;
5453 InlineCompletion::Move { target, snapshot }
5454 } else {
5455 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5456 && !self.inline_completions_hidden_for_vim_mode;
5457
5458 if show_completions_in_buffer {
5459 if edits
5460 .iter()
5461 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5462 {
5463 let mut inlays = Vec::new();
5464 for (range, new_text) in &edits {
5465 let inlay = Inlay::inline_completion(
5466 post_inc(&mut self.next_inlay_id),
5467 range.start,
5468 new_text.as_str(),
5469 );
5470 inlay_ids.push(inlay.id);
5471 inlays.push(inlay);
5472 }
5473
5474 self.splice_inlays(&[], inlays, cx);
5475 } else {
5476 let background_color = cx.theme().status().deleted_background;
5477 self.highlight_text::<InlineCompletionHighlight>(
5478 edits.iter().map(|(range, _)| range.clone()).collect(),
5479 HighlightStyle {
5480 background_color: Some(background_color),
5481 ..Default::default()
5482 },
5483 cx,
5484 );
5485 }
5486 }
5487
5488 invalidation_row_range = edit_start_row..edit_end_row;
5489
5490 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5491 if provider.show_tab_accept_marker() {
5492 EditDisplayMode::TabAccept
5493 } else {
5494 EditDisplayMode::Inline
5495 }
5496 } else {
5497 EditDisplayMode::DiffPopover
5498 };
5499
5500 InlineCompletion::Edit {
5501 edits,
5502 edit_preview: inline_completion.edit_preview,
5503 display_mode,
5504 snapshot,
5505 }
5506 };
5507
5508 let invalidation_range = multibuffer
5509 .anchor_before(Point::new(invalidation_row_range.start, 0))
5510 ..multibuffer.anchor_after(Point::new(
5511 invalidation_row_range.end,
5512 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5513 ));
5514
5515 self.stale_inline_completion_in_menu = None;
5516 self.active_inline_completion = Some(InlineCompletionState {
5517 inlay_ids,
5518 completion,
5519 completion_id: inline_completion.id,
5520 invalidation_range,
5521 });
5522
5523 cx.notify();
5524
5525 Some(())
5526 }
5527
5528 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5529 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5530 }
5531
5532 fn render_code_actions_indicator(
5533 &self,
5534 _style: &EditorStyle,
5535 row: DisplayRow,
5536 is_active: bool,
5537 cx: &mut Context<Self>,
5538 ) -> Option<IconButton> {
5539 if self.available_code_actions.is_some() {
5540 Some(
5541 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5542 .shape(ui::IconButtonShape::Square)
5543 .icon_size(IconSize::XSmall)
5544 .icon_color(Color::Muted)
5545 .toggle_state(is_active)
5546 .tooltip({
5547 let focus_handle = self.focus_handle.clone();
5548 move |window, cx| {
5549 Tooltip::for_action_in(
5550 "Toggle Code Actions",
5551 &ToggleCodeActions {
5552 deployed_from_indicator: None,
5553 },
5554 &focus_handle,
5555 window,
5556 cx,
5557 )
5558 }
5559 })
5560 .on_click(cx.listener(move |editor, _e, window, cx| {
5561 window.focus(&editor.focus_handle(cx));
5562 editor.toggle_code_actions(
5563 &ToggleCodeActions {
5564 deployed_from_indicator: Some(row),
5565 },
5566 window,
5567 cx,
5568 );
5569 })),
5570 )
5571 } else {
5572 None
5573 }
5574 }
5575
5576 fn clear_tasks(&mut self) {
5577 self.tasks.clear()
5578 }
5579
5580 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5581 if self.tasks.insert(key, value).is_some() {
5582 // This case should hopefully be rare, but just in case...
5583 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5584 }
5585 }
5586
5587 fn build_tasks_context(
5588 project: &Entity<Project>,
5589 buffer: &Entity<Buffer>,
5590 buffer_row: u32,
5591 tasks: &Arc<RunnableTasks>,
5592 cx: &mut Context<Self>,
5593 ) -> Task<Option<task::TaskContext>> {
5594 let position = Point::new(buffer_row, tasks.column);
5595 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5596 let location = Location {
5597 buffer: buffer.clone(),
5598 range: range_start..range_start,
5599 };
5600 // Fill in the environmental variables from the tree-sitter captures
5601 let mut captured_task_variables = TaskVariables::default();
5602 for (capture_name, value) in tasks.extra_variables.clone() {
5603 captured_task_variables.insert(
5604 task::VariableName::Custom(capture_name.into()),
5605 value.clone(),
5606 );
5607 }
5608 project.update(cx, |project, cx| {
5609 project.task_store().update(cx, |task_store, cx| {
5610 task_store.task_context_for_location(captured_task_variables, location, cx)
5611 })
5612 })
5613 }
5614
5615 pub fn spawn_nearest_task(
5616 &mut self,
5617 action: &SpawnNearestTask,
5618 window: &mut Window,
5619 cx: &mut Context<Self>,
5620 ) {
5621 let Some((workspace, _)) = self.workspace.clone() else {
5622 return;
5623 };
5624 let Some(project) = self.project.clone() else {
5625 return;
5626 };
5627
5628 // Try to find a closest, enclosing node using tree-sitter that has a
5629 // task
5630 let Some((buffer, buffer_row, tasks)) = self
5631 .find_enclosing_node_task(cx)
5632 // Or find the task that's closest in row-distance.
5633 .or_else(|| self.find_closest_task(cx))
5634 else {
5635 return;
5636 };
5637
5638 let reveal_strategy = action.reveal;
5639 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5640 cx.spawn_in(window, |_, mut cx| async move {
5641 let context = task_context.await?;
5642 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5643
5644 let resolved = resolved_task.resolved.as_mut()?;
5645 resolved.reveal = reveal_strategy;
5646
5647 workspace
5648 .update(&mut cx, |workspace, cx| {
5649 workspace::tasks::schedule_resolved_task(
5650 workspace,
5651 task_source_kind,
5652 resolved_task,
5653 false,
5654 cx,
5655 );
5656 })
5657 .ok()
5658 })
5659 .detach();
5660 }
5661
5662 fn find_closest_task(
5663 &mut self,
5664 cx: &mut Context<Self>,
5665 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5666 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5667
5668 let ((buffer_id, row), tasks) = self
5669 .tasks
5670 .iter()
5671 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5672
5673 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5674 let tasks = Arc::new(tasks.to_owned());
5675 Some((buffer, *row, tasks))
5676 }
5677
5678 fn find_enclosing_node_task(
5679 &mut self,
5680 cx: &mut Context<Self>,
5681 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5682 let snapshot = self.buffer.read(cx).snapshot(cx);
5683 let offset = self.selections.newest::<usize>(cx).head();
5684 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5685 let buffer_id = excerpt.buffer().remote_id();
5686
5687 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5688 let mut cursor = layer.node().walk();
5689
5690 while cursor.goto_first_child_for_byte(offset).is_some() {
5691 if cursor.node().end_byte() == offset {
5692 cursor.goto_next_sibling();
5693 }
5694 }
5695
5696 // Ascend to the smallest ancestor that contains the range and has a task.
5697 loop {
5698 let node = cursor.node();
5699 let node_range = node.byte_range();
5700 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5701
5702 // Check if this node contains our offset
5703 if node_range.start <= offset && node_range.end >= offset {
5704 // If it contains offset, check for task
5705 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5706 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5707 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5708 }
5709 }
5710
5711 if !cursor.goto_parent() {
5712 break;
5713 }
5714 }
5715 None
5716 }
5717
5718 fn render_run_indicator(
5719 &self,
5720 _style: &EditorStyle,
5721 is_active: bool,
5722 row: DisplayRow,
5723 cx: &mut Context<Self>,
5724 ) -> IconButton {
5725 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5726 .shape(ui::IconButtonShape::Square)
5727 .icon_size(IconSize::XSmall)
5728 .icon_color(Color::Muted)
5729 .toggle_state(is_active)
5730 .on_click(cx.listener(move |editor, _e, window, cx| {
5731 window.focus(&editor.focus_handle(cx));
5732 editor.toggle_code_actions(
5733 &ToggleCodeActions {
5734 deployed_from_indicator: Some(row),
5735 },
5736 window,
5737 cx,
5738 );
5739 }))
5740 }
5741
5742 pub fn context_menu_visible(&self) -> bool {
5743 !self.edit_prediction_preview_is_active()
5744 && self
5745 .context_menu
5746 .borrow()
5747 .as_ref()
5748 .map_or(false, |menu| menu.visible())
5749 }
5750
5751 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5752 self.context_menu
5753 .borrow()
5754 .as_ref()
5755 .map(|menu| menu.origin())
5756 }
5757
5758 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5759 px(30.)
5760 }
5761
5762 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5763 if self.read_only(cx) {
5764 cx.theme().players().read_only()
5765 } else {
5766 self.style.as_ref().unwrap().local_player
5767 }
5768 }
5769
5770 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5771 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5772 let accept_keystroke = accept_binding.keystroke()?;
5773
5774 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5775
5776 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5777 Color::Accent
5778 } else {
5779 Color::Muted
5780 };
5781
5782 h_flex()
5783 .px_0p5()
5784 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5785 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5786 .text_size(TextSize::XSmall.rems(cx))
5787 .child(h_flex().children(ui::render_modifiers(
5788 &accept_keystroke.modifiers,
5789 PlatformStyle::platform(),
5790 Some(modifiers_color),
5791 Some(IconSize::XSmall.rems().into()),
5792 true,
5793 )))
5794 .when(is_platform_style_mac, |parent| {
5795 parent.child(accept_keystroke.key.clone())
5796 })
5797 .when(!is_platform_style_mac, |parent| {
5798 parent.child(
5799 Key::new(
5800 util::capitalize(&accept_keystroke.key),
5801 Some(Color::Default),
5802 )
5803 .size(Some(IconSize::XSmall.rems().into())),
5804 )
5805 })
5806 .into()
5807 }
5808
5809 fn render_edit_prediction_line_popover(
5810 &self,
5811 label: impl Into<SharedString>,
5812 icon: Option<IconName>,
5813 window: &mut Window,
5814 cx: &App,
5815 ) -> Option<Div> {
5816 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5817
5818 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5819
5820 let result = h_flex()
5821 .gap_1()
5822 .border_1()
5823 .rounded_lg()
5824 .shadow_sm()
5825 .bg(bg_color)
5826 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5827 .py_0p5()
5828 .pl_1()
5829 .pr(padding_right)
5830 .children(self.render_edit_prediction_accept_keybind(window, cx))
5831 .child(Label::new(label).size(LabelSize::Small))
5832 .when_some(icon, |element, icon| {
5833 element.child(
5834 div()
5835 .mt(px(1.5))
5836 .child(Icon::new(icon).size(IconSize::Small)),
5837 )
5838 });
5839
5840 Some(result)
5841 }
5842
5843 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5844 let accent_color = cx.theme().colors().text_accent;
5845 let editor_bg_color = cx.theme().colors().editor_background;
5846 editor_bg_color.blend(accent_color.opacity(0.1))
5847 }
5848
5849 #[allow(clippy::too_many_arguments)]
5850 fn render_edit_prediction_cursor_popover(
5851 &self,
5852 min_width: Pixels,
5853 max_width: Pixels,
5854 cursor_point: Point,
5855 style: &EditorStyle,
5856 accept_keystroke: Option<&gpui::Keystroke>,
5857 _window: &Window,
5858 cx: &mut Context<Editor>,
5859 ) -> Option<AnyElement> {
5860 let provider = self.edit_prediction_provider.as_ref()?;
5861
5862 if provider.provider.needs_terms_acceptance(cx) {
5863 return Some(
5864 h_flex()
5865 .min_w(min_width)
5866 .flex_1()
5867 .px_2()
5868 .py_1()
5869 .gap_3()
5870 .elevation_2(cx)
5871 .hover(|style| style.bg(cx.theme().colors().element_hover))
5872 .id("accept-terms")
5873 .cursor_pointer()
5874 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5875 .on_click(cx.listener(|this, _event, window, cx| {
5876 cx.stop_propagation();
5877 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5878 window.dispatch_action(
5879 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5880 cx,
5881 );
5882 }))
5883 .child(
5884 h_flex()
5885 .flex_1()
5886 .gap_2()
5887 .child(Icon::new(IconName::ZedPredict))
5888 .child(Label::new("Accept Terms of Service"))
5889 .child(div().w_full())
5890 .child(
5891 Icon::new(IconName::ArrowUpRight)
5892 .color(Color::Muted)
5893 .size(IconSize::Small),
5894 )
5895 .into_any_element(),
5896 )
5897 .into_any(),
5898 );
5899 }
5900
5901 let is_refreshing = provider.provider.is_refreshing(cx);
5902
5903 fn pending_completion_container() -> Div {
5904 h_flex()
5905 .h_full()
5906 .flex_1()
5907 .gap_2()
5908 .child(Icon::new(IconName::ZedPredict))
5909 }
5910
5911 let completion = match &self.active_inline_completion {
5912 Some(completion) => match &completion.completion {
5913 InlineCompletion::Move {
5914 target, snapshot, ..
5915 } if !self.has_visible_completions_menu() => {
5916 use text::ToPoint as _;
5917
5918 return Some(
5919 h_flex()
5920 .px_2()
5921 .py_1()
5922 .elevation_2(cx)
5923 .border_color(cx.theme().colors().border)
5924 .rounded_tl(px(0.))
5925 .gap_2()
5926 .child(
5927 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5928 Icon::new(IconName::ZedPredictDown)
5929 } else {
5930 Icon::new(IconName::ZedPredictUp)
5931 },
5932 )
5933 .child(Label::new("Hold").size(LabelSize::Small))
5934 .child(h_flex().children(ui::render_modifiers(
5935 &accept_keystroke?.modifiers,
5936 PlatformStyle::platform(),
5937 Some(Color::Default),
5938 Some(IconSize::Small.rems().into()),
5939 false,
5940 )))
5941 .into_any(),
5942 );
5943 }
5944 _ => self.render_edit_prediction_cursor_popover_preview(
5945 completion,
5946 cursor_point,
5947 style,
5948 cx,
5949 )?,
5950 },
5951
5952 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5953 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5954 stale_completion,
5955 cursor_point,
5956 style,
5957 cx,
5958 )?,
5959
5960 None => {
5961 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5962 }
5963 },
5964
5965 None => pending_completion_container().child(Label::new("No Prediction")),
5966 };
5967
5968 let completion = if is_refreshing {
5969 completion
5970 .with_animation(
5971 "loading-completion",
5972 Animation::new(Duration::from_secs(2))
5973 .repeat()
5974 .with_easing(pulsating_between(0.4, 0.8)),
5975 |label, delta| label.opacity(delta),
5976 )
5977 .into_any_element()
5978 } else {
5979 completion.into_any_element()
5980 };
5981
5982 let has_completion = self.active_inline_completion.is_some();
5983
5984 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5985 Some(
5986 h_flex()
5987 .min_w(min_width)
5988 .max_w(max_width)
5989 .flex_1()
5990 .elevation_2(cx)
5991 .border_color(cx.theme().colors().border)
5992 .child(
5993 div()
5994 .flex_1()
5995 .py_1()
5996 .px_2()
5997 .overflow_hidden()
5998 .child(completion),
5999 )
6000 .when_some(accept_keystroke, |el, accept_keystroke| {
6001 if !accept_keystroke.modifiers.modified() {
6002 return el;
6003 }
6004
6005 el.child(
6006 h_flex()
6007 .h_full()
6008 .border_l_1()
6009 .rounded_r_lg()
6010 .border_color(cx.theme().colors().border)
6011 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6012 .gap_1()
6013 .py_1()
6014 .px_2()
6015 .child(
6016 h_flex()
6017 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6018 .when(is_platform_style_mac, |parent| parent.gap_1())
6019 .child(h_flex().children(ui::render_modifiers(
6020 &accept_keystroke.modifiers,
6021 PlatformStyle::platform(),
6022 Some(if !has_completion {
6023 Color::Muted
6024 } else {
6025 Color::Default
6026 }),
6027 None,
6028 false,
6029 ))),
6030 )
6031 .child(Label::new("Preview").into_any_element())
6032 .opacity(if has_completion { 1.0 } else { 0.4 }),
6033 )
6034 })
6035 .into_any(),
6036 )
6037 }
6038
6039 fn render_edit_prediction_cursor_popover_preview(
6040 &self,
6041 completion: &InlineCompletionState,
6042 cursor_point: Point,
6043 style: &EditorStyle,
6044 cx: &mut Context<Editor>,
6045 ) -> Option<Div> {
6046 use text::ToPoint as _;
6047
6048 fn render_relative_row_jump(
6049 prefix: impl Into<String>,
6050 current_row: u32,
6051 target_row: u32,
6052 ) -> Div {
6053 let (row_diff, arrow) = if target_row < current_row {
6054 (current_row - target_row, IconName::ArrowUp)
6055 } else {
6056 (target_row - current_row, IconName::ArrowDown)
6057 };
6058
6059 h_flex()
6060 .child(
6061 Label::new(format!("{}{}", prefix.into(), row_diff))
6062 .color(Color::Muted)
6063 .size(LabelSize::Small),
6064 )
6065 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6066 }
6067
6068 match &completion.completion {
6069 InlineCompletion::Move {
6070 target, snapshot, ..
6071 } => Some(
6072 h_flex()
6073 .px_2()
6074 .gap_2()
6075 .flex_1()
6076 .child(
6077 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6078 Icon::new(IconName::ZedPredictDown)
6079 } else {
6080 Icon::new(IconName::ZedPredictUp)
6081 },
6082 )
6083 .child(Label::new("Jump to Edit")),
6084 ),
6085
6086 InlineCompletion::Edit {
6087 edits,
6088 edit_preview,
6089 snapshot,
6090 display_mode: _,
6091 } => {
6092 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6093
6094 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6095 &snapshot,
6096 &edits,
6097 edit_preview.as_ref()?,
6098 true,
6099 cx,
6100 )
6101 .first_line_preview();
6102
6103 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6104 .with_highlights(&style.text, highlighted_edits.highlights);
6105
6106 let preview = h_flex()
6107 .gap_1()
6108 .min_w_16()
6109 .child(styled_text)
6110 .when(has_more_lines, |parent| parent.child("…"));
6111
6112 let left = if first_edit_row != cursor_point.row {
6113 render_relative_row_jump("", cursor_point.row, first_edit_row)
6114 .into_any_element()
6115 } else {
6116 Icon::new(IconName::ZedPredict).into_any_element()
6117 };
6118
6119 Some(
6120 h_flex()
6121 .h_full()
6122 .flex_1()
6123 .gap_2()
6124 .pr_1()
6125 .overflow_x_hidden()
6126 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6127 .child(left)
6128 .child(preview),
6129 )
6130 }
6131 }
6132 }
6133
6134 fn render_context_menu(
6135 &self,
6136 style: &EditorStyle,
6137 max_height_in_lines: u32,
6138 y_flipped: bool,
6139 window: &mut Window,
6140 cx: &mut Context<Editor>,
6141 ) -> Option<AnyElement> {
6142 let menu = self.context_menu.borrow();
6143 let menu = menu.as_ref()?;
6144 if !menu.visible() {
6145 return None;
6146 };
6147 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6148 }
6149
6150 fn render_context_menu_aside(
6151 &self,
6152 style: &EditorStyle,
6153 max_size: Size<Pixels>,
6154 cx: &mut Context<Editor>,
6155 ) -> Option<AnyElement> {
6156 self.context_menu.borrow().as_ref().and_then(|menu| {
6157 if menu.visible() {
6158 menu.render_aside(
6159 style,
6160 max_size,
6161 self.workspace.as_ref().map(|(w, _)| w.clone()),
6162 cx,
6163 )
6164 } else {
6165 None
6166 }
6167 })
6168 }
6169
6170 fn hide_context_menu(
6171 &mut self,
6172 window: &mut Window,
6173 cx: &mut Context<Self>,
6174 ) -> Option<CodeContextMenu> {
6175 cx.notify();
6176 self.completion_tasks.clear();
6177 let context_menu = self.context_menu.borrow_mut().take();
6178 self.stale_inline_completion_in_menu.take();
6179 self.update_visible_inline_completion(window, cx);
6180 context_menu
6181 }
6182
6183 fn show_snippet_choices(
6184 &mut self,
6185 choices: &Vec<String>,
6186 selection: Range<Anchor>,
6187 cx: &mut Context<Self>,
6188 ) {
6189 if selection.start.buffer_id.is_none() {
6190 return;
6191 }
6192 let buffer_id = selection.start.buffer_id.unwrap();
6193 let buffer = self.buffer().read(cx).buffer(buffer_id);
6194 let id = post_inc(&mut self.next_completion_id);
6195
6196 if let Some(buffer) = buffer {
6197 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6198 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6199 ));
6200 }
6201 }
6202
6203 pub fn insert_snippet(
6204 &mut self,
6205 insertion_ranges: &[Range<usize>],
6206 snippet: Snippet,
6207 window: &mut Window,
6208 cx: &mut Context<Self>,
6209 ) -> Result<()> {
6210 struct Tabstop<T> {
6211 is_end_tabstop: bool,
6212 ranges: Vec<Range<T>>,
6213 choices: Option<Vec<String>>,
6214 }
6215
6216 let tabstops = self.buffer.update(cx, |buffer, cx| {
6217 let snippet_text: Arc<str> = snippet.text.clone().into();
6218 buffer.edit(
6219 insertion_ranges
6220 .iter()
6221 .cloned()
6222 .map(|range| (range, snippet_text.clone())),
6223 Some(AutoindentMode::EachLine),
6224 cx,
6225 );
6226
6227 let snapshot = &*buffer.read(cx);
6228 let snippet = &snippet;
6229 snippet
6230 .tabstops
6231 .iter()
6232 .map(|tabstop| {
6233 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6234 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6235 });
6236 let mut tabstop_ranges = tabstop
6237 .ranges
6238 .iter()
6239 .flat_map(|tabstop_range| {
6240 let mut delta = 0_isize;
6241 insertion_ranges.iter().map(move |insertion_range| {
6242 let insertion_start = insertion_range.start as isize + delta;
6243 delta +=
6244 snippet.text.len() as isize - insertion_range.len() as isize;
6245
6246 let start = ((insertion_start + tabstop_range.start) as usize)
6247 .min(snapshot.len());
6248 let end = ((insertion_start + tabstop_range.end) as usize)
6249 .min(snapshot.len());
6250 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6251 })
6252 })
6253 .collect::<Vec<_>>();
6254 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6255
6256 Tabstop {
6257 is_end_tabstop,
6258 ranges: tabstop_ranges,
6259 choices: tabstop.choices.clone(),
6260 }
6261 })
6262 .collect::<Vec<_>>()
6263 });
6264 if let Some(tabstop) = tabstops.first() {
6265 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6266 s.select_ranges(tabstop.ranges.iter().cloned());
6267 });
6268
6269 if let Some(choices) = &tabstop.choices {
6270 if let Some(selection) = tabstop.ranges.first() {
6271 self.show_snippet_choices(choices, selection.clone(), cx)
6272 }
6273 }
6274
6275 // If we're already at the last tabstop and it's at the end of the snippet,
6276 // we're done, we don't need to keep the state around.
6277 if !tabstop.is_end_tabstop {
6278 let choices = tabstops
6279 .iter()
6280 .map(|tabstop| tabstop.choices.clone())
6281 .collect();
6282
6283 let ranges = tabstops
6284 .into_iter()
6285 .map(|tabstop| tabstop.ranges)
6286 .collect::<Vec<_>>();
6287
6288 self.snippet_stack.push(SnippetState {
6289 active_index: 0,
6290 ranges,
6291 choices,
6292 });
6293 }
6294
6295 // Check whether the just-entered snippet ends with an auto-closable bracket.
6296 if self.autoclose_regions.is_empty() {
6297 let snapshot = self.buffer.read(cx).snapshot(cx);
6298 for selection in &mut self.selections.all::<Point>(cx) {
6299 let selection_head = selection.head();
6300 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6301 continue;
6302 };
6303
6304 let mut bracket_pair = None;
6305 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6306 let prev_chars = snapshot
6307 .reversed_chars_at(selection_head)
6308 .collect::<String>();
6309 for (pair, enabled) in scope.brackets() {
6310 if enabled
6311 && pair.close
6312 && prev_chars.starts_with(pair.start.as_str())
6313 && next_chars.starts_with(pair.end.as_str())
6314 {
6315 bracket_pair = Some(pair.clone());
6316 break;
6317 }
6318 }
6319 if let Some(pair) = bracket_pair {
6320 let start = snapshot.anchor_after(selection_head);
6321 let end = snapshot.anchor_after(selection_head);
6322 self.autoclose_regions.push(AutocloseRegion {
6323 selection_id: selection.id,
6324 range: start..end,
6325 pair,
6326 });
6327 }
6328 }
6329 }
6330 }
6331 Ok(())
6332 }
6333
6334 pub fn move_to_next_snippet_tabstop(
6335 &mut self,
6336 window: &mut Window,
6337 cx: &mut Context<Self>,
6338 ) -> bool {
6339 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6340 }
6341
6342 pub fn move_to_prev_snippet_tabstop(
6343 &mut self,
6344 window: &mut Window,
6345 cx: &mut Context<Self>,
6346 ) -> bool {
6347 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6348 }
6349
6350 pub fn move_to_snippet_tabstop(
6351 &mut self,
6352 bias: Bias,
6353 window: &mut Window,
6354 cx: &mut Context<Self>,
6355 ) -> bool {
6356 if let Some(mut snippet) = self.snippet_stack.pop() {
6357 match bias {
6358 Bias::Left => {
6359 if snippet.active_index > 0 {
6360 snippet.active_index -= 1;
6361 } else {
6362 self.snippet_stack.push(snippet);
6363 return false;
6364 }
6365 }
6366 Bias::Right => {
6367 if snippet.active_index + 1 < snippet.ranges.len() {
6368 snippet.active_index += 1;
6369 } else {
6370 self.snippet_stack.push(snippet);
6371 return false;
6372 }
6373 }
6374 }
6375 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6376 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6377 s.select_anchor_ranges(current_ranges.iter().cloned())
6378 });
6379
6380 if let Some(choices) = &snippet.choices[snippet.active_index] {
6381 if let Some(selection) = current_ranges.first() {
6382 self.show_snippet_choices(&choices, selection.clone(), cx);
6383 }
6384 }
6385
6386 // If snippet state is not at the last tabstop, push it back on the stack
6387 if snippet.active_index + 1 < snippet.ranges.len() {
6388 self.snippet_stack.push(snippet);
6389 }
6390 return true;
6391 }
6392 }
6393
6394 false
6395 }
6396
6397 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6398 self.transact(window, cx, |this, window, cx| {
6399 this.select_all(&SelectAll, window, cx);
6400 this.insert("", window, cx);
6401 });
6402 }
6403
6404 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6405 self.transact(window, cx, |this, window, cx| {
6406 this.select_autoclose_pair(window, cx);
6407 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6408 if !this.linked_edit_ranges.is_empty() {
6409 let selections = this.selections.all::<MultiBufferPoint>(cx);
6410 let snapshot = this.buffer.read(cx).snapshot(cx);
6411
6412 for selection in selections.iter() {
6413 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6414 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6415 if selection_start.buffer_id != selection_end.buffer_id {
6416 continue;
6417 }
6418 if let Some(ranges) =
6419 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6420 {
6421 for (buffer, entries) in ranges {
6422 linked_ranges.entry(buffer).or_default().extend(entries);
6423 }
6424 }
6425 }
6426 }
6427
6428 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6429 if !this.selections.line_mode {
6430 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6431 for selection in &mut selections {
6432 if selection.is_empty() {
6433 let old_head = selection.head();
6434 let mut new_head =
6435 movement::left(&display_map, old_head.to_display_point(&display_map))
6436 .to_point(&display_map);
6437 if let Some((buffer, line_buffer_range)) = display_map
6438 .buffer_snapshot
6439 .buffer_line_for_row(MultiBufferRow(old_head.row))
6440 {
6441 let indent_size =
6442 buffer.indent_size_for_line(line_buffer_range.start.row);
6443 let indent_len = match indent_size.kind {
6444 IndentKind::Space => {
6445 buffer.settings_at(line_buffer_range.start, cx).tab_size
6446 }
6447 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6448 };
6449 if old_head.column <= indent_size.len && old_head.column > 0 {
6450 let indent_len = indent_len.get();
6451 new_head = cmp::min(
6452 new_head,
6453 MultiBufferPoint::new(
6454 old_head.row,
6455 ((old_head.column - 1) / indent_len) * indent_len,
6456 ),
6457 );
6458 }
6459 }
6460
6461 selection.set_head(new_head, SelectionGoal::None);
6462 }
6463 }
6464 }
6465
6466 this.signature_help_state.set_backspace_pressed(true);
6467 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6468 s.select(selections)
6469 });
6470 this.insert("", window, cx);
6471 let empty_str: Arc<str> = Arc::from("");
6472 for (buffer, edits) in linked_ranges {
6473 let snapshot = buffer.read(cx).snapshot();
6474 use text::ToPoint as TP;
6475
6476 let edits = edits
6477 .into_iter()
6478 .map(|range| {
6479 let end_point = TP::to_point(&range.end, &snapshot);
6480 let mut start_point = TP::to_point(&range.start, &snapshot);
6481
6482 if end_point == start_point {
6483 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6484 .saturating_sub(1);
6485 start_point =
6486 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6487 };
6488
6489 (start_point..end_point, empty_str.clone())
6490 })
6491 .sorted_by_key(|(range, _)| range.start)
6492 .collect::<Vec<_>>();
6493 buffer.update(cx, |this, cx| {
6494 this.edit(edits, None, cx);
6495 })
6496 }
6497 this.refresh_inline_completion(true, false, window, cx);
6498 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6499 });
6500 }
6501
6502 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6503 self.transact(window, cx, |this, window, cx| {
6504 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6505 let line_mode = s.line_mode;
6506 s.move_with(|map, selection| {
6507 if selection.is_empty() && !line_mode {
6508 let cursor = movement::right(map, selection.head());
6509 selection.end = cursor;
6510 selection.reversed = true;
6511 selection.goal = SelectionGoal::None;
6512 }
6513 })
6514 });
6515 this.insert("", window, cx);
6516 this.refresh_inline_completion(true, false, window, cx);
6517 });
6518 }
6519
6520 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6521 if self.move_to_prev_snippet_tabstop(window, cx) {
6522 return;
6523 }
6524
6525 self.outdent(&Outdent, window, cx);
6526 }
6527
6528 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6529 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6530 return;
6531 }
6532
6533 let mut selections = self.selections.all_adjusted(cx);
6534 let buffer = self.buffer.read(cx);
6535 let snapshot = buffer.snapshot(cx);
6536 let rows_iter = selections.iter().map(|s| s.head().row);
6537 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6538
6539 let mut edits = Vec::new();
6540 let mut prev_edited_row = 0;
6541 let mut row_delta = 0;
6542 for selection in &mut selections {
6543 if selection.start.row != prev_edited_row {
6544 row_delta = 0;
6545 }
6546 prev_edited_row = selection.end.row;
6547
6548 // If the selection is non-empty, then increase the indentation of the selected lines.
6549 if !selection.is_empty() {
6550 row_delta =
6551 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6552 continue;
6553 }
6554
6555 // If the selection is empty and the cursor is in the leading whitespace before the
6556 // suggested indentation, then auto-indent the line.
6557 let cursor = selection.head();
6558 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6559 if let Some(suggested_indent) =
6560 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6561 {
6562 if cursor.column < suggested_indent.len
6563 && cursor.column <= current_indent.len
6564 && current_indent.len <= suggested_indent.len
6565 {
6566 selection.start = Point::new(cursor.row, suggested_indent.len);
6567 selection.end = selection.start;
6568 if row_delta == 0 {
6569 edits.extend(Buffer::edit_for_indent_size_adjustment(
6570 cursor.row,
6571 current_indent,
6572 suggested_indent,
6573 ));
6574 row_delta = suggested_indent.len - current_indent.len;
6575 }
6576 continue;
6577 }
6578 }
6579
6580 // Otherwise, insert a hard or soft tab.
6581 let settings = buffer.settings_at(cursor, cx);
6582 let tab_size = if settings.hard_tabs {
6583 IndentSize::tab()
6584 } else {
6585 let tab_size = settings.tab_size.get();
6586 let char_column = snapshot
6587 .text_for_range(Point::new(cursor.row, 0)..cursor)
6588 .flat_map(str::chars)
6589 .count()
6590 + row_delta as usize;
6591 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6592 IndentSize::spaces(chars_to_next_tab_stop)
6593 };
6594 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6595 selection.end = selection.start;
6596 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6597 row_delta += tab_size.len;
6598 }
6599
6600 self.transact(window, cx, |this, window, cx| {
6601 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6602 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6603 s.select(selections)
6604 });
6605 this.refresh_inline_completion(true, false, window, cx);
6606 });
6607 }
6608
6609 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6610 if self.read_only(cx) {
6611 return;
6612 }
6613 let mut selections = self.selections.all::<Point>(cx);
6614 let mut prev_edited_row = 0;
6615 let mut row_delta = 0;
6616 let mut edits = Vec::new();
6617 let buffer = self.buffer.read(cx);
6618 let snapshot = buffer.snapshot(cx);
6619 for selection in &mut selections {
6620 if selection.start.row != prev_edited_row {
6621 row_delta = 0;
6622 }
6623 prev_edited_row = selection.end.row;
6624
6625 row_delta =
6626 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6627 }
6628
6629 self.transact(window, cx, |this, window, cx| {
6630 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6631 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6632 s.select(selections)
6633 });
6634 });
6635 }
6636
6637 fn indent_selection(
6638 buffer: &MultiBuffer,
6639 snapshot: &MultiBufferSnapshot,
6640 selection: &mut Selection<Point>,
6641 edits: &mut Vec<(Range<Point>, String)>,
6642 delta_for_start_row: u32,
6643 cx: &App,
6644 ) -> u32 {
6645 let settings = buffer.settings_at(selection.start, cx);
6646 let tab_size = settings.tab_size.get();
6647 let indent_kind = if settings.hard_tabs {
6648 IndentKind::Tab
6649 } else {
6650 IndentKind::Space
6651 };
6652 let mut start_row = selection.start.row;
6653 let mut end_row = selection.end.row + 1;
6654
6655 // If a selection ends at the beginning of a line, don't indent
6656 // that last line.
6657 if selection.end.column == 0 && selection.end.row > selection.start.row {
6658 end_row -= 1;
6659 }
6660
6661 // Avoid re-indenting a row that has already been indented by a
6662 // previous selection, but still update this selection's column
6663 // to reflect that indentation.
6664 if delta_for_start_row > 0 {
6665 start_row += 1;
6666 selection.start.column += delta_for_start_row;
6667 if selection.end.row == selection.start.row {
6668 selection.end.column += delta_for_start_row;
6669 }
6670 }
6671
6672 let mut delta_for_end_row = 0;
6673 let has_multiple_rows = start_row + 1 != end_row;
6674 for row in start_row..end_row {
6675 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6676 let indent_delta = match (current_indent.kind, indent_kind) {
6677 (IndentKind::Space, IndentKind::Space) => {
6678 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6679 IndentSize::spaces(columns_to_next_tab_stop)
6680 }
6681 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6682 (_, IndentKind::Tab) => IndentSize::tab(),
6683 };
6684
6685 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6686 0
6687 } else {
6688 selection.start.column
6689 };
6690 let row_start = Point::new(row, start);
6691 edits.push((
6692 row_start..row_start,
6693 indent_delta.chars().collect::<String>(),
6694 ));
6695
6696 // Update this selection's endpoints to reflect the indentation.
6697 if row == selection.start.row {
6698 selection.start.column += indent_delta.len;
6699 }
6700 if row == selection.end.row {
6701 selection.end.column += indent_delta.len;
6702 delta_for_end_row = indent_delta.len;
6703 }
6704 }
6705
6706 if selection.start.row == selection.end.row {
6707 delta_for_start_row + delta_for_end_row
6708 } else {
6709 delta_for_end_row
6710 }
6711 }
6712
6713 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6714 if self.read_only(cx) {
6715 return;
6716 }
6717 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6718 let selections = self.selections.all::<Point>(cx);
6719 let mut deletion_ranges = Vec::new();
6720 let mut last_outdent = None;
6721 {
6722 let buffer = self.buffer.read(cx);
6723 let snapshot = buffer.snapshot(cx);
6724 for selection in &selections {
6725 let settings = buffer.settings_at(selection.start, cx);
6726 let tab_size = settings.tab_size.get();
6727 let mut rows = selection.spanned_rows(false, &display_map);
6728
6729 // Avoid re-outdenting a row that has already been outdented by a
6730 // previous selection.
6731 if let Some(last_row) = last_outdent {
6732 if last_row == rows.start {
6733 rows.start = rows.start.next_row();
6734 }
6735 }
6736 let has_multiple_rows = rows.len() > 1;
6737 for row in rows.iter_rows() {
6738 let indent_size = snapshot.indent_size_for_line(row);
6739 if indent_size.len > 0 {
6740 let deletion_len = match indent_size.kind {
6741 IndentKind::Space => {
6742 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6743 if columns_to_prev_tab_stop == 0 {
6744 tab_size
6745 } else {
6746 columns_to_prev_tab_stop
6747 }
6748 }
6749 IndentKind::Tab => 1,
6750 };
6751 let start = if has_multiple_rows
6752 || deletion_len > selection.start.column
6753 || indent_size.len < selection.start.column
6754 {
6755 0
6756 } else {
6757 selection.start.column - deletion_len
6758 };
6759 deletion_ranges.push(
6760 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6761 );
6762 last_outdent = Some(row);
6763 }
6764 }
6765 }
6766 }
6767
6768 self.transact(window, cx, |this, window, cx| {
6769 this.buffer.update(cx, |buffer, cx| {
6770 let empty_str: Arc<str> = Arc::default();
6771 buffer.edit(
6772 deletion_ranges
6773 .into_iter()
6774 .map(|range| (range, empty_str.clone())),
6775 None,
6776 cx,
6777 );
6778 });
6779 let selections = this.selections.all::<usize>(cx);
6780 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6781 s.select(selections)
6782 });
6783 });
6784 }
6785
6786 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6787 if self.read_only(cx) {
6788 return;
6789 }
6790 let selections = self
6791 .selections
6792 .all::<usize>(cx)
6793 .into_iter()
6794 .map(|s| s.range());
6795
6796 self.transact(window, cx, |this, window, cx| {
6797 this.buffer.update(cx, |buffer, cx| {
6798 buffer.autoindent_ranges(selections, cx);
6799 });
6800 let selections = this.selections.all::<usize>(cx);
6801 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6802 s.select(selections)
6803 });
6804 });
6805 }
6806
6807 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6809 let selections = self.selections.all::<Point>(cx);
6810
6811 let mut new_cursors = Vec::new();
6812 let mut edit_ranges = Vec::new();
6813 let mut selections = selections.iter().peekable();
6814 while let Some(selection) = selections.next() {
6815 let mut rows = selection.spanned_rows(false, &display_map);
6816 let goal_display_column = selection.head().to_display_point(&display_map).column();
6817
6818 // Accumulate contiguous regions of rows that we want to delete.
6819 while let Some(next_selection) = selections.peek() {
6820 let next_rows = next_selection.spanned_rows(false, &display_map);
6821 if next_rows.start <= rows.end {
6822 rows.end = next_rows.end;
6823 selections.next().unwrap();
6824 } else {
6825 break;
6826 }
6827 }
6828
6829 let buffer = &display_map.buffer_snapshot;
6830 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6831 let edit_end;
6832 let cursor_buffer_row;
6833 if buffer.max_point().row >= rows.end.0 {
6834 // If there's a line after the range, delete the \n from the end of the row range
6835 // and position the cursor on the next line.
6836 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6837 cursor_buffer_row = rows.end;
6838 } else {
6839 // If there isn't a line after the range, delete the \n from the line before the
6840 // start of the row range and position the cursor there.
6841 edit_start = edit_start.saturating_sub(1);
6842 edit_end = buffer.len();
6843 cursor_buffer_row = rows.start.previous_row();
6844 }
6845
6846 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6847 *cursor.column_mut() =
6848 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6849
6850 new_cursors.push((
6851 selection.id,
6852 buffer.anchor_after(cursor.to_point(&display_map)),
6853 ));
6854 edit_ranges.push(edit_start..edit_end);
6855 }
6856
6857 self.transact(window, cx, |this, window, cx| {
6858 let buffer = this.buffer.update(cx, |buffer, cx| {
6859 let empty_str: Arc<str> = Arc::default();
6860 buffer.edit(
6861 edit_ranges
6862 .into_iter()
6863 .map(|range| (range, empty_str.clone())),
6864 None,
6865 cx,
6866 );
6867 buffer.snapshot(cx)
6868 });
6869 let new_selections = new_cursors
6870 .into_iter()
6871 .map(|(id, cursor)| {
6872 let cursor = cursor.to_point(&buffer);
6873 Selection {
6874 id,
6875 start: cursor,
6876 end: cursor,
6877 reversed: false,
6878 goal: SelectionGoal::None,
6879 }
6880 })
6881 .collect();
6882
6883 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6884 s.select(new_selections);
6885 });
6886 });
6887 }
6888
6889 pub fn join_lines_impl(
6890 &mut self,
6891 insert_whitespace: bool,
6892 window: &mut Window,
6893 cx: &mut Context<Self>,
6894 ) {
6895 if self.read_only(cx) {
6896 return;
6897 }
6898 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6899 for selection in self.selections.all::<Point>(cx) {
6900 let start = MultiBufferRow(selection.start.row);
6901 // Treat single line selections as if they include the next line. Otherwise this action
6902 // would do nothing for single line selections individual cursors.
6903 let end = if selection.start.row == selection.end.row {
6904 MultiBufferRow(selection.start.row + 1)
6905 } else {
6906 MultiBufferRow(selection.end.row)
6907 };
6908
6909 if let Some(last_row_range) = row_ranges.last_mut() {
6910 if start <= last_row_range.end {
6911 last_row_range.end = end;
6912 continue;
6913 }
6914 }
6915 row_ranges.push(start..end);
6916 }
6917
6918 let snapshot = self.buffer.read(cx).snapshot(cx);
6919 let mut cursor_positions = Vec::new();
6920 for row_range in &row_ranges {
6921 let anchor = snapshot.anchor_before(Point::new(
6922 row_range.end.previous_row().0,
6923 snapshot.line_len(row_range.end.previous_row()),
6924 ));
6925 cursor_positions.push(anchor..anchor);
6926 }
6927
6928 self.transact(window, cx, |this, window, cx| {
6929 for row_range in row_ranges.into_iter().rev() {
6930 for row in row_range.iter_rows().rev() {
6931 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6932 let next_line_row = row.next_row();
6933 let indent = snapshot.indent_size_for_line(next_line_row);
6934 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6935
6936 let replace =
6937 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6938 " "
6939 } else {
6940 ""
6941 };
6942
6943 this.buffer.update(cx, |buffer, cx| {
6944 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6945 });
6946 }
6947 }
6948
6949 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6950 s.select_anchor_ranges(cursor_positions)
6951 });
6952 });
6953 }
6954
6955 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6956 self.join_lines_impl(true, window, cx);
6957 }
6958
6959 pub fn sort_lines_case_sensitive(
6960 &mut self,
6961 _: &SortLinesCaseSensitive,
6962 window: &mut Window,
6963 cx: &mut Context<Self>,
6964 ) {
6965 self.manipulate_lines(window, cx, |lines| lines.sort())
6966 }
6967
6968 pub fn sort_lines_case_insensitive(
6969 &mut self,
6970 _: &SortLinesCaseInsensitive,
6971 window: &mut Window,
6972 cx: &mut Context<Self>,
6973 ) {
6974 self.manipulate_lines(window, cx, |lines| {
6975 lines.sort_by_key(|line| line.to_lowercase())
6976 })
6977 }
6978
6979 pub fn unique_lines_case_insensitive(
6980 &mut self,
6981 _: &UniqueLinesCaseInsensitive,
6982 window: &mut Window,
6983 cx: &mut Context<Self>,
6984 ) {
6985 self.manipulate_lines(window, cx, |lines| {
6986 let mut seen = HashSet::default();
6987 lines.retain(|line| seen.insert(line.to_lowercase()));
6988 })
6989 }
6990
6991 pub fn unique_lines_case_sensitive(
6992 &mut self,
6993 _: &UniqueLinesCaseSensitive,
6994 window: &mut Window,
6995 cx: &mut Context<Self>,
6996 ) {
6997 self.manipulate_lines(window, cx, |lines| {
6998 let mut seen = HashSet::default();
6999 lines.retain(|line| seen.insert(*line));
7000 })
7001 }
7002
7003 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7004 let mut revert_changes = HashMap::default();
7005 let snapshot = self.snapshot(window, cx);
7006 for hunk in snapshot
7007 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7008 {
7009 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7010 }
7011 if !revert_changes.is_empty() {
7012 self.transact(window, cx, |editor, window, cx| {
7013 editor.revert(revert_changes, window, cx);
7014 });
7015 }
7016 }
7017
7018 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7019 let Some(project) = self.project.clone() else {
7020 return;
7021 };
7022 self.reload(project, window, cx)
7023 .detach_and_notify_err(window, cx);
7024 }
7025
7026 pub fn revert_selected_hunks(
7027 &mut self,
7028 _: &RevertSelectedHunks,
7029 window: &mut Window,
7030 cx: &mut Context<Self>,
7031 ) {
7032 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7033 self.discard_hunks_in_ranges(selections, window, cx);
7034 }
7035
7036 fn discard_hunks_in_ranges(
7037 &mut self,
7038 ranges: impl Iterator<Item = Range<Point>>,
7039 window: &mut Window,
7040 cx: &mut Context<Editor>,
7041 ) {
7042 let mut revert_changes = HashMap::default();
7043 let snapshot = self.snapshot(window, cx);
7044 for hunk in &snapshot.hunks_for_ranges(ranges) {
7045 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7046 }
7047 if !revert_changes.is_empty() {
7048 self.transact(window, cx, |editor, window, cx| {
7049 editor.revert(revert_changes, window, cx);
7050 });
7051 }
7052 }
7053
7054 pub fn open_active_item_in_terminal(
7055 &mut self,
7056 _: &OpenInTerminal,
7057 window: &mut Window,
7058 cx: &mut Context<Self>,
7059 ) {
7060 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7061 let project_path = buffer.read(cx).project_path(cx)?;
7062 let project = self.project.as_ref()?.read(cx);
7063 let entry = project.entry_for_path(&project_path, cx)?;
7064 let parent = match &entry.canonical_path {
7065 Some(canonical_path) => canonical_path.to_path_buf(),
7066 None => project.absolute_path(&project_path, cx)?,
7067 }
7068 .parent()?
7069 .to_path_buf();
7070 Some(parent)
7071 }) {
7072 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7073 }
7074 }
7075
7076 pub fn prepare_revert_change(
7077 &self,
7078 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7079 hunk: &MultiBufferDiffHunk,
7080 cx: &mut App,
7081 ) -> Option<()> {
7082 let buffer = self.buffer.read(cx);
7083 let diff = buffer.diff_for(hunk.buffer_id)?;
7084 let buffer = buffer.buffer(hunk.buffer_id)?;
7085 let buffer = buffer.read(cx);
7086 let original_text = diff
7087 .read(cx)
7088 .base_text()
7089 .as_ref()?
7090 .as_rope()
7091 .slice(hunk.diff_base_byte_range.clone());
7092 let buffer_snapshot = buffer.snapshot();
7093 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7094 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7095 probe
7096 .0
7097 .start
7098 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7099 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7100 }) {
7101 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7102 Some(())
7103 } else {
7104 None
7105 }
7106 }
7107
7108 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7109 self.manipulate_lines(window, cx, |lines| lines.reverse())
7110 }
7111
7112 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7113 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7114 }
7115
7116 fn manipulate_lines<Fn>(
7117 &mut self,
7118 window: &mut Window,
7119 cx: &mut Context<Self>,
7120 mut callback: Fn,
7121 ) where
7122 Fn: FnMut(&mut Vec<&str>),
7123 {
7124 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7125 let buffer = self.buffer.read(cx).snapshot(cx);
7126
7127 let mut edits = Vec::new();
7128
7129 let selections = self.selections.all::<Point>(cx);
7130 let mut selections = selections.iter().peekable();
7131 let mut contiguous_row_selections = Vec::new();
7132 let mut new_selections = Vec::new();
7133 let mut added_lines = 0;
7134 let mut removed_lines = 0;
7135
7136 while let Some(selection) = selections.next() {
7137 let (start_row, end_row) = consume_contiguous_rows(
7138 &mut contiguous_row_selections,
7139 selection,
7140 &display_map,
7141 &mut selections,
7142 );
7143
7144 let start_point = Point::new(start_row.0, 0);
7145 let end_point = Point::new(
7146 end_row.previous_row().0,
7147 buffer.line_len(end_row.previous_row()),
7148 );
7149 let text = buffer
7150 .text_for_range(start_point..end_point)
7151 .collect::<String>();
7152
7153 let mut lines = text.split('\n').collect_vec();
7154
7155 let lines_before = lines.len();
7156 callback(&mut lines);
7157 let lines_after = lines.len();
7158
7159 edits.push((start_point..end_point, lines.join("\n")));
7160
7161 // Selections must change based on added and removed line count
7162 let start_row =
7163 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7164 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7165 new_selections.push(Selection {
7166 id: selection.id,
7167 start: start_row,
7168 end: end_row,
7169 goal: SelectionGoal::None,
7170 reversed: selection.reversed,
7171 });
7172
7173 if lines_after > lines_before {
7174 added_lines += lines_after - lines_before;
7175 } else if lines_before > lines_after {
7176 removed_lines += lines_before - lines_after;
7177 }
7178 }
7179
7180 self.transact(window, cx, |this, window, cx| {
7181 let buffer = this.buffer.update(cx, |buffer, cx| {
7182 buffer.edit(edits, None, cx);
7183 buffer.snapshot(cx)
7184 });
7185
7186 // Recalculate offsets on newly edited buffer
7187 let new_selections = new_selections
7188 .iter()
7189 .map(|s| {
7190 let start_point = Point::new(s.start.0, 0);
7191 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7192 Selection {
7193 id: s.id,
7194 start: buffer.point_to_offset(start_point),
7195 end: buffer.point_to_offset(end_point),
7196 goal: s.goal,
7197 reversed: s.reversed,
7198 }
7199 })
7200 .collect();
7201
7202 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7203 s.select(new_selections);
7204 });
7205
7206 this.request_autoscroll(Autoscroll::fit(), cx);
7207 });
7208 }
7209
7210 pub fn convert_to_upper_case(
7211 &mut self,
7212 _: &ConvertToUpperCase,
7213 window: &mut Window,
7214 cx: &mut Context<Self>,
7215 ) {
7216 self.manipulate_text(window, cx, |text| text.to_uppercase())
7217 }
7218
7219 pub fn convert_to_lower_case(
7220 &mut self,
7221 _: &ConvertToLowerCase,
7222 window: &mut Window,
7223 cx: &mut Context<Self>,
7224 ) {
7225 self.manipulate_text(window, cx, |text| text.to_lowercase())
7226 }
7227
7228 pub fn convert_to_title_case(
7229 &mut self,
7230 _: &ConvertToTitleCase,
7231 window: &mut Window,
7232 cx: &mut Context<Self>,
7233 ) {
7234 self.manipulate_text(window, cx, |text| {
7235 text.split('\n')
7236 .map(|line| line.to_case(Case::Title))
7237 .join("\n")
7238 })
7239 }
7240
7241 pub fn convert_to_snake_case(
7242 &mut self,
7243 _: &ConvertToSnakeCase,
7244 window: &mut Window,
7245 cx: &mut Context<Self>,
7246 ) {
7247 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7248 }
7249
7250 pub fn convert_to_kebab_case(
7251 &mut self,
7252 _: &ConvertToKebabCase,
7253 window: &mut Window,
7254 cx: &mut Context<Self>,
7255 ) {
7256 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7257 }
7258
7259 pub fn convert_to_upper_camel_case(
7260 &mut self,
7261 _: &ConvertToUpperCamelCase,
7262 window: &mut Window,
7263 cx: &mut Context<Self>,
7264 ) {
7265 self.manipulate_text(window, cx, |text| {
7266 text.split('\n')
7267 .map(|line| line.to_case(Case::UpperCamel))
7268 .join("\n")
7269 })
7270 }
7271
7272 pub fn convert_to_lower_camel_case(
7273 &mut self,
7274 _: &ConvertToLowerCamelCase,
7275 window: &mut Window,
7276 cx: &mut Context<Self>,
7277 ) {
7278 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7279 }
7280
7281 pub fn convert_to_opposite_case(
7282 &mut self,
7283 _: &ConvertToOppositeCase,
7284 window: &mut Window,
7285 cx: &mut Context<Self>,
7286 ) {
7287 self.manipulate_text(window, cx, |text| {
7288 text.chars()
7289 .fold(String::with_capacity(text.len()), |mut t, c| {
7290 if c.is_uppercase() {
7291 t.extend(c.to_lowercase());
7292 } else {
7293 t.extend(c.to_uppercase());
7294 }
7295 t
7296 })
7297 })
7298 }
7299
7300 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7301 where
7302 Fn: FnMut(&str) -> String,
7303 {
7304 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7305 let buffer = self.buffer.read(cx).snapshot(cx);
7306
7307 let mut new_selections = Vec::new();
7308 let mut edits = Vec::new();
7309 let mut selection_adjustment = 0i32;
7310
7311 for selection in self.selections.all::<usize>(cx) {
7312 let selection_is_empty = selection.is_empty();
7313
7314 let (start, end) = if selection_is_empty {
7315 let word_range = movement::surrounding_word(
7316 &display_map,
7317 selection.start.to_display_point(&display_map),
7318 );
7319 let start = word_range.start.to_offset(&display_map, Bias::Left);
7320 let end = word_range.end.to_offset(&display_map, Bias::Left);
7321 (start, end)
7322 } else {
7323 (selection.start, selection.end)
7324 };
7325
7326 let text = buffer.text_for_range(start..end).collect::<String>();
7327 let old_length = text.len() as i32;
7328 let text = callback(&text);
7329
7330 new_selections.push(Selection {
7331 start: (start as i32 - selection_adjustment) as usize,
7332 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7333 goal: SelectionGoal::None,
7334 ..selection
7335 });
7336
7337 selection_adjustment += old_length - text.len() as i32;
7338
7339 edits.push((start..end, text));
7340 }
7341
7342 self.transact(window, cx, |this, window, cx| {
7343 this.buffer.update(cx, |buffer, cx| {
7344 buffer.edit(edits, None, cx);
7345 });
7346
7347 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7348 s.select(new_selections);
7349 });
7350
7351 this.request_autoscroll(Autoscroll::fit(), cx);
7352 });
7353 }
7354
7355 pub fn duplicate(
7356 &mut self,
7357 upwards: bool,
7358 whole_lines: bool,
7359 window: &mut Window,
7360 cx: &mut Context<Self>,
7361 ) {
7362 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7363 let buffer = &display_map.buffer_snapshot;
7364 let selections = self.selections.all::<Point>(cx);
7365
7366 let mut edits = Vec::new();
7367 let mut selections_iter = selections.iter().peekable();
7368 while let Some(selection) = selections_iter.next() {
7369 let mut rows = selection.spanned_rows(false, &display_map);
7370 // duplicate line-wise
7371 if whole_lines || selection.start == selection.end {
7372 // Avoid duplicating the same lines twice.
7373 while let Some(next_selection) = selections_iter.peek() {
7374 let next_rows = next_selection.spanned_rows(false, &display_map);
7375 if next_rows.start < rows.end {
7376 rows.end = next_rows.end;
7377 selections_iter.next().unwrap();
7378 } else {
7379 break;
7380 }
7381 }
7382
7383 // Copy the text from the selected row region and splice it either at the start
7384 // or end of the region.
7385 let start = Point::new(rows.start.0, 0);
7386 let end = Point::new(
7387 rows.end.previous_row().0,
7388 buffer.line_len(rows.end.previous_row()),
7389 );
7390 let text = buffer
7391 .text_for_range(start..end)
7392 .chain(Some("\n"))
7393 .collect::<String>();
7394 let insert_location = if upwards {
7395 Point::new(rows.end.0, 0)
7396 } else {
7397 start
7398 };
7399 edits.push((insert_location..insert_location, text));
7400 } else {
7401 // duplicate character-wise
7402 let start = selection.start;
7403 let end = selection.end;
7404 let text = buffer.text_for_range(start..end).collect::<String>();
7405 edits.push((selection.end..selection.end, text));
7406 }
7407 }
7408
7409 self.transact(window, cx, |this, _, cx| {
7410 this.buffer.update(cx, |buffer, cx| {
7411 buffer.edit(edits, None, cx);
7412 });
7413
7414 this.request_autoscroll(Autoscroll::fit(), cx);
7415 });
7416 }
7417
7418 pub fn duplicate_line_up(
7419 &mut self,
7420 _: &DuplicateLineUp,
7421 window: &mut Window,
7422 cx: &mut Context<Self>,
7423 ) {
7424 self.duplicate(true, true, window, cx);
7425 }
7426
7427 pub fn duplicate_line_down(
7428 &mut self,
7429 _: &DuplicateLineDown,
7430 window: &mut Window,
7431 cx: &mut Context<Self>,
7432 ) {
7433 self.duplicate(false, true, window, cx);
7434 }
7435
7436 pub fn duplicate_selection(
7437 &mut self,
7438 _: &DuplicateSelection,
7439 window: &mut Window,
7440 cx: &mut Context<Self>,
7441 ) {
7442 self.duplicate(false, false, window, cx);
7443 }
7444
7445 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7446 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7447 let buffer = self.buffer.read(cx).snapshot(cx);
7448
7449 let mut edits = Vec::new();
7450 let mut unfold_ranges = Vec::new();
7451 let mut refold_creases = Vec::new();
7452
7453 let selections = self.selections.all::<Point>(cx);
7454 let mut selections = selections.iter().peekable();
7455 let mut contiguous_row_selections = Vec::new();
7456 let mut new_selections = Vec::new();
7457
7458 while let Some(selection) = selections.next() {
7459 // Find all the selections that span a contiguous row range
7460 let (start_row, end_row) = consume_contiguous_rows(
7461 &mut contiguous_row_selections,
7462 selection,
7463 &display_map,
7464 &mut selections,
7465 );
7466
7467 // Move the text spanned by the row range to be before the line preceding the row range
7468 if start_row.0 > 0 {
7469 let range_to_move = Point::new(
7470 start_row.previous_row().0,
7471 buffer.line_len(start_row.previous_row()),
7472 )
7473 ..Point::new(
7474 end_row.previous_row().0,
7475 buffer.line_len(end_row.previous_row()),
7476 );
7477 let insertion_point = display_map
7478 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7479 .0;
7480
7481 // Don't move lines across excerpts
7482 if buffer
7483 .excerpt_containing(insertion_point..range_to_move.end)
7484 .is_some()
7485 {
7486 let text = buffer
7487 .text_for_range(range_to_move.clone())
7488 .flat_map(|s| s.chars())
7489 .skip(1)
7490 .chain(['\n'])
7491 .collect::<String>();
7492
7493 edits.push((
7494 buffer.anchor_after(range_to_move.start)
7495 ..buffer.anchor_before(range_to_move.end),
7496 String::new(),
7497 ));
7498 let insertion_anchor = buffer.anchor_after(insertion_point);
7499 edits.push((insertion_anchor..insertion_anchor, text));
7500
7501 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7502
7503 // Move selections up
7504 new_selections.extend(contiguous_row_selections.drain(..).map(
7505 |mut selection| {
7506 selection.start.row -= row_delta;
7507 selection.end.row -= row_delta;
7508 selection
7509 },
7510 ));
7511
7512 // Move folds up
7513 unfold_ranges.push(range_to_move.clone());
7514 for fold in display_map.folds_in_range(
7515 buffer.anchor_before(range_to_move.start)
7516 ..buffer.anchor_after(range_to_move.end),
7517 ) {
7518 let mut start = fold.range.start.to_point(&buffer);
7519 let mut end = fold.range.end.to_point(&buffer);
7520 start.row -= row_delta;
7521 end.row -= row_delta;
7522 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7523 }
7524 }
7525 }
7526
7527 // If we didn't move line(s), preserve the existing selections
7528 new_selections.append(&mut contiguous_row_selections);
7529 }
7530
7531 self.transact(window, cx, |this, window, cx| {
7532 this.unfold_ranges(&unfold_ranges, true, true, cx);
7533 this.buffer.update(cx, |buffer, cx| {
7534 for (range, text) in edits {
7535 buffer.edit([(range, text)], None, cx);
7536 }
7537 });
7538 this.fold_creases(refold_creases, true, window, cx);
7539 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7540 s.select(new_selections);
7541 })
7542 });
7543 }
7544
7545 pub fn move_line_down(
7546 &mut self,
7547 _: &MoveLineDown,
7548 window: &mut Window,
7549 cx: &mut Context<Self>,
7550 ) {
7551 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7552 let buffer = self.buffer.read(cx).snapshot(cx);
7553
7554 let mut edits = Vec::new();
7555 let mut unfold_ranges = Vec::new();
7556 let mut refold_creases = Vec::new();
7557
7558 let selections = self.selections.all::<Point>(cx);
7559 let mut selections = selections.iter().peekable();
7560 let mut contiguous_row_selections = Vec::new();
7561 let mut new_selections = Vec::new();
7562
7563 while let Some(selection) = selections.next() {
7564 // Find all the selections that span a contiguous row range
7565 let (start_row, end_row) = consume_contiguous_rows(
7566 &mut contiguous_row_selections,
7567 selection,
7568 &display_map,
7569 &mut selections,
7570 );
7571
7572 // Move the text spanned by the row range to be after the last line of the row range
7573 if end_row.0 <= buffer.max_point().row {
7574 let range_to_move =
7575 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7576 let insertion_point = display_map
7577 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7578 .0;
7579
7580 // Don't move lines across excerpt boundaries
7581 if buffer
7582 .excerpt_containing(range_to_move.start..insertion_point)
7583 .is_some()
7584 {
7585 let mut text = String::from("\n");
7586 text.extend(buffer.text_for_range(range_to_move.clone()));
7587 text.pop(); // Drop trailing newline
7588 edits.push((
7589 buffer.anchor_after(range_to_move.start)
7590 ..buffer.anchor_before(range_to_move.end),
7591 String::new(),
7592 ));
7593 let insertion_anchor = buffer.anchor_after(insertion_point);
7594 edits.push((insertion_anchor..insertion_anchor, text));
7595
7596 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7597
7598 // Move selections down
7599 new_selections.extend(contiguous_row_selections.drain(..).map(
7600 |mut selection| {
7601 selection.start.row += row_delta;
7602 selection.end.row += row_delta;
7603 selection
7604 },
7605 ));
7606
7607 // Move folds down
7608 unfold_ranges.push(range_to_move.clone());
7609 for fold in display_map.folds_in_range(
7610 buffer.anchor_before(range_to_move.start)
7611 ..buffer.anchor_after(range_to_move.end),
7612 ) {
7613 let mut start = fold.range.start.to_point(&buffer);
7614 let mut end = fold.range.end.to_point(&buffer);
7615 start.row += row_delta;
7616 end.row += row_delta;
7617 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7618 }
7619 }
7620 }
7621
7622 // If we didn't move line(s), preserve the existing selections
7623 new_selections.append(&mut contiguous_row_selections);
7624 }
7625
7626 self.transact(window, cx, |this, window, cx| {
7627 this.unfold_ranges(&unfold_ranges, true, true, cx);
7628 this.buffer.update(cx, |buffer, cx| {
7629 for (range, text) in edits {
7630 buffer.edit([(range, text)], None, cx);
7631 }
7632 });
7633 this.fold_creases(refold_creases, true, window, cx);
7634 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7635 s.select(new_selections)
7636 });
7637 });
7638 }
7639
7640 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7641 let text_layout_details = &self.text_layout_details(window);
7642 self.transact(window, cx, |this, window, cx| {
7643 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7644 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7645 let line_mode = s.line_mode;
7646 s.move_with(|display_map, selection| {
7647 if !selection.is_empty() || line_mode {
7648 return;
7649 }
7650
7651 let mut head = selection.head();
7652 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7653 if head.column() == display_map.line_len(head.row()) {
7654 transpose_offset = display_map
7655 .buffer_snapshot
7656 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7657 }
7658
7659 if transpose_offset == 0 {
7660 return;
7661 }
7662
7663 *head.column_mut() += 1;
7664 head = display_map.clip_point(head, Bias::Right);
7665 let goal = SelectionGoal::HorizontalPosition(
7666 display_map
7667 .x_for_display_point(head, text_layout_details)
7668 .into(),
7669 );
7670 selection.collapse_to(head, goal);
7671
7672 let transpose_start = display_map
7673 .buffer_snapshot
7674 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7675 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7676 let transpose_end = display_map
7677 .buffer_snapshot
7678 .clip_offset(transpose_offset + 1, Bias::Right);
7679 if let Some(ch) =
7680 display_map.buffer_snapshot.chars_at(transpose_start).next()
7681 {
7682 edits.push((transpose_start..transpose_offset, String::new()));
7683 edits.push((transpose_end..transpose_end, ch.to_string()));
7684 }
7685 }
7686 });
7687 edits
7688 });
7689 this.buffer
7690 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7691 let selections = this.selections.all::<usize>(cx);
7692 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7693 s.select(selections);
7694 });
7695 });
7696 }
7697
7698 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7699 self.rewrap_impl(IsVimMode::No, cx)
7700 }
7701
7702 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7703 let buffer = self.buffer.read(cx).snapshot(cx);
7704 let selections = self.selections.all::<Point>(cx);
7705 let mut selections = selections.iter().peekable();
7706
7707 let mut edits = Vec::new();
7708 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7709
7710 while let Some(selection) = selections.next() {
7711 let mut start_row = selection.start.row;
7712 let mut end_row = selection.end.row;
7713
7714 // Skip selections that overlap with a range that has already been rewrapped.
7715 let selection_range = start_row..end_row;
7716 if rewrapped_row_ranges
7717 .iter()
7718 .any(|range| range.overlaps(&selection_range))
7719 {
7720 continue;
7721 }
7722
7723 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7724
7725 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7726 match language_scope.language_name().as_ref() {
7727 "Markdown" | "Plain Text" => {
7728 should_rewrap = true;
7729 }
7730 _ => {}
7731 }
7732 }
7733
7734 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7735
7736 // Since not all lines in the selection may be at the same indent
7737 // level, choose the indent size that is the most common between all
7738 // of the lines.
7739 //
7740 // If there is a tie, we use the deepest indent.
7741 let (indent_size, indent_end) = {
7742 let mut indent_size_occurrences = HashMap::default();
7743 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7744
7745 for row in start_row..=end_row {
7746 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7747 rows_by_indent_size.entry(indent).or_default().push(row);
7748 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7749 }
7750
7751 let indent_size = indent_size_occurrences
7752 .into_iter()
7753 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7754 .map(|(indent, _)| indent)
7755 .unwrap_or_default();
7756 let row = rows_by_indent_size[&indent_size][0];
7757 let indent_end = Point::new(row, indent_size.len);
7758
7759 (indent_size, indent_end)
7760 };
7761
7762 let mut line_prefix = indent_size.chars().collect::<String>();
7763
7764 if let Some(comment_prefix) =
7765 buffer
7766 .language_scope_at(selection.head())
7767 .and_then(|language| {
7768 language
7769 .line_comment_prefixes()
7770 .iter()
7771 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7772 .cloned()
7773 })
7774 {
7775 line_prefix.push_str(&comment_prefix);
7776 should_rewrap = true;
7777 }
7778
7779 if !should_rewrap {
7780 continue;
7781 }
7782
7783 if selection.is_empty() {
7784 'expand_upwards: while start_row > 0 {
7785 let prev_row = start_row - 1;
7786 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7787 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7788 {
7789 start_row = prev_row;
7790 } else {
7791 break 'expand_upwards;
7792 }
7793 }
7794
7795 'expand_downwards: while end_row < buffer.max_point().row {
7796 let next_row = end_row + 1;
7797 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7798 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7799 {
7800 end_row = next_row;
7801 } else {
7802 break 'expand_downwards;
7803 }
7804 }
7805 }
7806
7807 let start = Point::new(start_row, 0);
7808 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7809 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7810 let Some(lines_without_prefixes) = selection_text
7811 .lines()
7812 .map(|line| {
7813 line.strip_prefix(&line_prefix)
7814 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7815 .ok_or_else(|| {
7816 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7817 })
7818 })
7819 .collect::<Result<Vec<_>, _>>()
7820 .log_err()
7821 else {
7822 continue;
7823 };
7824
7825 let wrap_column = buffer
7826 .settings_at(Point::new(start_row, 0), cx)
7827 .preferred_line_length as usize;
7828 let wrapped_text = wrap_with_prefix(
7829 line_prefix,
7830 lines_without_prefixes.join(" "),
7831 wrap_column,
7832 tab_size,
7833 );
7834
7835 // TODO: should always use char-based diff while still supporting cursor behavior that
7836 // matches vim.
7837 let diff = match is_vim_mode {
7838 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7839 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7840 };
7841 let mut offset = start.to_offset(&buffer);
7842 let mut moved_since_edit = true;
7843
7844 for change in diff.iter_all_changes() {
7845 let value = change.value();
7846 match change.tag() {
7847 ChangeTag::Equal => {
7848 offset += value.len();
7849 moved_since_edit = true;
7850 }
7851 ChangeTag::Delete => {
7852 let start = buffer.anchor_after(offset);
7853 let end = buffer.anchor_before(offset + value.len());
7854
7855 if moved_since_edit {
7856 edits.push((start..end, String::new()));
7857 } else {
7858 edits.last_mut().unwrap().0.end = end;
7859 }
7860
7861 offset += value.len();
7862 moved_since_edit = false;
7863 }
7864 ChangeTag::Insert => {
7865 if moved_since_edit {
7866 let anchor = buffer.anchor_after(offset);
7867 edits.push((anchor..anchor, value.to_string()));
7868 } else {
7869 edits.last_mut().unwrap().1.push_str(value);
7870 }
7871
7872 moved_since_edit = false;
7873 }
7874 }
7875 }
7876
7877 rewrapped_row_ranges.push(start_row..=end_row);
7878 }
7879
7880 self.buffer
7881 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7882 }
7883
7884 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7885 let mut text = String::new();
7886 let buffer = self.buffer.read(cx).snapshot(cx);
7887 let mut selections = self.selections.all::<Point>(cx);
7888 let mut clipboard_selections = Vec::with_capacity(selections.len());
7889 {
7890 let max_point = buffer.max_point();
7891 let mut is_first = true;
7892 for selection in &mut selections {
7893 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7894 if is_entire_line {
7895 selection.start = Point::new(selection.start.row, 0);
7896 if !selection.is_empty() && selection.end.column == 0 {
7897 selection.end = cmp::min(max_point, selection.end);
7898 } else {
7899 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7900 }
7901 selection.goal = SelectionGoal::None;
7902 }
7903 if is_first {
7904 is_first = false;
7905 } else {
7906 text += "\n";
7907 }
7908 let mut len = 0;
7909 for chunk in buffer.text_for_range(selection.start..selection.end) {
7910 text.push_str(chunk);
7911 len += chunk.len();
7912 }
7913 clipboard_selections.push(ClipboardSelection {
7914 len,
7915 is_entire_line,
7916 first_line_indent: buffer
7917 .indent_size_for_line(MultiBufferRow(selection.start.row))
7918 .len,
7919 });
7920 }
7921 }
7922
7923 self.transact(window, cx, |this, window, cx| {
7924 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7925 s.select(selections);
7926 });
7927 this.insert("", window, cx);
7928 });
7929 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7930 }
7931
7932 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7933 let item = self.cut_common(window, cx);
7934 cx.write_to_clipboard(item);
7935 }
7936
7937 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7938 self.change_selections(None, window, cx, |s| {
7939 s.move_with(|snapshot, sel| {
7940 if sel.is_empty() {
7941 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7942 }
7943 });
7944 });
7945 let item = self.cut_common(window, cx);
7946 cx.set_global(KillRing(item))
7947 }
7948
7949 pub fn kill_ring_yank(
7950 &mut self,
7951 _: &KillRingYank,
7952 window: &mut Window,
7953 cx: &mut Context<Self>,
7954 ) {
7955 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7956 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7957 (kill_ring.text().to_string(), kill_ring.metadata_json())
7958 } else {
7959 return;
7960 }
7961 } else {
7962 return;
7963 };
7964 self.do_paste(&text, metadata, false, window, cx);
7965 }
7966
7967 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7968 let selections = self.selections.all::<Point>(cx);
7969 let buffer = self.buffer.read(cx).read(cx);
7970 let mut text = String::new();
7971
7972 let mut clipboard_selections = Vec::with_capacity(selections.len());
7973 {
7974 let max_point = buffer.max_point();
7975 let mut is_first = true;
7976 for selection in selections.iter() {
7977 let mut start = selection.start;
7978 let mut end = selection.end;
7979 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7980 if is_entire_line {
7981 start = Point::new(start.row, 0);
7982 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7983 }
7984 if is_first {
7985 is_first = false;
7986 } else {
7987 text += "\n";
7988 }
7989 let mut len = 0;
7990 for chunk in buffer.text_for_range(start..end) {
7991 text.push_str(chunk);
7992 len += chunk.len();
7993 }
7994 clipboard_selections.push(ClipboardSelection {
7995 len,
7996 is_entire_line,
7997 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7998 });
7999 }
8000 }
8001
8002 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8003 text,
8004 clipboard_selections,
8005 ));
8006 }
8007
8008 pub fn do_paste(
8009 &mut self,
8010 text: &String,
8011 clipboard_selections: Option<Vec<ClipboardSelection>>,
8012 handle_entire_lines: bool,
8013 window: &mut Window,
8014 cx: &mut Context<Self>,
8015 ) {
8016 if self.read_only(cx) {
8017 return;
8018 }
8019
8020 let clipboard_text = Cow::Borrowed(text);
8021
8022 self.transact(window, cx, |this, window, cx| {
8023 if let Some(mut clipboard_selections) = clipboard_selections {
8024 let old_selections = this.selections.all::<usize>(cx);
8025 let all_selections_were_entire_line =
8026 clipboard_selections.iter().all(|s| s.is_entire_line);
8027 let first_selection_indent_column =
8028 clipboard_selections.first().map(|s| s.first_line_indent);
8029 if clipboard_selections.len() != old_selections.len() {
8030 clipboard_selections.drain(..);
8031 }
8032 let cursor_offset = this.selections.last::<usize>(cx).head();
8033 let mut auto_indent_on_paste = true;
8034
8035 this.buffer.update(cx, |buffer, cx| {
8036 let snapshot = buffer.read(cx);
8037 auto_indent_on_paste =
8038 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8039
8040 let mut start_offset = 0;
8041 let mut edits = Vec::new();
8042 let mut original_indent_columns = Vec::new();
8043 for (ix, selection) in old_selections.iter().enumerate() {
8044 let to_insert;
8045 let entire_line;
8046 let original_indent_column;
8047 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8048 let end_offset = start_offset + clipboard_selection.len;
8049 to_insert = &clipboard_text[start_offset..end_offset];
8050 entire_line = clipboard_selection.is_entire_line;
8051 start_offset = end_offset + 1;
8052 original_indent_column = Some(clipboard_selection.first_line_indent);
8053 } else {
8054 to_insert = clipboard_text.as_str();
8055 entire_line = all_selections_were_entire_line;
8056 original_indent_column = first_selection_indent_column
8057 }
8058
8059 // If the corresponding selection was empty when this slice of the
8060 // clipboard text was written, then the entire line containing the
8061 // selection was copied. If this selection is also currently empty,
8062 // then paste the line before the current line of the buffer.
8063 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8064 let column = selection.start.to_point(&snapshot).column as usize;
8065 let line_start = selection.start - column;
8066 line_start..line_start
8067 } else {
8068 selection.range()
8069 };
8070
8071 edits.push((range, to_insert));
8072 original_indent_columns.extend(original_indent_column);
8073 }
8074 drop(snapshot);
8075
8076 buffer.edit(
8077 edits,
8078 if auto_indent_on_paste {
8079 Some(AutoindentMode::Block {
8080 original_indent_columns,
8081 })
8082 } else {
8083 None
8084 },
8085 cx,
8086 );
8087 });
8088
8089 let selections = this.selections.all::<usize>(cx);
8090 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8091 s.select(selections)
8092 });
8093 } else {
8094 this.insert(&clipboard_text, window, cx);
8095 }
8096 });
8097 }
8098
8099 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8100 if let Some(item) = cx.read_from_clipboard() {
8101 let entries = item.entries();
8102
8103 match entries.first() {
8104 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8105 // of all the pasted entries.
8106 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8107 .do_paste(
8108 clipboard_string.text(),
8109 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8110 true,
8111 window,
8112 cx,
8113 ),
8114 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8115 }
8116 }
8117 }
8118
8119 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8120 if self.read_only(cx) {
8121 return;
8122 }
8123
8124 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8125 if let Some((selections, _)) =
8126 self.selection_history.transaction(transaction_id).cloned()
8127 {
8128 self.change_selections(None, window, cx, |s| {
8129 s.select_anchors(selections.to_vec());
8130 });
8131 }
8132 self.request_autoscroll(Autoscroll::fit(), cx);
8133 self.unmark_text(window, cx);
8134 self.refresh_inline_completion(true, false, window, cx);
8135 cx.emit(EditorEvent::Edited { transaction_id });
8136 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8137 }
8138 }
8139
8140 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8141 if self.read_only(cx) {
8142 return;
8143 }
8144
8145 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8146 if let Some((_, Some(selections))) =
8147 self.selection_history.transaction(transaction_id).cloned()
8148 {
8149 self.change_selections(None, window, cx, |s| {
8150 s.select_anchors(selections.to_vec());
8151 });
8152 }
8153 self.request_autoscroll(Autoscroll::fit(), cx);
8154 self.unmark_text(window, cx);
8155 self.refresh_inline_completion(true, false, window, cx);
8156 cx.emit(EditorEvent::Edited { transaction_id });
8157 }
8158 }
8159
8160 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8161 self.buffer
8162 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8163 }
8164
8165 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8166 self.buffer
8167 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8168 }
8169
8170 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8171 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8172 let line_mode = s.line_mode;
8173 s.move_with(|map, selection| {
8174 let cursor = if selection.is_empty() && !line_mode {
8175 movement::left(map, selection.start)
8176 } else {
8177 selection.start
8178 };
8179 selection.collapse_to(cursor, SelectionGoal::None);
8180 });
8181 })
8182 }
8183
8184 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8185 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8186 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8187 })
8188 }
8189
8190 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8191 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8192 let line_mode = s.line_mode;
8193 s.move_with(|map, selection| {
8194 let cursor = if selection.is_empty() && !line_mode {
8195 movement::right(map, selection.end)
8196 } else {
8197 selection.end
8198 };
8199 selection.collapse_to(cursor, SelectionGoal::None)
8200 });
8201 })
8202 }
8203
8204 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8206 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8207 })
8208 }
8209
8210 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8211 if self.take_rename(true, window, cx).is_some() {
8212 return;
8213 }
8214
8215 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8216 cx.propagate();
8217 return;
8218 }
8219
8220 let text_layout_details = &self.text_layout_details(window);
8221 let selection_count = self.selections.count();
8222 let first_selection = self.selections.first_anchor();
8223
8224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8225 let line_mode = s.line_mode;
8226 s.move_with(|map, selection| {
8227 if !selection.is_empty() && !line_mode {
8228 selection.goal = SelectionGoal::None;
8229 }
8230 let (cursor, goal) = movement::up(
8231 map,
8232 selection.start,
8233 selection.goal,
8234 false,
8235 text_layout_details,
8236 );
8237 selection.collapse_to(cursor, goal);
8238 });
8239 });
8240
8241 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8242 {
8243 cx.propagate();
8244 }
8245 }
8246
8247 pub fn move_up_by_lines(
8248 &mut self,
8249 action: &MoveUpByLines,
8250 window: &mut Window,
8251 cx: &mut Context<Self>,
8252 ) {
8253 if self.take_rename(true, window, cx).is_some() {
8254 return;
8255 }
8256
8257 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8258 cx.propagate();
8259 return;
8260 }
8261
8262 let text_layout_details = &self.text_layout_details(window);
8263
8264 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8265 let line_mode = s.line_mode;
8266 s.move_with(|map, selection| {
8267 if !selection.is_empty() && !line_mode {
8268 selection.goal = SelectionGoal::None;
8269 }
8270 let (cursor, goal) = movement::up_by_rows(
8271 map,
8272 selection.start,
8273 action.lines,
8274 selection.goal,
8275 false,
8276 text_layout_details,
8277 );
8278 selection.collapse_to(cursor, goal);
8279 });
8280 })
8281 }
8282
8283 pub fn move_down_by_lines(
8284 &mut self,
8285 action: &MoveDownByLines,
8286 window: &mut Window,
8287 cx: &mut Context<Self>,
8288 ) {
8289 if self.take_rename(true, window, cx).is_some() {
8290 return;
8291 }
8292
8293 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8294 cx.propagate();
8295 return;
8296 }
8297
8298 let text_layout_details = &self.text_layout_details(window);
8299
8300 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8301 let line_mode = s.line_mode;
8302 s.move_with(|map, selection| {
8303 if !selection.is_empty() && !line_mode {
8304 selection.goal = SelectionGoal::None;
8305 }
8306 let (cursor, goal) = movement::down_by_rows(
8307 map,
8308 selection.start,
8309 action.lines,
8310 selection.goal,
8311 false,
8312 text_layout_details,
8313 );
8314 selection.collapse_to(cursor, goal);
8315 });
8316 })
8317 }
8318
8319 pub fn select_down_by_lines(
8320 &mut self,
8321 action: &SelectDownByLines,
8322 window: &mut Window,
8323 cx: &mut Context<Self>,
8324 ) {
8325 let text_layout_details = &self.text_layout_details(window);
8326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8327 s.move_heads_with(|map, head, goal| {
8328 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8329 })
8330 })
8331 }
8332
8333 pub fn select_up_by_lines(
8334 &mut self,
8335 action: &SelectUpByLines,
8336 window: &mut Window,
8337 cx: &mut Context<Self>,
8338 ) {
8339 let text_layout_details = &self.text_layout_details(window);
8340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8341 s.move_heads_with(|map, head, goal| {
8342 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8343 })
8344 })
8345 }
8346
8347 pub fn select_page_up(
8348 &mut self,
8349 _: &SelectPageUp,
8350 window: &mut Window,
8351 cx: &mut Context<Self>,
8352 ) {
8353 let Some(row_count) = self.visible_row_count() else {
8354 return;
8355 };
8356
8357 let text_layout_details = &self.text_layout_details(window);
8358
8359 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8360 s.move_heads_with(|map, head, goal| {
8361 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8362 })
8363 })
8364 }
8365
8366 pub fn move_page_up(
8367 &mut self,
8368 action: &MovePageUp,
8369 window: &mut Window,
8370 cx: &mut Context<Self>,
8371 ) {
8372 if self.take_rename(true, window, cx).is_some() {
8373 return;
8374 }
8375
8376 if self
8377 .context_menu
8378 .borrow_mut()
8379 .as_mut()
8380 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8381 .unwrap_or(false)
8382 {
8383 return;
8384 }
8385
8386 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8387 cx.propagate();
8388 return;
8389 }
8390
8391 let Some(row_count) = self.visible_row_count() else {
8392 return;
8393 };
8394
8395 let autoscroll = if action.center_cursor {
8396 Autoscroll::center()
8397 } else {
8398 Autoscroll::fit()
8399 };
8400
8401 let text_layout_details = &self.text_layout_details(window);
8402
8403 self.change_selections(Some(autoscroll), window, cx, |s| {
8404 let line_mode = s.line_mode;
8405 s.move_with(|map, selection| {
8406 if !selection.is_empty() && !line_mode {
8407 selection.goal = SelectionGoal::None;
8408 }
8409 let (cursor, goal) = movement::up_by_rows(
8410 map,
8411 selection.end,
8412 row_count,
8413 selection.goal,
8414 false,
8415 text_layout_details,
8416 );
8417 selection.collapse_to(cursor, goal);
8418 });
8419 });
8420 }
8421
8422 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8423 let text_layout_details = &self.text_layout_details(window);
8424 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8425 s.move_heads_with(|map, head, goal| {
8426 movement::up(map, head, goal, false, text_layout_details)
8427 })
8428 })
8429 }
8430
8431 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8432 self.take_rename(true, window, cx);
8433
8434 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8435 cx.propagate();
8436 return;
8437 }
8438
8439 let text_layout_details = &self.text_layout_details(window);
8440 let selection_count = self.selections.count();
8441 let first_selection = self.selections.first_anchor();
8442
8443 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8444 let line_mode = s.line_mode;
8445 s.move_with(|map, selection| {
8446 if !selection.is_empty() && !line_mode {
8447 selection.goal = SelectionGoal::None;
8448 }
8449 let (cursor, goal) = movement::down(
8450 map,
8451 selection.end,
8452 selection.goal,
8453 false,
8454 text_layout_details,
8455 );
8456 selection.collapse_to(cursor, goal);
8457 });
8458 });
8459
8460 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8461 {
8462 cx.propagate();
8463 }
8464 }
8465
8466 pub fn select_page_down(
8467 &mut self,
8468 _: &SelectPageDown,
8469 window: &mut Window,
8470 cx: &mut Context<Self>,
8471 ) {
8472 let Some(row_count) = self.visible_row_count() else {
8473 return;
8474 };
8475
8476 let text_layout_details = &self.text_layout_details(window);
8477
8478 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8479 s.move_heads_with(|map, head, goal| {
8480 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8481 })
8482 })
8483 }
8484
8485 pub fn move_page_down(
8486 &mut self,
8487 action: &MovePageDown,
8488 window: &mut Window,
8489 cx: &mut Context<Self>,
8490 ) {
8491 if self.take_rename(true, window, cx).is_some() {
8492 return;
8493 }
8494
8495 if self
8496 .context_menu
8497 .borrow_mut()
8498 .as_mut()
8499 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8500 .unwrap_or(false)
8501 {
8502 return;
8503 }
8504
8505 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8506 cx.propagate();
8507 return;
8508 }
8509
8510 let Some(row_count) = self.visible_row_count() else {
8511 return;
8512 };
8513
8514 let autoscroll = if action.center_cursor {
8515 Autoscroll::center()
8516 } else {
8517 Autoscroll::fit()
8518 };
8519
8520 let text_layout_details = &self.text_layout_details(window);
8521 self.change_selections(Some(autoscroll), window, cx, |s| {
8522 let line_mode = s.line_mode;
8523 s.move_with(|map, selection| {
8524 if !selection.is_empty() && !line_mode {
8525 selection.goal = SelectionGoal::None;
8526 }
8527 let (cursor, goal) = movement::down_by_rows(
8528 map,
8529 selection.end,
8530 row_count,
8531 selection.goal,
8532 false,
8533 text_layout_details,
8534 );
8535 selection.collapse_to(cursor, goal);
8536 });
8537 });
8538 }
8539
8540 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8541 let text_layout_details = &self.text_layout_details(window);
8542 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8543 s.move_heads_with(|map, head, goal| {
8544 movement::down(map, head, goal, false, text_layout_details)
8545 })
8546 });
8547 }
8548
8549 pub fn context_menu_first(
8550 &mut self,
8551 _: &ContextMenuFirst,
8552 _window: &mut Window,
8553 cx: &mut Context<Self>,
8554 ) {
8555 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8556 context_menu.select_first(self.completion_provider.as_deref(), cx);
8557 }
8558 }
8559
8560 pub fn context_menu_prev(
8561 &mut self,
8562 _: &ContextMenuPrev,
8563 _window: &mut Window,
8564 cx: &mut Context<Self>,
8565 ) {
8566 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8567 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8568 }
8569 }
8570
8571 pub fn context_menu_next(
8572 &mut self,
8573 _: &ContextMenuNext,
8574 _window: &mut Window,
8575 cx: &mut Context<Self>,
8576 ) {
8577 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8578 context_menu.select_next(self.completion_provider.as_deref(), cx);
8579 }
8580 }
8581
8582 pub fn context_menu_last(
8583 &mut self,
8584 _: &ContextMenuLast,
8585 _window: &mut Window,
8586 cx: &mut Context<Self>,
8587 ) {
8588 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8589 context_menu.select_last(self.completion_provider.as_deref(), cx);
8590 }
8591 }
8592
8593 pub fn move_to_previous_word_start(
8594 &mut self,
8595 _: &MoveToPreviousWordStart,
8596 window: &mut Window,
8597 cx: &mut Context<Self>,
8598 ) {
8599 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8600 s.move_cursors_with(|map, head, _| {
8601 (
8602 movement::previous_word_start(map, head),
8603 SelectionGoal::None,
8604 )
8605 });
8606 })
8607 }
8608
8609 pub fn move_to_previous_subword_start(
8610 &mut self,
8611 _: &MoveToPreviousSubwordStart,
8612 window: &mut Window,
8613 cx: &mut Context<Self>,
8614 ) {
8615 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8616 s.move_cursors_with(|map, head, _| {
8617 (
8618 movement::previous_subword_start(map, head),
8619 SelectionGoal::None,
8620 )
8621 });
8622 })
8623 }
8624
8625 pub fn select_to_previous_word_start(
8626 &mut self,
8627 _: &SelectToPreviousWordStart,
8628 window: &mut Window,
8629 cx: &mut Context<Self>,
8630 ) {
8631 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8632 s.move_heads_with(|map, head, _| {
8633 (
8634 movement::previous_word_start(map, head),
8635 SelectionGoal::None,
8636 )
8637 });
8638 })
8639 }
8640
8641 pub fn select_to_previous_subword_start(
8642 &mut self,
8643 _: &SelectToPreviousSubwordStart,
8644 window: &mut Window,
8645 cx: &mut Context<Self>,
8646 ) {
8647 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8648 s.move_heads_with(|map, head, _| {
8649 (
8650 movement::previous_subword_start(map, head),
8651 SelectionGoal::None,
8652 )
8653 });
8654 })
8655 }
8656
8657 pub fn delete_to_previous_word_start(
8658 &mut self,
8659 action: &DeleteToPreviousWordStart,
8660 window: &mut Window,
8661 cx: &mut Context<Self>,
8662 ) {
8663 self.transact(window, cx, |this, window, cx| {
8664 this.select_autoclose_pair(window, cx);
8665 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8666 let line_mode = s.line_mode;
8667 s.move_with(|map, selection| {
8668 if selection.is_empty() && !line_mode {
8669 let cursor = if action.ignore_newlines {
8670 movement::previous_word_start(map, selection.head())
8671 } else {
8672 movement::previous_word_start_or_newline(map, selection.head())
8673 };
8674 selection.set_head(cursor, SelectionGoal::None);
8675 }
8676 });
8677 });
8678 this.insert("", window, cx);
8679 });
8680 }
8681
8682 pub fn delete_to_previous_subword_start(
8683 &mut self,
8684 _: &DeleteToPreviousSubwordStart,
8685 window: &mut Window,
8686 cx: &mut Context<Self>,
8687 ) {
8688 self.transact(window, cx, |this, window, cx| {
8689 this.select_autoclose_pair(window, cx);
8690 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8691 let line_mode = s.line_mode;
8692 s.move_with(|map, selection| {
8693 if selection.is_empty() && !line_mode {
8694 let cursor = movement::previous_subword_start(map, selection.head());
8695 selection.set_head(cursor, SelectionGoal::None);
8696 }
8697 });
8698 });
8699 this.insert("", window, cx);
8700 });
8701 }
8702
8703 pub fn move_to_next_word_end(
8704 &mut self,
8705 _: &MoveToNextWordEnd,
8706 window: &mut Window,
8707 cx: &mut Context<Self>,
8708 ) {
8709 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8710 s.move_cursors_with(|map, head, _| {
8711 (movement::next_word_end(map, head), SelectionGoal::None)
8712 });
8713 })
8714 }
8715
8716 pub fn move_to_next_subword_end(
8717 &mut self,
8718 _: &MoveToNextSubwordEnd,
8719 window: &mut Window,
8720 cx: &mut Context<Self>,
8721 ) {
8722 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8723 s.move_cursors_with(|map, head, _| {
8724 (movement::next_subword_end(map, head), SelectionGoal::None)
8725 });
8726 })
8727 }
8728
8729 pub fn select_to_next_word_end(
8730 &mut self,
8731 _: &SelectToNextWordEnd,
8732 window: &mut Window,
8733 cx: &mut Context<Self>,
8734 ) {
8735 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8736 s.move_heads_with(|map, head, _| {
8737 (movement::next_word_end(map, head), SelectionGoal::None)
8738 });
8739 })
8740 }
8741
8742 pub fn select_to_next_subword_end(
8743 &mut self,
8744 _: &SelectToNextSubwordEnd,
8745 window: &mut Window,
8746 cx: &mut Context<Self>,
8747 ) {
8748 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8749 s.move_heads_with(|map, head, _| {
8750 (movement::next_subword_end(map, head), SelectionGoal::None)
8751 });
8752 })
8753 }
8754
8755 pub fn delete_to_next_word_end(
8756 &mut self,
8757 action: &DeleteToNextWordEnd,
8758 window: &mut Window,
8759 cx: &mut Context<Self>,
8760 ) {
8761 self.transact(window, cx, |this, window, cx| {
8762 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8763 let line_mode = s.line_mode;
8764 s.move_with(|map, selection| {
8765 if selection.is_empty() && !line_mode {
8766 let cursor = if action.ignore_newlines {
8767 movement::next_word_end(map, selection.head())
8768 } else {
8769 movement::next_word_end_or_newline(map, selection.head())
8770 };
8771 selection.set_head(cursor, SelectionGoal::None);
8772 }
8773 });
8774 });
8775 this.insert("", window, cx);
8776 });
8777 }
8778
8779 pub fn delete_to_next_subword_end(
8780 &mut self,
8781 _: &DeleteToNextSubwordEnd,
8782 window: &mut Window,
8783 cx: &mut Context<Self>,
8784 ) {
8785 self.transact(window, cx, |this, window, cx| {
8786 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8787 s.move_with(|map, selection| {
8788 if selection.is_empty() {
8789 let cursor = movement::next_subword_end(map, selection.head());
8790 selection.set_head(cursor, SelectionGoal::None);
8791 }
8792 });
8793 });
8794 this.insert("", window, cx);
8795 });
8796 }
8797
8798 pub fn move_to_beginning_of_line(
8799 &mut self,
8800 action: &MoveToBeginningOfLine,
8801 window: &mut Window,
8802 cx: &mut Context<Self>,
8803 ) {
8804 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8805 s.move_cursors_with(|map, head, _| {
8806 (
8807 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8808 SelectionGoal::None,
8809 )
8810 });
8811 })
8812 }
8813
8814 pub fn select_to_beginning_of_line(
8815 &mut self,
8816 action: &SelectToBeginningOfLine,
8817 window: &mut Window,
8818 cx: &mut Context<Self>,
8819 ) {
8820 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8821 s.move_heads_with(|map, head, _| {
8822 (
8823 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8824 SelectionGoal::None,
8825 )
8826 });
8827 });
8828 }
8829
8830 pub fn delete_to_beginning_of_line(
8831 &mut self,
8832 _: &DeleteToBeginningOfLine,
8833 window: &mut Window,
8834 cx: &mut Context<Self>,
8835 ) {
8836 self.transact(window, cx, |this, window, cx| {
8837 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8838 s.move_with(|_, selection| {
8839 selection.reversed = true;
8840 });
8841 });
8842
8843 this.select_to_beginning_of_line(
8844 &SelectToBeginningOfLine {
8845 stop_at_soft_wraps: false,
8846 },
8847 window,
8848 cx,
8849 );
8850 this.backspace(&Backspace, window, cx);
8851 });
8852 }
8853
8854 pub fn move_to_end_of_line(
8855 &mut self,
8856 action: &MoveToEndOfLine,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) {
8860 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8861 s.move_cursors_with(|map, head, _| {
8862 (
8863 movement::line_end(map, head, action.stop_at_soft_wraps),
8864 SelectionGoal::None,
8865 )
8866 });
8867 })
8868 }
8869
8870 pub fn select_to_end_of_line(
8871 &mut self,
8872 action: &SelectToEndOfLine,
8873 window: &mut Window,
8874 cx: &mut Context<Self>,
8875 ) {
8876 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8877 s.move_heads_with(|map, head, _| {
8878 (
8879 movement::line_end(map, head, action.stop_at_soft_wraps),
8880 SelectionGoal::None,
8881 )
8882 });
8883 })
8884 }
8885
8886 pub fn delete_to_end_of_line(
8887 &mut self,
8888 _: &DeleteToEndOfLine,
8889 window: &mut Window,
8890 cx: &mut Context<Self>,
8891 ) {
8892 self.transact(window, cx, |this, window, cx| {
8893 this.select_to_end_of_line(
8894 &SelectToEndOfLine {
8895 stop_at_soft_wraps: false,
8896 },
8897 window,
8898 cx,
8899 );
8900 this.delete(&Delete, window, cx);
8901 });
8902 }
8903
8904 pub fn cut_to_end_of_line(
8905 &mut self,
8906 _: &CutToEndOfLine,
8907 window: &mut Window,
8908 cx: &mut Context<Self>,
8909 ) {
8910 self.transact(window, cx, |this, window, cx| {
8911 this.select_to_end_of_line(
8912 &SelectToEndOfLine {
8913 stop_at_soft_wraps: false,
8914 },
8915 window,
8916 cx,
8917 );
8918 this.cut(&Cut, window, cx);
8919 });
8920 }
8921
8922 pub fn move_to_start_of_paragraph(
8923 &mut self,
8924 _: &MoveToStartOfParagraph,
8925 window: &mut Window,
8926 cx: &mut Context<Self>,
8927 ) {
8928 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8929 cx.propagate();
8930 return;
8931 }
8932
8933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8934 s.move_with(|map, selection| {
8935 selection.collapse_to(
8936 movement::start_of_paragraph(map, selection.head(), 1),
8937 SelectionGoal::None,
8938 )
8939 });
8940 })
8941 }
8942
8943 pub fn move_to_end_of_paragraph(
8944 &mut self,
8945 _: &MoveToEndOfParagraph,
8946 window: &mut Window,
8947 cx: &mut Context<Self>,
8948 ) {
8949 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8950 cx.propagate();
8951 return;
8952 }
8953
8954 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8955 s.move_with(|map, selection| {
8956 selection.collapse_to(
8957 movement::end_of_paragraph(map, selection.head(), 1),
8958 SelectionGoal::None,
8959 )
8960 });
8961 })
8962 }
8963
8964 pub fn select_to_start_of_paragraph(
8965 &mut self,
8966 _: &SelectToStartOfParagraph,
8967 window: &mut Window,
8968 cx: &mut Context<Self>,
8969 ) {
8970 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8971 cx.propagate();
8972 return;
8973 }
8974
8975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8976 s.move_heads_with(|map, head, _| {
8977 (
8978 movement::start_of_paragraph(map, head, 1),
8979 SelectionGoal::None,
8980 )
8981 });
8982 })
8983 }
8984
8985 pub fn select_to_end_of_paragraph(
8986 &mut self,
8987 _: &SelectToEndOfParagraph,
8988 window: &mut Window,
8989 cx: &mut Context<Self>,
8990 ) {
8991 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8992 cx.propagate();
8993 return;
8994 }
8995
8996 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8997 s.move_heads_with(|map, head, _| {
8998 (
8999 movement::end_of_paragraph(map, head, 1),
9000 SelectionGoal::None,
9001 )
9002 });
9003 })
9004 }
9005
9006 pub fn move_to_beginning(
9007 &mut self,
9008 _: &MoveToBeginning,
9009 window: &mut Window,
9010 cx: &mut Context<Self>,
9011 ) {
9012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9013 cx.propagate();
9014 return;
9015 }
9016
9017 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9018 s.select_ranges(vec![0..0]);
9019 });
9020 }
9021
9022 pub fn select_to_beginning(
9023 &mut self,
9024 _: &SelectToBeginning,
9025 window: &mut Window,
9026 cx: &mut Context<Self>,
9027 ) {
9028 let mut selection = self.selections.last::<Point>(cx);
9029 selection.set_head(Point::zero(), SelectionGoal::None);
9030
9031 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9032 s.select(vec![selection]);
9033 });
9034 }
9035
9036 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9037 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9038 cx.propagate();
9039 return;
9040 }
9041
9042 let cursor = self.buffer.read(cx).read(cx).len();
9043 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9044 s.select_ranges(vec![cursor..cursor])
9045 });
9046 }
9047
9048 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9049 self.nav_history = nav_history;
9050 }
9051
9052 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9053 self.nav_history.as_ref()
9054 }
9055
9056 fn push_to_nav_history(
9057 &mut self,
9058 cursor_anchor: Anchor,
9059 new_position: Option<Point>,
9060 cx: &mut Context<Self>,
9061 ) {
9062 if let Some(nav_history) = self.nav_history.as_mut() {
9063 let buffer = self.buffer.read(cx).read(cx);
9064 let cursor_position = cursor_anchor.to_point(&buffer);
9065 let scroll_state = self.scroll_manager.anchor();
9066 let scroll_top_row = scroll_state.top_row(&buffer);
9067 drop(buffer);
9068
9069 if let Some(new_position) = new_position {
9070 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9071 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9072 return;
9073 }
9074 }
9075
9076 nav_history.push(
9077 Some(NavigationData {
9078 cursor_anchor,
9079 cursor_position,
9080 scroll_anchor: scroll_state,
9081 scroll_top_row,
9082 }),
9083 cx,
9084 );
9085 }
9086 }
9087
9088 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9089 let buffer = self.buffer.read(cx).snapshot(cx);
9090 let mut selection = self.selections.first::<usize>(cx);
9091 selection.set_head(buffer.len(), SelectionGoal::None);
9092 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9093 s.select(vec![selection]);
9094 });
9095 }
9096
9097 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9098 let end = self.buffer.read(cx).read(cx).len();
9099 self.change_selections(None, window, cx, |s| {
9100 s.select_ranges(vec![0..end]);
9101 });
9102 }
9103
9104 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9106 let mut selections = self.selections.all::<Point>(cx);
9107 let max_point = display_map.buffer_snapshot.max_point();
9108 for selection in &mut selections {
9109 let rows = selection.spanned_rows(true, &display_map);
9110 selection.start = Point::new(rows.start.0, 0);
9111 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9112 selection.reversed = false;
9113 }
9114 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9115 s.select(selections);
9116 });
9117 }
9118
9119 pub fn split_selection_into_lines(
9120 &mut self,
9121 _: &SplitSelectionIntoLines,
9122 window: &mut Window,
9123 cx: &mut Context<Self>,
9124 ) {
9125 let selections = self
9126 .selections
9127 .all::<Point>(cx)
9128 .into_iter()
9129 .map(|selection| selection.start..selection.end)
9130 .collect::<Vec<_>>();
9131 self.unfold_ranges(&selections, true, true, cx);
9132
9133 let mut new_selection_ranges = Vec::new();
9134 {
9135 let buffer = self.buffer.read(cx).read(cx);
9136 for selection in selections {
9137 for row in selection.start.row..selection.end.row {
9138 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9139 new_selection_ranges.push(cursor..cursor);
9140 }
9141
9142 let is_multiline_selection = selection.start.row != selection.end.row;
9143 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9144 // so this action feels more ergonomic when paired with other selection operations
9145 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9146 if !should_skip_last {
9147 new_selection_ranges.push(selection.end..selection.end);
9148 }
9149 }
9150 }
9151 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9152 s.select_ranges(new_selection_ranges);
9153 });
9154 }
9155
9156 pub fn add_selection_above(
9157 &mut self,
9158 _: &AddSelectionAbove,
9159 window: &mut Window,
9160 cx: &mut Context<Self>,
9161 ) {
9162 self.add_selection(true, window, cx);
9163 }
9164
9165 pub fn add_selection_below(
9166 &mut self,
9167 _: &AddSelectionBelow,
9168 window: &mut Window,
9169 cx: &mut Context<Self>,
9170 ) {
9171 self.add_selection(false, window, cx);
9172 }
9173
9174 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9175 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9176 let mut selections = self.selections.all::<Point>(cx);
9177 let text_layout_details = self.text_layout_details(window);
9178 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9179 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9180 let range = oldest_selection.display_range(&display_map).sorted();
9181
9182 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9183 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9184 let positions = start_x.min(end_x)..start_x.max(end_x);
9185
9186 selections.clear();
9187 let mut stack = Vec::new();
9188 for row in range.start.row().0..=range.end.row().0 {
9189 if let Some(selection) = self.selections.build_columnar_selection(
9190 &display_map,
9191 DisplayRow(row),
9192 &positions,
9193 oldest_selection.reversed,
9194 &text_layout_details,
9195 ) {
9196 stack.push(selection.id);
9197 selections.push(selection);
9198 }
9199 }
9200
9201 if above {
9202 stack.reverse();
9203 }
9204
9205 AddSelectionsState { above, stack }
9206 });
9207
9208 let last_added_selection = *state.stack.last().unwrap();
9209 let mut new_selections = Vec::new();
9210 if above == state.above {
9211 let end_row = if above {
9212 DisplayRow(0)
9213 } else {
9214 display_map.max_point().row()
9215 };
9216
9217 'outer: for selection in selections {
9218 if selection.id == last_added_selection {
9219 let range = selection.display_range(&display_map).sorted();
9220 debug_assert_eq!(range.start.row(), range.end.row());
9221 let mut row = range.start.row();
9222 let positions =
9223 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9224 px(start)..px(end)
9225 } else {
9226 let start_x =
9227 display_map.x_for_display_point(range.start, &text_layout_details);
9228 let end_x =
9229 display_map.x_for_display_point(range.end, &text_layout_details);
9230 start_x.min(end_x)..start_x.max(end_x)
9231 };
9232
9233 while row != end_row {
9234 if above {
9235 row.0 -= 1;
9236 } else {
9237 row.0 += 1;
9238 }
9239
9240 if let Some(new_selection) = self.selections.build_columnar_selection(
9241 &display_map,
9242 row,
9243 &positions,
9244 selection.reversed,
9245 &text_layout_details,
9246 ) {
9247 state.stack.push(new_selection.id);
9248 if above {
9249 new_selections.push(new_selection);
9250 new_selections.push(selection);
9251 } else {
9252 new_selections.push(selection);
9253 new_selections.push(new_selection);
9254 }
9255
9256 continue 'outer;
9257 }
9258 }
9259 }
9260
9261 new_selections.push(selection);
9262 }
9263 } else {
9264 new_selections = selections;
9265 new_selections.retain(|s| s.id != last_added_selection);
9266 state.stack.pop();
9267 }
9268
9269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9270 s.select(new_selections);
9271 });
9272 if state.stack.len() > 1 {
9273 self.add_selections_state = Some(state);
9274 }
9275 }
9276
9277 pub fn select_next_match_internal(
9278 &mut self,
9279 display_map: &DisplaySnapshot,
9280 replace_newest: bool,
9281 autoscroll: Option<Autoscroll>,
9282 window: &mut Window,
9283 cx: &mut Context<Self>,
9284 ) -> Result<()> {
9285 fn select_next_match_ranges(
9286 this: &mut Editor,
9287 range: Range<usize>,
9288 replace_newest: bool,
9289 auto_scroll: Option<Autoscroll>,
9290 window: &mut Window,
9291 cx: &mut Context<Editor>,
9292 ) {
9293 this.unfold_ranges(&[range.clone()], false, true, cx);
9294 this.change_selections(auto_scroll, window, cx, |s| {
9295 if replace_newest {
9296 s.delete(s.newest_anchor().id);
9297 }
9298 s.insert_range(range.clone());
9299 });
9300 }
9301
9302 let buffer = &display_map.buffer_snapshot;
9303 let mut selections = self.selections.all::<usize>(cx);
9304 if let Some(mut select_next_state) = self.select_next_state.take() {
9305 let query = &select_next_state.query;
9306 if !select_next_state.done {
9307 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9308 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9309 let mut next_selected_range = None;
9310
9311 let bytes_after_last_selection =
9312 buffer.bytes_in_range(last_selection.end..buffer.len());
9313 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9314 let query_matches = query
9315 .stream_find_iter(bytes_after_last_selection)
9316 .map(|result| (last_selection.end, result))
9317 .chain(
9318 query
9319 .stream_find_iter(bytes_before_first_selection)
9320 .map(|result| (0, result)),
9321 );
9322
9323 for (start_offset, query_match) in query_matches {
9324 let query_match = query_match.unwrap(); // can only fail due to I/O
9325 let offset_range =
9326 start_offset + query_match.start()..start_offset + query_match.end();
9327 let display_range = offset_range.start.to_display_point(display_map)
9328 ..offset_range.end.to_display_point(display_map);
9329
9330 if !select_next_state.wordwise
9331 || (!movement::is_inside_word(display_map, display_range.start)
9332 && !movement::is_inside_word(display_map, display_range.end))
9333 {
9334 // TODO: This is n^2, because we might check all the selections
9335 if !selections
9336 .iter()
9337 .any(|selection| selection.range().overlaps(&offset_range))
9338 {
9339 next_selected_range = Some(offset_range);
9340 break;
9341 }
9342 }
9343 }
9344
9345 if let Some(next_selected_range) = next_selected_range {
9346 select_next_match_ranges(
9347 self,
9348 next_selected_range,
9349 replace_newest,
9350 autoscroll,
9351 window,
9352 cx,
9353 );
9354 } else {
9355 select_next_state.done = true;
9356 }
9357 }
9358
9359 self.select_next_state = Some(select_next_state);
9360 } else {
9361 let mut only_carets = true;
9362 let mut same_text_selected = true;
9363 let mut selected_text = None;
9364
9365 let mut selections_iter = selections.iter().peekable();
9366 while let Some(selection) = selections_iter.next() {
9367 if selection.start != selection.end {
9368 only_carets = false;
9369 }
9370
9371 if same_text_selected {
9372 if selected_text.is_none() {
9373 selected_text =
9374 Some(buffer.text_for_range(selection.range()).collect::<String>());
9375 }
9376
9377 if let Some(next_selection) = selections_iter.peek() {
9378 if next_selection.range().len() == selection.range().len() {
9379 let next_selected_text = buffer
9380 .text_for_range(next_selection.range())
9381 .collect::<String>();
9382 if Some(next_selected_text) != selected_text {
9383 same_text_selected = false;
9384 selected_text = None;
9385 }
9386 } else {
9387 same_text_selected = false;
9388 selected_text = None;
9389 }
9390 }
9391 }
9392 }
9393
9394 if only_carets {
9395 for selection in &mut selections {
9396 let word_range = movement::surrounding_word(
9397 display_map,
9398 selection.start.to_display_point(display_map),
9399 );
9400 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9401 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9402 selection.goal = SelectionGoal::None;
9403 selection.reversed = false;
9404 select_next_match_ranges(
9405 self,
9406 selection.start..selection.end,
9407 replace_newest,
9408 autoscroll,
9409 window,
9410 cx,
9411 );
9412 }
9413
9414 if selections.len() == 1 {
9415 let selection = selections
9416 .last()
9417 .expect("ensured that there's only one selection");
9418 let query = buffer
9419 .text_for_range(selection.start..selection.end)
9420 .collect::<String>();
9421 let is_empty = query.is_empty();
9422 let select_state = SelectNextState {
9423 query: AhoCorasick::new(&[query])?,
9424 wordwise: true,
9425 done: is_empty,
9426 };
9427 self.select_next_state = Some(select_state);
9428 } else {
9429 self.select_next_state = None;
9430 }
9431 } else if let Some(selected_text) = selected_text {
9432 self.select_next_state = Some(SelectNextState {
9433 query: AhoCorasick::new(&[selected_text])?,
9434 wordwise: false,
9435 done: false,
9436 });
9437 self.select_next_match_internal(
9438 display_map,
9439 replace_newest,
9440 autoscroll,
9441 window,
9442 cx,
9443 )?;
9444 }
9445 }
9446 Ok(())
9447 }
9448
9449 pub fn select_all_matches(
9450 &mut self,
9451 _action: &SelectAllMatches,
9452 window: &mut Window,
9453 cx: &mut Context<Self>,
9454 ) -> Result<()> {
9455 self.push_to_selection_history();
9456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9457
9458 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9459 let Some(select_next_state) = self.select_next_state.as_mut() else {
9460 return Ok(());
9461 };
9462 if select_next_state.done {
9463 return Ok(());
9464 }
9465
9466 let mut new_selections = self.selections.all::<usize>(cx);
9467
9468 let buffer = &display_map.buffer_snapshot;
9469 let query_matches = select_next_state
9470 .query
9471 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9472
9473 for query_match in query_matches {
9474 let query_match = query_match.unwrap(); // can only fail due to I/O
9475 let offset_range = query_match.start()..query_match.end();
9476 let display_range = offset_range.start.to_display_point(&display_map)
9477 ..offset_range.end.to_display_point(&display_map);
9478
9479 if !select_next_state.wordwise
9480 || (!movement::is_inside_word(&display_map, display_range.start)
9481 && !movement::is_inside_word(&display_map, display_range.end))
9482 {
9483 self.selections.change_with(cx, |selections| {
9484 new_selections.push(Selection {
9485 id: selections.new_selection_id(),
9486 start: offset_range.start,
9487 end: offset_range.end,
9488 reversed: false,
9489 goal: SelectionGoal::None,
9490 });
9491 });
9492 }
9493 }
9494
9495 new_selections.sort_by_key(|selection| selection.start);
9496 let mut ix = 0;
9497 while ix + 1 < new_selections.len() {
9498 let current_selection = &new_selections[ix];
9499 let next_selection = &new_selections[ix + 1];
9500 if current_selection.range().overlaps(&next_selection.range()) {
9501 if current_selection.id < next_selection.id {
9502 new_selections.remove(ix + 1);
9503 } else {
9504 new_selections.remove(ix);
9505 }
9506 } else {
9507 ix += 1;
9508 }
9509 }
9510
9511 let reversed = self.selections.oldest::<usize>(cx).reversed;
9512
9513 for selection in new_selections.iter_mut() {
9514 selection.reversed = reversed;
9515 }
9516
9517 select_next_state.done = true;
9518 self.unfold_ranges(
9519 &new_selections
9520 .iter()
9521 .map(|selection| selection.range())
9522 .collect::<Vec<_>>(),
9523 false,
9524 false,
9525 cx,
9526 );
9527 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9528 selections.select(new_selections)
9529 });
9530
9531 Ok(())
9532 }
9533
9534 pub fn select_next(
9535 &mut self,
9536 action: &SelectNext,
9537 window: &mut Window,
9538 cx: &mut Context<Self>,
9539 ) -> Result<()> {
9540 self.push_to_selection_history();
9541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9542 self.select_next_match_internal(
9543 &display_map,
9544 action.replace_newest,
9545 Some(Autoscroll::newest()),
9546 window,
9547 cx,
9548 )?;
9549 Ok(())
9550 }
9551
9552 pub fn select_previous(
9553 &mut self,
9554 action: &SelectPrevious,
9555 window: &mut Window,
9556 cx: &mut Context<Self>,
9557 ) -> Result<()> {
9558 self.push_to_selection_history();
9559 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9560 let buffer = &display_map.buffer_snapshot;
9561 let mut selections = self.selections.all::<usize>(cx);
9562 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9563 let query = &select_prev_state.query;
9564 if !select_prev_state.done {
9565 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9566 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9567 let mut next_selected_range = None;
9568 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9569 let bytes_before_last_selection =
9570 buffer.reversed_bytes_in_range(0..last_selection.start);
9571 let bytes_after_first_selection =
9572 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9573 let query_matches = query
9574 .stream_find_iter(bytes_before_last_selection)
9575 .map(|result| (last_selection.start, result))
9576 .chain(
9577 query
9578 .stream_find_iter(bytes_after_first_selection)
9579 .map(|result| (buffer.len(), result)),
9580 );
9581 for (end_offset, query_match) in query_matches {
9582 let query_match = query_match.unwrap(); // can only fail due to I/O
9583 let offset_range =
9584 end_offset - query_match.end()..end_offset - query_match.start();
9585 let display_range = offset_range.start.to_display_point(&display_map)
9586 ..offset_range.end.to_display_point(&display_map);
9587
9588 if !select_prev_state.wordwise
9589 || (!movement::is_inside_word(&display_map, display_range.start)
9590 && !movement::is_inside_word(&display_map, display_range.end))
9591 {
9592 next_selected_range = Some(offset_range);
9593 break;
9594 }
9595 }
9596
9597 if let Some(next_selected_range) = next_selected_range {
9598 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9599 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9600 if action.replace_newest {
9601 s.delete(s.newest_anchor().id);
9602 }
9603 s.insert_range(next_selected_range);
9604 });
9605 } else {
9606 select_prev_state.done = true;
9607 }
9608 }
9609
9610 self.select_prev_state = Some(select_prev_state);
9611 } else {
9612 let mut only_carets = true;
9613 let mut same_text_selected = true;
9614 let mut selected_text = None;
9615
9616 let mut selections_iter = selections.iter().peekable();
9617 while let Some(selection) = selections_iter.next() {
9618 if selection.start != selection.end {
9619 only_carets = false;
9620 }
9621
9622 if same_text_selected {
9623 if selected_text.is_none() {
9624 selected_text =
9625 Some(buffer.text_for_range(selection.range()).collect::<String>());
9626 }
9627
9628 if let Some(next_selection) = selections_iter.peek() {
9629 if next_selection.range().len() == selection.range().len() {
9630 let next_selected_text = buffer
9631 .text_for_range(next_selection.range())
9632 .collect::<String>();
9633 if Some(next_selected_text) != selected_text {
9634 same_text_selected = false;
9635 selected_text = None;
9636 }
9637 } else {
9638 same_text_selected = false;
9639 selected_text = None;
9640 }
9641 }
9642 }
9643 }
9644
9645 if only_carets {
9646 for selection in &mut selections {
9647 let word_range = movement::surrounding_word(
9648 &display_map,
9649 selection.start.to_display_point(&display_map),
9650 );
9651 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9652 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9653 selection.goal = SelectionGoal::None;
9654 selection.reversed = false;
9655 }
9656 if selections.len() == 1 {
9657 let selection = selections
9658 .last()
9659 .expect("ensured that there's only one selection");
9660 let query = buffer
9661 .text_for_range(selection.start..selection.end)
9662 .collect::<String>();
9663 let is_empty = query.is_empty();
9664 let select_state = SelectNextState {
9665 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9666 wordwise: true,
9667 done: is_empty,
9668 };
9669 self.select_prev_state = Some(select_state);
9670 } else {
9671 self.select_prev_state = None;
9672 }
9673
9674 self.unfold_ranges(
9675 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9676 false,
9677 true,
9678 cx,
9679 );
9680 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9681 s.select(selections);
9682 });
9683 } else if let Some(selected_text) = selected_text {
9684 self.select_prev_state = Some(SelectNextState {
9685 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9686 wordwise: false,
9687 done: false,
9688 });
9689 self.select_previous(action, window, cx)?;
9690 }
9691 }
9692 Ok(())
9693 }
9694
9695 pub fn toggle_comments(
9696 &mut self,
9697 action: &ToggleComments,
9698 window: &mut Window,
9699 cx: &mut Context<Self>,
9700 ) {
9701 if self.read_only(cx) {
9702 return;
9703 }
9704 let text_layout_details = &self.text_layout_details(window);
9705 self.transact(window, cx, |this, window, cx| {
9706 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9707 let mut edits = Vec::new();
9708 let mut selection_edit_ranges = Vec::new();
9709 let mut last_toggled_row = None;
9710 let snapshot = this.buffer.read(cx).read(cx);
9711 let empty_str: Arc<str> = Arc::default();
9712 let mut suffixes_inserted = Vec::new();
9713 let ignore_indent = action.ignore_indent;
9714
9715 fn comment_prefix_range(
9716 snapshot: &MultiBufferSnapshot,
9717 row: MultiBufferRow,
9718 comment_prefix: &str,
9719 comment_prefix_whitespace: &str,
9720 ignore_indent: bool,
9721 ) -> Range<Point> {
9722 let indent_size = if ignore_indent {
9723 0
9724 } else {
9725 snapshot.indent_size_for_line(row).len
9726 };
9727
9728 let start = Point::new(row.0, indent_size);
9729
9730 let mut line_bytes = snapshot
9731 .bytes_in_range(start..snapshot.max_point())
9732 .flatten()
9733 .copied();
9734
9735 // If this line currently begins with the line comment prefix, then record
9736 // the range containing the prefix.
9737 if line_bytes
9738 .by_ref()
9739 .take(comment_prefix.len())
9740 .eq(comment_prefix.bytes())
9741 {
9742 // Include any whitespace that matches the comment prefix.
9743 let matching_whitespace_len = line_bytes
9744 .zip(comment_prefix_whitespace.bytes())
9745 .take_while(|(a, b)| a == b)
9746 .count() as u32;
9747 let end = Point::new(
9748 start.row,
9749 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9750 );
9751 start..end
9752 } else {
9753 start..start
9754 }
9755 }
9756
9757 fn comment_suffix_range(
9758 snapshot: &MultiBufferSnapshot,
9759 row: MultiBufferRow,
9760 comment_suffix: &str,
9761 comment_suffix_has_leading_space: bool,
9762 ) -> Range<Point> {
9763 let end = Point::new(row.0, snapshot.line_len(row));
9764 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9765
9766 let mut line_end_bytes = snapshot
9767 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9768 .flatten()
9769 .copied();
9770
9771 let leading_space_len = if suffix_start_column > 0
9772 && line_end_bytes.next() == Some(b' ')
9773 && comment_suffix_has_leading_space
9774 {
9775 1
9776 } else {
9777 0
9778 };
9779
9780 // If this line currently begins with the line comment prefix, then record
9781 // the range containing the prefix.
9782 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9783 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9784 start..end
9785 } else {
9786 end..end
9787 }
9788 }
9789
9790 // TODO: Handle selections that cross excerpts
9791 for selection in &mut selections {
9792 let start_column = snapshot
9793 .indent_size_for_line(MultiBufferRow(selection.start.row))
9794 .len;
9795 let language = if let Some(language) =
9796 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9797 {
9798 language
9799 } else {
9800 continue;
9801 };
9802
9803 selection_edit_ranges.clear();
9804
9805 // If multiple selections contain a given row, avoid processing that
9806 // row more than once.
9807 let mut start_row = MultiBufferRow(selection.start.row);
9808 if last_toggled_row == Some(start_row) {
9809 start_row = start_row.next_row();
9810 }
9811 let end_row =
9812 if selection.end.row > selection.start.row && selection.end.column == 0 {
9813 MultiBufferRow(selection.end.row - 1)
9814 } else {
9815 MultiBufferRow(selection.end.row)
9816 };
9817 last_toggled_row = Some(end_row);
9818
9819 if start_row > end_row {
9820 continue;
9821 }
9822
9823 // If the language has line comments, toggle those.
9824 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9825
9826 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9827 if ignore_indent {
9828 full_comment_prefixes = full_comment_prefixes
9829 .into_iter()
9830 .map(|s| Arc::from(s.trim_end()))
9831 .collect();
9832 }
9833
9834 if !full_comment_prefixes.is_empty() {
9835 let first_prefix = full_comment_prefixes
9836 .first()
9837 .expect("prefixes is non-empty");
9838 let prefix_trimmed_lengths = full_comment_prefixes
9839 .iter()
9840 .map(|p| p.trim_end_matches(' ').len())
9841 .collect::<SmallVec<[usize; 4]>>();
9842
9843 let mut all_selection_lines_are_comments = true;
9844
9845 for row in start_row.0..=end_row.0 {
9846 let row = MultiBufferRow(row);
9847 if start_row < end_row && snapshot.is_line_blank(row) {
9848 continue;
9849 }
9850
9851 let prefix_range = full_comment_prefixes
9852 .iter()
9853 .zip(prefix_trimmed_lengths.iter().copied())
9854 .map(|(prefix, trimmed_prefix_len)| {
9855 comment_prefix_range(
9856 snapshot.deref(),
9857 row,
9858 &prefix[..trimmed_prefix_len],
9859 &prefix[trimmed_prefix_len..],
9860 ignore_indent,
9861 )
9862 })
9863 .max_by_key(|range| range.end.column - range.start.column)
9864 .expect("prefixes is non-empty");
9865
9866 if prefix_range.is_empty() {
9867 all_selection_lines_are_comments = false;
9868 }
9869
9870 selection_edit_ranges.push(prefix_range);
9871 }
9872
9873 if all_selection_lines_are_comments {
9874 edits.extend(
9875 selection_edit_ranges
9876 .iter()
9877 .cloned()
9878 .map(|range| (range, empty_str.clone())),
9879 );
9880 } else {
9881 let min_column = selection_edit_ranges
9882 .iter()
9883 .map(|range| range.start.column)
9884 .min()
9885 .unwrap_or(0);
9886 edits.extend(selection_edit_ranges.iter().map(|range| {
9887 let position = Point::new(range.start.row, min_column);
9888 (position..position, first_prefix.clone())
9889 }));
9890 }
9891 } else if let Some((full_comment_prefix, comment_suffix)) =
9892 language.block_comment_delimiters()
9893 {
9894 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9895 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9896 let prefix_range = comment_prefix_range(
9897 snapshot.deref(),
9898 start_row,
9899 comment_prefix,
9900 comment_prefix_whitespace,
9901 ignore_indent,
9902 );
9903 let suffix_range = comment_suffix_range(
9904 snapshot.deref(),
9905 end_row,
9906 comment_suffix.trim_start_matches(' '),
9907 comment_suffix.starts_with(' '),
9908 );
9909
9910 if prefix_range.is_empty() || suffix_range.is_empty() {
9911 edits.push((
9912 prefix_range.start..prefix_range.start,
9913 full_comment_prefix.clone(),
9914 ));
9915 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9916 suffixes_inserted.push((end_row, comment_suffix.len()));
9917 } else {
9918 edits.push((prefix_range, empty_str.clone()));
9919 edits.push((suffix_range, empty_str.clone()));
9920 }
9921 } else {
9922 continue;
9923 }
9924 }
9925
9926 drop(snapshot);
9927 this.buffer.update(cx, |buffer, cx| {
9928 buffer.edit(edits, None, cx);
9929 });
9930
9931 // Adjust selections so that they end before any comment suffixes that
9932 // were inserted.
9933 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9934 let mut selections = this.selections.all::<Point>(cx);
9935 let snapshot = this.buffer.read(cx).read(cx);
9936 for selection in &mut selections {
9937 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9938 match row.cmp(&MultiBufferRow(selection.end.row)) {
9939 Ordering::Less => {
9940 suffixes_inserted.next();
9941 continue;
9942 }
9943 Ordering::Greater => break,
9944 Ordering::Equal => {
9945 if selection.end.column == snapshot.line_len(row) {
9946 if selection.is_empty() {
9947 selection.start.column -= suffix_len as u32;
9948 }
9949 selection.end.column -= suffix_len as u32;
9950 }
9951 break;
9952 }
9953 }
9954 }
9955 }
9956
9957 drop(snapshot);
9958 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9959 s.select(selections)
9960 });
9961
9962 let selections = this.selections.all::<Point>(cx);
9963 let selections_on_single_row = selections.windows(2).all(|selections| {
9964 selections[0].start.row == selections[1].start.row
9965 && selections[0].end.row == selections[1].end.row
9966 && selections[0].start.row == selections[0].end.row
9967 });
9968 let selections_selecting = selections
9969 .iter()
9970 .any(|selection| selection.start != selection.end);
9971 let advance_downwards = action.advance_downwards
9972 && selections_on_single_row
9973 && !selections_selecting
9974 && !matches!(this.mode, EditorMode::SingleLine { .. });
9975
9976 if advance_downwards {
9977 let snapshot = this.buffer.read(cx).snapshot(cx);
9978
9979 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9980 s.move_cursors_with(|display_snapshot, display_point, _| {
9981 let mut point = display_point.to_point(display_snapshot);
9982 point.row += 1;
9983 point = snapshot.clip_point(point, Bias::Left);
9984 let display_point = point.to_display_point(display_snapshot);
9985 let goal = SelectionGoal::HorizontalPosition(
9986 display_snapshot
9987 .x_for_display_point(display_point, text_layout_details)
9988 .into(),
9989 );
9990 (display_point, goal)
9991 })
9992 });
9993 }
9994 });
9995 }
9996
9997 pub fn select_enclosing_symbol(
9998 &mut self,
9999 _: &SelectEnclosingSymbol,
10000 window: &mut Window,
10001 cx: &mut Context<Self>,
10002 ) {
10003 let buffer = self.buffer.read(cx).snapshot(cx);
10004 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10005
10006 fn update_selection(
10007 selection: &Selection<usize>,
10008 buffer_snap: &MultiBufferSnapshot,
10009 ) -> Option<Selection<usize>> {
10010 let cursor = selection.head();
10011 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10012 for symbol in symbols.iter().rev() {
10013 let start = symbol.range.start.to_offset(buffer_snap);
10014 let end = symbol.range.end.to_offset(buffer_snap);
10015 let new_range = start..end;
10016 if start < selection.start || end > selection.end {
10017 return Some(Selection {
10018 id: selection.id,
10019 start: new_range.start,
10020 end: new_range.end,
10021 goal: SelectionGoal::None,
10022 reversed: selection.reversed,
10023 });
10024 }
10025 }
10026 None
10027 }
10028
10029 let mut selected_larger_symbol = false;
10030 let new_selections = old_selections
10031 .iter()
10032 .map(|selection| match update_selection(selection, &buffer) {
10033 Some(new_selection) => {
10034 if new_selection.range() != selection.range() {
10035 selected_larger_symbol = true;
10036 }
10037 new_selection
10038 }
10039 None => selection.clone(),
10040 })
10041 .collect::<Vec<_>>();
10042
10043 if selected_larger_symbol {
10044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10045 s.select(new_selections);
10046 });
10047 }
10048 }
10049
10050 pub fn select_larger_syntax_node(
10051 &mut self,
10052 _: &SelectLargerSyntaxNode,
10053 window: &mut Window,
10054 cx: &mut Context<Self>,
10055 ) {
10056 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10057 let buffer = self.buffer.read(cx).snapshot(cx);
10058 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10059
10060 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10061 let mut selected_larger_node = false;
10062 let new_selections = old_selections
10063 .iter()
10064 .map(|selection| {
10065 let old_range = selection.start..selection.end;
10066 let mut new_range = old_range.clone();
10067 let mut new_node = None;
10068 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10069 {
10070 new_node = Some(node);
10071 new_range = containing_range;
10072 if !display_map.intersects_fold(new_range.start)
10073 && !display_map.intersects_fold(new_range.end)
10074 {
10075 break;
10076 }
10077 }
10078
10079 if let Some(node) = new_node {
10080 // Log the ancestor, to support using this action as a way to explore TreeSitter
10081 // nodes. Parent and grandparent are also logged because this operation will not
10082 // visit nodes that have the same range as their parent.
10083 log::info!("Node: {node:?}");
10084 let parent = node.parent();
10085 log::info!("Parent: {parent:?}");
10086 let grandparent = parent.and_then(|x| x.parent());
10087 log::info!("Grandparent: {grandparent:?}");
10088 }
10089
10090 selected_larger_node |= new_range != old_range;
10091 Selection {
10092 id: selection.id,
10093 start: new_range.start,
10094 end: new_range.end,
10095 goal: SelectionGoal::None,
10096 reversed: selection.reversed,
10097 }
10098 })
10099 .collect::<Vec<_>>();
10100
10101 if selected_larger_node {
10102 stack.push(old_selections);
10103 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10104 s.select(new_selections);
10105 });
10106 }
10107 self.select_larger_syntax_node_stack = stack;
10108 }
10109
10110 pub fn select_smaller_syntax_node(
10111 &mut self,
10112 _: &SelectSmallerSyntaxNode,
10113 window: &mut Window,
10114 cx: &mut Context<Self>,
10115 ) {
10116 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10117 if let Some(selections) = stack.pop() {
10118 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10119 s.select(selections.to_vec());
10120 });
10121 }
10122 self.select_larger_syntax_node_stack = stack;
10123 }
10124
10125 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10126 if !EditorSettings::get_global(cx).gutter.runnables {
10127 self.clear_tasks();
10128 return Task::ready(());
10129 }
10130 let project = self.project.as_ref().map(Entity::downgrade);
10131 cx.spawn_in(window, |this, mut cx| async move {
10132 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10133 let Some(project) = project.and_then(|p| p.upgrade()) else {
10134 return;
10135 };
10136 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10137 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10138 }) else {
10139 return;
10140 };
10141
10142 let hide_runnables = project
10143 .update(&mut cx, |project, cx| {
10144 // Do not display any test indicators in non-dev server remote projects.
10145 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10146 })
10147 .unwrap_or(true);
10148 if hide_runnables {
10149 return;
10150 }
10151 let new_rows =
10152 cx.background_executor()
10153 .spawn({
10154 let snapshot = display_snapshot.clone();
10155 async move {
10156 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10157 }
10158 })
10159 .await;
10160
10161 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10162 this.update(&mut cx, |this, _| {
10163 this.clear_tasks();
10164 for (key, value) in rows {
10165 this.insert_tasks(key, value);
10166 }
10167 })
10168 .ok();
10169 })
10170 }
10171 fn fetch_runnable_ranges(
10172 snapshot: &DisplaySnapshot,
10173 range: Range<Anchor>,
10174 ) -> Vec<language::RunnableRange> {
10175 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10176 }
10177
10178 fn runnable_rows(
10179 project: Entity<Project>,
10180 snapshot: DisplaySnapshot,
10181 runnable_ranges: Vec<RunnableRange>,
10182 mut cx: AsyncWindowContext,
10183 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10184 runnable_ranges
10185 .into_iter()
10186 .filter_map(|mut runnable| {
10187 let tasks = cx
10188 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10189 .ok()?;
10190 if tasks.is_empty() {
10191 return None;
10192 }
10193
10194 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10195
10196 let row = snapshot
10197 .buffer_snapshot
10198 .buffer_line_for_row(MultiBufferRow(point.row))?
10199 .1
10200 .start
10201 .row;
10202
10203 let context_range =
10204 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10205 Some((
10206 (runnable.buffer_id, row),
10207 RunnableTasks {
10208 templates: tasks,
10209 offset: MultiBufferOffset(runnable.run_range.start),
10210 context_range,
10211 column: point.column,
10212 extra_variables: runnable.extra_captures,
10213 },
10214 ))
10215 })
10216 .collect()
10217 }
10218
10219 fn templates_with_tags(
10220 project: &Entity<Project>,
10221 runnable: &mut Runnable,
10222 cx: &mut App,
10223 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10224 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10225 let (worktree_id, file) = project
10226 .buffer_for_id(runnable.buffer, cx)
10227 .and_then(|buffer| buffer.read(cx).file())
10228 .map(|file| (file.worktree_id(cx), file.clone()))
10229 .unzip();
10230
10231 (
10232 project.task_store().read(cx).task_inventory().cloned(),
10233 worktree_id,
10234 file,
10235 )
10236 });
10237
10238 let tags = mem::take(&mut runnable.tags);
10239 let mut tags: Vec<_> = tags
10240 .into_iter()
10241 .flat_map(|tag| {
10242 let tag = tag.0.clone();
10243 inventory
10244 .as_ref()
10245 .into_iter()
10246 .flat_map(|inventory| {
10247 inventory.read(cx).list_tasks(
10248 file.clone(),
10249 Some(runnable.language.clone()),
10250 worktree_id,
10251 cx,
10252 )
10253 })
10254 .filter(move |(_, template)| {
10255 template.tags.iter().any(|source_tag| source_tag == &tag)
10256 })
10257 })
10258 .sorted_by_key(|(kind, _)| kind.to_owned())
10259 .collect();
10260 if let Some((leading_tag_source, _)) = tags.first() {
10261 // Strongest source wins; if we have worktree tag binding, prefer that to
10262 // global and language bindings;
10263 // if we have a global binding, prefer that to language binding.
10264 let first_mismatch = tags
10265 .iter()
10266 .position(|(tag_source, _)| tag_source != leading_tag_source);
10267 if let Some(index) = first_mismatch {
10268 tags.truncate(index);
10269 }
10270 }
10271
10272 tags
10273 }
10274
10275 pub fn move_to_enclosing_bracket(
10276 &mut self,
10277 _: &MoveToEnclosingBracket,
10278 window: &mut Window,
10279 cx: &mut Context<Self>,
10280 ) {
10281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10282 s.move_offsets_with(|snapshot, selection| {
10283 let Some(enclosing_bracket_ranges) =
10284 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10285 else {
10286 return;
10287 };
10288
10289 let mut best_length = usize::MAX;
10290 let mut best_inside = false;
10291 let mut best_in_bracket_range = false;
10292 let mut best_destination = None;
10293 for (open, close) in enclosing_bracket_ranges {
10294 let close = close.to_inclusive();
10295 let length = close.end() - open.start;
10296 let inside = selection.start >= open.end && selection.end <= *close.start();
10297 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10298 || close.contains(&selection.head());
10299
10300 // If best is next to a bracket and current isn't, skip
10301 if !in_bracket_range && best_in_bracket_range {
10302 continue;
10303 }
10304
10305 // Prefer smaller lengths unless best is inside and current isn't
10306 if length > best_length && (best_inside || !inside) {
10307 continue;
10308 }
10309
10310 best_length = length;
10311 best_inside = inside;
10312 best_in_bracket_range = in_bracket_range;
10313 best_destination = Some(
10314 if close.contains(&selection.start) && close.contains(&selection.end) {
10315 if inside {
10316 open.end
10317 } else {
10318 open.start
10319 }
10320 } else if inside {
10321 *close.start()
10322 } else {
10323 *close.end()
10324 },
10325 );
10326 }
10327
10328 if let Some(destination) = best_destination {
10329 selection.collapse_to(destination, SelectionGoal::None);
10330 }
10331 })
10332 });
10333 }
10334
10335 pub fn undo_selection(
10336 &mut self,
10337 _: &UndoSelection,
10338 window: &mut Window,
10339 cx: &mut Context<Self>,
10340 ) {
10341 self.end_selection(window, cx);
10342 self.selection_history.mode = SelectionHistoryMode::Undoing;
10343 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10344 self.change_selections(None, window, cx, |s| {
10345 s.select_anchors(entry.selections.to_vec())
10346 });
10347 self.select_next_state = entry.select_next_state;
10348 self.select_prev_state = entry.select_prev_state;
10349 self.add_selections_state = entry.add_selections_state;
10350 self.request_autoscroll(Autoscroll::newest(), cx);
10351 }
10352 self.selection_history.mode = SelectionHistoryMode::Normal;
10353 }
10354
10355 pub fn redo_selection(
10356 &mut self,
10357 _: &RedoSelection,
10358 window: &mut Window,
10359 cx: &mut Context<Self>,
10360 ) {
10361 self.end_selection(window, cx);
10362 self.selection_history.mode = SelectionHistoryMode::Redoing;
10363 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10364 self.change_selections(None, window, cx, |s| {
10365 s.select_anchors(entry.selections.to_vec())
10366 });
10367 self.select_next_state = entry.select_next_state;
10368 self.select_prev_state = entry.select_prev_state;
10369 self.add_selections_state = entry.add_selections_state;
10370 self.request_autoscroll(Autoscroll::newest(), cx);
10371 }
10372 self.selection_history.mode = SelectionHistoryMode::Normal;
10373 }
10374
10375 pub fn expand_excerpts(
10376 &mut self,
10377 action: &ExpandExcerpts,
10378 _: &mut Window,
10379 cx: &mut Context<Self>,
10380 ) {
10381 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10382 }
10383
10384 pub fn expand_excerpts_down(
10385 &mut self,
10386 action: &ExpandExcerptsDown,
10387 _: &mut Window,
10388 cx: &mut Context<Self>,
10389 ) {
10390 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10391 }
10392
10393 pub fn expand_excerpts_up(
10394 &mut self,
10395 action: &ExpandExcerptsUp,
10396 _: &mut Window,
10397 cx: &mut Context<Self>,
10398 ) {
10399 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10400 }
10401
10402 pub fn expand_excerpts_for_direction(
10403 &mut self,
10404 lines: u32,
10405 direction: ExpandExcerptDirection,
10406
10407 cx: &mut Context<Self>,
10408 ) {
10409 let selections = self.selections.disjoint_anchors();
10410
10411 let lines = if lines == 0 {
10412 EditorSettings::get_global(cx).expand_excerpt_lines
10413 } else {
10414 lines
10415 };
10416
10417 self.buffer.update(cx, |buffer, cx| {
10418 let snapshot = buffer.snapshot(cx);
10419 let mut excerpt_ids = selections
10420 .iter()
10421 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10422 .collect::<Vec<_>>();
10423 excerpt_ids.sort();
10424 excerpt_ids.dedup();
10425 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10426 })
10427 }
10428
10429 pub fn expand_excerpt(
10430 &mut self,
10431 excerpt: ExcerptId,
10432 direction: ExpandExcerptDirection,
10433 cx: &mut Context<Self>,
10434 ) {
10435 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10436 self.buffer.update(cx, |buffer, cx| {
10437 buffer.expand_excerpts([excerpt], lines, direction, cx)
10438 })
10439 }
10440
10441 pub fn go_to_singleton_buffer_point(
10442 &mut self,
10443 point: Point,
10444 window: &mut Window,
10445 cx: &mut Context<Self>,
10446 ) {
10447 self.go_to_singleton_buffer_range(point..point, window, cx);
10448 }
10449
10450 pub fn go_to_singleton_buffer_range(
10451 &mut self,
10452 range: Range<Point>,
10453 window: &mut Window,
10454 cx: &mut Context<Self>,
10455 ) {
10456 let multibuffer = self.buffer().read(cx);
10457 let Some(buffer) = multibuffer.as_singleton() else {
10458 return;
10459 };
10460 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10461 return;
10462 };
10463 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10464 return;
10465 };
10466 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10467 s.select_anchor_ranges([start..end])
10468 });
10469 }
10470
10471 fn go_to_diagnostic(
10472 &mut self,
10473 _: &GoToDiagnostic,
10474 window: &mut Window,
10475 cx: &mut Context<Self>,
10476 ) {
10477 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10478 }
10479
10480 fn go_to_prev_diagnostic(
10481 &mut self,
10482 _: &GoToPrevDiagnostic,
10483 window: &mut Window,
10484 cx: &mut Context<Self>,
10485 ) {
10486 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10487 }
10488
10489 pub fn go_to_diagnostic_impl(
10490 &mut self,
10491 direction: Direction,
10492 window: &mut Window,
10493 cx: &mut Context<Self>,
10494 ) {
10495 let buffer = self.buffer.read(cx).snapshot(cx);
10496 let selection = self.selections.newest::<usize>(cx);
10497
10498 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10499 if direction == Direction::Next {
10500 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10501 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10502 return;
10503 };
10504 self.activate_diagnostics(
10505 buffer_id,
10506 popover.local_diagnostic.diagnostic.group_id,
10507 window,
10508 cx,
10509 );
10510 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10511 let primary_range_start = active_diagnostics.primary_range.start;
10512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10513 let mut new_selection = s.newest_anchor().clone();
10514 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10515 s.select_anchors(vec![new_selection.clone()]);
10516 });
10517 self.refresh_inline_completion(false, true, window, cx);
10518 }
10519 return;
10520 }
10521 }
10522
10523 let active_group_id = self
10524 .active_diagnostics
10525 .as_ref()
10526 .map(|active_group| active_group.group_id);
10527 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10528 active_diagnostics
10529 .primary_range
10530 .to_offset(&buffer)
10531 .to_inclusive()
10532 });
10533 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10534 if active_primary_range.contains(&selection.head()) {
10535 *active_primary_range.start()
10536 } else {
10537 selection.head()
10538 }
10539 } else {
10540 selection.head()
10541 };
10542
10543 let snapshot = self.snapshot(window, cx);
10544 let primary_diagnostics_before = buffer
10545 .diagnostics_in_range::<usize>(0..search_start)
10546 .filter(|entry| entry.diagnostic.is_primary)
10547 .filter(|entry| entry.range.start != entry.range.end)
10548 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10549 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10550 .collect::<Vec<_>>();
10551 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10552 primary_diagnostics_before
10553 .iter()
10554 .position(|entry| entry.diagnostic.group_id == active_group_id)
10555 });
10556
10557 let primary_diagnostics_after = buffer
10558 .diagnostics_in_range::<usize>(search_start..buffer.len())
10559 .filter(|entry| entry.diagnostic.is_primary)
10560 .filter(|entry| entry.range.start != entry.range.end)
10561 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10562 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10563 .collect::<Vec<_>>();
10564 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10565 primary_diagnostics_after
10566 .iter()
10567 .enumerate()
10568 .rev()
10569 .find_map(|(i, entry)| {
10570 if entry.diagnostic.group_id == active_group_id {
10571 Some(i)
10572 } else {
10573 None
10574 }
10575 })
10576 });
10577
10578 let next_primary_diagnostic = match direction {
10579 Direction::Prev => primary_diagnostics_before
10580 .iter()
10581 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10582 .rev()
10583 .next(),
10584 Direction::Next => primary_diagnostics_after
10585 .iter()
10586 .skip(
10587 last_same_group_diagnostic_after
10588 .map(|index| index + 1)
10589 .unwrap_or(0),
10590 )
10591 .next(),
10592 };
10593
10594 // Cycle around to the start of the buffer, potentially moving back to the start of
10595 // the currently active diagnostic.
10596 let cycle_around = || match direction {
10597 Direction::Prev => primary_diagnostics_after
10598 .iter()
10599 .rev()
10600 .chain(primary_diagnostics_before.iter().rev())
10601 .next(),
10602 Direction::Next => primary_diagnostics_before
10603 .iter()
10604 .chain(primary_diagnostics_after.iter())
10605 .next(),
10606 };
10607
10608 if let Some((primary_range, group_id)) = next_primary_diagnostic
10609 .or_else(cycle_around)
10610 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10611 {
10612 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10613 return;
10614 };
10615 self.activate_diagnostics(buffer_id, group_id, window, cx);
10616 if self.active_diagnostics.is_some() {
10617 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618 s.select(vec![Selection {
10619 id: selection.id,
10620 start: primary_range.start,
10621 end: primary_range.start,
10622 reversed: false,
10623 goal: SelectionGoal::None,
10624 }]);
10625 });
10626 self.refresh_inline_completion(false, true, window, cx);
10627 }
10628 }
10629 }
10630
10631 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10632 let snapshot = self.snapshot(window, cx);
10633 let selection = self.selections.newest::<Point>(cx);
10634 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10635 }
10636
10637 fn go_to_hunk_after_position(
10638 &mut self,
10639 snapshot: &EditorSnapshot,
10640 position: Point,
10641 window: &mut Window,
10642 cx: &mut Context<Editor>,
10643 ) -> Option<MultiBufferDiffHunk> {
10644 let mut hunk = snapshot
10645 .buffer_snapshot
10646 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10647 .find(|hunk| hunk.row_range.start.0 > position.row);
10648 if hunk.is_none() {
10649 hunk = snapshot
10650 .buffer_snapshot
10651 .diff_hunks_in_range(Point::zero()..position)
10652 .find(|hunk| hunk.row_range.end.0 < position.row)
10653 }
10654 if let Some(hunk) = &hunk {
10655 let destination = Point::new(hunk.row_range.start.0, 0);
10656 self.unfold_ranges(&[destination..destination], false, false, cx);
10657 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10658 s.select_ranges(vec![destination..destination]);
10659 });
10660 }
10661
10662 hunk
10663 }
10664
10665 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10666 let snapshot = self.snapshot(window, cx);
10667 let selection = self.selections.newest::<Point>(cx);
10668 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10669 }
10670
10671 fn go_to_hunk_before_position(
10672 &mut self,
10673 snapshot: &EditorSnapshot,
10674 position: Point,
10675 window: &mut Window,
10676 cx: &mut Context<Editor>,
10677 ) -> Option<MultiBufferDiffHunk> {
10678 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10679 if hunk.is_none() {
10680 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10681 }
10682 if let Some(hunk) = &hunk {
10683 let destination = Point::new(hunk.row_range.start.0, 0);
10684 self.unfold_ranges(&[destination..destination], false, false, cx);
10685 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686 s.select_ranges(vec![destination..destination]);
10687 });
10688 }
10689
10690 hunk
10691 }
10692
10693 pub fn go_to_definition(
10694 &mut self,
10695 _: &GoToDefinition,
10696 window: &mut Window,
10697 cx: &mut Context<Self>,
10698 ) -> Task<Result<Navigated>> {
10699 let definition =
10700 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10701 cx.spawn_in(window, |editor, mut cx| async move {
10702 if definition.await? == Navigated::Yes {
10703 return Ok(Navigated::Yes);
10704 }
10705 match editor.update_in(&mut cx, |editor, window, cx| {
10706 editor.find_all_references(&FindAllReferences, window, cx)
10707 })? {
10708 Some(references) => references.await,
10709 None => Ok(Navigated::No),
10710 }
10711 })
10712 }
10713
10714 pub fn go_to_declaration(
10715 &mut self,
10716 _: &GoToDeclaration,
10717 window: &mut Window,
10718 cx: &mut Context<Self>,
10719 ) -> Task<Result<Navigated>> {
10720 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10721 }
10722
10723 pub fn go_to_declaration_split(
10724 &mut self,
10725 _: &GoToDeclaration,
10726 window: &mut Window,
10727 cx: &mut Context<Self>,
10728 ) -> Task<Result<Navigated>> {
10729 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10730 }
10731
10732 pub fn go_to_implementation(
10733 &mut self,
10734 _: &GoToImplementation,
10735 window: &mut Window,
10736 cx: &mut Context<Self>,
10737 ) -> Task<Result<Navigated>> {
10738 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10739 }
10740
10741 pub fn go_to_implementation_split(
10742 &mut self,
10743 _: &GoToImplementationSplit,
10744 window: &mut Window,
10745 cx: &mut Context<Self>,
10746 ) -> Task<Result<Navigated>> {
10747 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10748 }
10749
10750 pub fn go_to_type_definition(
10751 &mut self,
10752 _: &GoToTypeDefinition,
10753 window: &mut Window,
10754 cx: &mut Context<Self>,
10755 ) -> Task<Result<Navigated>> {
10756 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10757 }
10758
10759 pub fn go_to_definition_split(
10760 &mut self,
10761 _: &GoToDefinitionSplit,
10762 window: &mut Window,
10763 cx: &mut Context<Self>,
10764 ) -> Task<Result<Navigated>> {
10765 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10766 }
10767
10768 pub fn go_to_type_definition_split(
10769 &mut self,
10770 _: &GoToTypeDefinitionSplit,
10771 window: &mut Window,
10772 cx: &mut Context<Self>,
10773 ) -> Task<Result<Navigated>> {
10774 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10775 }
10776
10777 fn go_to_definition_of_kind(
10778 &mut self,
10779 kind: GotoDefinitionKind,
10780 split: bool,
10781 window: &mut Window,
10782 cx: &mut Context<Self>,
10783 ) -> Task<Result<Navigated>> {
10784 let Some(provider) = self.semantics_provider.clone() else {
10785 return Task::ready(Ok(Navigated::No));
10786 };
10787 let head = self.selections.newest::<usize>(cx).head();
10788 let buffer = self.buffer.read(cx);
10789 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10790 text_anchor
10791 } else {
10792 return Task::ready(Ok(Navigated::No));
10793 };
10794
10795 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10796 return Task::ready(Ok(Navigated::No));
10797 };
10798
10799 cx.spawn_in(window, |editor, mut cx| async move {
10800 let definitions = definitions.await?;
10801 let navigated = editor
10802 .update_in(&mut cx, |editor, window, cx| {
10803 editor.navigate_to_hover_links(
10804 Some(kind),
10805 definitions
10806 .into_iter()
10807 .filter(|location| {
10808 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10809 })
10810 .map(HoverLink::Text)
10811 .collect::<Vec<_>>(),
10812 split,
10813 window,
10814 cx,
10815 )
10816 })?
10817 .await?;
10818 anyhow::Ok(navigated)
10819 })
10820 }
10821
10822 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10823 let selection = self.selections.newest_anchor();
10824 let head = selection.head();
10825 let tail = selection.tail();
10826
10827 let Some((buffer, start_position)) =
10828 self.buffer.read(cx).text_anchor_for_position(head, cx)
10829 else {
10830 return;
10831 };
10832
10833 let end_position = if head != tail {
10834 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10835 return;
10836 };
10837 Some(pos)
10838 } else {
10839 None
10840 };
10841
10842 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10843 let url = if let Some(end_pos) = end_position {
10844 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10845 } else {
10846 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10847 };
10848
10849 if let Some(url) = url {
10850 editor.update(&mut cx, |_, cx| {
10851 cx.open_url(&url);
10852 })
10853 } else {
10854 Ok(())
10855 }
10856 });
10857
10858 url_finder.detach();
10859 }
10860
10861 pub fn open_selected_filename(
10862 &mut self,
10863 _: &OpenSelectedFilename,
10864 window: &mut Window,
10865 cx: &mut Context<Self>,
10866 ) {
10867 let Some(workspace) = self.workspace() else {
10868 return;
10869 };
10870
10871 let position = self.selections.newest_anchor().head();
10872
10873 let Some((buffer, buffer_position)) =
10874 self.buffer.read(cx).text_anchor_for_position(position, cx)
10875 else {
10876 return;
10877 };
10878
10879 let project = self.project.clone();
10880
10881 cx.spawn_in(window, |_, mut cx| async move {
10882 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10883
10884 if let Some((_, path)) = result {
10885 workspace
10886 .update_in(&mut cx, |workspace, window, cx| {
10887 workspace.open_resolved_path(path, window, cx)
10888 })?
10889 .await?;
10890 }
10891 anyhow::Ok(())
10892 })
10893 .detach();
10894 }
10895
10896 pub(crate) fn navigate_to_hover_links(
10897 &mut self,
10898 kind: Option<GotoDefinitionKind>,
10899 mut definitions: Vec<HoverLink>,
10900 split: bool,
10901 window: &mut Window,
10902 cx: &mut Context<Editor>,
10903 ) -> Task<Result<Navigated>> {
10904 // If there is one definition, just open it directly
10905 if definitions.len() == 1 {
10906 let definition = definitions.pop().unwrap();
10907
10908 enum TargetTaskResult {
10909 Location(Option<Location>),
10910 AlreadyNavigated,
10911 }
10912
10913 let target_task = match definition {
10914 HoverLink::Text(link) => {
10915 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10916 }
10917 HoverLink::InlayHint(lsp_location, server_id) => {
10918 let computation =
10919 self.compute_target_location(lsp_location, server_id, window, cx);
10920 cx.background_executor().spawn(async move {
10921 let location = computation.await?;
10922 Ok(TargetTaskResult::Location(location))
10923 })
10924 }
10925 HoverLink::Url(url) => {
10926 cx.open_url(&url);
10927 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10928 }
10929 HoverLink::File(path) => {
10930 if let Some(workspace) = self.workspace() {
10931 cx.spawn_in(window, |_, mut cx| async move {
10932 workspace
10933 .update_in(&mut cx, |workspace, window, cx| {
10934 workspace.open_resolved_path(path, window, cx)
10935 })?
10936 .await
10937 .map(|_| TargetTaskResult::AlreadyNavigated)
10938 })
10939 } else {
10940 Task::ready(Ok(TargetTaskResult::Location(None)))
10941 }
10942 }
10943 };
10944 cx.spawn_in(window, |editor, mut cx| async move {
10945 let target = match target_task.await.context("target resolution task")? {
10946 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10947 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10948 TargetTaskResult::Location(Some(target)) => target,
10949 };
10950
10951 editor.update_in(&mut cx, |editor, window, cx| {
10952 let Some(workspace) = editor.workspace() else {
10953 return Navigated::No;
10954 };
10955 let pane = workspace.read(cx).active_pane().clone();
10956
10957 let range = target.range.to_point(target.buffer.read(cx));
10958 let range = editor.range_for_match(&range);
10959 let range = collapse_multiline_range(range);
10960
10961 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10962 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10963 } else {
10964 window.defer(cx, move |window, cx| {
10965 let target_editor: Entity<Self> =
10966 workspace.update(cx, |workspace, cx| {
10967 let pane = if split {
10968 workspace.adjacent_pane(window, cx)
10969 } else {
10970 workspace.active_pane().clone()
10971 };
10972
10973 workspace.open_project_item(
10974 pane,
10975 target.buffer.clone(),
10976 true,
10977 true,
10978 window,
10979 cx,
10980 )
10981 });
10982 target_editor.update(cx, |target_editor, cx| {
10983 // When selecting a definition in a different buffer, disable the nav history
10984 // to avoid creating a history entry at the previous cursor location.
10985 pane.update(cx, |pane, _| pane.disable_history());
10986 target_editor.go_to_singleton_buffer_range(range, window, cx);
10987 pane.update(cx, |pane, _| pane.enable_history());
10988 });
10989 });
10990 }
10991 Navigated::Yes
10992 })
10993 })
10994 } else if !definitions.is_empty() {
10995 cx.spawn_in(window, |editor, mut cx| async move {
10996 let (title, location_tasks, workspace) = editor
10997 .update_in(&mut cx, |editor, window, cx| {
10998 let tab_kind = match kind {
10999 Some(GotoDefinitionKind::Implementation) => "Implementations",
11000 _ => "Definitions",
11001 };
11002 let title = definitions
11003 .iter()
11004 .find_map(|definition| match definition {
11005 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11006 let buffer = origin.buffer.read(cx);
11007 format!(
11008 "{} for {}",
11009 tab_kind,
11010 buffer
11011 .text_for_range(origin.range.clone())
11012 .collect::<String>()
11013 )
11014 }),
11015 HoverLink::InlayHint(_, _) => None,
11016 HoverLink::Url(_) => None,
11017 HoverLink::File(_) => None,
11018 })
11019 .unwrap_or(tab_kind.to_string());
11020 let location_tasks = definitions
11021 .into_iter()
11022 .map(|definition| match definition {
11023 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11024 HoverLink::InlayHint(lsp_location, server_id) => editor
11025 .compute_target_location(lsp_location, server_id, window, cx),
11026 HoverLink::Url(_) => Task::ready(Ok(None)),
11027 HoverLink::File(_) => Task::ready(Ok(None)),
11028 })
11029 .collect::<Vec<_>>();
11030 (title, location_tasks, editor.workspace().clone())
11031 })
11032 .context("location tasks preparation")?;
11033
11034 let locations = future::join_all(location_tasks)
11035 .await
11036 .into_iter()
11037 .filter_map(|location| location.transpose())
11038 .collect::<Result<_>>()
11039 .context("location tasks")?;
11040
11041 let Some(workspace) = workspace else {
11042 return Ok(Navigated::No);
11043 };
11044 let opened = workspace
11045 .update_in(&mut cx, |workspace, window, cx| {
11046 Self::open_locations_in_multibuffer(
11047 workspace,
11048 locations,
11049 title,
11050 split,
11051 MultibufferSelectionMode::First,
11052 window,
11053 cx,
11054 )
11055 })
11056 .ok();
11057
11058 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11059 })
11060 } else {
11061 Task::ready(Ok(Navigated::No))
11062 }
11063 }
11064
11065 fn compute_target_location(
11066 &self,
11067 lsp_location: lsp::Location,
11068 server_id: LanguageServerId,
11069 window: &mut Window,
11070 cx: &mut Context<Self>,
11071 ) -> Task<anyhow::Result<Option<Location>>> {
11072 let Some(project) = self.project.clone() else {
11073 return Task::ready(Ok(None));
11074 };
11075
11076 cx.spawn_in(window, move |editor, mut cx| async move {
11077 let location_task = editor.update(&mut cx, |_, cx| {
11078 project.update(cx, |project, cx| {
11079 let language_server_name = project
11080 .language_server_statuses(cx)
11081 .find(|(id, _)| server_id == *id)
11082 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11083 language_server_name.map(|language_server_name| {
11084 project.open_local_buffer_via_lsp(
11085 lsp_location.uri.clone(),
11086 server_id,
11087 language_server_name,
11088 cx,
11089 )
11090 })
11091 })
11092 })?;
11093 let location = match location_task {
11094 Some(task) => Some({
11095 let target_buffer_handle = task.await.context("open local buffer")?;
11096 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11097 let target_start = target_buffer
11098 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11099 let target_end = target_buffer
11100 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11101 target_buffer.anchor_after(target_start)
11102 ..target_buffer.anchor_before(target_end)
11103 })?;
11104 Location {
11105 buffer: target_buffer_handle,
11106 range,
11107 }
11108 }),
11109 None => None,
11110 };
11111 Ok(location)
11112 })
11113 }
11114
11115 pub fn find_all_references(
11116 &mut self,
11117 _: &FindAllReferences,
11118 window: &mut Window,
11119 cx: &mut Context<Self>,
11120 ) -> Option<Task<Result<Navigated>>> {
11121 let selection = self.selections.newest::<usize>(cx);
11122 let multi_buffer = self.buffer.read(cx);
11123 let head = selection.head();
11124
11125 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11126 let head_anchor = multi_buffer_snapshot.anchor_at(
11127 head,
11128 if head < selection.tail() {
11129 Bias::Right
11130 } else {
11131 Bias::Left
11132 },
11133 );
11134
11135 match self
11136 .find_all_references_task_sources
11137 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11138 {
11139 Ok(_) => {
11140 log::info!(
11141 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11142 );
11143 return None;
11144 }
11145 Err(i) => {
11146 self.find_all_references_task_sources.insert(i, head_anchor);
11147 }
11148 }
11149
11150 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11151 let workspace = self.workspace()?;
11152 let project = workspace.read(cx).project().clone();
11153 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11154 Some(cx.spawn_in(window, |editor, mut cx| async move {
11155 let _cleanup = defer({
11156 let mut cx = cx.clone();
11157 move || {
11158 let _ = editor.update(&mut cx, |editor, _| {
11159 if let Ok(i) =
11160 editor
11161 .find_all_references_task_sources
11162 .binary_search_by(|anchor| {
11163 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11164 })
11165 {
11166 editor.find_all_references_task_sources.remove(i);
11167 }
11168 });
11169 }
11170 });
11171
11172 let locations = references.await?;
11173 if locations.is_empty() {
11174 return anyhow::Ok(Navigated::No);
11175 }
11176
11177 workspace.update_in(&mut cx, |workspace, window, cx| {
11178 let title = locations
11179 .first()
11180 .as_ref()
11181 .map(|location| {
11182 let buffer = location.buffer.read(cx);
11183 format!(
11184 "References to `{}`",
11185 buffer
11186 .text_for_range(location.range.clone())
11187 .collect::<String>()
11188 )
11189 })
11190 .unwrap();
11191 Self::open_locations_in_multibuffer(
11192 workspace,
11193 locations,
11194 title,
11195 false,
11196 MultibufferSelectionMode::First,
11197 window,
11198 cx,
11199 );
11200 Navigated::Yes
11201 })
11202 }))
11203 }
11204
11205 /// Opens a multibuffer with the given project locations in it
11206 pub fn open_locations_in_multibuffer(
11207 workspace: &mut Workspace,
11208 mut locations: Vec<Location>,
11209 title: String,
11210 split: bool,
11211 multibuffer_selection_mode: MultibufferSelectionMode,
11212 window: &mut Window,
11213 cx: &mut Context<Workspace>,
11214 ) {
11215 // If there are multiple definitions, open them in a multibuffer
11216 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11217 let mut locations = locations.into_iter().peekable();
11218 let mut ranges = Vec::new();
11219 let capability = workspace.project().read(cx).capability();
11220
11221 let excerpt_buffer = cx.new(|cx| {
11222 let mut multibuffer = MultiBuffer::new(capability);
11223 while let Some(location) = locations.next() {
11224 let buffer = location.buffer.read(cx);
11225 let mut ranges_for_buffer = Vec::new();
11226 let range = location.range.to_offset(buffer);
11227 ranges_for_buffer.push(range.clone());
11228
11229 while let Some(next_location) = locations.peek() {
11230 if next_location.buffer == location.buffer {
11231 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11232 locations.next();
11233 } else {
11234 break;
11235 }
11236 }
11237
11238 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11239 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11240 location.buffer.clone(),
11241 ranges_for_buffer,
11242 DEFAULT_MULTIBUFFER_CONTEXT,
11243 cx,
11244 ))
11245 }
11246
11247 multibuffer.with_title(title)
11248 });
11249
11250 let editor = cx.new(|cx| {
11251 Editor::for_multibuffer(
11252 excerpt_buffer,
11253 Some(workspace.project().clone()),
11254 true,
11255 window,
11256 cx,
11257 )
11258 });
11259 editor.update(cx, |editor, cx| {
11260 match multibuffer_selection_mode {
11261 MultibufferSelectionMode::First => {
11262 if let Some(first_range) = ranges.first() {
11263 editor.change_selections(None, window, cx, |selections| {
11264 selections.clear_disjoint();
11265 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11266 });
11267 }
11268 editor.highlight_background::<Self>(
11269 &ranges,
11270 |theme| theme.editor_highlighted_line_background,
11271 cx,
11272 );
11273 }
11274 MultibufferSelectionMode::All => {
11275 editor.change_selections(None, window, cx, |selections| {
11276 selections.clear_disjoint();
11277 selections.select_anchor_ranges(ranges);
11278 });
11279 }
11280 }
11281 editor.register_buffers_with_language_servers(cx);
11282 });
11283
11284 let item = Box::new(editor);
11285 let item_id = item.item_id();
11286
11287 if split {
11288 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11289 } else {
11290 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11291 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11292 pane.close_current_preview_item(window, cx)
11293 } else {
11294 None
11295 }
11296 });
11297 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11298 }
11299 workspace.active_pane().update(cx, |pane, cx| {
11300 pane.set_preview_item_id(Some(item_id), cx);
11301 });
11302 }
11303
11304 pub fn rename(
11305 &mut self,
11306 _: &Rename,
11307 window: &mut Window,
11308 cx: &mut Context<Self>,
11309 ) -> Option<Task<Result<()>>> {
11310 use language::ToOffset as _;
11311
11312 let provider = self.semantics_provider.clone()?;
11313 let selection = self.selections.newest_anchor().clone();
11314 let (cursor_buffer, cursor_buffer_position) = self
11315 .buffer
11316 .read(cx)
11317 .text_anchor_for_position(selection.head(), cx)?;
11318 let (tail_buffer, cursor_buffer_position_end) = self
11319 .buffer
11320 .read(cx)
11321 .text_anchor_for_position(selection.tail(), cx)?;
11322 if tail_buffer != cursor_buffer {
11323 return None;
11324 }
11325
11326 let snapshot = cursor_buffer.read(cx).snapshot();
11327 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11328 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11329 let prepare_rename = provider
11330 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11331 .unwrap_or_else(|| Task::ready(Ok(None)));
11332 drop(snapshot);
11333
11334 Some(cx.spawn_in(window, |this, mut cx| async move {
11335 let rename_range = if let Some(range) = prepare_rename.await? {
11336 Some(range)
11337 } else {
11338 this.update(&mut cx, |this, cx| {
11339 let buffer = this.buffer.read(cx).snapshot(cx);
11340 let mut buffer_highlights = this
11341 .document_highlights_for_position(selection.head(), &buffer)
11342 .filter(|highlight| {
11343 highlight.start.excerpt_id == selection.head().excerpt_id
11344 && highlight.end.excerpt_id == selection.head().excerpt_id
11345 });
11346 buffer_highlights
11347 .next()
11348 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11349 })?
11350 };
11351 if let Some(rename_range) = rename_range {
11352 this.update_in(&mut cx, |this, window, cx| {
11353 let snapshot = cursor_buffer.read(cx).snapshot();
11354 let rename_buffer_range = rename_range.to_offset(&snapshot);
11355 let cursor_offset_in_rename_range =
11356 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11357 let cursor_offset_in_rename_range_end =
11358 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11359
11360 this.take_rename(false, window, cx);
11361 let buffer = this.buffer.read(cx).read(cx);
11362 let cursor_offset = selection.head().to_offset(&buffer);
11363 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11364 let rename_end = rename_start + rename_buffer_range.len();
11365 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11366 let mut old_highlight_id = None;
11367 let old_name: Arc<str> = buffer
11368 .chunks(rename_start..rename_end, true)
11369 .map(|chunk| {
11370 if old_highlight_id.is_none() {
11371 old_highlight_id = chunk.syntax_highlight_id;
11372 }
11373 chunk.text
11374 })
11375 .collect::<String>()
11376 .into();
11377
11378 drop(buffer);
11379
11380 // Position the selection in the rename editor so that it matches the current selection.
11381 this.show_local_selections = false;
11382 let rename_editor = cx.new(|cx| {
11383 let mut editor = Editor::single_line(window, cx);
11384 editor.buffer.update(cx, |buffer, cx| {
11385 buffer.edit([(0..0, old_name.clone())], None, cx)
11386 });
11387 let rename_selection_range = match cursor_offset_in_rename_range
11388 .cmp(&cursor_offset_in_rename_range_end)
11389 {
11390 Ordering::Equal => {
11391 editor.select_all(&SelectAll, window, cx);
11392 return editor;
11393 }
11394 Ordering::Less => {
11395 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11396 }
11397 Ordering::Greater => {
11398 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11399 }
11400 };
11401 if rename_selection_range.end > old_name.len() {
11402 editor.select_all(&SelectAll, window, cx);
11403 } else {
11404 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11405 s.select_ranges([rename_selection_range]);
11406 });
11407 }
11408 editor
11409 });
11410 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11411 if e == &EditorEvent::Focused {
11412 cx.emit(EditorEvent::FocusedIn)
11413 }
11414 })
11415 .detach();
11416
11417 let write_highlights =
11418 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11419 let read_highlights =
11420 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11421 let ranges = write_highlights
11422 .iter()
11423 .flat_map(|(_, ranges)| ranges.iter())
11424 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11425 .cloned()
11426 .collect();
11427
11428 this.highlight_text::<Rename>(
11429 ranges,
11430 HighlightStyle {
11431 fade_out: Some(0.6),
11432 ..Default::default()
11433 },
11434 cx,
11435 );
11436 let rename_focus_handle = rename_editor.focus_handle(cx);
11437 window.focus(&rename_focus_handle);
11438 let block_id = this.insert_blocks(
11439 [BlockProperties {
11440 style: BlockStyle::Flex,
11441 placement: BlockPlacement::Below(range.start),
11442 height: 1,
11443 render: Arc::new({
11444 let rename_editor = rename_editor.clone();
11445 move |cx: &mut BlockContext| {
11446 let mut text_style = cx.editor_style.text.clone();
11447 if let Some(highlight_style) = old_highlight_id
11448 .and_then(|h| h.style(&cx.editor_style.syntax))
11449 {
11450 text_style = text_style.highlight(highlight_style);
11451 }
11452 div()
11453 .block_mouse_down()
11454 .pl(cx.anchor_x)
11455 .child(EditorElement::new(
11456 &rename_editor,
11457 EditorStyle {
11458 background: cx.theme().system().transparent,
11459 local_player: cx.editor_style.local_player,
11460 text: text_style,
11461 scrollbar_width: cx.editor_style.scrollbar_width,
11462 syntax: cx.editor_style.syntax.clone(),
11463 status: cx.editor_style.status.clone(),
11464 inlay_hints_style: HighlightStyle {
11465 font_weight: Some(FontWeight::BOLD),
11466 ..make_inlay_hints_style(cx.app)
11467 },
11468 inline_completion_styles: make_suggestion_styles(
11469 cx.app,
11470 ),
11471 ..EditorStyle::default()
11472 },
11473 ))
11474 .into_any_element()
11475 }
11476 }),
11477 priority: 0,
11478 }],
11479 Some(Autoscroll::fit()),
11480 cx,
11481 )[0];
11482 this.pending_rename = Some(RenameState {
11483 range,
11484 old_name,
11485 editor: rename_editor,
11486 block_id,
11487 });
11488 })?;
11489 }
11490
11491 Ok(())
11492 }))
11493 }
11494
11495 pub fn confirm_rename(
11496 &mut self,
11497 _: &ConfirmRename,
11498 window: &mut Window,
11499 cx: &mut Context<Self>,
11500 ) -> Option<Task<Result<()>>> {
11501 let rename = self.take_rename(false, window, cx)?;
11502 let workspace = self.workspace()?.downgrade();
11503 let (buffer, start) = self
11504 .buffer
11505 .read(cx)
11506 .text_anchor_for_position(rename.range.start, cx)?;
11507 let (end_buffer, _) = self
11508 .buffer
11509 .read(cx)
11510 .text_anchor_for_position(rename.range.end, cx)?;
11511 if buffer != end_buffer {
11512 return None;
11513 }
11514
11515 let old_name = rename.old_name;
11516 let new_name = rename.editor.read(cx).text(cx);
11517
11518 let rename = self.semantics_provider.as_ref()?.perform_rename(
11519 &buffer,
11520 start,
11521 new_name.clone(),
11522 cx,
11523 )?;
11524
11525 Some(cx.spawn_in(window, |editor, mut cx| async move {
11526 let project_transaction = rename.await?;
11527 Self::open_project_transaction(
11528 &editor,
11529 workspace,
11530 project_transaction,
11531 format!("Rename: {} → {}", old_name, new_name),
11532 cx.clone(),
11533 )
11534 .await?;
11535
11536 editor.update(&mut cx, |editor, cx| {
11537 editor.refresh_document_highlights(cx);
11538 })?;
11539 Ok(())
11540 }))
11541 }
11542
11543 fn take_rename(
11544 &mut self,
11545 moving_cursor: bool,
11546 window: &mut Window,
11547 cx: &mut Context<Self>,
11548 ) -> Option<RenameState> {
11549 let rename = self.pending_rename.take()?;
11550 if rename.editor.focus_handle(cx).is_focused(window) {
11551 window.focus(&self.focus_handle);
11552 }
11553
11554 self.remove_blocks(
11555 [rename.block_id].into_iter().collect(),
11556 Some(Autoscroll::fit()),
11557 cx,
11558 );
11559 self.clear_highlights::<Rename>(cx);
11560 self.show_local_selections = true;
11561
11562 if moving_cursor {
11563 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11564 editor.selections.newest::<usize>(cx).head()
11565 });
11566
11567 // Update the selection to match the position of the selection inside
11568 // the rename editor.
11569 let snapshot = self.buffer.read(cx).read(cx);
11570 let rename_range = rename.range.to_offset(&snapshot);
11571 let cursor_in_editor = snapshot
11572 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11573 .min(rename_range.end);
11574 drop(snapshot);
11575
11576 self.change_selections(None, window, cx, |s| {
11577 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11578 });
11579 } else {
11580 self.refresh_document_highlights(cx);
11581 }
11582
11583 Some(rename)
11584 }
11585
11586 pub fn pending_rename(&self) -> Option<&RenameState> {
11587 self.pending_rename.as_ref()
11588 }
11589
11590 fn format(
11591 &mut self,
11592 _: &Format,
11593 window: &mut Window,
11594 cx: &mut Context<Self>,
11595 ) -> Option<Task<Result<()>>> {
11596 let project = match &self.project {
11597 Some(project) => project.clone(),
11598 None => return None,
11599 };
11600
11601 Some(self.perform_format(
11602 project,
11603 FormatTrigger::Manual,
11604 FormatTarget::Buffers,
11605 window,
11606 cx,
11607 ))
11608 }
11609
11610 fn format_selections(
11611 &mut self,
11612 _: &FormatSelections,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) -> Option<Task<Result<()>>> {
11616 let project = match &self.project {
11617 Some(project) => project.clone(),
11618 None => return None,
11619 };
11620
11621 let ranges = self
11622 .selections
11623 .all_adjusted(cx)
11624 .into_iter()
11625 .map(|selection| selection.range())
11626 .collect_vec();
11627
11628 Some(self.perform_format(
11629 project,
11630 FormatTrigger::Manual,
11631 FormatTarget::Ranges(ranges),
11632 window,
11633 cx,
11634 ))
11635 }
11636
11637 fn perform_format(
11638 &mut self,
11639 project: Entity<Project>,
11640 trigger: FormatTrigger,
11641 target: FormatTarget,
11642 window: &mut Window,
11643 cx: &mut Context<Self>,
11644 ) -> Task<Result<()>> {
11645 let buffer = self.buffer.clone();
11646 let (buffers, target) = match target {
11647 FormatTarget::Buffers => {
11648 let mut buffers = buffer.read(cx).all_buffers();
11649 if trigger == FormatTrigger::Save {
11650 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11651 }
11652 (buffers, LspFormatTarget::Buffers)
11653 }
11654 FormatTarget::Ranges(selection_ranges) => {
11655 let multi_buffer = buffer.read(cx);
11656 let snapshot = multi_buffer.read(cx);
11657 let mut buffers = HashSet::default();
11658 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11659 BTreeMap::new();
11660 for selection_range in selection_ranges {
11661 for (buffer, buffer_range, _) in
11662 snapshot.range_to_buffer_ranges(selection_range)
11663 {
11664 let buffer_id = buffer.remote_id();
11665 let start = buffer.anchor_before(buffer_range.start);
11666 let end = buffer.anchor_after(buffer_range.end);
11667 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11668 buffer_id_to_ranges
11669 .entry(buffer_id)
11670 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11671 .or_insert_with(|| vec![start..end]);
11672 }
11673 }
11674 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11675 }
11676 };
11677
11678 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11679 let format = project.update(cx, |project, cx| {
11680 project.format(buffers, target, true, trigger, cx)
11681 });
11682
11683 cx.spawn_in(window, |_, mut cx| async move {
11684 let transaction = futures::select_biased! {
11685 () = timeout => {
11686 log::warn!("timed out waiting for formatting");
11687 None
11688 }
11689 transaction = format.log_err().fuse() => transaction,
11690 };
11691
11692 buffer
11693 .update(&mut cx, |buffer, cx| {
11694 if let Some(transaction) = transaction {
11695 if !buffer.is_singleton() {
11696 buffer.push_transaction(&transaction.0, cx);
11697 }
11698 }
11699
11700 cx.notify();
11701 })
11702 .ok();
11703
11704 Ok(())
11705 })
11706 }
11707
11708 fn restart_language_server(
11709 &mut self,
11710 _: &RestartLanguageServer,
11711 _: &mut Window,
11712 cx: &mut Context<Self>,
11713 ) {
11714 if let Some(project) = self.project.clone() {
11715 self.buffer.update(cx, |multi_buffer, cx| {
11716 project.update(cx, |project, cx| {
11717 project.restart_language_servers_for_buffers(
11718 multi_buffer.all_buffers().into_iter().collect(),
11719 cx,
11720 );
11721 });
11722 })
11723 }
11724 }
11725
11726 fn cancel_language_server_work(
11727 workspace: &mut Workspace,
11728 _: &actions::CancelLanguageServerWork,
11729 _: &mut Window,
11730 cx: &mut Context<Workspace>,
11731 ) {
11732 let project = workspace.project();
11733 let buffers = workspace
11734 .active_item(cx)
11735 .and_then(|item| item.act_as::<Editor>(cx))
11736 .map_or(HashSet::default(), |editor| {
11737 editor.read(cx).buffer.read(cx).all_buffers()
11738 });
11739 project.update(cx, |project, cx| {
11740 project.cancel_language_server_work_for_buffers(buffers, cx);
11741 });
11742 }
11743
11744 fn show_character_palette(
11745 &mut self,
11746 _: &ShowCharacterPalette,
11747 window: &mut Window,
11748 _: &mut Context<Self>,
11749 ) {
11750 window.show_character_palette();
11751 }
11752
11753 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11754 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11755 let buffer = self.buffer.read(cx).snapshot(cx);
11756 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11757 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11758 let is_valid = buffer
11759 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11760 .any(|entry| {
11761 entry.diagnostic.is_primary
11762 && !entry.range.is_empty()
11763 && entry.range.start == primary_range_start
11764 && entry.diagnostic.message == active_diagnostics.primary_message
11765 });
11766
11767 if is_valid != active_diagnostics.is_valid {
11768 active_diagnostics.is_valid = is_valid;
11769 let mut new_styles = HashMap::default();
11770 for (block_id, diagnostic) in &active_diagnostics.blocks {
11771 new_styles.insert(
11772 *block_id,
11773 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11774 );
11775 }
11776 self.display_map.update(cx, |display_map, _cx| {
11777 display_map.replace_blocks(new_styles)
11778 });
11779 }
11780 }
11781 }
11782
11783 fn activate_diagnostics(
11784 &mut self,
11785 buffer_id: BufferId,
11786 group_id: usize,
11787 window: &mut Window,
11788 cx: &mut Context<Self>,
11789 ) {
11790 self.dismiss_diagnostics(cx);
11791 let snapshot = self.snapshot(window, cx);
11792 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11793 let buffer = self.buffer.read(cx).snapshot(cx);
11794
11795 let mut primary_range = None;
11796 let mut primary_message = None;
11797 let diagnostic_group = buffer
11798 .diagnostic_group(buffer_id, group_id)
11799 .filter_map(|entry| {
11800 let start = entry.range.start;
11801 let end = entry.range.end;
11802 if snapshot.is_line_folded(MultiBufferRow(start.row))
11803 && (start.row == end.row
11804 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11805 {
11806 return None;
11807 }
11808 if entry.diagnostic.is_primary {
11809 primary_range = Some(entry.range.clone());
11810 primary_message = Some(entry.diagnostic.message.clone());
11811 }
11812 Some(entry)
11813 })
11814 .collect::<Vec<_>>();
11815 let primary_range = primary_range?;
11816 let primary_message = primary_message?;
11817
11818 let blocks = display_map
11819 .insert_blocks(
11820 diagnostic_group.iter().map(|entry| {
11821 let diagnostic = entry.diagnostic.clone();
11822 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11823 BlockProperties {
11824 style: BlockStyle::Fixed,
11825 placement: BlockPlacement::Below(
11826 buffer.anchor_after(entry.range.start),
11827 ),
11828 height: message_height,
11829 render: diagnostic_block_renderer(diagnostic, None, true, true),
11830 priority: 0,
11831 }
11832 }),
11833 cx,
11834 )
11835 .into_iter()
11836 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11837 .collect();
11838
11839 Some(ActiveDiagnosticGroup {
11840 primary_range: buffer.anchor_before(primary_range.start)
11841 ..buffer.anchor_after(primary_range.end),
11842 primary_message,
11843 group_id,
11844 blocks,
11845 is_valid: true,
11846 })
11847 });
11848 }
11849
11850 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11851 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11852 self.display_map.update(cx, |display_map, cx| {
11853 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11854 });
11855 cx.notify();
11856 }
11857 }
11858
11859 pub fn set_selections_from_remote(
11860 &mut self,
11861 selections: Vec<Selection<Anchor>>,
11862 pending_selection: Option<Selection<Anchor>>,
11863 window: &mut Window,
11864 cx: &mut Context<Self>,
11865 ) {
11866 let old_cursor_position = self.selections.newest_anchor().head();
11867 self.selections.change_with(cx, |s| {
11868 s.select_anchors(selections);
11869 if let Some(pending_selection) = pending_selection {
11870 s.set_pending(pending_selection, SelectMode::Character);
11871 } else {
11872 s.clear_pending();
11873 }
11874 });
11875 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11876 }
11877
11878 fn push_to_selection_history(&mut self) {
11879 self.selection_history.push(SelectionHistoryEntry {
11880 selections: self.selections.disjoint_anchors(),
11881 select_next_state: self.select_next_state.clone(),
11882 select_prev_state: self.select_prev_state.clone(),
11883 add_selections_state: self.add_selections_state.clone(),
11884 });
11885 }
11886
11887 pub fn transact(
11888 &mut self,
11889 window: &mut Window,
11890 cx: &mut Context<Self>,
11891 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11892 ) -> Option<TransactionId> {
11893 self.start_transaction_at(Instant::now(), window, cx);
11894 update(self, window, cx);
11895 self.end_transaction_at(Instant::now(), cx)
11896 }
11897
11898 pub fn start_transaction_at(
11899 &mut self,
11900 now: Instant,
11901 window: &mut Window,
11902 cx: &mut Context<Self>,
11903 ) {
11904 self.end_selection(window, cx);
11905 if let Some(tx_id) = self
11906 .buffer
11907 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11908 {
11909 self.selection_history
11910 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11911 cx.emit(EditorEvent::TransactionBegun {
11912 transaction_id: tx_id,
11913 })
11914 }
11915 }
11916
11917 pub fn end_transaction_at(
11918 &mut self,
11919 now: Instant,
11920 cx: &mut Context<Self>,
11921 ) -> Option<TransactionId> {
11922 if let Some(transaction_id) = self
11923 .buffer
11924 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11925 {
11926 if let Some((_, end_selections)) =
11927 self.selection_history.transaction_mut(transaction_id)
11928 {
11929 *end_selections = Some(self.selections.disjoint_anchors());
11930 } else {
11931 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11932 }
11933
11934 cx.emit(EditorEvent::Edited { transaction_id });
11935 Some(transaction_id)
11936 } else {
11937 None
11938 }
11939 }
11940
11941 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11942 if self.selection_mark_mode {
11943 self.change_selections(None, window, cx, |s| {
11944 s.move_with(|_, sel| {
11945 sel.collapse_to(sel.head(), SelectionGoal::None);
11946 });
11947 })
11948 }
11949 self.selection_mark_mode = true;
11950 cx.notify();
11951 }
11952
11953 pub fn swap_selection_ends(
11954 &mut self,
11955 _: &actions::SwapSelectionEnds,
11956 window: &mut Window,
11957 cx: &mut Context<Self>,
11958 ) {
11959 self.change_selections(None, window, cx, |s| {
11960 s.move_with(|_, sel| {
11961 if sel.start != sel.end {
11962 sel.reversed = !sel.reversed
11963 }
11964 });
11965 });
11966 self.request_autoscroll(Autoscroll::newest(), cx);
11967 cx.notify();
11968 }
11969
11970 pub fn toggle_fold(
11971 &mut self,
11972 _: &actions::ToggleFold,
11973 window: &mut Window,
11974 cx: &mut Context<Self>,
11975 ) {
11976 if self.is_singleton(cx) {
11977 let selection = self.selections.newest::<Point>(cx);
11978
11979 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11980 let range = if selection.is_empty() {
11981 let point = selection.head().to_display_point(&display_map);
11982 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11983 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11984 .to_point(&display_map);
11985 start..end
11986 } else {
11987 selection.range()
11988 };
11989 if display_map.folds_in_range(range).next().is_some() {
11990 self.unfold_lines(&Default::default(), window, cx)
11991 } else {
11992 self.fold(&Default::default(), window, cx)
11993 }
11994 } else {
11995 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11996 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11997 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11998 .map(|(snapshot, _, _)| snapshot.remote_id())
11999 .collect();
12000
12001 for buffer_id in buffer_ids {
12002 if self.is_buffer_folded(buffer_id, cx) {
12003 self.unfold_buffer(buffer_id, cx);
12004 } else {
12005 self.fold_buffer(buffer_id, cx);
12006 }
12007 }
12008 }
12009 }
12010
12011 pub fn toggle_fold_recursive(
12012 &mut self,
12013 _: &actions::ToggleFoldRecursive,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) {
12017 let selection = self.selections.newest::<Point>(cx);
12018
12019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12020 let range = if selection.is_empty() {
12021 let point = selection.head().to_display_point(&display_map);
12022 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12023 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12024 .to_point(&display_map);
12025 start..end
12026 } else {
12027 selection.range()
12028 };
12029 if display_map.folds_in_range(range).next().is_some() {
12030 self.unfold_recursive(&Default::default(), window, cx)
12031 } else {
12032 self.fold_recursive(&Default::default(), window, cx)
12033 }
12034 }
12035
12036 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12037 if self.is_singleton(cx) {
12038 let mut to_fold = Vec::new();
12039 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12040 let selections = self.selections.all_adjusted(cx);
12041
12042 for selection in selections {
12043 let range = selection.range().sorted();
12044 let buffer_start_row = range.start.row;
12045
12046 if range.start.row != range.end.row {
12047 let mut found = false;
12048 let mut row = range.start.row;
12049 while row <= range.end.row {
12050 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12051 {
12052 found = true;
12053 row = crease.range().end.row + 1;
12054 to_fold.push(crease);
12055 } else {
12056 row += 1
12057 }
12058 }
12059 if found {
12060 continue;
12061 }
12062 }
12063
12064 for row in (0..=range.start.row).rev() {
12065 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12066 if crease.range().end.row >= buffer_start_row {
12067 to_fold.push(crease);
12068 if row <= range.start.row {
12069 break;
12070 }
12071 }
12072 }
12073 }
12074 }
12075
12076 self.fold_creases(to_fold, true, window, cx);
12077 } else {
12078 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12079
12080 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12081 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12082 .map(|(snapshot, _, _)| snapshot.remote_id())
12083 .collect();
12084 for buffer_id in buffer_ids {
12085 self.fold_buffer(buffer_id, cx);
12086 }
12087 }
12088 }
12089
12090 fn fold_at_level(
12091 &mut self,
12092 fold_at: &FoldAtLevel,
12093 window: &mut Window,
12094 cx: &mut Context<Self>,
12095 ) {
12096 if !self.buffer.read(cx).is_singleton() {
12097 return;
12098 }
12099
12100 let fold_at_level = fold_at.0;
12101 let snapshot = self.buffer.read(cx).snapshot(cx);
12102 let mut to_fold = Vec::new();
12103 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12104
12105 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12106 while start_row < end_row {
12107 match self
12108 .snapshot(window, cx)
12109 .crease_for_buffer_row(MultiBufferRow(start_row))
12110 {
12111 Some(crease) => {
12112 let nested_start_row = crease.range().start.row + 1;
12113 let nested_end_row = crease.range().end.row;
12114
12115 if current_level < fold_at_level {
12116 stack.push((nested_start_row, nested_end_row, current_level + 1));
12117 } else if current_level == fold_at_level {
12118 to_fold.push(crease);
12119 }
12120
12121 start_row = nested_end_row + 1;
12122 }
12123 None => start_row += 1,
12124 }
12125 }
12126 }
12127
12128 self.fold_creases(to_fold, true, window, cx);
12129 }
12130
12131 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12132 if self.buffer.read(cx).is_singleton() {
12133 let mut fold_ranges = Vec::new();
12134 let snapshot = self.buffer.read(cx).snapshot(cx);
12135
12136 for row in 0..snapshot.max_row().0 {
12137 if let Some(foldable_range) = self
12138 .snapshot(window, cx)
12139 .crease_for_buffer_row(MultiBufferRow(row))
12140 {
12141 fold_ranges.push(foldable_range);
12142 }
12143 }
12144
12145 self.fold_creases(fold_ranges, true, window, cx);
12146 } else {
12147 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12148 editor
12149 .update_in(&mut cx, |editor, _, cx| {
12150 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12151 editor.fold_buffer(buffer_id, cx);
12152 }
12153 })
12154 .ok();
12155 });
12156 }
12157 }
12158
12159 pub fn fold_function_bodies(
12160 &mut self,
12161 _: &actions::FoldFunctionBodies,
12162 window: &mut Window,
12163 cx: &mut Context<Self>,
12164 ) {
12165 let snapshot = self.buffer.read(cx).snapshot(cx);
12166
12167 let ranges = snapshot
12168 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12169 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12170 .collect::<Vec<_>>();
12171
12172 let creases = ranges
12173 .into_iter()
12174 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12175 .collect();
12176
12177 self.fold_creases(creases, true, window, cx);
12178 }
12179
12180 pub fn fold_recursive(
12181 &mut self,
12182 _: &actions::FoldRecursive,
12183 window: &mut Window,
12184 cx: &mut Context<Self>,
12185 ) {
12186 let mut to_fold = Vec::new();
12187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12188 let selections = self.selections.all_adjusted(cx);
12189
12190 for selection in selections {
12191 let range = selection.range().sorted();
12192 let buffer_start_row = range.start.row;
12193
12194 if range.start.row != range.end.row {
12195 let mut found = false;
12196 for row in range.start.row..=range.end.row {
12197 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12198 found = true;
12199 to_fold.push(crease);
12200 }
12201 }
12202 if found {
12203 continue;
12204 }
12205 }
12206
12207 for row in (0..=range.start.row).rev() {
12208 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12209 if crease.range().end.row >= buffer_start_row {
12210 to_fold.push(crease);
12211 } else {
12212 break;
12213 }
12214 }
12215 }
12216 }
12217
12218 self.fold_creases(to_fold, true, window, cx);
12219 }
12220
12221 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12222 let buffer_row = fold_at.buffer_row;
12223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12224
12225 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12226 let autoscroll = self
12227 .selections
12228 .all::<Point>(cx)
12229 .iter()
12230 .any(|selection| crease.range().overlaps(&selection.range()));
12231
12232 self.fold_creases(vec![crease], autoscroll, window, cx);
12233 }
12234 }
12235
12236 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12237 if self.is_singleton(cx) {
12238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12239 let buffer = &display_map.buffer_snapshot;
12240 let selections = self.selections.all::<Point>(cx);
12241 let ranges = selections
12242 .iter()
12243 .map(|s| {
12244 let range = s.display_range(&display_map).sorted();
12245 let mut start = range.start.to_point(&display_map);
12246 let mut end = range.end.to_point(&display_map);
12247 start.column = 0;
12248 end.column = buffer.line_len(MultiBufferRow(end.row));
12249 start..end
12250 })
12251 .collect::<Vec<_>>();
12252
12253 self.unfold_ranges(&ranges, true, true, cx);
12254 } else {
12255 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12256 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12257 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12258 .map(|(snapshot, _, _)| snapshot.remote_id())
12259 .collect();
12260 for buffer_id in buffer_ids {
12261 self.unfold_buffer(buffer_id, cx);
12262 }
12263 }
12264 }
12265
12266 pub fn unfold_recursive(
12267 &mut self,
12268 _: &UnfoldRecursive,
12269 _window: &mut Window,
12270 cx: &mut Context<Self>,
12271 ) {
12272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12273 let selections = self.selections.all::<Point>(cx);
12274 let ranges = selections
12275 .iter()
12276 .map(|s| {
12277 let mut range = s.display_range(&display_map).sorted();
12278 *range.start.column_mut() = 0;
12279 *range.end.column_mut() = display_map.line_len(range.end.row());
12280 let start = range.start.to_point(&display_map);
12281 let end = range.end.to_point(&display_map);
12282 start..end
12283 })
12284 .collect::<Vec<_>>();
12285
12286 self.unfold_ranges(&ranges, true, true, cx);
12287 }
12288
12289 pub fn unfold_at(
12290 &mut self,
12291 unfold_at: &UnfoldAt,
12292 _window: &mut Window,
12293 cx: &mut Context<Self>,
12294 ) {
12295 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12296
12297 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12298 ..Point::new(
12299 unfold_at.buffer_row.0,
12300 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12301 );
12302
12303 let autoscroll = self
12304 .selections
12305 .all::<Point>(cx)
12306 .iter()
12307 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12308
12309 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12310 }
12311
12312 pub fn unfold_all(
12313 &mut self,
12314 _: &actions::UnfoldAll,
12315 _window: &mut Window,
12316 cx: &mut Context<Self>,
12317 ) {
12318 if self.buffer.read(cx).is_singleton() {
12319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12320 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12321 } else {
12322 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12323 editor
12324 .update(&mut cx, |editor, cx| {
12325 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12326 editor.unfold_buffer(buffer_id, cx);
12327 }
12328 })
12329 .ok();
12330 });
12331 }
12332 }
12333
12334 pub fn fold_selected_ranges(
12335 &mut self,
12336 _: &FoldSelectedRanges,
12337 window: &mut Window,
12338 cx: &mut Context<Self>,
12339 ) {
12340 let selections = self.selections.all::<Point>(cx);
12341 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12342 let line_mode = self.selections.line_mode;
12343 let ranges = selections
12344 .into_iter()
12345 .map(|s| {
12346 if line_mode {
12347 let start = Point::new(s.start.row, 0);
12348 let end = Point::new(
12349 s.end.row,
12350 display_map
12351 .buffer_snapshot
12352 .line_len(MultiBufferRow(s.end.row)),
12353 );
12354 Crease::simple(start..end, display_map.fold_placeholder.clone())
12355 } else {
12356 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12357 }
12358 })
12359 .collect::<Vec<_>>();
12360 self.fold_creases(ranges, true, window, cx);
12361 }
12362
12363 pub fn fold_ranges<T: ToOffset + Clone>(
12364 &mut self,
12365 ranges: Vec<Range<T>>,
12366 auto_scroll: bool,
12367 window: &mut Window,
12368 cx: &mut Context<Self>,
12369 ) {
12370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12371 let ranges = ranges
12372 .into_iter()
12373 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12374 .collect::<Vec<_>>();
12375 self.fold_creases(ranges, auto_scroll, window, cx);
12376 }
12377
12378 pub fn fold_creases<T: ToOffset + Clone>(
12379 &mut self,
12380 creases: Vec<Crease<T>>,
12381 auto_scroll: bool,
12382 window: &mut Window,
12383 cx: &mut Context<Self>,
12384 ) {
12385 if creases.is_empty() {
12386 return;
12387 }
12388
12389 let mut buffers_affected = HashSet::default();
12390 let multi_buffer = self.buffer().read(cx);
12391 for crease in &creases {
12392 if let Some((_, buffer, _)) =
12393 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12394 {
12395 buffers_affected.insert(buffer.read(cx).remote_id());
12396 };
12397 }
12398
12399 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12400
12401 if auto_scroll {
12402 self.request_autoscroll(Autoscroll::fit(), cx);
12403 }
12404
12405 cx.notify();
12406
12407 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12408 // Clear diagnostics block when folding a range that contains it.
12409 let snapshot = self.snapshot(window, cx);
12410 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12411 drop(snapshot);
12412 self.active_diagnostics = Some(active_diagnostics);
12413 self.dismiss_diagnostics(cx);
12414 } else {
12415 self.active_diagnostics = Some(active_diagnostics);
12416 }
12417 }
12418
12419 self.scrollbar_marker_state.dirty = true;
12420 }
12421
12422 /// Removes any folds whose ranges intersect any of the given ranges.
12423 pub fn unfold_ranges<T: ToOffset + Clone>(
12424 &mut self,
12425 ranges: &[Range<T>],
12426 inclusive: bool,
12427 auto_scroll: bool,
12428 cx: &mut Context<Self>,
12429 ) {
12430 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12431 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12432 });
12433 }
12434
12435 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12436 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12437 return;
12438 }
12439 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12440 self.display_map
12441 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12442 cx.emit(EditorEvent::BufferFoldToggled {
12443 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12444 folded: true,
12445 });
12446 cx.notify();
12447 }
12448
12449 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12450 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12451 return;
12452 }
12453 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12454 self.display_map.update(cx, |display_map, cx| {
12455 display_map.unfold_buffer(buffer_id, cx);
12456 });
12457 cx.emit(EditorEvent::BufferFoldToggled {
12458 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12459 folded: false,
12460 });
12461 cx.notify();
12462 }
12463
12464 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12465 self.display_map.read(cx).is_buffer_folded(buffer)
12466 }
12467
12468 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12469 self.display_map.read(cx).folded_buffers()
12470 }
12471
12472 /// Removes any folds with the given ranges.
12473 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12474 &mut self,
12475 ranges: &[Range<T>],
12476 type_id: TypeId,
12477 auto_scroll: bool,
12478 cx: &mut Context<Self>,
12479 ) {
12480 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12481 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12482 });
12483 }
12484
12485 fn remove_folds_with<T: ToOffset + Clone>(
12486 &mut self,
12487 ranges: &[Range<T>],
12488 auto_scroll: bool,
12489 cx: &mut Context<Self>,
12490 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12491 ) {
12492 if ranges.is_empty() {
12493 return;
12494 }
12495
12496 let mut buffers_affected = HashSet::default();
12497 let multi_buffer = self.buffer().read(cx);
12498 for range in ranges {
12499 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12500 buffers_affected.insert(buffer.read(cx).remote_id());
12501 };
12502 }
12503
12504 self.display_map.update(cx, update);
12505
12506 if auto_scroll {
12507 self.request_autoscroll(Autoscroll::fit(), cx);
12508 }
12509
12510 cx.notify();
12511 self.scrollbar_marker_state.dirty = true;
12512 self.active_indent_guides_state.dirty = true;
12513 }
12514
12515 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12516 self.display_map.read(cx).fold_placeholder.clone()
12517 }
12518
12519 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12520 self.buffer.update(cx, |buffer, cx| {
12521 buffer.set_all_diff_hunks_expanded(cx);
12522 });
12523 }
12524
12525 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12526 self.distinguish_unstaged_diff_hunks = true;
12527 }
12528
12529 pub fn expand_all_diff_hunks(
12530 &mut self,
12531 _: &ExpandAllHunkDiffs,
12532 _window: &mut Window,
12533 cx: &mut Context<Self>,
12534 ) {
12535 self.buffer.update(cx, |buffer, cx| {
12536 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12537 });
12538 }
12539
12540 pub fn toggle_selected_diff_hunks(
12541 &mut self,
12542 _: &ToggleSelectedDiffHunks,
12543 _window: &mut Window,
12544 cx: &mut Context<Self>,
12545 ) {
12546 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12547 self.toggle_diff_hunks_in_ranges(ranges, cx);
12548 }
12549
12550 fn diff_hunks_in_ranges<'a>(
12551 &'a self,
12552 ranges: &'a [Range<Anchor>],
12553 buffer: &'a MultiBufferSnapshot,
12554 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12555 ranges.iter().flat_map(move |range| {
12556 let end_excerpt_id = range.end.excerpt_id;
12557 let range = range.to_point(buffer);
12558 let mut peek_end = range.end;
12559 if range.end.row < buffer.max_row().0 {
12560 peek_end = Point::new(range.end.row + 1, 0);
12561 }
12562 buffer
12563 .diff_hunks_in_range(range.start..peek_end)
12564 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12565 })
12566 }
12567
12568 pub fn has_stageable_diff_hunks_in_ranges(
12569 &self,
12570 ranges: &[Range<Anchor>],
12571 snapshot: &MultiBufferSnapshot,
12572 ) -> bool {
12573 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12574 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12575 }
12576
12577 pub fn toggle_staged_selected_diff_hunks(
12578 &mut self,
12579 _: &ToggleStagedSelectedDiffHunks,
12580 _window: &mut Window,
12581 cx: &mut Context<Self>,
12582 ) {
12583 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12584 self.stage_or_unstage_diff_hunks(&ranges, cx);
12585 }
12586
12587 pub fn stage_or_unstage_diff_hunks(
12588 &mut self,
12589 ranges: &[Range<Anchor>],
12590 cx: &mut Context<Self>,
12591 ) {
12592 let Some(project) = &self.project else {
12593 return;
12594 };
12595 let snapshot = self.buffer.read(cx).snapshot(cx);
12596 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12597
12598 let chunk_by = self
12599 .diff_hunks_in_ranges(&ranges, &snapshot)
12600 .chunk_by(|hunk| hunk.buffer_id);
12601 for (buffer_id, hunks) in &chunk_by {
12602 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12603 log::debug!("no buffer for id");
12604 continue;
12605 };
12606 let buffer = buffer.read(cx).snapshot();
12607 let Some((repo, path)) = project
12608 .read(cx)
12609 .repository_and_path_for_buffer_id(buffer_id, cx)
12610 else {
12611 log::debug!("no git repo for buffer id");
12612 continue;
12613 };
12614 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12615 log::debug!("no diff for buffer id");
12616 continue;
12617 };
12618 let Some(secondary_diff) = diff.secondary_diff() else {
12619 log::debug!("no secondary diff for buffer id");
12620 continue;
12621 };
12622
12623 let edits = diff.secondary_edits_for_stage_or_unstage(
12624 stage,
12625 hunks.map(|hunk| {
12626 (
12627 hunk.diff_base_byte_range.clone(),
12628 hunk.secondary_diff_base_byte_range.clone(),
12629 hunk.buffer_range.clone(),
12630 )
12631 }),
12632 &buffer,
12633 );
12634
12635 let index_base = secondary_diff.base_text().map_or_else(
12636 || Rope::from(""),
12637 |snapshot| snapshot.text.as_rope().clone(),
12638 );
12639 let index_buffer = cx.new(|cx| {
12640 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12641 });
12642 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12643 index_buffer.edit(edits, None, cx);
12644 index_buffer.snapshot().as_rope().to_string()
12645 });
12646 let new_index_text = if new_index_text.is_empty()
12647 && (diff.is_single_insertion
12648 || buffer
12649 .file()
12650 .map_or(false, |file| file.disk_state() == DiskState::New))
12651 {
12652 log::debug!("removing from index");
12653 None
12654 } else {
12655 Some(new_index_text)
12656 };
12657
12658 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12659 }
12660 }
12661
12662 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12663 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12664 self.buffer
12665 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12666 }
12667
12668 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12669 self.buffer.update(cx, |buffer, cx| {
12670 let ranges = vec![Anchor::min()..Anchor::max()];
12671 if !buffer.all_diff_hunks_expanded()
12672 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12673 {
12674 buffer.collapse_diff_hunks(ranges, cx);
12675 true
12676 } else {
12677 false
12678 }
12679 })
12680 }
12681
12682 fn toggle_diff_hunks_in_ranges(
12683 &mut self,
12684 ranges: Vec<Range<Anchor>>,
12685 cx: &mut Context<'_, Editor>,
12686 ) {
12687 self.buffer.update(cx, |buffer, cx| {
12688 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12689 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12690 })
12691 }
12692
12693 fn toggle_diff_hunks_in_ranges_narrow(
12694 &mut self,
12695 ranges: Vec<Range<Anchor>>,
12696 cx: &mut Context<'_, Editor>,
12697 ) {
12698 self.buffer.update(cx, |buffer, cx| {
12699 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12700 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12701 })
12702 }
12703
12704 pub(crate) fn apply_all_diff_hunks(
12705 &mut self,
12706 _: &ApplyAllDiffHunks,
12707 window: &mut Window,
12708 cx: &mut Context<Self>,
12709 ) {
12710 let buffers = self.buffer.read(cx).all_buffers();
12711 for branch_buffer in buffers {
12712 branch_buffer.update(cx, |branch_buffer, cx| {
12713 branch_buffer.merge_into_base(Vec::new(), cx);
12714 });
12715 }
12716
12717 if let Some(project) = self.project.clone() {
12718 self.save(true, project, window, cx).detach_and_log_err(cx);
12719 }
12720 }
12721
12722 pub(crate) fn apply_selected_diff_hunks(
12723 &mut self,
12724 _: &ApplyDiffHunk,
12725 window: &mut Window,
12726 cx: &mut Context<Self>,
12727 ) {
12728 let snapshot = self.snapshot(window, cx);
12729 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12730 let mut ranges_by_buffer = HashMap::default();
12731 self.transact(window, cx, |editor, _window, cx| {
12732 for hunk in hunks {
12733 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12734 ranges_by_buffer
12735 .entry(buffer.clone())
12736 .or_insert_with(Vec::new)
12737 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12738 }
12739 }
12740
12741 for (buffer, ranges) in ranges_by_buffer {
12742 buffer.update(cx, |buffer, cx| {
12743 buffer.merge_into_base(ranges, cx);
12744 });
12745 }
12746 });
12747
12748 if let Some(project) = self.project.clone() {
12749 self.save(true, project, window, cx).detach_and_log_err(cx);
12750 }
12751 }
12752
12753 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12754 if hovered != self.gutter_hovered {
12755 self.gutter_hovered = hovered;
12756 cx.notify();
12757 }
12758 }
12759
12760 pub fn insert_blocks(
12761 &mut self,
12762 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12763 autoscroll: Option<Autoscroll>,
12764 cx: &mut Context<Self>,
12765 ) -> Vec<CustomBlockId> {
12766 let blocks = self
12767 .display_map
12768 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12769 if let Some(autoscroll) = autoscroll {
12770 self.request_autoscroll(autoscroll, cx);
12771 }
12772 cx.notify();
12773 blocks
12774 }
12775
12776 pub fn resize_blocks(
12777 &mut self,
12778 heights: HashMap<CustomBlockId, u32>,
12779 autoscroll: Option<Autoscroll>,
12780 cx: &mut Context<Self>,
12781 ) {
12782 self.display_map
12783 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12784 if let Some(autoscroll) = autoscroll {
12785 self.request_autoscroll(autoscroll, cx);
12786 }
12787 cx.notify();
12788 }
12789
12790 pub fn replace_blocks(
12791 &mut self,
12792 renderers: HashMap<CustomBlockId, RenderBlock>,
12793 autoscroll: Option<Autoscroll>,
12794 cx: &mut Context<Self>,
12795 ) {
12796 self.display_map
12797 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12798 if let Some(autoscroll) = autoscroll {
12799 self.request_autoscroll(autoscroll, cx);
12800 }
12801 cx.notify();
12802 }
12803
12804 pub fn remove_blocks(
12805 &mut self,
12806 block_ids: HashSet<CustomBlockId>,
12807 autoscroll: Option<Autoscroll>,
12808 cx: &mut Context<Self>,
12809 ) {
12810 self.display_map.update(cx, |display_map, cx| {
12811 display_map.remove_blocks(block_ids, cx)
12812 });
12813 if let Some(autoscroll) = autoscroll {
12814 self.request_autoscroll(autoscroll, cx);
12815 }
12816 cx.notify();
12817 }
12818
12819 pub fn row_for_block(
12820 &self,
12821 block_id: CustomBlockId,
12822 cx: &mut Context<Self>,
12823 ) -> Option<DisplayRow> {
12824 self.display_map
12825 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12826 }
12827
12828 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12829 self.focused_block = Some(focused_block);
12830 }
12831
12832 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12833 self.focused_block.take()
12834 }
12835
12836 pub fn insert_creases(
12837 &mut self,
12838 creases: impl IntoIterator<Item = Crease<Anchor>>,
12839 cx: &mut Context<Self>,
12840 ) -> Vec<CreaseId> {
12841 self.display_map
12842 .update(cx, |map, cx| map.insert_creases(creases, cx))
12843 }
12844
12845 pub fn remove_creases(
12846 &mut self,
12847 ids: impl IntoIterator<Item = CreaseId>,
12848 cx: &mut Context<Self>,
12849 ) {
12850 self.display_map
12851 .update(cx, |map, cx| map.remove_creases(ids, cx));
12852 }
12853
12854 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12855 self.display_map
12856 .update(cx, |map, cx| map.snapshot(cx))
12857 .longest_row()
12858 }
12859
12860 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12861 self.display_map
12862 .update(cx, |map, cx| map.snapshot(cx))
12863 .max_point()
12864 }
12865
12866 pub fn text(&self, cx: &App) -> String {
12867 self.buffer.read(cx).read(cx).text()
12868 }
12869
12870 pub fn is_empty(&self, cx: &App) -> bool {
12871 self.buffer.read(cx).read(cx).is_empty()
12872 }
12873
12874 pub fn text_option(&self, cx: &App) -> Option<String> {
12875 let text = self.text(cx);
12876 let text = text.trim();
12877
12878 if text.is_empty() {
12879 return None;
12880 }
12881
12882 Some(text.to_string())
12883 }
12884
12885 pub fn set_text(
12886 &mut self,
12887 text: impl Into<Arc<str>>,
12888 window: &mut Window,
12889 cx: &mut Context<Self>,
12890 ) {
12891 self.transact(window, cx, |this, _, cx| {
12892 this.buffer
12893 .read(cx)
12894 .as_singleton()
12895 .expect("you can only call set_text on editors for singleton buffers")
12896 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12897 });
12898 }
12899
12900 pub fn display_text(&self, cx: &mut App) -> String {
12901 self.display_map
12902 .update(cx, |map, cx| map.snapshot(cx))
12903 .text()
12904 }
12905
12906 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12907 let mut wrap_guides = smallvec::smallvec![];
12908
12909 if self.show_wrap_guides == Some(false) {
12910 return wrap_guides;
12911 }
12912
12913 let settings = self.buffer.read(cx).settings_at(0, cx);
12914 if settings.show_wrap_guides {
12915 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12916 wrap_guides.push((soft_wrap as usize, true));
12917 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12918 wrap_guides.push((soft_wrap as usize, true));
12919 }
12920 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12921 }
12922
12923 wrap_guides
12924 }
12925
12926 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12927 let settings = self.buffer.read(cx).settings_at(0, cx);
12928 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12929 match mode {
12930 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12931 SoftWrap::None
12932 }
12933 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12934 language_settings::SoftWrap::PreferredLineLength => {
12935 SoftWrap::Column(settings.preferred_line_length)
12936 }
12937 language_settings::SoftWrap::Bounded => {
12938 SoftWrap::Bounded(settings.preferred_line_length)
12939 }
12940 }
12941 }
12942
12943 pub fn set_soft_wrap_mode(
12944 &mut self,
12945 mode: language_settings::SoftWrap,
12946
12947 cx: &mut Context<Self>,
12948 ) {
12949 self.soft_wrap_mode_override = Some(mode);
12950 cx.notify();
12951 }
12952
12953 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12954 self.text_style_refinement = Some(style);
12955 }
12956
12957 /// called by the Element so we know what style we were most recently rendered with.
12958 pub(crate) fn set_style(
12959 &mut self,
12960 style: EditorStyle,
12961 window: &mut Window,
12962 cx: &mut Context<Self>,
12963 ) {
12964 let rem_size = window.rem_size();
12965 self.display_map.update(cx, |map, cx| {
12966 map.set_font(
12967 style.text.font(),
12968 style.text.font_size.to_pixels(rem_size),
12969 cx,
12970 )
12971 });
12972 self.style = Some(style);
12973 }
12974
12975 pub fn style(&self) -> Option<&EditorStyle> {
12976 self.style.as_ref()
12977 }
12978
12979 // Called by the element. This method is not designed to be called outside of the editor
12980 // element's layout code because it does not notify when rewrapping is computed synchronously.
12981 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12982 self.display_map
12983 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12984 }
12985
12986 pub fn set_soft_wrap(&mut self) {
12987 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12988 }
12989
12990 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12991 if self.soft_wrap_mode_override.is_some() {
12992 self.soft_wrap_mode_override.take();
12993 } else {
12994 let soft_wrap = match self.soft_wrap_mode(cx) {
12995 SoftWrap::GitDiff => return,
12996 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12997 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12998 language_settings::SoftWrap::None
12999 }
13000 };
13001 self.soft_wrap_mode_override = Some(soft_wrap);
13002 }
13003 cx.notify();
13004 }
13005
13006 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13007 let Some(workspace) = self.workspace() else {
13008 return;
13009 };
13010 let fs = workspace.read(cx).app_state().fs.clone();
13011 let current_show = TabBarSettings::get_global(cx).show;
13012 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13013 setting.show = Some(!current_show);
13014 });
13015 }
13016
13017 pub fn toggle_indent_guides(
13018 &mut self,
13019 _: &ToggleIndentGuides,
13020 _: &mut Window,
13021 cx: &mut Context<Self>,
13022 ) {
13023 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13024 self.buffer
13025 .read(cx)
13026 .settings_at(0, cx)
13027 .indent_guides
13028 .enabled
13029 });
13030 self.show_indent_guides = Some(!currently_enabled);
13031 cx.notify();
13032 }
13033
13034 fn should_show_indent_guides(&self) -> Option<bool> {
13035 self.show_indent_guides
13036 }
13037
13038 pub fn toggle_line_numbers(
13039 &mut self,
13040 _: &ToggleLineNumbers,
13041 _: &mut Window,
13042 cx: &mut Context<Self>,
13043 ) {
13044 let mut editor_settings = EditorSettings::get_global(cx).clone();
13045 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13046 EditorSettings::override_global(editor_settings, cx);
13047 }
13048
13049 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13050 self.use_relative_line_numbers
13051 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13052 }
13053
13054 pub fn toggle_relative_line_numbers(
13055 &mut self,
13056 _: &ToggleRelativeLineNumbers,
13057 _: &mut Window,
13058 cx: &mut Context<Self>,
13059 ) {
13060 let is_relative = self.should_use_relative_line_numbers(cx);
13061 self.set_relative_line_number(Some(!is_relative), cx)
13062 }
13063
13064 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13065 self.use_relative_line_numbers = is_relative;
13066 cx.notify();
13067 }
13068
13069 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13070 self.show_gutter = show_gutter;
13071 cx.notify();
13072 }
13073
13074 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13075 self.show_scrollbars = show_scrollbars;
13076 cx.notify();
13077 }
13078
13079 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13080 self.show_line_numbers = Some(show_line_numbers);
13081 cx.notify();
13082 }
13083
13084 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13085 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13086 cx.notify();
13087 }
13088
13089 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13090 self.show_code_actions = Some(show_code_actions);
13091 cx.notify();
13092 }
13093
13094 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13095 self.show_runnables = Some(show_runnables);
13096 cx.notify();
13097 }
13098
13099 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13100 if self.display_map.read(cx).masked != masked {
13101 self.display_map.update(cx, |map, _| map.masked = masked);
13102 }
13103 cx.notify()
13104 }
13105
13106 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13107 self.show_wrap_guides = Some(show_wrap_guides);
13108 cx.notify();
13109 }
13110
13111 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13112 self.show_indent_guides = Some(show_indent_guides);
13113 cx.notify();
13114 }
13115
13116 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13117 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13118 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13119 if let Some(dir) = file.abs_path(cx).parent() {
13120 return Some(dir.to_owned());
13121 }
13122 }
13123
13124 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13125 return Some(project_path.path.to_path_buf());
13126 }
13127 }
13128
13129 None
13130 }
13131
13132 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13133 self.active_excerpt(cx)?
13134 .1
13135 .read(cx)
13136 .file()
13137 .and_then(|f| f.as_local())
13138 }
13139
13140 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13141 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13142 let buffer = buffer.read(cx);
13143 if let Some(project_path) = buffer.project_path(cx) {
13144 let project = self.project.as_ref()?.read(cx);
13145 project.absolute_path(&project_path, cx)
13146 } else {
13147 buffer
13148 .file()
13149 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13150 }
13151 })
13152 }
13153
13154 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13155 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13156 let project_path = buffer.read(cx).project_path(cx)?;
13157 let project = self.project.as_ref()?.read(cx);
13158 let entry = project.entry_for_path(&project_path, cx)?;
13159 let path = entry.path.to_path_buf();
13160 Some(path)
13161 })
13162 }
13163
13164 pub fn reveal_in_finder(
13165 &mut self,
13166 _: &RevealInFileManager,
13167 _window: &mut Window,
13168 cx: &mut Context<Self>,
13169 ) {
13170 if let Some(target) = self.target_file(cx) {
13171 cx.reveal_path(&target.abs_path(cx));
13172 }
13173 }
13174
13175 pub fn copy_path(
13176 &mut self,
13177 _: &zed_actions::workspace::CopyPath,
13178 _window: &mut Window,
13179 cx: &mut Context<Self>,
13180 ) {
13181 if let Some(path) = self.target_file_abs_path(cx) {
13182 if let Some(path) = path.to_str() {
13183 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13184 }
13185 }
13186 }
13187
13188 pub fn copy_relative_path(
13189 &mut self,
13190 _: &zed_actions::workspace::CopyRelativePath,
13191 _window: &mut Window,
13192 cx: &mut Context<Self>,
13193 ) {
13194 if let Some(path) = self.target_file_path(cx) {
13195 if let Some(path) = path.to_str() {
13196 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13197 }
13198 }
13199 }
13200
13201 pub fn copy_file_name_without_extension(
13202 &mut self,
13203 _: &CopyFileNameWithoutExtension,
13204 _: &mut Window,
13205 cx: &mut Context<Self>,
13206 ) {
13207 if let Some(file) = self.target_file(cx) {
13208 if let Some(file_stem) = file.path().file_stem() {
13209 if let Some(name) = file_stem.to_str() {
13210 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13211 }
13212 }
13213 }
13214 }
13215
13216 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13217 if let Some(file) = self.target_file(cx) {
13218 if let Some(file_name) = file.path().file_name() {
13219 if let Some(name) = file_name.to_str() {
13220 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13221 }
13222 }
13223 }
13224 }
13225
13226 pub fn toggle_git_blame(
13227 &mut self,
13228 _: &ToggleGitBlame,
13229 window: &mut Window,
13230 cx: &mut Context<Self>,
13231 ) {
13232 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13233
13234 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13235 self.start_git_blame(true, window, cx);
13236 }
13237
13238 cx.notify();
13239 }
13240
13241 pub fn toggle_git_blame_inline(
13242 &mut self,
13243 _: &ToggleGitBlameInline,
13244 window: &mut Window,
13245 cx: &mut Context<Self>,
13246 ) {
13247 self.toggle_git_blame_inline_internal(true, window, cx);
13248 cx.notify();
13249 }
13250
13251 pub fn git_blame_inline_enabled(&self) -> bool {
13252 self.git_blame_inline_enabled
13253 }
13254
13255 pub fn toggle_selection_menu(
13256 &mut self,
13257 _: &ToggleSelectionMenu,
13258 _: &mut Window,
13259 cx: &mut Context<Self>,
13260 ) {
13261 self.show_selection_menu = self
13262 .show_selection_menu
13263 .map(|show_selections_menu| !show_selections_menu)
13264 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13265
13266 cx.notify();
13267 }
13268
13269 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13270 self.show_selection_menu
13271 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13272 }
13273
13274 fn start_git_blame(
13275 &mut self,
13276 user_triggered: bool,
13277 window: &mut Window,
13278 cx: &mut Context<Self>,
13279 ) {
13280 if let Some(project) = self.project.as_ref() {
13281 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13282 return;
13283 };
13284
13285 if buffer.read(cx).file().is_none() {
13286 return;
13287 }
13288
13289 let focused = self.focus_handle(cx).contains_focused(window, cx);
13290
13291 let project = project.clone();
13292 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13293 self.blame_subscription =
13294 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13295 self.blame = Some(blame);
13296 }
13297 }
13298
13299 fn toggle_git_blame_inline_internal(
13300 &mut self,
13301 user_triggered: bool,
13302 window: &mut Window,
13303 cx: &mut Context<Self>,
13304 ) {
13305 if self.git_blame_inline_enabled {
13306 self.git_blame_inline_enabled = false;
13307 self.show_git_blame_inline = false;
13308 self.show_git_blame_inline_delay_task.take();
13309 } else {
13310 self.git_blame_inline_enabled = true;
13311 self.start_git_blame_inline(user_triggered, window, cx);
13312 }
13313
13314 cx.notify();
13315 }
13316
13317 fn start_git_blame_inline(
13318 &mut self,
13319 user_triggered: bool,
13320 window: &mut Window,
13321 cx: &mut Context<Self>,
13322 ) {
13323 self.start_git_blame(user_triggered, window, cx);
13324
13325 if ProjectSettings::get_global(cx)
13326 .git
13327 .inline_blame_delay()
13328 .is_some()
13329 {
13330 self.start_inline_blame_timer(window, cx);
13331 } else {
13332 self.show_git_blame_inline = true
13333 }
13334 }
13335
13336 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13337 self.blame.as_ref()
13338 }
13339
13340 pub fn show_git_blame_gutter(&self) -> bool {
13341 self.show_git_blame_gutter
13342 }
13343
13344 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13345 self.show_git_blame_gutter && self.has_blame_entries(cx)
13346 }
13347
13348 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13349 self.show_git_blame_inline
13350 && self.focus_handle.is_focused(window)
13351 && !self.newest_selection_head_on_empty_line(cx)
13352 && self.has_blame_entries(cx)
13353 }
13354
13355 fn has_blame_entries(&self, cx: &App) -> bool {
13356 self.blame()
13357 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13358 }
13359
13360 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13361 let cursor_anchor = self.selections.newest_anchor().head();
13362
13363 let snapshot = self.buffer.read(cx).snapshot(cx);
13364 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13365
13366 snapshot.line_len(buffer_row) == 0
13367 }
13368
13369 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13370 let buffer_and_selection = maybe!({
13371 let selection = self.selections.newest::<Point>(cx);
13372 let selection_range = selection.range();
13373
13374 let multi_buffer = self.buffer().read(cx);
13375 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13376 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13377
13378 let (buffer, range, _) = if selection.reversed {
13379 buffer_ranges.first()
13380 } else {
13381 buffer_ranges.last()
13382 }?;
13383
13384 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13385 ..text::ToPoint::to_point(&range.end, &buffer).row;
13386 Some((
13387 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13388 selection,
13389 ))
13390 });
13391
13392 let Some((buffer, selection)) = buffer_and_selection else {
13393 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13394 };
13395
13396 let Some(project) = self.project.as_ref() else {
13397 return Task::ready(Err(anyhow!("editor does not have project")));
13398 };
13399
13400 project.update(cx, |project, cx| {
13401 project.get_permalink_to_line(&buffer, selection, cx)
13402 })
13403 }
13404
13405 pub fn copy_permalink_to_line(
13406 &mut self,
13407 _: &CopyPermalinkToLine,
13408 window: &mut Window,
13409 cx: &mut Context<Self>,
13410 ) {
13411 let permalink_task = self.get_permalink_to_line(cx);
13412 let workspace = self.workspace();
13413
13414 cx.spawn_in(window, |_, mut cx| async move {
13415 match permalink_task.await {
13416 Ok(permalink) => {
13417 cx.update(|_, cx| {
13418 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13419 })
13420 .ok();
13421 }
13422 Err(err) => {
13423 let message = format!("Failed to copy permalink: {err}");
13424
13425 Err::<(), anyhow::Error>(err).log_err();
13426
13427 if let Some(workspace) = workspace {
13428 workspace
13429 .update_in(&mut cx, |workspace, _, cx| {
13430 struct CopyPermalinkToLine;
13431
13432 workspace.show_toast(
13433 Toast::new(
13434 NotificationId::unique::<CopyPermalinkToLine>(),
13435 message,
13436 ),
13437 cx,
13438 )
13439 })
13440 .ok();
13441 }
13442 }
13443 }
13444 })
13445 .detach();
13446 }
13447
13448 pub fn copy_file_location(
13449 &mut self,
13450 _: &CopyFileLocation,
13451 _: &mut Window,
13452 cx: &mut Context<Self>,
13453 ) {
13454 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13455 if let Some(file) = self.target_file(cx) {
13456 if let Some(path) = file.path().to_str() {
13457 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13458 }
13459 }
13460 }
13461
13462 pub fn open_permalink_to_line(
13463 &mut self,
13464 _: &OpenPermalinkToLine,
13465 window: &mut Window,
13466 cx: &mut Context<Self>,
13467 ) {
13468 let permalink_task = self.get_permalink_to_line(cx);
13469 let workspace = self.workspace();
13470
13471 cx.spawn_in(window, |_, mut cx| async move {
13472 match permalink_task.await {
13473 Ok(permalink) => {
13474 cx.update(|_, cx| {
13475 cx.open_url(permalink.as_ref());
13476 })
13477 .ok();
13478 }
13479 Err(err) => {
13480 let message = format!("Failed to open permalink: {err}");
13481
13482 Err::<(), anyhow::Error>(err).log_err();
13483
13484 if let Some(workspace) = workspace {
13485 workspace
13486 .update(&mut cx, |workspace, cx| {
13487 struct OpenPermalinkToLine;
13488
13489 workspace.show_toast(
13490 Toast::new(
13491 NotificationId::unique::<OpenPermalinkToLine>(),
13492 message,
13493 ),
13494 cx,
13495 )
13496 })
13497 .ok();
13498 }
13499 }
13500 }
13501 })
13502 .detach();
13503 }
13504
13505 pub fn insert_uuid_v4(
13506 &mut self,
13507 _: &InsertUuidV4,
13508 window: &mut Window,
13509 cx: &mut Context<Self>,
13510 ) {
13511 self.insert_uuid(UuidVersion::V4, window, cx);
13512 }
13513
13514 pub fn insert_uuid_v7(
13515 &mut self,
13516 _: &InsertUuidV7,
13517 window: &mut Window,
13518 cx: &mut Context<Self>,
13519 ) {
13520 self.insert_uuid(UuidVersion::V7, window, cx);
13521 }
13522
13523 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13524 self.transact(window, cx, |this, window, cx| {
13525 let edits = this
13526 .selections
13527 .all::<Point>(cx)
13528 .into_iter()
13529 .map(|selection| {
13530 let uuid = match version {
13531 UuidVersion::V4 => uuid::Uuid::new_v4(),
13532 UuidVersion::V7 => uuid::Uuid::now_v7(),
13533 };
13534
13535 (selection.range(), uuid.to_string())
13536 });
13537 this.edit(edits, cx);
13538 this.refresh_inline_completion(true, false, window, cx);
13539 });
13540 }
13541
13542 pub fn open_selections_in_multibuffer(
13543 &mut self,
13544 _: &OpenSelectionsInMultibuffer,
13545 window: &mut Window,
13546 cx: &mut Context<Self>,
13547 ) {
13548 let multibuffer = self.buffer.read(cx);
13549
13550 let Some(buffer) = multibuffer.as_singleton() else {
13551 return;
13552 };
13553
13554 let Some(workspace) = self.workspace() else {
13555 return;
13556 };
13557
13558 let locations = self
13559 .selections
13560 .disjoint_anchors()
13561 .iter()
13562 .map(|range| Location {
13563 buffer: buffer.clone(),
13564 range: range.start.text_anchor..range.end.text_anchor,
13565 })
13566 .collect::<Vec<_>>();
13567
13568 let title = multibuffer.title(cx).to_string();
13569
13570 cx.spawn_in(window, |_, mut cx| async move {
13571 workspace.update_in(&mut cx, |workspace, window, cx| {
13572 Self::open_locations_in_multibuffer(
13573 workspace,
13574 locations,
13575 format!("Selections for '{title}'"),
13576 false,
13577 MultibufferSelectionMode::All,
13578 window,
13579 cx,
13580 );
13581 })
13582 })
13583 .detach();
13584 }
13585
13586 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13587 /// last highlight added will be used.
13588 ///
13589 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13590 pub fn highlight_rows<T: 'static>(
13591 &mut self,
13592 range: Range<Anchor>,
13593 color: Hsla,
13594 should_autoscroll: bool,
13595 cx: &mut Context<Self>,
13596 ) {
13597 let snapshot = self.buffer().read(cx).snapshot(cx);
13598 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13599 let ix = row_highlights.binary_search_by(|highlight| {
13600 Ordering::Equal
13601 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13602 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13603 });
13604
13605 if let Err(mut ix) = ix {
13606 let index = post_inc(&mut self.highlight_order);
13607
13608 // If this range intersects with the preceding highlight, then merge it with
13609 // the preceding highlight. Otherwise insert a new highlight.
13610 let mut merged = false;
13611 if ix > 0 {
13612 let prev_highlight = &mut row_highlights[ix - 1];
13613 if prev_highlight
13614 .range
13615 .end
13616 .cmp(&range.start, &snapshot)
13617 .is_ge()
13618 {
13619 ix -= 1;
13620 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13621 prev_highlight.range.end = range.end;
13622 }
13623 merged = true;
13624 prev_highlight.index = index;
13625 prev_highlight.color = color;
13626 prev_highlight.should_autoscroll = should_autoscroll;
13627 }
13628 }
13629
13630 if !merged {
13631 row_highlights.insert(
13632 ix,
13633 RowHighlight {
13634 range: range.clone(),
13635 index,
13636 color,
13637 should_autoscroll,
13638 },
13639 );
13640 }
13641
13642 // If any of the following highlights intersect with this one, merge them.
13643 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13644 let highlight = &row_highlights[ix];
13645 if next_highlight
13646 .range
13647 .start
13648 .cmp(&highlight.range.end, &snapshot)
13649 .is_le()
13650 {
13651 if next_highlight
13652 .range
13653 .end
13654 .cmp(&highlight.range.end, &snapshot)
13655 .is_gt()
13656 {
13657 row_highlights[ix].range.end = next_highlight.range.end;
13658 }
13659 row_highlights.remove(ix + 1);
13660 } else {
13661 break;
13662 }
13663 }
13664 }
13665 }
13666
13667 /// Remove any highlighted row ranges of the given type that intersect the
13668 /// given ranges.
13669 pub fn remove_highlighted_rows<T: 'static>(
13670 &mut self,
13671 ranges_to_remove: Vec<Range<Anchor>>,
13672 cx: &mut Context<Self>,
13673 ) {
13674 let snapshot = self.buffer().read(cx).snapshot(cx);
13675 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13676 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13677 row_highlights.retain(|highlight| {
13678 while let Some(range_to_remove) = ranges_to_remove.peek() {
13679 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13680 Ordering::Less | Ordering::Equal => {
13681 ranges_to_remove.next();
13682 }
13683 Ordering::Greater => {
13684 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13685 Ordering::Less | Ordering::Equal => {
13686 return false;
13687 }
13688 Ordering::Greater => break,
13689 }
13690 }
13691 }
13692 }
13693
13694 true
13695 })
13696 }
13697
13698 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13699 pub fn clear_row_highlights<T: 'static>(&mut self) {
13700 self.highlighted_rows.remove(&TypeId::of::<T>());
13701 }
13702
13703 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13704 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13705 self.highlighted_rows
13706 .get(&TypeId::of::<T>())
13707 .map_or(&[] as &[_], |vec| vec.as_slice())
13708 .iter()
13709 .map(|highlight| (highlight.range.clone(), highlight.color))
13710 }
13711
13712 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13713 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13714 /// Allows to ignore certain kinds of highlights.
13715 pub fn highlighted_display_rows(
13716 &self,
13717 window: &mut Window,
13718 cx: &mut App,
13719 ) -> BTreeMap<DisplayRow, Hsla> {
13720 let snapshot = self.snapshot(window, cx);
13721 let mut used_highlight_orders = HashMap::default();
13722 self.highlighted_rows
13723 .iter()
13724 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13725 .fold(
13726 BTreeMap::<DisplayRow, Hsla>::new(),
13727 |mut unique_rows, highlight| {
13728 let start = highlight.range.start.to_display_point(&snapshot);
13729 let end = highlight.range.end.to_display_point(&snapshot);
13730 let start_row = start.row().0;
13731 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13732 && end.column() == 0
13733 {
13734 end.row().0.saturating_sub(1)
13735 } else {
13736 end.row().0
13737 };
13738 for row in start_row..=end_row {
13739 let used_index =
13740 used_highlight_orders.entry(row).or_insert(highlight.index);
13741 if highlight.index >= *used_index {
13742 *used_index = highlight.index;
13743 unique_rows.insert(DisplayRow(row), highlight.color);
13744 }
13745 }
13746 unique_rows
13747 },
13748 )
13749 }
13750
13751 pub fn highlighted_display_row_for_autoscroll(
13752 &self,
13753 snapshot: &DisplaySnapshot,
13754 ) -> Option<DisplayRow> {
13755 self.highlighted_rows
13756 .values()
13757 .flat_map(|highlighted_rows| highlighted_rows.iter())
13758 .filter_map(|highlight| {
13759 if highlight.should_autoscroll {
13760 Some(highlight.range.start.to_display_point(snapshot).row())
13761 } else {
13762 None
13763 }
13764 })
13765 .min()
13766 }
13767
13768 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13769 self.highlight_background::<SearchWithinRange>(
13770 ranges,
13771 |colors| colors.editor_document_highlight_read_background,
13772 cx,
13773 )
13774 }
13775
13776 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13777 self.breadcrumb_header = Some(new_header);
13778 }
13779
13780 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13781 self.clear_background_highlights::<SearchWithinRange>(cx);
13782 }
13783
13784 pub fn highlight_background<T: 'static>(
13785 &mut self,
13786 ranges: &[Range<Anchor>],
13787 color_fetcher: fn(&ThemeColors) -> Hsla,
13788 cx: &mut Context<Self>,
13789 ) {
13790 self.background_highlights
13791 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13792 self.scrollbar_marker_state.dirty = true;
13793 cx.notify();
13794 }
13795
13796 pub fn clear_background_highlights<T: 'static>(
13797 &mut self,
13798 cx: &mut Context<Self>,
13799 ) -> Option<BackgroundHighlight> {
13800 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13801 if !text_highlights.1.is_empty() {
13802 self.scrollbar_marker_state.dirty = true;
13803 cx.notify();
13804 }
13805 Some(text_highlights)
13806 }
13807
13808 pub fn highlight_gutter<T: 'static>(
13809 &mut self,
13810 ranges: &[Range<Anchor>],
13811 color_fetcher: fn(&App) -> Hsla,
13812 cx: &mut Context<Self>,
13813 ) {
13814 self.gutter_highlights
13815 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13816 cx.notify();
13817 }
13818
13819 pub fn clear_gutter_highlights<T: 'static>(
13820 &mut self,
13821 cx: &mut Context<Self>,
13822 ) -> Option<GutterHighlight> {
13823 cx.notify();
13824 self.gutter_highlights.remove(&TypeId::of::<T>())
13825 }
13826
13827 #[cfg(feature = "test-support")]
13828 pub fn all_text_background_highlights(
13829 &self,
13830 window: &mut Window,
13831 cx: &mut Context<Self>,
13832 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13833 let snapshot = self.snapshot(window, cx);
13834 let buffer = &snapshot.buffer_snapshot;
13835 let start = buffer.anchor_before(0);
13836 let end = buffer.anchor_after(buffer.len());
13837 let theme = cx.theme().colors();
13838 self.background_highlights_in_range(start..end, &snapshot, theme)
13839 }
13840
13841 #[cfg(feature = "test-support")]
13842 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13843 let snapshot = self.buffer().read(cx).snapshot(cx);
13844
13845 let highlights = self
13846 .background_highlights
13847 .get(&TypeId::of::<items::BufferSearchHighlights>());
13848
13849 if let Some((_color, ranges)) = highlights {
13850 ranges
13851 .iter()
13852 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13853 .collect_vec()
13854 } else {
13855 vec![]
13856 }
13857 }
13858
13859 fn document_highlights_for_position<'a>(
13860 &'a self,
13861 position: Anchor,
13862 buffer: &'a MultiBufferSnapshot,
13863 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13864 let read_highlights = self
13865 .background_highlights
13866 .get(&TypeId::of::<DocumentHighlightRead>())
13867 .map(|h| &h.1);
13868 let write_highlights = self
13869 .background_highlights
13870 .get(&TypeId::of::<DocumentHighlightWrite>())
13871 .map(|h| &h.1);
13872 let left_position = position.bias_left(buffer);
13873 let right_position = position.bias_right(buffer);
13874 read_highlights
13875 .into_iter()
13876 .chain(write_highlights)
13877 .flat_map(move |ranges| {
13878 let start_ix = match ranges.binary_search_by(|probe| {
13879 let cmp = probe.end.cmp(&left_position, buffer);
13880 if cmp.is_ge() {
13881 Ordering::Greater
13882 } else {
13883 Ordering::Less
13884 }
13885 }) {
13886 Ok(i) | Err(i) => i,
13887 };
13888
13889 ranges[start_ix..]
13890 .iter()
13891 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13892 })
13893 }
13894
13895 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13896 self.background_highlights
13897 .get(&TypeId::of::<T>())
13898 .map_or(false, |(_, highlights)| !highlights.is_empty())
13899 }
13900
13901 pub fn background_highlights_in_range(
13902 &self,
13903 search_range: Range<Anchor>,
13904 display_snapshot: &DisplaySnapshot,
13905 theme: &ThemeColors,
13906 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13907 let mut results = Vec::new();
13908 for (color_fetcher, ranges) in self.background_highlights.values() {
13909 let color = color_fetcher(theme);
13910 let start_ix = match ranges.binary_search_by(|probe| {
13911 let cmp = probe
13912 .end
13913 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13914 if cmp.is_gt() {
13915 Ordering::Greater
13916 } else {
13917 Ordering::Less
13918 }
13919 }) {
13920 Ok(i) | Err(i) => i,
13921 };
13922 for range in &ranges[start_ix..] {
13923 if range
13924 .start
13925 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13926 .is_ge()
13927 {
13928 break;
13929 }
13930
13931 let start = range.start.to_display_point(display_snapshot);
13932 let end = range.end.to_display_point(display_snapshot);
13933 results.push((start..end, color))
13934 }
13935 }
13936 results
13937 }
13938
13939 pub fn background_highlight_row_ranges<T: 'static>(
13940 &self,
13941 search_range: Range<Anchor>,
13942 display_snapshot: &DisplaySnapshot,
13943 count: usize,
13944 ) -> Vec<RangeInclusive<DisplayPoint>> {
13945 let mut results = Vec::new();
13946 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13947 return vec![];
13948 };
13949
13950 let start_ix = match ranges.binary_search_by(|probe| {
13951 let cmp = probe
13952 .end
13953 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13954 if cmp.is_gt() {
13955 Ordering::Greater
13956 } else {
13957 Ordering::Less
13958 }
13959 }) {
13960 Ok(i) | Err(i) => i,
13961 };
13962 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13963 if let (Some(start_display), Some(end_display)) = (start, end) {
13964 results.push(
13965 start_display.to_display_point(display_snapshot)
13966 ..=end_display.to_display_point(display_snapshot),
13967 );
13968 }
13969 };
13970 let mut start_row: Option<Point> = None;
13971 let mut end_row: Option<Point> = None;
13972 if ranges.len() > count {
13973 return Vec::new();
13974 }
13975 for range in &ranges[start_ix..] {
13976 if range
13977 .start
13978 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13979 .is_ge()
13980 {
13981 break;
13982 }
13983 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13984 if let Some(current_row) = &end_row {
13985 if end.row == current_row.row {
13986 continue;
13987 }
13988 }
13989 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13990 if start_row.is_none() {
13991 assert_eq!(end_row, None);
13992 start_row = Some(start);
13993 end_row = Some(end);
13994 continue;
13995 }
13996 if let Some(current_end) = end_row.as_mut() {
13997 if start.row > current_end.row + 1 {
13998 push_region(start_row, end_row);
13999 start_row = Some(start);
14000 end_row = Some(end);
14001 } else {
14002 // Merge two hunks.
14003 *current_end = end;
14004 }
14005 } else {
14006 unreachable!();
14007 }
14008 }
14009 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14010 push_region(start_row, end_row);
14011 results
14012 }
14013
14014 pub fn gutter_highlights_in_range(
14015 &self,
14016 search_range: Range<Anchor>,
14017 display_snapshot: &DisplaySnapshot,
14018 cx: &App,
14019 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14020 let mut results = Vec::new();
14021 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14022 let color = color_fetcher(cx);
14023 let start_ix = match ranges.binary_search_by(|probe| {
14024 let cmp = probe
14025 .end
14026 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14027 if cmp.is_gt() {
14028 Ordering::Greater
14029 } else {
14030 Ordering::Less
14031 }
14032 }) {
14033 Ok(i) | Err(i) => i,
14034 };
14035 for range in &ranges[start_ix..] {
14036 if range
14037 .start
14038 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14039 .is_ge()
14040 {
14041 break;
14042 }
14043
14044 let start = range.start.to_display_point(display_snapshot);
14045 let end = range.end.to_display_point(display_snapshot);
14046 results.push((start..end, color))
14047 }
14048 }
14049 results
14050 }
14051
14052 /// Get the text ranges corresponding to the redaction query
14053 pub fn redacted_ranges(
14054 &self,
14055 search_range: Range<Anchor>,
14056 display_snapshot: &DisplaySnapshot,
14057 cx: &App,
14058 ) -> Vec<Range<DisplayPoint>> {
14059 display_snapshot
14060 .buffer_snapshot
14061 .redacted_ranges(search_range, |file| {
14062 if let Some(file) = file {
14063 file.is_private()
14064 && EditorSettings::get(
14065 Some(SettingsLocation {
14066 worktree_id: file.worktree_id(cx),
14067 path: file.path().as_ref(),
14068 }),
14069 cx,
14070 )
14071 .redact_private_values
14072 } else {
14073 false
14074 }
14075 })
14076 .map(|range| {
14077 range.start.to_display_point(display_snapshot)
14078 ..range.end.to_display_point(display_snapshot)
14079 })
14080 .collect()
14081 }
14082
14083 pub fn highlight_text<T: 'static>(
14084 &mut self,
14085 ranges: Vec<Range<Anchor>>,
14086 style: HighlightStyle,
14087 cx: &mut Context<Self>,
14088 ) {
14089 self.display_map.update(cx, |map, _| {
14090 map.highlight_text(TypeId::of::<T>(), ranges, style)
14091 });
14092 cx.notify();
14093 }
14094
14095 pub(crate) fn highlight_inlays<T: 'static>(
14096 &mut self,
14097 highlights: Vec<InlayHighlight>,
14098 style: HighlightStyle,
14099 cx: &mut Context<Self>,
14100 ) {
14101 self.display_map.update(cx, |map, _| {
14102 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14103 });
14104 cx.notify();
14105 }
14106
14107 pub fn text_highlights<'a, T: 'static>(
14108 &'a self,
14109 cx: &'a App,
14110 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14111 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14112 }
14113
14114 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14115 let cleared = self
14116 .display_map
14117 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14118 if cleared {
14119 cx.notify();
14120 }
14121 }
14122
14123 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14124 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14125 && self.focus_handle.is_focused(window)
14126 }
14127
14128 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14129 self.show_cursor_when_unfocused = is_enabled;
14130 cx.notify();
14131 }
14132
14133 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14134 cx.notify();
14135 }
14136
14137 fn on_buffer_event(
14138 &mut self,
14139 multibuffer: &Entity<MultiBuffer>,
14140 event: &multi_buffer::Event,
14141 window: &mut Window,
14142 cx: &mut Context<Self>,
14143 ) {
14144 match event {
14145 multi_buffer::Event::Edited {
14146 singleton_buffer_edited,
14147 edited_buffer: buffer_edited,
14148 } => {
14149 self.scrollbar_marker_state.dirty = true;
14150 self.active_indent_guides_state.dirty = true;
14151 self.refresh_active_diagnostics(cx);
14152 self.refresh_code_actions(window, cx);
14153 if self.has_active_inline_completion() {
14154 self.update_visible_inline_completion(window, cx);
14155 }
14156 if let Some(buffer) = buffer_edited {
14157 let buffer_id = buffer.read(cx).remote_id();
14158 if !self.registered_buffers.contains_key(&buffer_id) {
14159 if let Some(project) = self.project.as_ref() {
14160 project.update(cx, |project, cx| {
14161 self.registered_buffers.insert(
14162 buffer_id,
14163 project.register_buffer_with_language_servers(&buffer, cx),
14164 );
14165 })
14166 }
14167 }
14168 }
14169 cx.emit(EditorEvent::BufferEdited);
14170 cx.emit(SearchEvent::MatchesInvalidated);
14171 if *singleton_buffer_edited {
14172 if let Some(project) = &self.project {
14173 #[allow(clippy::mutable_key_type)]
14174 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14175 multibuffer
14176 .all_buffers()
14177 .into_iter()
14178 .filter_map(|buffer| {
14179 buffer.update(cx, |buffer, cx| {
14180 let language = buffer.language()?;
14181 let should_discard = project.update(cx, |project, cx| {
14182 project.is_local()
14183 && !project.has_language_servers_for(buffer, cx)
14184 });
14185 should_discard.not().then_some(language.clone())
14186 })
14187 })
14188 .collect::<HashSet<_>>()
14189 });
14190 if !languages_affected.is_empty() {
14191 self.refresh_inlay_hints(
14192 InlayHintRefreshReason::BufferEdited(languages_affected),
14193 cx,
14194 );
14195 }
14196 }
14197 }
14198
14199 let Some(project) = &self.project else { return };
14200 let (telemetry, is_via_ssh) = {
14201 let project = project.read(cx);
14202 let telemetry = project.client().telemetry().clone();
14203 let is_via_ssh = project.is_via_ssh();
14204 (telemetry, is_via_ssh)
14205 };
14206 refresh_linked_ranges(self, window, cx);
14207 telemetry.log_edit_event("editor", is_via_ssh);
14208 }
14209 multi_buffer::Event::ExcerptsAdded {
14210 buffer,
14211 predecessor,
14212 excerpts,
14213 } => {
14214 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14215 let buffer_id = buffer.read(cx).remote_id();
14216 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14217 if let Some(project) = &self.project {
14218 get_uncommitted_diff_for_buffer(
14219 project,
14220 [buffer.clone()],
14221 self.buffer.clone(),
14222 cx,
14223 )
14224 .detach();
14225 }
14226 }
14227 cx.emit(EditorEvent::ExcerptsAdded {
14228 buffer: buffer.clone(),
14229 predecessor: *predecessor,
14230 excerpts: excerpts.clone(),
14231 });
14232 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14233 }
14234 multi_buffer::Event::ExcerptsRemoved { ids } => {
14235 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14236 let buffer = self.buffer.read(cx);
14237 self.registered_buffers
14238 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14239 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14240 }
14241 multi_buffer::Event::ExcerptsEdited { ids } => {
14242 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14243 }
14244 multi_buffer::Event::ExcerptsExpanded { ids } => {
14245 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14246 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14247 }
14248 multi_buffer::Event::Reparsed(buffer_id) => {
14249 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14250
14251 cx.emit(EditorEvent::Reparsed(*buffer_id));
14252 }
14253 multi_buffer::Event::DiffHunksToggled => {
14254 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14255 }
14256 multi_buffer::Event::LanguageChanged(buffer_id) => {
14257 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14258 cx.emit(EditorEvent::Reparsed(*buffer_id));
14259 cx.notify();
14260 }
14261 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14262 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14263 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14264 cx.emit(EditorEvent::TitleChanged)
14265 }
14266 // multi_buffer::Event::DiffBaseChanged => {
14267 // self.scrollbar_marker_state.dirty = true;
14268 // cx.emit(EditorEvent::DiffBaseChanged);
14269 // cx.notify();
14270 // }
14271 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14272 multi_buffer::Event::DiagnosticsUpdated => {
14273 self.refresh_active_diagnostics(cx);
14274 self.scrollbar_marker_state.dirty = true;
14275 cx.notify();
14276 }
14277 _ => {}
14278 };
14279 }
14280
14281 fn on_display_map_changed(
14282 &mut self,
14283 _: Entity<DisplayMap>,
14284 _: &mut Window,
14285 cx: &mut Context<Self>,
14286 ) {
14287 cx.notify();
14288 }
14289
14290 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14291 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14292 self.refresh_inline_completion(true, false, window, cx);
14293 self.refresh_inlay_hints(
14294 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14295 self.selections.newest_anchor().head(),
14296 &self.buffer.read(cx).snapshot(cx),
14297 cx,
14298 )),
14299 cx,
14300 );
14301
14302 let old_cursor_shape = self.cursor_shape;
14303
14304 {
14305 let editor_settings = EditorSettings::get_global(cx);
14306 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14307 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14308 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14309 }
14310
14311 if old_cursor_shape != self.cursor_shape {
14312 cx.emit(EditorEvent::CursorShapeChanged);
14313 }
14314
14315 let project_settings = ProjectSettings::get_global(cx);
14316 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14317
14318 if self.mode == EditorMode::Full {
14319 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14320 if self.git_blame_inline_enabled != inline_blame_enabled {
14321 self.toggle_git_blame_inline_internal(false, window, cx);
14322 }
14323 }
14324
14325 cx.notify();
14326 }
14327
14328 pub fn set_searchable(&mut self, searchable: bool) {
14329 self.searchable = searchable;
14330 }
14331
14332 pub fn searchable(&self) -> bool {
14333 self.searchable
14334 }
14335
14336 fn open_proposed_changes_editor(
14337 &mut self,
14338 _: &OpenProposedChangesEditor,
14339 window: &mut Window,
14340 cx: &mut Context<Self>,
14341 ) {
14342 let Some(workspace) = self.workspace() else {
14343 cx.propagate();
14344 return;
14345 };
14346
14347 let selections = self.selections.all::<usize>(cx);
14348 let multi_buffer = self.buffer.read(cx);
14349 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14350 let mut new_selections_by_buffer = HashMap::default();
14351 for selection in selections {
14352 for (buffer, range, _) in
14353 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14354 {
14355 let mut range = range.to_point(buffer);
14356 range.start.column = 0;
14357 range.end.column = buffer.line_len(range.end.row);
14358 new_selections_by_buffer
14359 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14360 .or_insert(Vec::new())
14361 .push(range)
14362 }
14363 }
14364
14365 let proposed_changes_buffers = new_selections_by_buffer
14366 .into_iter()
14367 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14368 .collect::<Vec<_>>();
14369 let proposed_changes_editor = cx.new(|cx| {
14370 ProposedChangesEditor::new(
14371 "Proposed changes",
14372 proposed_changes_buffers,
14373 self.project.clone(),
14374 window,
14375 cx,
14376 )
14377 });
14378
14379 window.defer(cx, move |window, cx| {
14380 workspace.update(cx, |workspace, cx| {
14381 workspace.active_pane().update(cx, |pane, cx| {
14382 pane.add_item(
14383 Box::new(proposed_changes_editor),
14384 true,
14385 true,
14386 None,
14387 window,
14388 cx,
14389 );
14390 });
14391 });
14392 });
14393 }
14394
14395 pub fn open_excerpts_in_split(
14396 &mut self,
14397 _: &OpenExcerptsSplit,
14398 window: &mut Window,
14399 cx: &mut Context<Self>,
14400 ) {
14401 self.open_excerpts_common(None, true, window, cx)
14402 }
14403
14404 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14405 self.open_excerpts_common(None, false, window, cx)
14406 }
14407
14408 fn open_excerpts_common(
14409 &mut self,
14410 jump_data: Option<JumpData>,
14411 split: bool,
14412 window: &mut Window,
14413 cx: &mut Context<Self>,
14414 ) {
14415 let Some(workspace) = self.workspace() else {
14416 cx.propagate();
14417 return;
14418 };
14419
14420 if self.buffer.read(cx).is_singleton() {
14421 cx.propagate();
14422 return;
14423 }
14424
14425 let mut new_selections_by_buffer = HashMap::default();
14426 match &jump_data {
14427 Some(JumpData::MultiBufferPoint {
14428 excerpt_id,
14429 position,
14430 anchor,
14431 line_offset_from_top,
14432 }) => {
14433 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14434 if let Some(buffer) = multi_buffer_snapshot
14435 .buffer_id_for_excerpt(*excerpt_id)
14436 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14437 {
14438 let buffer_snapshot = buffer.read(cx).snapshot();
14439 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14440 language::ToPoint::to_point(anchor, &buffer_snapshot)
14441 } else {
14442 buffer_snapshot.clip_point(*position, Bias::Left)
14443 };
14444 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14445 new_selections_by_buffer.insert(
14446 buffer,
14447 (
14448 vec![jump_to_offset..jump_to_offset],
14449 Some(*line_offset_from_top),
14450 ),
14451 );
14452 }
14453 }
14454 Some(JumpData::MultiBufferRow {
14455 row,
14456 line_offset_from_top,
14457 }) => {
14458 let point = MultiBufferPoint::new(row.0, 0);
14459 if let Some((buffer, buffer_point, _)) =
14460 self.buffer.read(cx).point_to_buffer_point(point, cx)
14461 {
14462 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14463 new_selections_by_buffer
14464 .entry(buffer)
14465 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14466 .0
14467 .push(buffer_offset..buffer_offset)
14468 }
14469 }
14470 None => {
14471 let selections = self.selections.all::<usize>(cx);
14472 let multi_buffer = self.buffer.read(cx);
14473 for selection in selections {
14474 for (buffer, mut range, _) in multi_buffer
14475 .snapshot(cx)
14476 .range_to_buffer_ranges(selection.range())
14477 {
14478 // When editing branch buffers, jump to the corresponding location
14479 // in their base buffer.
14480 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14481 let buffer = buffer_handle.read(cx);
14482 if let Some(base_buffer) = buffer.base_buffer() {
14483 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14484 buffer_handle = base_buffer;
14485 }
14486
14487 if selection.reversed {
14488 mem::swap(&mut range.start, &mut range.end);
14489 }
14490 new_selections_by_buffer
14491 .entry(buffer_handle)
14492 .or_insert((Vec::new(), None))
14493 .0
14494 .push(range)
14495 }
14496 }
14497 }
14498 }
14499
14500 if new_selections_by_buffer.is_empty() {
14501 return;
14502 }
14503
14504 // We defer the pane interaction because we ourselves are a workspace item
14505 // and activating a new item causes the pane to call a method on us reentrantly,
14506 // which panics if we're on the stack.
14507 window.defer(cx, move |window, cx| {
14508 workspace.update(cx, |workspace, cx| {
14509 let pane = if split {
14510 workspace.adjacent_pane(window, cx)
14511 } else {
14512 workspace.active_pane().clone()
14513 };
14514
14515 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14516 let editor = buffer
14517 .read(cx)
14518 .file()
14519 .is_none()
14520 .then(|| {
14521 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14522 // so `workspace.open_project_item` will never find them, always opening a new editor.
14523 // Instead, we try to activate the existing editor in the pane first.
14524 let (editor, pane_item_index) =
14525 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14526 let editor = item.downcast::<Editor>()?;
14527 let singleton_buffer =
14528 editor.read(cx).buffer().read(cx).as_singleton()?;
14529 if singleton_buffer == buffer {
14530 Some((editor, i))
14531 } else {
14532 None
14533 }
14534 })?;
14535 pane.update(cx, |pane, cx| {
14536 pane.activate_item(pane_item_index, true, true, window, cx)
14537 });
14538 Some(editor)
14539 })
14540 .flatten()
14541 .unwrap_or_else(|| {
14542 workspace.open_project_item::<Self>(
14543 pane.clone(),
14544 buffer,
14545 true,
14546 true,
14547 window,
14548 cx,
14549 )
14550 });
14551
14552 editor.update(cx, |editor, cx| {
14553 let autoscroll = match scroll_offset {
14554 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14555 None => Autoscroll::newest(),
14556 };
14557 let nav_history = editor.nav_history.take();
14558 editor.change_selections(Some(autoscroll), window, cx, |s| {
14559 s.select_ranges(ranges);
14560 });
14561 editor.nav_history = nav_history;
14562 });
14563 }
14564 })
14565 });
14566 }
14567
14568 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14569 let snapshot = self.buffer.read(cx).read(cx);
14570 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14571 Some(
14572 ranges
14573 .iter()
14574 .map(move |range| {
14575 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14576 })
14577 .collect(),
14578 )
14579 }
14580
14581 fn selection_replacement_ranges(
14582 &self,
14583 range: Range<OffsetUtf16>,
14584 cx: &mut App,
14585 ) -> Vec<Range<OffsetUtf16>> {
14586 let selections = self.selections.all::<OffsetUtf16>(cx);
14587 let newest_selection = selections
14588 .iter()
14589 .max_by_key(|selection| selection.id)
14590 .unwrap();
14591 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14592 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14593 let snapshot = self.buffer.read(cx).read(cx);
14594 selections
14595 .into_iter()
14596 .map(|mut selection| {
14597 selection.start.0 =
14598 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14599 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14600 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14601 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14602 })
14603 .collect()
14604 }
14605
14606 fn report_editor_event(
14607 &self,
14608 event_type: &'static str,
14609 file_extension: Option<String>,
14610 cx: &App,
14611 ) {
14612 if cfg!(any(test, feature = "test-support")) {
14613 return;
14614 }
14615
14616 let Some(project) = &self.project else { return };
14617
14618 // If None, we are in a file without an extension
14619 let file = self
14620 .buffer
14621 .read(cx)
14622 .as_singleton()
14623 .and_then(|b| b.read(cx).file());
14624 let file_extension = file_extension.or(file
14625 .as_ref()
14626 .and_then(|file| Path::new(file.file_name(cx)).extension())
14627 .and_then(|e| e.to_str())
14628 .map(|a| a.to_string()));
14629
14630 let vim_mode = cx
14631 .global::<SettingsStore>()
14632 .raw_user_settings()
14633 .get("vim_mode")
14634 == Some(&serde_json::Value::Bool(true));
14635
14636 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14637 let copilot_enabled = edit_predictions_provider
14638 == language::language_settings::EditPredictionProvider::Copilot;
14639 let copilot_enabled_for_language = self
14640 .buffer
14641 .read(cx)
14642 .settings_at(0, cx)
14643 .show_edit_predictions;
14644
14645 let project = project.read(cx);
14646 telemetry::event!(
14647 event_type,
14648 file_extension,
14649 vim_mode,
14650 copilot_enabled,
14651 copilot_enabled_for_language,
14652 edit_predictions_provider,
14653 is_via_ssh = project.is_via_ssh(),
14654 );
14655 }
14656
14657 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14658 /// with each line being an array of {text, highlight} objects.
14659 fn copy_highlight_json(
14660 &mut self,
14661 _: &CopyHighlightJson,
14662 window: &mut Window,
14663 cx: &mut Context<Self>,
14664 ) {
14665 #[derive(Serialize)]
14666 struct Chunk<'a> {
14667 text: String,
14668 highlight: Option<&'a str>,
14669 }
14670
14671 let snapshot = self.buffer.read(cx).snapshot(cx);
14672 let range = self
14673 .selected_text_range(false, window, cx)
14674 .and_then(|selection| {
14675 if selection.range.is_empty() {
14676 None
14677 } else {
14678 Some(selection.range)
14679 }
14680 })
14681 .unwrap_or_else(|| 0..snapshot.len());
14682
14683 let chunks = snapshot.chunks(range, true);
14684 let mut lines = Vec::new();
14685 let mut line: VecDeque<Chunk> = VecDeque::new();
14686
14687 let Some(style) = self.style.as_ref() else {
14688 return;
14689 };
14690
14691 for chunk in chunks {
14692 let highlight = chunk
14693 .syntax_highlight_id
14694 .and_then(|id| id.name(&style.syntax));
14695 let mut chunk_lines = chunk.text.split('\n').peekable();
14696 while let Some(text) = chunk_lines.next() {
14697 let mut merged_with_last_token = false;
14698 if let Some(last_token) = line.back_mut() {
14699 if last_token.highlight == highlight {
14700 last_token.text.push_str(text);
14701 merged_with_last_token = true;
14702 }
14703 }
14704
14705 if !merged_with_last_token {
14706 line.push_back(Chunk {
14707 text: text.into(),
14708 highlight,
14709 });
14710 }
14711
14712 if chunk_lines.peek().is_some() {
14713 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14714 line.pop_front();
14715 }
14716 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14717 line.pop_back();
14718 }
14719
14720 lines.push(mem::take(&mut line));
14721 }
14722 }
14723 }
14724
14725 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14726 return;
14727 };
14728 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14729 }
14730
14731 pub fn open_context_menu(
14732 &mut self,
14733 _: &OpenContextMenu,
14734 window: &mut Window,
14735 cx: &mut Context<Self>,
14736 ) {
14737 self.request_autoscroll(Autoscroll::newest(), cx);
14738 let position = self.selections.newest_display(cx).start;
14739 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14740 }
14741
14742 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14743 &self.inlay_hint_cache
14744 }
14745
14746 pub fn replay_insert_event(
14747 &mut self,
14748 text: &str,
14749 relative_utf16_range: Option<Range<isize>>,
14750 window: &mut Window,
14751 cx: &mut Context<Self>,
14752 ) {
14753 if !self.input_enabled {
14754 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14755 return;
14756 }
14757 if let Some(relative_utf16_range) = relative_utf16_range {
14758 let selections = self.selections.all::<OffsetUtf16>(cx);
14759 self.change_selections(None, window, cx, |s| {
14760 let new_ranges = selections.into_iter().map(|range| {
14761 let start = OffsetUtf16(
14762 range
14763 .head()
14764 .0
14765 .saturating_add_signed(relative_utf16_range.start),
14766 );
14767 let end = OffsetUtf16(
14768 range
14769 .head()
14770 .0
14771 .saturating_add_signed(relative_utf16_range.end),
14772 );
14773 start..end
14774 });
14775 s.select_ranges(new_ranges);
14776 });
14777 }
14778
14779 self.handle_input(text, window, cx);
14780 }
14781
14782 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14783 let Some(provider) = self.semantics_provider.as_ref() else {
14784 return false;
14785 };
14786
14787 let mut supports = false;
14788 self.buffer().update(cx, |this, cx| {
14789 this.for_each_buffer(|buffer| {
14790 supports |= provider.supports_inlay_hints(buffer, cx);
14791 });
14792 });
14793
14794 supports
14795 }
14796
14797 pub fn is_focused(&self, window: &Window) -> bool {
14798 self.focus_handle.is_focused(window)
14799 }
14800
14801 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14802 cx.emit(EditorEvent::Focused);
14803
14804 if let Some(descendant) = self
14805 .last_focused_descendant
14806 .take()
14807 .and_then(|descendant| descendant.upgrade())
14808 {
14809 window.focus(&descendant);
14810 } else {
14811 if let Some(blame) = self.blame.as_ref() {
14812 blame.update(cx, GitBlame::focus)
14813 }
14814
14815 self.blink_manager.update(cx, BlinkManager::enable);
14816 self.show_cursor_names(window, cx);
14817 self.buffer.update(cx, |buffer, cx| {
14818 buffer.finalize_last_transaction(cx);
14819 if self.leader_peer_id.is_none() {
14820 buffer.set_active_selections(
14821 &self.selections.disjoint_anchors(),
14822 self.selections.line_mode,
14823 self.cursor_shape,
14824 cx,
14825 );
14826 }
14827 });
14828 }
14829 }
14830
14831 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14832 cx.emit(EditorEvent::FocusedIn)
14833 }
14834
14835 fn handle_focus_out(
14836 &mut self,
14837 event: FocusOutEvent,
14838 _window: &mut Window,
14839 _cx: &mut Context<Self>,
14840 ) {
14841 if event.blurred != self.focus_handle {
14842 self.last_focused_descendant = Some(event.blurred);
14843 }
14844 }
14845
14846 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14847 self.blink_manager.update(cx, BlinkManager::disable);
14848 self.buffer
14849 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14850
14851 if let Some(blame) = self.blame.as_ref() {
14852 blame.update(cx, GitBlame::blur)
14853 }
14854 if !self.hover_state.focused(window, cx) {
14855 hide_hover(self, cx);
14856 }
14857
14858 self.hide_context_menu(window, cx);
14859 self.discard_inline_completion(false, cx);
14860 cx.emit(EditorEvent::Blurred);
14861 cx.notify();
14862 }
14863
14864 pub fn register_action<A: Action>(
14865 &mut self,
14866 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14867 ) -> Subscription {
14868 let id = self.next_editor_action_id.post_inc();
14869 let listener = Arc::new(listener);
14870 self.editor_actions.borrow_mut().insert(
14871 id,
14872 Box::new(move |window, _| {
14873 let listener = listener.clone();
14874 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14875 let action = action.downcast_ref().unwrap();
14876 if phase == DispatchPhase::Bubble {
14877 listener(action, window, cx)
14878 }
14879 })
14880 }),
14881 );
14882
14883 let editor_actions = self.editor_actions.clone();
14884 Subscription::new(move || {
14885 editor_actions.borrow_mut().remove(&id);
14886 })
14887 }
14888
14889 pub fn file_header_size(&self) -> u32 {
14890 FILE_HEADER_HEIGHT
14891 }
14892
14893 pub fn revert(
14894 &mut self,
14895 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14896 window: &mut Window,
14897 cx: &mut Context<Self>,
14898 ) {
14899 self.buffer().update(cx, |multi_buffer, cx| {
14900 for (buffer_id, changes) in revert_changes {
14901 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14902 buffer.update(cx, |buffer, cx| {
14903 buffer.edit(
14904 changes.into_iter().map(|(range, text)| {
14905 (range, text.to_string().map(Arc::<str>::from))
14906 }),
14907 None,
14908 cx,
14909 );
14910 });
14911 }
14912 }
14913 });
14914 self.change_selections(None, window, cx, |selections| selections.refresh());
14915 }
14916
14917 pub fn to_pixel_point(
14918 &self,
14919 source: multi_buffer::Anchor,
14920 editor_snapshot: &EditorSnapshot,
14921 window: &mut Window,
14922 ) -> Option<gpui::Point<Pixels>> {
14923 let source_point = source.to_display_point(editor_snapshot);
14924 self.display_to_pixel_point(source_point, editor_snapshot, window)
14925 }
14926
14927 pub fn display_to_pixel_point(
14928 &self,
14929 source: DisplayPoint,
14930 editor_snapshot: &EditorSnapshot,
14931 window: &mut Window,
14932 ) -> Option<gpui::Point<Pixels>> {
14933 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14934 let text_layout_details = self.text_layout_details(window);
14935 let scroll_top = text_layout_details
14936 .scroll_anchor
14937 .scroll_position(editor_snapshot)
14938 .y;
14939
14940 if source.row().as_f32() < scroll_top.floor() {
14941 return None;
14942 }
14943 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14944 let source_y = line_height * (source.row().as_f32() - scroll_top);
14945 Some(gpui::Point::new(source_x, source_y))
14946 }
14947
14948 pub fn has_visible_completions_menu(&self) -> bool {
14949 !self.edit_prediction_preview_is_active()
14950 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14951 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14952 })
14953 }
14954
14955 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14956 self.addons
14957 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14958 }
14959
14960 pub fn unregister_addon<T: Addon>(&mut self) {
14961 self.addons.remove(&std::any::TypeId::of::<T>());
14962 }
14963
14964 pub fn addon<T: Addon>(&self) -> Option<&T> {
14965 let type_id = std::any::TypeId::of::<T>();
14966 self.addons
14967 .get(&type_id)
14968 .and_then(|item| item.to_any().downcast_ref::<T>())
14969 }
14970
14971 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14972 let text_layout_details = self.text_layout_details(window);
14973 let style = &text_layout_details.editor_style;
14974 let font_id = window.text_system().resolve_font(&style.text.font());
14975 let font_size = style.text.font_size.to_pixels(window.rem_size());
14976 let line_height = style.text.line_height_in_pixels(window.rem_size());
14977 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14978
14979 gpui::Size::new(em_width, line_height)
14980 }
14981
14982 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14983 self.load_diff_task.clone()
14984 }
14985}
14986
14987fn get_uncommitted_diff_for_buffer(
14988 project: &Entity<Project>,
14989 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14990 buffer: Entity<MultiBuffer>,
14991 cx: &mut App,
14992) -> Task<()> {
14993 let mut tasks = Vec::new();
14994 project.update(cx, |project, cx| {
14995 for buffer in buffers {
14996 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14997 }
14998 });
14999 cx.spawn(|mut cx| async move {
15000 let diffs = futures::future::join_all(tasks).await;
15001 buffer
15002 .update(&mut cx, |buffer, cx| {
15003 for diff in diffs.into_iter().flatten() {
15004 buffer.add_diff(diff, cx);
15005 }
15006 })
15007 .ok();
15008 })
15009}
15010
15011fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15012 let tab_size = tab_size.get() as usize;
15013 let mut width = offset;
15014
15015 for ch in text.chars() {
15016 width += if ch == '\t' {
15017 tab_size - (width % tab_size)
15018 } else {
15019 1
15020 };
15021 }
15022
15023 width - offset
15024}
15025
15026#[cfg(test)]
15027mod tests {
15028 use super::*;
15029
15030 #[test]
15031 fn test_string_size_with_expanded_tabs() {
15032 let nz = |val| NonZeroU32::new(val).unwrap();
15033 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15034 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15035 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15036 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15037 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15038 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15039 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15040 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15041 }
15042}
15043
15044/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15045struct WordBreakingTokenizer<'a> {
15046 input: &'a str,
15047}
15048
15049impl<'a> WordBreakingTokenizer<'a> {
15050 fn new(input: &'a str) -> Self {
15051 Self { input }
15052 }
15053}
15054
15055fn is_char_ideographic(ch: char) -> bool {
15056 use unicode_script::Script::*;
15057 use unicode_script::UnicodeScript;
15058 matches!(ch.script(), Han | Tangut | Yi)
15059}
15060
15061fn is_grapheme_ideographic(text: &str) -> bool {
15062 text.chars().any(is_char_ideographic)
15063}
15064
15065fn is_grapheme_whitespace(text: &str) -> bool {
15066 text.chars().any(|x| x.is_whitespace())
15067}
15068
15069fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15070 text.chars().next().map_or(false, |ch| {
15071 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15072 })
15073}
15074
15075#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15076struct WordBreakToken<'a> {
15077 token: &'a str,
15078 grapheme_len: usize,
15079 is_whitespace: bool,
15080}
15081
15082impl<'a> Iterator for WordBreakingTokenizer<'a> {
15083 /// Yields a span, the count of graphemes in the token, and whether it was
15084 /// whitespace. Note that it also breaks at word boundaries.
15085 type Item = WordBreakToken<'a>;
15086
15087 fn next(&mut self) -> Option<Self::Item> {
15088 use unicode_segmentation::UnicodeSegmentation;
15089 if self.input.is_empty() {
15090 return None;
15091 }
15092
15093 let mut iter = self.input.graphemes(true).peekable();
15094 let mut offset = 0;
15095 let mut graphemes = 0;
15096 if let Some(first_grapheme) = iter.next() {
15097 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15098 offset += first_grapheme.len();
15099 graphemes += 1;
15100 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15101 if let Some(grapheme) = iter.peek().copied() {
15102 if should_stay_with_preceding_ideograph(grapheme) {
15103 offset += grapheme.len();
15104 graphemes += 1;
15105 }
15106 }
15107 } else {
15108 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15109 let mut next_word_bound = words.peek().copied();
15110 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15111 next_word_bound = words.next();
15112 }
15113 while let Some(grapheme) = iter.peek().copied() {
15114 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15115 break;
15116 };
15117 if is_grapheme_whitespace(grapheme) != is_whitespace {
15118 break;
15119 };
15120 offset += grapheme.len();
15121 graphemes += 1;
15122 iter.next();
15123 }
15124 }
15125 let token = &self.input[..offset];
15126 self.input = &self.input[offset..];
15127 if is_whitespace {
15128 Some(WordBreakToken {
15129 token: " ",
15130 grapheme_len: 1,
15131 is_whitespace: true,
15132 })
15133 } else {
15134 Some(WordBreakToken {
15135 token,
15136 grapheme_len: graphemes,
15137 is_whitespace: false,
15138 })
15139 }
15140 } else {
15141 None
15142 }
15143 }
15144}
15145
15146#[test]
15147fn test_word_breaking_tokenizer() {
15148 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15149 ("", &[]),
15150 (" ", &[(" ", 1, true)]),
15151 ("Ʒ", &[("Ʒ", 1, false)]),
15152 ("Ǽ", &[("Ǽ", 1, false)]),
15153 ("⋑", &[("⋑", 1, false)]),
15154 ("⋑⋑", &[("⋑⋑", 2, false)]),
15155 (
15156 "原理,进而",
15157 &[
15158 ("原", 1, false),
15159 ("理,", 2, false),
15160 ("进", 1, false),
15161 ("而", 1, false),
15162 ],
15163 ),
15164 (
15165 "hello world",
15166 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15167 ),
15168 (
15169 "hello, world",
15170 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15171 ),
15172 (
15173 " hello world",
15174 &[
15175 (" ", 1, true),
15176 ("hello", 5, false),
15177 (" ", 1, true),
15178 ("world", 5, false),
15179 ],
15180 ),
15181 (
15182 "这是什么 \n 钢笔",
15183 &[
15184 ("这", 1, false),
15185 ("是", 1, false),
15186 ("什", 1, false),
15187 ("么", 1, false),
15188 (" ", 1, true),
15189 ("钢", 1, false),
15190 ("笔", 1, false),
15191 ],
15192 ),
15193 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15194 ];
15195
15196 for (input, result) in tests {
15197 assert_eq!(
15198 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15199 result
15200 .iter()
15201 .copied()
15202 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15203 token,
15204 grapheme_len,
15205 is_whitespace,
15206 })
15207 .collect::<Vec<_>>()
15208 );
15209 }
15210}
15211
15212fn wrap_with_prefix(
15213 line_prefix: String,
15214 unwrapped_text: String,
15215 wrap_column: usize,
15216 tab_size: NonZeroU32,
15217) -> String {
15218 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15219 let mut wrapped_text = String::new();
15220 let mut current_line = line_prefix.clone();
15221
15222 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15223 let mut current_line_len = line_prefix_len;
15224 for WordBreakToken {
15225 token,
15226 grapheme_len,
15227 is_whitespace,
15228 } in tokenizer
15229 {
15230 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15231 wrapped_text.push_str(current_line.trim_end());
15232 wrapped_text.push('\n');
15233 current_line.truncate(line_prefix.len());
15234 current_line_len = line_prefix_len;
15235 if !is_whitespace {
15236 current_line.push_str(token);
15237 current_line_len += grapheme_len;
15238 }
15239 } else if !is_whitespace {
15240 current_line.push_str(token);
15241 current_line_len += grapheme_len;
15242 } else if current_line_len != line_prefix_len {
15243 current_line.push(' ');
15244 current_line_len += 1;
15245 }
15246 }
15247
15248 if !current_line.is_empty() {
15249 wrapped_text.push_str(¤t_line);
15250 }
15251 wrapped_text
15252}
15253
15254#[test]
15255fn test_wrap_with_prefix() {
15256 assert_eq!(
15257 wrap_with_prefix(
15258 "# ".to_string(),
15259 "abcdefg".to_string(),
15260 4,
15261 NonZeroU32::new(4).unwrap()
15262 ),
15263 "# abcdefg"
15264 );
15265 assert_eq!(
15266 wrap_with_prefix(
15267 "".to_string(),
15268 "\thello world".to_string(),
15269 8,
15270 NonZeroU32::new(4).unwrap()
15271 ),
15272 "hello\nworld"
15273 );
15274 assert_eq!(
15275 wrap_with_prefix(
15276 "// ".to_string(),
15277 "xx \nyy zz aa bb cc".to_string(),
15278 12,
15279 NonZeroU32::new(4).unwrap()
15280 ),
15281 "// xx yy zz\n// aa bb cc"
15282 );
15283 assert_eq!(
15284 wrap_with_prefix(
15285 String::new(),
15286 "这是什么 \n 钢笔".to_string(),
15287 3,
15288 NonZeroU32::new(4).unwrap()
15289 ),
15290 "这是什\n么 钢\n笔"
15291 );
15292}
15293
15294pub trait CollaborationHub {
15295 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15296 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15297 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15298}
15299
15300impl CollaborationHub for Entity<Project> {
15301 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15302 self.read(cx).collaborators()
15303 }
15304
15305 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15306 self.read(cx).user_store().read(cx).participant_indices()
15307 }
15308
15309 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15310 let this = self.read(cx);
15311 let user_ids = this.collaborators().values().map(|c| c.user_id);
15312 this.user_store().read_with(cx, |user_store, cx| {
15313 user_store.participant_names(user_ids, cx)
15314 })
15315 }
15316}
15317
15318pub trait SemanticsProvider {
15319 fn hover(
15320 &self,
15321 buffer: &Entity<Buffer>,
15322 position: text::Anchor,
15323 cx: &mut App,
15324 ) -> Option<Task<Vec<project::Hover>>>;
15325
15326 fn inlay_hints(
15327 &self,
15328 buffer_handle: Entity<Buffer>,
15329 range: Range<text::Anchor>,
15330 cx: &mut App,
15331 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15332
15333 fn resolve_inlay_hint(
15334 &self,
15335 hint: InlayHint,
15336 buffer_handle: Entity<Buffer>,
15337 server_id: LanguageServerId,
15338 cx: &mut App,
15339 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15340
15341 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15342
15343 fn document_highlights(
15344 &self,
15345 buffer: &Entity<Buffer>,
15346 position: text::Anchor,
15347 cx: &mut App,
15348 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15349
15350 fn definitions(
15351 &self,
15352 buffer: &Entity<Buffer>,
15353 position: text::Anchor,
15354 kind: GotoDefinitionKind,
15355 cx: &mut App,
15356 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15357
15358 fn range_for_rename(
15359 &self,
15360 buffer: &Entity<Buffer>,
15361 position: text::Anchor,
15362 cx: &mut App,
15363 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15364
15365 fn perform_rename(
15366 &self,
15367 buffer: &Entity<Buffer>,
15368 position: text::Anchor,
15369 new_name: String,
15370 cx: &mut App,
15371 ) -> Option<Task<Result<ProjectTransaction>>>;
15372}
15373
15374pub trait CompletionProvider {
15375 fn completions(
15376 &self,
15377 buffer: &Entity<Buffer>,
15378 buffer_position: text::Anchor,
15379 trigger: CompletionContext,
15380 window: &mut Window,
15381 cx: &mut Context<Editor>,
15382 ) -> Task<Result<Vec<Completion>>>;
15383
15384 fn resolve_completions(
15385 &self,
15386 buffer: Entity<Buffer>,
15387 completion_indices: Vec<usize>,
15388 completions: Rc<RefCell<Box<[Completion]>>>,
15389 cx: &mut Context<Editor>,
15390 ) -> Task<Result<bool>>;
15391
15392 fn apply_additional_edits_for_completion(
15393 &self,
15394 _buffer: Entity<Buffer>,
15395 _completions: Rc<RefCell<Box<[Completion]>>>,
15396 _completion_index: usize,
15397 _push_to_history: bool,
15398 _cx: &mut Context<Editor>,
15399 ) -> Task<Result<Option<language::Transaction>>> {
15400 Task::ready(Ok(None))
15401 }
15402
15403 fn is_completion_trigger(
15404 &self,
15405 buffer: &Entity<Buffer>,
15406 position: language::Anchor,
15407 text: &str,
15408 trigger_in_words: bool,
15409 cx: &mut Context<Editor>,
15410 ) -> bool;
15411
15412 fn sort_completions(&self) -> bool {
15413 true
15414 }
15415}
15416
15417pub trait CodeActionProvider {
15418 fn id(&self) -> Arc<str>;
15419
15420 fn code_actions(
15421 &self,
15422 buffer: &Entity<Buffer>,
15423 range: Range<text::Anchor>,
15424 window: &mut Window,
15425 cx: &mut App,
15426 ) -> Task<Result<Vec<CodeAction>>>;
15427
15428 fn apply_code_action(
15429 &self,
15430 buffer_handle: Entity<Buffer>,
15431 action: CodeAction,
15432 excerpt_id: ExcerptId,
15433 push_to_history: bool,
15434 window: &mut Window,
15435 cx: &mut App,
15436 ) -> Task<Result<ProjectTransaction>>;
15437}
15438
15439impl CodeActionProvider for Entity<Project> {
15440 fn id(&self) -> Arc<str> {
15441 "project".into()
15442 }
15443
15444 fn code_actions(
15445 &self,
15446 buffer: &Entity<Buffer>,
15447 range: Range<text::Anchor>,
15448 _window: &mut Window,
15449 cx: &mut App,
15450 ) -> Task<Result<Vec<CodeAction>>> {
15451 self.update(cx, |project, cx| {
15452 project.code_actions(buffer, range, None, cx)
15453 })
15454 }
15455
15456 fn apply_code_action(
15457 &self,
15458 buffer_handle: Entity<Buffer>,
15459 action: CodeAction,
15460 _excerpt_id: ExcerptId,
15461 push_to_history: bool,
15462 _window: &mut Window,
15463 cx: &mut App,
15464 ) -> Task<Result<ProjectTransaction>> {
15465 self.update(cx, |project, cx| {
15466 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15467 })
15468 }
15469}
15470
15471fn snippet_completions(
15472 project: &Project,
15473 buffer: &Entity<Buffer>,
15474 buffer_position: text::Anchor,
15475 cx: &mut App,
15476) -> Task<Result<Vec<Completion>>> {
15477 let language = buffer.read(cx).language_at(buffer_position);
15478 let language_name = language.as_ref().map(|language| language.lsp_id());
15479 let snippet_store = project.snippets().read(cx);
15480 let snippets = snippet_store.snippets_for(language_name, cx);
15481
15482 if snippets.is_empty() {
15483 return Task::ready(Ok(vec![]));
15484 }
15485 let snapshot = buffer.read(cx).text_snapshot();
15486 let chars: String = snapshot
15487 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15488 .collect();
15489
15490 let scope = language.map(|language| language.default_scope());
15491 let executor = cx.background_executor().clone();
15492
15493 cx.background_executor().spawn(async move {
15494 let classifier = CharClassifier::new(scope).for_completion(true);
15495 let mut last_word = chars
15496 .chars()
15497 .take_while(|c| classifier.is_word(*c))
15498 .collect::<String>();
15499 last_word = last_word.chars().rev().collect();
15500
15501 if last_word.is_empty() {
15502 return Ok(vec![]);
15503 }
15504
15505 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15506 let to_lsp = |point: &text::Anchor| {
15507 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15508 point_to_lsp(end)
15509 };
15510 let lsp_end = to_lsp(&buffer_position);
15511
15512 let candidates = snippets
15513 .iter()
15514 .enumerate()
15515 .flat_map(|(ix, snippet)| {
15516 snippet
15517 .prefix
15518 .iter()
15519 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15520 })
15521 .collect::<Vec<StringMatchCandidate>>();
15522
15523 let mut matches = fuzzy::match_strings(
15524 &candidates,
15525 &last_word,
15526 last_word.chars().any(|c| c.is_uppercase()),
15527 100,
15528 &Default::default(),
15529 executor,
15530 )
15531 .await;
15532
15533 // Remove all candidates where the query's start does not match the start of any word in the candidate
15534 if let Some(query_start) = last_word.chars().next() {
15535 matches.retain(|string_match| {
15536 split_words(&string_match.string).any(|word| {
15537 // Check that the first codepoint of the word as lowercase matches the first
15538 // codepoint of the query as lowercase
15539 word.chars()
15540 .flat_map(|codepoint| codepoint.to_lowercase())
15541 .zip(query_start.to_lowercase())
15542 .all(|(word_cp, query_cp)| word_cp == query_cp)
15543 })
15544 });
15545 }
15546
15547 let matched_strings = matches
15548 .into_iter()
15549 .map(|m| m.string)
15550 .collect::<HashSet<_>>();
15551
15552 let result: Vec<Completion> = snippets
15553 .into_iter()
15554 .filter_map(|snippet| {
15555 let matching_prefix = snippet
15556 .prefix
15557 .iter()
15558 .find(|prefix| matched_strings.contains(*prefix))?;
15559 let start = as_offset - last_word.len();
15560 let start = snapshot.anchor_before(start);
15561 let range = start..buffer_position;
15562 let lsp_start = to_lsp(&start);
15563 let lsp_range = lsp::Range {
15564 start: lsp_start,
15565 end: lsp_end,
15566 };
15567 Some(Completion {
15568 old_range: range,
15569 new_text: snippet.body.clone(),
15570 resolved: false,
15571 label: CodeLabel {
15572 text: matching_prefix.clone(),
15573 runs: vec![],
15574 filter_range: 0..matching_prefix.len(),
15575 },
15576 server_id: LanguageServerId(usize::MAX),
15577 documentation: snippet
15578 .description
15579 .clone()
15580 .map(CompletionDocumentation::SingleLine),
15581 lsp_completion: lsp::CompletionItem {
15582 label: snippet.prefix.first().unwrap().clone(),
15583 kind: Some(CompletionItemKind::SNIPPET),
15584 label_details: snippet.description.as_ref().map(|description| {
15585 lsp::CompletionItemLabelDetails {
15586 detail: Some(description.clone()),
15587 description: None,
15588 }
15589 }),
15590 insert_text_format: Some(InsertTextFormat::SNIPPET),
15591 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15592 lsp::InsertReplaceEdit {
15593 new_text: snippet.body.clone(),
15594 insert: lsp_range,
15595 replace: lsp_range,
15596 },
15597 )),
15598 filter_text: Some(snippet.body.clone()),
15599 sort_text: Some(char::MAX.to_string()),
15600 ..Default::default()
15601 },
15602 confirm: None,
15603 })
15604 })
15605 .collect();
15606
15607 Ok(result)
15608 })
15609}
15610
15611impl CompletionProvider for Entity<Project> {
15612 fn completions(
15613 &self,
15614 buffer: &Entity<Buffer>,
15615 buffer_position: text::Anchor,
15616 options: CompletionContext,
15617 _window: &mut Window,
15618 cx: &mut Context<Editor>,
15619 ) -> Task<Result<Vec<Completion>>> {
15620 self.update(cx, |project, cx| {
15621 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15622 let project_completions = project.completions(buffer, buffer_position, options, cx);
15623 cx.background_executor().spawn(async move {
15624 let mut completions = project_completions.await?;
15625 let snippets_completions = snippets.await?;
15626 completions.extend(snippets_completions);
15627 Ok(completions)
15628 })
15629 })
15630 }
15631
15632 fn resolve_completions(
15633 &self,
15634 buffer: Entity<Buffer>,
15635 completion_indices: Vec<usize>,
15636 completions: Rc<RefCell<Box<[Completion]>>>,
15637 cx: &mut Context<Editor>,
15638 ) -> Task<Result<bool>> {
15639 self.update(cx, |project, cx| {
15640 project.lsp_store().update(cx, |lsp_store, cx| {
15641 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15642 })
15643 })
15644 }
15645
15646 fn apply_additional_edits_for_completion(
15647 &self,
15648 buffer: Entity<Buffer>,
15649 completions: Rc<RefCell<Box<[Completion]>>>,
15650 completion_index: usize,
15651 push_to_history: bool,
15652 cx: &mut Context<Editor>,
15653 ) -> Task<Result<Option<language::Transaction>>> {
15654 self.update(cx, |project, cx| {
15655 project.lsp_store().update(cx, |lsp_store, cx| {
15656 lsp_store.apply_additional_edits_for_completion(
15657 buffer,
15658 completions,
15659 completion_index,
15660 push_to_history,
15661 cx,
15662 )
15663 })
15664 })
15665 }
15666
15667 fn is_completion_trigger(
15668 &self,
15669 buffer: &Entity<Buffer>,
15670 position: language::Anchor,
15671 text: &str,
15672 trigger_in_words: bool,
15673 cx: &mut Context<Editor>,
15674 ) -> bool {
15675 let mut chars = text.chars();
15676 let char = if let Some(char) = chars.next() {
15677 char
15678 } else {
15679 return false;
15680 };
15681 if chars.next().is_some() {
15682 return false;
15683 }
15684
15685 let buffer = buffer.read(cx);
15686 let snapshot = buffer.snapshot();
15687 if !snapshot.settings_at(position, cx).show_completions_on_input {
15688 return false;
15689 }
15690 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15691 if trigger_in_words && classifier.is_word(char) {
15692 return true;
15693 }
15694
15695 buffer.completion_triggers().contains(text)
15696 }
15697}
15698
15699impl SemanticsProvider for Entity<Project> {
15700 fn hover(
15701 &self,
15702 buffer: &Entity<Buffer>,
15703 position: text::Anchor,
15704 cx: &mut App,
15705 ) -> Option<Task<Vec<project::Hover>>> {
15706 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15707 }
15708
15709 fn document_highlights(
15710 &self,
15711 buffer: &Entity<Buffer>,
15712 position: text::Anchor,
15713 cx: &mut App,
15714 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15715 Some(self.update(cx, |project, cx| {
15716 project.document_highlights(buffer, position, cx)
15717 }))
15718 }
15719
15720 fn definitions(
15721 &self,
15722 buffer: &Entity<Buffer>,
15723 position: text::Anchor,
15724 kind: GotoDefinitionKind,
15725 cx: &mut App,
15726 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15727 Some(self.update(cx, |project, cx| match kind {
15728 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15729 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15730 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15731 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15732 }))
15733 }
15734
15735 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15736 // TODO: make this work for remote projects
15737 self.update(cx, |this, cx| {
15738 buffer.update(cx, |buffer, cx| {
15739 this.any_language_server_supports_inlay_hints(buffer, cx)
15740 })
15741 })
15742 }
15743
15744 fn inlay_hints(
15745 &self,
15746 buffer_handle: Entity<Buffer>,
15747 range: Range<text::Anchor>,
15748 cx: &mut App,
15749 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15750 Some(self.update(cx, |project, cx| {
15751 project.inlay_hints(buffer_handle, range, cx)
15752 }))
15753 }
15754
15755 fn resolve_inlay_hint(
15756 &self,
15757 hint: InlayHint,
15758 buffer_handle: Entity<Buffer>,
15759 server_id: LanguageServerId,
15760 cx: &mut App,
15761 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15762 Some(self.update(cx, |project, cx| {
15763 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15764 }))
15765 }
15766
15767 fn range_for_rename(
15768 &self,
15769 buffer: &Entity<Buffer>,
15770 position: text::Anchor,
15771 cx: &mut App,
15772 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15773 Some(self.update(cx, |project, cx| {
15774 let buffer = buffer.clone();
15775 let task = project.prepare_rename(buffer.clone(), position, cx);
15776 cx.spawn(|_, mut cx| async move {
15777 Ok(match task.await? {
15778 PrepareRenameResponse::Success(range) => Some(range),
15779 PrepareRenameResponse::InvalidPosition => None,
15780 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15781 // Fallback on using TreeSitter info to determine identifier range
15782 buffer.update(&mut cx, |buffer, _| {
15783 let snapshot = buffer.snapshot();
15784 let (range, kind) = snapshot.surrounding_word(position);
15785 if kind != Some(CharKind::Word) {
15786 return None;
15787 }
15788 Some(
15789 snapshot.anchor_before(range.start)
15790 ..snapshot.anchor_after(range.end),
15791 )
15792 })?
15793 }
15794 })
15795 })
15796 }))
15797 }
15798
15799 fn perform_rename(
15800 &self,
15801 buffer: &Entity<Buffer>,
15802 position: text::Anchor,
15803 new_name: String,
15804 cx: &mut App,
15805 ) -> Option<Task<Result<ProjectTransaction>>> {
15806 Some(self.update(cx, |project, cx| {
15807 project.perform_rename(buffer.clone(), position, new_name, cx)
15808 }))
15809 }
15810}
15811
15812fn inlay_hint_settings(
15813 location: Anchor,
15814 snapshot: &MultiBufferSnapshot,
15815 cx: &mut Context<Editor>,
15816) -> InlayHintSettings {
15817 let file = snapshot.file_at(location);
15818 let language = snapshot.language_at(location).map(|l| l.name());
15819 language_settings(language, file, cx).inlay_hints
15820}
15821
15822fn consume_contiguous_rows(
15823 contiguous_row_selections: &mut Vec<Selection<Point>>,
15824 selection: &Selection<Point>,
15825 display_map: &DisplaySnapshot,
15826 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15827) -> (MultiBufferRow, MultiBufferRow) {
15828 contiguous_row_selections.push(selection.clone());
15829 let start_row = MultiBufferRow(selection.start.row);
15830 let mut end_row = ending_row(selection, display_map);
15831
15832 while let Some(next_selection) = selections.peek() {
15833 if next_selection.start.row <= end_row.0 {
15834 end_row = ending_row(next_selection, display_map);
15835 contiguous_row_selections.push(selections.next().unwrap().clone());
15836 } else {
15837 break;
15838 }
15839 }
15840 (start_row, end_row)
15841}
15842
15843fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15844 if next_selection.end.column > 0 || next_selection.is_empty() {
15845 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15846 } else {
15847 MultiBufferRow(next_selection.end.row)
15848 }
15849}
15850
15851impl EditorSnapshot {
15852 pub fn remote_selections_in_range<'a>(
15853 &'a self,
15854 range: &'a Range<Anchor>,
15855 collaboration_hub: &dyn CollaborationHub,
15856 cx: &'a App,
15857 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15858 let participant_names = collaboration_hub.user_names(cx);
15859 let participant_indices = collaboration_hub.user_participant_indices(cx);
15860 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15861 let collaborators_by_replica_id = collaborators_by_peer_id
15862 .iter()
15863 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15864 .collect::<HashMap<_, _>>();
15865 self.buffer_snapshot
15866 .selections_in_range(range, false)
15867 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15868 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15869 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15870 let user_name = participant_names.get(&collaborator.user_id).cloned();
15871 Some(RemoteSelection {
15872 replica_id,
15873 selection,
15874 cursor_shape,
15875 line_mode,
15876 participant_index,
15877 peer_id: collaborator.peer_id,
15878 user_name,
15879 })
15880 })
15881 }
15882
15883 pub fn hunks_for_ranges(
15884 &self,
15885 ranges: impl Iterator<Item = Range<Point>>,
15886 ) -> Vec<MultiBufferDiffHunk> {
15887 let mut hunks = Vec::new();
15888 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15889 HashMap::default();
15890 for query_range in ranges {
15891 let query_rows =
15892 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15893 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15894 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15895 ) {
15896 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15897 // when the caret is just above or just below the deleted hunk.
15898 let allow_adjacent = hunk.status().is_removed();
15899 let related_to_selection = if allow_adjacent {
15900 hunk.row_range.overlaps(&query_rows)
15901 || hunk.row_range.start == query_rows.end
15902 || hunk.row_range.end == query_rows.start
15903 } else {
15904 hunk.row_range.overlaps(&query_rows)
15905 };
15906 if related_to_selection {
15907 if !processed_buffer_rows
15908 .entry(hunk.buffer_id)
15909 .or_default()
15910 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15911 {
15912 continue;
15913 }
15914 hunks.push(hunk);
15915 }
15916 }
15917 }
15918
15919 hunks
15920 }
15921
15922 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15923 self.display_snapshot.buffer_snapshot.language_at(position)
15924 }
15925
15926 pub fn is_focused(&self) -> bool {
15927 self.is_focused
15928 }
15929
15930 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15931 self.placeholder_text.as_ref()
15932 }
15933
15934 pub fn scroll_position(&self) -> gpui::Point<f32> {
15935 self.scroll_anchor.scroll_position(&self.display_snapshot)
15936 }
15937
15938 fn gutter_dimensions(
15939 &self,
15940 font_id: FontId,
15941 font_size: Pixels,
15942 max_line_number_width: Pixels,
15943 cx: &App,
15944 ) -> Option<GutterDimensions> {
15945 if !self.show_gutter {
15946 return None;
15947 }
15948
15949 let descent = cx.text_system().descent(font_id, font_size);
15950 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15951 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15952
15953 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15954 matches!(
15955 ProjectSettings::get_global(cx).git.git_gutter,
15956 Some(GitGutterSetting::TrackedFiles)
15957 )
15958 });
15959 let gutter_settings = EditorSettings::get_global(cx).gutter;
15960 let show_line_numbers = self
15961 .show_line_numbers
15962 .unwrap_or(gutter_settings.line_numbers);
15963 let line_gutter_width = if show_line_numbers {
15964 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15965 let min_width_for_number_on_gutter = em_advance * 4.0;
15966 max_line_number_width.max(min_width_for_number_on_gutter)
15967 } else {
15968 0.0.into()
15969 };
15970
15971 let show_code_actions = self
15972 .show_code_actions
15973 .unwrap_or(gutter_settings.code_actions);
15974
15975 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15976
15977 let git_blame_entries_width =
15978 self.git_blame_gutter_max_author_length
15979 .map(|max_author_length| {
15980 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15981
15982 /// The number of characters to dedicate to gaps and margins.
15983 const SPACING_WIDTH: usize = 4;
15984
15985 let max_char_count = max_author_length
15986 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15987 + ::git::SHORT_SHA_LENGTH
15988 + MAX_RELATIVE_TIMESTAMP.len()
15989 + SPACING_WIDTH;
15990
15991 em_advance * max_char_count
15992 });
15993
15994 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15995 left_padding += if show_code_actions || show_runnables {
15996 em_width * 3.0
15997 } else if show_git_gutter && show_line_numbers {
15998 em_width * 2.0
15999 } else if show_git_gutter || show_line_numbers {
16000 em_width
16001 } else {
16002 px(0.)
16003 };
16004
16005 let right_padding = if gutter_settings.folds && show_line_numbers {
16006 em_width * 4.0
16007 } else if gutter_settings.folds {
16008 em_width * 3.0
16009 } else if show_line_numbers {
16010 em_width
16011 } else {
16012 px(0.)
16013 };
16014
16015 Some(GutterDimensions {
16016 left_padding,
16017 right_padding,
16018 width: line_gutter_width + left_padding + right_padding,
16019 margin: -descent,
16020 git_blame_entries_width,
16021 })
16022 }
16023
16024 pub fn render_crease_toggle(
16025 &self,
16026 buffer_row: MultiBufferRow,
16027 row_contains_cursor: bool,
16028 editor: Entity<Editor>,
16029 window: &mut Window,
16030 cx: &mut App,
16031 ) -> Option<AnyElement> {
16032 let folded = self.is_line_folded(buffer_row);
16033 let mut is_foldable = false;
16034
16035 if let Some(crease) = self
16036 .crease_snapshot
16037 .query_row(buffer_row, &self.buffer_snapshot)
16038 {
16039 is_foldable = true;
16040 match crease {
16041 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16042 if let Some(render_toggle) = render_toggle {
16043 let toggle_callback =
16044 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16045 if folded {
16046 editor.update(cx, |editor, cx| {
16047 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16048 });
16049 } else {
16050 editor.update(cx, |editor, cx| {
16051 editor.unfold_at(
16052 &crate::UnfoldAt { buffer_row },
16053 window,
16054 cx,
16055 )
16056 });
16057 }
16058 });
16059 return Some((render_toggle)(
16060 buffer_row,
16061 folded,
16062 toggle_callback,
16063 window,
16064 cx,
16065 ));
16066 }
16067 }
16068 }
16069 }
16070
16071 is_foldable |= self.starts_indent(buffer_row);
16072
16073 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16074 Some(
16075 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16076 .toggle_state(folded)
16077 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16078 if folded {
16079 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16080 } else {
16081 this.fold_at(&FoldAt { buffer_row }, window, cx);
16082 }
16083 }))
16084 .into_any_element(),
16085 )
16086 } else {
16087 None
16088 }
16089 }
16090
16091 pub fn render_crease_trailer(
16092 &self,
16093 buffer_row: MultiBufferRow,
16094 window: &mut Window,
16095 cx: &mut App,
16096 ) -> Option<AnyElement> {
16097 let folded = self.is_line_folded(buffer_row);
16098 if let Crease::Inline { render_trailer, .. } = self
16099 .crease_snapshot
16100 .query_row(buffer_row, &self.buffer_snapshot)?
16101 {
16102 let render_trailer = render_trailer.as_ref()?;
16103 Some(render_trailer(buffer_row, folded, window, cx))
16104 } else {
16105 None
16106 }
16107 }
16108}
16109
16110impl Deref for EditorSnapshot {
16111 type Target = DisplaySnapshot;
16112
16113 fn deref(&self) -> &Self::Target {
16114 &self.display_snapshot
16115 }
16116}
16117
16118#[derive(Clone, Debug, PartialEq, Eq)]
16119pub enum EditorEvent {
16120 InputIgnored {
16121 text: Arc<str>,
16122 },
16123 InputHandled {
16124 utf16_range_to_replace: Option<Range<isize>>,
16125 text: Arc<str>,
16126 },
16127 ExcerptsAdded {
16128 buffer: Entity<Buffer>,
16129 predecessor: ExcerptId,
16130 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16131 },
16132 ExcerptsRemoved {
16133 ids: Vec<ExcerptId>,
16134 },
16135 BufferFoldToggled {
16136 ids: Vec<ExcerptId>,
16137 folded: bool,
16138 },
16139 ExcerptsEdited {
16140 ids: Vec<ExcerptId>,
16141 },
16142 ExcerptsExpanded {
16143 ids: Vec<ExcerptId>,
16144 },
16145 BufferEdited,
16146 Edited {
16147 transaction_id: clock::Lamport,
16148 },
16149 Reparsed(BufferId),
16150 Focused,
16151 FocusedIn,
16152 Blurred,
16153 DirtyChanged,
16154 Saved,
16155 TitleChanged,
16156 DiffBaseChanged,
16157 SelectionsChanged {
16158 local: bool,
16159 },
16160 ScrollPositionChanged {
16161 local: bool,
16162 autoscroll: bool,
16163 },
16164 Closed,
16165 TransactionUndone {
16166 transaction_id: clock::Lamport,
16167 },
16168 TransactionBegun {
16169 transaction_id: clock::Lamport,
16170 },
16171 Reloaded,
16172 CursorShapeChanged,
16173}
16174
16175impl EventEmitter<EditorEvent> for Editor {}
16176
16177impl Focusable for Editor {
16178 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16179 self.focus_handle.clone()
16180 }
16181}
16182
16183impl Render for Editor {
16184 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16185 let settings = ThemeSettings::get_global(cx);
16186
16187 let mut text_style = match self.mode {
16188 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16189 color: cx.theme().colors().editor_foreground,
16190 font_family: settings.ui_font.family.clone(),
16191 font_features: settings.ui_font.features.clone(),
16192 font_fallbacks: settings.ui_font.fallbacks.clone(),
16193 font_size: rems(0.875).into(),
16194 font_weight: settings.ui_font.weight,
16195 line_height: relative(settings.buffer_line_height.value()),
16196 ..Default::default()
16197 },
16198 EditorMode::Full => TextStyle {
16199 color: cx.theme().colors().editor_foreground,
16200 font_family: settings.buffer_font.family.clone(),
16201 font_features: settings.buffer_font.features.clone(),
16202 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16203 font_size: settings.buffer_font_size(cx).into(),
16204 font_weight: settings.buffer_font.weight,
16205 line_height: relative(settings.buffer_line_height.value()),
16206 ..Default::default()
16207 },
16208 };
16209 if let Some(text_style_refinement) = &self.text_style_refinement {
16210 text_style.refine(text_style_refinement)
16211 }
16212
16213 let background = match self.mode {
16214 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16215 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16216 EditorMode::Full => cx.theme().colors().editor_background,
16217 };
16218
16219 EditorElement::new(
16220 &cx.entity(),
16221 EditorStyle {
16222 background,
16223 local_player: cx.theme().players().local(),
16224 text: text_style,
16225 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16226 syntax: cx.theme().syntax().clone(),
16227 status: cx.theme().status().clone(),
16228 inlay_hints_style: make_inlay_hints_style(cx),
16229 inline_completion_styles: make_suggestion_styles(cx),
16230 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16231 },
16232 )
16233 }
16234}
16235
16236impl EntityInputHandler for Editor {
16237 fn text_for_range(
16238 &mut self,
16239 range_utf16: Range<usize>,
16240 adjusted_range: &mut Option<Range<usize>>,
16241 _: &mut Window,
16242 cx: &mut Context<Self>,
16243 ) -> Option<String> {
16244 let snapshot = self.buffer.read(cx).read(cx);
16245 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16246 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16247 if (start.0..end.0) != range_utf16 {
16248 adjusted_range.replace(start.0..end.0);
16249 }
16250 Some(snapshot.text_for_range(start..end).collect())
16251 }
16252
16253 fn selected_text_range(
16254 &mut self,
16255 ignore_disabled_input: bool,
16256 _: &mut Window,
16257 cx: &mut Context<Self>,
16258 ) -> Option<UTF16Selection> {
16259 // Prevent the IME menu from appearing when holding down an alphabetic key
16260 // while input is disabled.
16261 if !ignore_disabled_input && !self.input_enabled {
16262 return None;
16263 }
16264
16265 let selection = self.selections.newest::<OffsetUtf16>(cx);
16266 let range = selection.range();
16267
16268 Some(UTF16Selection {
16269 range: range.start.0..range.end.0,
16270 reversed: selection.reversed,
16271 })
16272 }
16273
16274 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16275 let snapshot = self.buffer.read(cx).read(cx);
16276 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16277 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16278 }
16279
16280 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16281 self.clear_highlights::<InputComposition>(cx);
16282 self.ime_transaction.take();
16283 }
16284
16285 fn replace_text_in_range(
16286 &mut self,
16287 range_utf16: Option<Range<usize>>,
16288 text: &str,
16289 window: &mut Window,
16290 cx: &mut Context<Self>,
16291 ) {
16292 if !self.input_enabled {
16293 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16294 return;
16295 }
16296
16297 self.transact(window, cx, |this, window, cx| {
16298 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16299 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16300 Some(this.selection_replacement_ranges(range_utf16, cx))
16301 } else {
16302 this.marked_text_ranges(cx)
16303 };
16304
16305 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16306 let newest_selection_id = this.selections.newest_anchor().id;
16307 this.selections
16308 .all::<OffsetUtf16>(cx)
16309 .iter()
16310 .zip(ranges_to_replace.iter())
16311 .find_map(|(selection, range)| {
16312 if selection.id == newest_selection_id {
16313 Some(
16314 (range.start.0 as isize - selection.head().0 as isize)
16315 ..(range.end.0 as isize - selection.head().0 as isize),
16316 )
16317 } else {
16318 None
16319 }
16320 })
16321 });
16322
16323 cx.emit(EditorEvent::InputHandled {
16324 utf16_range_to_replace: range_to_replace,
16325 text: text.into(),
16326 });
16327
16328 if let Some(new_selected_ranges) = new_selected_ranges {
16329 this.change_selections(None, window, cx, |selections| {
16330 selections.select_ranges(new_selected_ranges)
16331 });
16332 this.backspace(&Default::default(), window, cx);
16333 }
16334
16335 this.handle_input(text, window, cx);
16336 });
16337
16338 if let Some(transaction) = self.ime_transaction {
16339 self.buffer.update(cx, |buffer, cx| {
16340 buffer.group_until_transaction(transaction, cx);
16341 });
16342 }
16343
16344 self.unmark_text(window, cx);
16345 }
16346
16347 fn replace_and_mark_text_in_range(
16348 &mut self,
16349 range_utf16: Option<Range<usize>>,
16350 text: &str,
16351 new_selected_range_utf16: Option<Range<usize>>,
16352 window: &mut Window,
16353 cx: &mut Context<Self>,
16354 ) {
16355 if !self.input_enabled {
16356 return;
16357 }
16358
16359 let transaction = self.transact(window, cx, |this, window, cx| {
16360 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16361 let snapshot = this.buffer.read(cx).read(cx);
16362 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16363 for marked_range in &mut marked_ranges {
16364 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16365 marked_range.start.0 += relative_range_utf16.start;
16366 marked_range.start =
16367 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16368 marked_range.end =
16369 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16370 }
16371 }
16372 Some(marked_ranges)
16373 } else if let Some(range_utf16) = range_utf16 {
16374 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16375 Some(this.selection_replacement_ranges(range_utf16, cx))
16376 } else {
16377 None
16378 };
16379
16380 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16381 let newest_selection_id = this.selections.newest_anchor().id;
16382 this.selections
16383 .all::<OffsetUtf16>(cx)
16384 .iter()
16385 .zip(ranges_to_replace.iter())
16386 .find_map(|(selection, range)| {
16387 if selection.id == newest_selection_id {
16388 Some(
16389 (range.start.0 as isize - selection.head().0 as isize)
16390 ..(range.end.0 as isize - selection.head().0 as isize),
16391 )
16392 } else {
16393 None
16394 }
16395 })
16396 });
16397
16398 cx.emit(EditorEvent::InputHandled {
16399 utf16_range_to_replace: range_to_replace,
16400 text: text.into(),
16401 });
16402
16403 if let Some(ranges) = ranges_to_replace {
16404 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16405 }
16406
16407 let marked_ranges = {
16408 let snapshot = this.buffer.read(cx).read(cx);
16409 this.selections
16410 .disjoint_anchors()
16411 .iter()
16412 .map(|selection| {
16413 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16414 })
16415 .collect::<Vec<_>>()
16416 };
16417
16418 if text.is_empty() {
16419 this.unmark_text(window, cx);
16420 } else {
16421 this.highlight_text::<InputComposition>(
16422 marked_ranges.clone(),
16423 HighlightStyle {
16424 underline: Some(UnderlineStyle {
16425 thickness: px(1.),
16426 color: None,
16427 wavy: false,
16428 }),
16429 ..Default::default()
16430 },
16431 cx,
16432 );
16433 }
16434
16435 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16436 let use_autoclose = this.use_autoclose;
16437 let use_auto_surround = this.use_auto_surround;
16438 this.set_use_autoclose(false);
16439 this.set_use_auto_surround(false);
16440 this.handle_input(text, window, cx);
16441 this.set_use_autoclose(use_autoclose);
16442 this.set_use_auto_surround(use_auto_surround);
16443
16444 if let Some(new_selected_range) = new_selected_range_utf16 {
16445 let snapshot = this.buffer.read(cx).read(cx);
16446 let new_selected_ranges = marked_ranges
16447 .into_iter()
16448 .map(|marked_range| {
16449 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16450 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16451 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16452 snapshot.clip_offset_utf16(new_start, Bias::Left)
16453 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16454 })
16455 .collect::<Vec<_>>();
16456
16457 drop(snapshot);
16458 this.change_selections(None, window, cx, |selections| {
16459 selections.select_ranges(new_selected_ranges)
16460 });
16461 }
16462 });
16463
16464 self.ime_transaction = self.ime_transaction.or(transaction);
16465 if let Some(transaction) = self.ime_transaction {
16466 self.buffer.update(cx, |buffer, cx| {
16467 buffer.group_until_transaction(transaction, cx);
16468 });
16469 }
16470
16471 if self.text_highlights::<InputComposition>(cx).is_none() {
16472 self.ime_transaction.take();
16473 }
16474 }
16475
16476 fn bounds_for_range(
16477 &mut self,
16478 range_utf16: Range<usize>,
16479 element_bounds: gpui::Bounds<Pixels>,
16480 window: &mut Window,
16481 cx: &mut Context<Self>,
16482 ) -> Option<gpui::Bounds<Pixels>> {
16483 let text_layout_details = self.text_layout_details(window);
16484 let gpui::Size {
16485 width: em_width,
16486 height: line_height,
16487 } = self.character_size(window);
16488
16489 let snapshot = self.snapshot(window, cx);
16490 let scroll_position = snapshot.scroll_position();
16491 let scroll_left = scroll_position.x * em_width;
16492
16493 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16494 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16495 + self.gutter_dimensions.width
16496 + self.gutter_dimensions.margin;
16497 let y = line_height * (start.row().as_f32() - scroll_position.y);
16498
16499 Some(Bounds {
16500 origin: element_bounds.origin + point(x, y),
16501 size: size(em_width, line_height),
16502 })
16503 }
16504
16505 fn character_index_for_point(
16506 &mut self,
16507 point: gpui::Point<Pixels>,
16508 _window: &mut Window,
16509 _cx: &mut Context<Self>,
16510 ) -> Option<usize> {
16511 let position_map = self.last_position_map.as_ref()?;
16512 if !position_map.text_hitbox.contains(&point) {
16513 return None;
16514 }
16515 let display_point = position_map.point_for_position(point).previous_valid;
16516 let anchor = position_map
16517 .snapshot
16518 .display_point_to_anchor(display_point, Bias::Left);
16519 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16520 Some(utf16_offset.0)
16521 }
16522}
16523
16524trait SelectionExt {
16525 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16526 fn spanned_rows(
16527 &self,
16528 include_end_if_at_line_start: bool,
16529 map: &DisplaySnapshot,
16530 ) -> Range<MultiBufferRow>;
16531}
16532
16533impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16534 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16535 let start = self
16536 .start
16537 .to_point(&map.buffer_snapshot)
16538 .to_display_point(map);
16539 let end = self
16540 .end
16541 .to_point(&map.buffer_snapshot)
16542 .to_display_point(map);
16543 if self.reversed {
16544 end..start
16545 } else {
16546 start..end
16547 }
16548 }
16549
16550 fn spanned_rows(
16551 &self,
16552 include_end_if_at_line_start: bool,
16553 map: &DisplaySnapshot,
16554 ) -> Range<MultiBufferRow> {
16555 let start = self.start.to_point(&map.buffer_snapshot);
16556 let mut end = self.end.to_point(&map.buffer_snapshot);
16557 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16558 end.row -= 1;
16559 }
16560
16561 let buffer_start = map.prev_line_boundary(start).0;
16562 let buffer_end = map.next_line_boundary(end).0;
16563 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16564 }
16565}
16566
16567impl<T: InvalidationRegion> InvalidationStack<T> {
16568 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16569 where
16570 S: Clone + ToOffset,
16571 {
16572 while let Some(region) = self.last() {
16573 let all_selections_inside_invalidation_ranges =
16574 if selections.len() == region.ranges().len() {
16575 selections
16576 .iter()
16577 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16578 .all(|(selection, invalidation_range)| {
16579 let head = selection.head().to_offset(buffer);
16580 invalidation_range.start <= head && invalidation_range.end >= head
16581 })
16582 } else {
16583 false
16584 };
16585
16586 if all_selections_inside_invalidation_ranges {
16587 break;
16588 } else {
16589 self.pop();
16590 }
16591 }
16592 }
16593}
16594
16595impl<T> Default for InvalidationStack<T> {
16596 fn default() -> Self {
16597 Self(Default::default())
16598 }
16599}
16600
16601impl<T> Deref for InvalidationStack<T> {
16602 type Target = Vec<T>;
16603
16604 fn deref(&self) -> &Self::Target {
16605 &self.0
16606 }
16607}
16608
16609impl<T> DerefMut for InvalidationStack<T> {
16610 fn deref_mut(&mut self) -> &mut Self::Target {
16611 &mut self.0
16612 }
16613}
16614
16615impl InvalidationRegion for SnippetState {
16616 fn ranges(&self) -> &[Range<Anchor>] {
16617 &self.ranges[self.active_index]
16618 }
16619}
16620
16621pub fn diagnostic_block_renderer(
16622 diagnostic: Diagnostic,
16623 max_message_rows: Option<u8>,
16624 allow_closing: bool,
16625 _is_valid: bool,
16626) -> RenderBlock {
16627 let (text_without_backticks, code_ranges) =
16628 highlight_diagnostic_message(&diagnostic, max_message_rows);
16629
16630 Arc::new(move |cx: &mut BlockContext| {
16631 let group_id: SharedString = cx.block_id.to_string().into();
16632
16633 let mut text_style = cx.window.text_style().clone();
16634 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16635 let theme_settings = ThemeSettings::get_global(cx);
16636 text_style.font_family = theme_settings.buffer_font.family.clone();
16637 text_style.font_style = theme_settings.buffer_font.style;
16638 text_style.font_features = theme_settings.buffer_font.features.clone();
16639 text_style.font_weight = theme_settings.buffer_font.weight;
16640
16641 let multi_line_diagnostic = diagnostic.message.contains('\n');
16642
16643 let buttons = |diagnostic: &Diagnostic| {
16644 if multi_line_diagnostic {
16645 v_flex()
16646 } else {
16647 h_flex()
16648 }
16649 .when(allow_closing, |div| {
16650 div.children(diagnostic.is_primary.then(|| {
16651 IconButton::new("close-block", IconName::XCircle)
16652 .icon_color(Color::Muted)
16653 .size(ButtonSize::Compact)
16654 .style(ButtonStyle::Transparent)
16655 .visible_on_hover(group_id.clone())
16656 .on_click(move |_click, window, cx| {
16657 window.dispatch_action(Box::new(Cancel), cx)
16658 })
16659 .tooltip(|window, cx| {
16660 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16661 })
16662 }))
16663 })
16664 .child(
16665 IconButton::new("copy-block", IconName::Copy)
16666 .icon_color(Color::Muted)
16667 .size(ButtonSize::Compact)
16668 .style(ButtonStyle::Transparent)
16669 .visible_on_hover(group_id.clone())
16670 .on_click({
16671 let message = diagnostic.message.clone();
16672 move |_click, _, cx| {
16673 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16674 }
16675 })
16676 .tooltip(Tooltip::text("Copy diagnostic message")),
16677 )
16678 };
16679
16680 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16681 AvailableSpace::min_size(),
16682 cx.window,
16683 cx.app,
16684 );
16685
16686 h_flex()
16687 .id(cx.block_id)
16688 .group(group_id.clone())
16689 .relative()
16690 .size_full()
16691 .block_mouse_down()
16692 .pl(cx.gutter_dimensions.width)
16693 .w(cx.max_width - cx.gutter_dimensions.full_width())
16694 .child(
16695 div()
16696 .flex()
16697 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16698 .flex_shrink(),
16699 )
16700 .child(buttons(&diagnostic))
16701 .child(div().flex().flex_shrink_0().child(
16702 StyledText::new(text_without_backticks.clone()).with_highlights(
16703 &text_style,
16704 code_ranges.iter().map(|range| {
16705 (
16706 range.clone(),
16707 HighlightStyle {
16708 font_weight: Some(FontWeight::BOLD),
16709 ..Default::default()
16710 },
16711 )
16712 }),
16713 ),
16714 ))
16715 .into_any_element()
16716 })
16717}
16718
16719fn inline_completion_edit_text(
16720 current_snapshot: &BufferSnapshot,
16721 edits: &[(Range<Anchor>, String)],
16722 edit_preview: &EditPreview,
16723 include_deletions: bool,
16724 cx: &App,
16725) -> HighlightedText {
16726 let edits = edits
16727 .iter()
16728 .map(|(anchor, text)| {
16729 (
16730 anchor.start.text_anchor..anchor.end.text_anchor,
16731 text.clone(),
16732 )
16733 })
16734 .collect::<Vec<_>>();
16735
16736 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16737}
16738
16739pub fn highlight_diagnostic_message(
16740 diagnostic: &Diagnostic,
16741 mut max_message_rows: Option<u8>,
16742) -> (SharedString, Vec<Range<usize>>) {
16743 let mut text_without_backticks = String::new();
16744 let mut code_ranges = Vec::new();
16745
16746 if let Some(source) = &diagnostic.source {
16747 text_without_backticks.push_str(source);
16748 code_ranges.push(0..source.len());
16749 text_without_backticks.push_str(": ");
16750 }
16751
16752 let mut prev_offset = 0;
16753 let mut in_code_block = false;
16754 let has_row_limit = max_message_rows.is_some();
16755 let mut newline_indices = diagnostic
16756 .message
16757 .match_indices('\n')
16758 .filter(|_| has_row_limit)
16759 .map(|(ix, _)| ix)
16760 .fuse()
16761 .peekable();
16762
16763 for (quote_ix, _) in diagnostic
16764 .message
16765 .match_indices('`')
16766 .chain([(diagnostic.message.len(), "")])
16767 {
16768 let mut first_newline_ix = None;
16769 let mut last_newline_ix = None;
16770 while let Some(newline_ix) = newline_indices.peek() {
16771 if *newline_ix < quote_ix {
16772 if first_newline_ix.is_none() {
16773 first_newline_ix = Some(*newline_ix);
16774 }
16775 last_newline_ix = Some(*newline_ix);
16776
16777 if let Some(rows_left) = &mut max_message_rows {
16778 if *rows_left == 0 {
16779 break;
16780 } else {
16781 *rows_left -= 1;
16782 }
16783 }
16784 let _ = newline_indices.next();
16785 } else {
16786 break;
16787 }
16788 }
16789 let prev_len = text_without_backticks.len();
16790 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16791 text_without_backticks.push_str(new_text);
16792 if in_code_block {
16793 code_ranges.push(prev_len..text_without_backticks.len());
16794 }
16795 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16796 in_code_block = !in_code_block;
16797 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16798 text_without_backticks.push_str("...");
16799 break;
16800 }
16801 }
16802
16803 (text_without_backticks.into(), code_ranges)
16804}
16805
16806fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16807 match severity {
16808 DiagnosticSeverity::ERROR => colors.error,
16809 DiagnosticSeverity::WARNING => colors.warning,
16810 DiagnosticSeverity::INFORMATION => colors.info,
16811 DiagnosticSeverity::HINT => colors.info,
16812 _ => colors.ignored,
16813 }
16814}
16815
16816pub fn styled_runs_for_code_label<'a>(
16817 label: &'a CodeLabel,
16818 syntax_theme: &'a theme::SyntaxTheme,
16819) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16820 let fade_out = HighlightStyle {
16821 fade_out: Some(0.35),
16822 ..Default::default()
16823 };
16824
16825 let mut prev_end = label.filter_range.end;
16826 label
16827 .runs
16828 .iter()
16829 .enumerate()
16830 .flat_map(move |(ix, (range, highlight_id))| {
16831 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16832 style
16833 } else {
16834 return Default::default();
16835 };
16836 let mut muted_style = style;
16837 muted_style.highlight(fade_out);
16838
16839 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16840 if range.start >= label.filter_range.end {
16841 if range.start > prev_end {
16842 runs.push((prev_end..range.start, fade_out));
16843 }
16844 runs.push((range.clone(), muted_style));
16845 } else if range.end <= label.filter_range.end {
16846 runs.push((range.clone(), style));
16847 } else {
16848 runs.push((range.start..label.filter_range.end, style));
16849 runs.push((label.filter_range.end..range.end, muted_style));
16850 }
16851 prev_end = cmp::max(prev_end, range.end);
16852
16853 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16854 runs.push((prev_end..label.text.len(), fade_out));
16855 }
16856
16857 runs
16858 })
16859}
16860
16861pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16862 let mut prev_index = 0;
16863 let mut prev_codepoint: Option<char> = None;
16864 text.char_indices()
16865 .chain([(text.len(), '\0')])
16866 .filter_map(move |(index, codepoint)| {
16867 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16868 let is_boundary = index == text.len()
16869 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16870 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16871 if is_boundary {
16872 let chunk = &text[prev_index..index];
16873 prev_index = index;
16874 Some(chunk)
16875 } else {
16876 None
16877 }
16878 })
16879}
16880
16881pub trait RangeToAnchorExt: Sized {
16882 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16883
16884 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16885 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16886 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16887 }
16888}
16889
16890impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16891 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16892 let start_offset = self.start.to_offset(snapshot);
16893 let end_offset = self.end.to_offset(snapshot);
16894 if start_offset == end_offset {
16895 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16896 } else {
16897 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16898 }
16899 }
16900}
16901
16902pub trait RowExt {
16903 fn as_f32(&self) -> f32;
16904
16905 fn next_row(&self) -> Self;
16906
16907 fn previous_row(&self) -> Self;
16908
16909 fn minus(&self, other: Self) -> u32;
16910}
16911
16912impl RowExt for DisplayRow {
16913 fn as_f32(&self) -> f32 {
16914 self.0 as f32
16915 }
16916
16917 fn next_row(&self) -> Self {
16918 Self(self.0 + 1)
16919 }
16920
16921 fn previous_row(&self) -> Self {
16922 Self(self.0.saturating_sub(1))
16923 }
16924
16925 fn minus(&self, other: Self) -> u32 {
16926 self.0 - other.0
16927 }
16928}
16929
16930impl RowExt for MultiBufferRow {
16931 fn as_f32(&self) -> f32 {
16932 self.0 as f32
16933 }
16934
16935 fn next_row(&self) -> Self {
16936 Self(self.0 + 1)
16937 }
16938
16939 fn previous_row(&self) -> Self {
16940 Self(self.0.saturating_sub(1))
16941 }
16942
16943 fn minus(&self, other: Self) -> u32 {
16944 self.0 - other.0
16945 }
16946}
16947
16948trait RowRangeExt {
16949 type Row;
16950
16951 fn len(&self) -> usize;
16952
16953 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16954}
16955
16956impl RowRangeExt for Range<MultiBufferRow> {
16957 type Row = MultiBufferRow;
16958
16959 fn len(&self) -> usize {
16960 (self.end.0 - self.start.0) as usize
16961 }
16962
16963 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16964 (self.start.0..self.end.0).map(MultiBufferRow)
16965 }
16966}
16967
16968impl RowRangeExt for Range<DisplayRow> {
16969 type Row = DisplayRow;
16970
16971 fn len(&self) -> usize {
16972 (self.end.0 - self.start.0) as usize
16973 }
16974
16975 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16976 (self.start.0..self.end.0).map(DisplayRow)
16977 }
16978}
16979
16980/// If select range has more than one line, we
16981/// just point the cursor to range.start.
16982fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16983 if range.start.row == range.end.row {
16984 range
16985 } else {
16986 range.start..range.start
16987 }
16988}
16989pub struct KillRing(ClipboardItem);
16990impl Global for KillRing {}
16991
16992const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16993
16994fn all_edits_insertions_or_deletions(
16995 edits: &Vec<(Range<Anchor>, String)>,
16996 snapshot: &MultiBufferSnapshot,
16997) -> bool {
16998 let mut all_insertions = true;
16999 let mut all_deletions = true;
17000
17001 for (range, new_text) in edits.iter() {
17002 let range_is_empty = range.to_offset(&snapshot).is_empty();
17003 let text_is_empty = new_text.is_empty();
17004
17005 if range_is_empty != text_is_empty {
17006 if range_is_empty {
17007 all_deletions = false;
17008 } else {
17009 all_insertions = false;
17010 }
17011 } else {
17012 return false;
17013 }
17014
17015 if !all_insertions && !all_deletions {
17016 return false;
17017 }
17018 }
17019 all_insertions || all_deletions
17020}