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 mut to_unfold = Vec::new();
9126 let mut new_selection_ranges = Vec::new();
9127 {
9128 let selections = self.selections.all::<Point>(cx);
9129 let buffer = self.buffer.read(cx).read(cx);
9130 for selection in selections {
9131 for row in selection.start.row..selection.end.row {
9132 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9133 new_selection_ranges.push(cursor..cursor);
9134 }
9135 new_selection_ranges.push(selection.end..selection.end);
9136 to_unfold.push(selection.start..selection.end);
9137 }
9138 }
9139 self.unfold_ranges(&to_unfold, true, true, cx);
9140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9141 s.select_ranges(new_selection_ranges);
9142 });
9143 }
9144
9145 pub fn add_selection_above(
9146 &mut self,
9147 _: &AddSelectionAbove,
9148 window: &mut Window,
9149 cx: &mut Context<Self>,
9150 ) {
9151 self.add_selection(true, window, cx);
9152 }
9153
9154 pub fn add_selection_below(
9155 &mut self,
9156 _: &AddSelectionBelow,
9157 window: &mut Window,
9158 cx: &mut Context<Self>,
9159 ) {
9160 self.add_selection(false, window, cx);
9161 }
9162
9163 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9164 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9165 let mut selections = self.selections.all::<Point>(cx);
9166 let text_layout_details = self.text_layout_details(window);
9167 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9168 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9169 let range = oldest_selection.display_range(&display_map).sorted();
9170
9171 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9172 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9173 let positions = start_x.min(end_x)..start_x.max(end_x);
9174
9175 selections.clear();
9176 let mut stack = Vec::new();
9177 for row in range.start.row().0..=range.end.row().0 {
9178 if let Some(selection) = self.selections.build_columnar_selection(
9179 &display_map,
9180 DisplayRow(row),
9181 &positions,
9182 oldest_selection.reversed,
9183 &text_layout_details,
9184 ) {
9185 stack.push(selection.id);
9186 selections.push(selection);
9187 }
9188 }
9189
9190 if above {
9191 stack.reverse();
9192 }
9193
9194 AddSelectionsState { above, stack }
9195 });
9196
9197 let last_added_selection = *state.stack.last().unwrap();
9198 let mut new_selections = Vec::new();
9199 if above == state.above {
9200 let end_row = if above {
9201 DisplayRow(0)
9202 } else {
9203 display_map.max_point().row()
9204 };
9205
9206 'outer: for selection in selections {
9207 if selection.id == last_added_selection {
9208 let range = selection.display_range(&display_map).sorted();
9209 debug_assert_eq!(range.start.row(), range.end.row());
9210 let mut row = range.start.row();
9211 let positions =
9212 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9213 px(start)..px(end)
9214 } else {
9215 let start_x =
9216 display_map.x_for_display_point(range.start, &text_layout_details);
9217 let end_x =
9218 display_map.x_for_display_point(range.end, &text_layout_details);
9219 start_x.min(end_x)..start_x.max(end_x)
9220 };
9221
9222 while row != end_row {
9223 if above {
9224 row.0 -= 1;
9225 } else {
9226 row.0 += 1;
9227 }
9228
9229 if let Some(new_selection) = self.selections.build_columnar_selection(
9230 &display_map,
9231 row,
9232 &positions,
9233 selection.reversed,
9234 &text_layout_details,
9235 ) {
9236 state.stack.push(new_selection.id);
9237 if above {
9238 new_selections.push(new_selection);
9239 new_selections.push(selection);
9240 } else {
9241 new_selections.push(selection);
9242 new_selections.push(new_selection);
9243 }
9244
9245 continue 'outer;
9246 }
9247 }
9248 }
9249
9250 new_selections.push(selection);
9251 }
9252 } else {
9253 new_selections = selections;
9254 new_selections.retain(|s| s.id != last_added_selection);
9255 state.stack.pop();
9256 }
9257
9258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9259 s.select(new_selections);
9260 });
9261 if state.stack.len() > 1 {
9262 self.add_selections_state = Some(state);
9263 }
9264 }
9265
9266 pub fn select_next_match_internal(
9267 &mut self,
9268 display_map: &DisplaySnapshot,
9269 replace_newest: bool,
9270 autoscroll: Option<Autoscroll>,
9271 window: &mut Window,
9272 cx: &mut Context<Self>,
9273 ) -> Result<()> {
9274 fn select_next_match_ranges(
9275 this: &mut Editor,
9276 range: Range<usize>,
9277 replace_newest: bool,
9278 auto_scroll: Option<Autoscroll>,
9279 window: &mut Window,
9280 cx: &mut Context<Editor>,
9281 ) {
9282 this.unfold_ranges(&[range.clone()], false, true, cx);
9283 this.change_selections(auto_scroll, window, cx, |s| {
9284 if replace_newest {
9285 s.delete(s.newest_anchor().id);
9286 }
9287 s.insert_range(range.clone());
9288 });
9289 }
9290
9291 let buffer = &display_map.buffer_snapshot;
9292 let mut selections = self.selections.all::<usize>(cx);
9293 if let Some(mut select_next_state) = self.select_next_state.take() {
9294 let query = &select_next_state.query;
9295 if !select_next_state.done {
9296 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9297 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9298 let mut next_selected_range = None;
9299
9300 let bytes_after_last_selection =
9301 buffer.bytes_in_range(last_selection.end..buffer.len());
9302 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9303 let query_matches = query
9304 .stream_find_iter(bytes_after_last_selection)
9305 .map(|result| (last_selection.end, result))
9306 .chain(
9307 query
9308 .stream_find_iter(bytes_before_first_selection)
9309 .map(|result| (0, result)),
9310 );
9311
9312 for (start_offset, query_match) in query_matches {
9313 let query_match = query_match.unwrap(); // can only fail due to I/O
9314 let offset_range =
9315 start_offset + query_match.start()..start_offset + query_match.end();
9316 let display_range = offset_range.start.to_display_point(display_map)
9317 ..offset_range.end.to_display_point(display_map);
9318
9319 if !select_next_state.wordwise
9320 || (!movement::is_inside_word(display_map, display_range.start)
9321 && !movement::is_inside_word(display_map, display_range.end))
9322 {
9323 // TODO: This is n^2, because we might check all the selections
9324 if !selections
9325 .iter()
9326 .any(|selection| selection.range().overlaps(&offset_range))
9327 {
9328 next_selected_range = Some(offset_range);
9329 break;
9330 }
9331 }
9332 }
9333
9334 if let Some(next_selected_range) = next_selected_range {
9335 select_next_match_ranges(
9336 self,
9337 next_selected_range,
9338 replace_newest,
9339 autoscroll,
9340 window,
9341 cx,
9342 );
9343 } else {
9344 select_next_state.done = true;
9345 }
9346 }
9347
9348 self.select_next_state = Some(select_next_state);
9349 } else {
9350 let mut only_carets = true;
9351 let mut same_text_selected = true;
9352 let mut selected_text = None;
9353
9354 let mut selections_iter = selections.iter().peekable();
9355 while let Some(selection) = selections_iter.next() {
9356 if selection.start != selection.end {
9357 only_carets = false;
9358 }
9359
9360 if same_text_selected {
9361 if selected_text.is_none() {
9362 selected_text =
9363 Some(buffer.text_for_range(selection.range()).collect::<String>());
9364 }
9365
9366 if let Some(next_selection) = selections_iter.peek() {
9367 if next_selection.range().len() == selection.range().len() {
9368 let next_selected_text = buffer
9369 .text_for_range(next_selection.range())
9370 .collect::<String>();
9371 if Some(next_selected_text) != selected_text {
9372 same_text_selected = false;
9373 selected_text = None;
9374 }
9375 } else {
9376 same_text_selected = false;
9377 selected_text = None;
9378 }
9379 }
9380 }
9381 }
9382
9383 if only_carets {
9384 for selection in &mut selections {
9385 let word_range = movement::surrounding_word(
9386 display_map,
9387 selection.start.to_display_point(display_map),
9388 );
9389 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9390 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9391 selection.goal = SelectionGoal::None;
9392 selection.reversed = false;
9393 select_next_match_ranges(
9394 self,
9395 selection.start..selection.end,
9396 replace_newest,
9397 autoscroll,
9398 window,
9399 cx,
9400 );
9401 }
9402
9403 if selections.len() == 1 {
9404 let selection = selections
9405 .last()
9406 .expect("ensured that there's only one selection");
9407 let query = buffer
9408 .text_for_range(selection.start..selection.end)
9409 .collect::<String>();
9410 let is_empty = query.is_empty();
9411 let select_state = SelectNextState {
9412 query: AhoCorasick::new(&[query])?,
9413 wordwise: true,
9414 done: is_empty,
9415 };
9416 self.select_next_state = Some(select_state);
9417 } else {
9418 self.select_next_state = None;
9419 }
9420 } else if let Some(selected_text) = selected_text {
9421 self.select_next_state = Some(SelectNextState {
9422 query: AhoCorasick::new(&[selected_text])?,
9423 wordwise: false,
9424 done: false,
9425 });
9426 self.select_next_match_internal(
9427 display_map,
9428 replace_newest,
9429 autoscroll,
9430 window,
9431 cx,
9432 )?;
9433 }
9434 }
9435 Ok(())
9436 }
9437
9438 pub fn select_all_matches(
9439 &mut self,
9440 _action: &SelectAllMatches,
9441 window: &mut Window,
9442 cx: &mut Context<Self>,
9443 ) -> Result<()> {
9444 self.push_to_selection_history();
9445 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9446
9447 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9448 let Some(select_next_state) = self.select_next_state.as_mut() else {
9449 return Ok(());
9450 };
9451 if select_next_state.done {
9452 return Ok(());
9453 }
9454
9455 let mut new_selections = self.selections.all::<usize>(cx);
9456
9457 let buffer = &display_map.buffer_snapshot;
9458 let query_matches = select_next_state
9459 .query
9460 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9461
9462 for query_match in query_matches {
9463 let query_match = query_match.unwrap(); // can only fail due to I/O
9464 let offset_range = query_match.start()..query_match.end();
9465 let display_range = offset_range.start.to_display_point(&display_map)
9466 ..offset_range.end.to_display_point(&display_map);
9467
9468 if !select_next_state.wordwise
9469 || (!movement::is_inside_word(&display_map, display_range.start)
9470 && !movement::is_inside_word(&display_map, display_range.end))
9471 {
9472 self.selections.change_with(cx, |selections| {
9473 new_selections.push(Selection {
9474 id: selections.new_selection_id(),
9475 start: offset_range.start,
9476 end: offset_range.end,
9477 reversed: false,
9478 goal: SelectionGoal::None,
9479 });
9480 });
9481 }
9482 }
9483
9484 new_selections.sort_by_key(|selection| selection.start);
9485 let mut ix = 0;
9486 while ix + 1 < new_selections.len() {
9487 let current_selection = &new_selections[ix];
9488 let next_selection = &new_selections[ix + 1];
9489 if current_selection.range().overlaps(&next_selection.range()) {
9490 if current_selection.id < next_selection.id {
9491 new_selections.remove(ix + 1);
9492 } else {
9493 new_selections.remove(ix);
9494 }
9495 } else {
9496 ix += 1;
9497 }
9498 }
9499
9500 let reversed = self.selections.oldest::<usize>(cx).reversed;
9501
9502 for selection in new_selections.iter_mut() {
9503 selection.reversed = reversed;
9504 }
9505
9506 select_next_state.done = true;
9507 self.unfold_ranges(
9508 &new_selections
9509 .iter()
9510 .map(|selection| selection.range())
9511 .collect::<Vec<_>>(),
9512 false,
9513 false,
9514 cx,
9515 );
9516 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9517 selections.select(new_selections)
9518 });
9519
9520 Ok(())
9521 }
9522
9523 pub fn select_next(
9524 &mut self,
9525 action: &SelectNext,
9526 window: &mut Window,
9527 cx: &mut Context<Self>,
9528 ) -> Result<()> {
9529 self.push_to_selection_history();
9530 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9531 self.select_next_match_internal(
9532 &display_map,
9533 action.replace_newest,
9534 Some(Autoscroll::newest()),
9535 window,
9536 cx,
9537 )?;
9538 Ok(())
9539 }
9540
9541 pub fn select_previous(
9542 &mut self,
9543 action: &SelectPrevious,
9544 window: &mut Window,
9545 cx: &mut Context<Self>,
9546 ) -> Result<()> {
9547 self.push_to_selection_history();
9548 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9549 let buffer = &display_map.buffer_snapshot;
9550 let mut selections = self.selections.all::<usize>(cx);
9551 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9552 let query = &select_prev_state.query;
9553 if !select_prev_state.done {
9554 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9555 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9556 let mut next_selected_range = None;
9557 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9558 let bytes_before_last_selection =
9559 buffer.reversed_bytes_in_range(0..last_selection.start);
9560 let bytes_after_first_selection =
9561 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9562 let query_matches = query
9563 .stream_find_iter(bytes_before_last_selection)
9564 .map(|result| (last_selection.start, result))
9565 .chain(
9566 query
9567 .stream_find_iter(bytes_after_first_selection)
9568 .map(|result| (buffer.len(), result)),
9569 );
9570 for (end_offset, query_match) in query_matches {
9571 let query_match = query_match.unwrap(); // can only fail due to I/O
9572 let offset_range =
9573 end_offset - query_match.end()..end_offset - query_match.start();
9574 let display_range = offset_range.start.to_display_point(&display_map)
9575 ..offset_range.end.to_display_point(&display_map);
9576
9577 if !select_prev_state.wordwise
9578 || (!movement::is_inside_word(&display_map, display_range.start)
9579 && !movement::is_inside_word(&display_map, display_range.end))
9580 {
9581 next_selected_range = Some(offset_range);
9582 break;
9583 }
9584 }
9585
9586 if let Some(next_selected_range) = next_selected_range {
9587 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9588 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9589 if action.replace_newest {
9590 s.delete(s.newest_anchor().id);
9591 }
9592 s.insert_range(next_selected_range);
9593 });
9594 } else {
9595 select_prev_state.done = true;
9596 }
9597 }
9598
9599 self.select_prev_state = Some(select_prev_state);
9600 } else {
9601 let mut only_carets = true;
9602 let mut same_text_selected = true;
9603 let mut selected_text = None;
9604
9605 let mut selections_iter = selections.iter().peekable();
9606 while let Some(selection) = selections_iter.next() {
9607 if selection.start != selection.end {
9608 only_carets = false;
9609 }
9610
9611 if same_text_selected {
9612 if selected_text.is_none() {
9613 selected_text =
9614 Some(buffer.text_for_range(selection.range()).collect::<String>());
9615 }
9616
9617 if let Some(next_selection) = selections_iter.peek() {
9618 if next_selection.range().len() == selection.range().len() {
9619 let next_selected_text = buffer
9620 .text_for_range(next_selection.range())
9621 .collect::<String>();
9622 if Some(next_selected_text) != selected_text {
9623 same_text_selected = false;
9624 selected_text = None;
9625 }
9626 } else {
9627 same_text_selected = false;
9628 selected_text = None;
9629 }
9630 }
9631 }
9632 }
9633
9634 if only_carets {
9635 for selection in &mut selections {
9636 let word_range = movement::surrounding_word(
9637 &display_map,
9638 selection.start.to_display_point(&display_map),
9639 );
9640 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9641 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9642 selection.goal = SelectionGoal::None;
9643 selection.reversed = false;
9644 }
9645 if selections.len() == 1 {
9646 let selection = selections
9647 .last()
9648 .expect("ensured that there's only one selection");
9649 let query = buffer
9650 .text_for_range(selection.start..selection.end)
9651 .collect::<String>();
9652 let is_empty = query.is_empty();
9653 let select_state = SelectNextState {
9654 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9655 wordwise: true,
9656 done: is_empty,
9657 };
9658 self.select_prev_state = Some(select_state);
9659 } else {
9660 self.select_prev_state = None;
9661 }
9662
9663 self.unfold_ranges(
9664 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9665 false,
9666 true,
9667 cx,
9668 );
9669 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9670 s.select(selections);
9671 });
9672 } else if let Some(selected_text) = selected_text {
9673 self.select_prev_state = Some(SelectNextState {
9674 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9675 wordwise: false,
9676 done: false,
9677 });
9678 self.select_previous(action, window, cx)?;
9679 }
9680 }
9681 Ok(())
9682 }
9683
9684 pub fn toggle_comments(
9685 &mut self,
9686 action: &ToggleComments,
9687 window: &mut Window,
9688 cx: &mut Context<Self>,
9689 ) {
9690 if self.read_only(cx) {
9691 return;
9692 }
9693 let text_layout_details = &self.text_layout_details(window);
9694 self.transact(window, cx, |this, window, cx| {
9695 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9696 let mut edits = Vec::new();
9697 let mut selection_edit_ranges = Vec::new();
9698 let mut last_toggled_row = None;
9699 let snapshot = this.buffer.read(cx).read(cx);
9700 let empty_str: Arc<str> = Arc::default();
9701 let mut suffixes_inserted = Vec::new();
9702 let ignore_indent = action.ignore_indent;
9703
9704 fn comment_prefix_range(
9705 snapshot: &MultiBufferSnapshot,
9706 row: MultiBufferRow,
9707 comment_prefix: &str,
9708 comment_prefix_whitespace: &str,
9709 ignore_indent: bool,
9710 ) -> Range<Point> {
9711 let indent_size = if ignore_indent {
9712 0
9713 } else {
9714 snapshot.indent_size_for_line(row).len
9715 };
9716
9717 let start = Point::new(row.0, indent_size);
9718
9719 let mut line_bytes = snapshot
9720 .bytes_in_range(start..snapshot.max_point())
9721 .flatten()
9722 .copied();
9723
9724 // If this line currently begins with the line comment prefix, then record
9725 // the range containing the prefix.
9726 if line_bytes
9727 .by_ref()
9728 .take(comment_prefix.len())
9729 .eq(comment_prefix.bytes())
9730 {
9731 // Include any whitespace that matches the comment prefix.
9732 let matching_whitespace_len = line_bytes
9733 .zip(comment_prefix_whitespace.bytes())
9734 .take_while(|(a, b)| a == b)
9735 .count() as u32;
9736 let end = Point::new(
9737 start.row,
9738 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9739 );
9740 start..end
9741 } else {
9742 start..start
9743 }
9744 }
9745
9746 fn comment_suffix_range(
9747 snapshot: &MultiBufferSnapshot,
9748 row: MultiBufferRow,
9749 comment_suffix: &str,
9750 comment_suffix_has_leading_space: bool,
9751 ) -> Range<Point> {
9752 let end = Point::new(row.0, snapshot.line_len(row));
9753 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9754
9755 let mut line_end_bytes = snapshot
9756 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9757 .flatten()
9758 .copied();
9759
9760 let leading_space_len = if suffix_start_column > 0
9761 && line_end_bytes.next() == Some(b' ')
9762 && comment_suffix_has_leading_space
9763 {
9764 1
9765 } else {
9766 0
9767 };
9768
9769 // If this line currently begins with the line comment prefix, then record
9770 // the range containing the prefix.
9771 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9772 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9773 start..end
9774 } else {
9775 end..end
9776 }
9777 }
9778
9779 // TODO: Handle selections that cross excerpts
9780 for selection in &mut selections {
9781 let start_column = snapshot
9782 .indent_size_for_line(MultiBufferRow(selection.start.row))
9783 .len;
9784 let language = if let Some(language) =
9785 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9786 {
9787 language
9788 } else {
9789 continue;
9790 };
9791
9792 selection_edit_ranges.clear();
9793
9794 // If multiple selections contain a given row, avoid processing that
9795 // row more than once.
9796 let mut start_row = MultiBufferRow(selection.start.row);
9797 if last_toggled_row == Some(start_row) {
9798 start_row = start_row.next_row();
9799 }
9800 let end_row =
9801 if selection.end.row > selection.start.row && selection.end.column == 0 {
9802 MultiBufferRow(selection.end.row - 1)
9803 } else {
9804 MultiBufferRow(selection.end.row)
9805 };
9806 last_toggled_row = Some(end_row);
9807
9808 if start_row > end_row {
9809 continue;
9810 }
9811
9812 // If the language has line comments, toggle those.
9813 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9814
9815 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9816 if ignore_indent {
9817 full_comment_prefixes = full_comment_prefixes
9818 .into_iter()
9819 .map(|s| Arc::from(s.trim_end()))
9820 .collect();
9821 }
9822
9823 if !full_comment_prefixes.is_empty() {
9824 let first_prefix = full_comment_prefixes
9825 .first()
9826 .expect("prefixes is non-empty");
9827 let prefix_trimmed_lengths = full_comment_prefixes
9828 .iter()
9829 .map(|p| p.trim_end_matches(' ').len())
9830 .collect::<SmallVec<[usize; 4]>>();
9831
9832 let mut all_selection_lines_are_comments = true;
9833
9834 for row in start_row.0..=end_row.0 {
9835 let row = MultiBufferRow(row);
9836 if start_row < end_row && snapshot.is_line_blank(row) {
9837 continue;
9838 }
9839
9840 let prefix_range = full_comment_prefixes
9841 .iter()
9842 .zip(prefix_trimmed_lengths.iter().copied())
9843 .map(|(prefix, trimmed_prefix_len)| {
9844 comment_prefix_range(
9845 snapshot.deref(),
9846 row,
9847 &prefix[..trimmed_prefix_len],
9848 &prefix[trimmed_prefix_len..],
9849 ignore_indent,
9850 )
9851 })
9852 .max_by_key(|range| range.end.column - range.start.column)
9853 .expect("prefixes is non-empty");
9854
9855 if prefix_range.is_empty() {
9856 all_selection_lines_are_comments = false;
9857 }
9858
9859 selection_edit_ranges.push(prefix_range);
9860 }
9861
9862 if all_selection_lines_are_comments {
9863 edits.extend(
9864 selection_edit_ranges
9865 .iter()
9866 .cloned()
9867 .map(|range| (range, empty_str.clone())),
9868 );
9869 } else {
9870 let min_column = selection_edit_ranges
9871 .iter()
9872 .map(|range| range.start.column)
9873 .min()
9874 .unwrap_or(0);
9875 edits.extend(selection_edit_ranges.iter().map(|range| {
9876 let position = Point::new(range.start.row, min_column);
9877 (position..position, first_prefix.clone())
9878 }));
9879 }
9880 } else if let Some((full_comment_prefix, comment_suffix)) =
9881 language.block_comment_delimiters()
9882 {
9883 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9884 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9885 let prefix_range = comment_prefix_range(
9886 snapshot.deref(),
9887 start_row,
9888 comment_prefix,
9889 comment_prefix_whitespace,
9890 ignore_indent,
9891 );
9892 let suffix_range = comment_suffix_range(
9893 snapshot.deref(),
9894 end_row,
9895 comment_suffix.trim_start_matches(' '),
9896 comment_suffix.starts_with(' '),
9897 );
9898
9899 if prefix_range.is_empty() || suffix_range.is_empty() {
9900 edits.push((
9901 prefix_range.start..prefix_range.start,
9902 full_comment_prefix.clone(),
9903 ));
9904 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9905 suffixes_inserted.push((end_row, comment_suffix.len()));
9906 } else {
9907 edits.push((prefix_range, empty_str.clone()));
9908 edits.push((suffix_range, empty_str.clone()));
9909 }
9910 } else {
9911 continue;
9912 }
9913 }
9914
9915 drop(snapshot);
9916 this.buffer.update(cx, |buffer, cx| {
9917 buffer.edit(edits, None, cx);
9918 });
9919
9920 // Adjust selections so that they end before any comment suffixes that
9921 // were inserted.
9922 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9923 let mut selections = this.selections.all::<Point>(cx);
9924 let snapshot = this.buffer.read(cx).read(cx);
9925 for selection in &mut selections {
9926 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9927 match row.cmp(&MultiBufferRow(selection.end.row)) {
9928 Ordering::Less => {
9929 suffixes_inserted.next();
9930 continue;
9931 }
9932 Ordering::Greater => break,
9933 Ordering::Equal => {
9934 if selection.end.column == snapshot.line_len(row) {
9935 if selection.is_empty() {
9936 selection.start.column -= suffix_len as u32;
9937 }
9938 selection.end.column -= suffix_len as u32;
9939 }
9940 break;
9941 }
9942 }
9943 }
9944 }
9945
9946 drop(snapshot);
9947 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9948 s.select(selections)
9949 });
9950
9951 let selections = this.selections.all::<Point>(cx);
9952 let selections_on_single_row = selections.windows(2).all(|selections| {
9953 selections[0].start.row == selections[1].start.row
9954 && selections[0].end.row == selections[1].end.row
9955 && selections[0].start.row == selections[0].end.row
9956 });
9957 let selections_selecting = selections
9958 .iter()
9959 .any(|selection| selection.start != selection.end);
9960 let advance_downwards = action.advance_downwards
9961 && selections_on_single_row
9962 && !selections_selecting
9963 && !matches!(this.mode, EditorMode::SingleLine { .. });
9964
9965 if advance_downwards {
9966 let snapshot = this.buffer.read(cx).snapshot(cx);
9967
9968 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9969 s.move_cursors_with(|display_snapshot, display_point, _| {
9970 let mut point = display_point.to_point(display_snapshot);
9971 point.row += 1;
9972 point = snapshot.clip_point(point, Bias::Left);
9973 let display_point = point.to_display_point(display_snapshot);
9974 let goal = SelectionGoal::HorizontalPosition(
9975 display_snapshot
9976 .x_for_display_point(display_point, text_layout_details)
9977 .into(),
9978 );
9979 (display_point, goal)
9980 })
9981 });
9982 }
9983 });
9984 }
9985
9986 pub fn select_enclosing_symbol(
9987 &mut self,
9988 _: &SelectEnclosingSymbol,
9989 window: &mut Window,
9990 cx: &mut Context<Self>,
9991 ) {
9992 let buffer = self.buffer.read(cx).snapshot(cx);
9993 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9994
9995 fn update_selection(
9996 selection: &Selection<usize>,
9997 buffer_snap: &MultiBufferSnapshot,
9998 ) -> Option<Selection<usize>> {
9999 let cursor = selection.head();
10000 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10001 for symbol in symbols.iter().rev() {
10002 let start = symbol.range.start.to_offset(buffer_snap);
10003 let end = symbol.range.end.to_offset(buffer_snap);
10004 let new_range = start..end;
10005 if start < selection.start || end > selection.end {
10006 return Some(Selection {
10007 id: selection.id,
10008 start: new_range.start,
10009 end: new_range.end,
10010 goal: SelectionGoal::None,
10011 reversed: selection.reversed,
10012 });
10013 }
10014 }
10015 None
10016 }
10017
10018 let mut selected_larger_symbol = false;
10019 let new_selections = old_selections
10020 .iter()
10021 .map(|selection| match update_selection(selection, &buffer) {
10022 Some(new_selection) => {
10023 if new_selection.range() != selection.range() {
10024 selected_larger_symbol = true;
10025 }
10026 new_selection
10027 }
10028 None => selection.clone(),
10029 })
10030 .collect::<Vec<_>>();
10031
10032 if selected_larger_symbol {
10033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10034 s.select(new_selections);
10035 });
10036 }
10037 }
10038
10039 pub fn select_larger_syntax_node(
10040 &mut self,
10041 _: &SelectLargerSyntaxNode,
10042 window: &mut Window,
10043 cx: &mut Context<Self>,
10044 ) {
10045 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10046 let buffer = self.buffer.read(cx).snapshot(cx);
10047 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10048
10049 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10050 let mut selected_larger_node = false;
10051 let new_selections = old_selections
10052 .iter()
10053 .map(|selection| {
10054 let old_range = selection.start..selection.end;
10055 let mut new_range = old_range.clone();
10056 let mut new_node = None;
10057 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10058 {
10059 new_node = Some(node);
10060 new_range = containing_range;
10061 if !display_map.intersects_fold(new_range.start)
10062 && !display_map.intersects_fold(new_range.end)
10063 {
10064 break;
10065 }
10066 }
10067
10068 if let Some(node) = new_node {
10069 // Log the ancestor, to support using this action as a way to explore TreeSitter
10070 // nodes. Parent and grandparent are also logged because this operation will not
10071 // visit nodes that have the same range as their parent.
10072 log::info!("Node: {node:?}");
10073 let parent = node.parent();
10074 log::info!("Parent: {parent:?}");
10075 let grandparent = parent.and_then(|x| x.parent());
10076 log::info!("Grandparent: {grandparent:?}");
10077 }
10078
10079 selected_larger_node |= new_range != old_range;
10080 Selection {
10081 id: selection.id,
10082 start: new_range.start,
10083 end: new_range.end,
10084 goal: SelectionGoal::None,
10085 reversed: selection.reversed,
10086 }
10087 })
10088 .collect::<Vec<_>>();
10089
10090 if selected_larger_node {
10091 stack.push(old_selections);
10092 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10093 s.select(new_selections);
10094 });
10095 }
10096 self.select_larger_syntax_node_stack = stack;
10097 }
10098
10099 pub fn select_smaller_syntax_node(
10100 &mut self,
10101 _: &SelectSmallerSyntaxNode,
10102 window: &mut Window,
10103 cx: &mut Context<Self>,
10104 ) {
10105 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10106 if let Some(selections) = stack.pop() {
10107 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10108 s.select(selections.to_vec());
10109 });
10110 }
10111 self.select_larger_syntax_node_stack = stack;
10112 }
10113
10114 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10115 if !EditorSettings::get_global(cx).gutter.runnables {
10116 self.clear_tasks();
10117 return Task::ready(());
10118 }
10119 let project = self.project.as_ref().map(Entity::downgrade);
10120 cx.spawn_in(window, |this, mut cx| async move {
10121 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10122 let Some(project) = project.and_then(|p| p.upgrade()) else {
10123 return;
10124 };
10125 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10126 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10127 }) else {
10128 return;
10129 };
10130
10131 let hide_runnables = project
10132 .update(&mut cx, |project, cx| {
10133 // Do not display any test indicators in non-dev server remote projects.
10134 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10135 })
10136 .unwrap_or(true);
10137 if hide_runnables {
10138 return;
10139 }
10140 let new_rows =
10141 cx.background_executor()
10142 .spawn({
10143 let snapshot = display_snapshot.clone();
10144 async move {
10145 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10146 }
10147 })
10148 .await;
10149
10150 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10151 this.update(&mut cx, |this, _| {
10152 this.clear_tasks();
10153 for (key, value) in rows {
10154 this.insert_tasks(key, value);
10155 }
10156 })
10157 .ok();
10158 })
10159 }
10160 fn fetch_runnable_ranges(
10161 snapshot: &DisplaySnapshot,
10162 range: Range<Anchor>,
10163 ) -> Vec<language::RunnableRange> {
10164 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10165 }
10166
10167 fn runnable_rows(
10168 project: Entity<Project>,
10169 snapshot: DisplaySnapshot,
10170 runnable_ranges: Vec<RunnableRange>,
10171 mut cx: AsyncWindowContext,
10172 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10173 runnable_ranges
10174 .into_iter()
10175 .filter_map(|mut runnable| {
10176 let tasks = cx
10177 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10178 .ok()?;
10179 if tasks.is_empty() {
10180 return None;
10181 }
10182
10183 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10184
10185 let row = snapshot
10186 .buffer_snapshot
10187 .buffer_line_for_row(MultiBufferRow(point.row))?
10188 .1
10189 .start
10190 .row;
10191
10192 let context_range =
10193 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10194 Some((
10195 (runnable.buffer_id, row),
10196 RunnableTasks {
10197 templates: tasks,
10198 offset: MultiBufferOffset(runnable.run_range.start),
10199 context_range,
10200 column: point.column,
10201 extra_variables: runnable.extra_captures,
10202 },
10203 ))
10204 })
10205 .collect()
10206 }
10207
10208 fn templates_with_tags(
10209 project: &Entity<Project>,
10210 runnable: &mut Runnable,
10211 cx: &mut App,
10212 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10213 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10214 let (worktree_id, file) = project
10215 .buffer_for_id(runnable.buffer, cx)
10216 .and_then(|buffer| buffer.read(cx).file())
10217 .map(|file| (file.worktree_id(cx), file.clone()))
10218 .unzip();
10219
10220 (
10221 project.task_store().read(cx).task_inventory().cloned(),
10222 worktree_id,
10223 file,
10224 )
10225 });
10226
10227 let tags = mem::take(&mut runnable.tags);
10228 let mut tags: Vec<_> = tags
10229 .into_iter()
10230 .flat_map(|tag| {
10231 let tag = tag.0.clone();
10232 inventory
10233 .as_ref()
10234 .into_iter()
10235 .flat_map(|inventory| {
10236 inventory.read(cx).list_tasks(
10237 file.clone(),
10238 Some(runnable.language.clone()),
10239 worktree_id,
10240 cx,
10241 )
10242 })
10243 .filter(move |(_, template)| {
10244 template.tags.iter().any(|source_tag| source_tag == &tag)
10245 })
10246 })
10247 .sorted_by_key(|(kind, _)| kind.to_owned())
10248 .collect();
10249 if let Some((leading_tag_source, _)) = tags.first() {
10250 // Strongest source wins; if we have worktree tag binding, prefer that to
10251 // global and language bindings;
10252 // if we have a global binding, prefer that to language binding.
10253 let first_mismatch = tags
10254 .iter()
10255 .position(|(tag_source, _)| tag_source != leading_tag_source);
10256 if let Some(index) = first_mismatch {
10257 tags.truncate(index);
10258 }
10259 }
10260
10261 tags
10262 }
10263
10264 pub fn move_to_enclosing_bracket(
10265 &mut self,
10266 _: &MoveToEnclosingBracket,
10267 window: &mut Window,
10268 cx: &mut Context<Self>,
10269 ) {
10270 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10271 s.move_offsets_with(|snapshot, selection| {
10272 let Some(enclosing_bracket_ranges) =
10273 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10274 else {
10275 return;
10276 };
10277
10278 let mut best_length = usize::MAX;
10279 let mut best_inside = false;
10280 let mut best_in_bracket_range = false;
10281 let mut best_destination = None;
10282 for (open, close) in enclosing_bracket_ranges {
10283 let close = close.to_inclusive();
10284 let length = close.end() - open.start;
10285 let inside = selection.start >= open.end && selection.end <= *close.start();
10286 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10287 || close.contains(&selection.head());
10288
10289 // If best is next to a bracket and current isn't, skip
10290 if !in_bracket_range && best_in_bracket_range {
10291 continue;
10292 }
10293
10294 // Prefer smaller lengths unless best is inside and current isn't
10295 if length > best_length && (best_inside || !inside) {
10296 continue;
10297 }
10298
10299 best_length = length;
10300 best_inside = inside;
10301 best_in_bracket_range = in_bracket_range;
10302 best_destination = Some(
10303 if close.contains(&selection.start) && close.contains(&selection.end) {
10304 if inside {
10305 open.end
10306 } else {
10307 open.start
10308 }
10309 } else if inside {
10310 *close.start()
10311 } else {
10312 *close.end()
10313 },
10314 );
10315 }
10316
10317 if let Some(destination) = best_destination {
10318 selection.collapse_to(destination, SelectionGoal::None);
10319 }
10320 })
10321 });
10322 }
10323
10324 pub fn undo_selection(
10325 &mut self,
10326 _: &UndoSelection,
10327 window: &mut Window,
10328 cx: &mut Context<Self>,
10329 ) {
10330 self.end_selection(window, cx);
10331 self.selection_history.mode = SelectionHistoryMode::Undoing;
10332 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10333 self.change_selections(None, window, cx, |s| {
10334 s.select_anchors(entry.selections.to_vec())
10335 });
10336 self.select_next_state = entry.select_next_state;
10337 self.select_prev_state = entry.select_prev_state;
10338 self.add_selections_state = entry.add_selections_state;
10339 self.request_autoscroll(Autoscroll::newest(), cx);
10340 }
10341 self.selection_history.mode = SelectionHistoryMode::Normal;
10342 }
10343
10344 pub fn redo_selection(
10345 &mut self,
10346 _: &RedoSelection,
10347 window: &mut Window,
10348 cx: &mut Context<Self>,
10349 ) {
10350 self.end_selection(window, cx);
10351 self.selection_history.mode = SelectionHistoryMode::Redoing;
10352 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10353 self.change_selections(None, window, cx, |s| {
10354 s.select_anchors(entry.selections.to_vec())
10355 });
10356 self.select_next_state = entry.select_next_state;
10357 self.select_prev_state = entry.select_prev_state;
10358 self.add_selections_state = entry.add_selections_state;
10359 self.request_autoscroll(Autoscroll::newest(), cx);
10360 }
10361 self.selection_history.mode = SelectionHistoryMode::Normal;
10362 }
10363
10364 pub fn expand_excerpts(
10365 &mut self,
10366 action: &ExpandExcerpts,
10367 _: &mut Window,
10368 cx: &mut Context<Self>,
10369 ) {
10370 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10371 }
10372
10373 pub fn expand_excerpts_down(
10374 &mut self,
10375 action: &ExpandExcerptsDown,
10376 _: &mut Window,
10377 cx: &mut Context<Self>,
10378 ) {
10379 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10380 }
10381
10382 pub fn expand_excerpts_up(
10383 &mut self,
10384 action: &ExpandExcerptsUp,
10385 _: &mut Window,
10386 cx: &mut Context<Self>,
10387 ) {
10388 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10389 }
10390
10391 pub fn expand_excerpts_for_direction(
10392 &mut self,
10393 lines: u32,
10394 direction: ExpandExcerptDirection,
10395
10396 cx: &mut Context<Self>,
10397 ) {
10398 let selections = self.selections.disjoint_anchors();
10399
10400 let lines = if lines == 0 {
10401 EditorSettings::get_global(cx).expand_excerpt_lines
10402 } else {
10403 lines
10404 };
10405
10406 self.buffer.update(cx, |buffer, cx| {
10407 let snapshot = buffer.snapshot(cx);
10408 let mut excerpt_ids = selections
10409 .iter()
10410 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10411 .collect::<Vec<_>>();
10412 excerpt_ids.sort();
10413 excerpt_ids.dedup();
10414 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10415 })
10416 }
10417
10418 pub fn expand_excerpt(
10419 &mut self,
10420 excerpt: ExcerptId,
10421 direction: ExpandExcerptDirection,
10422 cx: &mut Context<Self>,
10423 ) {
10424 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10425 self.buffer.update(cx, |buffer, cx| {
10426 buffer.expand_excerpts([excerpt], lines, direction, cx)
10427 })
10428 }
10429
10430 pub fn go_to_singleton_buffer_point(
10431 &mut self,
10432 point: Point,
10433 window: &mut Window,
10434 cx: &mut Context<Self>,
10435 ) {
10436 self.go_to_singleton_buffer_range(point..point, window, cx);
10437 }
10438
10439 pub fn go_to_singleton_buffer_range(
10440 &mut self,
10441 range: Range<Point>,
10442 window: &mut Window,
10443 cx: &mut Context<Self>,
10444 ) {
10445 let multibuffer = self.buffer().read(cx);
10446 let Some(buffer) = multibuffer.as_singleton() else {
10447 return;
10448 };
10449 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10450 return;
10451 };
10452 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10453 return;
10454 };
10455 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10456 s.select_anchor_ranges([start..end])
10457 });
10458 }
10459
10460 fn go_to_diagnostic(
10461 &mut self,
10462 _: &GoToDiagnostic,
10463 window: &mut Window,
10464 cx: &mut Context<Self>,
10465 ) {
10466 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10467 }
10468
10469 fn go_to_prev_diagnostic(
10470 &mut self,
10471 _: &GoToPrevDiagnostic,
10472 window: &mut Window,
10473 cx: &mut Context<Self>,
10474 ) {
10475 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10476 }
10477
10478 pub fn go_to_diagnostic_impl(
10479 &mut self,
10480 direction: Direction,
10481 window: &mut Window,
10482 cx: &mut Context<Self>,
10483 ) {
10484 let buffer = self.buffer.read(cx).snapshot(cx);
10485 let selection = self.selections.newest::<usize>(cx);
10486
10487 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10488 if direction == Direction::Next {
10489 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10490 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10491 return;
10492 };
10493 self.activate_diagnostics(
10494 buffer_id,
10495 popover.local_diagnostic.diagnostic.group_id,
10496 window,
10497 cx,
10498 );
10499 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10500 let primary_range_start = active_diagnostics.primary_range.start;
10501 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10502 let mut new_selection = s.newest_anchor().clone();
10503 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10504 s.select_anchors(vec![new_selection.clone()]);
10505 });
10506 self.refresh_inline_completion(false, true, window, cx);
10507 }
10508 return;
10509 }
10510 }
10511
10512 let active_group_id = self
10513 .active_diagnostics
10514 .as_ref()
10515 .map(|active_group| active_group.group_id);
10516 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10517 active_diagnostics
10518 .primary_range
10519 .to_offset(&buffer)
10520 .to_inclusive()
10521 });
10522 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10523 if active_primary_range.contains(&selection.head()) {
10524 *active_primary_range.start()
10525 } else {
10526 selection.head()
10527 }
10528 } else {
10529 selection.head()
10530 };
10531
10532 let snapshot = self.snapshot(window, cx);
10533 let primary_diagnostics_before = buffer
10534 .diagnostics_in_range::<usize>(0..search_start)
10535 .filter(|entry| entry.diagnostic.is_primary)
10536 .filter(|entry| entry.range.start != entry.range.end)
10537 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10538 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10539 .collect::<Vec<_>>();
10540 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10541 primary_diagnostics_before
10542 .iter()
10543 .position(|entry| entry.diagnostic.group_id == active_group_id)
10544 });
10545
10546 let primary_diagnostics_after = buffer
10547 .diagnostics_in_range::<usize>(search_start..buffer.len())
10548 .filter(|entry| entry.diagnostic.is_primary)
10549 .filter(|entry| entry.range.start != entry.range.end)
10550 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10551 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10552 .collect::<Vec<_>>();
10553 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10554 primary_diagnostics_after
10555 .iter()
10556 .enumerate()
10557 .rev()
10558 .find_map(|(i, entry)| {
10559 if entry.diagnostic.group_id == active_group_id {
10560 Some(i)
10561 } else {
10562 None
10563 }
10564 })
10565 });
10566
10567 let next_primary_diagnostic = match direction {
10568 Direction::Prev => primary_diagnostics_before
10569 .iter()
10570 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10571 .rev()
10572 .next(),
10573 Direction::Next => primary_diagnostics_after
10574 .iter()
10575 .skip(
10576 last_same_group_diagnostic_after
10577 .map(|index| index + 1)
10578 .unwrap_or(0),
10579 )
10580 .next(),
10581 };
10582
10583 // Cycle around to the start of the buffer, potentially moving back to the start of
10584 // the currently active diagnostic.
10585 let cycle_around = || match direction {
10586 Direction::Prev => primary_diagnostics_after
10587 .iter()
10588 .rev()
10589 .chain(primary_diagnostics_before.iter().rev())
10590 .next(),
10591 Direction::Next => primary_diagnostics_before
10592 .iter()
10593 .chain(primary_diagnostics_after.iter())
10594 .next(),
10595 };
10596
10597 if let Some((primary_range, group_id)) = next_primary_diagnostic
10598 .or_else(cycle_around)
10599 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10600 {
10601 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10602 return;
10603 };
10604 self.activate_diagnostics(buffer_id, group_id, window, cx);
10605 if self.active_diagnostics.is_some() {
10606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10607 s.select(vec![Selection {
10608 id: selection.id,
10609 start: primary_range.start,
10610 end: primary_range.start,
10611 reversed: false,
10612 goal: SelectionGoal::None,
10613 }]);
10614 });
10615 self.refresh_inline_completion(false, true, window, cx);
10616 }
10617 }
10618 }
10619
10620 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10621 let snapshot = self.snapshot(window, cx);
10622 let selection = self.selections.newest::<Point>(cx);
10623 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10624 }
10625
10626 fn go_to_hunk_after_position(
10627 &mut self,
10628 snapshot: &EditorSnapshot,
10629 position: Point,
10630 window: &mut Window,
10631 cx: &mut Context<Editor>,
10632 ) -> Option<MultiBufferDiffHunk> {
10633 let mut hunk = snapshot
10634 .buffer_snapshot
10635 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10636 .find(|hunk| hunk.row_range.start.0 > position.row);
10637 if hunk.is_none() {
10638 hunk = snapshot
10639 .buffer_snapshot
10640 .diff_hunks_in_range(Point::zero()..position)
10641 .find(|hunk| hunk.row_range.end.0 < position.row)
10642 }
10643 if let Some(hunk) = &hunk {
10644 let destination = Point::new(hunk.row_range.start.0, 0);
10645 self.unfold_ranges(&[destination..destination], false, false, cx);
10646 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10647 s.select_ranges(vec![destination..destination]);
10648 });
10649 }
10650
10651 hunk
10652 }
10653
10654 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10655 let snapshot = self.snapshot(window, cx);
10656 let selection = self.selections.newest::<Point>(cx);
10657 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10658 }
10659
10660 fn go_to_hunk_before_position(
10661 &mut self,
10662 snapshot: &EditorSnapshot,
10663 position: Point,
10664 window: &mut Window,
10665 cx: &mut Context<Editor>,
10666 ) -> Option<MultiBufferDiffHunk> {
10667 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10668 if hunk.is_none() {
10669 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10670 }
10671 if let Some(hunk) = &hunk {
10672 let destination = Point::new(hunk.row_range.start.0, 0);
10673 self.unfold_ranges(&[destination..destination], false, false, cx);
10674 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10675 s.select_ranges(vec![destination..destination]);
10676 });
10677 }
10678
10679 hunk
10680 }
10681
10682 pub fn go_to_definition(
10683 &mut self,
10684 _: &GoToDefinition,
10685 window: &mut Window,
10686 cx: &mut Context<Self>,
10687 ) -> Task<Result<Navigated>> {
10688 let definition =
10689 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10690 cx.spawn_in(window, |editor, mut cx| async move {
10691 if definition.await? == Navigated::Yes {
10692 return Ok(Navigated::Yes);
10693 }
10694 match editor.update_in(&mut cx, |editor, window, cx| {
10695 editor.find_all_references(&FindAllReferences, window, cx)
10696 })? {
10697 Some(references) => references.await,
10698 None => Ok(Navigated::No),
10699 }
10700 })
10701 }
10702
10703 pub fn go_to_declaration(
10704 &mut self,
10705 _: &GoToDeclaration,
10706 window: &mut Window,
10707 cx: &mut Context<Self>,
10708 ) -> Task<Result<Navigated>> {
10709 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10710 }
10711
10712 pub fn go_to_declaration_split(
10713 &mut self,
10714 _: &GoToDeclaration,
10715 window: &mut Window,
10716 cx: &mut Context<Self>,
10717 ) -> Task<Result<Navigated>> {
10718 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10719 }
10720
10721 pub fn go_to_implementation(
10722 &mut self,
10723 _: &GoToImplementation,
10724 window: &mut Window,
10725 cx: &mut Context<Self>,
10726 ) -> Task<Result<Navigated>> {
10727 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10728 }
10729
10730 pub fn go_to_implementation_split(
10731 &mut self,
10732 _: &GoToImplementationSplit,
10733 window: &mut Window,
10734 cx: &mut Context<Self>,
10735 ) -> Task<Result<Navigated>> {
10736 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10737 }
10738
10739 pub fn go_to_type_definition(
10740 &mut self,
10741 _: &GoToTypeDefinition,
10742 window: &mut Window,
10743 cx: &mut Context<Self>,
10744 ) -> Task<Result<Navigated>> {
10745 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10746 }
10747
10748 pub fn go_to_definition_split(
10749 &mut self,
10750 _: &GoToDefinitionSplit,
10751 window: &mut Window,
10752 cx: &mut Context<Self>,
10753 ) -> Task<Result<Navigated>> {
10754 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10755 }
10756
10757 pub fn go_to_type_definition_split(
10758 &mut self,
10759 _: &GoToTypeDefinitionSplit,
10760 window: &mut Window,
10761 cx: &mut Context<Self>,
10762 ) -> Task<Result<Navigated>> {
10763 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10764 }
10765
10766 fn go_to_definition_of_kind(
10767 &mut self,
10768 kind: GotoDefinitionKind,
10769 split: bool,
10770 window: &mut Window,
10771 cx: &mut Context<Self>,
10772 ) -> Task<Result<Navigated>> {
10773 let Some(provider) = self.semantics_provider.clone() else {
10774 return Task::ready(Ok(Navigated::No));
10775 };
10776 let head = self.selections.newest::<usize>(cx).head();
10777 let buffer = self.buffer.read(cx);
10778 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10779 text_anchor
10780 } else {
10781 return Task::ready(Ok(Navigated::No));
10782 };
10783
10784 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10785 return Task::ready(Ok(Navigated::No));
10786 };
10787
10788 cx.spawn_in(window, |editor, mut cx| async move {
10789 let definitions = definitions.await?;
10790 let navigated = editor
10791 .update_in(&mut cx, |editor, window, cx| {
10792 editor.navigate_to_hover_links(
10793 Some(kind),
10794 definitions
10795 .into_iter()
10796 .filter(|location| {
10797 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10798 })
10799 .map(HoverLink::Text)
10800 .collect::<Vec<_>>(),
10801 split,
10802 window,
10803 cx,
10804 )
10805 })?
10806 .await?;
10807 anyhow::Ok(navigated)
10808 })
10809 }
10810
10811 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10812 let selection = self.selections.newest_anchor();
10813 let head = selection.head();
10814 let tail = selection.tail();
10815
10816 let Some((buffer, start_position)) =
10817 self.buffer.read(cx).text_anchor_for_position(head, cx)
10818 else {
10819 return;
10820 };
10821
10822 let end_position = if head != tail {
10823 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10824 return;
10825 };
10826 Some(pos)
10827 } else {
10828 None
10829 };
10830
10831 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10832 let url = if let Some(end_pos) = end_position {
10833 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10834 } else {
10835 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10836 };
10837
10838 if let Some(url) = url {
10839 editor.update(&mut cx, |_, cx| {
10840 cx.open_url(&url);
10841 })
10842 } else {
10843 Ok(())
10844 }
10845 });
10846
10847 url_finder.detach();
10848 }
10849
10850 pub fn open_selected_filename(
10851 &mut self,
10852 _: &OpenSelectedFilename,
10853 window: &mut Window,
10854 cx: &mut Context<Self>,
10855 ) {
10856 let Some(workspace) = self.workspace() else {
10857 return;
10858 };
10859
10860 let position = self.selections.newest_anchor().head();
10861
10862 let Some((buffer, buffer_position)) =
10863 self.buffer.read(cx).text_anchor_for_position(position, cx)
10864 else {
10865 return;
10866 };
10867
10868 let project = self.project.clone();
10869
10870 cx.spawn_in(window, |_, mut cx| async move {
10871 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10872
10873 if let Some((_, path)) = result {
10874 workspace
10875 .update_in(&mut cx, |workspace, window, cx| {
10876 workspace.open_resolved_path(path, window, cx)
10877 })?
10878 .await?;
10879 }
10880 anyhow::Ok(())
10881 })
10882 .detach();
10883 }
10884
10885 pub(crate) fn navigate_to_hover_links(
10886 &mut self,
10887 kind: Option<GotoDefinitionKind>,
10888 mut definitions: Vec<HoverLink>,
10889 split: bool,
10890 window: &mut Window,
10891 cx: &mut Context<Editor>,
10892 ) -> Task<Result<Navigated>> {
10893 // If there is one definition, just open it directly
10894 if definitions.len() == 1 {
10895 let definition = definitions.pop().unwrap();
10896
10897 enum TargetTaskResult {
10898 Location(Option<Location>),
10899 AlreadyNavigated,
10900 }
10901
10902 let target_task = match definition {
10903 HoverLink::Text(link) => {
10904 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10905 }
10906 HoverLink::InlayHint(lsp_location, server_id) => {
10907 let computation =
10908 self.compute_target_location(lsp_location, server_id, window, cx);
10909 cx.background_executor().spawn(async move {
10910 let location = computation.await?;
10911 Ok(TargetTaskResult::Location(location))
10912 })
10913 }
10914 HoverLink::Url(url) => {
10915 cx.open_url(&url);
10916 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10917 }
10918 HoverLink::File(path) => {
10919 if let Some(workspace) = self.workspace() {
10920 cx.spawn_in(window, |_, mut cx| async move {
10921 workspace
10922 .update_in(&mut cx, |workspace, window, cx| {
10923 workspace.open_resolved_path(path, window, cx)
10924 })?
10925 .await
10926 .map(|_| TargetTaskResult::AlreadyNavigated)
10927 })
10928 } else {
10929 Task::ready(Ok(TargetTaskResult::Location(None)))
10930 }
10931 }
10932 };
10933 cx.spawn_in(window, |editor, mut cx| async move {
10934 let target = match target_task.await.context("target resolution task")? {
10935 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10936 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10937 TargetTaskResult::Location(Some(target)) => target,
10938 };
10939
10940 editor.update_in(&mut cx, |editor, window, cx| {
10941 let Some(workspace) = editor.workspace() else {
10942 return Navigated::No;
10943 };
10944 let pane = workspace.read(cx).active_pane().clone();
10945
10946 let range = target.range.to_point(target.buffer.read(cx));
10947 let range = editor.range_for_match(&range);
10948 let range = collapse_multiline_range(range);
10949
10950 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10951 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10952 } else {
10953 window.defer(cx, move |window, cx| {
10954 let target_editor: Entity<Self> =
10955 workspace.update(cx, |workspace, cx| {
10956 let pane = if split {
10957 workspace.adjacent_pane(window, cx)
10958 } else {
10959 workspace.active_pane().clone()
10960 };
10961
10962 workspace.open_project_item(
10963 pane,
10964 target.buffer.clone(),
10965 true,
10966 true,
10967 window,
10968 cx,
10969 )
10970 });
10971 target_editor.update(cx, |target_editor, cx| {
10972 // When selecting a definition in a different buffer, disable the nav history
10973 // to avoid creating a history entry at the previous cursor location.
10974 pane.update(cx, |pane, _| pane.disable_history());
10975 target_editor.go_to_singleton_buffer_range(range, window, cx);
10976 pane.update(cx, |pane, _| pane.enable_history());
10977 });
10978 });
10979 }
10980 Navigated::Yes
10981 })
10982 })
10983 } else if !definitions.is_empty() {
10984 cx.spawn_in(window, |editor, mut cx| async move {
10985 let (title, location_tasks, workspace) = editor
10986 .update_in(&mut cx, |editor, window, cx| {
10987 let tab_kind = match kind {
10988 Some(GotoDefinitionKind::Implementation) => "Implementations",
10989 _ => "Definitions",
10990 };
10991 let title = definitions
10992 .iter()
10993 .find_map(|definition| match definition {
10994 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10995 let buffer = origin.buffer.read(cx);
10996 format!(
10997 "{} for {}",
10998 tab_kind,
10999 buffer
11000 .text_for_range(origin.range.clone())
11001 .collect::<String>()
11002 )
11003 }),
11004 HoverLink::InlayHint(_, _) => None,
11005 HoverLink::Url(_) => None,
11006 HoverLink::File(_) => None,
11007 })
11008 .unwrap_or(tab_kind.to_string());
11009 let location_tasks = definitions
11010 .into_iter()
11011 .map(|definition| match definition {
11012 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11013 HoverLink::InlayHint(lsp_location, server_id) => editor
11014 .compute_target_location(lsp_location, server_id, window, cx),
11015 HoverLink::Url(_) => Task::ready(Ok(None)),
11016 HoverLink::File(_) => Task::ready(Ok(None)),
11017 })
11018 .collect::<Vec<_>>();
11019 (title, location_tasks, editor.workspace().clone())
11020 })
11021 .context("location tasks preparation")?;
11022
11023 let locations = future::join_all(location_tasks)
11024 .await
11025 .into_iter()
11026 .filter_map(|location| location.transpose())
11027 .collect::<Result<_>>()
11028 .context("location tasks")?;
11029
11030 let Some(workspace) = workspace else {
11031 return Ok(Navigated::No);
11032 };
11033 let opened = workspace
11034 .update_in(&mut cx, |workspace, window, cx| {
11035 Self::open_locations_in_multibuffer(
11036 workspace,
11037 locations,
11038 title,
11039 split,
11040 MultibufferSelectionMode::First,
11041 window,
11042 cx,
11043 )
11044 })
11045 .ok();
11046
11047 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11048 })
11049 } else {
11050 Task::ready(Ok(Navigated::No))
11051 }
11052 }
11053
11054 fn compute_target_location(
11055 &self,
11056 lsp_location: lsp::Location,
11057 server_id: LanguageServerId,
11058 window: &mut Window,
11059 cx: &mut Context<Self>,
11060 ) -> Task<anyhow::Result<Option<Location>>> {
11061 let Some(project) = self.project.clone() else {
11062 return Task::ready(Ok(None));
11063 };
11064
11065 cx.spawn_in(window, move |editor, mut cx| async move {
11066 let location_task = editor.update(&mut cx, |_, cx| {
11067 project.update(cx, |project, cx| {
11068 let language_server_name = project
11069 .language_server_statuses(cx)
11070 .find(|(id, _)| server_id == *id)
11071 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11072 language_server_name.map(|language_server_name| {
11073 project.open_local_buffer_via_lsp(
11074 lsp_location.uri.clone(),
11075 server_id,
11076 language_server_name,
11077 cx,
11078 )
11079 })
11080 })
11081 })?;
11082 let location = match location_task {
11083 Some(task) => Some({
11084 let target_buffer_handle = task.await.context("open local buffer")?;
11085 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11086 let target_start = target_buffer
11087 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11088 let target_end = target_buffer
11089 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11090 target_buffer.anchor_after(target_start)
11091 ..target_buffer.anchor_before(target_end)
11092 })?;
11093 Location {
11094 buffer: target_buffer_handle,
11095 range,
11096 }
11097 }),
11098 None => None,
11099 };
11100 Ok(location)
11101 })
11102 }
11103
11104 pub fn find_all_references(
11105 &mut self,
11106 _: &FindAllReferences,
11107 window: &mut Window,
11108 cx: &mut Context<Self>,
11109 ) -> Option<Task<Result<Navigated>>> {
11110 let selection = self.selections.newest::<usize>(cx);
11111 let multi_buffer = self.buffer.read(cx);
11112 let head = selection.head();
11113
11114 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11115 let head_anchor = multi_buffer_snapshot.anchor_at(
11116 head,
11117 if head < selection.tail() {
11118 Bias::Right
11119 } else {
11120 Bias::Left
11121 },
11122 );
11123
11124 match self
11125 .find_all_references_task_sources
11126 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11127 {
11128 Ok(_) => {
11129 log::info!(
11130 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11131 );
11132 return None;
11133 }
11134 Err(i) => {
11135 self.find_all_references_task_sources.insert(i, head_anchor);
11136 }
11137 }
11138
11139 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11140 let workspace = self.workspace()?;
11141 let project = workspace.read(cx).project().clone();
11142 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11143 Some(cx.spawn_in(window, |editor, mut cx| async move {
11144 let _cleanup = defer({
11145 let mut cx = cx.clone();
11146 move || {
11147 let _ = editor.update(&mut cx, |editor, _| {
11148 if let Ok(i) =
11149 editor
11150 .find_all_references_task_sources
11151 .binary_search_by(|anchor| {
11152 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11153 })
11154 {
11155 editor.find_all_references_task_sources.remove(i);
11156 }
11157 });
11158 }
11159 });
11160
11161 let locations = references.await?;
11162 if locations.is_empty() {
11163 return anyhow::Ok(Navigated::No);
11164 }
11165
11166 workspace.update_in(&mut cx, |workspace, window, cx| {
11167 let title = locations
11168 .first()
11169 .as_ref()
11170 .map(|location| {
11171 let buffer = location.buffer.read(cx);
11172 format!(
11173 "References to `{}`",
11174 buffer
11175 .text_for_range(location.range.clone())
11176 .collect::<String>()
11177 )
11178 })
11179 .unwrap();
11180 Self::open_locations_in_multibuffer(
11181 workspace,
11182 locations,
11183 title,
11184 false,
11185 MultibufferSelectionMode::First,
11186 window,
11187 cx,
11188 );
11189 Navigated::Yes
11190 })
11191 }))
11192 }
11193
11194 /// Opens a multibuffer with the given project locations in it
11195 pub fn open_locations_in_multibuffer(
11196 workspace: &mut Workspace,
11197 mut locations: Vec<Location>,
11198 title: String,
11199 split: bool,
11200 multibuffer_selection_mode: MultibufferSelectionMode,
11201 window: &mut Window,
11202 cx: &mut Context<Workspace>,
11203 ) {
11204 // If there are multiple definitions, open them in a multibuffer
11205 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11206 let mut locations = locations.into_iter().peekable();
11207 let mut ranges = Vec::new();
11208 let capability = workspace.project().read(cx).capability();
11209
11210 let excerpt_buffer = cx.new(|cx| {
11211 let mut multibuffer = MultiBuffer::new(capability);
11212 while let Some(location) = locations.next() {
11213 let buffer = location.buffer.read(cx);
11214 let mut ranges_for_buffer = Vec::new();
11215 let range = location.range.to_offset(buffer);
11216 ranges_for_buffer.push(range.clone());
11217
11218 while let Some(next_location) = locations.peek() {
11219 if next_location.buffer == location.buffer {
11220 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11221 locations.next();
11222 } else {
11223 break;
11224 }
11225 }
11226
11227 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11228 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11229 location.buffer.clone(),
11230 ranges_for_buffer,
11231 DEFAULT_MULTIBUFFER_CONTEXT,
11232 cx,
11233 ))
11234 }
11235
11236 multibuffer.with_title(title)
11237 });
11238
11239 let editor = cx.new(|cx| {
11240 Editor::for_multibuffer(
11241 excerpt_buffer,
11242 Some(workspace.project().clone()),
11243 true,
11244 window,
11245 cx,
11246 )
11247 });
11248 editor.update(cx, |editor, cx| {
11249 match multibuffer_selection_mode {
11250 MultibufferSelectionMode::First => {
11251 if let Some(first_range) = ranges.first() {
11252 editor.change_selections(None, window, cx, |selections| {
11253 selections.clear_disjoint();
11254 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11255 });
11256 }
11257 editor.highlight_background::<Self>(
11258 &ranges,
11259 |theme| theme.editor_highlighted_line_background,
11260 cx,
11261 );
11262 }
11263 MultibufferSelectionMode::All => {
11264 editor.change_selections(None, window, cx, |selections| {
11265 selections.clear_disjoint();
11266 selections.select_anchor_ranges(ranges);
11267 });
11268 }
11269 }
11270 editor.register_buffers_with_language_servers(cx);
11271 });
11272
11273 let item = Box::new(editor);
11274 let item_id = item.item_id();
11275
11276 if split {
11277 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11278 } else {
11279 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11280 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11281 pane.close_current_preview_item(window, cx)
11282 } else {
11283 None
11284 }
11285 });
11286 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11287 }
11288 workspace.active_pane().update(cx, |pane, cx| {
11289 pane.set_preview_item_id(Some(item_id), cx);
11290 });
11291 }
11292
11293 pub fn rename(
11294 &mut self,
11295 _: &Rename,
11296 window: &mut Window,
11297 cx: &mut Context<Self>,
11298 ) -> Option<Task<Result<()>>> {
11299 use language::ToOffset as _;
11300
11301 let provider = self.semantics_provider.clone()?;
11302 let selection = self.selections.newest_anchor().clone();
11303 let (cursor_buffer, cursor_buffer_position) = self
11304 .buffer
11305 .read(cx)
11306 .text_anchor_for_position(selection.head(), cx)?;
11307 let (tail_buffer, cursor_buffer_position_end) = self
11308 .buffer
11309 .read(cx)
11310 .text_anchor_for_position(selection.tail(), cx)?;
11311 if tail_buffer != cursor_buffer {
11312 return None;
11313 }
11314
11315 let snapshot = cursor_buffer.read(cx).snapshot();
11316 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11317 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11318 let prepare_rename = provider
11319 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11320 .unwrap_or_else(|| Task::ready(Ok(None)));
11321 drop(snapshot);
11322
11323 Some(cx.spawn_in(window, |this, mut cx| async move {
11324 let rename_range = if let Some(range) = prepare_rename.await? {
11325 Some(range)
11326 } else {
11327 this.update(&mut cx, |this, cx| {
11328 let buffer = this.buffer.read(cx).snapshot(cx);
11329 let mut buffer_highlights = this
11330 .document_highlights_for_position(selection.head(), &buffer)
11331 .filter(|highlight| {
11332 highlight.start.excerpt_id == selection.head().excerpt_id
11333 && highlight.end.excerpt_id == selection.head().excerpt_id
11334 });
11335 buffer_highlights
11336 .next()
11337 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11338 })?
11339 };
11340 if let Some(rename_range) = rename_range {
11341 this.update_in(&mut cx, |this, window, cx| {
11342 let snapshot = cursor_buffer.read(cx).snapshot();
11343 let rename_buffer_range = rename_range.to_offset(&snapshot);
11344 let cursor_offset_in_rename_range =
11345 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11346 let cursor_offset_in_rename_range_end =
11347 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11348
11349 this.take_rename(false, window, cx);
11350 let buffer = this.buffer.read(cx).read(cx);
11351 let cursor_offset = selection.head().to_offset(&buffer);
11352 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11353 let rename_end = rename_start + rename_buffer_range.len();
11354 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11355 let mut old_highlight_id = None;
11356 let old_name: Arc<str> = buffer
11357 .chunks(rename_start..rename_end, true)
11358 .map(|chunk| {
11359 if old_highlight_id.is_none() {
11360 old_highlight_id = chunk.syntax_highlight_id;
11361 }
11362 chunk.text
11363 })
11364 .collect::<String>()
11365 .into();
11366
11367 drop(buffer);
11368
11369 // Position the selection in the rename editor so that it matches the current selection.
11370 this.show_local_selections = false;
11371 let rename_editor = cx.new(|cx| {
11372 let mut editor = Editor::single_line(window, cx);
11373 editor.buffer.update(cx, |buffer, cx| {
11374 buffer.edit([(0..0, old_name.clone())], None, cx)
11375 });
11376 let rename_selection_range = match cursor_offset_in_rename_range
11377 .cmp(&cursor_offset_in_rename_range_end)
11378 {
11379 Ordering::Equal => {
11380 editor.select_all(&SelectAll, window, cx);
11381 return editor;
11382 }
11383 Ordering::Less => {
11384 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11385 }
11386 Ordering::Greater => {
11387 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11388 }
11389 };
11390 if rename_selection_range.end > old_name.len() {
11391 editor.select_all(&SelectAll, window, cx);
11392 } else {
11393 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11394 s.select_ranges([rename_selection_range]);
11395 });
11396 }
11397 editor
11398 });
11399 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11400 if e == &EditorEvent::Focused {
11401 cx.emit(EditorEvent::FocusedIn)
11402 }
11403 })
11404 .detach();
11405
11406 let write_highlights =
11407 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11408 let read_highlights =
11409 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11410 let ranges = write_highlights
11411 .iter()
11412 .flat_map(|(_, ranges)| ranges.iter())
11413 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11414 .cloned()
11415 .collect();
11416
11417 this.highlight_text::<Rename>(
11418 ranges,
11419 HighlightStyle {
11420 fade_out: Some(0.6),
11421 ..Default::default()
11422 },
11423 cx,
11424 );
11425 let rename_focus_handle = rename_editor.focus_handle(cx);
11426 window.focus(&rename_focus_handle);
11427 let block_id = this.insert_blocks(
11428 [BlockProperties {
11429 style: BlockStyle::Flex,
11430 placement: BlockPlacement::Below(range.start),
11431 height: 1,
11432 render: Arc::new({
11433 let rename_editor = rename_editor.clone();
11434 move |cx: &mut BlockContext| {
11435 let mut text_style = cx.editor_style.text.clone();
11436 if let Some(highlight_style) = old_highlight_id
11437 .and_then(|h| h.style(&cx.editor_style.syntax))
11438 {
11439 text_style = text_style.highlight(highlight_style);
11440 }
11441 div()
11442 .block_mouse_down()
11443 .pl(cx.anchor_x)
11444 .child(EditorElement::new(
11445 &rename_editor,
11446 EditorStyle {
11447 background: cx.theme().system().transparent,
11448 local_player: cx.editor_style.local_player,
11449 text: text_style,
11450 scrollbar_width: cx.editor_style.scrollbar_width,
11451 syntax: cx.editor_style.syntax.clone(),
11452 status: cx.editor_style.status.clone(),
11453 inlay_hints_style: HighlightStyle {
11454 font_weight: Some(FontWeight::BOLD),
11455 ..make_inlay_hints_style(cx.app)
11456 },
11457 inline_completion_styles: make_suggestion_styles(
11458 cx.app,
11459 ),
11460 ..EditorStyle::default()
11461 },
11462 ))
11463 .into_any_element()
11464 }
11465 }),
11466 priority: 0,
11467 }],
11468 Some(Autoscroll::fit()),
11469 cx,
11470 )[0];
11471 this.pending_rename = Some(RenameState {
11472 range,
11473 old_name,
11474 editor: rename_editor,
11475 block_id,
11476 });
11477 })?;
11478 }
11479
11480 Ok(())
11481 }))
11482 }
11483
11484 pub fn confirm_rename(
11485 &mut self,
11486 _: &ConfirmRename,
11487 window: &mut Window,
11488 cx: &mut Context<Self>,
11489 ) -> Option<Task<Result<()>>> {
11490 let rename = self.take_rename(false, window, cx)?;
11491 let workspace = self.workspace()?.downgrade();
11492 let (buffer, start) = self
11493 .buffer
11494 .read(cx)
11495 .text_anchor_for_position(rename.range.start, cx)?;
11496 let (end_buffer, _) = self
11497 .buffer
11498 .read(cx)
11499 .text_anchor_for_position(rename.range.end, cx)?;
11500 if buffer != end_buffer {
11501 return None;
11502 }
11503
11504 let old_name = rename.old_name;
11505 let new_name = rename.editor.read(cx).text(cx);
11506
11507 let rename = self.semantics_provider.as_ref()?.perform_rename(
11508 &buffer,
11509 start,
11510 new_name.clone(),
11511 cx,
11512 )?;
11513
11514 Some(cx.spawn_in(window, |editor, mut cx| async move {
11515 let project_transaction = rename.await?;
11516 Self::open_project_transaction(
11517 &editor,
11518 workspace,
11519 project_transaction,
11520 format!("Rename: {} → {}", old_name, new_name),
11521 cx.clone(),
11522 )
11523 .await?;
11524
11525 editor.update(&mut cx, |editor, cx| {
11526 editor.refresh_document_highlights(cx);
11527 })?;
11528 Ok(())
11529 }))
11530 }
11531
11532 fn take_rename(
11533 &mut self,
11534 moving_cursor: bool,
11535 window: &mut Window,
11536 cx: &mut Context<Self>,
11537 ) -> Option<RenameState> {
11538 let rename = self.pending_rename.take()?;
11539 if rename.editor.focus_handle(cx).is_focused(window) {
11540 window.focus(&self.focus_handle);
11541 }
11542
11543 self.remove_blocks(
11544 [rename.block_id].into_iter().collect(),
11545 Some(Autoscroll::fit()),
11546 cx,
11547 );
11548 self.clear_highlights::<Rename>(cx);
11549 self.show_local_selections = true;
11550
11551 if moving_cursor {
11552 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11553 editor.selections.newest::<usize>(cx).head()
11554 });
11555
11556 // Update the selection to match the position of the selection inside
11557 // the rename editor.
11558 let snapshot = self.buffer.read(cx).read(cx);
11559 let rename_range = rename.range.to_offset(&snapshot);
11560 let cursor_in_editor = snapshot
11561 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11562 .min(rename_range.end);
11563 drop(snapshot);
11564
11565 self.change_selections(None, window, cx, |s| {
11566 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11567 });
11568 } else {
11569 self.refresh_document_highlights(cx);
11570 }
11571
11572 Some(rename)
11573 }
11574
11575 pub fn pending_rename(&self) -> Option<&RenameState> {
11576 self.pending_rename.as_ref()
11577 }
11578
11579 fn format(
11580 &mut self,
11581 _: &Format,
11582 window: &mut Window,
11583 cx: &mut Context<Self>,
11584 ) -> Option<Task<Result<()>>> {
11585 let project = match &self.project {
11586 Some(project) => project.clone(),
11587 None => return None,
11588 };
11589
11590 Some(self.perform_format(
11591 project,
11592 FormatTrigger::Manual,
11593 FormatTarget::Buffers,
11594 window,
11595 cx,
11596 ))
11597 }
11598
11599 fn format_selections(
11600 &mut self,
11601 _: &FormatSelections,
11602 window: &mut Window,
11603 cx: &mut Context<Self>,
11604 ) -> Option<Task<Result<()>>> {
11605 let project = match &self.project {
11606 Some(project) => project.clone(),
11607 None => return None,
11608 };
11609
11610 let ranges = self
11611 .selections
11612 .all_adjusted(cx)
11613 .into_iter()
11614 .map(|selection| selection.range())
11615 .collect_vec();
11616
11617 Some(self.perform_format(
11618 project,
11619 FormatTrigger::Manual,
11620 FormatTarget::Ranges(ranges),
11621 window,
11622 cx,
11623 ))
11624 }
11625
11626 fn perform_format(
11627 &mut self,
11628 project: Entity<Project>,
11629 trigger: FormatTrigger,
11630 target: FormatTarget,
11631 window: &mut Window,
11632 cx: &mut Context<Self>,
11633 ) -> Task<Result<()>> {
11634 let buffer = self.buffer.clone();
11635 let (buffers, target) = match target {
11636 FormatTarget::Buffers => {
11637 let mut buffers = buffer.read(cx).all_buffers();
11638 if trigger == FormatTrigger::Save {
11639 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11640 }
11641 (buffers, LspFormatTarget::Buffers)
11642 }
11643 FormatTarget::Ranges(selection_ranges) => {
11644 let multi_buffer = buffer.read(cx);
11645 let snapshot = multi_buffer.read(cx);
11646 let mut buffers = HashSet::default();
11647 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11648 BTreeMap::new();
11649 for selection_range in selection_ranges {
11650 for (buffer, buffer_range, _) in
11651 snapshot.range_to_buffer_ranges(selection_range)
11652 {
11653 let buffer_id = buffer.remote_id();
11654 let start = buffer.anchor_before(buffer_range.start);
11655 let end = buffer.anchor_after(buffer_range.end);
11656 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11657 buffer_id_to_ranges
11658 .entry(buffer_id)
11659 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11660 .or_insert_with(|| vec![start..end]);
11661 }
11662 }
11663 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11664 }
11665 };
11666
11667 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11668 let format = project.update(cx, |project, cx| {
11669 project.format(buffers, target, true, trigger, cx)
11670 });
11671
11672 cx.spawn_in(window, |_, mut cx| async move {
11673 let transaction = futures::select_biased! {
11674 () = timeout => {
11675 log::warn!("timed out waiting for formatting");
11676 None
11677 }
11678 transaction = format.log_err().fuse() => transaction,
11679 };
11680
11681 buffer
11682 .update(&mut cx, |buffer, cx| {
11683 if let Some(transaction) = transaction {
11684 if !buffer.is_singleton() {
11685 buffer.push_transaction(&transaction.0, cx);
11686 }
11687 }
11688
11689 cx.notify();
11690 })
11691 .ok();
11692
11693 Ok(())
11694 })
11695 }
11696
11697 fn restart_language_server(
11698 &mut self,
11699 _: &RestartLanguageServer,
11700 _: &mut Window,
11701 cx: &mut Context<Self>,
11702 ) {
11703 if let Some(project) = self.project.clone() {
11704 self.buffer.update(cx, |multi_buffer, cx| {
11705 project.update(cx, |project, cx| {
11706 project.restart_language_servers_for_buffers(
11707 multi_buffer.all_buffers().into_iter().collect(),
11708 cx,
11709 );
11710 });
11711 })
11712 }
11713 }
11714
11715 fn cancel_language_server_work(
11716 workspace: &mut Workspace,
11717 _: &actions::CancelLanguageServerWork,
11718 _: &mut Window,
11719 cx: &mut Context<Workspace>,
11720 ) {
11721 let project = workspace.project();
11722 let buffers = workspace
11723 .active_item(cx)
11724 .and_then(|item| item.act_as::<Editor>(cx))
11725 .map_or(HashSet::default(), |editor| {
11726 editor.read(cx).buffer.read(cx).all_buffers()
11727 });
11728 project.update(cx, |project, cx| {
11729 project.cancel_language_server_work_for_buffers(buffers, cx);
11730 });
11731 }
11732
11733 fn show_character_palette(
11734 &mut self,
11735 _: &ShowCharacterPalette,
11736 window: &mut Window,
11737 _: &mut Context<Self>,
11738 ) {
11739 window.show_character_palette();
11740 }
11741
11742 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11743 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11744 let buffer = self.buffer.read(cx).snapshot(cx);
11745 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11746 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11747 let is_valid = buffer
11748 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11749 .any(|entry| {
11750 entry.diagnostic.is_primary
11751 && !entry.range.is_empty()
11752 && entry.range.start == primary_range_start
11753 && entry.diagnostic.message == active_diagnostics.primary_message
11754 });
11755
11756 if is_valid != active_diagnostics.is_valid {
11757 active_diagnostics.is_valid = is_valid;
11758 let mut new_styles = HashMap::default();
11759 for (block_id, diagnostic) in &active_diagnostics.blocks {
11760 new_styles.insert(
11761 *block_id,
11762 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11763 );
11764 }
11765 self.display_map.update(cx, |display_map, _cx| {
11766 display_map.replace_blocks(new_styles)
11767 });
11768 }
11769 }
11770 }
11771
11772 fn activate_diagnostics(
11773 &mut self,
11774 buffer_id: BufferId,
11775 group_id: usize,
11776 window: &mut Window,
11777 cx: &mut Context<Self>,
11778 ) {
11779 self.dismiss_diagnostics(cx);
11780 let snapshot = self.snapshot(window, cx);
11781 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11782 let buffer = self.buffer.read(cx).snapshot(cx);
11783
11784 let mut primary_range = None;
11785 let mut primary_message = None;
11786 let diagnostic_group = buffer
11787 .diagnostic_group(buffer_id, group_id)
11788 .filter_map(|entry| {
11789 let start = entry.range.start;
11790 let end = entry.range.end;
11791 if snapshot.is_line_folded(MultiBufferRow(start.row))
11792 && (start.row == end.row
11793 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11794 {
11795 return None;
11796 }
11797 if entry.diagnostic.is_primary {
11798 primary_range = Some(entry.range.clone());
11799 primary_message = Some(entry.diagnostic.message.clone());
11800 }
11801 Some(entry)
11802 })
11803 .collect::<Vec<_>>();
11804 let primary_range = primary_range?;
11805 let primary_message = primary_message?;
11806
11807 let blocks = display_map
11808 .insert_blocks(
11809 diagnostic_group.iter().map(|entry| {
11810 let diagnostic = entry.diagnostic.clone();
11811 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11812 BlockProperties {
11813 style: BlockStyle::Fixed,
11814 placement: BlockPlacement::Below(
11815 buffer.anchor_after(entry.range.start),
11816 ),
11817 height: message_height,
11818 render: diagnostic_block_renderer(diagnostic, None, true, true),
11819 priority: 0,
11820 }
11821 }),
11822 cx,
11823 )
11824 .into_iter()
11825 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11826 .collect();
11827
11828 Some(ActiveDiagnosticGroup {
11829 primary_range: buffer.anchor_before(primary_range.start)
11830 ..buffer.anchor_after(primary_range.end),
11831 primary_message,
11832 group_id,
11833 blocks,
11834 is_valid: true,
11835 })
11836 });
11837 }
11838
11839 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11840 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11841 self.display_map.update(cx, |display_map, cx| {
11842 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11843 });
11844 cx.notify();
11845 }
11846 }
11847
11848 pub fn set_selections_from_remote(
11849 &mut self,
11850 selections: Vec<Selection<Anchor>>,
11851 pending_selection: Option<Selection<Anchor>>,
11852 window: &mut Window,
11853 cx: &mut Context<Self>,
11854 ) {
11855 let old_cursor_position = self.selections.newest_anchor().head();
11856 self.selections.change_with(cx, |s| {
11857 s.select_anchors(selections);
11858 if let Some(pending_selection) = pending_selection {
11859 s.set_pending(pending_selection, SelectMode::Character);
11860 } else {
11861 s.clear_pending();
11862 }
11863 });
11864 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11865 }
11866
11867 fn push_to_selection_history(&mut self) {
11868 self.selection_history.push(SelectionHistoryEntry {
11869 selections: self.selections.disjoint_anchors(),
11870 select_next_state: self.select_next_state.clone(),
11871 select_prev_state: self.select_prev_state.clone(),
11872 add_selections_state: self.add_selections_state.clone(),
11873 });
11874 }
11875
11876 pub fn transact(
11877 &mut self,
11878 window: &mut Window,
11879 cx: &mut Context<Self>,
11880 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11881 ) -> Option<TransactionId> {
11882 self.start_transaction_at(Instant::now(), window, cx);
11883 update(self, window, cx);
11884 self.end_transaction_at(Instant::now(), cx)
11885 }
11886
11887 pub fn start_transaction_at(
11888 &mut self,
11889 now: Instant,
11890 window: &mut Window,
11891 cx: &mut Context<Self>,
11892 ) {
11893 self.end_selection(window, cx);
11894 if let Some(tx_id) = self
11895 .buffer
11896 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11897 {
11898 self.selection_history
11899 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11900 cx.emit(EditorEvent::TransactionBegun {
11901 transaction_id: tx_id,
11902 })
11903 }
11904 }
11905
11906 pub fn end_transaction_at(
11907 &mut self,
11908 now: Instant,
11909 cx: &mut Context<Self>,
11910 ) -> Option<TransactionId> {
11911 if let Some(transaction_id) = self
11912 .buffer
11913 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11914 {
11915 if let Some((_, end_selections)) =
11916 self.selection_history.transaction_mut(transaction_id)
11917 {
11918 *end_selections = Some(self.selections.disjoint_anchors());
11919 } else {
11920 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11921 }
11922
11923 cx.emit(EditorEvent::Edited { transaction_id });
11924 Some(transaction_id)
11925 } else {
11926 None
11927 }
11928 }
11929
11930 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11931 if self.selection_mark_mode {
11932 self.change_selections(None, window, cx, |s| {
11933 s.move_with(|_, sel| {
11934 sel.collapse_to(sel.head(), SelectionGoal::None);
11935 });
11936 })
11937 }
11938 self.selection_mark_mode = true;
11939 cx.notify();
11940 }
11941
11942 pub fn swap_selection_ends(
11943 &mut self,
11944 _: &actions::SwapSelectionEnds,
11945 window: &mut Window,
11946 cx: &mut Context<Self>,
11947 ) {
11948 self.change_selections(None, window, cx, |s| {
11949 s.move_with(|_, sel| {
11950 if sel.start != sel.end {
11951 sel.reversed = !sel.reversed
11952 }
11953 });
11954 });
11955 self.request_autoscroll(Autoscroll::newest(), cx);
11956 cx.notify();
11957 }
11958
11959 pub fn toggle_fold(
11960 &mut self,
11961 _: &actions::ToggleFold,
11962 window: &mut Window,
11963 cx: &mut Context<Self>,
11964 ) {
11965 if self.is_singleton(cx) {
11966 let selection = self.selections.newest::<Point>(cx);
11967
11968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11969 let range = if selection.is_empty() {
11970 let point = selection.head().to_display_point(&display_map);
11971 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11972 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11973 .to_point(&display_map);
11974 start..end
11975 } else {
11976 selection.range()
11977 };
11978 if display_map.folds_in_range(range).next().is_some() {
11979 self.unfold_lines(&Default::default(), window, cx)
11980 } else {
11981 self.fold(&Default::default(), window, cx)
11982 }
11983 } else {
11984 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11985 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11986 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11987 .map(|(snapshot, _, _)| snapshot.remote_id())
11988 .collect();
11989
11990 for buffer_id in buffer_ids {
11991 if self.is_buffer_folded(buffer_id, cx) {
11992 self.unfold_buffer(buffer_id, cx);
11993 } else {
11994 self.fold_buffer(buffer_id, cx);
11995 }
11996 }
11997 }
11998 }
11999
12000 pub fn toggle_fold_recursive(
12001 &mut self,
12002 _: &actions::ToggleFoldRecursive,
12003 window: &mut Window,
12004 cx: &mut Context<Self>,
12005 ) {
12006 let selection = self.selections.newest::<Point>(cx);
12007
12008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12009 let range = if selection.is_empty() {
12010 let point = selection.head().to_display_point(&display_map);
12011 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12012 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12013 .to_point(&display_map);
12014 start..end
12015 } else {
12016 selection.range()
12017 };
12018 if display_map.folds_in_range(range).next().is_some() {
12019 self.unfold_recursive(&Default::default(), window, cx)
12020 } else {
12021 self.fold_recursive(&Default::default(), window, cx)
12022 }
12023 }
12024
12025 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12026 if self.is_singleton(cx) {
12027 let mut to_fold = Vec::new();
12028 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12029 let selections = self.selections.all_adjusted(cx);
12030
12031 for selection in selections {
12032 let range = selection.range().sorted();
12033 let buffer_start_row = range.start.row;
12034
12035 if range.start.row != range.end.row {
12036 let mut found = false;
12037 let mut row = range.start.row;
12038 while row <= range.end.row {
12039 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12040 {
12041 found = true;
12042 row = crease.range().end.row + 1;
12043 to_fold.push(crease);
12044 } else {
12045 row += 1
12046 }
12047 }
12048 if found {
12049 continue;
12050 }
12051 }
12052
12053 for row in (0..=range.start.row).rev() {
12054 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12055 if crease.range().end.row >= buffer_start_row {
12056 to_fold.push(crease);
12057 if row <= range.start.row {
12058 break;
12059 }
12060 }
12061 }
12062 }
12063 }
12064
12065 self.fold_creases(to_fold, true, window, cx);
12066 } else {
12067 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12068
12069 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12070 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12071 .map(|(snapshot, _, _)| snapshot.remote_id())
12072 .collect();
12073 for buffer_id in buffer_ids {
12074 self.fold_buffer(buffer_id, cx);
12075 }
12076 }
12077 }
12078
12079 fn fold_at_level(
12080 &mut self,
12081 fold_at: &FoldAtLevel,
12082 window: &mut Window,
12083 cx: &mut Context<Self>,
12084 ) {
12085 if !self.buffer.read(cx).is_singleton() {
12086 return;
12087 }
12088
12089 let fold_at_level = fold_at.0;
12090 let snapshot = self.buffer.read(cx).snapshot(cx);
12091 let mut to_fold = Vec::new();
12092 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12093
12094 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12095 while start_row < end_row {
12096 match self
12097 .snapshot(window, cx)
12098 .crease_for_buffer_row(MultiBufferRow(start_row))
12099 {
12100 Some(crease) => {
12101 let nested_start_row = crease.range().start.row + 1;
12102 let nested_end_row = crease.range().end.row;
12103
12104 if current_level < fold_at_level {
12105 stack.push((nested_start_row, nested_end_row, current_level + 1));
12106 } else if current_level == fold_at_level {
12107 to_fold.push(crease);
12108 }
12109
12110 start_row = nested_end_row + 1;
12111 }
12112 None => start_row += 1,
12113 }
12114 }
12115 }
12116
12117 self.fold_creases(to_fold, true, window, cx);
12118 }
12119
12120 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12121 if self.buffer.read(cx).is_singleton() {
12122 let mut fold_ranges = Vec::new();
12123 let snapshot = self.buffer.read(cx).snapshot(cx);
12124
12125 for row in 0..snapshot.max_row().0 {
12126 if let Some(foldable_range) = self
12127 .snapshot(window, cx)
12128 .crease_for_buffer_row(MultiBufferRow(row))
12129 {
12130 fold_ranges.push(foldable_range);
12131 }
12132 }
12133
12134 self.fold_creases(fold_ranges, true, window, cx);
12135 } else {
12136 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12137 editor
12138 .update_in(&mut cx, |editor, _, cx| {
12139 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12140 editor.fold_buffer(buffer_id, cx);
12141 }
12142 })
12143 .ok();
12144 });
12145 }
12146 }
12147
12148 pub fn fold_function_bodies(
12149 &mut self,
12150 _: &actions::FoldFunctionBodies,
12151 window: &mut Window,
12152 cx: &mut Context<Self>,
12153 ) {
12154 let snapshot = self.buffer.read(cx).snapshot(cx);
12155
12156 let ranges = snapshot
12157 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12158 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12159 .collect::<Vec<_>>();
12160
12161 let creases = ranges
12162 .into_iter()
12163 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12164 .collect();
12165
12166 self.fold_creases(creases, true, window, cx);
12167 }
12168
12169 pub fn fold_recursive(
12170 &mut self,
12171 _: &actions::FoldRecursive,
12172 window: &mut Window,
12173 cx: &mut Context<Self>,
12174 ) {
12175 let mut to_fold = Vec::new();
12176 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12177 let selections = self.selections.all_adjusted(cx);
12178
12179 for selection in selections {
12180 let range = selection.range().sorted();
12181 let buffer_start_row = range.start.row;
12182
12183 if range.start.row != range.end.row {
12184 let mut found = false;
12185 for row in range.start.row..=range.end.row {
12186 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12187 found = true;
12188 to_fold.push(crease);
12189 }
12190 }
12191 if found {
12192 continue;
12193 }
12194 }
12195
12196 for row in (0..=range.start.row).rev() {
12197 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12198 if crease.range().end.row >= buffer_start_row {
12199 to_fold.push(crease);
12200 } else {
12201 break;
12202 }
12203 }
12204 }
12205 }
12206
12207 self.fold_creases(to_fold, true, window, cx);
12208 }
12209
12210 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12211 let buffer_row = fold_at.buffer_row;
12212 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12213
12214 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12215 let autoscroll = self
12216 .selections
12217 .all::<Point>(cx)
12218 .iter()
12219 .any(|selection| crease.range().overlaps(&selection.range()));
12220
12221 self.fold_creases(vec![crease], autoscroll, window, cx);
12222 }
12223 }
12224
12225 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12226 if self.is_singleton(cx) {
12227 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12228 let buffer = &display_map.buffer_snapshot;
12229 let selections = self.selections.all::<Point>(cx);
12230 let ranges = selections
12231 .iter()
12232 .map(|s| {
12233 let range = s.display_range(&display_map).sorted();
12234 let mut start = range.start.to_point(&display_map);
12235 let mut end = range.end.to_point(&display_map);
12236 start.column = 0;
12237 end.column = buffer.line_len(MultiBufferRow(end.row));
12238 start..end
12239 })
12240 .collect::<Vec<_>>();
12241
12242 self.unfold_ranges(&ranges, true, true, cx);
12243 } else {
12244 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12245 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12246 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12247 .map(|(snapshot, _, _)| snapshot.remote_id())
12248 .collect();
12249 for buffer_id in buffer_ids {
12250 self.unfold_buffer(buffer_id, cx);
12251 }
12252 }
12253 }
12254
12255 pub fn unfold_recursive(
12256 &mut self,
12257 _: &UnfoldRecursive,
12258 _window: &mut Window,
12259 cx: &mut Context<Self>,
12260 ) {
12261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12262 let selections = self.selections.all::<Point>(cx);
12263 let ranges = selections
12264 .iter()
12265 .map(|s| {
12266 let mut range = s.display_range(&display_map).sorted();
12267 *range.start.column_mut() = 0;
12268 *range.end.column_mut() = display_map.line_len(range.end.row());
12269 let start = range.start.to_point(&display_map);
12270 let end = range.end.to_point(&display_map);
12271 start..end
12272 })
12273 .collect::<Vec<_>>();
12274
12275 self.unfold_ranges(&ranges, true, true, cx);
12276 }
12277
12278 pub fn unfold_at(
12279 &mut self,
12280 unfold_at: &UnfoldAt,
12281 _window: &mut Window,
12282 cx: &mut Context<Self>,
12283 ) {
12284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12285
12286 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12287 ..Point::new(
12288 unfold_at.buffer_row.0,
12289 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12290 );
12291
12292 let autoscroll = self
12293 .selections
12294 .all::<Point>(cx)
12295 .iter()
12296 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12297
12298 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12299 }
12300
12301 pub fn unfold_all(
12302 &mut self,
12303 _: &actions::UnfoldAll,
12304 _window: &mut Window,
12305 cx: &mut Context<Self>,
12306 ) {
12307 if self.buffer.read(cx).is_singleton() {
12308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12309 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12310 } else {
12311 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12312 editor
12313 .update(&mut cx, |editor, cx| {
12314 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12315 editor.unfold_buffer(buffer_id, cx);
12316 }
12317 })
12318 .ok();
12319 });
12320 }
12321 }
12322
12323 pub fn fold_selected_ranges(
12324 &mut self,
12325 _: &FoldSelectedRanges,
12326 window: &mut Window,
12327 cx: &mut Context<Self>,
12328 ) {
12329 let selections = self.selections.all::<Point>(cx);
12330 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12331 let line_mode = self.selections.line_mode;
12332 let ranges = selections
12333 .into_iter()
12334 .map(|s| {
12335 if line_mode {
12336 let start = Point::new(s.start.row, 0);
12337 let end = Point::new(
12338 s.end.row,
12339 display_map
12340 .buffer_snapshot
12341 .line_len(MultiBufferRow(s.end.row)),
12342 );
12343 Crease::simple(start..end, display_map.fold_placeholder.clone())
12344 } else {
12345 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12346 }
12347 })
12348 .collect::<Vec<_>>();
12349 self.fold_creases(ranges, true, window, cx);
12350 }
12351
12352 pub fn fold_ranges<T: ToOffset + Clone>(
12353 &mut self,
12354 ranges: Vec<Range<T>>,
12355 auto_scroll: bool,
12356 window: &mut Window,
12357 cx: &mut Context<Self>,
12358 ) {
12359 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12360 let ranges = ranges
12361 .into_iter()
12362 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12363 .collect::<Vec<_>>();
12364 self.fold_creases(ranges, auto_scroll, window, cx);
12365 }
12366
12367 pub fn fold_creases<T: ToOffset + Clone>(
12368 &mut self,
12369 creases: Vec<Crease<T>>,
12370 auto_scroll: bool,
12371 window: &mut Window,
12372 cx: &mut Context<Self>,
12373 ) {
12374 if creases.is_empty() {
12375 return;
12376 }
12377
12378 let mut buffers_affected = HashSet::default();
12379 let multi_buffer = self.buffer().read(cx);
12380 for crease in &creases {
12381 if let Some((_, buffer, _)) =
12382 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12383 {
12384 buffers_affected.insert(buffer.read(cx).remote_id());
12385 };
12386 }
12387
12388 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12389
12390 if auto_scroll {
12391 self.request_autoscroll(Autoscroll::fit(), cx);
12392 }
12393
12394 cx.notify();
12395
12396 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12397 // Clear diagnostics block when folding a range that contains it.
12398 let snapshot = self.snapshot(window, cx);
12399 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12400 drop(snapshot);
12401 self.active_diagnostics = Some(active_diagnostics);
12402 self.dismiss_diagnostics(cx);
12403 } else {
12404 self.active_diagnostics = Some(active_diagnostics);
12405 }
12406 }
12407
12408 self.scrollbar_marker_state.dirty = true;
12409 }
12410
12411 /// Removes any folds whose ranges intersect any of the given ranges.
12412 pub fn unfold_ranges<T: ToOffset + Clone>(
12413 &mut self,
12414 ranges: &[Range<T>],
12415 inclusive: bool,
12416 auto_scroll: bool,
12417 cx: &mut Context<Self>,
12418 ) {
12419 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12420 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12421 });
12422 }
12423
12424 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12425 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12426 return;
12427 }
12428 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12429 self.display_map
12430 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12431 cx.emit(EditorEvent::BufferFoldToggled {
12432 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12433 folded: true,
12434 });
12435 cx.notify();
12436 }
12437
12438 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12439 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12440 return;
12441 }
12442 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12443 self.display_map.update(cx, |display_map, cx| {
12444 display_map.unfold_buffer(buffer_id, cx);
12445 });
12446 cx.emit(EditorEvent::BufferFoldToggled {
12447 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12448 folded: false,
12449 });
12450 cx.notify();
12451 }
12452
12453 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12454 self.display_map.read(cx).is_buffer_folded(buffer)
12455 }
12456
12457 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12458 self.display_map.read(cx).folded_buffers()
12459 }
12460
12461 /// Removes any folds with the given ranges.
12462 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12463 &mut self,
12464 ranges: &[Range<T>],
12465 type_id: TypeId,
12466 auto_scroll: bool,
12467 cx: &mut Context<Self>,
12468 ) {
12469 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12470 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12471 });
12472 }
12473
12474 fn remove_folds_with<T: ToOffset + Clone>(
12475 &mut self,
12476 ranges: &[Range<T>],
12477 auto_scroll: bool,
12478 cx: &mut Context<Self>,
12479 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12480 ) {
12481 if ranges.is_empty() {
12482 return;
12483 }
12484
12485 let mut buffers_affected = HashSet::default();
12486 let multi_buffer = self.buffer().read(cx);
12487 for range in ranges {
12488 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12489 buffers_affected.insert(buffer.read(cx).remote_id());
12490 };
12491 }
12492
12493 self.display_map.update(cx, update);
12494
12495 if auto_scroll {
12496 self.request_autoscroll(Autoscroll::fit(), cx);
12497 }
12498
12499 cx.notify();
12500 self.scrollbar_marker_state.dirty = true;
12501 self.active_indent_guides_state.dirty = true;
12502 }
12503
12504 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12505 self.display_map.read(cx).fold_placeholder.clone()
12506 }
12507
12508 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12509 self.buffer.update(cx, |buffer, cx| {
12510 buffer.set_all_diff_hunks_expanded(cx);
12511 });
12512 }
12513
12514 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12515 self.distinguish_unstaged_diff_hunks = true;
12516 }
12517
12518 pub fn expand_all_diff_hunks(
12519 &mut self,
12520 _: &ExpandAllHunkDiffs,
12521 _window: &mut Window,
12522 cx: &mut Context<Self>,
12523 ) {
12524 self.buffer.update(cx, |buffer, cx| {
12525 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12526 });
12527 }
12528
12529 pub fn toggle_selected_diff_hunks(
12530 &mut self,
12531 _: &ToggleSelectedDiffHunks,
12532 _window: &mut Window,
12533 cx: &mut Context<Self>,
12534 ) {
12535 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12536 self.toggle_diff_hunks_in_ranges(ranges, cx);
12537 }
12538
12539 fn diff_hunks_in_ranges<'a>(
12540 &'a self,
12541 ranges: &'a [Range<Anchor>],
12542 buffer: &'a MultiBufferSnapshot,
12543 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12544 ranges.iter().flat_map(move |range| {
12545 let end_excerpt_id = range.end.excerpt_id;
12546 let range = range.to_point(buffer);
12547 let mut peek_end = range.end;
12548 if range.end.row < buffer.max_row().0 {
12549 peek_end = Point::new(range.end.row + 1, 0);
12550 }
12551 buffer
12552 .diff_hunks_in_range(range.start..peek_end)
12553 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12554 })
12555 }
12556
12557 pub fn has_stageable_diff_hunks_in_ranges(
12558 &self,
12559 ranges: &[Range<Anchor>],
12560 snapshot: &MultiBufferSnapshot,
12561 ) -> bool {
12562 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12563 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12564 }
12565
12566 pub fn toggle_staged_selected_diff_hunks(
12567 &mut self,
12568 _: &ToggleStagedSelectedDiffHunks,
12569 _window: &mut Window,
12570 cx: &mut Context<Self>,
12571 ) {
12572 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12573 self.stage_or_unstage_diff_hunks(&ranges, cx);
12574 }
12575
12576 pub fn stage_or_unstage_diff_hunks(
12577 &mut self,
12578 ranges: &[Range<Anchor>],
12579 cx: &mut Context<Self>,
12580 ) {
12581 let Some(project) = &self.project else {
12582 return;
12583 };
12584 let snapshot = self.buffer.read(cx).snapshot(cx);
12585 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12586
12587 let chunk_by = self
12588 .diff_hunks_in_ranges(&ranges, &snapshot)
12589 .chunk_by(|hunk| hunk.buffer_id);
12590 for (buffer_id, hunks) in &chunk_by {
12591 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12592 log::debug!("no buffer for id");
12593 continue;
12594 };
12595 let buffer = buffer.read(cx).snapshot();
12596 let Some((repo, path)) = project
12597 .read(cx)
12598 .repository_and_path_for_buffer_id(buffer_id, cx)
12599 else {
12600 log::debug!("no git repo for buffer id");
12601 continue;
12602 };
12603 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12604 log::debug!("no diff for buffer id");
12605 continue;
12606 };
12607 let Some(secondary_diff) = diff.secondary_diff() else {
12608 log::debug!("no secondary diff for buffer id");
12609 continue;
12610 };
12611
12612 let edits = diff.secondary_edits_for_stage_or_unstage(
12613 stage,
12614 hunks.map(|hunk| {
12615 (
12616 hunk.diff_base_byte_range.clone(),
12617 hunk.secondary_diff_base_byte_range.clone(),
12618 hunk.buffer_range.clone(),
12619 )
12620 }),
12621 &buffer,
12622 );
12623
12624 let index_base = secondary_diff.base_text().map_or_else(
12625 || Rope::from(""),
12626 |snapshot| snapshot.text.as_rope().clone(),
12627 );
12628 let index_buffer = cx.new(|cx| {
12629 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12630 });
12631 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12632 index_buffer.edit(edits, None, cx);
12633 index_buffer.snapshot().as_rope().to_string()
12634 });
12635 let new_index_text = if new_index_text.is_empty()
12636 && (diff.is_single_insertion
12637 || buffer
12638 .file()
12639 .map_or(false, |file| file.disk_state() == DiskState::New))
12640 {
12641 log::debug!("removing from index");
12642 None
12643 } else {
12644 Some(new_index_text)
12645 };
12646
12647 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12648 }
12649 }
12650
12651 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12652 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12653 self.buffer
12654 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12655 }
12656
12657 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12658 self.buffer.update(cx, |buffer, cx| {
12659 let ranges = vec![Anchor::min()..Anchor::max()];
12660 if !buffer.all_diff_hunks_expanded()
12661 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12662 {
12663 buffer.collapse_diff_hunks(ranges, cx);
12664 true
12665 } else {
12666 false
12667 }
12668 })
12669 }
12670
12671 fn toggle_diff_hunks_in_ranges(
12672 &mut self,
12673 ranges: Vec<Range<Anchor>>,
12674 cx: &mut Context<'_, Editor>,
12675 ) {
12676 self.buffer.update(cx, |buffer, cx| {
12677 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12678 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12679 })
12680 }
12681
12682 fn toggle_diff_hunks_in_ranges_narrow(
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_narrow(ranges, expand, cx);
12690 })
12691 }
12692
12693 pub(crate) fn apply_all_diff_hunks(
12694 &mut self,
12695 _: &ApplyAllDiffHunks,
12696 window: &mut Window,
12697 cx: &mut Context<Self>,
12698 ) {
12699 let buffers = self.buffer.read(cx).all_buffers();
12700 for branch_buffer in buffers {
12701 branch_buffer.update(cx, |branch_buffer, cx| {
12702 branch_buffer.merge_into_base(Vec::new(), cx);
12703 });
12704 }
12705
12706 if let Some(project) = self.project.clone() {
12707 self.save(true, project, window, cx).detach_and_log_err(cx);
12708 }
12709 }
12710
12711 pub(crate) fn apply_selected_diff_hunks(
12712 &mut self,
12713 _: &ApplyDiffHunk,
12714 window: &mut Window,
12715 cx: &mut Context<Self>,
12716 ) {
12717 let snapshot = self.snapshot(window, cx);
12718 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12719 let mut ranges_by_buffer = HashMap::default();
12720 self.transact(window, cx, |editor, _window, cx| {
12721 for hunk in hunks {
12722 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12723 ranges_by_buffer
12724 .entry(buffer.clone())
12725 .or_insert_with(Vec::new)
12726 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12727 }
12728 }
12729
12730 for (buffer, ranges) in ranges_by_buffer {
12731 buffer.update(cx, |buffer, cx| {
12732 buffer.merge_into_base(ranges, cx);
12733 });
12734 }
12735 });
12736
12737 if let Some(project) = self.project.clone() {
12738 self.save(true, project, window, cx).detach_and_log_err(cx);
12739 }
12740 }
12741
12742 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12743 if hovered != self.gutter_hovered {
12744 self.gutter_hovered = hovered;
12745 cx.notify();
12746 }
12747 }
12748
12749 pub fn insert_blocks(
12750 &mut self,
12751 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12752 autoscroll: Option<Autoscroll>,
12753 cx: &mut Context<Self>,
12754 ) -> Vec<CustomBlockId> {
12755 let blocks = self
12756 .display_map
12757 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12758 if let Some(autoscroll) = autoscroll {
12759 self.request_autoscroll(autoscroll, cx);
12760 }
12761 cx.notify();
12762 blocks
12763 }
12764
12765 pub fn resize_blocks(
12766 &mut self,
12767 heights: HashMap<CustomBlockId, u32>,
12768 autoscroll: Option<Autoscroll>,
12769 cx: &mut Context<Self>,
12770 ) {
12771 self.display_map
12772 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12773 if let Some(autoscroll) = autoscroll {
12774 self.request_autoscroll(autoscroll, cx);
12775 }
12776 cx.notify();
12777 }
12778
12779 pub fn replace_blocks(
12780 &mut self,
12781 renderers: HashMap<CustomBlockId, RenderBlock>,
12782 autoscroll: Option<Autoscroll>,
12783 cx: &mut Context<Self>,
12784 ) {
12785 self.display_map
12786 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12787 if let Some(autoscroll) = autoscroll {
12788 self.request_autoscroll(autoscroll, cx);
12789 }
12790 cx.notify();
12791 }
12792
12793 pub fn remove_blocks(
12794 &mut self,
12795 block_ids: HashSet<CustomBlockId>,
12796 autoscroll: Option<Autoscroll>,
12797 cx: &mut Context<Self>,
12798 ) {
12799 self.display_map.update(cx, |display_map, cx| {
12800 display_map.remove_blocks(block_ids, cx)
12801 });
12802 if let Some(autoscroll) = autoscroll {
12803 self.request_autoscroll(autoscroll, cx);
12804 }
12805 cx.notify();
12806 }
12807
12808 pub fn row_for_block(
12809 &self,
12810 block_id: CustomBlockId,
12811 cx: &mut Context<Self>,
12812 ) -> Option<DisplayRow> {
12813 self.display_map
12814 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12815 }
12816
12817 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12818 self.focused_block = Some(focused_block);
12819 }
12820
12821 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12822 self.focused_block.take()
12823 }
12824
12825 pub fn insert_creases(
12826 &mut self,
12827 creases: impl IntoIterator<Item = Crease<Anchor>>,
12828 cx: &mut Context<Self>,
12829 ) -> Vec<CreaseId> {
12830 self.display_map
12831 .update(cx, |map, cx| map.insert_creases(creases, cx))
12832 }
12833
12834 pub fn remove_creases(
12835 &mut self,
12836 ids: impl IntoIterator<Item = CreaseId>,
12837 cx: &mut Context<Self>,
12838 ) {
12839 self.display_map
12840 .update(cx, |map, cx| map.remove_creases(ids, cx));
12841 }
12842
12843 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12844 self.display_map
12845 .update(cx, |map, cx| map.snapshot(cx))
12846 .longest_row()
12847 }
12848
12849 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12850 self.display_map
12851 .update(cx, |map, cx| map.snapshot(cx))
12852 .max_point()
12853 }
12854
12855 pub fn text(&self, cx: &App) -> String {
12856 self.buffer.read(cx).read(cx).text()
12857 }
12858
12859 pub fn is_empty(&self, cx: &App) -> bool {
12860 self.buffer.read(cx).read(cx).is_empty()
12861 }
12862
12863 pub fn text_option(&self, cx: &App) -> Option<String> {
12864 let text = self.text(cx);
12865 let text = text.trim();
12866
12867 if text.is_empty() {
12868 return None;
12869 }
12870
12871 Some(text.to_string())
12872 }
12873
12874 pub fn set_text(
12875 &mut self,
12876 text: impl Into<Arc<str>>,
12877 window: &mut Window,
12878 cx: &mut Context<Self>,
12879 ) {
12880 self.transact(window, cx, |this, _, cx| {
12881 this.buffer
12882 .read(cx)
12883 .as_singleton()
12884 .expect("you can only call set_text on editors for singleton buffers")
12885 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12886 });
12887 }
12888
12889 pub fn display_text(&self, cx: &mut App) -> String {
12890 self.display_map
12891 .update(cx, |map, cx| map.snapshot(cx))
12892 .text()
12893 }
12894
12895 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12896 let mut wrap_guides = smallvec::smallvec![];
12897
12898 if self.show_wrap_guides == Some(false) {
12899 return wrap_guides;
12900 }
12901
12902 let settings = self.buffer.read(cx).settings_at(0, cx);
12903 if settings.show_wrap_guides {
12904 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12905 wrap_guides.push((soft_wrap as usize, true));
12906 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12907 wrap_guides.push((soft_wrap as usize, true));
12908 }
12909 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12910 }
12911
12912 wrap_guides
12913 }
12914
12915 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12916 let settings = self.buffer.read(cx).settings_at(0, cx);
12917 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12918 match mode {
12919 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12920 SoftWrap::None
12921 }
12922 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12923 language_settings::SoftWrap::PreferredLineLength => {
12924 SoftWrap::Column(settings.preferred_line_length)
12925 }
12926 language_settings::SoftWrap::Bounded => {
12927 SoftWrap::Bounded(settings.preferred_line_length)
12928 }
12929 }
12930 }
12931
12932 pub fn set_soft_wrap_mode(
12933 &mut self,
12934 mode: language_settings::SoftWrap,
12935
12936 cx: &mut Context<Self>,
12937 ) {
12938 self.soft_wrap_mode_override = Some(mode);
12939 cx.notify();
12940 }
12941
12942 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12943 self.text_style_refinement = Some(style);
12944 }
12945
12946 /// called by the Element so we know what style we were most recently rendered with.
12947 pub(crate) fn set_style(
12948 &mut self,
12949 style: EditorStyle,
12950 window: &mut Window,
12951 cx: &mut Context<Self>,
12952 ) {
12953 let rem_size = window.rem_size();
12954 self.display_map.update(cx, |map, cx| {
12955 map.set_font(
12956 style.text.font(),
12957 style.text.font_size.to_pixels(rem_size),
12958 cx,
12959 )
12960 });
12961 self.style = Some(style);
12962 }
12963
12964 pub fn style(&self) -> Option<&EditorStyle> {
12965 self.style.as_ref()
12966 }
12967
12968 // Called by the element. This method is not designed to be called outside of the editor
12969 // element's layout code because it does not notify when rewrapping is computed synchronously.
12970 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12971 self.display_map
12972 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12973 }
12974
12975 pub fn set_soft_wrap(&mut self) {
12976 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12977 }
12978
12979 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12980 if self.soft_wrap_mode_override.is_some() {
12981 self.soft_wrap_mode_override.take();
12982 } else {
12983 let soft_wrap = match self.soft_wrap_mode(cx) {
12984 SoftWrap::GitDiff => return,
12985 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12986 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12987 language_settings::SoftWrap::None
12988 }
12989 };
12990 self.soft_wrap_mode_override = Some(soft_wrap);
12991 }
12992 cx.notify();
12993 }
12994
12995 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12996 let Some(workspace) = self.workspace() else {
12997 return;
12998 };
12999 let fs = workspace.read(cx).app_state().fs.clone();
13000 let current_show = TabBarSettings::get_global(cx).show;
13001 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13002 setting.show = Some(!current_show);
13003 });
13004 }
13005
13006 pub fn toggle_indent_guides(
13007 &mut self,
13008 _: &ToggleIndentGuides,
13009 _: &mut Window,
13010 cx: &mut Context<Self>,
13011 ) {
13012 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13013 self.buffer
13014 .read(cx)
13015 .settings_at(0, cx)
13016 .indent_guides
13017 .enabled
13018 });
13019 self.show_indent_guides = Some(!currently_enabled);
13020 cx.notify();
13021 }
13022
13023 fn should_show_indent_guides(&self) -> Option<bool> {
13024 self.show_indent_guides
13025 }
13026
13027 pub fn toggle_line_numbers(
13028 &mut self,
13029 _: &ToggleLineNumbers,
13030 _: &mut Window,
13031 cx: &mut Context<Self>,
13032 ) {
13033 let mut editor_settings = EditorSettings::get_global(cx).clone();
13034 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13035 EditorSettings::override_global(editor_settings, cx);
13036 }
13037
13038 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13039 self.use_relative_line_numbers
13040 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13041 }
13042
13043 pub fn toggle_relative_line_numbers(
13044 &mut self,
13045 _: &ToggleRelativeLineNumbers,
13046 _: &mut Window,
13047 cx: &mut Context<Self>,
13048 ) {
13049 let is_relative = self.should_use_relative_line_numbers(cx);
13050 self.set_relative_line_number(Some(!is_relative), cx)
13051 }
13052
13053 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13054 self.use_relative_line_numbers = is_relative;
13055 cx.notify();
13056 }
13057
13058 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13059 self.show_gutter = show_gutter;
13060 cx.notify();
13061 }
13062
13063 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13064 self.show_scrollbars = show_scrollbars;
13065 cx.notify();
13066 }
13067
13068 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13069 self.show_line_numbers = Some(show_line_numbers);
13070 cx.notify();
13071 }
13072
13073 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13074 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13075 cx.notify();
13076 }
13077
13078 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13079 self.show_code_actions = Some(show_code_actions);
13080 cx.notify();
13081 }
13082
13083 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13084 self.show_runnables = Some(show_runnables);
13085 cx.notify();
13086 }
13087
13088 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13089 if self.display_map.read(cx).masked != masked {
13090 self.display_map.update(cx, |map, _| map.masked = masked);
13091 }
13092 cx.notify()
13093 }
13094
13095 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13096 self.show_wrap_guides = Some(show_wrap_guides);
13097 cx.notify();
13098 }
13099
13100 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13101 self.show_indent_guides = Some(show_indent_guides);
13102 cx.notify();
13103 }
13104
13105 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13106 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13107 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13108 if let Some(dir) = file.abs_path(cx).parent() {
13109 return Some(dir.to_owned());
13110 }
13111 }
13112
13113 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13114 return Some(project_path.path.to_path_buf());
13115 }
13116 }
13117
13118 None
13119 }
13120
13121 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13122 self.active_excerpt(cx)?
13123 .1
13124 .read(cx)
13125 .file()
13126 .and_then(|f| f.as_local())
13127 }
13128
13129 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13130 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13131 let buffer = buffer.read(cx);
13132 if let Some(project_path) = buffer.project_path(cx) {
13133 let project = self.project.as_ref()?.read(cx);
13134 project.absolute_path(&project_path, cx)
13135 } else {
13136 buffer
13137 .file()
13138 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13139 }
13140 })
13141 }
13142
13143 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13144 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13145 let project_path = buffer.read(cx).project_path(cx)?;
13146 let project = self.project.as_ref()?.read(cx);
13147 let entry = project.entry_for_path(&project_path, cx)?;
13148 let path = entry.path.to_path_buf();
13149 Some(path)
13150 })
13151 }
13152
13153 pub fn reveal_in_finder(
13154 &mut self,
13155 _: &RevealInFileManager,
13156 _window: &mut Window,
13157 cx: &mut Context<Self>,
13158 ) {
13159 if let Some(target) = self.target_file(cx) {
13160 cx.reveal_path(&target.abs_path(cx));
13161 }
13162 }
13163
13164 pub fn copy_path(
13165 &mut self,
13166 _: &zed_actions::workspace::CopyPath,
13167 _window: &mut Window,
13168 cx: &mut Context<Self>,
13169 ) {
13170 if let Some(path) = self.target_file_abs_path(cx) {
13171 if let Some(path) = path.to_str() {
13172 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13173 }
13174 }
13175 }
13176
13177 pub fn copy_relative_path(
13178 &mut self,
13179 _: &zed_actions::workspace::CopyRelativePath,
13180 _window: &mut Window,
13181 cx: &mut Context<Self>,
13182 ) {
13183 if let Some(path) = self.target_file_path(cx) {
13184 if let Some(path) = path.to_str() {
13185 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13186 }
13187 }
13188 }
13189
13190 pub fn copy_file_name_without_extension(
13191 &mut self,
13192 _: &CopyFileNameWithoutExtension,
13193 _: &mut Window,
13194 cx: &mut Context<Self>,
13195 ) {
13196 if let Some(file) = self.target_file(cx) {
13197 if let Some(file_stem) = file.path().file_stem() {
13198 if let Some(name) = file_stem.to_str() {
13199 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13200 }
13201 }
13202 }
13203 }
13204
13205 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13206 if let Some(file) = self.target_file(cx) {
13207 if let Some(file_name) = file.path().file_name() {
13208 if let Some(name) = file_name.to_str() {
13209 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13210 }
13211 }
13212 }
13213 }
13214
13215 pub fn toggle_git_blame(
13216 &mut self,
13217 _: &ToggleGitBlame,
13218 window: &mut Window,
13219 cx: &mut Context<Self>,
13220 ) {
13221 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13222
13223 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13224 self.start_git_blame(true, window, cx);
13225 }
13226
13227 cx.notify();
13228 }
13229
13230 pub fn toggle_git_blame_inline(
13231 &mut self,
13232 _: &ToggleGitBlameInline,
13233 window: &mut Window,
13234 cx: &mut Context<Self>,
13235 ) {
13236 self.toggle_git_blame_inline_internal(true, window, cx);
13237 cx.notify();
13238 }
13239
13240 pub fn git_blame_inline_enabled(&self) -> bool {
13241 self.git_blame_inline_enabled
13242 }
13243
13244 pub fn toggle_selection_menu(
13245 &mut self,
13246 _: &ToggleSelectionMenu,
13247 _: &mut Window,
13248 cx: &mut Context<Self>,
13249 ) {
13250 self.show_selection_menu = self
13251 .show_selection_menu
13252 .map(|show_selections_menu| !show_selections_menu)
13253 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13254
13255 cx.notify();
13256 }
13257
13258 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13259 self.show_selection_menu
13260 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13261 }
13262
13263 fn start_git_blame(
13264 &mut self,
13265 user_triggered: bool,
13266 window: &mut Window,
13267 cx: &mut Context<Self>,
13268 ) {
13269 if let Some(project) = self.project.as_ref() {
13270 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13271 return;
13272 };
13273
13274 if buffer.read(cx).file().is_none() {
13275 return;
13276 }
13277
13278 let focused = self.focus_handle(cx).contains_focused(window, cx);
13279
13280 let project = project.clone();
13281 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13282 self.blame_subscription =
13283 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13284 self.blame = Some(blame);
13285 }
13286 }
13287
13288 fn toggle_git_blame_inline_internal(
13289 &mut self,
13290 user_triggered: bool,
13291 window: &mut Window,
13292 cx: &mut Context<Self>,
13293 ) {
13294 if self.git_blame_inline_enabled {
13295 self.git_blame_inline_enabled = false;
13296 self.show_git_blame_inline = false;
13297 self.show_git_blame_inline_delay_task.take();
13298 } else {
13299 self.git_blame_inline_enabled = true;
13300 self.start_git_blame_inline(user_triggered, window, cx);
13301 }
13302
13303 cx.notify();
13304 }
13305
13306 fn start_git_blame_inline(
13307 &mut self,
13308 user_triggered: bool,
13309 window: &mut Window,
13310 cx: &mut Context<Self>,
13311 ) {
13312 self.start_git_blame(user_triggered, window, cx);
13313
13314 if ProjectSettings::get_global(cx)
13315 .git
13316 .inline_blame_delay()
13317 .is_some()
13318 {
13319 self.start_inline_blame_timer(window, cx);
13320 } else {
13321 self.show_git_blame_inline = true
13322 }
13323 }
13324
13325 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13326 self.blame.as_ref()
13327 }
13328
13329 pub fn show_git_blame_gutter(&self) -> bool {
13330 self.show_git_blame_gutter
13331 }
13332
13333 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13334 self.show_git_blame_gutter && self.has_blame_entries(cx)
13335 }
13336
13337 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13338 self.show_git_blame_inline
13339 && self.focus_handle.is_focused(window)
13340 && !self.newest_selection_head_on_empty_line(cx)
13341 && self.has_blame_entries(cx)
13342 }
13343
13344 fn has_blame_entries(&self, cx: &App) -> bool {
13345 self.blame()
13346 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13347 }
13348
13349 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13350 let cursor_anchor = self.selections.newest_anchor().head();
13351
13352 let snapshot = self.buffer.read(cx).snapshot(cx);
13353 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13354
13355 snapshot.line_len(buffer_row) == 0
13356 }
13357
13358 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13359 let buffer_and_selection = maybe!({
13360 let selection = self.selections.newest::<Point>(cx);
13361 let selection_range = selection.range();
13362
13363 let multi_buffer = self.buffer().read(cx);
13364 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13365 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13366
13367 let (buffer, range, _) = if selection.reversed {
13368 buffer_ranges.first()
13369 } else {
13370 buffer_ranges.last()
13371 }?;
13372
13373 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13374 ..text::ToPoint::to_point(&range.end, &buffer).row;
13375 Some((
13376 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13377 selection,
13378 ))
13379 });
13380
13381 let Some((buffer, selection)) = buffer_and_selection else {
13382 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13383 };
13384
13385 let Some(project) = self.project.as_ref() else {
13386 return Task::ready(Err(anyhow!("editor does not have project")));
13387 };
13388
13389 project.update(cx, |project, cx| {
13390 project.get_permalink_to_line(&buffer, selection, cx)
13391 })
13392 }
13393
13394 pub fn copy_permalink_to_line(
13395 &mut self,
13396 _: &CopyPermalinkToLine,
13397 window: &mut Window,
13398 cx: &mut Context<Self>,
13399 ) {
13400 let permalink_task = self.get_permalink_to_line(cx);
13401 let workspace = self.workspace();
13402
13403 cx.spawn_in(window, |_, mut cx| async move {
13404 match permalink_task.await {
13405 Ok(permalink) => {
13406 cx.update(|_, cx| {
13407 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13408 })
13409 .ok();
13410 }
13411 Err(err) => {
13412 let message = format!("Failed to copy permalink: {err}");
13413
13414 Err::<(), anyhow::Error>(err).log_err();
13415
13416 if let Some(workspace) = workspace {
13417 workspace
13418 .update_in(&mut cx, |workspace, _, cx| {
13419 struct CopyPermalinkToLine;
13420
13421 workspace.show_toast(
13422 Toast::new(
13423 NotificationId::unique::<CopyPermalinkToLine>(),
13424 message,
13425 ),
13426 cx,
13427 )
13428 })
13429 .ok();
13430 }
13431 }
13432 }
13433 })
13434 .detach();
13435 }
13436
13437 pub fn copy_file_location(
13438 &mut self,
13439 _: &CopyFileLocation,
13440 _: &mut Window,
13441 cx: &mut Context<Self>,
13442 ) {
13443 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13444 if let Some(file) = self.target_file(cx) {
13445 if let Some(path) = file.path().to_str() {
13446 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13447 }
13448 }
13449 }
13450
13451 pub fn open_permalink_to_line(
13452 &mut self,
13453 _: &OpenPermalinkToLine,
13454 window: &mut Window,
13455 cx: &mut Context<Self>,
13456 ) {
13457 let permalink_task = self.get_permalink_to_line(cx);
13458 let workspace = self.workspace();
13459
13460 cx.spawn_in(window, |_, mut cx| async move {
13461 match permalink_task.await {
13462 Ok(permalink) => {
13463 cx.update(|_, cx| {
13464 cx.open_url(permalink.as_ref());
13465 })
13466 .ok();
13467 }
13468 Err(err) => {
13469 let message = format!("Failed to open permalink: {err}");
13470
13471 Err::<(), anyhow::Error>(err).log_err();
13472
13473 if let Some(workspace) = workspace {
13474 workspace
13475 .update(&mut cx, |workspace, cx| {
13476 struct OpenPermalinkToLine;
13477
13478 workspace.show_toast(
13479 Toast::new(
13480 NotificationId::unique::<OpenPermalinkToLine>(),
13481 message,
13482 ),
13483 cx,
13484 )
13485 })
13486 .ok();
13487 }
13488 }
13489 }
13490 })
13491 .detach();
13492 }
13493
13494 pub fn insert_uuid_v4(
13495 &mut self,
13496 _: &InsertUuidV4,
13497 window: &mut Window,
13498 cx: &mut Context<Self>,
13499 ) {
13500 self.insert_uuid(UuidVersion::V4, window, cx);
13501 }
13502
13503 pub fn insert_uuid_v7(
13504 &mut self,
13505 _: &InsertUuidV7,
13506 window: &mut Window,
13507 cx: &mut Context<Self>,
13508 ) {
13509 self.insert_uuid(UuidVersion::V7, window, cx);
13510 }
13511
13512 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13513 self.transact(window, cx, |this, window, cx| {
13514 let edits = this
13515 .selections
13516 .all::<Point>(cx)
13517 .into_iter()
13518 .map(|selection| {
13519 let uuid = match version {
13520 UuidVersion::V4 => uuid::Uuid::new_v4(),
13521 UuidVersion::V7 => uuid::Uuid::now_v7(),
13522 };
13523
13524 (selection.range(), uuid.to_string())
13525 });
13526 this.edit(edits, cx);
13527 this.refresh_inline_completion(true, false, window, cx);
13528 });
13529 }
13530
13531 pub fn open_selections_in_multibuffer(
13532 &mut self,
13533 _: &OpenSelectionsInMultibuffer,
13534 window: &mut Window,
13535 cx: &mut Context<Self>,
13536 ) {
13537 let multibuffer = self.buffer.read(cx);
13538
13539 let Some(buffer) = multibuffer.as_singleton() else {
13540 return;
13541 };
13542
13543 let Some(workspace) = self.workspace() else {
13544 return;
13545 };
13546
13547 let locations = self
13548 .selections
13549 .disjoint_anchors()
13550 .iter()
13551 .map(|range| Location {
13552 buffer: buffer.clone(),
13553 range: range.start.text_anchor..range.end.text_anchor,
13554 })
13555 .collect::<Vec<_>>();
13556
13557 let title = multibuffer.title(cx).to_string();
13558
13559 cx.spawn_in(window, |_, mut cx| async move {
13560 workspace.update_in(&mut cx, |workspace, window, cx| {
13561 Self::open_locations_in_multibuffer(
13562 workspace,
13563 locations,
13564 format!("Selections for '{title}'"),
13565 false,
13566 MultibufferSelectionMode::All,
13567 window,
13568 cx,
13569 );
13570 })
13571 })
13572 .detach();
13573 }
13574
13575 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13576 /// last highlight added will be used.
13577 ///
13578 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13579 pub fn highlight_rows<T: 'static>(
13580 &mut self,
13581 range: Range<Anchor>,
13582 color: Hsla,
13583 should_autoscroll: bool,
13584 cx: &mut Context<Self>,
13585 ) {
13586 let snapshot = self.buffer().read(cx).snapshot(cx);
13587 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13588 let ix = row_highlights.binary_search_by(|highlight| {
13589 Ordering::Equal
13590 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13591 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13592 });
13593
13594 if let Err(mut ix) = ix {
13595 let index = post_inc(&mut self.highlight_order);
13596
13597 // If this range intersects with the preceding highlight, then merge it with
13598 // the preceding highlight. Otherwise insert a new highlight.
13599 let mut merged = false;
13600 if ix > 0 {
13601 let prev_highlight = &mut row_highlights[ix - 1];
13602 if prev_highlight
13603 .range
13604 .end
13605 .cmp(&range.start, &snapshot)
13606 .is_ge()
13607 {
13608 ix -= 1;
13609 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13610 prev_highlight.range.end = range.end;
13611 }
13612 merged = true;
13613 prev_highlight.index = index;
13614 prev_highlight.color = color;
13615 prev_highlight.should_autoscroll = should_autoscroll;
13616 }
13617 }
13618
13619 if !merged {
13620 row_highlights.insert(
13621 ix,
13622 RowHighlight {
13623 range: range.clone(),
13624 index,
13625 color,
13626 should_autoscroll,
13627 },
13628 );
13629 }
13630
13631 // If any of the following highlights intersect with this one, merge them.
13632 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13633 let highlight = &row_highlights[ix];
13634 if next_highlight
13635 .range
13636 .start
13637 .cmp(&highlight.range.end, &snapshot)
13638 .is_le()
13639 {
13640 if next_highlight
13641 .range
13642 .end
13643 .cmp(&highlight.range.end, &snapshot)
13644 .is_gt()
13645 {
13646 row_highlights[ix].range.end = next_highlight.range.end;
13647 }
13648 row_highlights.remove(ix + 1);
13649 } else {
13650 break;
13651 }
13652 }
13653 }
13654 }
13655
13656 /// Remove any highlighted row ranges of the given type that intersect the
13657 /// given ranges.
13658 pub fn remove_highlighted_rows<T: 'static>(
13659 &mut self,
13660 ranges_to_remove: Vec<Range<Anchor>>,
13661 cx: &mut Context<Self>,
13662 ) {
13663 let snapshot = self.buffer().read(cx).snapshot(cx);
13664 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13665 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13666 row_highlights.retain(|highlight| {
13667 while let Some(range_to_remove) = ranges_to_remove.peek() {
13668 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13669 Ordering::Less | Ordering::Equal => {
13670 ranges_to_remove.next();
13671 }
13672 Ordering::Greater => {
13673 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13674 Ordering::Less | Ordering::Equal => {
13675 return false;
13676 }
13677 Ordering::Greater => break,
13678 }
13679 }
13680 }
13681 }
13682
13683 true
13684 })
13685 }
13686
13687 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13688 pub fn clear_row_highlights<T: 'static>(&mut self) {
13689 self.highlighted_rows.remove(&TypeId::of::<T>());
13690 }
13691
13692 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13693 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13694 self.highlighted_rows
13695 .get(&TypeId::of::<T>())
13696 .map_or(&[] as &[_], |vec| vec.as_slice())
13697 .iter()
13698 .map(|highlight| (highlight.range.clone(), highlight.color))
13699 }
13700
13701 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13702 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13703 /// Allows to ignore certain kinds of highlights.
13704 pub fn highlighted_display_rows(
13705 &self,
13706 window: &mut Window,
13707 cx: &mut App,
13708 ) -> BTreeMap<DisplayRow, Hsla> {
13709 let snapshot = self.snapshot(window, cx);
13710 let mut used_highlight_orders = HashMap::default();
13711 self.highlighted_rows
13712 .iter()
13713 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13714 .fold(
13715 BTreeMap::<DisplayRow, Hsla>::new(),
13716 |mut unique_rows, highlight| {
13717 let start = highlight.range.start.to_display_point(&snapshot);
13718 let end = highlight.range.end.to_display_point(&snapshot);
13719 let start_row = start.row().0;
13720 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13721 && end.column() == 0
13722 {
13723 end.row().0.saturating_sub(1)
13724 } else {
13725 end.row().0
13726 };
13727 for row in start_row..=end_row {
13728 let used_index =
13729 used_highlight_orders.entry(row).or_insert(highlight.index);
13730 if highlight.index >= *used_index {
13731 *used_index = highlight.index;
13732 unique_rows.insert(DisplayRow(row), highlight.color);
13733 }
13734 }
13735 unique_rows
13736 },
13737 )
13738 }
13739
13740 pub fn highlighted_display_row_for_autoscroll(
13741 &self,
13742 snapshot: &DisplaySnapshot,
13743 ) -> Option<DisplayRow> {
13744 self.highlighted_rows
13745 .values()
13746 .flat_map(|highlighted_rows| highlighted_rows.iter())
13747 .filter_map(|highlight| {
13748 if highlight.should_autoscroll {
13749 Some(highlight.range.start.to_display_point(snapshot).row())
13750 } else {
13751 None
13752 }
13753 })
13754 .min()
13755 }
13756
13757 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13758 self.highlight_background::<SearchWithinRange>(
13759 ranges,
13760 |colors| colors.editor_document_highlight_read_background,
13761 cx,
13762 )
13763 }
13764
13765 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13766 self.breadcrumb_header = Some(new_header);
13767 }
13768
13769 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13770 self.clear_background_highlights::<SearchWithinRange>(cx);
13771 }
13772
13773 pub fn highlight_background<T: 'static>(
13774 &mut self,
13775 ranges: &[Range<Anchor>],
13776 color_fetcher: fn(&ThemeColors) -> Hsla,
13777 cx: &mut Context<Self>,
13778 ) {
13779 self.background_highlights
13780 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13781 self.scrollbar_marker_state.dirty = true;
13782 cx.notify();
13783 }
13784
13785 pub fn clear_background_highlights<T: 'static>(
13786 &mut self,
13787 cx: &mut Context<Self>,
13788 ) -> Option<BackgroundHighlight> {
13789 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13790 if !text_highlights.1.is_empty() {
13791 self.scrollbar_marker_state.dirty = true;
13792 cx.notify();
13793 }
13794 Some(text_highlights)
13795 }
13796
13797 pub fn highlight_gutter<T: 'static>(
13798 &mut self,
13799 ranges: &[Range<Anchor>],
13800 color_fetcher: fn(&App) -> Hsla,
13801 cx: &mut Context<Self>,
13802 ) {
13803 self.gutter_highlights
13804 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13805 cx.notify();
13806 }
13807
13808 pub fn clear_gutter_highlights<T: 'static>(
13809 &mut self,
13810 cx: &mut Context<Self>,
13811 ) -> Option<GutterHighlight> {
13812 cx.notify();
13813 self.gutter_highlights.remove(&TypeId::of::<T>())
13814 }
13815
13816 #[cfg(feature = "test-support")]
13817 pub fn all_text_background_highlights(
13818 &self,
13819 window: &mut Window,
13820 cx: &mut Context<Self>,
13821 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13822 let snapshot = self.snapshot(window, cx);
13823 let buffer = &snapshot.buffer_snapshot;
13824 let start = buffer.anchor_before(0);
13825 let end = buffer.anchor_after(buffer.len());
13826 let theme = cx.theme().colors();
13827 self.background_highlights_in_range(start..end, &snapshot, theme)
13828 }
13829
13830 #[cfg(feature = "test-support")]
13831 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13832 let snapshot = self.buffer().read(cx).snapshot(cx);
13833
13834 let highlights = self
13835 .background_highlights
13836 .get(&TypeId::of::<items::BufferSearchHighlights>());
13837
13838 if let Some((_color, ranges)) = highlights {
13839 ranges
13840 .iter()
13841 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13842 .collect_vec()
13843 } else {
13844 vec![]
13845 }
13846 }
13847
13848 fn document_highlights_for_position<'a>(
13849 &'a self,
13850 position: Anchor,
13851 buffer: &'a MultiBufferSnapshot,
13852 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13853 let read_highlights = self
13854 .background_highlights
13855 .get(&TypeId::of::<DocumentHighlightRead>())
13856 .map(|h| &h.1);
13857 let write_highlights = self
13858 .background_highlights
13859 .get(&TypeId::of::<DocumentHighlightWrite>())
13860 .map(|h| &h.1);
13861 let left_position = position.bias_left(buffer);
13862 let right_position = position.bias_right(buffer);
13863 read_highlights
13864 .into_iter()
13865 .chain(write_highlights)
13866 .flat_map(move |ranges| {
13867 let start_ix = match ranges.binary_search_by(|probe| {
13868 let cmp = probe.end.cmp(&left_position, buffer);
13869 if cmp.is_ge() {
13870 Ordering::Greater
13871 } else {
13872 Ordering::Less
13873 }
13874 }) {
13875 Ok(i) | Err(i) => i,
13876 };
13877
13878 ranges[start_ix..]
13879 .iter()
13880 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13881 })
13882 }
13883
13884 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13885 self.background_highlights
13886 .get(&TypeId::of::<T>())
13887 .map_or(false, |(_, highlights)| !highlights.is_empty())
13888 }
13889
13890 pub fn background_highlights_in_range(
13891 &self,
13892 search_range: Range<Anchor>,
13893 display_snapshot: &DisplaySnapshot,
13894 theme: &ThemeColors,
13895 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13896 let mut results = Vec::new();
13897 for (color_fetcher, ranges) in self.background_highlights.values() {
13898 let color = color_fetcher(theme);
13899 let start_ix = match ranges.binary_search_by(|probe| {
13900 let cmp = probe
13901 .end
13902 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13903 if cmp.is_gt() {
13904 Ordering::Greater
13905 } else {
13906 Ordering::Less
13907 }
13908 }) {
13909 Ok(i) | Err(i) => i,
13910 };
13911 for range in &ranges[start_ix..] {
13912 if range
13913 .start
13914 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13915 .is_ge()
13916 {
13917 break;
13918 }
13919
13920 let start = range.start.to_display_point(display_snapshot);
13921 let end = range.end.to_display_point(display_snapshot);
13922 results.push((start..end, color))
13923 }
13924 }
13925 results
13926 }
13927
13928 pub fn background_highlight_row_ranges<T: 'static>(
13929 &self,
13930 search_range: Range<Anchor>,
13931 display_snapshot: &DisplaySnapshot,
13932 count: usize,
13933 ) -> Vec<RangeInclusive<DisplayPoint>> {
13934 let mut results = Vec::new();
13935 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13936 return vec![];
13937 };
13938
13939 let start_ix = match ranges.binary_search_by(|probe| {
13940 let cmp = probe
13941 .end
13942 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13943 if cmp.is_gt() {
13944 Ordering::Greater
13945 } else {
13946 Ordering::Less
13947 }
13948 }) {
13949 Ok(i) | Err(i) => i,
13950 };
13951 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13952 if let (Some(start_display), Some(end_display)) = (start, end) {
13953 results.push(
13954 start_display.to_display_point(display_snapshot)
13955 ..=end_display.to_display_point(display_snapshot),
13956 );
13957 }
13958 };
13959 let mut start_row: Option<Point> = None;
13960 let mut end_row: Option<Point> = None;
13961 if ranges.len() > count {
13962 return Vec::new();
13963 }
13964 for range in &ranges[start_ix..] {
13965 if range
13966 .start
13967 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13968 .is_ge()
13969 {
13970 break;
13971 }
13972 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13973 if let Some(current_row) = &end_row {
13974 if end.row == current_row.row {
13975 continue;
13976 }
13977 }
13978 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13979 if start_row.is_none() {
13980 assert_eq!(end_row, None);
13981 start_row = Some(start);
13982 end_row = Some(end);
13983 continue;
13984 }
13985 if let Some(current_end) = end_row.as_mut() {
13986 if start.row > current_end.row + 1 {
13987 push_region(start_row, end_row);
13988 start_row = Some(start);
13989 end_row = Some(end);
13990 } else {
13991 // Merge two hunks.
13992 *current_end = end;
13993 }
13994 } else {
13995 unreachable!();
13996 }
13997 }
13998 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13999 push_region(start_row, end_row);
14000 results
14001 }
14002
14003 pub fn gutter_highlights_in_range(
14004 &self,
14005 search_range: Range<Anchor>,
14006 display_snapshot: &DisplaySnapshot,
14007 cx: &App,
14008 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14009 let mut results = Vec::new();
14010 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14011 let color = color_fetcher(cx);
14012 let start_ix = match ranges.binary_search_by(|probe| {
14013 let cmp = probe
14014 .end
14015 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14016 if cmp.is_gt() {
14017 Ordering::Greater
14018 } else {
14019 Ordering::Less
14020 }
14021 }) {
14022 Ok(i) | Err(i) => i,
14023 };
14024 for range in &ranges[start_ix..] {
14025 if range
14026 .start
14027 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14028 .is_ge()
14029 {
14030 break;
14031 }
14032
14033 let start = range.start.to_display_point(display_snapshot);
14034 let end = range.end.to_display_point(display_snapshot);
14035 results.push((start..end, color))
14036 }
14037 }
14038 results
14039 }
14040
14041 /// Get the text ranges corresponding to the redaction query
14042 pub fn redacted_ranges(
14043 &self,
14044 search_range: Range<Anchor>,
14045 display_snapshot: &DisplaySnapshot,
14046 cx: &App,
14047 ) -> Vec<Range<DisplayPoint>> {
14048 display_snapshot
14049 .buffer_snapshot
14050 .redacted_ranges(search_range, |file| {
14051 if let Some(file) = file {
14052 file.is_private()
14053 && EditorSettings::get(
14054 Some(SettingsLocation {
14055 worktree_id: file.worktree_id(cx),
14056 path: file.path().as_ref(),
14057 }),
14058 cx,
14059 )
14060 .redact_private_values
14061 } else {
14062 false
14063 }
14064 })
14065 .map(|range| {
14066 range.start.to_display_point(display_snapshot)
14067 ..range.end.to_display_point(display_snapshot)
14068 })
14069 .collect()
14070 }
14071
14072 pub fn highlight_text<T: 'static>(
14073 &mut self,
14074 ranges: Vec<Range<Anchor>>,
14075 style: HighlightStyle,
14076 cx: &mut Context<Self>,
14077 ) {
14078 self.display_map.update(cx, |map, _| {
14079 map.highlight_text(TypeId::of::<T>(), ranges, style)
14080 });
14081 cx.notify();
14082 }
14083
14084 pub(crate) fn highlight_inlays<T: 'static>(
14085 &mut self,
14086 highlights: Vec<InlayHighlight>,
14087 style: HighlightStyle,
14088 cx: &mut Context<Self>,
14089 ) {
14090 self.display_map.update(cx, |map, _| {
14091 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14092 });
14093 cx.notify();
14094 }
14095
14096 pub fn text_highlights<'a, T: 'static>(
14097 &'a self,
14098 cx: &'a App,
14099 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14100 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14101 }
14102
14103 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14104 let cleared = self
14105 .display_map
14106 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14107 if cleared {
14108 cx.notify();
14109 }
14110 }
14111
14112 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14113 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14114 && self.focus_handle.is_focused(window)
14115 }
14116
14117 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14118 self.show_cursor_when_unfocused = is_enabled;
14119 cx.notify();
14120 }
14121
14122 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14123 cx.notify();
14124 }
14125
14126 fn on_buffer_event(
14127 &mut self,
14128 multibuffer: &Entity<MultiBuffer>,
14129 event: &multi_buffer::Event,
14130 window: &mut Window,
14131 cx: &mut Context<Self>,
14132 ) {
14133 match event {
14134 multi_buffer::Event::Edited {
14135 singleton_buffer_edited,
14136 edited_buffer: buffer_edited,
14137 } => {
14138 self.scrollbar_marker_state.dirty = true;
14139 self.active_indent_guides_state.dirty = true;
14140 self.refresh_active_diagnostics(cx);
14141 self.refresh_code_actions(window, cx);
14142 if self.has_active_inline_completion() {
14143 self.update_visible_inline_completion(window, cx);
14144 }
14145 if let Some(buffer) = buffer_edited {
14146 let buffer_id = buffer.read(cx).remote_id();
14147 if !self.registered_buffers.contains_key(&buffer_id) {
14148 if let Some(project) = self.project.as_ref() {
14149 project.update(cx, |project, cx| {
14150 self.registered_buffers.insert(
14151 buffer_id,
14152 project.register_buffer_with_language_servers(&buffer, cx),
14153 );
14154 })
14155 }
14156 }
14157 }
14158 cx.emit(EditorEvent::BufferEdited);
14159 cx.emit(SearchEvent::MatchesInvalidated);
14160 if *singleton_buffer_edited {
14161 if let Some(project) = &self.project {
14162 #[allow(clippy::mutable_key_type)]
14163 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14164 multibuffer
14165 .all_buffers()
14166 .into_iter()
14167 .filter_map(|buffer| {
14168 buffer.update(cx, |buffer, cx| {
14169 let language = buffer.language()?;
14170 let should_discard = project.update(cx, |project, cx| {
14171 project.is_local()
14172 && !project.has_language_servers_for(buffer, cx)
14173 });
14174 should_discard.not().then_some(language.clone())
14175 })
14176 })
14177 .collect::<HashSet<_>>()
14178 });
14179 if !languages_affected.is_empty() {
14180 self.refresh_inlay_hints(
14181 InlayHintRefreshReason::BufferEdited(languages_affected),
14182 cx,
14183 );
14184 }
14185 }
14186 }
14187
14188 let Some(project) = &self.project else { return };
14189 let (telemetry, is_via_ssh) = {
14190 let project = project.read(cx);
14191 let telemetry = project.client().telemetry().clone();
14192 let is_via_ssh = project.is_via_ssh();
14193 (telemetry, is_via_ssh)
14194 };
14195 refresh_linked_ranges(self, window, cx);
14196 telemetry.log_edit_event("editor", is_via_ssh);
14197 }
14198 multi_buffer::Event::ExcerptsAdded {
14199 buffer,
14200 predecessor,
14201 excerpts,
14202 } => {
14203 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14204 let buffer_id = buffer.read(cx).remote_id();
14205 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14206 if let Some(project) = &self.project {
14207 get_uncommitted_diff_for_buffer(
14208 project,
14209 [buffer.clone()],
14210 self.buffer.clone(),
14211 cx,
14212 )
14213 .detach();
14214 }
14215 }
14216 cx.emit(EditorEvent::ExcerptsAdded {
14217 buffer: buffer.clone(),
14218 predecessor: *predecessor,
14219 excerpts: excerpts.clone(),
14220 });
14221 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14222 }
14223 multi_buffer::Event::ExcerptsRemoved { ids } => {
14224 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14225 let buffer = self.buffer.read(cx);
14226 self.registered_buffers
14227 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14228 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14229 }
14230 multi_buffer::Event::ExcerptsEdited { ids } => {
14231 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14232 }
14233 multi_buffer::Event::ExcerptsExpanded { ids } => {
14234 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14235 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14236 }
14237 multi_buffer::Event::Reparsed(buffer_id) => {
14238 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14239
14240 cx.emit(EditorEvent::Reparsed(*buffer_id));
14241 }
14242 multi_buffer::Event::DiffHunksToggled => {
14243 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14244 }
14245 multi_buffer::Event::LanguageChanged(buffer_id) => {
14246 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14247 cx.emit(EditorEvent::Reparsed(*buffer_id));
14248 cx.notify();
14249 }
14250 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14251 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14252 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14253 cx.emit(EditorEvent::TitleChanged)
14254 }
14255 // multi_buffer::Event::DiffBaseChanged => {
14256 // self.scrollbar_marker_state.dirty = true;
14257 // cx.emit(EditorEvent::DiffBaseChanged);
14258 // cx.notify();
14259 // }
14260 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14261 multi_buffer::Event::DiagnosticsUpdated => {
14262 self.refresh_active_diagnostics(cx);
14263 self.scrollbar_marker_state.dirty = true;
14264 cx.notify();
14265 }
14266 _ => {}
14267 };
14268 }
14269
14270 fn on_display_map_changed(
14271 &mut self,
14272 _: Entity<DisplayMap>,
14273 _: &mut Window,
14274 cx: &mut Context<Self>,
14275 ) {
14276 cx.notify();
14277 }
14278
14279 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14280 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14281 self.refresh_inline_completion(true, false, window, cx);
14282 self.refresh_inlay_hints(
14283 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14284 self.selections.newest_anchor().head(),
14285 &self.buffer.read(cx).snapshot(cx),
14286 cx,
14287 )),
14288 cx,
14289 );
14290
14291 let old_cursor_shape = self.cursor_shape;
14292
14293 {
14294 let editor_settings = EditorSettings::get_global(cx);
14295 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14296 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14297 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14298 }
14299
14300 if old_cursor_shape != self.cursor_shape {
14301 cx.emit(EditorEvent::CursorShapeChanged);
14302 }
14303
14304 let project_settings = ProjectSettings::get_global(cx);
14305 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14306
14307 if self.mode == EditorMode::Full {
14308 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14309 if self.git_blame_inline_enabled != inline_blame_enabled {
14310 self.toggle_git_blame_inline_internal(false, window, cx);
14311 }
14312 }
14313
14314 cx.notify();
14315 }
14316
14317 pub fn set_searchable(&mut self, searchable: bool) {
14318 self.searchable = searchable;
14319 }
14320
14321 pub fn searchable(&self) -> bool {
14322 self.searchable
14323 }
14324
14325 fn open_proposed_changes_editor(
14326 &mut self,
14327 _: &OpenProposedChangesEditor,
14328 window: &mut Window,
14329 cx: &mut Context<Self>,
14330 ) {
14331 let Some(workspace) = self.workspace() else {
14332 cx.propagate();
14333 return;
14334 };
14335
14336 let selections = self.selections.all::<usize>(cx);
14337 let multi_buffer = self.buffer.read(cx);
14338 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14339 let mut new_selections_by_buffer = HashMap::default();
14340 for selection in selections {
14341 for (buffer, range, _) in
14342 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14343 {
14344 let mut range = range.to_point(buffer);
14345 range.start.column = 0;
14346 range.end.column = buffer.line_len(range.end.row);
14347 new_selections_by_buffer
14348 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14349 .or_insert(Vec::new())
14350 .push(range)
14351 }
14352 }
14353
14354 let proposed_changes_buffers = new_selections_by_buffer
14355 .into_iter()
14356 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14357 .collect::<Vec<_>>();
14358 let proposed_changes_editor = cx.new(|cx| {
14359 ProposedChangesEditor::new(
14360 "Proposed changes",
14361 proposed_changes_buffers,
14362 self.project.clone(),
14363 window,
14364 cx,
14365 )
14366 });
14367
14368 window.defer(cx, move |window, cx| {
14369 workspace.update(cx, |workspace, cx| {
14370 workspace.active_pane().update(cx, |pane, cx| {
14371 pane.add_item(
14372 Box::new(proposed_changes_editor),
14373 true,
14374 true,
14375 None,
14376 window,
14377 cx,
14378 );
14379 });
14380 });
14381 });
14382 }
14383
14384 pub fn open_excerpts_in_split(
14385 &mut self,
14386 _: &OpenExcerptsSplit,
14387 window: &mut Window,
14388 cx: &mut Context<Self>,
14389 ) {
14390 self.open_excerpts_common(None, true, window, cx)
14391 }
14392
14393 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14394 self.open_excerpts_common(None, false, window, cx)
14395 }
14396
14397 fn open_excerpts_common(
14398 &mut self,
14399 jump_data: Option<JumpData>,
14400 split: bool,
14401 window: &mut Window,
14402 cx: &mut Context<Self>,
14403 ) {
14404 let Some(workspace) = self.workspace() else {
14405 cx.propagate();
14406 return;
14407 };
14408
14409 if self.buffer.read(cx).is_singleton() {
14410 cx.propagate();
14411 return;
14412 }
14413
14414 let mut new_selections_by_buffer = HashMap::default();
14415 match &jump_data {
14416 Some(JumpData::MultiBufferPoint {
14417 excerpt_id,
14418 position,
14419 anchor,
14420 line_offset_from_top,
14421 }) => {
14422 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14423 if let Some(buffer) = multi_buffer_snapshot
14424 .buffer_id_for_excerpt(*excerpt_id)
14425 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14426 {
14427 let buffer_snapshot = buffer.read(cx).snapshot();
14428 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14429 language::ToPoint::to_point(anchor, &buffer_snapshot)
14430 } else {
14431 buffer_snapshot.clip_point(*position, Bias::Left)
14432 };
14433 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14434 new_selections_by_buffer.insert(
14435 buffer,
14436 (
14437 vec![jump_to_offset..jump_to_offset],
14438 Some(*line_offset_from_top),
14439 ),
14440 );
14441 }
14442 }
14443 Some(JumpData::MultiBufferRow {
14444 row,
14445 line_offset_from_top,
14446 }) => {
14447 let point = MultiBufferPoint::new(row.0, 0);
14448 if let Some((buffer, buffer_point, _)) =
14449 self.buffer.read(cx).point_to_buffer_point(point, cx)
14450 {
14451 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14452 new_selections_by_buffer
14453 .entry(buffer)
14454 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14455 .0
14456 .push(buffer_offset..buffer_offset)
14457 }
14458 }
14459 None => {
14460 let selections = self.selections.all::<usize>(cx);
14461 let multi_buffer = self.buffer.read(cx);
14462 for selection in selections {
14463 for (buffer, mut range, _) in multi_buffer
14464 .snapshot(cx)
14465 .range_to_buffer_ranges(selection.range())
14466 {
14467 // When editing branch buffers, jump to the corresponding location
14468 // in their base buffer.
14469 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14470 let buffer = buffer_handle.read(cx);
14471 if let Some(base_buffer) = buffer.base_buffer() {
14472 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14473 buffer_handle = base_buffer;
14474 }
14475
14476 if selection.reversed {
14477 mem::swap(&mut range.start, &mut range.end);
14478 }
14479 new_selections_by_buffer
14480 .entry(buffer_handle)
14481 .or_insert((Vec::new(), None))
14482 .0
14483 .push(range)
14484 }
14485 }
14486 }
14487 }
14488
14489 if new_selections_by_buffer.is_empty() {
14490 return;
14491 }
14492
14493 // We defer the pane interaction because we ourselves are a workspace item
14494 // and activating a new item causes the pane to call a method on us reentrantly,
14495 // which panics if we're on the stack.
14496 window.defer(cx, move |window, cx| {
14497 workspace.update(cx, |workspace, cx| {
14498 let pane = if split {
14499 workspace.adjacent_pane(window, cx)
14500 } else {
14501 workspace.active_pane().clone()
14502 };
14503
14504 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14505 let editor = buffer
14506 .read(cx)
14507 .file()
14508 .is_none()
14509 .then(|| {
14510 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14511 // so `workspace.open_project_item` will never find them, always opening a new editor.
14512 // Instead, we try to activate the existing editor in the pane first.
14513 let (editor, pane_item_index) =
14514 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14515 let editor = item.downcast::<Editor>()?;
14516 let singleton_buffer =
14517 editor.read(cx).buffer().read(cx).as_singleton()?;
14518 if singleton_buffer == buffer {
14519 Some((editor, i))
14520 } else {
14521 None
14522 }
14523 })?;
14524 pane.update(cx, |pane, cx| {
14525 pane.activate_item(pane_item_index, true, true, window, cx)
14526 });
14527 Some(editor)
14528 })
14529 .flatten()
14530 .unwrap_or_else(|| {
14531 workspace.open_project_item::<Self>(
14532 pane.clone(),
14533 buffer,
14534 true,
14535 true,
14536 window,
14537 cx,
14538 )
14539 });
14540
14541 editor.update(cx, |editor, cx| {
14542 let autoscroll = match scroll_offset {
14543 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14544 None => Autoscroll::newest(),
14545 };
14546 let nav_history = editor.nav_history.take();
14547 editor.change_selections(Some(autoscroll), window, cx, |s| {
14548 s.select_ranges(ranges);
14549 });
14550 editor.nav_history = nav_history;
14551 });
14552 }
14553 })
14554 });
14555 }
14556
14557 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14558 let snapshot = self.buffer.read(cx).read(cx);
14559 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14560 Some(
14561 ranges
14562 .iter()
14563 .map(move |range| {
14564 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14565 })
14566 .collect(),
14567 )
14568 }
14569
14570 fn selection_replacement_ranges(
14571 &self,
14572 range: Range<OffsetUtf16>,
14573 cx: &mut App,
14574 ) -> Vec<Range<OffsetUtf16>> {
14575 let selections = self.selections.all::<OffsetUtf16>(cx);
14576 let newest_selection = selections
14577 .iter()
14578 .max_by_key(|selection| selection.id)
14579 .unwrap();
14580 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14581 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14582 let snapshot = self.buffer.read(cx).read(cx);
14583 selections
14584 .into_iter()
14585 .map(|mut selection| {
14586 selection.start.0 =
14587 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14588 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14589 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14590 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14591 })
14592 .collect()
14593 }
14594
14595 fn report_editor_event(
14596 &self,
14597 event_type: &'static str,
14598 file_extension: Option<String>,
14599 cx: &App,
14600 ) {
14601 if cfg!(any(test, feature = "test-support")) {
14602 return;
14603 }
14604
14605 let Some(project) = &self.project else { return };
14606
14607 // If None, we are in a file without an extension
14608 let file = self
14609 .buffer
14610 .read(cx)
14611 .as_singleton()
14612 .and_then(|b| b.read(cx).file());
14613 let file_extension = file_extension.or(file
14614 .as_ref()
14615 .and_then(|file| Path::new(file.file_name(cx)).extension())
14616 .and_then(|e| e.to_str())
14617 .map(|a| a.to_string()));
14618
14619 let vim_mode = cx
14620 .global::<SettingsStore>()
14621 .raw_user_settings()
14622 .get("vim_mode")
14623 == Some(&serde_json::Value::Bool(true));
14624
14625 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14626 let copilot_enabled = edit_predictions_provider
14627 == language::language_settings::EditPredictionProvider::Copilot;
14628 let copilot_enabled_for_language = self
14629 .buffer
14630 .read(cx)
14631 .settings_at(0, cx)
14632 .show_edit_predictions;
14633
14634 let project = project.read(cx);
14635 telemetry::event!(
14636 event_type,
14637 file_extension,
14638 vim_mode,
14639 copilot_enabled,
14640 copilot_enabled_for_language,
14641 edit_predictions_provider,
14642 is_via_ssh = project.is_via_ssh(),
14643 );
14644 }
14645
14646 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14647 /// with each line being an array of {text, highlight} objects.
14648 fn copy_highlight_json(
14649 &mut self,
14650 _: &CopyHighlightJson,
14651 window: &mut Window,
14652 cx: &mut Context<Self>,
14653 ) {
14654 #[derive(Serialize)]
14655 struct Chunk<'a> {
14656 text: String,
14657 highlight: Option<&'a str>,
14658 }
14659
14660 let snapshot = self.buffer.read(cx).snapshot(cx);
14661 let range = self
14662 .selected_text_range(false, window, cx)
14663 .and_then(|selection| {
14664 if selection.range.is_empty() {
14665 None
14666 } else {
14667 Some(selection.range)
14668 }
14669 })
14670 .unwrap_or_else(|| 0..snapshot.len());
14671
14672 let chunks = snapshot.chunks(range, true);
14673 let mut lines = Vec::new();
14674 let mut line: VecDeque<Chunk> = VecDeque::new();
14675
14676 let Some(style) = self.style.as_ref() else {
14677 return;
14678 };
14679
14680 for chunk in chunks {
14681 let highlight = chunk
14682 .syntax_highlight_id
14683 .and_then(|id| id.name(&style.syntax));
14684 let mut chunk_lines = chunk.text.split('\n').peekable();
14685 while let Some(text) = chunk_lines.next() {
14686 let mut merged_with_last_token = false;
14687 if let Some(last_token) = line.back_mut() {
14688 if last_token.highlight == highlight {
14689 last_token.text.push_str(text);
14690 merged_with_last_token = true;
14691 }
14692 }
14693
14694 if !merged_with_last_token {
14695 line.push_back(Chunk {
14696 text: text.into(),
14697 highlight,
14698 });
14699 }
14700
14701 if chunk_lines.peek().is_some() {
14702 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14703 line.pop_front();
14704 }
14705 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14706 line.pop_back();
14707 }
14708
14709 lines.push(mem::take(&mut line));
14710 }
14711 }
14712 }
14713
14714 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14715 return;
14716 };
14717 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14718 }
14719
14720 pub fn open_context_menu(
14721 &mut self,
14722 _: &OpenContextMenu,
14723 window: &mut Window,
14724 cx: &mut Context<Self>,
14725 ) {
14726 self.request_autoscroll(Autoscroll::newest(), cx);
14727 let position = self.selections.newest_display(cx).start;
14728 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14729 }
14730
14731 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14732 &self.inlay_hint_cache
14733 }
14734
14735 pub fn replay_insert_event(
14736 &mut self,
14737 text: &str,
14738 relative_utf16_range: Option<Range<isize>>,
14739 window: &mut Window,
14740 cx: &mut Context<Self>,
14741 ) {
14742 if !self.input_enabled {
14743 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14744 return;
14745 }
14746 if let Some(relative_utf16_range) = relative_utf16_range {
14747 let selections = self.selections.all::<OffsetUtf16>(cx);
14748 self.change_selections(None, window, cx, |s| {
14749 let new_ranges = selections.into_iter().map(|range| {
14750 let start = OffsetUtf16(
14751 range
14752 .head()
14753 .0
14754 .saturating_add_signed(relative_utf16_range.start),
14755 );
14756 let end = OffsetUtf16(
14757 range
14758 .head()
14759 .0
14760 .saturating_add_signed(relative_utf16_range.end),
14761 );
14762 start..end
14763 });
14764 s.select_ranges(new_ranges);
14765 });
14766 }
14767
14768 self.handle_input(text, window, cx);
14769 }
14770
14771 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14772 let Some(provider) = self.semantics_provider.as_ref() else {
14773 return false;
14774 };
14775
14776 let mut supports = false;
14777 self.buffer().update(cx, |this, cx| {
14778 this.for_each_buffer(|buffer| {
14779 supports |= provider.supports_inlay_hints(buffer, cx);
14780 });
14781 });
14782
14783 supports
14784 }
14785
14786 pub fn is_focused(&self, window: &Window) -> bool {
14787 self.focus_handle.is_focused(window)
14788 }
14789
14790 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14791 cx.emit(EditorEvent::Focused);
14792
14793 if let Some(descendant) = self
14794 .last_focused_descendant
14795 .take()
14796 .and_then(|descendant| descendant.upgrade())
14797 {
14798 window.focus(&descendant);
14799 } else {
14800 if let Some(blame) = self.blame.as_ref() {
14801 blame.update(cx, GitBlame::focus)
14802 }
14803
14804 self.blink_manager.update(cx, BlinkManager::enable);
14805 self.show_cursor_names(window, cx);
14806 self.buffer.update(cx, |buffer, cx| {
14807 buffer.finalize_last_transaction(cx);
14808 if self.leader_peer_id.is_none() {
14809 buffer.set_active_selections(
14810 &self.selections.disjoint_anchors(),
14811 self.selections.line_mode,
14812 self.cursor_shape,
14813 cx,
14814 );
14815 }
14816 });
14817 }
14818 }
14819
14820 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14821 cx.emit(EditorEvent::FocusedIn)
14822 }
14823
14824 fn handle_focus_out(
14825 &mut self,
14826 event: FocusOutEvent,
14827 _window: &mut Window,
14828 _cx: &mut Context<Self>,
14829 ) {
14830 if event.blurred != self.focus_handle {
14831 self.last_focused_descendant = Some(event.blurred);
14832 }
14833 }
14834
14835 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14836 self.blink_manager.update(cx, BlinkManager::disable);
14837 self.buffer
14838 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14839
14840 if let Some(blame) = self.blame.as_ref() {
14841 blame.update(cx, GitBlame::blur)
14842 }
14843 if !self.hover_state.focused(window, cx) {
14844 hide_hover(self, cx);
14845 }
14846
14847 self.hide_context_menu(window, cx);
14848 self.discard_inline_completion(false, cx);
14849 cx.emit(EditorEvent::Blurred);
14850 cx.notify();
14851 }
14852
14853 pub fn register_action<A: Action>(
14854 &mut self,
14855 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14856 ) -> Subscription {
14857 let id = self.next_editor_action_id.post_inc();
14858 let listener = Arc::new(listener);
14859 self.editor_actions.borrow_mut().insert(
14860 id,
14861 Box::new(move |window, _| {
14862 let listener = listener.clone();
14863 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14864 let action = action.downcast_ref().unwrap();
14865 if phase == DispatchPhase::Bubble {
14866 listener(action, window, cx)
14867 }
14868 })
14869 }),
14870 );
14871
14872 let editor_actions = self.editor_actions.clone();
14873 Subscription::new(move || {
14874 editor_actions.borrow_mut().remove(&id);
14875 })
14876 }
14877
14878 pub fn file_header_size(&self) -> u32 {
14879 FILE_HEADER_HEIGHT
14880 }
14881
14882 pub fn revert(
14883 &mut self,
14884 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14885 window: &mut Window,
14886 cx: &mut Context<Self>,
14887 ) {
14888 self.buffer().update(cx, |multi_buffer, cx| {
14889 for (buffer_id, changes) in revert_changes {
14890 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14891 buffer.update(cx, |buffer, cx| {
14892 buffer.edit(
14893 changes.into_iter().map(|(range, text)| {
14894 (range, text.to_string().map(Arc::<str>::from))
14895 }),
14896 None,
14897 cx,
14898 );
14899 });
14900 }
14901 }
14902 });
14903 self.change_selections(None, window, cx, |selections| selections.refresh());
14904 }
14905
14906 pub fn to_pixel_point(
14907 &self,
14908 source: multi_buffer::Anchor,
14909 editor_snapshot: &EditorSnapshot,
14910 window: &mut Window,
14911 ) -> Option<gpui::Point<Pixels>> {
14912 let source_point = source.to_display_point(editor_snapshot);
14913 self.display_to_pixel_point(source_point, editor_snapshot, window)
14914 }
14915
14916 pub fn display_to_pixel_point(
14917 &self,
14918 source: DisplayPoint,
14919 editor_snapshot: &EditorSnapshot,
14920 window: &mut Window,
14921 ) -> Option<gpui::Point<Pixels>> {
14922 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14923 let text_layout_details = self.text_layout_details(window);
14924 let scroll_top = text_layout_details
14925 .scroll_anchor
14926 .scroll_position(editor_snapshot)
14927 .y;
14928
14929 if source.row().as_f32() < scroll_top.floor() {
14930 return None;
14931 }
14932 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14933 let source_y = line_height * (source.row().as_f32() - scroll_top);
14934 Some(gpui::Point::new(source_x, source_y))
14935 }
14936
14937 pub fn has_visible_completions_menu(&self) -> bool {
14938 !self.edit_prediction_preview_is_active()
14939 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14940 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14941 })
14942 }
14943
14944 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14945 self.addons
14946 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14947 }
14948
14949 pub fn unregister_addon<T: Addon>(&mut self) {
14950 self.addons.remove(&std::any::TypeId::of::<T>());
14951 }
14952
14953 pub fn addon<T: Addon>(&self) -> Option<&T> {
14954 let type_id = std::any::TypeId::of::<T>();
14955 self.addons
14956 .get(&type_id)
14957 .and_then(|item| item.to_any().downcast_ref::<T>())
14958 }
14959
14960 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14961 let text_layout_details = self.text_layout_details(window);
14962 let style = &text_layout_details.editor_style;
14963 let font_id = window.text_system().resolve_font(&style.text.font());
14964 let font_size = style.text.font_size.to_pixels(window.rem_size());
14965 let line_height = style.text.line_height_in_pixels(window.rem_size());
14966 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14967
14968 gpui::Size::new(em_width, line_height)
14969 }
14970
14971 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14972 self.load_diff_task.clone()
14973 }
14974}
14975
14976fn get_uncommitted_diff_for_buffer(
14977 project: &Entity<Project>,
14978 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14979 buffer: Entity<MultiBuffer>,
14980 cx: &mut App,
14981) -> Task<()> {
14982 let mut tasks = Vec::new();
14983 project.update(cx, |project, cx| {
14984 for buffer in buffers {
14985 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14986 }
14987 });
14988 cx.spawn(|mut cx| async move {
14989 let diffs = futures::future::join_all(tasks).await;
14990 buffer
14991 .update(&mut cx, |buffer, cx| {
14992 for diff in diffs.into_iter().flatten() {
14993 buffer.add_diff(diff, cx);
14994 }
14995 })
14996 .ok();
14997 })
14998}
14999
15000fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15001 let tab_size = tab_size.get() as usize;
15002 let mut width = offset;
15003
15004 for ch in text.chars() {
15005 width += if ch == '\t' {
15006 tab_size - (width % tab_size)
15007 } else {
15008 1
15009 };
15010 }
15011
15012 width - offset
15013}
15014
15015#[cfg(test)]
15016mod tests {
15017 use super::*;
15018
15019 #[test]
15020 fn test_string_size_with_expanded_tabs() {
15021 let nz = |val| NonZeroU32::new(val).unwrap();
15022 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15023 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15024 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15025 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15026 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15027 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15028 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15029 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15030 }
15031}
15032
15033/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15034struct WordBreakingTokenizer<'a> {
15035 input: &'a str,
15036}
15037
15038impl<'a> WordBreakingTokenizer<'a> {
15039 fn new(input: &'a str) -> Self {
15040 Self { input }
15041 }
15042}
15043
15044fn is_char_ideographic(ch: char) -> bool {
15045 use unicode_script::Script::*;
15046 use unicode_script::UnicodeScript;
15047 matches!(ch.script(), Han | Tangut | Yi)
15048}
15049
15050fn is_grapheme_ideographic(text: &str) -> bool {
15051 text.chars().any(is_char_ideographic)
15052}
15053
15054fn is_grapheme_whitespace(text: &str) -> bool {
15055 text.chars().any(|x| x.is_whitespace())
15056}
15057
15058fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15059 text.chars().next().map_or(false, |ch| {
15060 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15061 })
15062}
15063
15064#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15065struct WordBreakToken<'a> {
15066 token: &'a str,
15067 grapheme_len: usize,
15068 is_whitespace: bool,
15069}
15070
15071impl<'a> Iterator for WordBreakingTokenizer<'a> {
15072 /// Yields a span, the count of graphemes in the token, and whether it was
15073 /// whitespace. Note that it also breaks at word boundaries.
15074 type Item = WordBreakToken<'a>;
15075
15076 fn next(&mut self) -> Option<Self::Item> {
15077 use unicode_segmentation::UnicodeSegmentation;
15078 if self.input.is_empty() {
15079 return None;
15080 }
15081
15082 let mut iter = self.input.graphemes(true).peekable();
15083 let mut offset = 0;
15084 let mut graphemes = 0;
15085 if let Some(first_grapheme) = iter.next() {
15086 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15087 offset += first_grapheme.len();
15088 graphemes += 1;
15089 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15090 if let Some(grapheme) = iter.peek().copied() {
15091 if should_stay_with_preceding_ideograph(grapheme) {
15092 offset += grapheme.len();
15093 graphemes += 1;
15094 }
15095 }
15096 } else {
15097 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15098 let mut next_word_bound = words.peek().copied();
15099 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15100 next_word_bound = words.next();
15101 }
15102 while let Some(grapheme) = iter.peek().copied() {
15103 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15104 break;
15105 };
15106 if is_grapheme_whitespace(grapheme) != is_whitespace {
15107 break;
15108 };
15109 offset += grapheme.len();
15110 graphemes += 1;
15111 iter.next();
15112 }
15113 }
15114 let token = &self.input[..offset];
15115 self.input = &self.input[offset..];
15116 if is_whitespace {
15117 Some(WordBreakToken {
15118 token: " ",
15119 grapheme_len: 1,
15120 is_whitespace: true,
15121 })
15122 } else {
15123 Some(WordBreakToken {
15124 token,
15125 grapheme_len: graphemes,
15126 is_whitespace: false,
15127 })
15128 }
15129 } else {
15130 None
15131 }
15132 }
15133}
15134
15135#[test]
15136fn test_word_breaking_tokenizer() {
15137 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15138 ("", &[]),
15139 (" ", &[(" ", 1, true)]),
15140 ("Ʒ", &[("Ʒ", 1, false)]),
15141 ("Ǽ", &[("Ǽ", 1, false)]),
15142 ("⋑", &[("⋑", 1, false)]),
15143 ("⋑⋑", &[("⋑⋑", 2, false)]),
15144 (
15145 "原理,进而",
15146 &[
15147 ("原", 1, false),
15148 ("理,", 2, false),
15149 ("进", 1, false),
15150 ("而", 1, false),
15151 ],
15152 ),
15153 (
15154 "hello world",
15155 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15156 ),
15157 (
15158 "hello, world",
15159 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15160 ),
15161 (
15162 " hello world",
15163 &[
15164 (" ", 1, true),
15165 ("hello", 5, false),
15166 (" ", 1, true),
15167 ("world", 5, false),
15168 ],
15169 ),
15170 (
15171 "这是什么 \n 钢笔",
15172 &[
15173 ("这", 1, false),
15174 ("是", 1, false),
15175 ("什", 1, false),
15176 ("么", 1, false),
15177 (" ", 1, true),
15178 ("钢", 1, false),
15179 ("笔", 1, false),
15180 ],
15181 ),
15182 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15183 ];
15184
15185 for (input, result) in tests {
15186 assert_eq!(
15187 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15188 result
15189 .iter()
15190 .copied()
15191 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15192 token,
15193 grapheme_len,
15194 is_whitespace,
15195 })
15196 .collect::<Vec<_>>()
15197 );
15198 }
15199}
15200
15201fn wrap_with_prefix(
15202 line_prefix: String,
15203 unwrapped_text: String,
15204 wrap_column: usize,
15205 tab_size: NonZeroU32,
15206) -> String {
15207 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15208 let mut wrapped_text = String::new();
15209 let mut current_line = line_prefix.clone();
15210
15211 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15212 let mut current_line_len = line_prefix_len;
15213 for WordBreakToken {
15214 token,
15215 grapheme_len,
15216 is_whitespace,
15217 } in tokenizer
15218 {
15219 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15220 wrapped_text.push_str(current_line.trim_end());
15221 wrapped_text.push('\n');
15222 current_line.truncate(line_prefix.len());
15223 current_line_len = line_prefix_len;
15224 if !is_whitespace {
15225 current_line.push_str(token);
15226 current_line_len += grapheme_len;
15227 }
15228 } else if !is_whitespace {
15229 current_line.push_str(token);
15230 current_line_len += grapheme_len;
15231 } else if current_line_len != line_prefix_len {
15232 current_line.push(' ');
15233 current_line_len += 1;
15234 }
15235 }
15236
15237 if !current_line.is_empty() {
15238 wrapped_text.push_str(¤t_line);
15239 }
15240 wrapped_text
15241}
15242
15243#[test]
15244fn test_wrap_with_prefix() {
15245 assert_eq!(
15246 wrap_with_prefix(
15247 "# ".to_string(),
15248 "abcdefg".to_string(),
15249 4,
15250 NonZeroU32::new(4).unwrap()
15251 ),
15252 "# abcdefg"
15253 );
15254 assert_eq!(
15255 wrap_with_prefix(
15256 "".to_string(),
15257 "\thello world".to_string(),
15258 8,
15259 NonZeroU32::new(4).unwrap()
15260 ),
15261 "hello\nworld"
15262 );
15263 assert_eq!(
15264 wrap_with_prefix(
15265 "// ".to_string(),
15266 "xx \nyy zz aa bb cc".to_string(),
15267 12,
15268 NonZeroU32::new(4).unwrap()
15269 ),
15270 "// xx yy zz\n// aa bb cc"
15271 );
15272 assert_eq!(
15273 wrap_with_prefix(
15274 String::new(),
15275 "这是什么 \n 钢笔".to_string(),
15276 3,
15277 NonZeroU32::new(4).unwrap()
15278 ),
15279 "这是什\n么 钢\n笔"
15280 );
15281}
15282
15283pub trait CollaborationHub {
15284 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15285 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15286 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15287}
15288
15289impl CollaborationHub for Entity<Project> {
15290 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15291 self.read(cx).collaborators()
15292 }
15293
15294 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15295 self.read(cx).user_store().read(cx).participant_indices()
15296 }
15297
15298 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15299 let this = self.read(cx);
15300 let user_ids = this.collaborators().values().map(|c| c.user_id);
15301 this.user_store().read_with(cx, |user_store, cx| {
15302 user_store.participant_names(user_ids, cx)
15303 })
15304 }
15305}
15306
15307pub trait SemanticsProvider {
15308 fn hover(
15309 &self,
15310 buffer: &Entity<Buffer>,
15311 position: text::Anchor,
15312 cx: &mut App,
15313 ) -> Option<Task<Vec<project::Hover>>>;
15314
15315 fn inlay_hints(
15316 &self,
15317 buffer_handle: Entity<Buffer>,
15318 range: Range<text::Anchor>,
15319 cx: &mut App,
15320 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15321
15322 fn resolve_inlay_hint(
15323 &self,
15324 hint: InlayHint,
15325 buffer_handle: Entity<Buffer>,
15326 server_id: LanguageServerId,
15327 cx: &mut App,
15328 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15329
15330 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15331
15332 fn document_highlights(
15333 &self,
15334 buffer: &Entity<Buffer>,
15335 position: text::Anchor,
15336 cx: &mut App,
15337 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15338
15339 fn definitions(
15340 &self,
15341 buffer: &Entity<Buffer>,
15342 position: text::Anchor,
15343 kind: GotoDefinitionKind,
15344 cx: &mut App,
15345 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15346
15347 fn range_for_rename(
15348 &self,
15349 buffer: &Entity<Buffer>,
15350 position: text::Anchor,
15351 cx: &mut App,
15352 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15353
15354 fn perform_rename(
15355 &self,
15356 buffer: &Entity<Buffer>,
15357 position: text::Anchor,
15358 new_name: String,
15359 cx: &mut App,
15360 ) -> Option<Task<Result<ProjectTransaction>>>;
15361}
15362
15363pub trait CompletionProvider {
15364 fn completions(
15365 &self,
15366 buffer: &Entity<Buffer>,
15367 buffer_position: text::Anchor,
15368 trigger: CompletionContext,
15369 window: &mut Window,
15370 cx: &mut Context<Editor>,
15371 ) -> Task<Result<Vec<Completion>>>;
15372
15373 fn resolve_completions(
15374 &self,
15375 buffer: Entity<Buffer>,
15376 completion_indices: Vec<usize>,
15377 completions: Rc<RefCell<Box<[Completion]>>>,
15378 cx: &mut Context<Editor>,
15379 ) -> Task<Result<bool>>;
15380
15381 fn apply_additional_edits_for_completion(
15382 &self,
15383 _buffer: Entity<Buffer>,
15384 _completions: Rc<RefCell<Box<[Completion]>>>,
15385 _completion_index: usize,
15386 _push_to_history: bool,
15387 _cx: &mut Context<Editor>,
15388 ) -> Task<Result<Option<language::Transaction>>> {
15389 Task::ready(Ok(None))
15390 }
15391
15392 fn is_completion_trigger(
15393 &self,
15394 buffer: &Entity<Buffer>,
15395 position: language::Anchor,
15396 text: &str,
15397 trigger_in_words: bool,
15398 cx: &mut Context<Editor>,
15399 ) -> bool;
15400
15401 fn sort_completions(&self) -> bool {
15402 true
15403 }
15404}
15405
15406pub trait CodeActionProvider {
15407 fn id(&self) -> Arc<str>;
15408
15409 fn code_actions(
15410 &self,
15411 buffer: &Entity<Buffer>,
15412 range: Range<text::Anchor>,
15413 window: &mut Window,
15414 cx: &mut App,
15415 ) -> Task<Result<Vec<CodeAction>>>;
15416
15417 fn apply_code_action(
15418 &self,
15419 buffer_handle: Entity<Buffer>,
15420 action: CodeAction,
15421 excerpt_id: ExcerptId,
15422 push_to_history: bool,
15423 window: &mut Window,
15424 cx: &mut App,
15425 ) -> Task<Result<ProjectTransaction>>;
15426}
15427
15428impl CodeActionProvider for Entity<Project> {
15429 fn id(&self) -> Arc<str> {
15430 "project".into()
15431 }
15432
15433 fn code_actions(
15434 &self,
15435 buffer: &Entity<Buffer>,
15436 range: Range<text::Anchor>,
15437 _window: &mut Window,
15438 cx: &mut App,
15439 ) -> Task<Result<Vec<CodeAction>>> {
15440 self.update(cx, |project, cx| {
15441 project.code_actions(buffer, range, None, cx)
15442 })
15443 }
15444
15445 fn apply_code_action(
15446 &self,
15447 buffer_handle: Entity<Buffer>,
15448 action: CodeAction,
15449 _excerpt_id: ExcerptId,
15450 push_to_history: bool,
15451 _window: &mut Window,
15452 cx: &mut App,
15453 ) -> Task<Result<ProjectTransaction>> {
15454 self.update(cx, |project, cx| {
15455 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15456 })
15457 }
15458}
15459
15460fn snippet_completions(
15461 project: &Project,
15462 buffer: &Entity<Buffer>,
15463 buffer_position: text::Anchor,
15464 cx: &mut App,
15465) -> Task<Result<Vec<Completion>>> {
15466 let language = buffer.read(cx).language_at(buffer_position);
15467 let language_name = language.as_ref().map(|language| language.lsp_id());
15468 let snippet_store = project.snippets().read(cx);
15469 let snippets = snippet_store.snippets_for(language_name, cx);
15470
15471 if snippets.is_empty() {
15472 return Task::ready(Ok(vec![]));
15473 }
15474 let snapshot = buffer.read(cx).text_snapshot();
15475 let chars: String = snapshot
15476 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15477 .collect();
15478
15479 let scope = language.map(|language| language.default_scope());
15480 let executor = cx.background_executor().clone();
15481
15482 cx.background_executor().spawn(async move {
15483 let classifier = CharClassifier::new(scope).for_completion(true);
15484 let mut last_word = chars
15485 .chars()
15486 .take_while(|c| classifier.is_word(*c))
15487 .collect::<String>();
15488 last_word = last_word.chars().rev().collect();
15489
15490 if last_word.is_empty() {
15491 return Ok(vec![]);
15492 }
15493
15494 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15495 let to_lsp = |point: &text::Anchor| {
15496 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15497 point_to_lsp(end)
15498 };
15499 let lsp_end = to_lsp(&buffer_position);
15500
15501 let candidates = snippets
15502 .iter()
15503 .enumerate()
15504 .flat_map(|(ix, snippet)| {
15505 snippet
15506 .prefix
15507 .iter()
15508 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15509 })
15510 .collect::<Vec<StringMatchCandidate>>();
15511
15512 let mut matches = fuzzy::match_strings(
15513 &candidates,
15514 &last_word,
15515 last_word.chars().any(|c| c.is_uppercase()),
15516 100,
15517 &Default::default(),
15518 executor,
15519 )
15520 .await;
15521
15522 // Remove all candidates where the query's start does not match the start of any word in the candidate
15523 if let Some(query_start) = last_word.chars().next() {
15524 matches.retain(|string_match| {
15525 split_words(&string_match.string).any(|word| {
15526 // Check that the first codepoint of the word as lowercase matches the first
15527 // codepoint of the query as lowercase
15528 word.chars()
15529 .flat_map(|codepoint| codepoint.to_lowercase())
15530 .zip(query_start.to_lowercase())
15531 .all(|(word_cp, query_cp)| word_cp == query_cp)
15532 })
15533 });
15534 }
15535
15536 let matched_strings = matches
15537 .into_iter()
15538 .map(|m| m.string)
15539 .collect::<HashSet<_>>();
15540
15541 let result: Vec<Completion> = snippets
15542 .into_iter()
15543 .filter_map(|snippet| {
15544 let matching_prefix = snippet
15545 .prefix
15546 .iter()
15547 .find(|prefix| matched_strings.contains(*prefix))?;
15548 let start = as_offset - last_word.len();
15549 let start = snapshot.anchor_before(start);
15550 let range = start..buffer_position;
15551 let lsp_start = to_lsp(&start);
15552 let lsp_range = lsp::Range {
15553 start: lsp_start,
15554 end: lsp_end,
15555 };
15556 Some(Completion {
15557 old_range: range,
15558 new_text: snippet.body.clone(),
15559 resolved: false,
15560 label: CodeLabel {
15561 text: matching_prefix.clone(),
15562 runs: vec![],
15563 filter_range: 0..matching_prefix.len(),
15564 },
15565 server_id: LanguageServerId(usize::MAX),
15566 documentation: snippet
15567 .description
15568 .clone()
15569 .map(CompletionDocumentation::SingleLine),
15570 lsp_completion: lsp::CompletionItem {
15571 label: snippet.prefix.first().unwrap().clone(),
15572 kind: Some(CompletionItemKind::SNIPPET),
15573 label_details: snippet.description.as_ref().map(|description| {
15574 lsp::CompletionItemLabelDetails {
15575 detail: Some(description.clone()),
15576 description: None,
15577 }
15578 }),
15579 insert_text_format: Some(InsertTextFormat::SNIPPET),
15580 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15581 lsp::InsertReplaceEdit {
15582 new_text: snippet.body.clone(),
15583 insert: lsp_range,
15584 replace: lsp_range,
15585 },
15586 )),
15587 filter_text: Some(snippet.body.clone()),
15588 sort_text: Some(char::MAX.to_string()),
15589 ..Default::default()
15590 },
15591 confirm: None,
15592 })
15593 })
15594 .collect();
15595
15596 Ok(result)
15597 })
15598}
15599
15600impl CompletionProvider for Entity<Project> {
15601 fn completions(
15602 &self,
15603 buffer: &Entity<Buffer>,
15604 buffer_position: text::Anchor,
15605 options: CompletionContext,
15606 _window: &mut Window,
15607 cx: &mut Context<Editor>,
15608 ) -> Task<Result<Vec<Completion>>> {
15609 self.update(cx, |project, cx| {
15610 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15611 let project_completions = project.completions(buffer, buffer_position, options, cx);
15612 cx.background_executor().spawn(async move {
15613 let mut completions = project_completions.await?;
15614 let snippets_completions = snippets.await?;
15615 completions.extend(snippets_completions);
15616 Ok(completions)
15617 })
15618 })
15619 }
15620
15621 fn resolve_completions(
15622 &self,
15623 buffer: Entity<Buffer>,
15624 completion_indices: Vec<usize>,
15625 completions: Rc<RefCell<Box<[Completion]>>>,
15626 cx: &mut Context<Editor>,
15627 ) -> Task<Result<bool>> {
15628 self.update(cx, |project, cx| {
15629 project.lsp_store().update(cx, |lsp_store, cx| {
15630 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15631 })
15632 })
15633 }
15634
15635 fn apply_additional_edits_for_completion(
15636 &self,
15637 buffer: Entity<Buffer>,
15638 completions: Rc<RefCell<Box<[Completion]>>>,
15639 completion_index: usize,
15640 push_to_history: bool,
15641 cx: &mut Context<Editor>,
15642 ) -> Task<Result<Option<language::Transaction>>> {
15643 self.update(cx, |project, cx| {
15644 project.lsp_store().update(cx, |lsp_store, cx| {
15645 lsp_store.apply_additional_edits_for_completion(
15646 buffer,
15647 completions,
15648 completion_index,
15649 push_to_history,
15650 cx,
15651 )
15652 })
15653 })
15654 }
15655
15656 fn is_completion_trigger(
15657 &self,
15658 buffer: &Entity<Buffer>,
15659 position: language::Anchor,
15660 text: &str,
15661 trigger_in_words: bool,
15662 cx: &mut Context<Editor>,
15663 ) -> bool {
15664 let mut chars = text.chars();
15665 let char = if let Some(char) = chars.next() {
15666 char
15667 } else {
15668 return false;
15669 };
15670 if chars.next().is_some() {
15671 return false;
15672 }
15673
15674 let buffer = buffer.read(cx);
15675 let snapshot = buffer.snapshot();
15676 if !snapshot.settings_at(position, cx).show_completions_on_input {
15677 return false;
15678 }
15679 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15680 if trigger_in_words && classifier.is_word(char) {
15681 return true;
15682 }
15683
15684 buffer.completion_triggers().contains(text)
15685 }
15686}
15687
15688impl SemanticsProvider for Entity<Project> {
15689 fn hover(
15690 &self,
15691 buffer: &Entity<Buffer>,
15692 position: text::Anchor,
15693 cx: &mut App,
15694 ) -> Option<Task<Vec<project::Hover>>> {
15695 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15696 }
15697
15698 fn document_highlights(
15699 &self,
15700 buffer: &Entity<Buffer>,
15701 position: text::Anchor,
15702 cx: &mut App,
15703 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15704 Some(self.update(cx, |project, cx| {
15705 project.document_highlights(buffer, position, cx)
15706 }))
15707 }
15708
15709 fn definitions(
15710 &self,
15711 buffer: &Entity<Buffer>,
15712 position: text::Anchor,
15713 kind: GotoDefinitionKind,
15714 cx: &mut App,
15715 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15716 Some(self.update(cx, |project, cx| match kind {
15717 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15718 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15719 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15720 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15721 }))
15722 }
15723
15724 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15725 // TODO: make this work for remote projects
15726 self.update(cx, |this, cx| {
15727 buffer.update(cx, |buffer, cx| {
15728 this.any_language_server_supports_inlay_hints(buffer, cx)
15729 })
15730 })
15731 }
15732
15733 fn inlay_hints(
15734 &self,
15735 buffer_handle: Entity<Buffer>,
15736 range: Range<text::Anchor>,
15737 cx: &mut App,
15738 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15739 Some(self.update(cx, |project, cx| {
15740 project.inlay_hints(buffer_handle, range, cx)
15741 }))
15742 }
15743
15744 fn resolve_inlay_hint(
15745 &self,
15746 hint: InlayHint,
15747 buffer_handle: Entity<Buffer>,
15748 server_id: LanguageServerId,
15749 cx: &mut App,
15750 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15751 Some(self.update(cx, |project, cx| {
15752 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15753 }))
15754 }
15755
15756 fn range_for_rename(
15757 &self,
15758 buffer: &Entity<Buffer>,
15759 position: text::Anchor,
15760 cx: &mut App,
15761 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15762 Some(self.update(cx, |project, cx| {
15763 let buffer = buffer.clone();
15764 let task = project.prepare_rename(buffer.clone(), position, cx);
15765 cx.spawn(|_, mut cx| async move {
15766 Ok(match task.await? {
15767 PrepareRenameResponse::Success(range) => Some(range),
15768 PrepareRenameResponse::InvalidPosition => None,
15769 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15770 // Fallback on using TreeSitter info to determine identifier range
15771 buffer.update(&mut cx, |buffer, _| {
15772 let snapshot = buffer.snapshot();
15773 let (range, kind) = snapshot.surrounding_word(position);
15774 if kind != Some(CharKind::Word) {
15775 return None;
15776 }
15777 Some(
15778 snapshot.anchor_before(range.start)
15779 ..snapshot.anchor_after(range.end),
15780 )
15781 })?
15782 }
15783 })
15784 })
15785 }))
15786 }
15787
15788 fn perform_rename(
15789 &self,
15790 buffer: &Entity<Buffer>,
15791 position: text::Anchor,
15792 new_name: String,
15793 cx: &mut App,
15794 ) -> Option<Task<Result<ProjectTransaction>>> {
15795 Some(self.update(cx, |project, cx| {
15796 project.perform_rename(buffer.clone(), position, new_name, cx)
15797 }))
15798 }
15799}
15800
15801fn inlay_hint_settings(
15802 location: Anchor,
15803 snapshot: &MultiBufferSnapshot,
15804 cx: &mut Context<Editor>,
15805) -> InlayHintSettings {
15806 let file = snapshot.file_at(location);
15807 let language = snapshot.language_at(location).map(|l| l.name());
15808 language_settings(language, file, cx).inlay_hints
15809}
15810
15811fn consume_contiguous_rows(
15812 contiguous_row_selections: &mut Vec<Selection<Point>>,
15813 selection: &Selection<Point>,
15814 display_map: &DisplaySnapshot,
15815 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15816) -> (MultiBufferRow, MultiBufferRow) {
15817 contiguous_row_selections.push(selection.clone());
15818 let start_row = MultiBufferRow(selection.start.row);
15819 let mut end_row = ending_row(selection, display_map);
15820
15821 while let Some(next_selection) = selections.peek() {
15822 if next_selection.start.row <= end_row.0 {
15823 end_row = ending_row(next_selection, display_map);
15824 contiguous_row_selections.push(selections.next().unwrap().clone());
15825 } else {
15826 break;
15827 }
15828 }
15829 (start_row, end_row)
15830}
15831
15832fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15833 if next_selection.end.column > 0 || next_selection.is_empty() {
15834 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15835 } else {
15836 MultiBufferRow(next_selection.end.row)
15837 }
15838}
15839
15840impl EditorSnapshot {
15841 pub fn remote_selections_in_range<'a>(
15842 &'a self,
15843 range: &'a Range<Anchor>,
15844 collaboration_hub: &dyn CollaborationHub,
15845 cx: &'a App,
15846 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15847 let participant_names = collaboration_hub.user_names(cx);
15848 let participant_indices = collaboration_hub.user_participant_indices(cx);
15849 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15850 let collaborators_by_replica_id = collaborators_by_peer_id
15851 .iter()
15852 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15853 .collect::<HashMap<_, _>>();
15854 self.buffer_snapshot
15855 .selections_in_range(range, false)
15856 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15857 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15858 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15859 let user_name = participant_names.get(&collaborator.user_id).cloned();
15860 Some(RemoteSelection {
15861 replica_id,
15862 selection,
15863 cursor_shape,
15864 line_mode,
15865 participant_index,
15866 peer_id: collaborator.peer_id,
15867 user_name,
15868 })
15869 })
15870 }
15871
15872 pub fn hunks_for_ranges(
15873 &self,
15874 ranges: impl Iterator<Item = Range<Point>>,
15875 ) -> Vec<MultiBufferDiffHunk> {
15876 let mut hunks = Vec::new();
15877 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15878 HashMap::default();
15879 for query_range in ranges {
15880 let query_rows =
15881 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15882 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15883 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15884 ) {
15885 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15886 // when the caret is just above or just below the deleted hunk.
15887 let allow_adjacent = hunk.status().is_removed();
15888 let related_to_selection = if allow_adjacent {
15889 hunk.row_range.overlaps(&query_rows)
15890 || hunk.row_range.start == query_rows.end
15891 || hunk.row_range.end == query_rows.start
15892 } else {
15893 hunk.row_range.overlaps(&query_rows)
15894 };
15895 if related_to_selection {
15896 if !processed_buffer_rows
15897 .entry(hunk.buffer_id)
15898 .or_default()
15899 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15900 {
15901 continue;
15902 }
15903 hunks.push(hunk);
15904 }
15905 }
15906 }
15907
15908 hunks
15909 }
15910
15911 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15912 self.display_snapshot.buffer_snapshot.language_at(position)
15913 }
15914
15915 pub fn is_focused(&self) -> bool {
15916 self.is_focused
15917 }
15918
15919 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15920 self.placeholder_text.as_ref()
15921 }
15922
15923 pub fn scroll_position(&self) -> gpui::Point<f32> {
15924 self.scroll_anchor.scroll_position(&self.display_snapshot)
15925 }
15926
15927 fn gutter_dimensions(
15928 &self,
15929 font_id: FontId,
15930 font_size: Pixels,
15931 max_line_number_width: Pixels,
15932 cx: &App,
15933 ) -> Option<GutterDimensions> {
15934 if !self.show_gutter {
15935 return None;
15936 }
15937
15938 let descent = cx.text_system().descent(font_id, font_size);
15939 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15940 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15941
15942 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15943 matches!(
15944 ProjectSettings::get_global(cx).git.git_gutter,
15945 Some(GitGutterSetting::TrackedFiles)
15946 )
15947 });
15948 let gutter_settings = EditorSettings::get_global(cx).gutter;
15949 let show_line_numbers = self
15950 .show_line_numbers
15951 .unwrap_or(gutter_settings.line_numbers);
15952 let line_gutter_width = if show_line_numbers {
15953 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15954 let min_width_for_number_on_gutter = em_advance * 4.0;
15955 max_line_number_width.max(min_width_for_number_on_gutter)
15956 } else {
15957 0.0.into()
15958 };
15959
15960 let show_code_actions = self
15961 .show_code_actions
15962 .unwrap_or(gutter_settings.code_actions);
15963
15964 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15965
15966 let git_blame_entries_width =
15967 self.git_blame_gutter_max_author_length
15968 .map(|max_author_length| {
15969 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15970
15971 /// The number of characters to dedicate to gaps and margins.
15972 const SPACING_WIDTH: usize = 4;
15973
15974 let max_char_count = max_author_length
15975 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15976 + ::git::SHORT_SHA_LENGTH
15977 + MAX_RELATIVE_TIMESTAMP.len()
15978 + SPACING_WIDTH;
15979
15980 em_advance * max_char_count
15981 });
15982
15983 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15984 left_padding += if show_code_actions || show_runnables {
15985 em_width * 3.0
15986 } else if show_git_gutter && show_line_numbers {
15987 em_width * 2.0
15988 } else if show_git_gutter || show_line_numbers {
15989 em_width
15990 } else {
15991 px(0.)
15992 };
15993
15994 let right_padding = if gutter_settings.folds && show_line_numbers {
15995 em_width * 4.0
15996 } else if gutter_settings.folds {
15997 em_width * 3.0
15998 } else if show_line_numbers {
15999 em_width
16000 } else {
16001 px(0.)
16002 };
16003
16004 Some(GutterDimensions {
16005 left_padding,
16006 right_padding,
16007 width: line_gutter_width + left_padding + right_padding,
16008 margin: -descent,
16009 git_blame_entries_width,
16010 })
16011 }
16012
16013 pub fn render_crease_toggle(
16014 &self,
16015 buffer_row: MultiBufferRow,
16016 row_contains_cursor: bool,
16017 editor: Entity<Editor>,
16018 window: &mut Window,
16019 cx: &mut App,
16020 ) -> Option<AnyElement> {
16021 let folded = self.is_line_folded(buffer_row);
16022 let mut is_foldable = false;
16023
16024 if let Some(crease) = self
16025 .crease_snapshot
16026 .query_row(buffer_row, &self.buffer_snapshot)
16027 {
16028 is_foldable = true;
16029 match crease {
16030 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16031 if let Some(render_toggle) = render_toggle {
16032 let toggle_callback =
16033 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16034 if folded {
16035 editor.update(cx, |editor, cx| {
16036 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16037 });
16038 } else {
16039 editor.update(cx, |editor, cx| {
16040 editor.unfold_at(
16041 &crate::UnfoldAt { buffer_row },
16042 window,
16043 cx,
16044 )
16045 });
16046 }
16047 });
16048 return Some((render_toggle)(
16049 buffer_row,
16050 folded,
16051 toggle_callback,
16052 window,
16053 cx,
16054 ));
16055 }
16056 }
16057 }
16058 }
16059
16060 is_foldable |= self.starts_indent(buffer_row);
16061
16062 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16063 Some(
16064 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16065 .toggle_state(folded)
16066 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16067 if folded {
16068 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16069 } else {
16070 this.fold_at(&FoldAt { buffer_row }, window, cx);
16071 }
16072 }))
16073 .into_any_element(),
16074 )
16075 } else {
16076 None
16077 }
16078 }
16079
16080 pub fn render_crease_trailer(
16081 &self,
16082 buffer_row: MultiBufferRow,
16083 window: &mut Window,
16084 cx: &mut App,
16085 ) -> Option<AnyElement> {
16086 let folded = self.is_line_folded(buffer_row);
16087 if let Crease::Inline { render_trailer, .. } = self
16088 .crease_snapshot
16089 .query_row(buffer_row, &self.buffer_snapshot)?
16090 {
16091 let render_trailer = render_trailer.as_ref()?;
16092 Some(render_trailer(buffer_row, folded, window, cx))
16093 } else {
16094 None
16095 }
16096 }
16097}
16098
16099impl Deref for EditorSnapshot {
16100 type Target = DisplaySnapshot;
16101
16102 fn deref(&self) -> &Self::Target {
16103 &self.display_snapshot
16104 }
16105}
16106
16107#[derive(Clone, Debug, PartialEq, Eq)]
16108pub enum EditorEvent {
16109 InputIgnored {
16110 text: Arc<str>,
16111 },
16112 InputHandled {
16113 utf16_range_to_replace: Option<Range<isize>>,
16114 text: Arc<str>,
16115 },
16116 ExcerptsAdded {
16117 buffer: Entity<Buffer>,
16118 predecessor: ExcerptId,
16119 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16120 },
16121 ExcerptsRemoved {
16122 ids: Vec<ExcerptId>,
16123 },
16124 BufferFoldToggled {
16125 ids: Vec<ExcerptId>,
16126 folded: bool,
16127 },
16128 ExcerptsEdited {
16129 ids: Vec<ExcerptId>,
16130 },
16131 ExcerptsExpanded {
16132 ids: Vec<ExcerptId>,
16133 },
16134 BufferEdited,
16135 Edited {
16136 transaction_id: clock::Lamport,
16137 },
16138 Reparsed(BufferId),
16139 Focused,
16140 FocusedIn,
16141 Blurred,
16142 DirtyChanged,
16143 Saved,
16144 TitleChanged,
16145 DiffBaseChanged,
16146 SelectionsChanged {
16147 local: bool,
16148 },
16149 ScrollPositionChanged {
16150 local: bool,
16151 autoscroll: bool,
16152 },
16153 Closed,
16154 TransactionUndone {
16155 transaction_id: clock::Lamport,
16156 },
16157 TransactionBegun {
16158 transaction_id: clock::Lamport,
16159 },
16160 Reloaded,
16161 CursorShapeChanged,
16162}
16163
16164impl EventEmitter<EditorEvent> for Editor {}
16165
16166impl Focusable for Editor {
16167 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16168 self.focus_handle.clone()
16169 }
16170}
16171
16172impl Render for Editor {
16173 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16174 let settings = ThemeSettings::get_global(cx);
16175
16176 let mut text_style = match self.mode {
16177 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16178 color: cx.theme().colors().editor_foreground,
16179 font_family: settings.ui_font.family.clone(),
16180 font_features: settings.ui_font.features.clone(),
16181 font_fallbacks: settings.ui_font.fallbacks.clone(),
16182 font_size: rems(0.875).into(),
16183 font_weight: settings.ui_font.weight,
16184 line_height: relative(settings.buffer_line_height.value()),
16185 ..Default::default()
16186 },
16187 EditorMode::Full => TextStyle {
16188 color: cx.theme().colors().editor_foreground,
16189 font_family: settings.buffer_font.family.clone(),
16190 font_features: settings.buffer_font.features.clone(),
16191 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16192 font_size: settings.buffer_font_size(cx).into(),
16193 font_weight: settings.buffer_font.weight,
16194 line_height: relative(settings.buffer_line_height.value()),
16195 ..Default::default()
16196 },
16197 };
16198 if let Some(text_style_refinement) = &self.text_style_refinement {
16199 text_style.refine(text_style_refinement)
16200 }
16201
16202 let background = match self.mode {
16203 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16204 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16205 EditorMode::Full => cx.theme().colors().editor_background,
16206 };
16207
16208 EditorElement::new(
16209 &cx.entity(),
16210 EditorStyle {
16211 background,
16212 local_player: cx.theme().players().local(),
16213 text: text_style,
16214 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16215 syntax: cx.theme().syntax().clone(),
16216 status: cx.theme().status().clone(),
16217 inlay_hints_style: make_inlay_hints_style(cx),
16218 inline_completion_styles: make_suggestion_styles(cx),
16219 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16220 },
16221 )
16222 }
16223}
16224
16225impl EntityInputHandler for Editor {
16226 fn text_for_range(
16227 &mut self,
16228 range_utf16: Range<usize>,
16229 adjusted_range: &mut Option<Range<usize>>,
16230 _: &mut Window,
16231 cx: &mut Context<Self>,
16232 ) -> Option<String> {
16233 let snapshot = self.buffer.read(cx).read(cx);
16234 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16235 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16236 if (start.0..end.0) != range_utf16 {
16237 adjusted_range.replace(start.0..end.0);
16238 }
16239 Some(snapshot.text_for_range(start..end).collect())
16240 }
16241
16242 fn selected_text_range(
16243 &mut self,
16244 ignore_disabled_input: bool,
16245 _: &mut Window,
16246 cx: &mut Context<Self>,
16247 ) -> Option<UTF16Selection> {
16248 // Prevent the IME menu from appearing when holding down an alphabetic key
16249 // while input is disabled.
16250 if !ignore_disabled_input && !self.input_enabled {
16251 return None;
16252 }
16253
16254 let selection = self.selections.newest::<OffsetUtf16>(cx);
16255 let range = selection.range();
16256
16257 Some(UTF16Selection {
16258 range: range.start.0..range.end.0,
16259 reversed: selection.reversed,
16260 })
16261 }
16262
16263 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16264 let snapshot = self.buffer.read(cx).read(cx);
16265 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16266 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16267 }
16268
16269 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16270 self.clear_highlights::<InputComposition>(cx);
16271 self.ime_transaction.take();
16272 }
16273
16274 fn replace_text_in_range(
16275 &mut self,
16276 range_utf16: Option<Range<usize>>,
16277 text: &str,
16278 window: &mut Window,
16279 cx: &mut Context<Self>,
16280 ) {
16281 if !self.input_enabled {
16282 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16283 return;
16284 }
16285
16286 self.transact(window, cx, |this, window, cx| {
16287 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16288 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16289 Some(this.selection_replacement_ranges(range_utf16, cx))
16290 } else {
16291 this.marked_text_ranges(cx)
16292 };
16293
16294 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16295 let newest_selection_id = this.selections.newest_anchor().id;
16296 this.selections
16297 .all::<OffsetUtf16>(cx)
16298 .iter()
16299 .zip(ranges_to_replace.iter())
16300 .find_map(|(selection, range)| {
16301 if selection.id == newest_selection_id {
16302 Some(
16303 (range.start.0 as isize - selection.head().0 as isize)
16304 ..(range.end.0 as isize - selection.head().0 as isize),
16305 )
16306 } else {
16307 None
16308 }
16309 })
16310 });
16311
16312 cx.emit(EditorEvent::InputHandled {
16313 utf16_range_to_replace: range_to_replace,
16314 text: text.into(),
16315 });
16316
16317 if let Some(new_selected_ranges) = new_selected_ranges {
16318 this.change_selections(None, window, cx, |selections| {
16319 selections.select_ranges(new_selected_ranges)
16320 });
16321 this.backspace(&Default::default(), window, cx);
16322 }
16323
16324 this.handle_input(text, window, cx);
16325 });
16326
16327 if let Some(transaction) = self.ime_transaction {
16328 self.buffer.update(cx, |buffer, cx| {
16329 buffer.group_until_transaction(transaction, cx);
16330 });
16331 }
16332
16333 self.unmark_text(window, cx);
16334 }
16335
16336 fn replace_and_mark_text_in_range(
16337 &mut self,
16338 range_utf16: Option<Range<usize>>,
16339 text: &str,
16340 new_selected_range_utf16: Option<Range<usize>>,
16341 window: &mut Window,
16342 cx: &mut Context<Self>,
16343 ) {
16344 if !self.input_enabled {
16345 return;
16346 }
16347
16348 let transaction = self.transact(window, cx, |this, window, cx| {
16349 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16350 let snapshot = this.buffer.read(cx).read(cx);
16351 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16352 for marked_range in &mut marked_ranges {
16353 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16354 marked_range.start.0 += relative_range_utf16.start;
16355 marked_range.start =
16356 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16357 marked_range.end =
16358 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16359 }
16360 }
16361 Some(marked_ranges)
16362 } else if let Some(range_utf16) = range_utf16 {
16363 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16364 Some(this.selection_replacement_ranges(range_utf16, cx))
16365 } else {
16366 None
16367 };
16368
16369 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16370 let newest_selection_id = this.selections.newest_anchor().id;
16371 this.selections
16372 .all::<OffsetUtf16>(cx)
16373 .iter()
16374 .zip(ranges_to_replace.iter())
16375 .find_map(|(selection, range)| {
16376 if selection.id == newest_selection_id {
16377 Some(
16378 (range.start.0 as isize - selection.head().0 as isize)
16379 ..(range.end.0 as isize - selection.head().0 as isize),
16380 )
16381 } else {
16382 None
16383 }
16384 })
16385 });
16386
16387 cx.emit(EditorEvent::InputHandled {
16388 utf16_range_to_replace: range_to_replace,
16389 text: text.into(),
16390 });
16391
16392 if let Some(ranges) = ranges_to_replace {
16393 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16394 }
16395
16396 let marked_ranges = {
16397 let snapshot = this.buffer.read(cx).read(cx);
16398 this.selections
16399 .disjoint_anchors()
16400 .iter()
16401 .map(|selection| {
16402 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16403 })
16404 .collect::<Vec<_>>()
16405 };
16406
16407 if text.is_empty() {
16408 this.unmark_text(window, cx);
16409 } else {
16410 this.highlight_text::<InputComposition>(
16411 marked_ranges.clone(),
16412 HighlightStyle {
16413 underline: Some(UnderlineStyle {
16414 thickness: px(1.),
16415 color: None,
16416 wavy: false,
16417 }),
16418 ..Default::default()
16419 },
16420 cx,
16421 );
16422 }
16423
16424 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16425 let use_autoclose = this.use_autoclose;
16426 let use_auto_surround = this.use_auto_surround;
16427 this.set_use_autoclose(false);
16428 this.set_use_auto_surround(false);
16429 this.handle_input(text, window, cx);
16430 this.set_use_autoclose(use_autoclose);
16431 this.set_use_auto_surround(use_auto_surround);
16432
16433 if let Some(new_selected_range) = new_selected_range_utf16 {
16434 let snapshot = this.buffer.read(cx).read(cx);
16435 let new_selected_ranges = marked_ranges
16436 .into_iter()
16437 .map(|marked_range| {
16438 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16439 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16440 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16441 snapshot.clip_offset_utf16(new_start, Bias::Left)
16442 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16443 })
16444 .collect::<Vec<_>>();
16445
16446 drop(snapshot);
16447 this.change_selections(None, window, cx, |selections| {
16448 selections.select_ranges(new_selected_ranges)
16449 });
16450 }
16451 });
16452
16453 self.ime_transaction = self.ime_transaction.or(transaction);
16454 if let Some(transaction) = self.ime_transaction {
16455 self.buffer.update(cx, |buffer, cx| {
16456 buffer.group_until_transaction(transaction, cx);
16457 });
16458 }
16459
16460 if self.text_highlights::<InputComposition>(cx).is_none() {
16461 self.ime_transaction.take();
16462 }
16463 }
16464
16465 fn bounds_for_range(
16466 &mut self,
16467 range_utf16: Range<usize>,
16468 element_bounds: gpui::Bounds<Pixels>,
16469 window: &mut Window,
16470 cx: &mut Context<Self>,
16471 ) -> Option<gpui::Bounds<Pixels>> {
16472 let text_layout_details = self.text_layout_details(window);
16473 let gpui::Size {
16474 width: em_width,
16475 height: line_height,
16476 } = self.character_size(window);
16477
16478 let snapshot = self.snapshot(window, cx);
16479 let scroll_position = snapshot.scroll_position();
16480 let scroll_left = scroll_position.x * em_width;
16481
16482 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16483 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16484 + self.gutter_dimensions.width
16485 + self.gutter_dimensions.margin;
16486 let y = line_height * (start.row().as_f32() - scroll_position.y);
16487
16488 Some(Bounds {
16489 origin: element_bounds.origin + point(x, y),
16490 size: size(em_width, line_height),
16491 })
16492 }
16493
16494 fn character_index_for_point(
16495 &mut self,
16496 point: gpui::Point<Pixels>,
16497 _window: &mut Window,
16498 _cx: &mut Context<Self>,
16499 ) -> Option<usize> {
16500 let position_map = self.last_position_map.as_ref()?;
16501 if !position_map.text_hitbox.contains(&point) {
16502 return None;
16503 }
16504 let display_point = position_map.point_for_position(point).previous_valid;
16505 let anchor = position_map
16506 .snapshot
16507 .display_point_to_anchor(display_point, Bias::Left);
16508 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16509 Some(utf16_offset.0)
16510 }
16511}
16512
16513trait SelectionExt {
16514 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16515 fn spanned_rows(
16516 &self,
16517 include_end_if_at_line_start: bool,
16518 map: &DisplaySnapshot,
16519 ) -> Range<MultiBufferRow>;
16520}
16521
16522impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16523 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16524 let start = self
16525 .start
16526 .to_point(&map.buffer_snapshot)
16527 .to_display_point(map);
16528 let end = self
16529 .end
16530 .to_point(&map.buffer_snapshot)
16531 .to_display_point(map);
16532 if self.reversed {
16533 end..start
16534 } else {
16535 start..end
16536 }
16537 }
16538
16539 fn spanned_rows(
16540 &self,
16541 include_end_if_at_line_start: bool,
16542 map: &DisplaySnapshot,
16543 ) -> Range<MultiBufferRow> {
16544 let start = self.start.to_point(&map.buffer_snapshot);
16545 let mut end = self.end.to_point(&map.buffer_snapshot);
16546 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16547 end.row -= 1;
16548 }
16549
16550 let buffer_start = map.prev_line_boundary(start).0;
16551 let buffer_end = map.next_line_boundary(end).0;
16552 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16553 }
16554}
16555
16556impl<T: InvalidationRegion> InvalidationStack<T> {
16557 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16558 where
16559 S: Clone + ToOffset,
16560 {
16561 while let Some(region) = self.last() {
16562 let all_selections_inside_invalidation_ranges =
16563 if selections.len() == region.ranges().len() {
16564 selections
16565 .iter()
16566 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16567 .all(|(selection, invalidation_range)| {
16568 let head = selection.head().to_offset(buffer);
16569 invalidation_range.start <= head && invalidation_range.end >= head
16570 })
16571 } else {
16572 false
16573 };
16574
16575 if all_selections_inside_invalidation_ranges {
16576 break;
16577 } else {
16578 self.pop();
16579 }
16580 }
16581 }
16582}
16583
16584impl<T> Default for InvalidationStack<T> {
16585 fn default() -> Self {
16586 Self(Default::default())
16587 }
16588}
16589
16590impl<T> Deref for InvalidationStack<T> {
16591 type Target = Vec<T>;
16592
16593 fn deref(&self) -> &Self::Target {
16594 &self.0
16595 }
16596}
16597
16598impl<T> DerefMut for InvalidationStack<T> {
16599 fn deref_mut(&mut self) -> &mut Self::Target {
16600 &mut self.0
16601 }
16602}
16603
16604impl InvalidationRegion for SnippetState {
16605 fn ranges(&self) -> &[Range<Anchor>] {
16606 &self.ranges[self.active_index]
16607 }
16608}
16609
16610pub fn diagnostic_block_renderer(
16611 diagnostic: Diagnostic,
16612 max_message_rows: Option<u8>,
16613 allow_closing: bool,
16614 _is_valid: bool,
16615) -> RenderBlock {
16616 let (text_without_backticks, code_ranges) =
16617 highlight_diagnostic_message(&diagnostic, max_message_rows);
16618
16619 Arc::new(move |cx: &mut BlockContext| {
16620 let group_id: SharedString = cx.block_id.to_string().into();
16621
16622 let mut text_style = cx.window.text_style().clone();
16623 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16624 let theme_settings = ThemeSettings::get_global(cx);
16625 text_style.font_family = theme_settings.buffer_font.family.clone();
16626 text_style.font_style = theme_settings.buffer_font.style;
16627 text_style.font_features = theme_settings.buffer_font.features.clone();
16628 text_style.font_weight = theme_settings.buffer_font.weight;
16629
16630 let multi_line_diagnostic = diagnostic.message.contains('\n');
16631
16632 let buttons = |diagnostic: &Diagnostic| {
16633 if multi_line_diagnostic {
16634 v_flex()
16635 } else {
16636 h_flex()
16637 }
16638 .when(allow_closing, |div| {
16639 div.children(diagnostic.is_primary.then(|| {
16640 IconButton::new("close-block", IconName::XCircle)
16641 .icon_color(Color::Muted)
16642 .size(ButtonSize::Compact)
16643 .style(ButtonStyle::Transparent)
16644 .visible_on_hover(group_id.clone())
16645 .on_click(move |_click, window, cx| {
16646 window.dispatch_action(Box::new(Cancel), cx)
16647 })
16648 .tooltip(|window, cx| {
16649 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16650 })
16651 }))
16652 })
16653 .child(
16654 IconButton::new("copy-block", IconName::Copy)
16655 .icon_color(Color::Muted)
16656 .size(ButtonSize::Compact)
16657 .style(ButtonStyle::Transparent)
16658 .visible_on_hover(group_id.clone())
16659 .on_click({
16660 let message = diagnostic.message.clone();
16661 move |_click, _, cx| {
16662 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16663 }
16664 })
16665 .tooltip(Tooltip::text("Copy diagnostic message")),
16666 )
16667 };
16668
16669 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16670 AvailableSpace::min_size(),
16671 cx.window,
16672 cx.app,
16673 );
16674
16675 h_flex()
16676 .id(cx.block_id)
16677 .group(group_id.clone())
16678 .relative()
16679 .size_full()
16680 .block_mouse_down()
16681 .pl(cx.gutter_dimensions.width)
16682 .w(cx.max_width - cx.gutter_dimensions.full_width())
16683 .child(
16684 div()
16685 .flex()
16686 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16687 .flex_shrink(),
16688 )
16689 .child(buttons(&diagnostic))
16690 .child(div().flex().flex_shrink_0().child(
16691 StyledText::new(text_without_backticks.clone()).with_highlights(
16692 &text_style,
16693 code_ranges.iter().map(|range| {
16694 (
16695 range.clone(),
16696 HighlightStyle {
16697 font_weight: Some(FontWeight::BOLD),
16698 ..Default::default()
16699 },
16700 )
16701 }),
16702 ),
16703 ))
16704 .into_any_element()
16705 })
16706}
16707
16708fn inline_completion_edit_text(
16709 current_snapshot: &BufferSnapshot,
16710 edits: &[(Range<Anchor>, String)],
16711 edit_preview: &EditPreview,
16712 include_deletions: bool,
16713 cx: &App,
16714) -> HighlightedText {
16715 let edits = edits
16716 .iter()
16717 .map(|(anchor, text)| {
16718 (
16719 anchor.start.text_anchor..anchor.end.text_anchor,
16720 text.clone(),
16721 )
16722 })
16723 .collect::<Vec<_>>();
16724
16725 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16726}
16727
16728pub fn highlight_diagnostic_message(
16729 diagnostic: &Diagnostic,
16730 mut max_message_rows: Option<u8>,
16731) -> (SharedString, Vec<Range<usize>>) {
16732 let mut text_without_backticks = String::new();
16733 let mut code_ranges = Vec::new();
16734
16735 if let Some(source) = &diagnostic.source {
16736 text_without_backticks.push_str(source);
16737 code_ranges.push(0..source.len());
16738 text_without_backticks.push_str(": ");
16739 }
16740
16741 let mut prev_offset = 0;
16742 let mut in_code_block = false;
16743 let has_row_limit = max_message_rows.is_some();
16744 let mut newline_indices = diagnostic
16745 .message
16746 .match_indices('\n')
16747 .filter(|_| has_row_limit)
16748 .map(|(ix, _)| ix)
16749 .fuse()
16750 .peekable();
16751
16752 for (quote_ix, _) in diagnostic
16753 .message
16754 .match_indices('`')
16755 .chain([(diagnostic.message.len(), "")])
16756 {
16757 let mut first_newline_ix = None;
16758 let mut last_newline_ix = None;
16759 while let Some(newline_ix) = newline_indices.peek() {
16760 if *newline_ix < quote_ix {
16761 if first_newline_ix.is_none() {
16762 first_newline_ix = Some(*newline_ix);
16763 }
16764 last_newline_ix = Some(*newline_ix);
16765
16766 if let Some(rows_left) = &mut max_message_rows {
16767 if *rows_left == 0 {
16768 break;
16769 } else {
16770 *rows_left -= 1;
16771 }
16772 }
16773 let _ = newline_indices.next();
16774 } else {
16775 break;
16776 }
16777 }
16778 let prev_len = text_without_backticks.len();
16779 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16780 text_without_backticks.push_str(new_text);
16781 if in_code_block {
16782 code_ranges.push(prev_len..text_without_backticks.len());
16783 }
16784 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16785 in_code_block = !in_code_block;
16786 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16787 text_without_backticks.push_str("...");
16788 break;
16789 }
16790 }
16791
16792 (text_without_backticks.into(), code_ranges)
16793}
16794
16795fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16796 match severity {
16797 DiagnosticSeverity::ERROR => colors.error,
16798 DiagnosticSeverity::WARNING => colors.warning,
16799 DiagnosticSeverity::INFORMATION => colors.info,
16800 DiagnosticSeverity::HINT => colors.info,
16801 _ => colors.ignored,
16802 }
16803}
16804
16805pub fn styled_runs_for_code_label<'a>(
16806 label: &'a CodeLabel,
16807 syntax_theme: &'a theme::SyntaxTheme,
16808) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16809 let fade_out = HighlightStyle {
16810 fade_out: Some(0.35),
16811 ..Default::default()
16812 };
16813
16814 let mut prev_end = label.filter_range.end;
16815 label
16816 .runs
16817 .iter()
16818 .enumerate()
16819 .flat_map(move |(ix, (range, highlight_id))| {
16820 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16821 style
16822 } else {
16823 return Default::default();
16824 };
16825 let mut muted_style = style;
16826 muted_style.highlight(fade_out);
16827
16828 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16829 if range.start >= label.filter_range.end {
16830 if range.start > prev_end {
16831 runs.push((prev_end..range.start, fade_out));
16832 }
16833 runs.push((range.clone(), muted_style));
16834 } else if range.end <= label.filter_range.end {
16835 runs.push((range.clone(), style));
16836 } else {
16837 runs.push((range.start..label.filter_range.end, style));
16838 runs.push((label.filter_range.end..range.end, muted_style));
16839 }
16840 prev_end = cmp::max(prev_end, range.end);
16841
16842 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16843 runs.push((prev_end..label.text.len(), fade_out));
16844 }
16845
16846 runs
16847 })
16848}
16849
16850pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16851 let mut prev_index = 0;
16852 let mut prev_codepoint: Option<char> = None;
16853 text.char_indices()
16854 .chain([(text.len(), '\0')])
16855 .filter_map(move |(index, codepoint)| {
16856 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16857 let is_boundary = index == text.len()
16858 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16859 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16860 if is_boundary {
16861 let chunk = &text[prev_index..index];
16862 prev_index = index;
16863 Some(chunk)
16864 } else {
16865 None
16866 }
16867 })
16868}
16869
16870pub trait RangeToAnchorExt: Sized {
16871 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16872
16873 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16874 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16875 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16876 }
16877}
16878
16879impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16880 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16881 let start_offset = self.start.to_offset(snapshot);
16882 let end_offset = self.end.to_offset(snapshot);
16883 if start_offset == end_offset {
16884 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16885 } else {
16886 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16887 }
16888 }
16889}
16890
16891pub trait RowExt {
16892 fn as_f32(&self) -> f32;
16893
16894 fn next_row(&self) -> Self;
16895
16896 fn previous_row(&self) -> Self;
16897
16898 fn minus(&self, other: Self) -> u32;
16899}
16900
16901impl RowExt for DisplayRow {
16902 fn as_f32(&self) -> f32 {
16903 self.0 as f32
16904 }
16905
16906 fn next_row(&self) -> Self {
16907 Self(self.0 + 1)
16908 }
16909
16910 fn previous_row(&self) -> Self {
16911 Self(self.0.saturating_sub(1))
16912 }
16913
16914 fn minus(&self, other: Self) -> u32 {
16915 self.0 - other.0
16916 }
16917}
16918
16919impl RowExt for MultiBufferRow {
16920 fn as_f32(&self) -> f32 {
16921 self.0 as f32
16922 }
16923
16924 fn next_row(&self) -> Self {
16925 Self(self.0 + 1)
16926 }
16927
16928 fn previous_row(&self) -> Self {
16929 Self(self.0.saturating_sub(1))
16930 }
16931
16932 fn minus(&self, other: Self) -> u32 {
16933 self.0 - other.0
16934 }
16935}
16936
16937trait RowRangeExt {
16938 type Row;
16939
16940 fn len(&self) -> usize;
16941
16942 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16943}
16944
16945impl RowRangeExt for Range<MultiBufferRow> {
16946 type Row = MultiBufferRow;
16947
16948 fn len(&self) -> usize {
16949 (self.end.0 - self.start.0) as usize
16950 }
16951
16952 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16953 (self.start.0..self.end.0).map(MultiBufferRow)
16954 }
16955}
16956
16957impl RowRangeExt for Range<DisplayRow> {
16958 type Row = DisplayRow;
16959
16960 fn len(&self) -> usize {
16961 (self.end.0 - self.start.0) as usize
16962 }
16963
16964 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16965 (self.start.0..self.end.0).map(DisplayRow)
16966 }
16967}
16968
16969/// If select range has more than one line, we
16970/// just point the cursor to range.start.
16971fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16972 if range.start.row == range.end.row {
16973 range
16974 } else {
16975 range.start..range.start
16976 }
16977}
16978pub struct KillRing(ClipboardItem);
16979impl Global for KillRing {}
16980
16981const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16982
16983fn all_edits_insertions_or_deletions(
16984 edits: &Vec<(Range<Anchor>, String)>,
16985 snapshot: &MultiBufferSnapshot,
16986) -> bool {
16987 let mut all_insertions = true;
16988 let mut all_deletions = true;
16989
16990 for (range, new_text) in edits.iter() {
16991 let range_is_empty = range.to_offset(&snapshot).is_empty();
16992 let text_is_empty = new_text.is_empty();
16993
16994 if range_is_empty != text_is_empty {
16995 if range_is_empty {
16996 all_deletions = false;
16997 } else {
16998 all_insertions = false;
16999 }
17000 } else {
17001 return false;
17002 }
17003
17004 if !all_insertions && !all_deletions {
17005 return false;
17006 }
17007 }
17008 all_insertions || all_deletions
17009}