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, TakeUntilExt, 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 {}
286
287#[derive(Debug, Copy, Clone, PartialEq, Eq)]
288pub enum Navigated {
289 Yes,
290 No,
291}
292
293impl Navigated {
294 pub fn from_bool(yes: bool) -> Navigated {
295 if yes {
296 Navigated::Yes
297 } else {
298 Navigated::No
299 }
300 }
301}
302
303pub fn init_settings(cx: &mut App) {
304 EditorSettings::register(cx);
305}
306
307pub fn init(cx: &mut App) {
308 init_settings(cx);
309
310 workspace::register_project_item::<Editor>(cx);
311 workspace::FollowableViewRegistry::register::<Editor>(cx);
312 workspace::register_serializable_item::<Editor>(cx);
313
314 cx.observe_new(
315 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
316 workspace.register_action(Editor::new_file);
317 workspace.register_action(Editor::new_file_vertical);
318 workspace.register_action(Editor::new_file_horizontal);
319 workspace.register_action(Editor::cancel_language_server_work);
320 },
321 )
322 .detach();
323
324 cx.on_action(move |_: &workspace::NewFile, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(
328 Default::default(),
329 app_state,
330 cx,
331 |workspace, window, cx| {
332 Editor::new_file(workspace, &Default::default(), window, cx)
333 },
334 )
335 .detach();
336 }
337 });
338 cx.on_action(move |_: &workspace::NewWindow, cx| {
339 let app_state = workspace::AppState::global(cx);
340 if let Some(app_state) = app_state.upgrade() {
341 workspace::open_new(
342 Default::default(),
343 app_state,
344 cx,
345 |workspace, window, cx| {
346 cx.activate(true);
347 Editor::new_file(workspace, &Default::default(), window, cx)
348 },
349 )
350 .detach();
351 }
352 });
353}
354
355pub struct SearchWithinRange;
356
357trait InvalidationRegion {
358 fn ranges(&self) -> &[Range<Anchor>];
359}
360
361#[derive(Clone, Debug, PartialEq)]
362pub enum SelectPhase {
363 Begin {
364 position: DisplayPoint,
365 add: bool,
366 click_count: usize,
367 },
368 BeginColumnar {
369 position: DisplayPoint,
370 reset: bool,
371 goal_column: u32,
372 },
373 Extend {
374 position: DisplayPoint,
375 click_count: usize,
376 },
377 Update {
378 position: DisplayPoint,
379 goal_column: u32,
380 scroll_delta: gpui::Point<f32>,
381 },
382 End,
383}
384
385#[derive(Clone, Debug)]
386pub enum SelectMode {
387 Character,
388 Word(Range<Anchor>),
389 Line(Range<Anchor>),
390 All,
391}
392
393#[derive(Copy, Clone, PartialEq, Eq, Debug)]
394pub enum EditorMode {
395 SingleLine { auto_width: bool },
396 AutoHeight { max_lines: usize },
397 Full,
398}
399
400#[derive(Copy, Clone, Debug)]
401pub enum SoftWrap {
402 /// Prefer not to wrap at all.
403 ///
404 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
405 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
406 GitDiff,
407 /// Prefer a single line generally, unless an overly long line is encountered.
408 None,
409 /// Soft wrap lines that exceed the editor width.
410 EditorWidth,
411 /// Soft wrap lines at the preferred line length.
412 Column(u32),
413 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
414 Bounded(u32),
415}
416
417#[derive(Clone)]
418pub struct EditorStyle {
419 pub background: Hsla,
420 pub local_player: PlayerColor,
421 pub text: TextStyle,
422 pub scrollbar_width: Pixels,
423 pub syntax: Arc<SyntaxTheme>,
424 pub status: StatusColors,
425 pub inlay_hints_style: HighlightStyle,
426 pub inline_completion_styles: InlineCompletionStyles,
427 pub unnecessary_code_fade: f32,
428}
429
430impl Default for EditorStyle {
431 fn default() -> Self {
432 Self {
433 background: Hsla::default(),
434 local_player: PlayerColor::default(),
435 text: TextStyle::default(),
436 scrollbar_width: Pixels::default(),
437 syntax: Default::default(),
438 // HACK: Status colors don't have a real default.
439 // We should look into removing the status colors from the editor
440 // style and retrieve them directly from the theme.
441 status: StatusColors::dark(),
442 inlay_hints_style: HighlightStyle::default(),
443 inline_completion_styles: InlineCompletionStyles {
444 insertion: HighlightStyle::default(),
445 whitespace: HighlightStyle::default(),
446 },
447 unnecessary_code_fade: Default::default(),
448 }
449 }
450}
451
452pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
453 let show_background = language_settings::language_settings(None, None, cx)
454 .inlay_hints
455 .show_background;
456
457 HighlightStyle {
458 color: Some(cx.theme().status().hint),
459 background_color: show_background.then(|| cx.theme().status().hint_background),
460 ..HighlightStyle::default()
461 }
462}
463
464pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
465 InlineCompletionStyles {
466 insertion: HighlightStyle {
467 color: Some(cx.theme().status().predictive),
468 ..HighlightStyle::default()
469 },
470 whitespace: HighlightStyle {
471 background_color: Some(cx.theme().status().created_background),
472 ..HighlightStyle::default()
473 },
474 }
475}
476
477type CompletionId = usize;
478
479pub(crate) enum EditDisplayMode {
480 TabAccept,
481 DiffPopover,
482 Inline,
483}
484
485enum InlineCompletion {
486 Edit {
487 edits: Vec<(Range<Anchor>, String)>,
488 edit_preview: Option<EditPreview>,
489 display_mode: EditDisplayMode,
490 snapshot: BufferSnapshot,
491 },
492 Move {
493 target: Anchor,
494 snapshot: BufferSnapshot,
495 },
496}
497
498struct InlineCompletionState {
499 inlay_ids: Vec<InlayId>,
500 completion: InlineCompletion,
501 completion_id: Option<SharedString>,
502 invalidation_range: Range<Anchor>,
503}
504
505enum EditPredictionSettings {
506 Disabled,
507 Enabled {
508 show_in_menu: bool,
509 preview_requires_modifier: bool,
510 },
511}
512
513enum InlineCompletionHighlight {}
514
515pub enum MenuInlineCompletionsPolicy {
516 Never,
517 ByProvider,
518}
519
520pub enum EditPredictionPreview {
521 /// Modifier is not pressed
522 Inactive,
523 /// Modifier pressed
524 Active {
525 previous_scroll_position: Option<ScrollAnchor>,
526 },
527}
528
529#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
530struct EditorActionId(usize);
531
532impl EditorActionId {
533 pub fn post_inc(&mut self) -> Self {
534 let answer = self.0;
535
536 *self = Self(answer + 1);
537
538 Self(answer)
539 }
540}
541
542// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
543// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
544
545type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
546type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
547
548#[derive(Default)]
549struct ScrollbarMarkerState {
550 scrollbar_size: Size<Pixels>,
551 dirty: bool,
552 markers: Arc<[PaintQuad]>,
553 pending_refresh: Option<Task<Result<()>>>,
554}
555
556impl ScrollbarMarkerState {
557 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
558 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
559 }
560}
561
562#[derive(Clone, Debug)]
563struct RunnableTasks {
564 templates: Vec<(TaskSourceKind, TaskTemplate)>,
565 offset: MultiBufferOffset,
566 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
567 column: u32,
568 // Values of all named captures, including those starting with '_'
569 extra_variables: HashMap<String, String>,
570 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
571 context_range: Range<BufferOffset>,
572}
573
574impl RunnableTasks {
575 fn resolve<'a>(
576 &'a self,
577 cx: &'a task::TaskContext,
578 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
579 self.templates.iter().filter_map(|(kind, template)| {
580 template
581 .resolve_task(&kind.to_id_base(), cx)
582 .map(|task| (kind.clone(), task))
583 })
584 }
585}
586
587#[derive(Clone)]
588struct ResolvedTasks {
589 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
590 position: Anchor,
591}
592#[derive(Copy, Clone, Debug)]
593struct MultiBufferOffset(usize);
594#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
595struct BufferOffset(usize);
596
597// Addons allow storing per-editor state in other crates (e.g. Vim)
598pub trait Addon: 'static {
599 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
600
601 fn render_buffer_header_controls(
602 &self,
603 _: &ExcerptInfo,
604 _: &Window,
605 _: &App,
606 ) -> Option<AnyElement> {
607 None
608 }
609
610 fn to_any(&self) -> &dyn std::any::Any;
611}
612
613#[derive(Debug, Copy, Clone, PartialEq, Eq)]
614pub enum IsVimMode {
615 Yes,
616 No,
617}
618
619/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
620///
621/// See the [module level documentation](self) for more information.
622pub struct Editor {
623 focus_handle: FocusHandle,
624 last_focused_descendant: Option<WeakFocusHandle>,
625 /// The text buffer being edited
626 buffer: Entity<MultiBuffer>,
627 /// Map of how text in the buffer should be displayed.
628 /// Handles soft wraps, folds, fake inlay text insertions, etc.
629 pub display_map: Entity<DisplayMap>,
630 pub selections: SelectionsCollection,
631 pub scroll_manager: ScrollManager,
632 /// When inline assist editors are linked, they all render cursors because
633 /// typing enters text into each of them, even the ones that aren't focused.
634 pub(crate) show_cursor_when_unfocused: bool,
635 columnar_selection_tail: Option<Anchor>,
636 add_selections_state: Option<AddSelectionsState>,
637 select_next_state: Option<SelectNextState>,
638 select_prev_state: Option<SelectNextState>,
639 selection_history: SelectionHistory,
640 autoclose_regions: Vec<AutocloseRegion>,
641 snippet_stack: InvalidationStack<SnippetState>,
642 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
643 ime_transaction: Option<TransactionId>,
644 active_diagnostics: Option<ActiveDiagnosticGroup>,
645 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
646
647 // TODO: make this a access method
648 pub project: Option<Entity<Project>>,
649 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
650 completion_provider: Option<Box<dyn CompletionProvider>>,
651 collaboration_hub: Option<Box<dyn CollaborationHub>>,
652 blink_manager: Entity<BlinkManager>,
653 show_cursor_names: bool,
654 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
655 pub show_local_selections: bool,
656 mode: EditorMode,
657 show_breadcrumbs: bool,
658 show_gutter: bool,
659 show_scrollbars: bool,
660 show_line_numbers: Option<bool>,
661 use_relative_line_numbers: Option<bool>,
662 show_git_diff_gutter: Option<bool>,
663 show_code_actions: Option<bool>,
664 show_runnables: Option<bool>,
665 show_wrap_guides: Option<bool>,
666 show_indent_guides: Option<bool>,
667 placeholder_text: Option<Arc<str>>,
668 highlight_order: usize,
669 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
670 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
671 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
672 scrollbar_marker_state: ScrollbarMarkerState,
673 active_indent_guides_state: ActiveIndentGuidesState,
674 nav_history: Option<ItemNavHistory>,
675 context_menu: RefCell<Option<CodeContextMenu>>,
676 mouse_context_menu: Option<MouseContextMenu>,
677 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
678 signature_help_state: SignatureHelpState,
679 auto_signature_help: Option<bool>,
680 find_all_references_task_sources: Vec<Anchor>,
681 next_completion_id: CompletionId,
682 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
683 code_actions_task: Option<Task<Result<()>>>,
684 document_highlights_task: Option<Task<()>>,
685 linked_editing_range_task: Option<Task<Option<()>>>,
686 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
687 pending_rename: Option<RenameState>,
688 searchable: bool,
689 cursor_shape: CursorShape,
690 current_line_highlight: Option<CurrentLineHighlight>,
691 collapse_matches: bool,
692 autoindent_mode: Option<AutoindentMode>,
693 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
694 input_enabled: bool,
695 use_modal_editing: bool,
696 read_only: bool,
697 leader_peer_id: Option<PeerId>,
698 remote_id: Option<ViewId>,
699 hover_state: HoverState,
700 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
701 gutter_hovered: bool,
702 hovered_link_state: Option<HoveredLinkState>,
703 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
704 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
705 active_inline_completion: Option<InlineCompletionState>,
706 /// Used to prevent flickering as the user types while the menu is open
707 stale_inline_completion_in_menu: Option<InlineCompletionState>,
708 edit_prediction_settings: EditPredictionSettings,
709 inline_completions_hidden_for_vim_mode: bool,
710 show_inline_completions_override: Option<bool>,
711 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
712 edit_prediction_preview: EditPredictionPreview,
713 edit_prediction_cursor_on_leading_whitespace: bool,
714 edit_prediction_requires_modifier_in_leading_space: bool,
715 inlay_hint_cache: InlayHintCache,
716 next_inlay_id: usize,
717 _subscriptions: Vec<Subscription>,
718 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
719 gutter_dimensions: GutterDimensions,
720 style: Option<EditorStyle>,
721 text_style_refinement: Option<TextStyleRefinement>,
722 next_editor_action_id: EditorActionId,
723 editor_actions:
724 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
725 use_autoclose: bool,
726 use_auto_surround: bool,
727 auto_replace_emoji_shortcode: bool,
728 show_git_blame_gutter: bool,
729 show_git_blame_inline: bool,
730 show_git_blame_inline_delay_task: Option<Task<()>>,
731 distinguish_unstaged_diff_hunks: bool,
732 git_blame_inline_enabled: bool,
733 serialize_dirty_buffers: bool,
734 show_selection_menu: Option<bool>,
735 blame: Option<Entity<GitBlame>>,
736 blame_subscription: Option<Subscription>,
737 custom_context_menu: Option<
738 Box<
739 dyn 'static
740 + Fn(
741 &mut Self,
742 DisplayPoint,
743 &mut Window,
744 &mut Context<Self>,
745 ) -> Option<Entity<ui::ContextMenu>>,
746 >,
747 >,
748 last_bounds: Option<Bounds<Pixels>>,
749 last_position_map: Option<Rc<PositionMap>>,
750 expect_bounds_change: Option<Bounds<Pixels>>,
751 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
752 tasks_update_task: Option<Task<()>>,
753 in_project_search: bool,
754 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
755 breadcrumb_header: Option<String>,
756 focused_block: Option<FocusedBlock>,
757 next_scroll_position: NextScrollCursorCenterTopBottom,
758 addons: HashMap<TypeId, Box<dyn Addon>>,
759 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
760 load_diff_task: Option<Shared<Task<()>>>,
761 selection_mark_mode: bool,
762 toggle_fold_multiple_buffers: Task<()>,
763 _scroll_cursor_center_top_bottom_task: Task<()>,
764}
765
766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
767enum NextScrollCursorCenterTopBottom {
768 #[default]
769 Center,
770 Top,
771 Bottom,
772}
773
774impl NextScrollCursorCenterTopBottom {
775 fn next(&self) -> Self {
776 match self {
777 Self::Center => Self::Top,
778 Self::Top => Self::Bottom,
779 Self::Bottom => Self::Center,
780 }
781 }
782}
783
784#[derive(Clone)]
785pub struct EditorSnapshot {
786 pub mode: EditorMode,
787 show_gutter: bool,
788 show_line_numbers: Option<bool>,
789 show_git_diff_gutter: Option<bool>,
790 show_code_actions: Option<bool>,
791 show_runnables: Option<bool>,
792 git_blame_gutter_max_author_length: Option<usize>,
793 pub display_snapshot: DisplaySnapshot,
794 pub placeholder_text: Option<Arc<str>>,
795 is_focused: bool,
796 scroll_anchor: ScrollAnchor,
797 ongoing_scroll: OngoingScroll,
798 current_line_highlight: CurrentLineHighlight,
799 gutter_hovered: bool,
800}
801
802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
803
804#[derive(Default, Debug, Clone, Copy)]
805pub struct GutterDimensions {
806 pub left_padding: Pixels,
807 pub right_padding: Pixels,
808 pub width: Pixels,
809 pub margin: Pixels,
810 pub git_blame_entries_width: Option<Pixels>,
811}
812
813impl GutterDimensions {
814 /// The full width of the space taken up by the gutter.
815 pub fn full_width(&self) -> Pixels {
816 self.margin + self.width
817 }
818
819 /// The width of the space reserved for the fold indicators,
820 /// use alongside 'justify_end' and `gutter_width` to
821 /// right align content with the line numbers
822 pub fn fold_area_width(&self) -> Pixels {
823 self.margin + self.right_padding
824 }
825}
826
827#[derive(Debug)]
828pub struct RemoteSelection {
829 pub replica_id: ReplicaId,
830 pub selection: Selection<Anchor>,
831 pub cursor_shape: CursorShape,
832 pub peer_id: PeerId,
833 pub line_mode: bool,
834 pub participant_index: Option<ParticipantIndex>,
835 pub user_name: Option<SharedString>,
836}
837
838#[derive(Clone, Debug)]
839struct SelectionHistoryEntry {
840 selections: Arc<[Selection<Anchor>]>,
841 select_next_state: Option<SelectNextState>,
842 select_prev_state: Option<SelectNextState>,
843 add_selections_state: Option<AddSelectionsState>,
844}
845
846enum SelectionHistoryMode {
847 Normal,
848 Undoing,
849 Redoing,
850}
851
852#[derive(Clone, PartialEq, Eq, Hash)]
853struct HoveredCursor {
854 replica_id: u16,
855 selection_id: usize,
856}
857
858impl Default for SelectionHistoryMode {
859 fn default() -> Self {
860 Self::Normal
861 }
862}
863
864#[derive(Default)]
865struct SelectionHistory {
866 #[allow(clippy::type_complexity)]
867 selections_by_transaction:
868 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
869 mode: SelectionHistoryMode,
870 undo_stack: VecDeque<SelectionHistoryEntry>,
871 redo_stack: VecDeque<SelectionHistoryEntry>,
872}
873
874impl SelectionHistory {
875 fn insert_transaction(
876 &mut self,
877 transaction_id: TransactionId,
878 selections: Arc<[Selection<Anchor>]>,
879 ) {
880 self.selections_by_transaction
881 .insert(transaction_id, (selections, None));
882 }
883
884 #[allow(clippy::type_complexity)]
885 fn transaction(
886 &self,
887 transaction_id: TransactionId,
888 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
889 self.selections_by_transaction.get(&transaction_id)
890 }
891
892 #[allow(clippy::type_complexity)]
893 fn transaction_mut(
894 &mut self,
895 transaction_id: TransactionId,
896 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
897 self.selections_by_transaction.get_mut(&transaction_id)
898 }
899
900 fn push(&mut self, entry: SelectionHistoryEntry) {
901 if !entry.selections.is_empty() {
902 match self.mode {
903 SelectionHistoryMode::Normal => {
904 self.push_undo(entry);
905 self.redo_stack.clear();
906 }
907 SelectionHistoryMode::Undoing => self.push_redo(entry),
908 SelectionHistoryMode::Redoing => self.push_undo(entry),
909 }
910 }
911 }
912
913 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
914 if self
915 .undo_stack
916 .back()
917 .map_or(true, |e| e.selections != entry.selections)
918 {
919 self.undo_stack.push_back(entry);
920 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
921 self.undo_stack.pop_front();
922 }
923 }
924 }
925
926 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
927 if self
928 .redo_stack
929 .back()
930 .map_or(true, |e| e.selections != entry.selections)
931 {
932 self.redo_stack.push_back(entry);
933 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
934 self.redo_stack.pop_front();
935 }
936 }
937 }
938}
939
940struct RowHighlight {
941 index: usize,
942 range: Range<Anchor>,
943 color: Hsla,
944 should_autoscroll: bool,
945}
946
947#[derive(Clone, Debug)]
948struct AddSelectionsState {
949 above: bool,
950 stack: Vec<usize>,
951}
952
953#[derive(Clone)]
954struct SelectNextState {
955 query: AhoCorasick,
956 wordwise: bool,
957 done: bool,
958}
959
960impl std::fmt::Debug for SelectNextState {
961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962 f.debug_struct(std::any::type_name::<Self>())
963 .field("wordwise", &self.wordwise)
964 .field("done", &self.done)
965 .finish()
966 }
967}
968
969#[derive(Debug)]
970struct AutocloseRegion {
971 selection_id: usize,
972 range: Range<Anchor>,
973 pair: BracketPair,
974}
975
976#[derive(Debug)]
977struct SnippetState {
978 ranges: Vec<Vec<Range<Anchor>>>,
979 active_index: usize,
980 choices: Vec<Option<Vec<String>>>,
981}
982
983#[doc(hidden)]
984pub struct RenameState {
985 pub range: Range<Anchor>,
986 pub old_name: Arc<str>,
987 pub editor: Entity<Editor>,
988 block_id: CustomBlockId,
989}
990
991struct InvalidationStack<T>(Vec<T>);
992
993struct RegisteredInlineCompletionProvider {
994 provider: Arc<dyn InlineCompletionProviderHandle>,
995 _subscription: Subscription,
996}
997
998#[derive(Debug)]
999struct ActiveDiagnosticGroup {
1000 primary_range: Range<Anchor>,
1001 primary_message: String,
1002 group_id: usize,
1003 blocks: HashMap<CustomBlockId, Diagnostic>,
1004 is_valid: bool,
1005}
1006
1007#[derive(Serialize, Deserialize, Clone, Debug)]
1008pub struct ClipboardSelection {
1009 pub len: usize,
1010 pub is_entire_line: bool,
1011 pub first_line_indent: u32,
1012}
1013
1014#[derive(Debug)]
1015pub(crate) struct NavigationData {
1016 cursor_anchor: Anchor,
1017 cursor_position: Point,
1018 scroll_anchor: ScrollAnchor,
1019 scroll_top_row: u32,
1020}
1021
1022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1023pub enum GotoDefinitionKind {
1024 Symbol,
1025 Declaration,
1026 Type,
1027 Implementation,
1028}
1029
1030#[derive(Debug, Clone)]
1031enum InlayHintRefreshReason {
1032 Toggle(bool),
1033 SettingsChange(InlayHintSettings),
1034 NewLinesShown,
1035 BufferEdited(HashSet<Arc<Language>>),
1036 RefreshRequested,
1037 ExcerptsRemoved(Vec<ExcerptId>),
1038}
1039
1040impl InlayHintRefreshReason {
1041 fn description(&self) -> &'static str {
1042 match self {
1043 Self::Toggle(_) => "toggle",
1044 Self::SettingsChange(_) => "settings change",
1045 Self::NewLinesShown => "new lines shown",
1046 Self::BufferEdited(_) => "buffer edited",
1047 Self::RefreshRequested => "refresh requested",
1048 Self::ExcerptsRemoved(_) => "excerpts removed",
1049 }
1050 }
1051}
1052
1053pub enum FormatTarget {
1054 Buffers,
1055 Ranges(Vec<Range<MultiBufferPoint>>),
1056}
1057
1058pub(crate) struct FocusedBlock {
1059 id: BlockId,
1060 focus_handle: WeakFocusHandle,
1061}
1062
1063#[derive(Clone)]
1064enum JumpData {
1065 MultiBufferRow {
1066 row: MultiBufferRow,
1067 line_offset_from_top: u32,
1068 },
1069 MultiBufferPoint {
1070 excerpt_id: ExcerptId,
1071 position: Point,
1072 anchor: text::Anchor,
1073 line_offset_from_top: u32,
1074 },
1075}
1076
1077pub enum MultibufferSelectionMode {
1078 First,
1079 All,
1080}
1081
1082impl Editor {
1083 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1084 let buffer = cx.new(|cx| Buffer::local("", cx));
1085 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1086 Self::new(
1087 EditorMode::SingleLine { auto_width: false },
1088 buffer,
1089 None,
1090 false,
1091 window,
1092 cx,
1093 )
1094 }
1095
1096 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1097 let buffer = cx.new(|cx| Buffer::local("", cx));
1098 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1099 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1100 }
1101
1102 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1103 let buffer = cx.new(|cx| Buffer::local("", cx));
1104 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1105 Self::new(
1106 EditorMode::SingleLine { auto_width: true },
1107 buffer,
1108 None,
1109 false,
1110 window,
1111 cx,
1112 )
1113 }
1114
1115 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1116 let buffer = cx.new(|cx| Buffer::local("", cx));
1117 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1118 Self::new(
1119 EditorMode::AutoHeight { max_lines },
1120 buffer,
1121 None,
1122 false,
1123 window,
1124 cx,
1125 )
1126 }
1127
1128 pub fn for_buffer(
1129 buffer: Entity<Buffer>,
1130 project: Option<Entity<Project>>,
1131 window: &mut Window,
1132 cx: &mut Context<Self>,
1133 ) -> Self {
1134 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1135 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1136 }
1137
1138 pub fn for_multibuffer(
1139 buffer: Entity<MultiBuffer>,
1140 project: Option<Entity<Project>>,
1141 show_excerpt_controls: bool,
1142 window: &mut Window,
1143 cx: &mut Context<Self>,
1144 ) -> Self {
1145 Self::new(
1146 EditorMode::Full,
1147 buffer,
1148 project,
1149 show_excerpt_controls,
1150 window,
1151 cx,
1152 )
1153 }
1154
1155 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1156 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1157 let mut clone = Self::new(
1158 self.mode,
1159 self.buffer.clone(),
1160 self.project.clone(),
1161 show_excerpt_controls,
1162 window,
1163 cx,
1164 );
1165 self.display_map.update(cx, |display_map, cx| {
1166 let snapshot = display_map.snapshot(cx);
1167 clone.display_map.update(cx, |display_map, cx| {
1168 display_map.set_state(&snapshot, cx);
1169 });
1170 });
1171 clone.selections.clone_state(&self.selections);
1172 clone.scroll_manager.clone_state(&self.scroll_manager);
1173 clone.searchable = self.searchable;
1174 clone
1175 }
1176
1177 pub fn new(
1178 mode: EditorMode,
1179 buffer: Entity<MultiBuffer>,
1180 project: Option<Entity<Project>>,
1181 show_excerpt_controls: bool,
1182 window: &mut Window,
1183 cx: &mut Context<Self>,
1184 ) -> Self {
1185 let style = window.text_style();
1186 let font_size = style.font_size.to_pixels(window.rem_size());
1187 let editor = cx.entity().downgrade();
1188 let fold_placeholder = FoldPlaceholder {
1189 constrain_width: true,
1190 render: Arc::new(move |fold_id, fold_range, _, cx| {
1191 let editor = editor.clone();
1192 div()
1193 .id(fold_id)
1194 .bg(cx.theme().colors().ghost_element_background)
1195 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1196 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1197 .rounded_sm()
1198 .size_full()
1199 .cursor_pointer()
1200 .child("⋯")
1201 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1202 .on_click(move |_, _window, cx| {
1203 editor
1204 .update(cx, |editor, cx| {
1205 editor.unfold_ranges(
1206 &[fold_range.start..fold_range.end],
1207 true,
1208 false,
1209 cx,
1210 );
1211 cx.stop_propagation();
1212 })
1213 .ok();
1214 })
1215 .into_any()
1216 }),
1217 merge_adjacent: true,
1218 ..Default::default()
1219 };
1220 let display_map = cx.new(|cx| {
1221 DisplayMap::new(
1222 buffer.clone(),
1223 style.font(),
1224 font_size,
1225 None,
1226 show_excerpt_controls,
1227 FILE_HEADER_HEIGHT,
1228 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1229 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1230 fold_placeholder,
1231 cx,
1232 )
1233 });
1234
1235 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1236
1237 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1238
1239 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1240 .then(|| language_settings::SoftWrap::None);
1241
1242 let mut project_subscriptions = Vec::new();
1243 if mode == EditorMode::Full {
1244 if let Some(project) = project.as_ref() {
1245 if buffer.read(cx).is_singleton() {
1246 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1247 cx.emit(EditorEvent::TitleChanged);
1248 }));
1249 }
1250 project_subscriptions.push(cx.subscribe_in(
1251 project,
1252 window,
1253 |editor, _, event, window, cx| {
1254 if let project::Event::RefreshInlayHints = event {
1255 editor
1256 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1257 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1258 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1259 let focus_handle = editor.focus_handle(cx);
1260 if focus_handle.is_focused(window) {
1261 let snapshot = buffer.read(cx).snapshot();
1262 for (range, snippet) in snippet_edits {
1263 let editor_range =
1264 language::range_from_lsp(*range).to_offset(&snapshot);
1265 editor
1266 .insert_snippet(
1267 &[editor_range],
1268 snippet.clone(),
1269 window,
1270 cx,
1271 )
1272 .ok();
1273 }
1274 }
1275 }
1276 }
1277 },
1278 ));
1279 if let Some(task_inventory) = project
1280 .read(cx)
1281 .task_store()
1282 .read(cx)
1283 .task_inventory()
1284 .cloned()
1285 {
1286 project_subscriptions.push(cx.observe_in(
1287 &task_inventory,
1288 window,
1289 |editor, _, window, cx| {
1290 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1291 },
1292 ));
1293 }
1294 }
1295 }
1296
1297 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1298
1299 let inlay_hint_settings =
1300 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1301 let focus_handle = cx.focus_handle();
1302 cx.on_focus(&focus_handle, window, Self::handle_focus)
1303 .detach();
1304 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1305 .detach();
1306 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1307 .detach();
1308 cx.on_blur(&focus_handle, window, Self::handle_blur)
1309 .detach();
1310
1311 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1312 Some(false)
1313 } else {
1314 None
1315 };
1316
1317 let mut code_action_providers = Vec::new();
1318 let mut load_uncommitted_diff = None;
1319 if let Some(project) = project.clone() {
1320 load_uncommitted_diff = Some(
1321 get_uncommitted_diff_for_buffer(
1322 &project,
1323 buffer.read(cx).all_buffers(),
1324 buffer.clone(),
1325 cx,
1326 )
1327 .shared(),
1328 );
1329 code_action_providers.push(Rc::new(project) as Rc<_>);
1330 }
1331
1332 let mut this = Self {
1333 focus_handle,
1334 show_cursor_when_unfocused: false,
1335 last_focused_descendant: None,
1336 buffer: buffer.clone(),
1337 display_map: display_map.clone(),
1338 selections,
1339 scroll_manager: ScrollManager::new(cx),
1340 columnar_selection_tail: None,
1341 add_selections_state: None,
1342 select_next_state: None,
1343 select_prev_state: None,
1344 selection_history: Default::default(),
1345 autoclose_regions: Default::default(),
1346 snippet_stack: Default::default(),
1347 select_larger_syntax_node_stack: Vec::new(),
1348 ime_transaction: Default::default(),
1349 active_diagnostics: None,
1350 soft_wrap_mode_override,
1351 completion_provider: project.clone().map(|project| Box::new(project) as _),
1352 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1353 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1354 project,
1355 blink_manager: blink_manager.clone(),
1356 show_local_selections: true,
1357 show_scrollbars: true,
1358 mode,
1359 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1360 show_gutter: mode == EditorMode::Full,
1361 show_line_numbers: None,
1362 use_relative_line_numbers: None,
1363 show_git_diff_gutter: None,
1364 show_code_actions: None,
1365 show_runnables: None,
1366 show_wrap_guides: None,
1367 show_indent_guides,
1368 placeholder_text: None,
1369 highlight_order: 0,
1370 highlighted_rows: HashMap::default(),
1371 background_highlights: Default::default(),
1372 gutter_highlights: TreeMap::default(),
1373 scrollbar_marker_state: ScrollbarMarkerState::default(),
1374 active_indent_guides_state: ActiveIndentGuidesState::default(),
1375 nav_history: None,
1376 context_menu: RefCell::new(None),
1377 mouse_context_menu: None,
1378 completion_tasks: Default::default(),
1379 signature_help_state: SignatureHelpState::default(),
1380 auto_signature_help: None,
1381 find_all_references_task_sources: Vec::new(),
1382 next_completion_id: 0,
1383 next_inlay_id: 0,
1384 code_action_providers,
1385 available_code_actions: Default::default(),
1386 code_actions_task: Default::default(),
1387 document_highlights_task: Default::default(),
1388 linked_editing_range_task: Default::default(),
1389 pending_rename: Default::default(),
1390 searchable: true,
1391 cursor_shape: EditorSettings::get_global(cx)
1392 .cursor_shape
1393 .unwrap_or_default(),
1394 current_line_highlight: None,
1395 autoindent_mode: Some(AutoindentMode::EachLine),
1396 collapse_matches: false,
1397 workspace: None,
1398 input_enabled: true,
1399 use_modal_editing: mode == EditorMode::Full,
1400 read_only: false,
1401 use_autoclose: true,
1402 use_auto_surround: true,
1403 auto_replace_emoji_shortcode: false,
1404 leader_peer_id: None,
1405 remote_id: None,
1406 hover_state: Default::default(),
1407 pending_mouse_down: None,
1408 hovered_link_state: Default::default(),
1409 edit_prediction_provider: None,
1410 active_inline_completion: None,
1411 stale_inline_completion_in_menu: None,
1412 edit_prediction_preview: EditPredictionPreview::Inactive,
1413 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1414
1415 gutter_hovered: false,
1416 pixel_position_of_newest_cursor: None,
1417 last_bounds: None,
1418 last_position_map: None,
1419 expect_bounds_change: None,
1420 gutter_dimensions: GutterDimensions::default(),
1421 style: None,
1422 show_cursor_names: false,
1423 hovered_cursors: Default::default(),
1424 next_editor_action_id: EditorActionId::default(),
1425 editor_actions: Rc::default(),
1426 inline_completions_hidden_for_vim_mode: false,
1427 show_inline_completions_override: None,
1428 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1429 edit_prediction_settings: EditPredictionSettings::Disabled,
1430 edit_prediction_cursor_on_leading_whitespace: false,
1431 edit_prediction_requires_modifier_in_leading_space: true,
1432 custom_context_menu: None,
1433 show_git_blame_gutter: false,
1434 show_git_blame_inline: false,
1435 distinguish_unstaged_diff_hunks: false,
1436 show_selection_menu: None,
1437 show_git_blame_inline_delay_task: None,
1438 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1439 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1440 .session
1441 .restore_unsaved_buffers,
1442 blame: None,
1443 blame_subscription: None,
1444 tasks: Default::default(),
1445 _subscriptions: vec![
1446 cx.observe(&buffer, Self::on_buffer_changed),
1447 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1448 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1449 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1450 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1451 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1452 cx.observe_window_activation(window, |editor, window, cx| {
1453 let active = window.is_window_active();
1454 editor.blink_manager.update(cx, |blink_manager, cx| {
1455 if active {
1456 blink_manager.enable(cx);
1457 } else {
1458 blink_manager.disable(cx);
1459 }
1460 });
1461 }),
1462 ],
1463 tasks_update_task: None,
1464 linked_edit_ranges: Default::default(),
1465 in_project_search: false,
1466 previous_search_ranges: None,
1467 breadcrumb_header: None,
1468 focused_block: None,
1469 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1470 addons: HashMap::default(),
1471 registered_buffers: HashMap::default(),
1472 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1473 selection_mark_mode: false,
1474 toggle_fold_multiple_buffers: Task::ready(()),
1475 text_style_refinement: None,
1476 load_diff_task: load_uncommitted_diff,
1477 };
1478 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1479 this._subscriptions.extend(project_subscriptions);
1480
1481 this.end_selection(window, cx);
1482 this.scroll_manager.show_scrollbar(window, cx);
1483
1484 if mode == EditorMode::Full {
1485 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1486 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1487
1488 if this.git_blame_inline_enabled {
1489 this.git_blame_inline_enabled = true;
1490 this.start_git_blame_inline(false, window, cx);
1491 }
1492
1493 if let Some(buffer) = buffer.read(cx).as_singleton() {
1494 if let Some(project) = this.project.as_ref() {
1495 let handle = project.update(cx, |project, cx| {
1496 project.register_buffer_with_language_servers(&buffer, cx)
1497 });
1498 this.registered_buffers
1499 .insert(buffer.read(cx).remote_id(), handle);
1500 }
1501 }
1502 }
1503
1504 this.report_editor_event("Editor Opened", None, cx);
1505 this
1506 }
1507
1508 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1509 self.mouse_context_menu
1510 .as_ref()
1511 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1512 }
1513
1514 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1515 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1516 }
1517
1518 fn key_context_internal(
1519 &self,
1520 has_active_edit_prediction: bool,
1521 window: &Window,
1522 cx: &App,
1523 ) -> KeyContext {
1524 let mut key_context = KeyContext::new_with_defaults();
1525 key_context.add("Editor");
1526 let mode = match self.mode {
1527 EditorMode::SingleLine { .. } => "single_line",
1528 EditorMode::AutoHeight { .. } => "auto_height",
1529 EditorMode::Full => "full",
1530 };
1531
1532 if EditorSettings::jupyter_enabled(cx) {
1533 key_context.add("jupyter");
1534 }
1535
1536 key_context.set("mode", mode);
1537 if self.pending_rename.is_some() {
1538 key_context.add("renaming");
1539 }
1540
1541 match self.context_menu.borrow().as_ref() {
1542 Some(CodeContextMenu::Completions(_)) => {
1543 key_context.add("menu");
1544 key_context.add("showing_completions");
1545 }
1546 Some(CodeContextMenu::CodeActions(_)) => {
1547 key_context.add("menu");
1548 key_context.add("showing_code_actions")
1549 }
1550 None => {}
1551 }
1552
1553 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1554 if !self.focus_handle(cx).contains_focused(window, cx)
1555 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1556 {
1557 for addon in self.addons.values() {
1558 addon.extend_key_context(&mut key_context, cx)
1559 }
1560 }
1561
1562 if let Some(extension) = self
1563 .buffer
1564 .read(cx)
1565 .as_singleton()
1566 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1567 {
1568 key_context.set("extension", extension.to_string());
1569 }
1570
1571 if has_active_edit_prediction {
1572 if self.edit_prediction_in_conflict() {
1573 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1574 } else {
1575 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1576 key_context.add("copilot_suggestion");
1577 }
1578 }
1579
1580 if self.selection_mark_mode {
1581 key_context.add("selection_mode");
1582 }
1583
1584 key_context
1585 }
1586
1587 pub fn edit_prediction_in_conflict(&self) -> bool {
1588 if !self.show_edit_predictions_in_menu() {
1589 return false;
1590 }
1591
1592 let showing_completions = self
1593 .context_menu
1594 .borrow()
1595 .as_ref()
1596 .map_or(false, |context| {
1597 matches!(context, CodeContextMenu::Completions(_))
1598 });
1599
1600 showing_completions
1601 || self.edit_prediction_requires_modifier()
1602 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1603 // bindings to insert tab characters.
1604 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1605 }
1606
1607 pub fn accept_edit_prediction_keybind(
1608 &self,
1609 window: &Window,
1610 cx: &App,
1611 ) -> AcceptEditPredictionBinding {
1612 let key_context = self.key_context_internal(true, window, cx);
1613 let in_conflict = self.edit_prediction_in_conflict();
1614
1615 AcceptEditPredictionBinding(
1616 window
1617 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1618 .into_iter()
1619 .filter(|binding| {
1620 !in_conflict
1621 || binding
1622 .keystrokes()
1623 .first()
1624 .map_or(false, |keystroke| keystroke.modifiers.modified())
1625 })
1626 .rev()
1627 .min_by_key(|binding| {
1628 binding
1629 .keystrokes()
1630 .first()
1631 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1632 }),
1633 )
1634 }
1635
1636 pub fn new_file(
1637 workspace: &mut Workspace,
1638 _: &workspace::NewFile,
1639 window: &mut Window,
1640 cx: &mut Context<Workspace>,
1641 ) {
1642 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1643 "Failed to create buffer",
1644 window,
1645 cx,
1646 |e, _, _| match e.error_code() {
1647 ErrorCode::RemoteUpgradeRequired => Some(format!(
1648 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1649 e.error_tag("required").unwrap_or("the latest version")
1650 )),
1651 _ => None,
1652 },
1653 );
1654 }
1655
1656 pub fn new_in_workspace(
1657 workspace: &mut Workspace,
1658 window: &mut Window,
1659 cx: &mut Context<Workspace>,
1660 ) -> Task<Result<Entity<Editor>>> {
1661 let project = workspace.project().clone();
1662 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1663
1664 cx.spawn_in(window, |workspace, mut cx| async move {
1665 let buffer = create.await?;
1666 workspace.update_in(&mut cx, |workspace, window, cx| {
1667 let editor =
1668 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1669 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1670 editor
1671 })
1672 })
1673 }
1674
1675 fn new_file_vertical(
1676 workspace: &mut Workspace,
1677 _: &workspace::NewFileSplitVertical,
1678 window: &mut Window,
1679 cx: &mut Context<Workspace>,
1680 ) {
1681 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1682 }
1683
1684 fn new_file_horizontal(
1685 workspace: &mut Workspace,
1686 _: &workspace::NewFileSplitHorizontal,
1687 window: &mut Window,
1688 cx: &mut Context<Workspace>,
1689 ) {
1690 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1691 }
1692
1693 fn new_file_in_direction(
1694 workspace: &mut Workspace,
1695 direction: SplitDirection,
1696 window: &mut Window,
1697 cx: &mut Context<Workspace>,
1698 ) {
1699 let project = workspace.project().clone();
1700 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1701
1702 cx.spawn_in(window, |workspace, mut cx| async move {
1703 let buffer = create.await?;
1704 workspace.update_in(&mut cx, move |workspace, window, cx| {
1705 workspace.split_item(
1706 direction,
1707 Box::new(
1708 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1709 ),
1710 window,
1711 cx,
1712 )
1713 })?;
1714 anyhow::Ok(())
1715 })
1716 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1717 match e.error_code() {
1718 ErrorCode::RemoteUpgradeRequired => Some(format!(
1719 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1720 e.error_tag("required").unwrap_or("the latest version")
1721 )),
1722 _ => None,
1723 }
1724 });
1725 }
1726
1727 pub fn leader_peer_id(&self) -> Option<PeerId> {
1728 self.leader_peer_id
1729 }
1730
1731 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1732 &self.buffer
1733 }
1734
1735 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1736 self.workspace.as_ref()?.0.upgrade()
1737 }
1738
1739 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1740 self.buffer().read(cx).title(cx)
1741 }
1742
1743 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1744 let git_blame_gutter_max_author_length = self
1745 .render_git_blame_gutter(cx)
1746 .then(|| {
1747 if let Some(blame) = self.blame.as_ref() {
1748 let max_author_length =
1749 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1750 Some(max_author_length)
1751 } else {
1752 None
1753 }
1754 })
1755 .flatten();
1756
1757 EditorSnapshot {
1758 mode: self.mode,
1759 show_gutter: self.show_gutter,
1760 show_line_numbers: self.show_line_numbers,
1761 show_git_diff_gutter: self.show_git_diff_gutter,
1762 show_code_actions: self.show_code_actions,
1763 show_runnables: self.show_runnables,
1764 git_blame_gutter_max_author_length,
1765 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1766 scroll_anchor: self.scroll_manager.anchor(),
1767 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1768 placeholder_text: self.placeholder_text.clone(),
1769 is_focused: self.focus_handle.is_focused(window),
1770 current_line_highlight: self
1771 .current_line_highlight
1772 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1773 gutter_hovered: self.gutter_hovered,
1774 }
1775 }
1776
1777 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1778 self.buffer.read(cx).language_at(point, cx)
1779 }
1780
1781 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1782 self.buffer.read(cx).read(cx).file_at(point).cloned()
1783 }
1784
1785 pub fn active_excerpt(
1786 &self,
1787 cx: &App,
1788 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1789 self.buffer
1790 .read(cx)
1791 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1792 }
1793
1794 pub fn mode(&self) -> EditorMode {
1795 self.mode
1796 }
1797
1798 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1799 self.collaboration_hub.as_deref()
1800 }
1801
1802 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1803 self.collaboration_hub = Some(hub);
1804 }
1805
1806 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1807 self.in_project_search = in_project_search;
1808 }
1809
1810 pub fn set_custom_context_menu(
1811 &mut self,
1812 f: impl 'static
1813 + Fn(
1814 &mut Self,
1815 DisplayPoint,
1816 &mut Window,
1817 &mut Context<Self>,
1818 ) -> Option<Entity<ui::ContextMenu>>,
1819 ) {
1820 self.custom_context_menu = Some(Box::new(f))
1821 }
1822
1823 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1824 self.completion_provider = provider;
1825 }
1826
1827 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1828 self.semantics_provider.clone()
1829 }
1830
1831 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1832 self.semantics_provider = provider;
1833 }
1834
1835 pub fn set_edit_prediction_provider<T>(
1836 &mut self,
1837 provider: Option<Entity<T>>,
1838 window: &mut Window,
1839 cx: &mut Context<Self>,
1840 ) where
1841 T: EditPredictionProvider,
1842 {
1843 self.edit_prediction_provider =
1844 provider.map(|provider| RegisteredInlineCompletionProvider {
1845 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1846 if this.focus_handle.is_focused(window) {
1847 this.update_visible_inline_completion(window, cx);
1848 }
1849 }),
1850 provider: Arc::new(provider),
1851 });
1852 self.refresh_inline_completion(false, false, window, cx);
1853 }
1854
1855 pub fn placeholder_text(&self) -> Option<&str> {
1856 self.placeholder_text.as_deref()
1857 }
1858
1859 pub fn set_placeholder_text(
1860 &mut self,
1861 placeholder_text: impl Into<Arc<str>>,
1862 cx: &mut Context<Self>,
1863 ) {
1864 let placeholder_text = Some(placeholder_text.into());
1865 if self.placeholder_text != placeholder_text {
1866 self.placeholder_text = placeholder_text;
1867 cx.notify();
1868 }
1869 }
1870
1871 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1872 self.cursor_shape = cursor_shape;
1873
1874 // Disrupt blink for immediate user feedback that the cursor shape has changed
1875 self.blink_manager.update(cx, BlinkManager::show_cursor);
1876
1877 cx.notify();
1878 }
1879
1880 pub fn set_current_line_highlight(
1881 &mut self,
1882 current_line_highlight: Option<CurrentLineHighlight>,
1883 ) {
1884 self.current_line_highlight = current_line_highlight;
1885 }
1886
1887 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1888 self.collapse_matches = collapse_matches;
1889 }
1890
1891 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1892 let buffers = self.buffer.read(cx).all_buffers();
1893 let Some(project) = self.project.as_ref() else {
1894 return;
1895 };
1896 project.update(cx, |project, cx| {
1897 for buffer in buffers {
1898 self.registered_buffers
1899 .entry(buffer.read(cx).remote_id())
1900 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1901 }
1902 })
1903 }
1904
1905 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1906 if self.collapse_matches {
1907 return range.start..range.start;
1908 }
1909 range.clone()
1910 }
1911
1912 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1913 if self.display_map.read(cx).clip_at_line_ends != clip {
1914 self.display_map
1915 .update(cx, |map, _| map.clip_at_line_ends = clip);
1916 }
1917 }
1918
1919 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1920 self.input_enabled = input_enabled;
1921 }
1922
1923 pub fn set_inline_completions_hidden_for_vim_mode(
1924 &mut self,
1925 hidden: bool,
1926 window: &mut Window,
1927 cx: &mut Context<Self>,
1928 ) {
1929 if hidden != self.inline_completions_hidden_for_vim_mode {
1930 self.inline_completions_hidden_for_vim_mode = hidden;
1931 if hidden {
1932 self.update_visible_inline_completion(window, cx);
1933 } else {
1934 self.refresh_inline_completion(true, false, window, cx);
1935 }
1936 }
1937 }
1938
1939 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1940 self.menu_inline_completions_policy = value;
1941 }
1942
1943 pub fn set_autoindent(&mut self, autoindent: bool) {
1944 if autoindent {
1945 self.autoindent_mode = Some(AutoindentMode::EachLine);
1946 } else {
1947 self.autoindent_mode = None;
1948 }
1949 }
1950
1951 pub fn read_only(&self, cx: &App) -> bool {
1952 self.read_only || self.buffer.read(cx).read_only()
1953 }
1954
1955 pub fn set_read_only(&mut self, read_only: bool) {
1956 self.read_only = read_only;
1957 }
1958
1959 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1960 self.use_autoclose = autoclose;
1961 }
1962
1963 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1964 self.use_auto_surround = auto_surround;
1965 }
1966
1967 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1968 self.auto_replace_emoji_shortcode = auto_replace;
1969 }
1970
1971 pub fn toggle_inline_completions(
1972 &mut self,
1973 _: &ToggleEditPrediction,
1974 window: &mut Window,
1975 cx: &mut Context<Self>,
1976 ) {
1977 if self.show_inline_completions_override.is_some() {
1978 self.set_show_edit_predictions(None, window, cx);
1979 } else {
1980 let show_edit_predictions = !self.edit_predictions_enabled();
1981 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1982 }
1983 }
1984
1985 pub fn set_show_edit_predictions(
1986 &mut self,
1987 show_edit_predictions: Option<bool>,
1988 window: &mut Window,
1989 cx: &mut Context<Self>,
1990 ) {
1991 self.show_inline_completions_override = show_edit_predictions;
1992 self.refresh_inline_completion(false, true, window, cx);
1993 }
1994
1995 fn inline_completions_disabled_in_scope(
1996 &self,
1997 buffer: &Entity<Buffer>,
1998 buffer_position: language::Anchor,
1999 cx: &App,
2000 ) -> bool {
2001 let snapshot = buffer.read(cx).snapshot();
2002 let settings = snapshot.settings_at(buffer_position, cx);
2003
2004 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2005 return false;
2006 };
2007
2008 scope.override_name().map_or(false, |scope_name| {
2009 settings
2010 .edit_predictions_disabled_in
2011 .iter()
2012 .any(|s| s == scope_name)
2013 })
2014 }
2015
2016 pub fn set_use_modal_editing(&mut self, to: bool) {
2017 self.use_modal_editing = to;
2018 }
2019
2020 pub fn use_modal_editing(&self) -> bool {
2021 self.use_modal_editing
2022 }
2023
2024 fn selections_did_change(
2025 &mut self,
2026 local: bool,
2027 old_cursor_position: &Anchor,
2028 show_completions: bool,
2029 window: &mut Window,
2030 cx: &mut Context<Self>,
2031 ) {
2032 window.invalidate_character_coordinates();
2033
2034 // Copy selections to primary selection buffer
2035 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2036 if local {
2037 let selections = self.selections.all::<usize>(cx);
2038 let buffer_handle = self.buffer.read(cx).read(cx);
2039
2040 let mut text = String::new();
2041 for (index, selection) in selections.iter().enumerate() {
2042 let text_for_selection = buffer_handle
2043 .text_for_range(selection.start..selection.end)
2044 .collect::<String>();
2045
2046 text.push_str(&text_for_selection);
2047 if index != selections.len() - 1 {
2048 text.push('\n');
2049 }
2050 }
2051
2052 if !text.is_empty() {
2053 cx.write_to_primary(ClipboardItem::new_string(text));
2054 }
2055 }
2056
2057 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2058 self.buffer.update(cx, |buffer, cx| {
2059 buffer.set_active_selections(
2060 &self.selections.disjoint_anchors(),
2061 self.selections.line_mode,
2062 self.cursor_shape,
2063 cx,
2064 )
2065 });
2066 }
2067 let display_map = self
2068 .display_map
2069 .update(cx, |display_map, cx| display_map.snapshot(cx));
2070 let buffer = &display_map.buffer_snapshot;
2071 self.add_selections_state = None;
2072 self.select_next_state = None;
2073 self.select_prev_state = None;
2074 self.select_larger_syntax_node_stack.clear();
2075 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2076 self.snippet_stack
2077 .invalidate(&self.selections.disjoint_anchors(), buffer);
2078 self.take_rename(false, window, cx);
2079
2080 let new_cursor_position = self.selections.newest_anchor().head();
2081
2082 self.push_to_nav_history(
2083 *old_cursor_position,
2084 Some(new_cursor_position.to_point(buffer)),
2085 cx,
2086 );
2087
2088 if local {
2089 let new_cursor_position = self.selections.newest_anchor().head();
2090 let mut context_menu = self.context_menu.borrow_mut();
2091 let completion_menu = match context_menu.as_ref() {
2092 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2093 _ => {
2094 *context_menu = None;
2095 None
2096 }
2097 };
2098 if let Some(buffer_id) = new_cursor_position.buffer_id {
2099 if !self.registered_buffers.contains_key(&buffer_id) {
2100 if let Some(project) = self.project.as_ref() {
2101 project.update(cx, |project, cx| {
2102 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2103 return;
2104 };
2105 self.registered_buffers.insert(
2106 buffer_id,
2107 project.register_buffer_with_language_servers(&buffer, cx),
2108 );
2109 })
2110 }
2111 }
2112 }
2113
2114 if let Some(completion_menu) = completion_menu {
2115 let cursor_position = new_cursor_position.to_offset(buffer);
2116 let (word_range, kind) =
2117 buffer.surrounding_word(completion_menu.initial_position, true);
2118 if kind == Some(CharKind::Word)
2119 && word_range.to_inclusive().contains(&cursor_position)
2120 {
2121 let mut completion_menu = completion_menu.clone();
2122 drop(context_menu);
2123
2124 let query = Self::completion_query(buffer, cursor_position);
2125 cx.spawn(move |this, mut cx| async move {
2126 completion_menu
2127 .filter(query.as_deref(), cx.background_executor().clone())
2128 .await;
2129
2130 this.update(&mut cx, |this, cx| {
2131 let mut context_menu = this.context_menu.borrow_mut();
2132 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2133 else {
2134 return;
2135 };
2136
2137 if menu.id > completion_menu.id {
2138 return;
2139 }
2140
2141 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2142 drop(context_menu);
2143 cx.notify();
2144 })
2145 })
2146 .detach();
2147
2148 if show_completions {
2149 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2150 }
2151 } else {
2152 drop(context_menu);
2153 self.hide_context_menu(window, cx);
2154 }
2155 } else {
2156 drop(context_menu);
2157 }
2158
2159 hide_hover(self, cx);
2160
2161 if old_cursor_position.to_display_point(&display_map).row()
2162 != new_cursor_position.to_display_point(&display_map).row()
2163 {
2164 self.available_code_actions.take();
2165 }
2166 self.refresh_code_actions(window, cx);
2167 self.refresh_document_highlights(cx);
2168 refresh_matching_bracket_highlights(self, window, cx);
2169 self.update_visible_inline_completion(window, cx);
2170 self.edit_prediction_requires_modifier_in_leading_space = true;
2171 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2172 if self.git_blame_inline_enabled {
2173 self.start_inline_blame_timer(window, cx);
2174 }
2175 }
2176
2177 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2178 cx.emit(EditorEvent::SelectionsChanged { local });
2179
2180 if self.selections.disjoint_anchors().len() == 1 {
2181 cx.emit(SearchEvent::ActiveMatchChanged)
2182 }
2183 cx.notify();
2184 }
2185
2186 pub fn change_selections<R>(
2187 &mut self,
2188 autoscroll: Option<Autoscroll>,
2189 window: &mut Window,
2190 cx: &mut Context<Self>,
2191 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2192 ) -> R {
2193 self.change_selections_inner(autoscroll, true, window, cx, change)
2194 }
2195
2196 pub fn change_selections_inner<R>(
2197 &mut self,
2198 autoscroll: Option<Autoscroll>,
2199 request_completions: bool,
2200 window: &mut Window,
2201 cx: &mut Context<Self>,
2202 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2203 ) -> R {
2204 let old_cursor_position = self.selections.newest_anchor().head();
2205 self.push_to_selection_history();
2206
2207 let (changed, result) = self.selections.change_with(cx, change);
2208
2209 if changed {
2210 if let Some(autoscroll) = autoscroll {
2211 self.request_autoscroll(autoscroll, cx);
2212 }
2213 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2214
2215 if self.should_open_signature_help_automatically(
2216 &old_cursor_position,
2217 self.signature_help_state.backspace_pressed(),
2218 cx,
2219 ) {
2220 self.show_signature_help(&ShowSignatureHelp, window, cx);
2221 }
2222 self.signature_help_state.set_backspace_pressed(false);
2223 }
2224
2225 result
2226 }
2227
2228 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2229 where
2230 I: IntoIterator<Item = (Range<S>, T)>,
2231 S: ToOffset,
2232 T: Into<Arc<str>>,
2233 {
2234 if self.read_only(cx) {
2235 return;
2236 }
2237
2238 self.buffer
2239 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2240 }
2241
2242 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2243 where
2244 I: IntoIterator<Item = (Range<S>, T)>,
2245 S: ToOffset,
2246 T: Into<Arc<str>>,
2247 {
2248 if self.read_only(cx) {
2249 return;
2250 }
2251
2252 self.buffer.update(cx, |buffer, cx| {
2253 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2254 });
2255 }
2256
2257 pub fn edit_with_block_indent<I, S, T>(
2258 &mut self,
2259 edits: I,
2260 original_indent_columns: Vec<u32>,
2261 cx: &mut Context<Self>,
2262 ) where
2263 I: IntoIterator<Item = (Range<S>, T)>,
2264 S: ToOffset,
2265 T: Into<Arc<str>>,
2266 {
2267 if self.read_only(cx) {
2268 return;
2269 }
2270
2271 self.buffer.update(cx, |buffer, cx| {
2272 buffer.edit(
2273 edits,
2274 Some(AutoindentMode::Block {
2275 original_indent_columns,
2276 }),
2277 cx,
2278 )
2279 });
2280 }
2281
2282 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2283 self.hide_context_menu(window, cx);
2284
2285 match phase {
2286 SelectPhase::Begin {
2287 position,
2288 add,
2289 click_count,
2290 } => self.begin_selection(position, add, click_count, window, cx),
2291 SelectPhase::BeginColumnar {
2292 position,
2293 goal_column,
2294 reset,
2295 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2296 SelectPhase::Extend {
2297 position,
2298 click_count,
2299 } => self.extend_selection(position, click_count, window, cx),
2300 SelectPhase::Update {
2301 position,
2302 goal_column,
2303 scroll_delta,
2304 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2305 SelectPhase::End => self.end_selection(window, cx),
2306 }
2307 }
2308
2309 fn extend_selection(
2310 &mut self,
2311 position: DisplayPoint,
2312 click_count: usize,
2313 window: &mut Window,
2314 cx: &mut Context<Self>,
2315 ) {
2316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2317 let tail = self.selections.newest::<usize>(cx).tail();
2318 self.begin_selection(position, false, click_count, window, cx);
2319
2320 let position = position.to_offset(&display_map, Bias::Left);
2321 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2322
2323 let mut pending_selection = self
2324 .selections
2325 .pending_anchor()
2326 .expect("extend_selection not called with pending selection");
2327 if position >= tail {
2328 pending_selection.start = tail_anchor;
2329 } else {
2330 pending_selection.end = tail_anchor;
2331 pending_selection.reversed = true;
2332 }
2333
2334 let mut pending_mode = self.selections.pending_mode().unwrap();
2335 match &mut pending_mode {
2336 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2337 _ => {}
2338 }
2339
2340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2341 s.set_pending(pending_selection, pending_mode)
2342 });
2343 }
2344
2345 fn begin_selection(
2346 &mut self,
2347 position: DisplayPoint,
2348 add: bool,
2349 click_count: usize,
2350 window: &mut Window,
2351 cx: &mut Context<Self>,
2352 ) {
2353 if !self.focus_handle.is_focused(window) {
2354 self.last_focused_descendant = None;
2355 window.focus(&self.focus_handle);
2356 }
2357
2358 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2359 let buffer = &display_map.buffer_snapshot;
2360 let newest_selection = self.selections.newest_anchor().clone();
2361 let position = display_map.clip_point(position, Bias::Left);
2362
2363 let start;
2364 let end;
2365 let mode;
2366 let mut auto_scroll;
2367 match click_count {
2368 1 => {
2369 start = buffer.anchor_before(position.to_point(&display_map));
2370 end = start;
2371 mode = SelectMode::Character;
2372 auto_scroll = true;
2373 }
2374 2 => {
2375 let range = movement::surrounding_word(&display_map, position);
2376 start = buffer.anchor_before(range.start.to_point(&display_map));
2377 end = buffer.anchor_before(range.end.to_point(&display_map));
2378 mode = SelectMode::Word(start..end);
2379 auto_scroll = true;
2380 }
2381 3 => {
2382 let position = display_map
2383 .clip_point(position, Bias::Left)
2384 .to_point(&display_map);
2385 let line_start = display_map.prev_line_boundary(position).0;
2386 let next_line_start = buffer.clip_point(
2387 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2388 Bias::Left,
2389 );
2390 start = buffer.anchor_before(line_start);
2391 end = buffer.anchor_before(next_line_start);
2392 mode = SelectMode::Line(start..end);
2393 auto_scroll = true;
2394 }
2395 _ => {
2396 start = buffer.anchor_before(0);
2397 end = buffer.anchor_before(buffer.len());
2398 mode = SelectMode::All;
2399 auto_scroll = false;
2400 }
2401 }
2402 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2403
2404 let point_to_delete: Option<usize> = {
2405 let selected_points: Vec<Selection<Point>> =
2406 self.selections.disjoint_in_range(start..end, cx);
2407
2408 if !add || click_count > 1 {
2409 None
2410 } else if !selected_points.is_empty() {
2411 Some(selected_points[0].id)
2412 } else {
2413 let clicked_point_already_selected =
2414 self.selections.disjoint.iter().find(|selection| {
2415 selection.start.to_point(buffer) == start.to_point(buffer)
2416 || selection.end.to_point(buffer) == end.to_point(buffer)
2417 });
2418
2419 clicked_point_already_selected.map(|selection| selection.id)
2420 }
2421 };
2422
2423 let selections_count = self.selections.count();
2424
2425 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2426 if let Some(point_to_delete) = point_to_delete {
2427 s.delete(point_to_delete);
2428
2429 if selections_count == 1 {
2430 s.set_pending_anchor_range(start..end, mode);
2431 }
2432 } else {
2433 if !add {
2434 s.clear_disjoint();
2435 } else if click_count > 1 {
2436 s.delete(newest_selection.id)
2437 }
2438
2439 s.set_pending_anchor_range(start..end, mode);
2440 }
2441 });
2442 }
2443
2444 fn begin_columnar_selection(
2445 &mut self,
2446 position: DisplayPoint,
2447 goal_column: u32,
2448 reset: bool,
2449 window: &mut Window,
2450 cx: &mut Context<Self>,
2451 ) {
2452 if !self.focus_handle.is_focused(window) {
2453 self.last_focused_descendant = None;
2454 window.focus(&self.focus_handle);
2455 }
2456
2457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2458
2459 if reset {
2460 let pointer_position = display_map
2461 .buffer_snapshot
2462 .anchor_before(position.to_point(&display_map));
2463
2464 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2465 s.clear_disjoint();
2466 s.set_pending_anchor_range(
2467 pointer_position..pointer_position,
2468 SelectMode::Character,
2469 );
2470 });
2471 }
2472
2473 let tail = self.selections.newest::<Point>(cx).tail();
2474 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2475
2476 if !reset {
2477 self.select_columns(
2478 tail.to_display_point(&display_map),
2479 position,
2480 goal_column,
2481 &display_map,
2482 window,
2483 cx,
2484 );
2485 }
2486 }
2487
2488 fn update_selection(
2489 &mut self,
2490 position: DisplayPoint,
2491 goal_column: u32,
2492 scroll_delta: gpui::Point<f32>,
2493 window: &mut Window,
2494 cx: &mut Context<Self>,
2495 ) {
2496 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2497
2498 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2499 let tail = tail.to_display_point(&display_map);
2500 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2501 } else if let Some(mut pending) = self.selections.pending_anchor() {
2502 let buffer = self.buffer.read(cx).snapshot(cx);
2503 let head;
2504 let tail;
2505 let mode = self.selections.pending_mode().unwrap();
2506 match &mode {
2507 SelectMode::Character => {
2508 head = position.to_point(&display_map);
2509 tail = pending.tail().to_point(&buffer);
2510 }
2511 SelectMode::Word(original_range) => {
2512 let original_display_range = original_range.start.to_display_point(&display_map)
2513 ..original_range.end.to_display_point(&display_map);
2514 let original_buffer_range = original_display_range.start.to_point(&display_map)
2515 ..original_display_range.end.to_point(&display_map);
2516 if movement::is_inside_word(&display_map, position)
2517 || original_display_range.contains(&position)
2518 {
2519 let word_range = movement::surrounding_word(&display_map, position);
2520 if word_range.start < original_display_range.start {
2521 head = word_range.start.to_point(&display_map);
2522 } else {
2523 head = word_range.end.to_point(&display_map);
2524 }
2525 } else {
2526 head = position.to_point(&display_map);
2527 }
2528
2529 if head <= original_buffer_range.start {
2530 tail = original_buffer_range.end;
2531 } else {
2532 tail = original_buffer_range.start;
2533 }
2534 }
2535 SelectMode::Line(original_range) => {
2536 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2537
2538 let position = display_map
2539 .clip_point(position, Bias::Left)
2540 .to_point(&display_map);
2541 let line_start = display_map.prev_line_boundary(position).0;
2542 let next_line_start = buffer.clip_point(
2543 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2544 Bias::Left,
2545 );
2546
2547 if line_start < original_range.start {
2548 head = line_start
2549 } else {
2550 head = next_line_start
2551 }
2552
2553 if head <= original_range.start {
2554 tail = original_range.end;
2555 } else {
2556 tail = original_range.start;
2557 }
2558 }
2559 SelectMode::All => {
2560 return;
2561 }
2562 };
2563
2564 if head < tail {
2565 pending.start = buffer.anchor_before(head);
2566 pending.end = buffer.anchor_before(tail);
2567 pending.reversed = true;
2568 } else {
2569 pending.start = buffer.anchor_before(tail);
2570 pending.end = buffer.anchor_before(head);
2571 pending.reversed = false;
2572 }
2573
2574 self.change_selections(None, window, cx, |s| {
2575 s.set_pending(pending, mode);
2576 });
2577 } else {
2578 log::error!("update_selection dispatched with no pending selection");
2579 return;
2580 }
2581
2582 self.apply_scroll_delta(scroll_delta, window, cx);
2583 cx.notify();
2584 }
2585
2586 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2587 self.columnar_selection_tail.take();
2588 if self.selections.pending_anchor().is_some() {
2589 let selections = self.selections.all::<usize>(cx);
2590 self.change_selections(None, window, cx, |s| {
2591 s.select(selections);
2592 s.clear_pending();
2593 });
2594 }
2595 }
2596
2597 fn select_columns(
2598 &mut self,
2599 tail: DisplayPoint,
2600 head: DisplayPoint,
2601 goal_column: u32,
2602 display_map: &DisplaySnapshot,
2603 window: &mut Window,
2604 cx: &mut Context<Self>,
2605 ) {
2606 let start_row = cmp::min(tail.row(), head.row());
2607 let end_row = cmp::max(tail.row(), head.row());
2608 let start_column = cmp::min(tail.column(), goal_column);
2609 let end_column = cmp::max(tail.column(), goal_column);
2610 let reversed = start_column < tail.column();
2611
2612 let selection_ranges = (start_row.0..=end_row.0)
2613 .map(DisplayRow)
2614 .filter_map(|row| {
2615 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2616 let start = display_map
2617 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2618 .to_point(display_map);
2619 let end = display_map
2620 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2621 .to_point(display_map);
2622 if reversed {
2623 Some(end..start)
2624 } else {
2625 Some(start..end)
2626 }
2627 } else {
2628 None
2629 }
2630 })
2631 .collect::<Vec<_>>();
2632
2633 self.change_selections(None, window, cx, |s| {
2634 s.select_ranges(selection_ranges);
2635 });
2636 cx.notify();
2637 }
2638
2639 pub fn has_pending_nonempty_selection(&self) -> bool {
2640 let pending_nonempty_selection = match self.selections.pending_anchor() {
2641 Some(Selection { start, end, .. }) => start != end,
2642 None => false,
2643 };
2644
2645 pending_nonempty_selection
2646 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2647 }
2648
2649 pub fn has_pending_selection(&self) -> bool {
2650 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2651 }
2652
2653 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2654 self.selection_mark_mode = false;
2655
2656 if self.clear_expanded_diff_hunks(cx) {
2657 cx.notify();
2658 return;
2659 }
2660 if self.dismiss_menus_and_popups(true, window, cx) {
2661 return;
2662 }
2663
2664 if self.mode == EditorMode::Full
2665 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2666 {
2667 return;
2668 }
2669
2670 cx.propagate();
2671 }
2672
2673 pub fn dismiss_menus_and_popups(
2674 &mut self,
2675 is_user_requested: bool,
2676 window: &mut Window,
2677 cx: &mut Context<Self>,
2678 ) -> bool {
2679 if self.take_rename(false, window, cx).is_some() {
2680 return true;
2681 }
2682
2683 if hide_hover(self, cx) {
2684 return true;
2685 }
2686
2687 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2688 return true;
2689 }
2690
2691 if self.hide_context_menu(window, cx).is_some() {
2692 return true;
2693 }
2694
2695 if self.mouse_context_menu.take().is_some() {
2696 return true;
2697 }
2698
2699 if is_user_requested && self.discard_inline_completion(true, cx) {
2700 return true;
2701 }
2702
2703 if self.snippet_stack.pop().is_some() {
2704 return true;
2705 }
2706
2707 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2708 self.dismiss_diagnostics(cx);
2709 return true;
2710 }
2711
2712 false
2713 }
2714
2715 fn linked_editing_ranges_for(
2716 &self,
2717 selection: Range<text::Anchor>,
2718 cx: &App,
2719 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2720 if self.linked_edit_ranges.is_empty() {
2721 return None;
2722 }
2723 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2724 selection.end.buffer_id.and_then(|end_buffer_id| {
2725 if selection.start.buffer_id != Some(end_buffer_id) {
2726 return None;
2727 }
2728 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2729 let snapshot = buffer.read(cx).snapshot();
2730 self.linked_edit_ranges
2731 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2732 .map(|ranges| (ranges, snapshot, buffer))
2733 })?;
2734 use text::ToOffset as TO;
2735 // find offset from the start of current range to current cursor position
2736 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2737
2738 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2739 let start_difference = start_offset - start_byte_offset;
2740 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2741 let end_difference = end_offset - start_byte_offset;
2742 // Current range has associated linked ranges.
2743 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2744 for range in linked_ranges.iter() {
2745 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2746 let end_offset = start_offset + end_difference;
2747 let start_offset = start_offset + start_difference;
2748 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2749 continue;
2750 }
2751 if self.selections.disjoint_anchor_ranges().any(|s| {
2752 if s.start.buffer_id != selection.start.buffer_id
2753 || s.end.buffer_id != selection.end.buffer_id
2754 {
2755 return false;
2756 }
2757 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2758 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2759 }) {
2760 continue;
2761 }
2762 let start = buffer_snapshot.anchor_after(start_offset);
2763 let end = buffer_snapshot.anchor_after(end_offset);
2764 linked_edits
2765 .entry(buffer.clone())
2766 .or_default()
2767 .push(start..end);
2768 }
2769 Some(linked_edits)
2770 }
2771
2772 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2773 let text: Arc<str> = text.into();
2774
2775 if self.read_only(cx) {
2776 return;
2777 }
2778
2779 let selections = self.selections.all_adjusted(cx);
2780 let mut bracket_inserted = false;
2781 let mut edits = Vec::new();
2782 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2783 let mut new_selections = Vec::with_capacity(selections.len());
2784 let mut new_autoclose_regions = Vec::new();
2785 let snapshot = self.buffer.read(cx).read(cx);
2786
2787 for (selection, autoclose_region) in
2788 self.selections_with_autoclose_regions(selections, &snapshot)
2789 {
2790 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2791 // Determine if the inserted text matches the opening or closing
2792 // bracket of any of this language's bracket pairs.
2793 let mut bracket_pair = None;
2794 let mut is_bracket_pair_start = false;
2795 let mut is_bracket_pair_end = false;
2796 if !text.is_empty() {
2797 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2798 // and they are removing the character that triggered IME popup.
2799 for (pair, enabled) in scope.brackets() {
2800 if !pair.close && !pair.surround {
2801 continue;
2802 }
2803
2804 if enabled && pair.start.ends_with(text.as_ref()) {
2805 let prefix_len = pair.start.len() - text.len();
2806 let preceding_text_matches_prefix = prefix_len == 0
2807 || (selection.start.column >= (prefix_len as u32)
2808 && snapshot.contains_str_at(
2809 Point::new(
2810 selection.start.row,
2811 selection.start.column - (prefix_len as u32),
2812 ),
2813 &pair.start[..prefix_len],
2814 ));
2815 if preceding_text_matches_prefix {
2816 bracket_pair = Some(pair.clone());
2817 is_bracket_pair_start = true;
2818 break;
2819 }
2820 }
2821 if pair.end.as_str() == text.as_ref() {
2822 bracket_pair = Some(pair.clone());
2823 is_bracket_pair_end = true;
2824 break;
2825 }
2826 }
2827 }
2828
2829 if let Some(bracket_pair) = bracket_pair {
2830 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2831 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2832 let auto_surround =
2833 self.use_auto_surround && snapshot_settings.use_auto_surround;
2834 if selection.is_empty() {
2835 if is_bracket_pair_start {
2836 // If the inserted text is a suffix of an opening bracket and the
2837 // selection is preceded by the rest of the opening bracket, then
2838 // insert the closing bracket.
2839 let following_text_allows_autoclose = snapshot
2840 .chars_at(selection.start)
2841 .next()
2842 .map_or(true, |c| scope.should_autoclose_before(c));
2843
2844 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2845 && bracket_pair.start.len() == 1
2846 {
2847 let target = bracket_pair.start.chars().next().unwrap();
2848 let current_line_count = snapshot
2849 .reversed_chars_at(selection.start)
2850 .take_while(|&c| c != '\n')
2851 .filter(|&c| c == target)
2852 .count();
2853 current_line_count % 2 == 1
2854 } else {
2855 false
2856 };
2857
2858 if autoclose
2859 && bracket_pair.close
2860 && following_text_allows_autoclose
2861 && !is_closing_quote
2862 {
2863 let anchor = snapshot.anchor_before(selection.end);
2864 new_selections.push((selection.map(|_| anchor), text.len()));
2865 new_autoclose_regions.push((
2866 anchor,
2867 text.len(),
2868 selection.id,
2869 bracket_pair.clone(),
2870 ));
2871 edits.push((
2872 selection.range(),
2873 format!("{}{}", text, bracket_pair.end).into(),
2874 ));
2875 bracket_inserted = true;
2876 continue;
2877 }
2878 }
2879
2880 if let Some(region) = autoclose_region {
2881 // If the selection is followed by an auto-inserted closing bracket,
2882 // then don't insert that closing bracket again; just move the selection
2883 // past the closing bracket.
2884 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2885 && text.as_ref() == region.pair.end.as_str();
2886 if should_skip {
2887 let anchor = snapshot.anchor_after(selection.end);
2888 new_selections
2889 .push((selection.map(|_| anchor), region.pair.end.len()));
2890 continue;
2891 }
2892 }
2893
2894 let always_treat_brackets_as_autoclosed = snapshot
2895 .settings_at(selection.start, cx)
2896 .always_treat_brackets_as_autoclosed;
2897 if always_treat_brackets_as_autoclosed
2898 && is_bracket_pair_end
2899 && snapshot.contains_str_at(selection.end, text.as_ref())
2900 {
2901 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2902 // and the inserted text is a closing bracket and the selection is followed
2903 // by the closing bracket then move the selection past the closing bracket.
2904 let anchor = snapshot.anchor_after(selection.end);
2905 new_selections.push((selection.map(|_| anchor), text.len()));
2906 continue;
2907 }
2908 }
2909 // If an opening bracket is 1 character long and is typed while
2910 // text is selected, then surround that text with the bracket pair.
2911 else if auto_surround
2912 && bracket_pair.surround
2913 && is_bracket_pair_start
2914 && bracket_pair.start.chars().count() == 1
2915 {
2916 edits.push((selection.start..selection.start, text.clone()));
2917 edits.push((
2918 selection.end..selection.end,
2919 bracket_pair.end.as_str().into(),
2920 ));
2921 bracket_inserted = true;
2922 new_selections.push((
2923 Selection {
2924 id: selection.id,
2925 start: snapshot.anchor_after(selection.start),
2926 end: snapshot.anchor_before(selection.end),
2927 reversed: selection.reversed,
2928 goal: selection.goal,
2929 },
2930 0,
2931 ));
2932 continue;
2933 }
2934 }
2935 }
2936
2937 if self.auto_replace_emoji_shortcode
2938 && selection.is_empty()
2939 && text.as_ref().ends_with(':')
2940 {
2941 if let Some(possible_emoji_short_code) =
2942 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2943 {
2944 if !possible_emoji_short_code.is_empty() {
2945 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2946 let emoji_shortcode_start = Point::new(
2947 selection.start.row,
2948 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2949 );
2950
2951 // Remove shortcode from buffer
2952 edits.push((
2953 emoji_shortcode_start..selection.start,
2954 "".to_string().into(),
2955 ));
2956 new_selections.push((
2957 Selection {
2958 id: selection.id,
2959 start: snapshot.anchor_after(emoji_shortcode_start),
2960 end: snapshot.anchor_before(selection.start),
2961 reversed: selection.reversed,
2962 goal: selection.goal,
2963 },
2964 0,
2965 ));
2966
2967 // Insert emoji
2968 let selection_start_anchor = snapshot.anchor_after(selection.start);
2969 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2970 edits.push((selection.start..selection.end, emoji.to_string().into()));
2971
2972 continue;
2973 }
2974 }
2975 }
2976 }
2977
2978 // If not handling any auto-close operation, then just replace the selected
2979 // text with the given input and move the selection to the end of the
2980 // newly inserted text.
2981 let anchor = snapshot.anchor_after(selection.end);
2982 if !self.linked_edit_ranges.is_empty() {
2983 let start_anchor = snapshot.anchor_before(selection.start);
2984
2985 let is_word_char = text.chars().next().map_or(true, |char| {
2986 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2987 classifier.is_word(char)
2988 });
2989
2990 if is_word_char {
2991 if let Some(ranges) = self
2992 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2993 {
2994 for (buffer, edits) in ranges {
2995 linked_edits
2996 .entry(buffer.clone())
2997 .or_default()
2998 .extend(edits.into_iter().map(|range| (range, text.clone())));
2999 }
3000 }
3001 }
3002 }
3003
3004 new_selections.push((selection.map(|_| anchor), 0));
3005 edits.push((selection.start..selection.end, text.clone()));
3006 }
3007
3008 drop(snapshot);
3009
3010 self.transact(window, cx, |this, window, cx| {
3011 this.buffer.update(cx, |buffer, cx| {
3012 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3013 });
3014 for (buffer, edits) in linked_edits {
3015 buffer.update(cx, |buffer, cx| {
3016 let snapshot = buffer.snapshot();
3017 let edits = edits
3018 .into_iter()
3019 .map(|(range, text)| {
3020 use text::ToPoint as TP;
3021 let end_point = TP::to_point(&range.end, &snapshot);
3022 let start_point = TP::to_point(&range.start, &snapshot);
3023 (start_point..end_point, text)
3024 })
3025 .sorted_by_key(|(range, _)| range.start)
3026 .collect::<Vec<_>>();
3027 buffer.edit(edits, None, cx);
3028 })
3029 }
3030 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3031 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3032 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3033 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3034 .zip(new_selection_deltas)
3035 .map(|(selection, delta)| Selection {
3036 id: selection.id,
3037 start: selection.start + delta,
3038 end: selection.end + delta,
3039 reversed: selection.reversed,
3040 goal: SelectionGoal::None,
3041 })
3042 .collect::<Vec<_>>();
3043
3044 let mut i = 0;
3045 for (position, delta, selection_id, pair) in new_autoclose_regions {
3046 let position = position.to_offset(&map.buffer_snapshot) + delta;
3047 let start = map.buffer_snapshot.anchor_before(position);
3048 let end = map.buffer_snapshot.anchor_after(position);
3049 while let Some(existing_state) = this.autoclose_regions.get(i) {
3050 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3051 Ordering::Less => i += 1,
3052 Ordering::Greater => break,
3053 Ordering::Equal => {
3054 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3055 Ordering::Less => i += 1,
3056 Ordering::Equal => break,
3057 Ordering::Greater => break,
3058 }
3059 }
3060 }
3061 }
3062 this.autoclose_regions.insert(
3063 i,
3064 AutocloseRegion {
3065 selection_id,
3066 range: start..end,
3067 pair,
3068 },
3069 );
3070 }
3071
3072 let had_active_inline_completion = this.has_active_inline_completion();
3073 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3074 s.select(new_selections)
3075 });
3076
3077 if !bracket_inserted {
3078 if let Some(on_type_format_task) =
3079 this.trigger_on_type_formatting(text.to_string(), window, cx)
3080 {
3081 on_type_format_task.detach_and_log_err(cx);
3082 }
3083 }
3084
3085 let editor_settings = EditorSettings::get_global(cx);
3086 if bracket_inserted
3087 && (editor_settings.auto_signature_help
3088 || editor_settings.show_signature_help_after_edits)
3089 {
3090 this.show_signature_help(&ShowSignatureHelp, window, cx);
3091 }
3092
3093 let trigger_in_words =
3094 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3095 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3096 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3097 this.refresh_inline_completion(true, false, window, cx);
3098 });
3099 }
3100
3101 fn find_possible_emoji_shortcode_at_position(
3102 snapshot: &MultiBufferSnapshot,
3103 position: Point,
3104 ) -> Option<String> {
3105 let mut chars = Vec::new();
3106 let mut found_colon = false;
3107 for char in snapshot.reversed_chars_at(position).take(100) {
3108 // Found a possible emoji shortcode in the middle of the buffer
3109 if found_colon {
3110 if char.is_whitespace() {
3111 chars.reverse();
3112 return Some(chars.iter().collect());
3113 }
3114 // If the previous character is not a whitespace, we are in the middle of a word
3115 // and we only want to complete the shortcode if the word is made up of other emojis
3116 let mut containing_word = String::new();
3117 for ch in snapshot
3118 .reversed_chars_at(position)
3119 .skip(chars.len() + 1)
3120 .take(100)
3121 {
3122 if ch.is_whitespace() {
3123 break;
3124 }
3125 containing_word.push(ch);
3126 }
3127 let containing_word = containing_word.chars().rev().collect::<String>();
3128 if util::word_consists_of_emojis(containing_word.as_str()) {
3129 chars.reverse();
3130 return Some(chars.iter().collect());
3131 }
3132 }
3133
3134 if char.is_whitespace() || !char.is_ascii() {
3135 return None;
3136 }
3137 if char == ':' {
3138 found_colon = true;
3139 } else {
3140 chars.push(char);
3141 }
3142 }
3143 // Found a possible emoji shortcode at the beginning of the buffer
3144 chars.reverse();
3145 Some(chars.iter().collect())
3146 }
3147
3148 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3149 self.transact(window, cx, |this, window, cx| {
3150 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3151 let selections = this.selections.all::<usize>(cx);
3152 let multi_buffer = this.buffer.read(cx);
3153 let buffer = multi_buffer.snapshot(cx);
3154 selections
3155 .iter()
3156 .map(|selection| {
3157 let start_point = selection.start.to_point(&buffer);
3158 let mut indent =
3159 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3160 indent.len = cmp::min(indent.len, start_point.column);
3161 let start = selection.start;
3162 let end = selection.end;
3163 let selection_is_empty = start == end;
3164 let language_scope = buffer.language_scope_at(start);
3165 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3166 &language_scope
3167 {
3168 let leading_whitespace_len = buffer
3169 .reversed_chars_at(start)
3170 .take_while(|c| c.is_whitespace() && *c != '\n')
3171 .map(|c| c.len_utf8())
3172 .sum::<usize>();
3173
3174 let trailing_whitespace_len = buffer
3175 .chars_at(end)
3176 .take_while(|c| c.is_whitespace() && *c != '\n')
3177 .map(|c| c.len_utf8())
3178 .sum::<usize>();
3179
3180 let insert_extra_newline =
3181 language.brackets().any(|(pair, enabled)| {
3182 let pair_start = pair.start.trim_end();
3183 let pair_end = pair.end.trim_start();
3184
3185 enabled
3186 && pair.newline
3187 && buffer.contains_str_at(
3188 end + trailing_whitespace_len,
3189 pair_end,
3190 )
3191 && buffer.contains_str_at(
3192 (start - leading_whitespace_len)
3193 .saturating_sub(pair_start.len()),
3194 pair_start,
3195 )
3196 });
3197
3198 // Comment extension on newline is allowed only for cursor selections
3199 let comment_delimiter = maybe!({
3200 if !selection_is_empty {
3201 return None;
3202 }
3203
3204 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3205 return None;
3206 }
3207
3208 let delimiters = language.line_comment_prefixes();
3209 let max_len_of_delimiter =
3210 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3211 let (snapshot, range) =
3212 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3213
3214 let mut index_of_first_non_whitespace = 0;
3215 let comment_candidate = snapshot
3216 .chars_for_range(range)
3217 .skip_while(|c| {
3218 let should_skip = c.is_whitespace();
3219 if should_skip {
3220 index_of_first_non_whitespace += 1;
3221 }
3222 should_skip
3223 })
3224 .take(max_len_of_delimiter)
3225 .collect::<String>();
3226 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3227 comment_candidate.starts_with(comment_prefix.as_ref())
3228 })?;
3229 let cursor_is_placed_after_comment_marker =
3230 index_of_first_non_whitespace + comment_prefix.len()
3231 <= start_point.column as usize;
3232 if cursor_is_placed_after_comment_marker {
3233 Some(comment_prefix.clone())
3234 } else {
3235 None
3236 }
3237 });
3238 (comment_delimiter, insert_extra_newline)
3239 } else {
3240 (None, false)
3241 };
3242
3243 let capacity_for_delimiter = comment_delimiter
3244 .as_deref()
3245 .map(str::len)
3246 .unwrap_or_default();
3247 let mut new_text =
3248 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3249 new_text.push('\n');
3250 new_text.extend(indent.chars());
3251 if let Some(delimiter) = &comment_delimiter {
3252 new_text.push_str(delimiter);
3253 }
3254 if insert_extra_newline {
3255 new_text = new_text.repeat(2);
3256 }
3257
3258 let anchor = buffer.anchor_after(end);
3259 let new_selection = selection.map(|_| anchor);
3260 (
3261 (start..end, new_text),
3262 (insert_extra_newline, new_selection),
3263 )
3264 })
3265 .unzip()
3266 };
3267
3268 this.edit_with_autoindent(edits, cx);
3269 let buffer = this.buffer.read(cx).snapshot(cx);
3270 let new_selections = selection_fixup_info
3271 .into_iter()
3272 .map(|(extra_newline_inserted, new_selection)| {
3273 let mut cursor = new_selection.end.to_point(&buffer);
3274 if extra_newline_inserted {
3275 cursor.row -= 1;
3276 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3277 }
3278 new_selection.map(|_| cursor)
3279 })
3280 .collect();
3281
3282 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3283 s.select(new_selections)
3284 });
3285 this.refresh_inline_completion(true, false, window, cx);
3286 });
3287 }
3288
3289 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3290 let buffer = self.buffer.read(cx);
3291 let snapshot = buffer.snapshot(cx);
3292
3293 let mut edits = Vec::new();
3294 let mut rows = Vec::new();
3295
3296 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3297 let cursor = selection.head();
3298 let row = cursor.row;
3299
3300 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3301
3302 let newline = "\n".to_string();
3303 edits.push((start_of_line..start_of_line, newline));
3304
3305 rows.push(row + rows_inserted as u32);
3306 }
3307
3308 self.transact(window, cx, |editor, window, cx| {
3309 editor.edit(edits, cx);
3310
3311 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3312 let mut index = 0;
3313 s.move_cursors_with(|map, _, _| {
3314 let row = rows[index];
3315 index += 1;
3316
3317 let point = Point::new(row, 0);
3318 let boundary = map.next_line_boundary(point).1;
3319 let clipped = map.clip_point(boundary, Bias::Left);
3320
3321 (clipped, SelectionGoal::None)
3322 });
3323 });
3324
3325 let mut indent_edits = Vec::new();
3326 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3327 for row in rows {
3328 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3329 for (row, indent) in indents {
3330 if indent.len == 0 {
3331 continue;
3332 }
3333
3334 let text = match indent.kind {
3335 IndentKind::Space => " ".repeat(indent.len as usize),
3336 IndentKind::Tab => "\t".repeat(indent.len as usize),
3337 };
3338 let point = Point::new(row.0, 0);
3339 indent_edits.push((point..point, text));
3340 }
3341 }
3342 editor.edit(indent_edits, cx);
3343 });
3344 }
3345
3346 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3347 let buffer = self.buffer.read(cx);
3348 let snapshot = buffer.snapshot(cx);
3349
3350 let mut edits = Vec::new();
3351 let mut rows = Vec::new();
3352 let mut rows_inserted = 0;
3353
3354 for selection in self.selections.all_adjusted(cx) {
3355 let cursor = selection.head();
3356 let row = cursor.row;
3357
3358 let point = Point::new(row + 1, 0);
3359 let start_of_line = snapshot.clip_point(point, Bias::Left);
3360
3361 let newline = "\n".to_string();
3362 edits.push((start_of_line..start_of_line, newline));
3363
3364 rows_inserted += 1;
3365 rows.push(row + rows_inserted);
3366 }
3367
3368 self.transact(window, cx, |editor, window, cx| {
3369 editor.edit(edits, cx);
3370
3371 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3372 let mut index = 0;
3373 s.move_cursors_with(|map, _, _| {
3374 let row = rows[index];
3375 index += 1;
3376
3377 let point = Point::new(row, 0);
3378 let boundary = map.next_line_boundary(point).1;
3379 let clipped = map.clip_point(boundary, Bias::Left);
3380
3381 (clipped, SelectionGoal::None)
3382 });
3383 });
3384
3385 let mut indent_edits = Vec::new();
3386 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3387 for row in rows {
3388 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3389 for (row, indent) in indents {
3390 if indent.len == 0 {
3391 continue;
3392 }
3393
3394 let text = match indent.kind {
3395 IndentKind::Space => " ".repeat(indent.len as usize),
3396 IndentKind::Tab => "\t".repeat(indent.len as usize),
3397 };
3398 let point = Point::new(row.0, 0);
3399 indent_edits.push((point..point, text));
3400 }
3401 }
3402 editor.edit(indent_edits, cx);
3403 });
3404 }
3405
3406 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3407 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3408 original_indent_columns: Vec::new(),
3409 });
3410 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3411 }
3412
3413 fn insert_with_autoindent_mode(
3414 &mut self,
3415 text: &str,
3416 autoindent_mode: Option<AutoindentMode>,
3417 window: &mut Window,
3418 cx: &mut Context<Self>,
3419 ) {
3420 if self.read_only(cx) {
3421 return;
3422 }
3423
3424 let text: Arc<str> = text.into();
3425 self.transact(window, cx, |this, window, cx| {
3426 let old_selections = this.selections.all_adjusted(cx);
3427 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3428 let anchors = {
3429 let snapshot = buffer.read(cx);
3430 old_selections
3431 .iter()
3432 .map(|s| {
3433 let anchor = snapshot.anchor_after(s.head());
3434 s.map(|_| anchor)
3435 })
3436 .collect::<Vec<_>>()
3437 };
3438 buffer.edit(
3439 old_selections
3440 .iter()
3441 .map(|s| (s.start..s.end, text.clone())),
3442 autoindent_mode,
3443 cx,
3444 );
3445 anchors
3446 });
3447
3448 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3449 s.select_anchors(selection_anchors);
3450 });
3451
3452 cx.notify();
3453 });
3454 }
3455
3456 fn trigger_completion_on_input(
3457 &mut self,
3458 text: &str,
3459 trigger_in_words: bool,
3460 window: &mut Window,
3461 cx: &mut Context<Self>,
3462 ) {
3463 if self.is_completion_trigger(text, trigger_in_words, cx) {
3464 self.show_completions(
3465 &ShowCompletions {
3466 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3467 },
3468 window,
3469 cx,
3470 );
3471 } else {
3472 self.hide_context_menu(window, cx);
3473 }
3474 }
3475
3476 fn is_completion_trigger(
3477 &self,
3478 text: &str,
3479 trigger_in_words: bool,
3480 cx: &mut Context<Self>,
3481 ) -> bool {
3482 let position = self.selections.newest_anchor().head();
3483 let multibuffer = self.buffer.read(cx);
3484 let Some(buffer) = position
3485 .buffer_id
3486 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3487 else {
3488 return false;
3489 };
3490
3491 if let Some(completion_provider) = &self.completion_provider {
3492 completion_provider.is_completion_trigger(
3493 &buffer,
3494 position.text_anchor,
3495 text,
3496 trigger_in_words,
3497 cx,
3498 )
3499 } else {
3500 false
3501 }
3502 }
3503
3504 /// If any empty selections is touching the start of its innermost containing autoclose
3505 /// region, expand it to select the brackets.
3506 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3507 let selections = self.selections.all::<usize>(cx);
3508 let buffer = self.buffer.read(cx).read(cx);
3509 let new_selections = self
3510 .selections_with_autoclose_regions(selections, &buffer)
3511 .map(|(mut selection, region)| {
3512 if !selection.is_empty() {
3513 return selection;
3514 }
3515
3516 if let Some(region) = region {
3517 let mut range = region.range.to_offset(&buffer);
3518 if selection.start == range.start && range.start >= region.pair.start.len() {
3519 range.start -= region.pair.start.len();
3520 if buffer.contains_str_at(range.start, ®ion.pair.start)
3521 && buffer.contains_str_at(range.end, ®ion.pair.end)
3522 {
3523 range.end += region.pair.end.len();
3524 selection.start = range.start;
3525 selection.end = range.end;
3526
3527 return selection;
3528 }
3529 }
3530 }
3531
3532 let always_treat_brackets_as_autoclosed = buffer
3533 .settings_at(selection.start, cx)
3534 .always_treat_brackets_as_autoclosed;
3535
3536 if !always_treat_brackets_as_autoclosed {
3537 return selection;
3538 }
3539
3540 if let Some(scope) = buffer.language_scope_at(selection.start) {
3541 for (pair, enabled) in scope.brackets() {
3542 if !enabled || !pair.close {
3543 continue;
3544 }
3545
3546 if buffer.contains_str_at(selection.start, &pair.end) {
3547 let pair_start_len = pair.start.len();
3548 if buffer.contains_str_at(
3549 selection.start.saturating_sub(pair_start_len),
3550 &pair.start,
3551 ) {
3552 selection.start -= pair_start_len;
3553 selection.end += pair.end.len();
3554
3555 return selection;
3556 }
3557 }
3558 }
3559 }
3560
3561 selection
3562 })
3563 .collect();
3564
3565 drop(buffer);
3566 self.change_selections(None, window, cx, |selections| {
3567 selections.select(new_selections)
3568 });
3569 }
3570
3571 /// Iterate the given selections, and for each one, find the smallest surrounding
3572 /// autoclose region. This uses the ordering of the selections and the autoclose
3573 /// regions to avoid repeated comparisons.
3574 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3575 &'a self,
3576 selections: impl IntoIterator<Item = Selection<D>>,
3577 buffer: &'a MultiBufferSnapshot,
3578 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3579 let mut i = 0;
3580 let mut regions = self.autoclose_regions.as_slice();
3581 selections.into_iter().map(move |selection| {
3582 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3583
3584 let mut enclosing = None;
3585 while let Some(pair_state) = regions.get(i) {
3586 if pair_state.range.end.to_offset(buffer) < range.start {
3587 regions = ®ions[i + 1..];
3588 i = 0;
3589 } else if pair_state.range.start.to_offset(buffer) > range.end {
3590 break;
3591 } else {
3592 if pair_state.selection_id == selection.id {
3593 enclosing = Some(pair_state);
3594 }
3595 i += 1;
3596 }
3597 }
3598
3599 (selection, enclosing)
3600 })
3601 }
3602
3603 /// Remove any autoclose regions that no longer contain their selection.
3604 fn invalidate_autoclose_regions(
3605 &mut self,
3606 mut selections: &[Selection<Anchor>],
3607 buffer: &MultiBufferSnapshot,
3608 ) {
3609 self.autoclose_regions.retain(|state| {
3610 let mut i = 0;
3611 while let Some(selection) = selections.get(i) {
3612 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3613 selections = &selections[1..];
3614 continue;
3615 }
3616 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3617 break;
3618 }
3619 if selection.id == state.selection_id {
3620 return true;
3621 } else {
3622 i += 1;
3623 }
3624 }
3625 false
3626 });
3627 }
3628
3629 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3630 let offset = position.to_offset(buffer);
3631 let (word_range, kind) = buffer.surrounding_word(offset, true);
3632 if offset > word_range.start && kind == Some(CharKind::Word) {
3633 Some(
3634 buffer
3635 .text_for_range(word_range.start..offset)
3636 .collect::<String>(),
3637 )
3638 } else {
3639 None
3640 }
3641 }
3642
3643 pub fn toggle_inlay_hints(
3644 &mut self,
3645 _: &ToggleInlayHints,
3646 _: &mut Window,
3647 cx: &mut Context<Self>,
3648 ) {
3649 self.refresh_inlay_hints(
3650 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3651 cx,
3652 );
3653 }
3654
3655 pub fn inlay_hints_enabled(&self) -> bool {
3656 self.inlay_hint_cache.enabled
3657 }
3658
3659 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3660 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3661 return;
3662 }
3663
3664 let reason_description = reason.description();
3665 let ignore_debounce = matches!(
3666 reason,
3667 InlayHintRefreshReason::SettingsChange(_)
3668 | InlayHintRefreshReason::Toggle(_)
3669 | InlayHintRefreshReason::ExcerptsRemoved(_)
3670 );
3671 let (invalidate_cache, required_languages) = match reason {
3672 InlayHintRefreshReason::Toggle(enabled) => {
3673 self.inlay_hint_cache.enabled = enabled;
3674 if enabled {
3675 (InvalidationStrategy::RefreshRequested, None)
3676 } else {
3677 self.inlay_hint_cache.clear();
3678 self.splice_inlays(
3679 &self
3680 .visible_inlay_hints(cx)
3681 .iter()
3682 .map(|inlay| inlay.id)
3683 .collect::<Vec<InlayId>>(),
3684 Vec::new(),
3685 cx,
3686 );
3687 return;
3688 }
3689 }
3690 InlayHintRefreshReason::SettingsChange(new_settings) => {
3691 match self.inlay_hint_cache.update_settings(
3692 &self.buffer,
3693 new_settings,
3694 self.visible_inlay_hints(cx),
3695 cx,
3696 ) {
3697 ControlFlow::Break(Some(InlaySplice {
3698 to_remove,
3699 to_insert,
3700 })) => {
3701 self.splice_inlays(&to_remove, to_insert, cx);
3702 return;
3703 }
3704 ControlFlow::Break(None) => return,
3705 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3706 }
3707 }
3708 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3709 if let Some(InlaySplice {
3710 to_remove,
3711 to_insert,
3712 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3713 {
3714 self.splice_inlays(&to_remove, to_insert, cx);
3715 }
3716 return;
3717 }
3718 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3719 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3720 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3721 }
3722 InlayHintRefreshReason::RefreshRequested => {
3723 (InvalidationStrategy::RefreshRequested, None)
3724 }
3725 };
3726
3727 if let Some(InlaySplice {
3728 to_remove,
3729 to_insert,
3730 }) = self.inlay_hint_cache.spawn_hint_refresh(
3731 reason_description,
3732 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3733 invalidate_cache,
3734 ignore_debounce,
3735 cx,
3736 ) {
3737 self.splice_inlays(&to_remove, to_insert, cx);
3738 }
3739 }
3740
3741 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3742 self.display_map
3743 .read(cx)
3744 .current_inlays()
3745 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3746 .cloned()
3747 .collect()
3748 }
3749
3750 pub fn excerpts_for_inlay_hints_query(
3751 &self,
3752 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3753 cx: &mut Context<Editor>,
3754 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3755 let Some(project) = self.project.as_ref() else {
3756 return HashMap::default();
3757 };
3758 let project = project.read(cx);
3759 let multi_buffer = self.buffer().read(cx);
3760 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3761 let multi_buffer_visible_start = self
3762 .scroll_manager
3763 .anchor()
3764 .anchor
3765 .to_point(&multi_buffer_snapshot);
3766 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3767 multi_buffer_visible_start
3768 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3769 Bias::Left,
3770 );
3771 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3772 multi_buffer_snapshot
3773 .range_to_buffer_ranges(multi_buffer_visible_range)
3774 .into_iter()
3775 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3776 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3777 let buffer_file = project::File::from_dyn(buffer.file())?;
3778 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3779 let worktree_entry = buffer_worktree
3780 .read(cx)
3781 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3782 if worktree_entry.is_ignored {
3783 return None;
3784 }
3785
3786 let language = buffer.language()?;
3787 if let Some(restrict_to_languages) = restrict_to_languages {
3788 if !restrict_to_languages.contains(language) {
3789 return None;
3790 }
3791 }
3792 Some((
3793 excerpt_id,
3794 (
3795 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3796 buffer.version().clone(),
3797 excerpt_visible_range,
3798 ),
3799 ))
3800 })
3801 .collect()
3802 }
3803
3804 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3805 TextLayoutDetails {
3806 text_system: window.text_system().clone(),
3807 editor_style: self.style.clone().unwrap(),
3808 rem_size: window.rem_size(),
3809 scroll_anchor: self.scroll_manager.anchor(),
3810 visible_rows: self.visible_line_count(),
3811 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3812 }
3813 }
3814
3815 pub fn splice_inlays(
3816 &self,
3817 to_remove: &[InlayId],
3818 to_insert: Vec<Inlay>,
3819 cx: &mut Context<Self>,
3820 ) {
3821 self.display_map.update(cx, |display_map, cx| {
3822 display_map.splice_inlays(to_remove, to_insert, cx)
3823 });
3824 cx.notify();
3825 }
3826
3827 fn trigger_on_type_formatting(
3828 &self,
3829 input: String,
3830 window: &mut Window,
3831 cx: &mut Context<Self>,
3832 ) -> Option<Task<Result<()>>> {
3833 if input.len() != 1 {
3834 return None;
3835 }
3836
3837 let project = self.project.as_ref()?;
3838 let position = self.selections.newest_anchor().head();
3839 let (buffer, buffer_position) = self
3840 .buffer
3841 .read(cx)
3842 .text_anchor_for_position(position, cx)?;
3843
3844 let settings = language_settings::language_settings(
3845 buffer
3846 .read(cx)
3847 .language_at(buffer_position)
3848 .map(|l| l.name()),
3849 buffer.read(cx).file(),
3850 cx,
3851 );
3852 if !settings.use_on_type_format {
3853 return None;
3854 }
3855
3856 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3857 // hence we do LSP request & edit on host side only — add formats to host's history.
3858 let push_to_lsp_host_history = true;
3859 // If this is not the host, append its history with new edits.
3860 let push_to_client_history = project.read(cx).is_via_collab();
3861
3862 let on_type_formatting = project.update(cx, |project, cx| {
3863 project.on_type_format(
3864 buffer.clone(),
3865 buffer_position,
3866 input,
3867 push_to_lsp_host_history,
3868 cx,
3869 )
3870 });
3871 Some(cx.spawn_in(window, |editor, mut cx| async move {
3872 if let Some(transaction) = on_type_formatting.await? {
3873 if push_to_client_history {
3874 buffer
3875 .update(&mut cx, |buffer, _| {
3876 buffer.push_transaction(transaction, Instant::now());
3877 })
3878 .ok();
3879 }
3880 editor.update(&mut cx, |editor, cx| {
3881 editor.refresh_document_highlights(cx);
3882 })?;
3883 }
3884 Ok(())
3885 }))
3886 }
3887
3888 pub fn show_completions(
3889 &mut self,
3890 options: &ShowCompletions,
3891 window: &mut Window,
3892 cx: &mut Context<Self>,
3893 ) {
3894 if self.pending_rename.is_some() {
3895 return;
3896 }
3897
3898 let Some(provider) = self.completion_provider.as_ref() else {
3899 return;
3900 };
3901
3902 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3903 return;
3904 }
3905
3906 let position = self.selections.newest_anchor().head();
3907 if position.diff_base_anchor.is_some() {
3908 return;
3909 }
3910 let (buffer, buffer_position) =
3911 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3912 output
3913 } else {
3914 return;
3915 };
3916 let show_completion_documentation = buffer
3917 .read(cx)
3918 .snapshot()
3919 .settings_at(buffer_position, cx)
3920 .show_completion_documentation;
3921
3922 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3923
3924 let trigger_kind = match &options.trigger {
3925 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3926 CompletionTriggerKind::TRIGGER_CHARACTER
3927 }
3928 _ => CompletionTriggerKind::INVOKED,
3929 };
3930 let completion_context = CompletionContext {
3931 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3932 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3933 Some(String::from(trigger))
3934 } else {
3935 None
3936 }
3937 }),
3938 trigger_kind,
3939 };
3940 let completions =
3941 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3942 let sort_completions = provider.sort_completions();
3943
3944 let id = post_inc(&mut self.next_completion_id);
3945 let task = cx.spawn_in(window, |editor, mut cx| {
3946 async move {
3947 editor.update(&mut cx, |this, _| {
3948 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3949 })?;
3950 let completions = completions.await.log_err();
3951 let menu = if let Some(completions) = completions {
3952 let mut menu = CompletionsMenu::new(
3953 id,
3954 sort_completions,
3955 show_completion_documentation,
3956 position,
3957 buffer.clone(),
3958 completions.into(),
3959 );
3960
3961 menu.filter(query.as_deref(), cx.background_executor().clone())
3962 .await;
3963
3964 menu.visible().then_some(menu)
3965 } else {
3966 None
3967 };
3968
3969 editor.update_in(&mut cx, |editor, window, cx| {
3970 match editor.context_menu.borrow().as_ref() {
3971 None => {}
3972 Some(CodeContextMenu::Completions(prev_menu)) => {
3973 if prev_menu.id > id {
3974 return;
3975 }
3976 }
3977 _ => return,
3978 }
3979
3980 if editor.focus_handle.is_focused(window) && menu.is_some() {
3981 let mut menu = menu.unwrap();
3982 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3983
3984 *editor.context_menu.borrow_mut() =
3985 Some(CodeContextMenu::Completions(menu));
3986
3987 if editor.show_edit_predictions_in_menu() {
3988 editor.update_visible_inline_completion(window, cx);
3989 } else {
3990 editor.discard_inline_completion(false, cx);
3991 }
3992
3993 cx.notify();
3994 } else if editor.completion_tasks.len() <= 1 {
3995 // If there are no more completion tasks and the last menu was
3996 // empty, we should hide it.
3997 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3998 // If it was already hidden and we don't show inline
3999 // completions in the menu, we should also show the
4000 // inline-completion when available.
4001 if was_hidden && editor.show_edit_predictions_in_menu() {
4002 editor.update_visible_inline_completion(window, cx);
4003 }
4004 }
4005 })?;
4006
4007 Ok::<_, anyhow::Error>(())
4008 }
4009 .log_err()
4010 });
4011
4012 self.completion_tasks.push((id, task));
4013 }
4014
4015 pub fn confirm_completion(
4016 &mut self,
4017 action: &ConfirmCompletion,
4018 window: &mut Window,
4019 cx: &mut Context<Self>,
4020 ) -> Option<Task<Result<()>>> {
4021 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4022 }
4023
4024 pub fn compose_completion(
4025 &mut self,
4026 action: &ComposeCompletion,
4027 window: &mut Window,
4028 cx: &mut Context<Self>,
4029 ) -> Option<Task<Result<()>>> {
4030 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4031 }
4032
4033 fn do_completion(
4034 &mut self,
4035 item_ix: Option<usize>,
4036 intent: CompletionIntent,
4037 window: &mut Window,
4038 cx: &mut Context<Editor>,
4039 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4040 use language::ToOffset as _;
4041
4042 let completions_menu =
4043 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4044 menu
4045 } else {
4046 return None;
4047 };
4048
4049 let entries = completions_menu.entries.borrow();
4050 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4051 if self.show_edit_predictions_in_menu() {
4052 self.discard_inline_completion(true, cx);
4053 }
4054 let candidate_id = mat.candidate_id;
4055 drop(entries);
4056
4057 let buffer_handle = completions_menu.buffer;
4058 let completion = completions_menu
4059 .completions
4060 .borrow()
4061 .get(candidate_id)?
4062 .clone();
4063 cx.stop_propagation();
4064
4065 let snippet;
4066 let text;
4067
4068 if completion.is_snippet() {
4069 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4070 text = snippet.as_ref().unwrap().text.clone();
4071 } else {
4072 snippet = None;
4073 text = completion.new_text.clone();
4074 };
4075 let selections = self.selections.all::<usize>(cx);
4076 let buffer = buffer_handle.read(cx);
4077 let old_range = completion.old_range.to_offset(buffer);
4078 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4079
4080 let newest_selection = self.selections.newest_anchor();
4081 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4082 return None;
4083 }
4084
4085 let lookbehind = newest_selection
4086 .start
4087 .text_anchor
4088 .to_offset(buffer)
4089 .saturating_sub(old_range.start);
4090 let lookahead = old_range
4091 .end
4092 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4093 let mut common_prefix_len = old_text
4094 .bytes()
4095 .zip(text.bytes())
4096 .take_while(|(a, b)| a == b)
4097 .count();
4098
4099 let snapshot = self.buffer.read(cx).snapshot(cx);
4100 let mut range_to_replace: Option<Range<isize>> = None;
4101 let mut ranges = Vec::new();
4102 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4103 for selection in &selections {
4104 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4105 let start = selection.start.saturating_sub(lookbehind);
4106 let end = selection.end + lookahead;
4107 if selection.id == newest_selection.id {
4108 range_to_replace = Some(
4109 ((start + common_prefix_len) as isize - selection.start as isize)
4110 ..(end as isize - selection.start as isize),
4111 );
4112 }
4113 ranges.push(start + common_prefix_len..end);
4114 } else {
4115 common_prefix_len = 0;
4116 ranges.clear();
4117 ranges.extend(selections.iter().map(|s| {
4118 if s.id == newest_selection.id {
4119 range_to_replace = Some(
4120 old_range.start.to_offset_utf16(&snapshot).0 as isize
4121 - selection.start as isize
4122 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4123 - selection.start as isize,
4124 );
4125 old_range.clone()
4126 } else {
4127 s.start..s.end
4128 }
4129 }));
4130 break;
4131 }
4132 if !self.linked_edit_ranges.is_empty() {
4133 let start_anchor = snapshot.anchor_before(selection.head());
4134 let end_anchor = snapshot.anchor_after(selection.tail());
4135 if let Some(ranges) = self
4136 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4137 {
4138 for (buffer, edits) in ranges {
4139 linked_edits.entry(buffer.clone()).or_default().extend(
4140 edits
4141 .into_iter()
4142 .map(|range| (range, text[common_prefix_len..].to_owned())),
4143 );
4144 }
4145 }
4146 }
4147 }
4148 let text = &text[common_prefix_len..];
4149
4150 cx.emit(EditorEvent::InputHandled {
4151 utf16_range_to_replace: range_to_replace,
4152 text: text.into(),
4153 });
4154
4155 self.transact(window, cx, |this, window, cx| {
4156 if let Some(mut snippet) = snippet {
4157 snippet.text = text.to_string();
4158 for tabstop in snippet
4159 .tabstops
4160 .iter_mut()
4161 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4162 {
4163 tabstop.start -= common_prefix_len as isize;
4164 tabstop.end -= common_prefix_len as isize;
4165 }
4166
4167 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4168 } else {
4169 this.buffer.update(cx, |buffer, cx| {
4170 buffer.edit(
4171 ranges.iter().map(|range| (range.clone(), text)),
4172 this.autoindent_mode.clone(),
4173 cx,
4174 );
4175 });
4176 }
4177 for (buffer, edits) in linked_edits {
4178 buffer.update(cx, |buffer, cx| {
4179 let snapshot = buffer.snapshot();
4180 let edits = edits
4181 .into_iter()
4182 .map(|(range, text)| {
4183 use text::ToPoint as TP;
4184 let end_point = TP::to_point(&range.end, &snapshot);
4185 let start_point = TP::to_point(&range.start, &snapshot);
4186 (start_point..end_point, text)
4187 })
4188 .sorted_by_key(|(range, _)| range.start)
4189 .collect::<Vec<_>>();
4190 buffer.edit(edits, None, cx);
4191 })
4192 }
4193
4194 this.refresh_inline_completion(true, false, window, cx);
4195 });
4196
4197 let show_new_completions_on_confirm = completion
4198 .confirm
4199 .as_ref()
4200 .map_or(false, |confirm| confirm(intent, window, cx));
4201 if show_new_completions_on_confirm {
4202 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4203 }
4204
4205 let provider = self.completion_provider.as_ref()?;
4206 drop(completion);
4207 let apply_edits = provider.apply_additional_edits_for_completion(
4208 buffer_handle,
4209 completions_menu.completions.clone(),
4210 candidate_id,
4211 true,
4212 cx,
4213 );
4214
4215 let editor_settings = EditorSettings::get_global(cx);
4216 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4217 // After the code completion is finished, users often want to know what signatures are needed.
4218 // so we should automatically call signature_help
4219 self.show_signature_help(&ShowSignatureHelp, window, cx);
4220 }
4221
4222 Some(cx.foreground_executor().spawn(async move {
4223 apply_edits.await?;
4224 Ok(())
4225 }))
4226 }
4227
4228 pub fn toggle_code_actions(
4229 &mut self,
4230 action: &ToggleCodeActions,
4231 window: &mut Window,
4232 cx: &mut Context<Self>,
4233 ) {
4234 let mut context_menu = self.context_menu.borrow_mut();
4235 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4236 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4237 // Toggle if we're selecting the same one
4238 *context_menu = None;
4239 cx.notify();
4240 return;
4241 } else {
4242 // Otherwise, clear it and start a new one
4243 *context_menu = None;
4244 cx.notify();
4245 }
4246 }
4247 drop(context_menu);
4248 let snapshot = self.snapshot(window, cx);
4249 let deployed_from_indicator = action.deployed_from_indicator;
4250 let mut task = self.code_actions_task.take();
4251 let action = action.clone();
4252 cx.spawn_in(window, |editor, mut cx| async move {
4253 while let Some(prev_task) = task {
4254 prev_task.await.log_err();
4255 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4256 }
4257
4258 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4259 if editor.focus_handle.is_focused(window) {
4260 let multibuffer_point = action
4261 .deployed_from_indicator
4262 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4263 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4264 let (buffer, buffer_row) = snapshot
4265 .buffer_snapshot
4266 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4267 .and_then(|(buffer_snapshot, range)| {
4268 editor
4269 .buffer
4270 .read(cx)
4271 .buffer(buffer_snapshot.remote_id())
4272 .map(|buffer| (buffer, range.start.row))
4273 })?;
4274 let (_, code_actions) = editor
4275 .available_code_actions
4276 .clone()
4277 .and_then(|(location, code_actions)| {
4278 let snapshot = location.buffer.read(cx).snapshot();
4279 let point_range = location.range.to_point(&snapshot);
4280 let point_range = point_range.start.row..=point_range.end.row;
4281 if point_range.contains(&buffer_row) {
4282 Some((location, code_actions))
4283 } else {
4284 None
4285 }
4286 })
4287 .unzip();
4288 let buffer_id = buffer.read(cx).remote_id();
4289 let tasks = editor
4290 .tasks
4291 .get(&(buffer_id, buffer_row))
4292 .map(|t| Arc::new(t.to_owned()));
4293 if tasks.is_none() && code_actions.is_none() {
4294 return None;
4295 }
4296
4297 editor.completion_tasks.clear();
4298 editor.discard_inline_completion(false, cx);
4299 let task_context =
4300 tasks
4301 .as_ref()
4302 .zip(editor.project.clone())
4303 .map(|(tasks, project)| {
4304 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4305 });
4306
4307 Some(cx.spawn_in(window, |editor, mut cx| async move {
4308 let task_context = match task_context {
4309 Some(task_context) => task_context.await,
4310 None => None,
4311 };
4312 let resolved_tasks =
4313 tasks.zip(task_context).map(|(tasks, task_context)| {
4314 Rc::new(ResolvedTasks {
4315 templates: tasks.resolve(&task_context).collect(),
4316 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4317 multibuffer_point.row,
4318 tasks.column,
4319 )),
4320 })
4321 });
4322 let spawn_straight_away = resolved_tasks
4323 .as_ref()
4324 .map_or(false, |tasks| tasks.templates.len() == 1)
4325 && code_actions
4326 .as_ref()
4327 .map_or(true, |actions| actions.is_empty());
4328 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4329 *editor.context_menu.borrow_mut() =
4330 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4331 buffer,
4332 actions: CodeActionContents {
4333 tasks: resolved_tasks,
4334 actions: code_actions,
4335 },
4336 selected_item: Default::default(),
4337 scroll_handle: UniformListScrollHandle::default(),
4338 deployed_from_indicator,
4339 }));
4340 if spawn_straight_away {
4341 if let Some(task) = editor.confirm_code_action(
4342 &ConfirmCodeAction { item_ix: Some(0) },
4343 window,
4344 cx,
4345 ) {
4346 cx.notify();
4347 return task;
4348 }
4349 }
4350 cx.notify();
4351 Task::ready(Ok(()))
4352 }) {
4353 task.await
4354 } else {
4355 Ok(())
4356 }
4357 }))
4358 } else {
4359 Some(Task::ready(Ok(())))
4360 }
4361 })?;
4362 if let Some(task) = spawned_test_task {
4363 task.await?;
4364 }
4365
4366 Ok::<_, anyhow::Error>(())
4367 })
4368 .detach_and_log_err(cx);
4369 }
4370
4371 pub fn confirm_code_action(
4372 &mut self,
4373 action: &ConfirmCodeAction,
4374 window: &mut Window,
4375 cx: &mut Context<Self>,
4376 ) -> Option<Task<Result<()>>> {
4377 let actions_menu =
4378 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4379 menu
4380 } else {
4381 return None;
4382 };
4383 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4384 let action = actions_menu.actions.get(action_ix)?;
4385 let title = action.label();
4386 let buffer = actions_menu.buffer;
4387 let workspace = self.workspace()?;
4388
4389 match action {
4390 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4391 workspace.update(cx, |workspace, cx| {
4392 workspace::tasks::schedule_resolved_task(
4393 workspace,
4394 task_source_kind,
4395 resolved_task,
4396 false,
4397 cx,
4398 );
4399
4400 Some(Task::ready(Ok(())))
4401 })
4402 }
4403 CodeActionsItem::CodeAction {
4404 excerpt_id,
4405 action,
4406 provider,
4407 } => {
4408 let apply_code_action =
4409 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4410 let workspace = workspace.downgrade();
4411 Some(cx.spawn_in(window, |editor, cx| async move {
4412 let project_transaction = apply_code_action.await?;
4413 Self::open_project_transaction(
4414 &editor,
4415 workspace,
4416 project_transaction,
4417 title,
4418 cx,
4419 )
4420 .await
4421 }))
4422 }
4423 }
4424 }
4425
4426 pub async fn open_project_transaction(
4427 this: &WeakEntity<Editor>,
4428 workspace: WeakEntity<Workspace>,
4429 transaction: ProjectTransaction,
4430 title: String,
4431 mut cx: AsyncWindowContext,
4432 ) -> Result<()> {
4433 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4434 cx.update(|_, cx| {
4435 entries.sort_unstable_by_key(|(buffer, _)| {
4436 buffer.read(cx).file().map(|f| f.path().clone())
4437 });
4438 })?;
4439
4440 // If the project transaction's edits are all contained within this editor, then
4441 // avoid opening a new editor to display them.
4442
4443 if let Some((buffer, transaction)) = entries.first() {
4444 if entries.len() == 1 {
4445 let excerpt = this.update(&mut cx, |editor, cx| {
4446 editor
4447 .buffer()
4448 .read(cx)
4449 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4450 })?;
4451 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4452 if excerpted_buffer == *buffer {
4453 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4454 let excerpt_range = excerpt_range.to_offset(buffer);
4455 buffer
4456 .edited_ranges_for_transaction::<usize>(transaction)
4457 .all(|range| {
4458 excerpt_range.start <= range.start
4459 && excerpt_range.end >= range.end
4460 })
4461 })?;
4462
4463 if all_edits_within_excerpt {
4464 return Ok(());
4465 }
4466 }
4467 }
4468 }
4469 } else {
4470 return Ok(());
4471 }
4472
4473 let mut ranges_to_highlight = Vec::new();
4474 let excerpt_buffer = cx.new(|cx| {
4475 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4476 for (buffer_handle, transaction) in &entries {
4477 let buffer = buffer_handle.read(cx);
4478 ranges_to_highlight.extend(
4479 multibuffer.push_excerpts_with_context_lines(
4480 buffer_handle.clone(),
4481 buffer
4482 .edited_ranges_for_transaction::<usize>(transaction)
4483 .collect(),
4484 DEFAULT_MULTIBUFFER_CONTEXT,
4485 cx,
4486 ),
4487 );
4488 }
4489 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4490 multibuffer
4491 })?;
4492
4493 workspace.update_in(&mut cx, |workspace, window, cx| {
4494 let project = workspace.project().clone();
4495 let editor = cx
4496 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4497 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4498 editor.update(cx, |editor, cx| {
4499 editor.highlight_background::<Self>(
4500 &ranges_to_highlight,
4501 |theme| theme.editor_highlighted_line_background,
4502 cx,
4503 );
4504 });
4505 })?;
4506
4507 Ok(())
4508 }
4509
4510 pub fn clear_code_action_providers(&mut self) {
4511 self.code_action_providers.clear();
4512 self.available_code_actions.take();
4513 }
4514
4515 pub fn add_code_action_provider(
4516 &mut self,
4517 provider: Rc<dyn CodeActionProvider>,
4518 window: &mut Window,
4519 cx: &mut Context<Self>,
4520 ) {
4521 if self
4522 .code_action_providers
4523 .iter()
4524 .any(|existing_provider| existing_provider.id() == provider.id())
4525 {
4526 return;
4527 }
4528
4529 self.code_action_providers.push(provider);
4530 self.refresh_code_actions(window, cx);
4531 }
4532
4533 pub fn remove_code_action_provider(
4534 &mut self,
4535 id: Arc<str>,
4536 window: &mut Window,
4537 cx: &mut Context<Self>,
4538 ) {
4539 self.code_action_providers
4540 .retain(|provider| provider.id() != id);
4541 self.refresh_code_actions(window, cx);
4542 }
4543
4544 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4545 let buffer = self.buffer.read(cx);
4546 let newest_selection = self.selections.newest_anchor().clone();
4547 if newest_selection.head().diff_base_anchor.is_some() {
4548 return None;
4549 }
4550 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4551 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4552 if start_buffer != end_buffer {
4553 return None;
4554 }
4555
4556 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4557 cx.background_executor()
4558 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4559 .await;
4560
4561 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4562 let providers = this.code_action_providers.clone();
4563 let tasks = this
4564 .code_action_providers
4565 .iter()
4566 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4567 .collect::<Vec<_>>();
4568 (providers, tasks)
4569 })?;
4570
4571 let mut actions = Vec::new();
4572 for (provider, provider_actions) in
4573 providers.into_iter().zip(future::join_all(tasks).await)
4574 {
4575 if let Some(provider_actions) = provider_actions.log_err() {
4576 actions.extend(provider_actions.into_iter().map(|action| {
4577 AvailableCodeAction {
4578 excerpt_id: newest_selection.start.excerpt_id,
4579 action,
4580 provider: provider.clone(),
4581 }
4582 }));
4583 }
4584 }
4585
4586 this.update(&mut cx, |this, cx| {
4587 this.available_code_actions = if actions.is_empty() {
4588 None
4589 } else {
4590 Some((
4591 Location {
4592 buffer: start_buffer,
4593 range: start..end,
4594 },
4595 actions.into(),
4596 ))
4597 };
4598 cx.notify();
4599 })
4600 }));
4601 None
4602 }
4603
4604 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4605 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4606 self.show_git_blame_inline = false;
4607
4608 self.show_git_blame_inline_delay_task =
4609 Some(cx.spawn_in(window, |this, mut cx| async move {
4610 cx.background_executor().timer(delay).await;
4611
4612 this.update(&mut cx, |this, cx| {
4613 this.show_git_blame_inline = true;
4614 cx.notify();
4615 })
4616 .log_err();
4617 }));
4618 }
4619 }
4620
4621 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4622 if self.pending_rename.is_some() {
4623 return None;
4624 }
4625
4626 let provider = self.semantics_provider.clone()?;
4627 let buffer = self.buffer.read(cx);
4628 let newest_selection = self.selections.newest_anchor().clone();
4629 let cursor_position = newest_selection.head();
4630 let (cursor_buffer, cursor_buffer_position) =
4631 buffer.text_anchor_for_position(cursor_position, cx)?;
4632 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4633 if cursor_buffer != tail_buffer {
4634 return None;
4635 }
4636 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4637 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4638 cx.background_executor()
4639 .timer(Duration::from_millis(debounce))
4640 .await;
4641
4642 let highlights = if let Some(highlights) = cx
4643 .update(|cx| {
4644 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4645 })
4646 .ok()
4647 .flatten()
4648 {
4649 highlights.await.log_err()
4650 } else {
4651 None
4652 };
4653
4654 if let Some(highlights) = highlights {
4655 this.update(&mut cx, |this, cx| {
4656 if this.pending_rename.is_some() {
4657 return;
4658 }
4659
4660 let buffer_id = cursor_position.buffer_id;
4661 let buffer = this.buffer.read(cx);
4662 if !buffer
4663 .text_anchor_for_position(cursor_position, cx)
4664 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4665 {
4666 return;
4667 }
4668
4669 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4670 let mut write_ranges = Vec::new();
4671 let mut read_ranges = Vec::new();
4672 for highlight in highlights {
4673 for (excerpt_id, excerpt_range) in
4674 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4675 {
4676 let start = highlight
4677 .range
4678 .start
4679 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4680 let end = highlight
4681 .range
4682 .end
4683 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4684 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4685 continue;
4686 }
4687
4688 let range = Anchor {
4689 buffer_id,
4690 excerpt_id,
4691 text_anchor: start,
4692 diff_base_anchor: None,
4693 }..Anchor {
4694 buffer_id,
4695 excerpt_id,
4696 text_anchor: end,
4697 diff_base_anchor: None,
4698 };
4699 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4700 write_ranges.push(range);
4701 } else {
4702 read_ranges.push(range);
4703 }
4704 }
4705 }
4706
4707 this.highlight_background::<DocumentHighlightRead>(
4708 &read_ranges,
4709 |theme| theme.editor_document_highlight_read_background,
4710 cx,
4711 );
4712 this.highlight_background::<DocumentHighlightWrite>(
4713 &write_ranges,
4714 |theme| theme.editor_document_highlight_write_background,
4715 cx,
4716 );
4717 cx.notify();
4718 })
4719 .log_err();
4720 }
4721 }));
4722 None
4723 }
4724
4725 pub fn refresh_inline_completion(
4726 &mut self,
4727 debounce: bool,
4728 user_requested: bool,
4729 window: &mut Window,
4730 cx: &mut Context<Self>,
4731 ) -> Option<()> {
4732 let provider = self.edit_prediction_provider()?;
4733 let cursor = self.selections.newest_anchor().head();
4734 let (buffer, cursor_buffer_position) =
4735 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4736
4737 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4738 self.discard_inline_completion(false, cx);
4739 return None;
4740 }
4741
4742 if !user_requested
4743 && (!self.should_show_edit_predictions()
4744 || !self.is_focused(window)
4745 || buffer.read(cx).is_empty())
4746 {
4747 self.discard_inline_completion(false, cx);
4748 return None;
4749 }
4750
4751 self.update_visible_inline_completion(window, cx);
4752 provider.refresh(
4753 self.project.clone(),
4754 buffer,
4755 cursor_buffer_position,
4756 debounce,
4757 cx,
4758 );
4759 Some(())
4760 }
4761
4762 fn show_edit_predictions_in_menu(&self) -> bool {
4763 match self.edit_prediction_settings {
4764 EditPredictionSettings::Disabled => false,
4765 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4766 }
4767 }
4768
4769 pub fn edit_predictions_enabled(&self) -> bool {
4770 match self.edit_prediction_settings {
4771 EditPredictionSettings::Disabled => false,
4772 EditPredictionSettings::Enabled { .. } => true,
4773 }
4774 }
4775
4776 fn edit_prediction_requires_modifier(&self) -> bool {
4777 match self.edit_prediction_settings {
4778 EditPredictionSettings::Disabled => false,
4779 EditPredictionSettings::Enabled {
4780 preview_requires_modifier,
4781 ..
4782 } => preview_requires_modifier,
4783 }
4784 }
4785
4786 fn edit_prediction_settings_at_position(
4787 &self,
4788 buffer: &Entity<Buffer>,
4789 buffer_position: language::Anchor,
4790 cx: &App,
4791 ) -> EditPredictionSettings {
4792 if self.mode != EditorMode::Full
4793 || !self.show_inline_completions_override.unwrap_or(true)
4794 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4795 {
4796 return EditPredictionSettings::Disabled;
4797 }
4798
4799 let buffer = buffer.read(cx);
4800
4801 let file = buffer.file();
4802
4803 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4804 return EditPredictionSettings::Disabled;
4805 };
4806
4807 let by_provider = matches!(
4808 self.menu_inline_completions_policy,
4809 MenuInlineCompletionsPolicy::ByProvider
4810 );
4811
4812 let show_in_menu = by_provider
4813 && self
4814 .edit_prediction_provider
4815 .as_ref()
4816 .map_or(false, |provider| {
4817 provider.provider.show_completions_in_menu()
4818 });
4819
4820 let preview_requires_modifier =
4821 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4822
4823 EditPredictionSettings::Enabled {
4824 show_in_menu,
4825 preview_requires_modifier,
4826 }
4827 }
4828
4829 fn should_show_edit_predictions(&self) -> bool {
4830 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4831 }
4832
4833 pub fn edit_prediction_preview_is_active(&self) -> bool {
4834 matches!(
4835 self.edit_prediction_preview,
4836 EditPredictionPreview::Active { .. }
4837 )
4838 }
4839
4840 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4841 let cursor = self.selections.newest_anchor().head();
4842 if let Some((buffer, cursor_position)) =
4843 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4844 {
4845 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4846 } else {
4847 false
4848 }
4849 }
4850
4851 fn inline_completions_enabled_in_buffer(
4852 &self,
4853 buffer: &Entity<Buffer>,
4854 buffer_position: language::Anchor,
4855 cx: &App,
4856 ) -> bool {
4857 maybe!({
4858 let provider = self.edit_prediction_provider()?;
4859 if !provider.is_enabled(&buffer, buffer_position, cx) {
4860 return Some(false);
4861 }
4862 let buffer = buffer.read(cx);
4863 let Some(file) = buffer.file() else {
4864 return Some(true);
4865 };
4866 let settings = all_language_settings(Some(file), cx);
4867 Some(settings.inline_completions_enabled_for_path(file.path()))
4868 })
4869 .unwrap_or(false)
4870 }
4871
4872 fn cycle_inline_completion(
4873 &mut self,
4874 direction: Direction,
4875 window: &mut Window,
4876 cx: &mut Context<Self>,
4877 ) -> Option<()> {
4878 let provider = self.edit_prediction_provider()?;
4879 let cursor = self.selections.newest_anchor().head();
4880 let (buffer, cursor_buffer_position) =
4881 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4882 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4883 return None;
4884 }
4885
4886 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4887 self.update_visible_inline_completion(window, cx);
4888
4889 Some(())
4890 }
4891
4892 pub fn show_inline_completion(
4893 &mut self,
4894 _: &ShowEditPrediction,
4895 window: &mut Window,
4896 cx: &mut Context<Self>,
4897 ) {
4898 if !self.has_active_inline_completion() {
4899 self.refresh_inline_completion(false, true, window, cx);
4900 return;
4901 }
4902
4903 self.update_visible_inline_completion(window, cx);
4904 }
4905
4906 pub fn display_cursor_names(
4907 &mut self,
4908 _: &DisplayCursorNames,
4909 window: &mut Window,
4910 cx: &mut Context<Self>,
4911 ) {
4912 self.show_cursor_names(window, cx);
4913 }
4914
4915 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4916 self.show_cursor_names = true;
4917 cx.notify();
4918 cx.spawn_in(window, |this, mut cx| async move {
4919 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4920 this.update(&mut cx, |this, cx| {
4921 this.show_cursor_names = false;
4922 cx.notify()
4923 })
4924 .ok()
4925 })
4926 .detach();
4927 }
4928
4929 pub fn next_edit_prediction(
4930 &mut self,
4931 _: &NextEditPrediction,
4932 window: &mut Window,
4933 cx: &mut Context<Self>,
4934 ) {
4935 if self.has_active_inline_completion() {
4936 self.cycle_inline_completion(Direction::Next, window, cx);
4937 } else {
4938 let is_copilot_disabled = self
4939 .refresh_inline_completion(false, true, window, cx)
4940 .is_none();
4941 if is_copilot_disabled {
4942 cx.propagate();
4943 }
4944 }
4945 }
4946
4947 pub fn previous_edit_prediction(
4948 &mut self,
4949 _: &PreviousEditPrediction,
4950 window: &mut Window,
4951 cx: &mut Context<Self>,
4952 ) {
4953 if self.has_active_inline_completion() {
4954 self.cycle_inline_completion(Direction::Prev, window, cx);
4955 } else {
4956 let is_copilot_disabled = self
4957 .refresh_inline_completion(false, true, window, cx)
4958 .is_none();
4959 if is_copilot_disabled {
4960 cx.propagate();
4961 }
4962 }
4963 }
4964
4965 pub fn accept_edit_prediction(
4966 &mut self,
4967 _: &AcceptEditPrediction,
4968 window: &mut Window,
4969 cx: &mut Context<Self>,
4970 ) {
4971 if self.show_edit_predictions_in_menu() {
4972 self.hide_context_menu(window, cx);
4973 }
4974
4975 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4976 return;
4977 };
4978
4979 self.report_inline_completion_event(
4980 active_inline_completion.completion_id.clone(),
4981 true,
4982 cx,
4983 );
4984
4985 match &active_inline_completion.completion {
4986 InlineCompletion::Move { target, .. } => {
4987 let target = *target;
4988
4989 if let Some(position_map) = &self.last_position_map {
4990 if position_map
4991 .visible_row_range
4992 .contains(&target.to_display_point(&position_map.snapshot).row())
4993 || !self.edit_prediction_requires_modifier()
4994 {
4995 // Note that this is also done in vim's handler of the Tab action.
4996 self.change_selections(
4997 Some(Autoscroll::newest()),
4998 window,
4999 cx,
5000 |selections| {
5001 selections.select_anchor_ranges([target..target]);
5002 },
5003 );
5004 self.clear_row_highlights::<EditPredictionPreview>();
5005
5006 self.edit_prediction_preview = EditPredictionPreview::Active {
5007 previous_scroll_position: None,
5008 };
5009 } else {
5010 self.edit_prediction_preview = EditPredictionPreview::Active {
5011 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5012 };
5013 self.highlight_rows::<EditPredictionPreview>(
5014 target..target,
5015 cx.theme().colors().editor_highlighted_line_background,
5016 true,
5017 cx,
5018 );
5019 self.request_autoscroll(Autoscroll::fit(), cx);
5020 }
5021 }
5022 }
5023 InlineCompletion::Edit { edits, .. } => {
5024 if let Some(provider) = self.edit_prediction_provider() {
5025 provider.accept(cx);
5026 }
5027
5028 let snapshot = self.buffer.read(cx).snapshot(cx);
5029 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5030
5031 self.buffer.update(cx, |buffer, cx| {
5032 buffer.edit(edits.iter().cloned(), None, cx)
5033 });
5034
5035 self.change_selections(None, window, cx, |s| {
5036 s.select_anchor_ranges([last_edit_end..last_edit_end])
5037 });
5038
5039 self.update_visible_inline_completion(window, cx);
5040 if self.active_inline_completion.is_none() {
5041 self.refresh_inline_completion(true, true, window, cx);
5042 }
5043
5044 cx.notify();
5045 }
5046 }
5047
5048 self.edit_prediction_requires_modifier_in_leading_space = false;
5049 }
5050
5051 pub fn accept_partial_inline_completion(
5052 &mut self,
5053 _: &AcceptPartialEditPrediction,
5054 window: &mut Window,
5055 cx: &mut Context<Self>,
5056 ) {
5057 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5058 return;
5059 };
5060 if self.selections.count() != 1 {
5061 return;
5062 }
5063
5064 self.report_inline_completion_event(
5065 active_inline_completion.completion_id.clone(),
5066 true,
5067 cx,
5068 );
5069
5070 match &active_inline_completion.completion {
5071 InlineCompletion::Move { target, .. } => {
5072 let target = *target;
5073 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5074 selections.select_anchor_ranges([target..target]);
5075 });
5076 }
5077 InlineCompletion::Edit { edits, .. } => {
5078 // Find an insertion that starts at the cursor position.
5079 let snapshot = self.buffer.read(cx).snapshot(cx);
5080 let cursor_offset = self.selections.newest::<usize>(cx).head();
5081 let insertion = edits.iter().find_map(|(range, text)| {
5082 let range = range.to_offset(&snapshot);
5083 if range.is_empty() && range.start == cursor_offset {
5084 Some(text)
5085 } else {
5086 None
5087 }
5088 });
5089
5090 if let Some(text) = insertion {
5091 let mut partial_completion = text
5092 .chars()
5093 .by_ref()
5094 .take_while(|c| c.is_alphabetic())
5095 .collect::<String>();
5096 if partial_completion.is_empty() {
5097 partial_completion = text
5098 .chars()
5099 .by_ref()
5100 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5101 .collect::<String>();
5102 }
5103
5104 cx.emit(EditorEvent::InputHandled {
5105 utf16_range_to_replace: None,
5106 text: partial_completion.clone().into(),
5107 });
5108
5109 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5110
5111 self.refresh_inline_completion(true, true, window, cx);
5112 cx.notify();
5113 } else {
5114 self.accept_edit_prediction(&Default::default(), window, cx);
5115 }
5116 }
5117 }
5118 }
5119
5120 fn discard_inline_completion(
5121 &mut self,
5122 should_report_inline_completion_event: bool,
5123 cx: &mut Context<Self>,
5124 ) -> bool {
5125 if should_report_inline_completion_event {
5126 let completion_id = self
5127 .active_inline_completion
5128 .as_ref()
5129 .and_then(|active_completion| active_completion.completion_id.clone());
5130
5131 self.report_inline_completion_event(completion_id, false, cx);
5132 }
5133
5134 if let Some(provider) = self.edit_prediction_provider() {
5135 provider.discard(cx);
5136 }
5137
5138 self.take_active_inline_completion(cx)
5139 }
5140
5141 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5142 let Some(provider) = self.edit_prediction_provider() else {
5143 return;
5144 };
5145
5146 let Some((_, buffer, _)) = self
5147 .buffer
5148 .read(cx)
5149 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5150 else {
5151 return;
5152 };
5153
5154 let extension = buffer
5155 .read(cx)
5156 .file()
5157 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5158
5159 let event_type = match accepted {
5160 true => "Edit Prediction Accepted",
5161 false => "Edit Prediction Discarded",
5162 };
5163 telemetry::event!(
5164 event_type,
5165 provider = provider.name(),
5166 prediction_id = id,
5167 suggestion_accepted = accepted,
5168 file_extension = extension,
5169 );
5170 }
5171
5172 pub fn has_active_inline_completion(&self) -> bool {
5173 self.active_inline_completion.is_some()
5174 }
5175
5176 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5177 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5178 return false;
5179 };
5180
5181 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5182 self.clear_highlights::<InlineCompletionHighlight>(cx);
5183 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5184 true
5185 }
5186
5187 /// Returns true when we're displaying the edit prediction popover below the cursor
5188 /// like we are not previewing and the LSP autocomplete menu is visible
5189 /// or we are in `when_holding_modifier` mode.
5190 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5191 if self.edit_prediction_preview_is_active()
5192 || !self.show_edit_predictions_in_menu()
5193 || !self.edit_predictions_enabled()
5194 {
5195 return false;
5196 }
5197
5198 if self.has_visible_completions_menu() {
5199 return true;
5200 }
5201
5202 has_completion && self.edit_prediction_requires_modifier()
5203 }
5204
5205 fn handle_modifiers_changed(
5206 &mut self,
5207 modifiers: Modifiers,
5208 position_map: &PositionMap,
5209 window: &mut Window,
5210 cx: &mut Context<Self>,
5211 ) {
5212 if self.show_edit_predictions_in_menu() {
5213 self.update_edit_prediction_preview(&modifiers, window, cx);
5214 }
5215
5216 let mouse_position = window.mouse_position();
5217 if !position_map.text_hitbox.is_hovered(window) {
5218 return;
5219 }
5220
5221 self.update_hovered_link(
5222 position_map.point_for_position(mouse_position),
5223 &position_map.snapshot,
5224 modifiers,
5225 window,
5226 cx,
5227 )
5228 }
5229
5230 fn update_edit_prediction_preview(
5231 &mut self,
5232 modifiers: &Modifiers,
5233 window: &mut Window,
5234 cx: &mut Context<Self>,
5235 ) {
5236 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5237 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5238 return;
5239 };
5240
5241 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5242 if matches!(
5243 self.edit_prediction_preview,
5244 EditPredictionPreview::Inactive
5245 ) {
5246 self.edit_prediction_preview = EditPredictionPreview::Active {
5247 previous_scroll_position: None,
5248 };
5249
5250 self.update_visible_inline_completion(window, cx);
5251 cx.notify();
5252 }
5253 } else if let EditPredictionPreview::Active {
5254 previous_scroll_position,
5255 } = self.edit_prediction_preview
5256 {
5257 if let (Some(previous_scroll_position), Some(position_map)) =
5258 (previous_scroll_position, self.last_position_map.as_ref())
5259 {
5260 self.set_scroll_position(
5261 previous_scroll_position
5262 .scroll_position(&position_map.snapshot.display_snapshot),
5263 window,
5264 cx,
5265 );
5266 }
5267
5268 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5269 self.clear_row_highlights::<EditPredictionPreview>();
5270 self.update_visible_inline_completion(window, cx);
5271 cx.notify();
5272 }
5273 }
5274
5275 fn update_visible_inline_completion(
5276 &mut self,
5277 _window: &mut Window,
5278 cx: &mut Context<Self>,
5279 ) -> Option<()> {
5280 let selection = self.selections.newest_anchor();
5281 let cursor = selection.head();
5282 let multibuffer = self.buffer.read(cx).snapshot(cx);
5283 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5284 let excerpt_id = cursor.excerpt_id;
5285
5286 let show_in_menu = self.show_edit_predictions_in_menu();
5287 let completions_menu_has_precedence = !show_in_menu
5288 && (self.context_menu.borrow().is_some()
5289 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5290
5291 if completions_menu_has_precedence
5292 || !offset_selection.is_empty()
5293 || self
5294 .active_inline_completion
5295 .as_ref()
5296 .map_or(false, |completion| {
5297 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5298 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5299 !invalidation_range.contains(&offset_selection.head())
5300 })
5301 {
5302 self.discard_inline_completion(false, cx);
5303 return None;
5304 }
5305
5306 self.take_active_inline_completion(cx);
5307 let Some(provider) = self.edit_prediction_provider() else {
5308 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5309 return None;
5310 };
5311
5312 let (buffer, cursor_buffer_position) =
5313 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5314
5315 self.edit_prediction_settings =
5316 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5317
5318 self.edit_prediction_cursor_on_leading_whitespace =
5319 multibuffer.is_line_whitespace_upto(cursor);
5320
5321 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5322 let edits = inline_completion
5323 .edits
5324 .into_iter()
5325 .flat_map(|(range, new_text)| {
5326 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5327 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5328 Some((start..end, new_text))
5329 })
5330 .collect::<Vec<_>>();
5331 if edits.is_empty() {
5332 return None;
5333 }
5334
5335 let first_edit_start = edits.first().unwrap().0.start;
5336 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5337 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5338
5339 let last_edit_end = edits.last().unwrap().0.end;
5340 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5341 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5342
5343 let cursor_row = cursor.to_point(&multibuffer).row;
5344
5345 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5346
5347 let mut inlay_ids = Vec::new();
5348 let invalidation_row_range;
5349 let move_invalidation_row_range = if cursor_row < edit_start_row {
5350 Some(cursor_row..edit_end_row)
5351 } else if cursor_row > edit_end_row {
5352 Some(edit_start_row..cursor_row)
5353 } else {
5354 None
5355 };
5356 let is_move =
5357 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5358 let completion = if is_move {
5359 invalidation_row_range =
5360 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5361 let target = first_edit_start;
5362 InlineCompletion::Move { target, snapshot }
5363 } else {
5364 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5365 && !self.inline_completions_hidden_for_vim_mode;
5366
5367 if show_completions_in_buffer {
5368 if edits
5369 .iter()
5370 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5371 {
5372 let mut inlays = Vec::new();
5373 for (range, new_text) in &edits {
5374 let inlay = Inlay::inline_completion(
5375 post_inc(&mut self.next_inlay_id),
5376 range.start,
5377 new_text.as_str(),
5378 );
5379 inlay_ids.push(inlay.id);
5380 inlays.push(inlay);
5381 }
5382
5383 self.splice_inlays(&[], inlays, cx);
5384 } else {
5385 let background_color = cx.theme().status().deleted_background;
5386 self.highlight_text::<InlineCompletionHighlight>(
5387 edits.iter().map(|(range, _)| range.clone()).collect(),
5388 HighlightStyle {
5389 background_color: Some(background_color),
5390 ..Default::default()
5391 },
5392 cx,
5393 );
5394 }
5395 }
5396
5397 invalidation_row_range = edit_start_row..edit_end_row;
5398
5399 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5400 if provider.show_tab_accept_marker() {
5401 EditDisplayMode::TabAccept
5402 } else {
5403 EditDisplayMode::Inline
5404 }
5405 } else {
5406 EditDisplayMode::DiffPopover
5407 };
5408
5409 InlineCompletion::Edit {
5410 edits,
5411 edit_preview: inline_completion.edit_preview,
5412 display_mode,
5413 snapshot,
5414 }
5415 };
5416
5417 let invalidation_range = multibuffer
5418 .anchor_before(Point::new(invalidation_row_range.start, 0))
5419 ..multibuffer.anchor_after(Point::new(
5420 invalidation_row_range.end,
5421 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5422 ));
5423
5424 self.stale_inline_completion_in_menu = None;
5425 self.active_inline_completion = Some(InlineCompletionState {
5426 inlay_ids,
5427 completion,
5428 completion_id: inline_completion.id,
5429 invalidation_range,
5430 });
5431
5432 cx.notify();
5433
5434 Some(())
5435 }
5436
5437 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5438 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5439 }
5440
5441 fn render_code_actions_indicator(
5442 &self,
5443 _style: &EditorStyle,
5444 row: DisplayRow,
5445 is_active: bool,
5446 cx: &mut Context<Self>,
5447 ) -> Option<IconButton> {
5448 if self.available_code_actions.is_some() {
5449 Some(
5450 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5451 .shape(ui::IconButtonShape::Square)
5452 .icon_size(IconSize::XSmall)
5453 .icon_color(Color::Muted)
5454 .toggle_state(is_active)
5455 .tooltip({
5456 let focus_handle = self.focus_handle.clone();
5457 move |window, cx| {
5458 Tooltip::for_action_in(
5459 "Toggle Code Actions",
5460 &ToggleCodeActions {
5461 deployed_from_indicator: None,
5462 },
5463 &focus_handle,
5464 window,
5465 cx,
5466 )
5467 }
5468 })
5469 .on_click(cx.listener(move |editor, _e, window, cx| {
5470 window.focus(&editor.focus_handle(cx));
5471 editor.toggle_code_actions(
5472 &ToggleCodeActions {
5473 deployed_from_indicator: Some(row),
5474 },
5475 window,
5476 cx,
5477 );
5478 })),
5479 )
5480 } else {
5481 None
5482 }
5483 }
5484
5485 fn clear_tasks(&mut self) {
5486 self.tasks.clear()
5487 }
5488
5489 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5490 if self.tasks.insert(key, value).is_some() {
5491 // This case should hopefully be rare, but just in case...
5492 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5493 }
5494 }
5495
5496 fn build_tasks_context(
5497 project: &Entity<Project>,
5498 buffer: &Entity<Buffer>,
5499 buffer_row: u32,
5500 tasks: &Arc<RunnableTasks>,
5501 cx: &mut Context<Self>,
5502 ) -> Task<Option<task::TaskContext>> {
5503 let position = Point::new(buffer_row, tasks.column);
5504 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5505 let location = Location {
5506 buffer: buffer.clone(),
5507 range: range_start..range_start,
5508 };
5509 // Fill in the environmental variables from the tree-sitter captures
5510 let mut captured_task_variables = TaskVariables::default();
5511 for (capture_name, value) in tasks.extra_variables.clone() {
5512 captured_task_variables.insert(
5513 task::VariableName::Custom(capture_name.into()),
5514 value.clone(),
5515 );
5516 }
5517 project.update(cx, |project, cx| {
5518 project.task_store().update(cx, |task_store, cx| {
5519 task_store.task_context_for_location(captured_task_variables, location, cx)
5520 })
5521 })
5522 }
5523
5524 pub fn spawn_nearest_task(
5525 &mut self,
5526 action: &SpawnNearestTask,
5527 window: &mut Window,
5528 cx: &mut Context<Self>,
5529 ) {
5530 let Some((workspace, _)) = self.workspace.clone() else {
5531 return;
5532 };
5533 let Some(project) = self.project.clone() else {
5534 return;
5535 };
5536
5537 // Try to find a closest, enclosing node using tree-sitter that has a
5538 // task
5539 let Some((buffer, buffer_row, tasks)) = self
5540 .find_enclosing_node_task(cx)
5541 // Or find the task that's closest in row-distance.
5542 .or_else(|| self.find_closest_task(cx))
5543 else {
5544 return;
5545 };
5546
5547 let reveal_strategy = action.reveal;
5548 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5549 cx.spawn_in(window, |_, mut cx| async move {
5550 let context = task_context.await?;
5551 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5552
5553 let resolved = resolved_task.resolved.as_mut()?;
5554 resolved.reveal = reveal_strategy;
5555
5556 workspace
5557 .update(&mut cx, |workspace, cx| {
5558 workspace::tasks::schedule_resolved_task(
5559 workspace,
5560 task_source_kind,
5561 resolved_task,
5562 false,
5563 cx,
5564 );
5565 })
5566 .ok()
5567 })
5568 .detach();
5569 }
5570
5571 fn find_closest_task(
5572 &mut self,
5573 cx: &mut Context<Self>,
5574 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5575 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5576
5577 let ((buffer_id, row), tasks) = self
5578 .tasks
5579 .iter()
5580 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5581
5582 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5583 let tasks = Arc::new(tasks.to_owned());
5584 Some((buffer, *row, tasks))
5585 }
5586
5587 fn find_enclosing_node_task(
5588 &mut self,
5589 cx: &mut Context<Self>,
5590 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5591 let snapshot = self.buffer.read(cx).snapshot(cx);
5592 let offset = self.selections.newest::<usize>(cx).head();
5593 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5594 let buffer_id = excerpt.buffer().remote_id();
5595
5596 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5597 let mut cursor = layer.node().walk();
5598
5599 while cursor.goto_first_child_for_byte(offset).is_some() {
5600 if cursor.node().end_byte() == offset {
5601 cursor.goto_next_sibling();
5602 }
5603 }
5604
5605 // Ascend to the smallest ancestor that contains the range and has a task.
5606 loop {
5607 let node = cursor.node();
5608 let node_range = node.byte_range();
5609 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5610
5611 // Check if this node contains our offset
5612 if node_range.start <= offset && node_range.end >= offset {
5613 // If it contains offset, check for task
5614 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5615 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5616 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5617 }
5618 }
5619
5620 if !cursor.goto_parent() {
5621 break;
5622 }
5623 }
5624 None
5625 }
5626
5627 fn render_run_indicator(
5628 &self,
5629 _style: &EditorStyle,
5630 is_active: bool,
5631 row: DisplayRow,
5632 cx: &mut Context<Self>,
5633 ) -> IconButton {
5634 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5635 .shape(ui::IconButtonShape::Square)
5636 .icon_size(IconSize::XSmall)
5637 .icon_color(Color::Muted)
5638 .toggle_state(is_active)
5639 .on_click(cx.listener(move |editor, _e, window, cx| {
5640 window.focus(&editor.focus_handle(cx));
5641 editor.toggle_code_actions(
5642 &ToggleCodeActions {
5643 deployed_from_indicator: Some(row),
5644 },
5645 window,
5646 cx,
5647 );
5648 }))
5649 }
5650
5651 pub fn context_menu_visible(&self) -> bool {
5652 !self.edit_prediction_preview_is_active()
5653 && self
5654 .context_menu
5655 .borrow()
5656 .as_ref()
5657 .map_or(false, |menu| menu.visible())
5658 }
5659
5660 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5661 self.context_menu
5662 .borrow()
5663 .as_ref()
5664 .map(|menu| menu.origin())
5665 }
5666
5667 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5668 px(30.)
5669 }
5670
5671 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5672 if self.read_only(cx) {
5673 cx.theme().players().read_only()
5674 } else {
5675 self.style.as_ref().unwrap().local_player
5676 }
5677 }
5678
5679 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5680 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5681 let accept_keystroke = accept_binding.keystroke()?;
5682
5683 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5684
5685 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5686 Color::Accent
5687 } else {
5688 Color::Muted
5689 };
5690
5691 h_flex()
5692 .px_0p5()
5693 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5694 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5695 .text_size(TextSize::XSmall.rems(cx))
5696 .child(h_flex().children(ui::render_modifiers(
5697 &accept_keystroke.modifiers,
5698 PlatformStyle::platform(),
5699 Some(modifiers_color),
5700 Some(IconSize::XSmall.rems().into()),
5701 true,
5702 )))
5703 .when(is_platform_style_mac, |parent| {
5704 parent.child(accept_keystroke.key.clone())
5705 })
5706 .when(!is_platform_style_mac, |parent| {
5707 parent.child(
5708 Key::new(
5709 util::capitalize(&accept_keystroke.key),
5710 Some(Color::Default),
5711 )
5712 .size(Some(IconSize::XSmall.rems().into())),
5713 )
5714 })
5715 .into()
5716 }
5717
5718 fn render_edit_prediction_line_popover(
5719 &self,
5720 label: impl Into<SharedString>,
5721 icon: Option<IconName>,
5722 window: &mut Window,
5723 cx: &App,
5724 ) -> Option<Div> {
5725 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5726
5727 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5728
5729 let result = h_flex()
5730 .gap_1()
5731 .border_1()
5732 .rounded_lg()
5733 .shadow_sm()
5734 .bg(bg_color)
5735 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5736 .py_0p5()
5737 .pl_1()
5738 .pr(padding_right)
5739 .children(self.render_edit_prediction_accept_keybind(window, cx))
5740 .child(Label::new(label).size(LabelSize::Small))
5741 .when_some(icon, |element, icon| {
5742 element.child(
5743 div()
5744 .mt(px(1.5))
5745 .child(Icon::new(icon).size(IconSize::Small)),
5746 )
5747 });
5748
5749 Some(result)
5750 }
5751
5752 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5753 let accent_color = cx.theme().colors().text_accent;
5754 let editor_bg_color = cx.theme().colors().editor_background;
5755 editor_bg_color.blend(accent_color.opacity(0.1))
5756 }
5757
5758 #[allow(clippy::too_many_arguments)]
5759 fn render_edit_prediction_cursor_popover(
5760 &self,
5761 min_width: Pixels,
5762 max_width: Pixels,
5763 cursor_point: Point,
5764 style: &EditorStyle,
5765 accept_keystroke: &gpui::Keystroke,
5766 _window: &Window,
5767 cx: &mut Context<Editor>,
5768 ) -> Option<AnyElement> {
5769 let provider = self.edit_prediction_provider.as_ref()?;
5770
5771 if provider.provider.needs_terms_acceptance(cx) {
5772 return Some(
5773 h_flex()
5774 .min_w(min_width)
5775 .flex_1()
5776 .px_2()
5777 .py_1()
5778 .gap_3()
5779 .elevation_2(cx)
5780 .hover(|style| style.bg(cx.theme().colors().element_hover))
5781 .id("accept-terms")
5782 .cursor_pointer()
5783 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5784 .on_click(cx.listener(|this, _event, window, cx| {
5785 cx.stop_propagation();
5786 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5787 window.dispatch_action(
5788 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5789 cx,
5790 );
5791 }))
5792 .child(
5793 h_flex()
5794 .flex_1()
5795 .gap_2()
5796 .child(Icon::new(IconName::ZedPredict))
5797 .child(Label::new("Accept Terms of Service"))
5798 .child(div().w_full())
5799 .child(
5800 Icon::new(IconName::ArrowUpRight)
5801 .color(Color::Muted)
5802 .size(IconSize::Small),
5803 )
5804 .into_any_element(),
5805 )
5806 .into_any(),
5807 );
5808 }
5809
5810 let is_refreshing = provider.provider.is_refreshing(cx);
5811
5812 fn pending_completion_container() -> Div {
5813 h_flex()
5814 .h_full()
5815 .flex_1()
5816 .gap_2()
5817 .child(Icon::new(IconName::ZedPredict))
5818 }
5819
5820 let completion = match &self.active_inline_completion {
5821 Some(completion) => match &completion.completion {
5822 InlineCompletion::Move {
5823 target, snapshot, ..
5824 } if !self.has_visible_completions_menu() => {
5825 use text::ToPoint as _;
5826
5827 return Some(
5828 h_flex()
5829 .px_2()
5830 .py_1()
5831 .elevation_2(cx)
5832 .border_color(cx.theme().colors().border)
5833 .rounded_tl(px(0.))
5834 .gap_2()
5835 .child(
5836 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5837 Icon::new(IconName::ZedPredictDown)
5838 } else {
5839 Icon::new(IconName::ZedPredictUp)
5840 },
5841 )
5842 .child(Label::new("Hold").size(LabelSize::Small))
5843 .child(h_flex().children(ui::render_modifiers(
5844 &accept_keystroke.modifiers,
5845 PlatformStyle::platform(),
5846 Some(Color::Default),
5847 Some(IconSize::Small.rems().into()),
5848 false,
5849 )))
5850 .into_any(),
5851 );
5852 }
5853 _ => self.render_edit_prediction_cursor_popover_preview(
5854 completion,
5855 cursor_point,
5856 style,
5857 cx,
5858 )?,
5859 },
5860
5861 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5862 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5863 stale_completion,
5864 cursor_point,
5865 style,
5866 cx,
5867 )?,
5868
5869 None => {
5870 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5871 }
5872 },
5873
5874 None => pending_completion_container().child(Label::new("No Prediction")),
5875 };
5876
5877 let completion = if is_refreshing {
5878 completion
5879 .with_animation(
5880 "loading-completion",
5881 Animation::new(Duration::from_secs(2))
5882 .repeat()
5883 .with_easing(pulsating_between(0.4, 0.8)),
5884 |label, delta| label.opacity(delta),
5885 )
5886 .into_any_element()
5887 } else {
5888 completion.into_any_element()
5889 };
5890
5891 let has_completion = self.active_inline_completion.is_some();
5892
5893 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5894 Some(
5895 h_flex()
5896 .min_w(min_width)
5897 .max_w(max_width)
5898 .flex_1()
5899 .elevation_2(cx)
5900 .border_color(cx.theme().colors().border)
5901 .child(
5902 div()
5903 .flex_1()
5904 .py_1()
5905 .px_2()
5906 .overflow_hidden()
5907 .child(completion),
5908 )
5909 .child(
5910 h_flex()
5911 .h_full()
5912 .border_l_1()
5913 .rounded_r_lg()
5914 .border_color(cx.theme().colors().border)
5915 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5916 .gap_1()
5917 .py_1()
5918 .px_2()
5919 .child(
5920 h_flex()
5921 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5922 .when(is_platform_style_mac, |parent| parent.gap_1())
5923 .child(h_flex().children(ui::render_modifiers(
5924 &accept_keystroke.modifiers,
5925 PlatformStyle::platform(),
5926 Some(if !has_completion {
5927 Color::Muted
5928 } else {
5929 Color::Default
5930 }),
5931 None,
5932 false,
5933 ))),
5934 )
5935 .child(Label::new("Preview").into_any_element())
5936 .opacity(if has_completion { 1.0 } else { 0.4 }),
5937 )
5938 .into_any(),
5939 )
5940 }
5941
5942 fn render_edit_prediction_cursor_popover_preview(
5943 &self,
5944 completion: &InlineCompletionState,
5945 cursor_point: Point,
5946 style: &EditorStyle,
5947 cx: &mut Context<Editor>,
5948 ) -> Option<Div> {
5949 use text::ToPoint as _;
5950
5951 fn render_relative_row_jump(
5952 prefix: impl Into<String>,
5953 current_row: u32,
5954 target_row: u32,
5955 ) -> Div {
5956 let (row_diff, arrow) = if target_row < current_row {
5957 (current_row - target_row, IconName::ArrowUp)
5958 } else {
5959 (target_row - current_row, IconName::ArrowDown)
5960 };
5961
5962 h_flex()
5963 .child(
5964 Label::new(format!("{}{}", prefix.into(), row_diff))
5965 .color(Color::Muted)
5966 .size(LabelSize::Small),
5967 )
5968 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5969 }
5970
5971 match &completion.completion {
5972 InlineCompletion::Move {
5973 target, snapshot, ..
5974 } => Some(
5975 h_flex()
5976 .px_2()
5977 .gap_2()
5978 .flex_1()
5979 .child(
5980 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5981 Icon::new(IconName::ZedPredictDown)
5982 } else {
5983 Icon::new(IconName::ZedPredictUp)
5984 },
5985 )
5986 .child(Label::new("Jump to Edit")),
5987 ),
5988
5989 InlineCompletion::Edit {
5990 edits,
5991 edit_preview,
5992 snapshot,
5993 display_mode: _,
5994 } => {
5995 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5996
5997 let highlighted_edits = crate::inline_completion_edit_text(
5998 &snapshot,
5999 &edits,
6000 edit_preview.as_ref()?,
6001 true,
6002 cx,
6003 );
6004
6005 let len_total = highlighted_edits.text.len();
6006 let first_line = &highlighted_edits.text
6007 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
6008 let first_line_len = first_line.len();
6009
6010 let first_highlight_start = highlighted_edits
6011 .highlights
6012 .first()
6013 .map_or(0, |(range, _)| range.start);
6014 let drop_prefix_len = first_line
6015 .char_indices()
6016 .find(|(_, c)| !c.is_whitespace())
6017 .map_or(first_highlight_start, |(ix, _)| {
6018 ix.min(first_highlight_start)
6019 });
6020
6021 let preview_text = &first_line[drop_prefix_len..];
6022 let preview_len = preview_text.len();
6023 let highlights = highlighted_edits
6024 .highlights
6025 .into_iter()
6026 .take_until(|(range, _)| range.start > first_line_len)
6027 .map(|(range, style)| {
6028 (
6029 range.start - drop_prefix_len
6030 ..(range.end - drop_prefix_len).min(preview_len),
6031 style,
6032 )
6033 });
6034
6035 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
6036 .with_highlights(&style.text, highlights);
6037
6038 let preview = h_flex()
6039 .gap_1()
6040 .min_w_16()
6041 .child(styled_text)
6042 .when(len_total > first_line_len, |parent| parent.child("…"));
6043
6044 let left = if first_edit_row != cursor_point.row {
6045 render_relative_row_jump("", cursor_point.row, first_edit_row)
6046 .into_any_element()
6047 } else {
6048 Icon::new(IconName::ZedPredict).into_any_element()
6049 };
6050
6051 Some(
6052 h_flex()
6053 .h_full()
6054 .flex_1()
6055 .gap_2()
6056 .pr_1()
6057 .overflow_x_hidden()
6058 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6059 .child(left)
6060 .child(preview),
6061 )
6062 }
6063 }
6064 }
6065
6066 fn render_context_menu(
6067 &self,
6068 style: &EditorStyle,
6069 max_height_in_lines: u32,
6070 y_flipped: bool,
6071 window: &mut Window,
6072 cx: &mut Context<Editor>,
6073 ) -> Option<AnyElement> {
6074 let menu = self.context_menu.borrow();
6075 let menu = menu.as_ref()?;
6076 if !menu.visible() {
6077 return None;
6078 };
6079 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6080 }
6081
6082 fn render_context_menu_aside(
6083 &self,
6084 style: &EditorStyle,
6085 max_size: Size<Pixels>,
6086 cx: &mut Context<Editor>,
6087 ) -> Option<AnyElement> {
6088 self.context_menu.borrow().as_ref().and_then(|menu| {
6089 if menu.visible() {
6090 menu.render_aside(
6091 style,
6092 max_size,
6093 self.workspace.as_ref().map(|(w, _)| w.clone()),
6094 cx,
6095 )
6096 } else {
6097 None
6098 }
6099 })
6100 }
6101
6102 fn hide_context_menu(
6103 &mut self,
6104 window: &mut Window,
6105 cx: &mut Context<Self>,
6106 ) -> Option<CodeContextMenu> {
6107 cx.notify();
6108 self.completion_tasks.clear();
6109 let context_menu = self.context_menu.borrow_mut().take();
6110 self.stale_inline_completion_in_menu.take();
6111 self.update_visible_inline_completion(window, cx);
6112 context_menu
6113 }
6114
6115 fn show_snippet_choices(
6116 &mut self,
6117 choices: &Vec<String>,
6118 selection: Range<Anchor>,
6119 cx: &mut Context<Self>,
6120 ) {
6121 if selection.start.buffer_id.is_none() {
6122 return;
6123 }
6124 let buffer_id = selection.start.buffer_id.unwrap();
6125 let buffer = self.buffer().read(cx).buffer(buffer_id);
6126 let id = post_inc(&mut self.next_completion_id);
6127
6128 if let Some(buffer) = buffer {
6129 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6130 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6131 ));
6132 }
6133 }
6134
6135 pub fn insert_snippet(
6136 &mut self,
6137 insertion_ranges: &[Range<usize>],
6138 snippet: Snippet,
6139 window: &mut Window,
6140 cx: &mut Context<Self>,
6141 ) -> Result<()> {
6142 struct Tabstop<T> {
6143 is_end_tabstop: bool,
6144 ranges: Vec<Range<T>>,
6145 choices: Option<Vec<String>>,
6146 }
6147
6148 let tabstops = self.buffer.update(cx, |buffer, cx| {
6149 let snippet_text: Arc<str> = snippet.text.clone().into();
6150 buffer.edit(
6151 insertion_ranges
6152 .iter()
6153 .cloned()
6154 .map(|range| (range, snippet_text.clone())),
6155 Some(AutoindentMode::EachLine),
6156 cx,
6157 );
6158
6159 let snapshot = &*buffer.read(cx);
6160 let snippet = &snippet;
6161 snippet
6162 .tabstops
6163 .iter()
6164 .map(|tabstop| {
6165 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6166 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6167 });
6168 let mut tabstop_ranges = tabstop
6169 .ranges
6170 .iter()
6171 .flat_map(|tabstop_range| {
6172 let mut delta = 0_isize;
6173 insertion_ranges.iter().map(move |insertion_range| {
6174 let insertion_start = insertion_range.start as isize + delta;
6175 delta +=
6176 snippet.text.len() as isize - insertion_range.len() as isize;
6177
6178 let start = ((insertion_start + tabstop_range.start) as usize)
6179 .min(snapshot.len());
6180 let end = ((insertion_start + tabstop_range.end) as usize)
6181 .min(snapshot.len());
6182 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6183 })
6184 })
6185 .collect::<Vec<_>>();
6186 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6187
6188 Tabstop {
6189 is_end_tabstop,
6190 ranges: tabstop_ranges,
6191 choices: tabstop.choices.clone(),
6192 }
6193 })
6194 .collect::<Vec<_>>()
6195 });
6196 if let Some(tabstop) = tabstops.first() {
6197 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6198 s.select_ranges(tabstop.ranges.iter().cloned());
6199 });
6200
6201 if let Some(choices) = &tabstop.choices {
6202 if let Some(selection) = tabstop.ranges.first() {
6203 self.show_snippet_choices(choices, selection.clone(), cx)
6204 }
6205 }
6206
6207 // If we're already at the last tabstop and it's at the end of the snippet,
6208 // we're done, we don't need to keep the state around.
6209 if !tabstop.is_end_tabstop {
6210 let choices = tabstops
6211 .iter()
6212 .map(|tabstop| tabstop.choices.clone())
6213 .collect();
6214
6215 let ranges = tabstops
6216 .into_iter()
6217 .map(|tabstop| tabstop.ranges)
6218 .collect::<Vec<_>>();
6219
6220 self.snippet_stack.push(SnippetState {
6221 active_index: 0,
6222 ranges,
6223 choices,
6224 });
6225 }
6226
6227 // Check whether the just-entered snippet ends with an auto-closable bracket.
6228 if self.autoclose_regions.is_empty() {
6229 let snapshot = self.buffer.read(cx).snapshot(cx);
6230 for selection in &mut self.selections.all::<Point>(cx) {
6231 let selection_head = selection.head();
6232 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6233 continue;
6234 };
6235
6236 let mut bracket_pair = None;
6237 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6238 let prev_chars = snapshot
6239 .reversed_chars_at(selection_head)
6240 .collect::<String>();
6241 for (pair, enabled) in scope.brackets() {
6242 if enabled
6243 && pair.close
6244 && prev_chars.starts_with(pair.start.as_str())
6245 && next_chars.starts_with(pair.end.as_str())
6246 {
6247 bracket_pair = Some(pair.clone());
6248 break;
6249 }
6250 }
6251 if let Some(pair) = bracket_pair {
6252 let start = snapshot.anchor_after(selection_head);
6253 let end = snapshot.anchor_after(selection_head);
6254 self.autoclose_regions.push(AutocloseRegion {
6255 selection_id: selection.id,
6256 range: start..end,
6257 pair,
6258 });
6259 }
6260 }
6261 }
6262 }
6263 Ok(())
6264 }
6265
6266 pub fn move_to_next_snippet_tabstop(
6267 &mut self,
6268 window: &mut Window,
6269 cx: &mut Context<Self>,
6270 ) -> bool {
6271 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6272 }
6273
6274 pub fn move_to_prev_snippet_tabstop(
6275 &mut self,
6276 window: &mut Window,
6277 cx: &mut Context<Self>,
6278 ) -> bool {
6279 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6280 }
6281
6282 pub fn move_to_snippet_tabstop(
6283 &mut self,
6284 bias: Bias,
6285 window: &mut Window,
6286 cx: &mut Context<Self>,
6287 ) -> bool {
6288 if let Some(mut snippet) = self.snippet_stack.pop() {
6289 match bias {
6290 Bias::Left => {
6291 if snippet.active_index > 0 {
6292 snippet.active_index -= 1;
6293 } else {
6294 self.snippet_stack.push(snippet);
6295 return false;
6296 }
6297 }
6298 Bias::Right => {
6299 if snippet.active_index + 1 < snippet.ranges.len() {
6300 snippet.active_index += 1;
6301 } else {
6302 self.snippet_stack.push(snippet);
6303 return false;
6304 }
6305 }
6306 }
6307 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6309 s.select_anchor_ranges(current_ranges.iter().cloned())
6310 });
6311
6312 if let Some(choices) = &snippet.choices[snippet.active_index] {
6313 if let Some(selection) = current_ranges.first() {
6314 self.show_snippet_choices(&choices, selection.clone(), cx);
6315 }
6316 }
6317
6318 // If snippet state is not at the last tabstop, push it back on the stack
6319 if snippet.active_index + 1 < snippet.ranges.len() {
6320 self.snippet_stack.push(snippet);
6321 }
6322 return true;
6323 }
6324 }
6325
6326 false
6327 }
6328
6329 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6330 self.transact(window, cx, |this, window, cx| {
6331 this.select_all(&SelectAll, window, cx);
6332 this.insert("", window, cx);
6333 });
6334 }
6335
6336 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6337 self.transact(window, cx, |this, window, cx| {
6338 this.select_autoclose_pair(window, cx);
6339 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6340 if !this.linked_edit_ranges.is_empty() {
6341 let selections = this.selections.all::<MultiBufferPoint>(cx);
6342 let snapshot = this.buffer.read(cx).snapshot(cx);
6343
6344 for selection in selections.iter() {
6345 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6346 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6347 if selection_start.buffer_id != selection_end.buffer_id {
6348 continue;
6349 }
6350 if let Some(ranges) =
6351 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6352 {
6353 for (buffer, entries) in ranges {
6354 linked_ranges.entry(buffer).or_default().extend(entries);
6355 }
6356 }
6357 }
6358 }
6359
6360 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6361 if !this.selections.line_mode {
6362 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6363 for selection in &mut selections {
6364 if selection.is_empty() {
6365 let old_head = selection.head();
6366 let mut new_head =
6367 movement::left(&display_map, old_head.to_display_point(&display_map))
6368 .to_point(&display_map);
6369 if let Some((buffer, line_buffer_range)) = display_map
6370 .buffer_snapshot
6371 .buffer_line_for_row(MultiBufferRow(old_head.row))
6372 {
6373 let indent_size =
6374 buffer.indent_size_for_line(line_buffer_range.start.row);
6375 let indent_len = match indent_size.kind {
6376 IndentKind::Space => {
6377 buffer.settings_at(line_buffer_range.start, cx).tab_size
6378 }
6379 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6380 };
6381 if old_head.column <= indent_size.len && old_head.column > 0 {
6382 let indent_len = indent_len.get();
6383 new_head = cmp::min(
6384 new_head,
6385 MultiBufferPoint::new(
6386 old_head.row,
6387 ((old_head.column - 1) / indent_len) * indent_len,
6388 ),
6389 );
6390 }
6391 }
6392
6393 selection.set_head(new_head, SelectionGoal::None);
6394 }
6395 }
6396 }
6397
6398 this.signature_help_state.set_backspace_pressed(true);
6399 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6400 s.select(selections)
6401 });
6402 this.insert("", window, cx);
6403 let empty_str: Arc<str> = Arc::from("");
6404 for (buffer, edits) in linked_ranges {
6405 let snapshot = buffer.read(cx).snapshot();
6406 use text::ToPoint as TP;
6407
6408 let edits = edits
6409 .into_iter()
6410 .map(|range| {
6411 let end_point = TP::to_point(&range.end, &snapshot);
6412 let mut start_point = TP::to_point(&range.start, &snapshot);
6413
6414 if end_point == start_point {
6415 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6416 .saturating_sub(1);
6417 start_point =
6418 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6419 };
6420
6421 (start_point..end_point, empty_str.clone())
6422 })
6423 .sorted_by_key(|(range, _)| range.start)
6424 .collect::<Vec<_>>();
6425 buffer.update(cx, |this, cx| {
6426 this.edit(edits, None, cx);
6427 })
6428 }
6429 this.refresh_inline_completion(true, false, window, cx);
6430 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6431 });
6432 }
6433
6434 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6435 self.transact(window, cx, |this, window, cx| {
6436 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6437 let line_mode = s.line_mode;
6438 s.move_with(|map, selection| {
6439 if selection.is_empty() && !line_mode {
6440 let cursor = movement::right(map, selection.head());
6441 selection.end = cursor;
6442 selection.reversed = true;
6443 selection.goal = SelectionGoal::None;
6444 }
6445 })
6446 });
6447 this.insert("", window, cx);
6448 this.refresh_inline_completion(true, false, window, cx);
6449 });
6450 }
6451
6452 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6453 if self.move_to_prev_snippet_tabstop(window, cx) {
6454 return;
6455 }
6456
6457 self.outdent(&Outdent, window, cx);
6458 }
6459
6460 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6461 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6462 return;
6463 }
6464
6465 let mut selections = self.selections.all_adjusted(cx);
6466 let buffer = self.buffer.read(cx);
6467 let snapshot = buffer.snapshot(cx);
6468 let rows_iter = selections.iter().map(|s| s.head().row);
6469 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6470
6471 let mut edits = Vec::new();
6472 let mut prev_edited_row = 0;
6473 let mut row_delta = 0;
6474 for selection in &mut selections {
6475 if selection.start.row != prev_edited_row {
6476 row_delta = 0;
6477 }
6478 prev_edited_row = selection.end.row;
6479
6480 // If the selection is non-empty, then increase the indentation of the selected lines.
6481 if !selection.is_empty() {
6482 row_delta =
6483 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6484 continue;
6485 }
6486
6487 // If the selection is empty and the cursor is in the leading whitespace before the
6488 // suggested indentation, then auto-indent the line.
6489 let cursor = selection.head();
6490 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6491 if let Some(suggested_indent) =
6492 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6493 {
6494 if cursor.column < suggested_indent.len
6495 && cursor.column <= current_indent.len
6496 && current_indent.len <= suggested_indent.len
6497 {
6498 selection.start = Point::new(cursor.row, suggested_indent.len);
6499 selection.end = selection.start;
6500 if row_delta == 0 {
6501 edits.extend(Buffer::edit_for_indent_size_adjustment(
6502 cursor.row,
6503 current_indent,
6504 suggested_indent,
6505 ));
6506 row_delta = suggested_indent.len - current_indent.len;
6507 }
6508 continue;
6509 }
6510 }
6511
6512 // Otherwise, insert a hard or soft tab.
6513 let settings = buffer.settings_at(cursor, cx);
6514 let tab_size = if settings.hard_tabs {
6515 IndentSize::tab()
6516 } else {
6517 let tab_size = settings.tab_size.get();
6518 let char_column = snapshot
6519 .text_for_range(Point::new(cursor.row, 0)..cursor)
6520 .flat_map(str::chars)
6521 .count()
6522 + row_delta as usize;
6523 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6524 IndentSize::spaces(chars_to_next_tab_stop)
6525 };
6526 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6527 selection.end = selection.start;
6528 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6529 row_delta += tab_size.len;
6530 }
6531
6532 self.transact(window, cx, |this, window, cx| {
6533 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6534 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6535 s.select(selections)
6536 });
6537 this.refresh_inline_completion(true, false, window, cx);
6538 });
6539 }
6540
6541 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6542 if self.read_only(cx) {
6543 return;
6544 }
6545 let mut selections = self.selections.all::<Point>(cx);
6546 let mut prev_edited_row = 0;
6547 let mut row_delta = 0;
6548 let mut edits = Vec::new();
6549 let buffer = self.buffer.read(cx);
6550 let snapshot = buffer.snapshot(cx);
6551 for selection in &mut selections {
6552 if selection.start.row != prev_edited_row {
6553 row_delta = 0;
6554 }
6555 prev_edited_row = selection.end.row;
6556
6557 row_delta =
6558 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6559 }
6560
6561 self.transact(window, cx, |this, window, cx| {
6562 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6563 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6564 s.select(selections)
6565 });
6566 });
6567 }
6568
6569 fn indent_selection(
6570 buffer: &MultiBuffer,
6571 snapshot: &MultiBufferSnapshot,
6572 selection: &mut Selection<Point>,
6573 edits: &mut Vec<(Range<Point>, String)>,
6574 delta_for_start_row: u32,
6575 cx: &App,
6576 ) -> u32 {
6577 let settings = buffer.settings_at(selection.start, cx);
6578 let tab_size = settings.tab_size.get();
6579 let indent_kind = if settings.hard_tabs {
6580 IndentKind::Tab
6581 } else {
6582 IndentKind::Space
6583 };
6584 let mut start_row = selection.start.row;
6585 let mut end_row = selection.end.row + 1;
6586
6587 // If a selection ends at the beginning of a line, don't indent
6588 // that last line.
6589 if selection.end.column == 0 && selection.end.row > selection.start.row {
6590 end_row -= 1;
6591 }
6592
6593 // Avoid re-indenting a row that has already been indented by a
6594 // previous selection, but still update this selection's column
6595 // to reflect that indentation.
6596 if delta_for_start_row > 0 {
6597 start_row += 1;
6598 selection.start.column += delta_for_start_row;
6599 if selection.end.row == selection.start.row {
6600 selection.end.column += delta_for_start_row;
6601 }
6602 }
6603
6604 let mut delta_for_end_row = 0;
6605 let has_multiple_rows = start_row + 1 != end_row;
6606 for row in start_row..end_row {
6607 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6608 let indent_delta = match (current_indent.kind, indent_kind) {
6609 (IndentKind::Space, IndentKind::Space) => {
6610 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6611 IndentSize::spaces(columns_to_next_tab_stop)
6612 }
6613 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6614 (_, IndentKind::Tab) => IndentSize::tab(),
6615 };
6616
6617 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6618 0
6619 } else {
6620 selection.start.column
6621 };
6622 let row_start = Point::new(row, start);
6623 edits.push((
6624 row_start..row_start,
6625 indent_delta.chars().collect::<String>(),
6626 ));
6627
6628 // Update this selection's endpoints to reflect the indentation.
6629 if row == selection.start.row {
6630 selection.start.column += indent_delta.len;
6631 }
6632 if row == selection.end.row {
6633 selection.end.column += indent_delta.len;
6634 delta_for_end_row = indent_delta.len;
6635 }
6636 }
6637
6638 if selection.start.row == selection.end.row {
6639 delta_for_start_row + delta_for_end_row
6640 } else {
6641 delta_for_end_row
6642 }
6643 }
6644
6645 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6646 if self.read_only(cx) {
6647 return;
6648 }
6649 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6650 let selections = self.selections.all::<Point>(cx);
6651 let mut deletion_ranges = Vec::new();
6652 let mut last_outdent = None;
6653 {
6654 let buffer = self.buffer.read(cx);
6655 let snapshot = buffer.snapshot(cx);
6656 for selection in &selections {
6657 let settings = buffer.settings_at(selection.start, cx);
6658 let tab_size = settings.tab_size.get();
6659 let mut rows = selection.spanned_rows(false, &display_map);
6660
6661 // Avoid re-outdenting a row that has already been outdented by a
6662 // previous selection.
6663 if let Some(last_row) = last_outdent {
6664 if last_row == rows.start {
6665 rows.start = rows.start.next_row();
6666 }
6667 }
6668 let has_multiple_rows = rows.len() > 1;
6669 for row in rows.iter_rows() {
6670 let indent_size = snapshot.indent_size_for_line(row);
6671 if indent_size.len > 0 {
6672 let deletion_len = match indent_size.kind {
6673 IndentKind::Space => {
6674 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6675 if columns_to_prev_tab_stop == 0 {
6676 tab_size
6677 } else {
6678 columns_to_prev_tab_stop
6679 }
6680 }
6681 IndentKind::Tab => 1,
6682 };
6683 let start = if has_multiple_rows
6684 || deletion_len > selection.start.column
6685 || indent_size.len < selection.start.column
6686 {
6687 0
6688 } else {
6689 selection.start.column - deletion_len
6690 };
6691 deletion_ranges.push(
6692 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6693 );
6694 last_outdent = Some(row);
6695 }
6696 }
6697 }
6698 }
6699
6700 self.transact(window, cx, |this, window, cx| {
6701 this.buffer.update(cx, |buffer, cx| {
6702 let empty_str: Arc<str> = Arc::default();
6703 buffer.edit(
6704 deletion_ranges
6705 .into_iter()
6706 .map(|range| (range, empty_str.clone())),
6707 None,
6708 cx,
6709 );
6710 });
6711 let selections = this.selections.all::<usize>(cx);
6712 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6713 s.select(selections)
6714 });
6715 });
6716 }
6717
6718 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6719 if self.read_only(cx) {
6720 return;
6721 }
6722 let selections = self
6723 .selections
6724 .all::<usize>(cx)
6725 .into_iter()
6726 .map(|s| s.range());
6727
6728 self.transact(window, cx, |this, window, cx| {
6729 this.buffer.update(cx, |buffer, cx| {
6730 buffer.autoindent_ranges(selections, cx);
6731 });
6732 let selections = this.selections.all::<usize>(cx);
6733 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6734 s.select(selections)
6735 });
6736 });
6737 }
6738
6739 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6740 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6741 let selections = self.selections.all::<Point>(cx);
6742
6743 let mut new_cursors = Vec::new();
6744 let mut edit_ranges = Vec::new();
6745 let mut selections = selections.iter().peekable();
6746 while let Some(selection) = selections.next() {
6747 let mut rows = selection.spanned_rows(false, &display_map);
6748 let goal_display_column = selection.head().to_display_point(&display_map).column();
6749
6750 // Accumulate contiguous regions of rows that we want to delete.
6751 while let Some(next_selection) = selections.peek() {
6752 let next_rows = next_selection.spanned_rows(false, &display_map);
6753 if next_rows.start <= rows.end {
6754 rows.end = next_rows.end;
6755 selections.next().unwrap();
6756 } else {
6757 break;
6758 }
6759 }
6760
6761 let buffer = &display_map.buffer_snapshot;
6762 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6763 let edit_end;
6764 let cursor_buffer_row;
6765 if buffer.max_point().row >= rows.end.0 {
6766 // If there's a line after the range, delete the \n from the end of the row range
6767 // and position the cursor on the next line.
6768 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6769 cursor_buffer_row = rows.end;
6770 } else {
6771 // If there isn't a line after the range, delete the \n from the line before the
6772 // start of the row range and position the cursor there.
6773 edit_start = edit_start.saturating_sub(1);
6774 edit_end = buffer.len();
6775 cursor_buffer_row = rows.start.previous_row();
6776 }
6777
6778 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6779 *cursor.column_mut() =
6780 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6781
6782 new_cursors.push((
6783 selection.id,
6784 buffer.anchor_after(cursor.to_point(&display_map)),
6785 ));
6786 edit_ranges.push(edit_start..edit_end);
6787 }
6788
6789 self.transact(window, cx, |this, window, cx| {
6790 let buffer = this.buffer.update(cx, |buffer, cx| {
6791 let empty_str: Arc<str> = Arc::default();
6792 buffer.edit(
6793 edit_ranges
6794 .into_iter()
6795 .map(|range| (range, empty_str.clone())),
6796 None,
6797 cx,
6798 );
6799 buffer.snapshot(cx)
6800 });
6801 let new_selections = new_cursors
6802 .into_iter()
6803 .map(|(id, cursor)| {
6804 let cursor = cursor.to_point(&buffer);
6805 Selection {
6806 id,
6807 start: cursor,
6808 end: cursor,
6809 reversed: false,
6810 goal: SelectionGoal::None,
6811 }
6812 })
6813 .collect();
6814
6815 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6816 s.select(new_selections);
6817 });
6818 });
6819 }
6820
6821 pub fn join_lines_impl(
6822 &mut self,
6823 insert_whitespace: bool,
6824 window: &mut Window,
6825 cx: &mut Context<Self>,
6826 ) {
6827 if self.read_only(cx) {
6828 return;
6829 }
6830 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6831 for selection in self.selections.all::<Point>(cx) {
6832 let start = MultiBufferRow(selection.start.row);
6833 // Treat single line selections as if they include the next line. Otherwise this action
6834 // would do nothing for single line selections individual cursors.
6835 let end = if selection.start.row == selection.end.row {
6836 MultiBufferRow(selection.start.row + 1)
6837 } else {
6838 MultiBufferRow(selection.end.row)
6839 };
6840
6841 if let Some(last_row_range) = row_ranges.last_mut() {
6842 if start <= last_row_range.end {
6843 last_row_range.end = end;
6844 continue;
6845 }
6846 }
6847 row_ranges.push(start..end);
6848 }
6849
6850 let snapshot = self.buffer.read(cx).snapshot(cx);
6851 let mut cursor_positions = Vec::new();
6852 for row_range in &row_ranges {
6853 let anchor = snapshot.anchor_before(Point::new(
6854 row_range.end.previous_row().0,
6855 snapshot.line_len(row_range.end.previous_row()),
6856 ));
6857 cursor_positions.push(anchor..anchor);
6858 }
6859
6860 self.transact(window, cx, |this, window, cx| {
6861 for row_range in row_ranges.into_iter().rev() {
6862 for row in row_range.iter_rows().rev() {
6863 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6864 let next_line_row = row.next_row();
6865 let indent = snapshot.indent_size_for_line(next_line_row);
6866 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6867
6868 let replace =
6869 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6870 " "
6871 } else {
6872 ""
6873 };
6874
6875 this.buffer.update(cx, |buffer, cx| {
6876 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6877 });
6878 }
6879 }
6880
6881 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6882 s.select_anchor_ranges(cursor_positions)
6883 });
6884 });
6885 }
6886
6887 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6888 self.join_lines_impl(true, window, cx);
6889 }
6890
6891 pub fn sort_lines_case_sensitive(
6892 &mut self,
6893 _: &SortLinesCaseSensitive,
6894 window: &mut Window,
6895 cx: &mut Context<Self>,
6896 ) {
6897 self.manipulate_lines(window, cx, |lines| lines.sort())
6898 }
6899
6900 pub fn sort_lines_case_insensitive(
6901 &mut self,
6902 _: &SortLinesCaseInsensitive,
6903 window: &mut Window,
6904 cx: &mut Context<Self>,
6905 ) {
6906 self.manipulate_lines(window, cx, |lines| {
6907 lines.sort_by_key(|line| line.to_lowercase())
6908 })
6909 }
6910
6911 pub fn unique_lines_case_insensitive(
6912 &mut self,
6913 _: &UniqueLinesCaseInsensitive,
6914 window: &mut Window,
6915 cx: &mut Context<Self>,
6916 ) {
6917 self.manipulate_lines(window, cx, |lines| {
6918 let mut seen = HashSet::default();
6919 lines.retain(|line| seen.insert(line.to_lowercase()));
6920 })
6921 }
6922
6923 pub fn unique_lines_case_sensitive(
6924 &mut self,
6925 _: &UniqueLinesCaseSensitive,
6926 window: &mut Window,
6927 cx: &mut Context<Self>,
6928 ) {
6929 self.manipulate_lines(window, cx, |lines| {
6930 let mut seen = HashSet::default();
6931 lines.retain(|line| seen.insert(*line));
6932 })
6933 }
6934
6935 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6936 let mut revert_changes = HashMap::default();
6937 let snapshot = self.snapshot(window, cx);
6938 for hunk in snapshot
6939 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6940 {
6941 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6942 }
6943 if !revert_changes.is_empty() {
6944 self.transact(window, cx, |editor, window, cx| {
6945 editor.revert(revert_changes, window, cx);
6946 });
6947 }
6948 }
6949
6950 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6951 let Some(project) = self.project.clone() else {
6952 return;
6953 };
6954 self.reload(project, window, cx)
6955 .detach_and_notify_err(window, cx);
6956 }
6957
6958 pub fn revert_selected_hunks(
6959 &mut self,
6960 _: &RevertSelectedHunks,
6961 window: &mut Window,
6962 cx: &mut Context<Self>,
6963 ) {
6964 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6965 self.discard_hunks_in_ranges(selections, window, cx);
6966 }
6967
6968 fn discard_hunks_in_ranges(
6969 &mut self,
6970 ranges: impl Iterator<Item = Range<Point>>,
6971 window: &mut Window,
6972 cx: &mut Context<Editor>,
6973 ) {
6974 let mut revert_changes = HashMap::default();
6975 let snapshot = self.snapshot(window, cx);
6976 for hunk in &snapshot.hunks_for_ranges(ranges) {
6977 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6978 }
6979 if !revert_changes.is_empty() {
6980 self.transact(window, cx, |editor, window, cx| {
6981 editor.revert(revert_changes, window, cx);
6982 });
6983 }
6984 }
6985
6986 pub fn open_active_item_in_terminal(
6987 &mut self,
6988 _: &OpenInTerminal,
6989 window: &mut Window,
6990 cx: &mut Context<Self>,
6991 ) {
6992 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6993 let project_path = buffer.read(cx).project_path(cx)?;
6994 let project = self.project.as_ref()?.read(cx);
6995 let entry = project.entry_for_path(&project_path, cx)?;
6996 let parent = match &entry.canonical_path {
6997 Some(canonical_path) => canonical_path.to_path_buf(),
6998 None => project.absolute_path(&project_path, cx)?,
6999 }
7000 .parent()?
7001 .to_path_buf();
7002 Some(parent)
7003 }) {
7004 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7005 }
7006 }
7007
7008 pub fn prepare_revert_change(
7009 &self,
7010 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7011 hunk: &MultiBufferDiffHunk,
7012 cx: &mut App,
7013 ) -> Option<()> {
7014 let buffer = self.buffer.read(cx);
7015 let diff = buffer.diff_for(hunk.buffer_id)?;
7016 let buffer = buffer.buffer(hunk.buffer_id)?;
7017 let buffer = buffer.read(cx);
7018 let original_text = diff
7019 .read(cx)
7020 .base_text()
7021 .as_ref()?
7022 .as_rope()
7023 .slice(hunk.diff_base_byte_range.clone());
7024 let buffer_snapshot = buffer.snapshot();
7025 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7026 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7027 probe
7028 .0
7029 .start
7030 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7031 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7032 }) {
7033 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7034 Some(())
7035 } else {
7036 None
7037 }
7038 }
7039
7040 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7041 self.manipulate_lines(window, cx, |lines| lines.reverse())
7042 }
7043
7044 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7045 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7046 }
7047
7048 fn manipulate_lines<Fn>(
7049 &mut self,
7050 window: &mut Window,
7051 cx: &mut Context<Self>,
7052 mut callback: Fn,
7053 ) where
7054 Fn: FnMut(&mut Vec<&str>),
7055 {
7056 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7057 let buffer = self.buffer.read(cx).snapshot(cx);
7058
7059 let mut edits = Vec::new();
7060
7061 let selections = self.selections.all::<Point>(cx);
7062 let mut selections = selections.iter().peekable();
7063 let mut contiguous_row_selections = Vec::new();
7064 let mut new_selections = Vec::new();
7065 let mut added_lines = 0;
7066 let mut removed_lines = 0;
7067
7068 while let Some(selection) = selections.next() {
7069 let (start_row, end_row) = consume_contiguous_rows(
7070 &mut contiguous_row_selections,
7071 selection,
7072 &display_map,
7073 &mut selections,
7074 );
7075
7076 let start_point = Point::new(start_row.0, 0);
7077 let end_point = Point::new(
7078 end_row.previous_row().0,
7079 buffer.line_len(end_row.previous_row()),
7080 );
7081 let text = buffer
7082 .text_for_range(start_point..end_point)
7083 .collect::<String>();
7084
7085 let mut lines = text.split('\n').collect_vec();
7086
7087 let lines_before = lines.len();
7088 callback(&mut lines);
7089 let lines_after = lines.len();
7090
7091 edits.push((start_point..end_point, lines.join("\n")));
7092
7093 // Selections must change based on added and removed line count
7094 let start_row =
7095 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7096 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7097 new_selections.push(Selection {
7098 id: selection.id,
7099 start: start_row,
7100 end: end_row,
7101 goal: SelectionGoal::None,
7102 reversed: selection.reversed,
7103 });
7104
7105 if lines_after > lines_before {
7106 added_lines += lines_after - lines_before;
7107 } else if lines_before > lines_after {
7108 removed_lines += lines_before - lines_after;
7109 }
7110 }
7111
7112 self.transact(window, cx, |this, window, cx| {
7113 let buffer = this.buffer.update(cx, |buffer, cx| {
7114 buffer.edit(edits, None, cx);
7115 buffer.snapshot(cx)
7116 });
7117
7118 // Recalculate offsets on newly edited buffer
7119 let new_selections = new_selections
7120 .iter()
7121 .map(|s| {
7122 let start_point = Point::new(s.start.0, 0);
7123 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7124 Selection {
7125 id: s.id,
7126 start: buffer.point_to_offset(start_point),
7127 end: buffer.point_to_offset(end_point),
7128 goal: s.goal,
7129 reversed: s.reversed,
7130 }
7131 })
7132 .collect();
7133
7134 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7135 s.select(new_selections);
7136 });
7137
7138 this.request_autoscroll(Autoscroll::fit(), cx);
7139 });
7140 }
7141
7142 pub fn convert_to_upper_case(
7143 &mut self,
7144 _: &ConvertToUpperCase,
7145 window: &mut Window,
7146 cx: &mut Context<Self>,
7147 ) {
7148 self.manipulate_text(window, cx, |text| text.to_uppercase())
7149 }
7150
7151 pub fn convert_to_lower_case(
7152 &mut self,
7153 _: &ConvertToLowerCase,
7154 window: &mut Window,
7155 cx: &mut Context<Self>,
7156 ) {
7157 self.manipulate_text(window, cx, |text| text.to_lowercase())
7158 }
7159
7160 pub fn convert_to_title_case(
7161 &mut self,
7162 _: &ConvertToTitleCase,
7163 window: &mut Window,
7164 cx: &mut Context<Self>,
7165 ) {
7166 self.manipulate_text(window, cx, |text| {
7167 text.split('\n')
7168 .map(|line| line.to_case(Case::Title))
7169 .join("\n")
7170 })
7171 }
7172
7173 pub fn convert_to_snake_case(
7174 &mut self,
7175 _: &ConvertToSnakeCase,
7176 window: &mut Window,
7177 cx: &mut Context<Self>,
7178 ) {
7179 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7180 }
7181
7182 pub fn convert_to_kebab_case(
7183 &mut self,
7184 _: &ConvertToKebabCase,
7185 window: &mut Window,
7186 cx: &mut Context<Self>,
7187 ) {
7188 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7189 }
7190
7191 pub fn convert_to_upper_camel_case(
7192 &mut self,
7193 _: &ConvertToUpperCamelCase,
7194 window: &mut Window,
7195 cx: &mut Context<Self>,
7196 ) {
7197 self.manipulate_text(window, cx, |text| {
7198 text.split('\n')
7199 .map(|line| line.to_case(Case::UpperCamel))
7200 .join("\n")
7201 })
7202 }
7203
7204 pub fn convert_to_lower_camel_case(
7205 &mut self,
7206 _: &ConvertToLowerCamelCase,
7207 window: &mut Window,
7208 cx: &mut Context<Self>,
7209 ) {
7210 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7211 }
7212
7213 pub fn convert_to_opposite_case(
7214 &mut self,
7215 _: &ConvertToOppositeCase,
7216 window: &mut Window,
7217 cx: &mut Context<Self>,
7218 ) {
7219 self.manipulate_text(window, cx, |text| {
7220 text.chars()
7221 .fold(String::with_capacity(text.len()), |mut t, c| {
7222 if c.is_uppercase() {
7223 t.extend(c.to_lowercase());
7224 } else {
7225 t.extend(c.to_uppercase());
7226 }
7227 t
7228 })
7229 })
7230 }
7231
7232 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7233 where
7234 Fn: FnMut(&str) -> String,
7235 {
7236 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7237 let buffer = self.buffer.read(cx).snapshot(cx);
7238
7239 let mut new_selections = Vec::new();
7240 let mut edits = Vec::new();
7241 let mut selection_adjustment = 0i32;
7242
7243 for selection in self.selections.all::<usize>(cx) {
7244 let selection_is_empty = selection.is_empty();
7245
7246 let (start, end) = if selection_is_empty {
7247 let word_range = movement::surrounding_word(
7248 &display_map,
7249 selection.start.to_display_point(&display_map),
7250 );
7251 let start = word_range.start.to_offset(&display_map, Bias::Left);
7252 let end = word_range.end.to_offset(&display_map, Bias::Left);
7253 (start, end)
7254 } else {
7255 (selection.start, selection.end)
7256 };
7257
7258 let text = buffer.text_for_range(start..end).collect::<String>();
7259 let old_length = text.len() as i32;
7260 let text = callback(&text);
7261
7262 new_selections.push(Selection {
7263 start: (start as i32 - selection_adjustment) as usize,
7264 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7265 goal: SelectionGoal::None,
7266 ..selection
7267 });
7268
7269 selection_adjustment += old_length - text.len() as i32;
7270
7271 edits.push((start..end, text));
7272 }
7273
7274 self.transact(window, cx, |this, window, cx| {
7275 this.buffer.update(cx, |buffer, cx| {
7276 buffer.edit(edits, None, cx);
7277 });
7278
7279 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7280 s.select(new_selections);
7281 });
7282
7283 this.request_autoscroll(Autoscroll::fit(), cx);
7284 });
7285 }
7286
7287 pub fn duplicate(
7288 &mut self,
7289 upwards: bool,
7290 whole_lines: bool,
7291 window: &mut Window,
7292 cx: &mut Context<Self>,
7293 ) {
7294 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7295 let buffer = &display_map.buffer_snapshot;
7296 let selections = self.selections.all::<Point>(cx);
7297
7298 let mut edits = Vec::new();
7299 let mut selections_iter = selections.iter().peekable();
7300 while let Some(selection) = selections_iter.next() {
7301 let mut rows = selection.spanned_rows(false, &display_map);
7302 // duplicate line-wise
7303 if whole_lines || selection.start == selection.end {
7304 // Avoid duplicating the same lines twice.
7305 while let Some(next_selection) = selections_iter.peek() {
7306 let next_rows = next_selection.spanned_rows(false, &display_map);
7307 if next_rows.start < rows.end {
7308 rows.end = next_rows.end;
7309 selections_iter.next().unwrap();
7310 } else {
7311 break;
7312 }
7313 }
7314
7315 // Copy the text from the selected row region and splice it either at the start
7316 // or end of the region.
7317 let start = Point::new(rows.start.0, 0);
7318 let end = Point::new(
7319 rows.end.previous_row().0,
7320 buffer.line_len(rows.end.previous_row()),
7321 );
7322 let text = buffer
7323 .text_for_range(start..end)
7324 .chain(Some("\n"))
7325 .collect::<String>();
7326 let insert_location = if upwards {
7327 Point::new(rows.end.0, 0)
7328 } else {
7329 start
7330 };
7331 edits.push((insert_location..insert_location, text));
7332 } else {
7333 // duplicate character-wise
7334 let start = selection.start;
7335 let end = selection.end;
7336 let text = buffer.text_for_range(start..end).collect::<String>();
7337 edits.push((selection.end..selection.end, text));
7338 }
7339 }
7340
7341 self.transact(window, cx, |this, _, cx| {
7342 this.buffer.update(cx, |buffer, cx| {
7343 buffer.edit(edits, None, cx);
7344 });
7345
7346 this.request_autoscroll(Autoscroll::fit(), cx);
7347 });
7348 }
7349
7350 pub fn duplicate_line_up(
7351 &mut self,
7352 _: &DuplicateLineUp,
7353 window: &mut Window,
7354 cx: &mut Context<Self>,
7355 ) {
7356 self.duplicate(true, true, window, cx);
7357 }
7358
7359 pub fn duplicate_line_down(
7360 &mut self,
7361 _: &DuplicateLineDown,
7362 window: &mut Window,
7363 cx: &mut Context<Self>,
7364 ) {
7365 self.duplicate(false, true, window, cx);
7366 }
7367
7368 pub fn duplicate_selection(
7369 &mut self,
7370 _: &DuplicateSelection,
7371 window: &mut Window,
7372 cx: &mut Context<Self>,
7373 ) {
7374 self.duplicate(false, false, window, cx);
7375 }
7376
7377 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7379 let buffer = self.buffer.read(cx).snapshot(cx);
7380
7381 let mut edits = Vec::new();
7382 let mut unfold_ranges = Vec::new();
7383 let mut refold_creases = Vec::new();
7384
7385 let selections = self.selections.all::<Point>(cx);
7386 let mut selections = selections.iter().peekable();
7387 let mut contiguous_row_selections = Vec::new();
7388 let mut new_selections = Vec::new();
7389
7390 while let Some(selection) = selections.next() {
7391 // Find all the selections that span a contiguous row range
7392 let (start_row, end_row) = consume_contiguous_rows(
7393 &mut contiguous_row_selections,
7394 selection,
7395 &display_map,
7396 &mut selections,
7397 );
7398
7399 // Move the text spanned by the row range to be before the line preceding the row range
7400 if start_row.0 > 0 {
7401 let range_to_move = Point::new(
7402 start_row.previous_row().0,
7403 buffer.line_len(start_row.previous_row()),
7404 )
7405 ..Point::new(
7406 end_row.previous_row().0,
7407 buffer.line_len(end_row.previous_row()),
7408 );
7409 let insertion_point = display_map
7410 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7411 .0;
7412
7413 // Don't move lines across excerpts
7414 if buffer
7415 .excerpt_containing(insertion_point..range_to_move.end)
7416 .is_some()
7417 {
7418 let text = buffer
7419 .text_for_range(range_to_move.clone())
7420 .flat_map(|s| s.chars())
7421 .skip(1)
7422 .chain(['\n'])
7423 .collect::<String>();
7424
7425 edits.push((
7426 buffer.anchor_after(range_to_move.start)
7427 ..buffer.anchor_before(range_to_move.end),
7428 String::new(),
7429 ));
7430 let insertion_anchor = buffer.anchor_after(insertion_point);
7431 edits.push((insertion_anchor..insertion_anchor, text));
7432
7433 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7434
7435 // Move selections up
7436 new_selections.extend(contiguous_row_selections.drain(..).map(
7437 |mut selection| {
7438 selection.start.row -= row_delta;
7439 selection.end.row -= row_delta;
7440 selection
7441 },
7442 ));
7443
7444 // Move folds up
7445 unfold_ranges.push(range_to_move.clone());
7446 for fold in display_map.folds_in_range(
7447 buffer.anchor_before(range_to_move.start)
7448 ..buffer.anchor_after(range_to_move.end),
7449 ) {
7450 let mut start = fold.range.start.to_point(&buffer);
7451 let mut end = fold.range.end.to_point(&buffer);
7452 start.row -= row_delta;
7453 end.row -= row_delta;
7454 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7455 }
7456 }
7457 }
7458
7459 // If we didn't move line(s), preserve the existing selections
7460 new_selections.append(&mut contiguous_row_selections);
7461 }
7462
7463 self.transact(window, cx, |this, window, cx| {
7464 this.unfold_ranges(&unfold_ranges, true, true, cx);
7465 this.buffer.update(cx, |buffer, cx| {
7466 for (range, text) in edits {
7467 buffer.edit([(range, text)], None, cx);
7468 }
7469 });
7470 this.fold_creases(refold_creases, true, window, cx);
7471 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7472 s.select(new_selections);
7473 })
7474 });
7475 }
7476
7477 pub fn move_line_down(
7478 &mut self,
7479 _: &MoveLineDown,
7480 window: &mut Window,
7481 cx: &mut Context<Self>,
7482 ) {
7483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7484 let buffer = self.buffer.read(cx).snapshot(cx);
7485
7486 let mut edits = Vec::new();
7487 let mut unfold_ranges = Vec::new();
7488 let mut refold_creases = Vec::new();
7489
7490 let selections = self.selections.all::<Point>(cx);
7491 let mut selections = selections.iter().peekable();
7492 let mut contiguous_row_selections = Vec::new();
7493 let mut new_selections = Vec::new();
7494
7495 while let Some(selection) = selections.next() {
7496 // Find all the selections that span a contiguous row range
7497 let (start_row, end_row) = consume_contiguous_rows(
7498 &mut contiguous_row_selections,
7499 selection,
7500 &display_map,
7501 &mut selections,
7502 );
7503
7504 // Move the text spanned by the row range to be after the last line of the row range
7505 if end_row.0 <= buffer.max_point().row {
7506 let range_to_move =
7507 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7508 let insertion_point = display_map
7509 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7510 .0;
7511
7512 // Don't move lines across excerpt boundaries
7513 if buffer
7514 .excerpt_containing(range_to_move.start..insertion_point)
7515 .is_some()
7516 {
7517 let mut text = String::from("\n");
7518 text.extend(buffer.text_for_range(range_to_move.clone()));
7519 text.pop(); // Drop trailing newline
7520 edits.push((
7521 buffer.anchor_after(range_to_move.start)
7522 ..buffer.anchor_before(range_to_move.end),
7523 String::new(),
7524 ));
7525 let insertion_anchor = buffer.anchor_after(insertion_point);
7526 edits.push((insertion_anchor..insertion_anchor, text));
7527
7528 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7529
7530 // Move selections down
7531 new_selections.extend(contiguous_row_selections.drain(..).map(
7532 |mut selection| {
7533 selection.start.row += row_delta;
7534 selection.end.row += row_delta;
7535 selection
7536 },
7537 ));
7538
7539 // Move folds down
7540 unfold_ranges.push(range_to_move.clone());
7541 for fold in display_map.folds_in_range(
7542 buffer.anchor_before(range_to_move.start)
7543 ..buffer.anchor_after(range_to_move.end),
7544 ) {
7545 let mut start = fold.range.start.to_point(&buffer);
7546 let mut end = fold.range.end.to_point(&buffer);
7547 start.row += row_delta;
7548 end.row += row_delta;
7549 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7550 }
7551 }
7552 }
7553
7554 // If we didn't move line(s), preserve the existing selections
7555 new_selections.append(&mut contiguous_row_selections);
7556 }
7557
7558 self.transact(window, cx, |this, window, cx| {
7559 this.unfold_ranges(&unfold_ranges, true, true, cx);
7560 this.buffer.update(cx, |buffer, cx| {
7561 for (range, text) in edits {
7562 buffer.edit([(range, text)], None, cx);
7563 }
7564 });
7565 this.fold_creases(refold_creases, true, window, cx);
7566 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7567 s.select(new_selections)
7568 });
7569 });
7570 }
7571
7572 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7573 let text_layout_details = &self.text_layout_details(window);
7574 self.transact(window, cx, |this, window, cx| {
7575 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7576 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7577 let line_mode = s.line_mode;
7578 s.move_with(|display_map, selection| {
7579 if !selection.is_empty() || line_mode {
7580 return;
7581 }
7582
7583 let mut head = selection.head();
7584 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7585 if head.column() == display_map.line_len(head.row()) {
7586 transpose_offset = display_map
7587 .buffer_snapshot
7588 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7589 }
7590
7591 if transpose_offset == 0 {
7592 return;
7593 }
7594
7595 *head.column_mut() += 1;
7596 head = display_map.clip_point(head, Bias::Right);
7597 let goal = SelectionGoal::HorizontalPosition(
7598 display_map
7599 .x_for_display_point(head, text_layout_details)
7600 .into(),
7601 );
7602 selection.collapse_to(head, goal);
7603
7604 let transpose_start = display_map
7605 .buffer_snapshot
7606 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7607 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7608 let transpose_end = display_map
7609 .buffer_snapshot
7610 .clip_offset(transpose_offset + 1, Bias::Right);
7611 if let Some(ch) =
7612 display_map.buffer_snapshot.chars_at(transpose_start).next()
7613 {
7614 edits.push((transpose_start..transpose_offset, String::new()));
7615 edits.push((transpose_end..transpose_end, ch.to_string()));
7616 }
7617 }
7618 });
7619 edits
7620 });
7621 this.buffer
7622 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7623 let selections = this.selections.all::<usize>(cx);
7624 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7625 s.select(selections);
7626 });
7627 });
7628 }
7629
7630 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7631 self.rewrap_impl(IsVimMode::No, cx)
7632 }
7633
7634 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7635 let buffer = self.buffer.read(cx).snapshot(cx);
7636 let selections = self.selections.all::<Point>(cx);
7637 let mut selections = selections.iter().peekable();
7638
7639 let mut edits = Vec::new();
7640 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7641
7642 while let Some(selection) = selections.next() {
7643 let mut start_row = selection.start.row;
7644 let mut end_row = selection.end.row;
7645
7646 // Skip selections that overlap with a range that has already been rewrapped.
7647 let selection_range = start_row..end_row;
7648 if rewrapped_row_ranges
7649 .iter()
7650 .any(|range| range.overlaps(&selection_range))
7651 {
7652 continue;
7653 }
7654
7655 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7656
7657 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7658 match language_scope.language_name().as_ref() {
7659 "Markdown" | "Plain Text" => {
7660 should_rewrap = true;
7661 }
7662 _ => {}
7663 }
7664 }
7665
7666 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7667
7668 // Since not all lines in the selection may be at the same indent
7669 // level, choose the indent size that is the most common between all
7670 // of the lines.
7671 //
7672 // If there is a tie, we use the deepest indent.
7673 let (indent_size, indent_end) = {
7674 let mut indent_size_occurrences = HashMap::default();
7675 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7676
7677 for row in start_row..=end_row {
7678 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7679 rows_by_indent_size.entry(indent).or_default().push(row);
7680 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7681 }
7682
7683 let indent_size = indent_size_occurrences
7684 .into_iter()
7685 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7686 .map(|(indent, _)| indent)
7687 .unwrap_or_default();
7688 let row = rows_by_indent_size[&indent_size][0];
7689 let indent_end = Point::new(row, indent_size.len);
7690
7691 (indent_size, indent_end)
7692 };
7693
7694 let mut line_prefix = indent_size.chars().collect::<String>();
7695
7696 if let Some(comment_prefix) =
7697 buffer
7698 .language_scope_at(selection.head())
7699 .and_then(|language| {
7700 language
7701 .line_comment_prefixes()
7702 .iter()
7703 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7704 .cloned()
7705 })
7706 {
7707 line_prefix.push_str(&comment_prefix);
7708 should_rewrap = true;
7709 }
7710
7711 if !should_rewrap {
7712 continue;
7713 }
7714
7715 if selection.is_empty() {
7716 'expand_upwards: while start_row > 0 {
7717 let prev_row = start_row - 1;
7718 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7719 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7720 {
7721 start_row = prev_row;
7722 } else {
7723 break 'expand_upwards;
7724 }
7725 }
7726
7727 'expand_downwards: while end_row < buffer.max_point().row {
7728 let next_row = end_row + 1;
7729 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7730 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7731 {
7732 end_row = next_row;
7733 } else {
7734 break 'expand_downwards;
7735 }
7736 }
7737 }
7738
7739 let start = Point::new(start_row, 0);
7740 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7741 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7742 let Some(lines_without_prefixes) = selection_text
7743 .lines()
7744 .map(|line| {
7745 line.strip_prefix(&line_prefix)
7746 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7747 .ok_or_else(|| {
7748 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7749 })
7750 })
7751 .collect::<Result<Vec<_>, _>>()
7752 .log_err()
7753 else {
7754 continue;
7755 };
7756
7757 let wrap_column = buffer
7758 .settings_at(Point::new(start_row, 0), cx)
7759 .preferred_line_length as usize;
7760 let wrapped_text = wrap_with_prefix(
7761 line_prefix,
7762 lines_without_prefixes.join(" "),
7763 wrap_column,
7764 tab_size,
7765 );
7766
7767 // TODO: should always use char-based diff while still supporting cursor behavior that
7768 // matches vim.
7769 let diff = match is_vim_mode {
7770 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7771 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7772 };
7773 let mut offset = start.to_offset(&buffer);
7774 let mut moved_since_edit = true;
7775
7776 for change in diff.iter_all_changes() {
7777 let value = change.value();
7778 match change.tag() {
7779 ChangeTag::Equal => {
7780 offset += value.len();
7781 moved_since_edit = true;
7782 }
7783 ChangeTag::Delete => {
7784 let start = buffer.anchor_after(offset);
7785 let end = buffer.anchor_before(offset + value.len());
7786
7787 if moved_since_edit {
7788 edits.push((start..end, String::new()));
7789 } else {
7790 edits.last_mut().unwrap().0.end = end;
7791 }
7792
7793 offset += value.len();
7794 moved_since_edit = false;
7795 }
7796 ChangeTag::Insert => {
7797 if moved_since_edit {
7798 let anchor = buffer.anchor_after(offset);
7799 edits.push((anchor..anchor, value.to_string()));
7800 } else {
7801 edits.last_mut().unwrap().1.push_str(value);
7802 }
7803
7804 moved_since_edit = false;
7805 }
7806 }
7807 }
7808
7809 rewrapped_row_ranges.push(start_row..=end_row);
7810 }
7811
7812 self.buffer
7813 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7814 }
7815
7816 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7817 let mut text = String::new();
7818 let buffer = self.buffer.read(cx).snapshot(cx);
7819 let mut selections = self.selections.all::<Point>(cx);
7820 let mut clipboard_selections = Vec::with_capacity(selections.len());
7821 {
7822 let max_point = buffer.max_point();
7823 let mut is_first = true;
7824 for selection in &mut selections {
7825 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7826 if is_entire_line {
7827 selection.start = Point::new(selection.start.row, 0);
7828 if !selection.is_empty() && selection.end.column == 0 {
7829 selection.end = cmp::min(max_point, selection.end);
7830 } else {
7831 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7832 }
7833 selection.goal = SelectionGoal::None;
7834 }
7835 if is_first {
7836 is_first = false;
7837 } else {
7838 text += "\n";
7839 }
7840 let mut len = 0;
7841 for chunk in buffer.text_for_range(selection.start..selection.end) {
7842 text.push_str(chunk);
7843 len += chunk.len();
7844 }
7845 clipboard_selections.push(ClipboardSelection {
7846 len,
7847 is_entire_line,
7848 first_line_indent: buffer
7849 .indent_size_for_line(MultiBufferRow(selection.start.row))
7850 .len,
7851 });
7852 }
7853 }
7854
7855 self.transact(window, cx, |this, window, cx| {
7856 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7857 s.select(selections);
7858 });
7859 this.insert("", window, cx);
7860 });
7861 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7862 }
7863
7864 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7865 let item = self.cut_common(window, cx);
7866 cx.write_to_clipboard(item);
7867 }
7868
7869 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7870 self.change_selections(None, window, cx, |s| {
7871 s.move_with(|snapshot, sel| {
7872 if sel.is_empty() {
7873 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7874 }
7875 });
7876 });
7877 let item = self.cut_common(window, cx);
7878 cx.set_global(KillRing(item))
7879 }
7880
7881 pub fn kill_ring_yank(
7882 &mut self,
7883 _: &KillRingYank,
7884 window: &mut Window,
7885 cx: &mut Context<Self>,
7886 ) {
7887 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7888 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7889 (kill_ring.text().to_string(), kill_ring.metadata_json())
7890 } else {
7891 return;
7892 }
7893 } else {
7894 return;
7895 };
7896 self.do_paste(&text, metadata, false, window, cx);
7897 }
7898
7899 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7900 let selections = self.selections.all::<Point>(cx);
7901 let buffer = self.buffer.read(cx).read(cx);
7902 let mut text = String::new();
7903
7904 let mut clipboard_selections = Vec::with_capacity(selections.len());
7905 {
7906 let max_point = buffer.max_point();
7907 let mut is_first = true;
7908 for selection in selections.iter() {
7909 let mut start = selection.start;
7910 let mut end = selection.end;
7911 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7912 if is_entire_line {
7913 start = Point::new(start.row, 0);
7914 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7915 }
7916 if is_first {
7917 is_first = false;
7918 } else {
7919 text += "\n";
7920 }
7921 let mut len = 0;
7922 for chunk in buffer.text_for_range(start..end) {
7923 text.push_str(chunk);
7924 len += chunk.len();
7925 }
7926 clipboard_selections.push(ClipboardSelection {
7927 len,
7928 is_entire_line,
7929 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7930 });
7931 }
7932 }
7933
7934 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7935 text,
7936 clipboard_selections,
7937 ));
7938 }
7939
7940 pub fn do_paste(
7941 &mut self,
7942 text: &String,
7943 clipboard_selections: Option<Vec<ClipboardSelection>>,
7944 handle_entire_lines: bool,
7945 window: &mut Window,
7946 cx: &mut Context<Self>,
7947 ) {
7948 if self.read_only(cx) {
7949 return;
7950 }
7951
7952 let clipboard_text = Cow::Borrowed(text);
7953
7954 self.transact(window, cx, |this, window, cx| {
7955 if let Some(mut clipboard_selections) = clipboard_selections {
7956 let old_selections = this.selections.all::<usize>(cx);
7957 let all_selections_were_entire_line =
7958 clipboard_selections.iter().all(|s| s.is_entire_line);
7959 let first_selection_indent_column =
7960 clipboard_selections.first().map(|s| s.first_line_indent);
7961 if clipboard_selections.len() != old_selections.len() {
7962 clipboard_selections.drain(..);
7963 }
7964 let cursor_offset = this.selections.last::<usize>(cx).head();
7965 let mut auto_indent_on_paste = true;
7966
7967 this.buffer.update(cx, |buffer, cx| {
7968 let snapshot = buffer.read(cx);
7969 auto_indent_on_paste =
7970 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7971
7972 let mut start_offset = 0;
7973 let mut edits = Vec::new();
7974 let mut original_indent_columns = Vec::new();
7975 for (ix, selection) in old_selections.iter().enumerate() {
7976 let to_insert;
7977 let entire_line;
7978 let original_indent_column;
7979 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7980 let end_offset = start_offset + clipboard_selection.len;
7981 to_insert = &clipboard_text[start_offset..end_offset];
7982 entire_line = clipboard_selection.is_entire_line;
7983 start_offset = end_offset + 1;
7984 original_indent_column = Some(clipboard_selection.first_line_indent);
7985 } else {
7986 to_insert = clipboard_text.as_str();
7987 entire_line = all_selections_were_entire_line;
7988 original_indent_column = first_selection_indent_column
7989 }
7990
7991 // If the corresponding selection was empty when this slice of the
7992 // clipboard text was written, then the entire line containing the
7993 // selection was copied. If this selection is also currently empty,
7994 // then paste the line before the current line of the buffer.
7995 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7996 let column = selection.start.to_point(&snapshot).column as usize;
7997 let line_start = selection.start - column;
7998 line_start..line_start
7999 } else {
8000 selection.range()
8001 };
8002
8003 edits.push((range, to_insert));
8004 original_indent_columns.extend(original_indent_column);
8005 }
8006 drop(snapshot);
8007
8008 buffer.edit(
8009 edits,
8010 if auto_indent_on_paste {
8011 Some(AutoindentMode::Block {
8012 original_indent_columns,
8013 })
8014 } else {
8015 None
8016 },
8017 cx,
8018 );
8019 });
8020
8021 let selections = this.selections.all::<usize>(cx);
8022 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8023 s.select(selections)
8024 });
8025 } else {
8026 this.insert(&clipboard_text, window, cx);
8027 }
8028 });
8029 }
8030
8031 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8032 if let Some(item) = cx.read_from_clipboard() {
8033 let entries = item.entries();
8034
8035 match entries.first() {
8036 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8037 // of all the pasted entries.
8038 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8039 .do_paste(
8040 clipboard_string.text(),
8041 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8042 true,
8043 window,
8044 cx,
8045 ),
8046 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8047 }
8048 }
8049 }
8050
8051 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8052 if self.read_only(cx) {
8053 return;
8054 }
8055
8056 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8057 if let Some((selections, _)) =
8058 self.selection_history.transaction(transaction_id).cloned()
8059 {
8060 self.change_selections(None, window, cx, |s| {
8061 s.select_anchors(selections.to_vec());
8062 });
8063 }
8064 self.request_autoscroll(Autoscroll::fit(), cx);
8065 self.unmark_text(window, cx);
8066 self.refresh_inline_completion(true, false, window, cx);
8067 cx.emit(EditorEvent::Edited { transaction_id });
8068 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8069 }
8070 }
8071
8072 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8073 if self.read_only(cx) {
8074 return;
8075 }
8076
8077 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8078 if let Some((_, Some(selections))) =
8079 self.selection_history.transaction(transaction_id).cloned()
8080 {
8081 self.change_selections(None, window, cx, |s| {
8082 s.select_anchors(selections.to_vec());
8083 });
8084 }
8085 self.request_autoscroll(Autoscroll::fit(), cx);
8086 self.unmark_text(window, cx);
8087 self.refresh_inline_completion(true, false, window, cx);
8088 cx.emit(EditorEvent::Edited { transaction_id });
8089 }
8090 }
8091
8092 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8093 self.buffer
8094 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8095 }
8096
8097 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8098 self.buffer
8099 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8100 }
8101
8102 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8103 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8104 let line_mode = s.line_mode;
8105 s.move_with(|map, selection| {
8106 let cursor = if selection.is_empty() && !line_mode {
8107 movement::left(map, selection.start)
8108 } else {
8109 selection.start
8110 };
8111 selection.collapse_to(cursor, SelectionGoal::None);
8112 });
8113 })
8114 }
8115
8116 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8117 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8118 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8119 })
8120 }
8121
8122 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8123 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8124 let line_mode = s.line_mode;
8125 s.move_with(|map, selection| {
8126 let cursor = if selection.is_empty() && !line_mode {
8127 movement::right(map, selection.end)
8128 } else {
8129 selection.end
8130 };
8131 selection.collapse_to(cursor, SelectionGoal::None)
8132 });
8133 })
8134 }
8135
8136 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8137 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8138 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8139 })
8140 }
8141
8142 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8143 if self.take_rename(true, window, cx).is_some() {
8144 return;
8145 }
8146
8147 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8148 cx.propagate();
8149 return;
8150 }
8151
8152 let text_layout_details = &self.text_layout_details(window);
8153 let selection_count = self.selections.count();
8154 let first_selection = self.selections.first_anchor();
8155
8156 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8157 let line_mode = s.line_mode;
8158 s.move_with(|map, selection| {
8159 if !selection.is_empty() && !line_mode {
8160 selection.goal = SelectionGoal::None;
8161 }
8162 let (cursor, goal) = movement::up(
8163 map,
8164 selection.start,
8165 selection.goal,
8166 false,
8167 text_layout_details,
8168 );
8169 selection.collapse_to(cursor, goal);
8170 });
8171 });
8172
8173 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8174 {
8175 cx.propagate();
8176 }
8177 }
8178
8179 pub fn move_up_by_lines(
8180 &mut self,
8181 action: &MoveUpByLines,
8182 window: &mut Window,
8183 cx: &mut Context<Self>,
8184 ) {
8185 if self.take_rename(true, window, cx).is_some() {
8186 return;
8187 }
8188
8189 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8190 cx.propagate();
8191 return;
8192 }
8193
8194 let text_layout_details = &self.text_layout_details(window);
8195
8196 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8197 let line_mode = s.line_mode;
8198 s.move_with(|map, selection| {
8199 if !selection.is_empty() && !line_mode {
8200 selection.goal = SelectionGoal::None;
8201 }
8202 let (cursor, goal) = movement::up_by_rows(
8203 map,
8204 selection.start,
8205 action.lines,
8206 selection.goal,
8207 false,
8208 text_layout_details,
8209 );
8210 selection.collapse_to(cursor, goal);
8211 });
8212 })
8213 }
8214
8215 pub fn move_down_by_lines(
8216 &mut self,
8217 action: &MoveDownByLines,
8218 window: &mut Window,
8219 cx: &mut Context<Self>,
8220 ) {
8221 if self.take_rename(true, window, cx).is_some() {
8222 return;
8223 }
8224
8225 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8226 cx.propagate();
8227 return;
8228 }
8229
8230 let text_layout_details = &self.text_layout_details(window);
8231
8232 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8233 let line_mode = s.line_mode;
8234 s.move_with(|map, selection| {
8235 if !selection.is_empty() && !line_mode {
8236 selection.goal = SelectionGoal::None;
8237 }
8238 let (cursor, goal) = movement::down_by_rows(
8239 map,
8240 selection.start,
8241 action.lines,
8242 selection.goal,
8243 false,
8244 text_layout_details,
8245 );
8246 selection.collapse_to(cursor, goal);
8247 });
8248 })
8249 }
8250
8251 pub fn select_down_by_lines(
8252 &mut self,
8253 action: &SelectDownByLines,
8254 window: &mut Window,
8255 cx: &mut Context<Self>,
8256 ) {
8257 let text_layout_details = &self.text_layout_details(window);
8258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8259 s.move_heads_with(|map, head, goal| {
8260 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8261 })
8262 })
8263 }
8264
8265 pub fn select_up_by_lines(
8266 &mut self,
8267 action: &SelectUpByLines,
8268 window: &mut Window,
8269 cx: &mut Context<Self>,
8270 ) {
8271 let text_layout_details = &self.text_layout_details(window);
8272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8273 s.move_heads_with(|map, head, goal| {
8274 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8275 })
8276 })
8277 }
8278
8279 pub fn select_page_up(
8280 &mut self,
8281 _: &SelectPageUp,
8282 window: &mut Window,
8283 cx: &mut Context<Self>,
8284 ) {
8285 let Some(row_count) = self.visible_row_count() else {
8286 return;
8287 };
8288
8289 let text_layout_details = &self.text_layout_details(window);
8290
8291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8292 s.move_heads_with(|map, head, goal| {
8293 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8294 })
8295 })
8296 }
8297
8298 pub fn move_page_up(
8299 &mut self,
8300 action: &MovePageUp,
8301 window: &mut Window,
8302 cx: &mut Context<Self>,
8303 ) {
8304 if self.take_rename(true, window, cx).is_some() {
8305 return;
8306 }
8307
8308 if self
8309 .context_menu
8310 .borrow_mut()
8311 .as_mut()
8312 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8313 .unwrap_or(false)
8314 {
8315 return;
8316 }
8317
8318 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8319 cx.propagate();
8320 return;
8321 }
8322
8323 let Some(row_count) = self.visible_row_count() else {
8324 return;
8325 };
8326
8327 let autoscroll = if action.center_cursor {
8328 Autoscroll::center()
8329 } else {
8330 Autoscroll::fit()
8331 };
8332
8333 let text_layout_details = &self.text_layout_details(window);
8334
8335 self.change_selections(Some(autoscroll), window, cx, |s| {
8336 let line_mode = s.line_mode;
8337 s.move_with(|map, selection| {
8338 if !selection.is_empty() && !line_mode {
8339 selection.goal = SelectionGoal::None;
8340 }
8341 let (cursor, goal) = movement::up_by_rows(
8342 map,
8343 selection.end,
8344 row_count,
8345 selection.goal,
8346 false,
8347 text_layout_details,
8348 );
8349 selection.collapse_to(cursor, goal);
8350 });
8351 });
8352 }
8353
8354 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8355 let text_layout_details = &self.text_layout_details(window);
8356 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8357 s.move_heads_with(|map, head, goal| {
8358 movement::up(map, head, goal, false, text_layout_details)
8359 })
8360 })
8361 }
8362
8363 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8364 self.take_rename(true, window, cx);
8365
8366 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8367 cx.propagate();
8368 return;
8369 }
8370
8371 let text_layout_details = &self.text_layout_details(window);
8372 let selection_count = self.selections.count();
8373 let first_selection = self.selections.first_anchor();
8374
8375 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8376 let line_mode = s.line_mode;
8377 s.move_with(|map, selection| {
8378 if !selection.is_empty() && !line_mode {
8379 selection.goal = SelectionGoal::None;
8380 }
8381 let (cursor, goal) = movement::down(
8382 map,
8383 selection.end,
8384 selection.goal,
8385 false,
8386 text_layout_details,
8387 );
8388 selection.collapse_to(cursor, goal);
8389 });
8390 });
8391
8392 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8393 {
8394 cx.propagate();
8395 }
8396 }
8397
8398 pub fn select_page_down(
8399 &mut self,
8400 _: &SelectPageDown,
8401 window: &mut Window,
8402 cx: &mut Context<Self>,
8403 ) {
8404 let Some(row_count) = self.visible_row_count() else {
8405 return;
8406 };
8407
8408 let text_layout_details = &self.text_layout_details(window);
8409
8410 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8411 s.move_heads_with(|map, head, goal| {
8412 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8413 })
8414 })
8415 }
8416
8417 pub fn move_page_down(
8418 &mut self,
8419 action: &MovePageDown,
8420 window: &mut Window,
8421 cx: &mut Context<Self>,
8422 ) {
8423 if self.take_rename(true, window, cx).is_some() {
8424 return;
8425 }
8426
8427 if self
8428 .context_menu
8429 .borrow_mut()
8430 .as_mut()
8431 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8432 .unwrap_or(false)
8433 {
8434 return;
8435 }
8436
8437 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8438 cx.propagate();
8439 return;
8440 }
8441
8442 let Some(row_count) = self.visible_row_count() else {
8443 return;
8444 };
8445
8446 let autoscroll = if action.center_cursor {
8447 Autoscroll::center()
8448 } else {
8449 Autoscroll::fit()
8450 };
8451
8452 let text_layout_details = &self.text_layout_details(window);
8453 self.change_selections(Some(autoscroll), window, cx, |s| {
8454 let line_mode = s.line_mode;
8455 s.move_with(|map, selection| {
8456 if !selection.is_empty() && !line_mode {
8457 selection.goal = SelectionGoal::None;
8458 }
8459 let (cursor, goal) = movement::down_by_rows(
8460 map,
8461 selection.end,
8462 row_count,
8463 selection.goal,
8464 false,
8465 text_layout_details,
8466 );
8467 selection.collapse_to(cursor, goal);
8468 });
8469 });
8470 }
8471
8472 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8473 let text_layout_details = &self.text_layout_details(window);
8474 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8475 s.move_heads_with(|map, head, goal| {
8476 movement::down(map, head, goal, false, text_layout_details)
8477 })
8478 });
8479 }
8480
8481 pub fn context_menu_first(
8482 &mut self,
8483 _: &ContextMenuFirst,
8484 _window: &mut Window,
8485 cx: &mut Context<Self>,
8486 ) {
8487 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8488 context_menu.select_first(self.completion_provider.as_deref(), cx);
8489 }
8490 }
8491
8492 pub fn context_menu_prev(
8493 &mut self,
8494 _: &ContextMenuPrev,
8495 _window: &mut Window,
8496 cx: &mut Context<Self>,
8497 ) {
8498 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8499 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8500 }
8501 }
8502
8503 pub fn context_menu_next(
8504 &mut self,
8505 _: &ContextMenuNext,
8506 _window: &mut Window,
8507 cx: &mut Context<Self>,
8508 ) {
8509 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8510 context_menu.select_next(self.completion_provider.as_deref(), cx);
8511 }
8512 }
8513
8514 pub fn context_menu_last(
8515 &mut self,
8516 _: &ContextMenuLast,
8517 _window: &mut Window,
8518 cx: &mut Context<Self>,
8519 ) {
8520 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8521 context_menu.select_last(self.completion_provider.as_deref(), cx);
8522 }
8523 }
8524
8525 pub fn move_to_previous_word_start(
8526 &mut self,
8527 _: &MoveToPreviousWordStart,
8528 window: &mut Window,
8529 cx: &mut Context<Self>,
8530 ) {
8531 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8532 s.move_cursors_with(|map, head, _| {
8533 (
8534 movement::previous_word_start(map, head),
8535 SelectionGoal::None,
8536 )
8537 });
8538 })
8539 }
8540
8541 pub fn move_to_previous_subword_start(
8542 &mut self,
8543 _: &MoveToPreviousSubwordStart,
8544 window: &mut Window,
8545 cx: &mut Context<Self>,
8546 ) {
8547 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8548 s.move_cursors_with(|map, head, _| {
8549 (
8550 movement::previous_subword_start(map, head),
8551 SelectionGoal::None,
8552 )
8553 });
8554 })
8555 }
8556
8557 pub fn select_to_previous_word_start(
8558 &mut self,
8559 _: &SelectToPreviousWordStart,
8560 window: &mut Window,
8561 cx: &mut Context<Self>,
8562 ) {
8563 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8564 s.move_heads_with(|map, head, _| {
8565 (
8566 movement::previous_word_start(map, head),
8567 SelectionGoal::None,
8568 )
8569 });
8570 })
8571 }
8572
8573 pub fn select_to_previous_subword_start(
8574 &mut self,
8575 _: &SelectToPreviousSubwordStart,
8576 window: &mut Window,
8577 cx: &mut Context<Self>,
8578 ) {
8579 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8580 s.move_heads_with(|map, head, _| {
8581 (
8582 movement::previous_subword_start(map, head),
8583 SelectionGoal::None,
8584 )
8585 });
8586 })
8587 }
8588
8589 pub fn delete_to_previous_word_start(
8590 &mut self,
8591 action: &DeleteToPreviousWordStart,
8592 window: &mut Window,
8593 cx: &mut Context<Self>,
8594 ) {
8595 self.transact(window, cx, |this, window, cx| {
8596 this.select_autoclose_pair(window, cx);
8597 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8598 let line_mode = s.line_mode;
8599 s.move_with(|map, selection| {
8600 if selection.is_empty() && !line_mode {
8601 let cursor = if action.ignore_newlines {
8602 movement::previous_word_start(map, selection.head())
8603 } else {
8604 movement::previous_word_start_or_newline(map, selection.head())
8605 };
8606 selection.set_head(cursor, SelectionGoal::None);
8607 }
8608 });
8609 });
8610 this.insert("", window, cx);
8611 });
8612 }
8613
8614 pub fn delete_to_previous_subword_start(
8615 &mut self,
8616 _: &DeleteToPreviousSubwordStart,
8617 window: &mut Window,
8618 cx: &mut Context<Self>,
8619 ) {
8620 self.transact(window, cx, |this, window, cx| {
8621 this.select_autoclose_pair(window, cx);
8622 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8623 let line_mode = s.line_mode;
8624 s.move_with(|map, selection| {
8625 if selection.is_empty() && !line_mode {
8626 let cursor = movement::previous_subword_start(map, selection.head());
8627 selection.set_head(cursor, SelectionGoal::None);
8628 }
8629 });
8630 });
8631 this.insert("", window, cx);
8632 });
8633 }
8634
8635 pub fn move_to_next_word_end(
8636 &mut self,
8637 _: &MoveToNextWordEnd,
8638 window: &mut Window,
8639 cx: &mut Context<Self>,
8640 ) {
8641 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8642 s.move_cursors_with(|map, head, _| {
8643 (movement::next_word_end(map, head), SelectionGoal::None)
8644 });
8645 })
8646 }
8647
8648 pub fn move_to_next_subword_end(
8649 &mut self,
8650 _: &MoveToNextSubwordEnd,
8651 window: &mut Window,
8652 cx: &mut Context<Self>,
8653 ) {
8654 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8655 s.move_cursors_with(|map, head, _| {
8656 (movement::next_subword_end(map, head), SelectionGoal::None)
8657 });
8658 })
8659 }
8660
8661 pub fn select_to_next_word_end(
8662 &mut self,
8663 _: &SelectToNextWordEnd,
8664 window: &mut Window,
8665 cx: &mut Context<Self>,
8666 ) {
8667 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8668 s.move_heads_with(|map, head, _| {
8669 (movement::next_word_end(map, head), SelectionGoal::None)
8670 });
8671 })
8672 }
8673
8674 pub fn select_to_next_subword_end(
8675 &mut self,
8676 _: &SelectToNextSubwordEnd,
8677 window: &mut Window,
8678 cx: &mut Context<Self>,
8679 ) {
8680 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8681 s.move_heads_with(|map, head, _| {
8682 (movement::next_subword_end(map, head), SelectionGoal::None)
8683 });
8684 })
8685 }
8686
8687 pub fn delete_to_next_word_end(
8688 &mut self,
8689 action: &DeleteToNextWordEnd,
8690 window: &mut Window,
8691 cx: &mut Context<Self>,
8692 ) {
8693 self.transact(window, cx, |this, window, cx| {
8694 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8695 let line_mode = s.line_mode;
8696 s.move_with(|map, selection| {
8697 if selection.is_empty() && !line_mode {
8698 let cursor = if action.ignore_newlines {
8699 movement::next_word_end(map, selection.head())
8700 } else {
8701 movement::next_word_end_or_newline(map, selection.head())
8702 };
8703 selection.set_head(cursor, SelectionGoal::None);
8704 }
8705 });
8706 });
8707 this.insert("", window, cx);
8708 });
8709 }
8710
8711 pub fn delete_to_next_subword_end(
8712 &mut self,
8713 _: &DeleteToNextSubwordEnd,
8714 window: &mut Window,
8715 cx: &mut Context<Self>,
8716 ) {
8717 self.transact(window, cx, |this, window, cx| {
8718 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8719 s.move_with(|map, selection| {
8720 if selection.is_empty() {
8721 let cursor = movement::next_subword_end(map, selection.head());
8722 selection.set_head(cursor, SelectionGoal::None);
8723 }
8724 });
8725 });
8726 this.insert("", window, cx);
8727 });
8728 }
8729
8730 pub fn move_to_beginning_of_line(
8731 &mut self,
8732 action: &MoveToBeginningOfLine,
8733 window: &mut Window,
8734 cx: &mut Context<Self>,
8735 ) {
8736 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8737 s.move_cursors_with(|map, head, _| {
8738 (
8739 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8740 SelectionGoal::None,
8741 )
8742 });
8743 })
8744 }
8745
8746 pub fn select_to_beginning_of_line(
8747 &mut self,
8748 action: &SelectToBeginningOfLine,
8749 window: &mut Window,
8750 cx: &mut Context<Self>,
8751 ) {
8752 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8753 s.move_heads_with(|map, head, _| {
8754 (
8755 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8756 SelectionGoal::None,
8757 )
8758 });
8759 });
8760 }
8761
8762 pub fn delete_to_beginning_of_line(
8763 &mut self,
8764 _: &DeleteToBeginningOfLine,
8765 window: &mut Window,
8766 cx: &mut Context<Self>,
8767 ) {
8768 self.transact(window, cx, |this, window, cx| {
8769 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8770 s.move_with(|_, selection| {
8771 selection.reversed = true;
8772 });
8773 });
8774
8775 this.select_to_beginning_of_line(
8776 &SelectToBeginningOfLine {
8777 stop_at_soft_wraps: false,
8778 },
8779 window,
8780 cx,
8781 );
8782 this.backspace(&Backspace, window, cx);
8783 });
8784 }
8785
8786 pub fn move_to_end_of_line(
8787 &mut self,
8788 action: &MoveToEndOfLine,
8789 window: &mut Window,
8790 cx: &mut Context<Self>,
8791 ) {
8792 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8793 s.move_cursors_with(|map, head, _| {
8794 (
8795 movement::line_end(map, head, action.stop_at_soft_wraps),
8796 SelectionGoal::None,
8797 )
8798 });
8799 })
8800 }
8801
8802 pub fn select_to_end_of_line(
8803 &mut self,
8804 action: &SelectToEndOfLine,
8805 window: &mut Window,
8806 cx: &mut Context<Self>,
8807 ) {
8808 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8809 s.move_heads_with(|map, head, _| {
8810 (
8811 movement::line_end(map, head, action.stop_at_soft_wraps),
8812 SelectionGoal::None,
8813 )
8814 });
8815 })
8816 }
8817
8818 pub fn delete_to_end_of_line(
8819 &mut self,
8820 _: &DeleteToEndOfLine,
8821 window: &mut Window,
8822 cx: &mut Context<Self>,
8823 ) {
8824 self.transact(window, cx, |this, window, cx| {
8825 this.select_to_end_of_line(
8826 &SelectToEndOfLine {
8827 stop_at_soft_wraps: false,
8828 },
8829 window,
8830 cx,
8831 );
8832 this.delete(&Delete, window, cx);
8833 });
8834 }
8835
8836 pub fn cut_to_end_of_line(
8837 &mut self,
8838 _: &CutToEndOfLine,
8839 window: &mut Window,
8840 cx: &mut Context<Self>,
8841 ) {
8842 self.transact(window, cx, |this, window, cx| {
8843 this.select_to_end_of_line(
8844 &SelectToEndOfLine {
8845 stop_at_soft_wraps: false,
8846 },
8847 window,
8848 cx,
8849 );
8850 this.cut(&Cut, window, cx);
8851 });
8852 }
8853
8854 pub fn move_to_start_of_paragraph(
8855 &mut self,
8856 _: &MoveToStartOfParagraph,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) {
8860 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8861 cx.propagate();
8862 return;
8863 }
8864
8865 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8866 s.move_with(|map, selection| {
8867 selection.collapse_to(
8868 movement::start_of_paragraph(map, selection.head(), 1),
8869 SelectionGoal::None,
8870 )
8871 });
8872 })
8873 }
8874
8875 pub fn move_to_end_of_paragraph(
8876 &mut self,
8877 _: &MoveToEndOfParagraph,
8878 window: &mut Window,
8879 cx: &mut Context<Self>,
8880 ) {
8881 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8882 cx.propagate();
8883 return;
8884 }
8885
8886 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8887 s.move_with(|map, selection| {
8888 selection.collapse_to(
8889 movement::end_of_paragraph(map, selection.head(), 1),
8890 SelectionGoal::None,
8891 )
8892 });
8893 })
8894 }
8895
8896 pub fn select_to_start_of_paragraph(
8897 &mut self,
8898 _: &SelectToStartOfParagraph,
8899 window: &mut Window,
8900 cx: &mut Context<Self>,
8901 ) {
8902 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8903 cx.propagate();
8904 return;
8905 }
8906
8907 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8908 s.move_heads_with(|map, head, _| {
8909 (
8910 movement::start_of_paragraph(map, head, 1),
8911 SelectionGoal::None,
8912 )
8913 });
8914 })
8915 }
8916
8917 pub fn select_to_end_of_paragraph(
8918 &mut self,
8919 _: &SelectToEndOfParagraph,
8920 window: &mut Window,
8921 cx: &mut Context<Self>,
8922 ) {
8923 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8924 cx.propagate();
8925 return;
8926 }
8927
8928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8929 s.move_heads_with(|map, head, _| {
8930 (
8931 movement::end_of_paragraph(map, head, 1),
8932 SelectionGoal::None,
8933 )
8934 });
8935 })
8936 }
8937
8938 pub fn move_to_beginning(
8939 &mut self,
8940 _: &MoveToBeginning,
8941 window: &mut Window,
8942 cx: &mut Context<Self>,
8943 ) {
8944 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8945 cx.propagate();
8946 return;
8947 }
8948
8949 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8950 s.select_ranges(vec![0..0]);
8951 });
8952 }
8953
8954 pub fn select_to_beginning(
8955 &mut self,
8956 _: &SelectToBeginning,
8957 window: &mut Window,
8958 cx: &mut Context<Self>,
8959 ) {
8960 let mut selection = self.selections.last::<Point>(cx);
8961 selection.set_head(Point::zero(), SelectionGoal::None);
8962
8963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8964 s.select(vec![selection]);
8965 });
8966 }
8967
8968 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8969 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8970 cx.propagate();
8971 return;
8972 }
8973
8974 let cursor = self.buffer.read(cx).read(cx).len();
8975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8976 s.select_ranges(vec![cursor..cursor])
8977 });
8978 }
8979
8980 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8981 self.nav_history = nav_history;
8982 }
8983
8984 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8985 self.nav_history.as_ref()
8986 }
8987
8988 fn push_to_nav_history(
8989 &mut self,
8990 cursor_anchor: Anchor,
8991 new_position: Option<Point>,
8992 cx: &mut Context<Self>,
8993 ) {
8994 if let Some(nav_history) = self.nav_history.as_mut() {
8995 let buffer = self.buffer.read(cx).read(cx);
8996 let cursor_position = cursor_anchor.to_point(&buffer);
8997 let scroll_state = self.scroll_manager.anchor();
8998 let scroll_top_row = scroll_state.top_row(&buffer);
8999 drop(buffer);
9000
9001 if let Some(new_position) = new_position {
9002 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9003 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9004 return;
9005 }
9006 }
9007
9008 nav_history.push(
9009 Some(NavigationData {
9010 cursor_anchor,
9011 cursor_position,
9012 scroll_anchor: scroll_state,
9013 scroll_top_row,
9014 }),
9015 cx,
9016 );
9017 }
9018 }
9019
9020 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9021 let buffer = self.buffer.read(cx).snapshot(cx);
9022 let mut selection = self.selections.first::<usize>(cx);
9023 selection.set_head(buffer.len(), SelectionGoal::None);
9024 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9025 s.select(vec![selection]);
9026 });
9027 }
9028
9029 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9030 let end = self.buffer.read(cx).read(cx).len();
9031 self.change_selections(None, window, cx, |s| {
9032 s.select_ranges(vec![0..end]);
9033 });
9034 }
9035
9036 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9037 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9038 let mut selections = self.selections.all::<Point>(cx);
9039 let max_point = display_map.buffer_snapshot.max_point();
9040 for selection in &mut selections {
9041 let rows = selection.spanned_rows(true, &display_map);
9042 selection.start = Point::new(rows.start.0, 0);
9043 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9044 selection.reversed = false;
9045 }
9046 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9047 s.select(selections);
9048 });
9049 }
9050
9051 pub fn split_selection_into_lines(
9052 &mut self,
9053 _: &SplitSelectionIntoLines,
9054 window: &mut Window,
9055 cx: &mut Context<Self>,
9056 ) {
9057 let mut to_unfold = Vec::new();
9058 let mut new_selection_ranges = Vec::new();
9059 {
9060 let selections = self.selections.all::<Point>(cx);
9061 let buffer = self.buffer.read(cx).read(cx);
9062 for selection in selections {
9063 for row in selection.start.row..selection.end.row {
9064 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9065 new_selection_ranges.push(cursor..cursor);
9066 }
9067 new_selection_ranges.push(selection.end..selection.end);
9068 to_unfold.push(selection.start..selection.end);
9069 }
9070 }
9071 self.unfold_ranges(&to_unfold, true, true, cx);
9072 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9073 s.select_ranges(new_selection_ranges);
9074 });
9075 }
9076
9077 pub fn add_selection_above(
9078 &mut self,
9079 _: &AddSelectionAbove,
9080 window: &mut Window,
9081 cx: &mut Context<Self>,
9082 ) {
9083 self.add_selection(true, window, cx);
9084 }
9085
9086 pub fn add_selection_below(
9087 &mut self,
9088 _: &AddSelectionBelow,
9089 window: &mut Window,
9090 cx: &mut Context<Self>,
9091 ) {
9092 self.add_selection(false, window, cx);
9093 }
9094
9095 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9096 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9097 let mut selections = self.selections.all::<Point>(cx);
9098 let text_layout_details = self.text_layout_details(window);
9099 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9100 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9101 let range = oldest_selection.display_range(&display_map).sorted();
9102
9103 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9104 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9105 let positions = start_x.min(end_x)..start_x.max(end_x);
9106
9107 selections.clear();
9108 let mut stack = Vec::new();
9109 for row in range.start.row().0..=range.end.row().0 {
9110 if let Some(selection) = self.selections.build_columnar_selection(
9111 &display_map,
9112 DisplayRow(row),
9113 &positions,
9114 oldest_selection.reversed,
9115 &text_layout_details,
9116 ) {
9117 stack.push(selection.id);
9118 selections.push(selection);
9119 }
9120 }
9121
9122 if above {
9123 stack.reverse();
9124 }
9125
9126 AddSelectionsState { above, stack }
9127 });
9128
9129 let last_added_selection = *state.stack.last().unwrap();
9130 let mut new_selections = Vec::new();
9131 if above == state.above {
9132 let end_row = if above {
9133 DisplayRow(0)
9134 } else {
9135 display_map.max_point().row()
9136 };
9137
9138 'outer: for selection in selections {
9139 if selection.id == last_added_selection {
9140 let range = selection.display_range(&display_map).sorted();
9141 debug_assert_eq!(range.start.row(), range.end.row());
9142 let mut row = range.start.row();
9143 let positions =
9144 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9145 px(start)..px(end)
9146 } else {
9147 let start_x =
9148 display_map.x_for_display_point(range.start, &text_layout_details);
9149 let end_x =
9150 display_map.x_for_display_point(range.end, &text_layout_details);
9151 start_x.min(end_x)..start_x.max(end_x)
9152 };
9153
9154 while row != end_row {
9155 if above {
9156 row.0 -= 1;
9157 } else {
9158 row.0 += 1;
9159 }
9160
9161 if let Some(new_selection) = self.selections.build_columnar_selection(
9162 &display_map,
9163 row,
9164 &positions,
9165 selection.reversed,
9166 &text_layout_details,
9167 ) {
9168 state.stack.push(new_selection.id);
9169 if above {
9170 new_selections.push(new_selection);
9171 new_selections.push(selection);
9172 } else {
9173 new_selections.push(selection);
9174 new_selections.push(new_selection);
9175 }
9176
9177 continue 'outer;
9178 }
9179 }
9180 }
9181
9182 new_selections.push(selection);
9183 }
9184 } else {
9185 new_selections = selections;
9186 new_selections.retain(|s| s.id != last_added_selection);
9187 state.stack.pop();
9188 }
9189
9190 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9191 s.select(new_selections);
9192 });
9193 if state.stack.len() > 1 {
9194 self.add_selections_state = Some(state);
9195 }
9196 }
9197
9198 pub fn select_next_match_internal(
9199 &mut self,
9200 display_map: &DisplaySnapshot,
9201 replace_newest: bool,
9202 autoscroll: Option<Autoscroll>,
9203 window: &mut Window,
9204 cx: &mut Context<Self>,
9205 ) -> Result<()> {
9206 fn select_next_match_ranges(
9207 this: &mut Editor,
9208 range: Range<usize>,
9209 replace_newest: bool,
9210 auto_scroll: Option<Autoscroll>,
9211 window: &mut Window,
9212 cx: &mut Context<Editor>,
9213 ) {
9214 this.unfold_ranges(&[range.clone()], false, true, cx);
9215 this.change_selections(auto_scroll, window, cx, |s| {
9216 if replace_newest {
9217 s.delete(s.newest_anchor().id);
9218 }
9219 s.insert_range(range.clone());
9220 });
9221 }
9222
9223 let buffer = &display_map.buffer_snapshot;
9224 let mut selections = self.selections.all::<usize>(cx);
9225 if let Some(mut select_next_state) = self.select_next_state.take() {
9226 let query = &select_next_state.query;
9227 if !select_next_state.done {
9228 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9229 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9230 let mut next_selected_range = None;
9231
9232 let bytes_after_last_selection =
9233 buffer.bytes_in_range(last_selection.end..buffer.len());
9234 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9235 let query_matches = query
9236 .stream_find_iter(bytes_after_last_selection)
9237 .map(|result| (last_selection.end, result))
9238 .chain(
9239 query
9240 .stream_find_iter(bytes_before_first_selection)
9241 .map(|result| (0, result)),
9242 );
9243
9244 for (start_offset, query_match) in query_matches {
9245 let query_match = query_match.unwrap(); // can only fail due to I/O
9246 let offset_range =
9247 start_offset + query_match.start()..start_offset + query_match.end();
9248 let display_range = offset_range.start.to_display_point(display_map)
9249 ..offset_range.end.to_display_point(display_map);
9250
9251 if !select_next_state.wordwise
9252 || (!movement::is_inside_word(display_map, display_range.start)
9253 && !movement::is_inside_word(display_map, display_range.end))
9254 {
9255 // TODO: This is n^2, because we might check all the selections
9256 if !selections
9257 .iter()
9258 .any(|selection| selection.range().overlaps(&offset_range))
9259 {
9260 next_selected_range = Some(offset_range);
9261 break;
9262 }
9263 }
9264 }
9265
9266 if let Some(next_selected_range) = next_selected_range {
9267 select_next_match_ranges(
9268 self,
9269 next_selected_range,
9270 replace_newest,
9271 autoscroll,
9272 window,
9273 cx,
9274 );
9275 } else {
9276 select_next_state.done = true;
9277 }
9278 }
9279
9280 self.select_next_state = Some(select_next_state);
9281 } else {
9282 let mut only_carets = true;
9283 let mut same_text_selected = true;
9284 let mut selected_text = None;
9285
9286 let mut selections_iter = selections.iter().peekable();
9287 while let Some(selection) = selections_iter.next() {
9288 if selection.start != selection.end {
9289 only_carets = false;
9290 }
9291
9292 if same_text_selected {
9293 if selected_text.is_none() {
9294 selected_text =
9295 Some(buffer.text_for_range(selection.range()).collect::<String>());
9296 }
9297
9298 if let Some(next_selection) = selections_iter.peek() {
9299 if next_selection.range().len() == selection.range().len() {
9300 let next_selected_text = buffer
9301 .text_for_range(next_selection.range())
9302 .collect::<String>();
9303 if Some(next_selected_text) != selected_text {
9304 same_text_selected = false;
9305 selected_text = None;
9306 }
9307 } else {
9308 same_text_selected = false;
9309 selected_text = None;
9310 }
9311 }
9312 }
9313 }
9314
9315 if only_carets {
9316 for selection in &mut selections {
9317 let word_range = movement::surrounding_word(
9318 display_map,
9319 selection.start.to_display_point(display_map),
9320 );
9321 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9322 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9323 selection.goal = SelectionGoal::None;
9324 selection.reversed = false;
9325 select_next_match_ranges(
9326 self,
9327 selection.start..selection.end,
9328 replace_newest,
9329 autoscroll,
9330 window,
9331 cx,
9332 );
9333 }
9334
9335 if selections.len() == 1 {
9336 let selection = selections
9337 .last()
9338 .expect("ensured that there's only one selection");
9339 let query = buffer
9340 .text_for_range(selection.start..selection.end)
9341 .collect::<String>();
9342 let is_empty = query.is_empty();
9343 let select_state = SelectNextState {
9344 query: AhoCorasick::new(&[query])?,
9345 wordwise: true,
9346 done: is_empty,
9347 };
9348 self.select_next_state = Some(select_state);
9349 } else {
9350 self.select_next_state = None;
9351 }
9352 } else if let Some(selected_text) = selected_text {
9353 self.select_next_state = Some(SelectNextState {
9354 query: AhoCorasick::new(&[selected_text])?,
9355 wordwise: false,
9356 done: false,
9357 });
9358 self.select_next_match_internal(
9359 display_map,
9360 replace_newest,
9361 autoscroll,
9362 window,
9363 cx,
9364 )?;
9365 }
9366 }
9367 Ok(())
9368 }
9369
9370 pub fn select_all_matches(
9371 &mut self,
9372 _action: &SelectAllMatches,
9373 window: &mut Window,
9374 cx: &mut Context<Self>,
9375 ) -> Result<()> {
9376 self.push_to_selection_history();
9377 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9378
9379 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9380 let Some(select_next_state) = self.select_next_state.as_mut() else {
9381 return Ok(());
9382 };
9383 if select_next_state.done {
9384 return Ok(());
9385 }
9386
9387 let mut new_selections = self.selections.all::<usize>(cx);
9388
9389 let buffer = &display_map.buffer_snapshot;
9390 let query_matches = select_next_state
9391 .query
9392 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9393
9394 for query_match in query_matches {
9395 let query_match = query_match.unwrap(); // can only fail due to I/O
9396 let offset_range = query_match.start()..query_match.end();
9397 let display_range = offset_range.start.to_display_point(&display_map)
9398 ..offset_range.end.to_display_point(&display_map);
9399
9400 if !select_next_state.wordwise
9401 || (!movement::is_inside_word(&display_map, display_range.start)
9402 && !movement::is_inside_word(&display_map, display_range.end))
9403 {
9404 self.selections.change_with(cx, |selections| {
9405 new_selections.push(Selection {
9406 id: selections.new_selection_id(),
9407 start: offset_range.start,
9408 end: offset_range.end,
9409 reversed: false,
9410 goal: SelectionGoal::None,
9411 });
9412 });
9413 }
9414 }
9415
9416 new_selections.sort_by_key(|selection| selection.start);
9417 let mut ix = 0;
9418 while ix + 1 < new_selections.len() {
9419 let current_selection = &new_selections[ix];
9420 let next_selection = &new_selections[ix + 1];
9421 if current_selection.range().overlaps(&next_selection.range()) {
9422 if current_selection.id < next_selection.id {
9423 new_selections.remove(ix + 1);
9424 } else {
9425 new_selections.remove(ix);
9426 }
9427 } else {
9428 ix += 1;
9429 }
9430 }
9431
9432 let reversed = self.selections.oldest::<usize>(cx).reversed;
9433
9434 for selection in new_selections.iter_mut() {
9435 selection.reversed = reversed;
9436 }
9437
9438 select_next_state.done = true;
9439 self.unfold_ranges(
9440 &new_selections
9441 .iter()
9442 .map(|selection| selection.range())
9443 .collect::<Vec<_>>(),
9444 false,
9445 false,
9446 cx,
9447 );
9448 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9449 selections.select(new_selections)
9450 });
9451
9452 Ok(())
9453 }
9454
9455 pub fn select_next(
9456 &mut self,
9457 action: &SelectNext,
9458 window: &mut Window,
9459 cx: &mut Context<Self>,
9460 ) -> Result<()> {
9461 self.push_to_selection_history();
9462 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9463 self.select_next_match_internal(
9464 &display_map,
9465 action.replace_newest,
9466 Some(Autoscroll::newest()),
9467 window,
9468 cx,
9469 )?;
9470 Ok(())
9471 }
9472
9473 pub fn select_previous(
9474 &mut self,
9475 action: &SelectPrevious,
9476 window: &mut Window,
9477 cx: &mut Context<Self>,
9478 ) -> Result<()> {
9479 self.push_to_selection_history();
9480 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9481 let buffer = &display_map.buffer_snapshot;
9482 let mut selections = self.selections.all::<usize>(cx);
9483 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9484 let query = &select_prev_state.query;
9485 if !select_prev_state.done {
9486 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9487 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9488 let mut next_selected_range = None;
9489 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9490 let bytes_before_last_selection =
9491 buffer.reversed_bytes_in_range(0..last_selection.start);
9492 let bytes_after_first_selection =
9493 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9494 let query_matches = query
9495 .stream_find_iter(bytes_before_last_selection)
9496 .map(|result| (last_selection.start, result))
9497 .chain(
9498 query
9499 .stream_find_iter(bytes_after_first_selection)
9500 .map(|result| (buffer.len(), result)),
9501 );
9502 for (end_offset, query_match) in query_matches {
9503 let query_match = query_match.unwrap(); // can only fail due to I/O
9504 let offset_range =
9505 end_offset - query_match.end()..end_offset - query_match.start();
9506 let display_range = offset_range.start.to_display_point(&display_map)
9507 ..offset_range.end.to_display_point(&display_map);
9508
9509 if !select_prev_state.wordwise
9510 || (!movement::is_inside_word(&display_map, display_range.start)
9511 && !movement::is_inside_word(&display_map, display_range.end))
9512 {
9513 next_selected_range = Some(offset_range);
9514 break;
9515 }
9516 }
9517
9518 if let Some(next_selected_range) = next_selected_range {
9519 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9520 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9521 if action.replace_newest {
9522 s.delete(s.newest_anchor().id);
9523 }
9524 s.insert_range(next_selected_range);
9525 });
9526 } else {
9527 select_prev_state.done = true;
9528 }
9529 }
9530
9531 self.select_prev_state = Some(select_prev_state);
9532 } else {
9533 let mut only_carets = true;
9534 let mut same_text_selected = true;
9535 let mut selected_text = None;
9536
9537 let mut selections_iter = selections.iter().peekable();
9538 while let Some(selection) = selections_iter.next() {
9539 if selection.start != selection.end {
9540 only_carets = false;
9541 }
9542
9543 if same_text_selected {
9544 if selected_text.is_none() {
9545 selected_text =
9546 Some(buffer.text_for_range(selection.range()).collect::<String>());
9547 }
9548
9549 if let Some(next_selection) = selections_iter.peek() {
9550 if next_selection.range().len() == selection.range().len() {
9551 let next_selected_text = buffer
9552 .text_for_range(next_selection.range())
9553 .collect::<String>();
9554 if Some(next_selected_text) != selected_text {
9555 same_text_selected = false;
9556 selected_text = None;
9557 }
9558 } else {
9559 same_text_selected = false;
9560 selected_text = None;
9561 }
9562 }
9563 }
9564 }
9565
9566 if only_carets {
9567 for selection in &mut selections {
9568 let word_range = movement::surrounding_word(
9569 &display_map,
9570 selection.start.to_display_point(&display_map),
9571 );
9572 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9573 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9574 selection.goal = SelectionGoal::None;
9575 selection.reversed = false;
9576 }
9577 if selections.len() == 1 {
9578 let selection = selections
9579 .last()
9580 .expect("ensured that there's only one selection");
9581 let query = buffer
9582 .text_for_range(selection.start..selection.end)
9583 .collect::<String>();
9584 let is_empty = query.is_empty();
9585 let select_state = SelectNextState {
9586 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9587 wordwise: true,
9588 done: is_empty,
9589 };
9590 self.select_prev_state = Some(select_state);
9591 } else {
9592 self.select_prev_state = None;
9593 }
9594
9595 self.unfold_ranges(
9596 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9597 false,
9598 true,
9599 cx,
9600 );
9601 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9602 s.select(selections);
9603 });
9604 } else if let Some(selected_text) = selected_text {
9605 self.select_prev_state = Some(SelectNextState {
9606 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9607 wordwise: false,
9608 done: false,
9609 });
9610 self.select_previous(action, window, cx)?;
9611 }
9612 }
9613 Ok(())
9614 }
9615
9616 pub fn toggle_comments(
9617 &mut self,
9618 action: &ToggleComments,
9619 window: &mut Window,
9620 cx: &mut Context<Self>,
9621 ) {
9622 if self.read_only(cx) {
9623 return;
9624 }
9625 let text_layout_details = &self.text_layout_details(window);
9626 self.transact(window, cx, |this, window, cx| {
9627 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9628 let mut edits = Vec::new();
9629 let mut selection_edit_ranges = Vec::new();
9630 let mut last_toggled_row = None;
9631 let snapshot = this.buffer.read(cx).read(cx);
9632 let empty_str: Arc<str> = Arc::default();
9633 let mut suffixes_inserted = Vec::new();
9634 let ignore_indent = action.ignore_indent;
9635
9636 fn comment_prefix_range(
9637 snapshot: &MultiBufferSnapshot,
9638 row: MultiBufferRow,
9639 comment_prefix: &str,
9640 comment_prefix_whitespace: &str,
9641 ignore_indent: bool,
9642 ) -> Range<Point> {
9643 let indent_size = if ignore_indent {
9644 0
9645 } else {
9646 snapshot.indent_size_for_line(row).len
9647 };
9648
9649 let start = Point::new(row.0, indent_size);
9650
9651 let mut line_bytes = snapshot
9652 .bytes_in_range(start..snapshot.max_point())
9653 .flatten()
9654 .copied();
9655
9656 // If this line currently begins with the line comment prefix, then record
9657 // the range containing the prefix.
9658 if line_bytes
9659 .by_ref()
9660 .take(comment_prefix.len())
9661 .eq(comment_prefix.bytes())
9662 {
9663 // Include any whitespace that matches the comment prefix.
9664 let matching_whitespace_len = line_bytes
9665 .zip(comment_prefix_whitespace.bytes())
9666 .take_while(|(a, b)| a == b)
9667 .count() as u32;
9668 let end = Point::new(
9669 start.row,
9670 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9671 );
9672 start..end
9673 } else {
9674 start..start
9675 }
9676 }
9677
9678 fn comment_suffix_range(
9679 snapshot: &MultiBufferSnapshot,
9680 row: MultiBufferRow,
9681 comment_suffix: &str,
9682 comment_suffix_has_leading_space: bool,
9683 ) -> Range<Point> {
9684 let end = Point::new(row.0, snapshot.line_len(row));
9685 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9686
9687 let mut line_end_bytes = snapshot
9688 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9689 .flatten()
9690 .copied();
9691
9692 let leading_space_len = if suffix_start_column > 0
9693 && line_end_bytes.next() == Some(b' ')
9694 && comment_suffix_has_leading_space
9695 {
9696 1
9697 } else {
9698 0
9699 };
9700
9701 // If this line currently begins with the line comment prefix, then record
9702 // the range containing the prefix.
9703 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9704 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9705 start..end
9706 } else {
9707 end..end
9708 }
9709 }
9710
9711 // TODO: Handle selections that cross excerpts
9712 for selection in &mut selections {
9713 let start_column = snapshot
9714 .indent_size_for_line(MultiBufferRow(selection.start.row))
9715 .len;
9716 let language = if let Some(language) =
9717 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9718 {
9719 language
9720 } else {
9721 continue;
9722 };
9723
9724 selection_edit_ranges.clear();
9725
9726 // If multiple selections contain a given row, avoid processing that
9727 // row more than once.
9728 let mut start_row = MultiBufferRow(selection.start.row);
9729 if last_toggled_row == Some(start_row) {
9730 start_row = start_row.next_row();
9731 }
9732 let end_row =
9733 if selection.end.row > selection.start.row && selection.end.column == 0 {
9734 MultiBufferRow(selection.end.row - 1)
9735 } else {
9736 MultiBufferRow(selection.end.row)
9737 };
9738 last_toggled_row = Some(end_row);
9739
9740 if start_row > end_row {
9741 continue;
9742 }
9743
9744 // If the language has line comments, toggle those.
9745 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9746
9747 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9748 if ignore_indent {
9749 full_comment_prefixes = full_comment_prefixes
9750 .into_iter()
9751 .map(|s| Arc::from(s.trim_end()))
9752 .collect();
9753 }
9754
9755 if !full_comment_prefixes.is_empty() {
9756 let first_prefix = full_comment_prefixes
9757 .first()
9758 .expect("prefixes is non-empty");
9759 let prefix_trimmed_lengths = full_comment_prefixes
9760 .iter()
9761 .map(|p| p.trim_end_matches(' ').len())
9762 .collect::<SmallVec<[usize; 4]>>();
9763
9764 let mut all_selection_lines_are_comments = true;
9765
9766 for row in start_row.0..=end_row.0 {
9767 let row = MultiBufferRow(row);
9768 if start_row < end_row && snapshot.is_line_blank(row) {
9769 continue;
9770 }
9771
9772 let prefix_range = full_comment_prefixes
9773 .iter()
9774 .zip(prefix_trimmed_lengths.iter().copied())
9775 .map(|(prefix, trimmed_prefix_len)| {
9776 comment_prefix_range(
9777 snapshot.deref(),
9778 row,
9779 &prefix[..trimmed_prefix_len],
9780 &prefix[trimmed_prefix_len..],
9781 ignore_indent,
9782 )
9783 })
9784 .max_by_key(|range| range.end.column - range.start.column)
9785 .expect("prefixes is non-empty");
9786
9787 if prefix_range.is_empty() {
9788 all_selection_lines_are_comments = false;
9789 }
9790
9791 selection_edit_ranges.push(prefix_range);
9792 }
9793
9794 if all_selection_lines_are_comments {
9795 edits.extend(
9796 selection_edit_ranges
9797 .iter()
9798 .cloned()
9799 .map(|range| (range, empty_str.clone())),
9800 );
9801 } else {
9802 let min_column = selection_edit_ranges
9803 .iter()
9804 .map(|range| range.start.column)
9805 .min()
9806 .unwrap_or(0);
9807 edits.extend(selection_edit_ranges.iter().map(|range| {
9808 let position = Point::new(range.start.row, min_column);
9809 (position..position, first_prefix.clone())
9810 }));
9811 }
9812 } else if let Some((full_comment_prefix, comment_suffix)) =
9813 language.block_comment_delimiters()
9814 {
9815 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9816 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9817 let prefix_range = comment_prefix_range(
9818 snapshot.deref(),
9819 start_row,
9820 comment_prefix,
9821 comment_prefix_whitespace,
9822 ignore_indent,
9823 );
9824 let suffix_range = comment_suffix_range(
9825 snapshot.deref(),
9826 end_row,
9827 comment_suffix.trim_start_matches(' '),
9828 comment_suffix.starts_with(' '),
9829 );
9830
9831 if prefix_range.is_empty() || suffix_range.is_empty() {
9832 edits.push((
9833 prefix_range.start..prefix_range.start,
9834 full_comment_prefix.clone(),
9835 ));
9836 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9837 suffixes_inserted.push((end_row, comment_suffix.len()));
9838 } else {
9839 edits.push((prefix_range, empty_str.clone()));
9840 edits.push((suffix_range, empty_str.clone()));
9841 }
9842 } else {
9843 continue;
9844 }
9845 }
9846
9847 drop(snapshot);
9848 this.buffer.update(cx, |buffer, cx| {
9849 buffer.edit(edits, None, cx);
9850 });
9851
9852 // Adjust selections so that they end before any comment suffixes that
9853 // were inserted.
9854 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9855 let mut selections = this.selections.all::<Point>(cx);
9856 let snapshot = this.buffer.read(cx).read(cx);
9857 for selection in &mut selections {
9858 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9859 match row.cmp(&MultiBufferRow(selection.end.row)) {
9860 Ordering::Less => {
9861 suffixes_inserted.next();
9862 continue;
9863 }
9864 Ordering::Greater => break,
9865 Ordering::Equal => {
9866 if selection.end.column == snapshot.line_len(row) {
9867 if selection.is_empty() {
9868 selection.start.column -= suffix_len as u32;
9869 }
9870 selection.end.column -= suffix_len as u32;
9871 }
9872 break;
9873 }
9874 }
9875 }
9876 }
9877
9878 drop(snapshot);
9879 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9880 s.select(selections)
9881 });
9882
9883 let selections = this.selections.all::<Point>(cx);
9884 let selections_on_single_row = selections.windows(2).all(|selections| {
9885 selections[0].start.row == selections[1].start.row
9886 && selections[0].end.row == selections[1].end.row
9887 && selections[0].start.row == selections[0].end.row
9888 });
9889 let selections_selecting = selections
9890 .iter()
9891 .any(|selection| selection.start != selection.end);
9892 let advance_downwards = action.advance_downwards
9893 && selections_on_single_row
9894 && !selections_selecting
9895 && !matches!(this.mode, EditorMode::SingleLine { .. });
9896
9897 if advance_downwards {
9898 let snapshot = this.buffer.read(cx).snapshot(cx);
9899
9900 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9901 s.move_cursors_with(|display_snapshot, display_point, _| {
9902 let mut point = display_point.to_point(display_snapshot);
9903 point.row += 1;
9904 point = snapshot.clip_point(point, Bias::Left);
9905 let display_point = point.to_display_point(display_snapshot);
9906 let goal = SelectionGoal::HorizontalPosition(
9907 display_snapshot
9908 .x_for_display_point(display_point, text_layout_details)
9909 .into(),
9910 );
9911 (display_point, goal)
9912 })
9913 });
9914 }
9915 });
9916 }
9917
9918 pub fn select_enclosing_symbol(
9919 &mut self,
9920 _: &SelectEnclosingSymbol,
9921 window: &mut Window,
9922 cx: &mut Context<Self>,
9923 ) {
9924 let buffer = self.buffer.read(cx).snapshot(cx);
9925 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9926
9927 fn update_selection(
9928 selection: &Selection<usize>,
9929 buffer_snap: &MultiBufferSnapshot,
9930 ) -> Option<Selection<usize>> {
9931 let cursor = selection.head();
9932 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9933 for symbol in symbols.iter().rev() {
9934 let start = symbol.range.start.to_offset(buffer_snap);
9935 let end = symbol.range.end.to_offset(buffer_snap);
9936 let new_range = start..end;
9937 if start < selection.start || end > selection.end {
9938 return Some(Selection {
9939 id: selection.id,
9940 start: new_range.start,
9941 end: new_range.end,
9942 goal: SelectionGoal::None,
9943 reversed: selection.reversed,
9944 });
9945 }
9946 }
9947 None
9948 }
9949
9950 let mut selected_larger_symbol = false;
9951 let new_selections = old_selections
9952 .iter()
9953 .map(|selection| match update_selection(selection, &buffer) {
9954 Some(new_selection) => {
9955 if new_selection.range() != selection.range() {
9956 selected_larger_symbol = true;
9957 }
9958 new_selection
9959 }
9960 None => selection.clone(),
9961 })
9962 .collect::<Vec<_>>();
9963
9964 if selected_larger_symbol {
9965 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9966 s.select(new_selections);
9967 });
9968 }
9969 }
9970
9971 pub fn select_larger_syntax_node(
9972 &mut self,
9973 _: &SelectLargerSyntaxNode,
9974 window: &mut Window,
9975 cx: &mut Context<Self>,
9976 ) {
9977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9978 let buffer = self.buffer.read(cx).snapshot(cx);
9979 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9980
9981 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9982 let mut selected_larger_node = false;
9983 let new_selections = old_selections
9984 .iter()
9985 .map(|selection| {
9986 let old_range = selection.start..selection.end;
9987 let mut new_range = old_range.clone();
9988 let mut new_node = None;
9989 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9990 {
9991 new_node = Some(node);
9992 new_range = containing_range;
9993 if !display_map.intersects_fold(new_range.start)
9994 && !display_map.intersects_fold(new_range.end)
9995 {
9996 break;
9997 }
9998 }
9999
10000 if let Some(node) = new_node {
10001 // Log the ancestor, to support using this action as a way to explore TreeSitter
10002 // nodes. Parent and grandparent are also logged because this operation will not
10003 // visit nodes that have the same range as their parent.
10004 log::info!("Node: {node:?}");
10005 let parent = node.parent();
10006 log::info!("Parent: {parent:?}");
10007 let grandparent = parent.and_then(|x| x.parent());
10008 log::info!("Grandparent: {grandparent:?}");
10009 }
10010
10011 selected_larger_node |= new_range != old_range;
10012 Selection {
10013 id: selection.id,
10014 start: new_range.start,
10015 end: new_range.end,
10016 goal: SelectionGoal::None,
10017 reversed: selection.reversed,
10018 }
10019 })
10020 .collect::<Vec<_>>();
10021
10022 if selected_larger_node {
10023 stack.push(old_selections);
10024 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10025 s.select(new_selections);
10026 });
10027 }
10028 self.select_larger_syntax_node_stack = stack;
10029 }
10030
10031 pub fn select_smaller_syntax_node(
10032 &mut self,
10033 _: &SelectSmallerSyntaxNode,
10034 window: &mut Window,
10035 cx: &mut Context<Self>,
10036 ) {
10037 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10038 if let Some(selections) = stack.pop() {
10039 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10040 s.select(selections.to_vec());
10041 });
10042 }
10043 self.select_larger_syntax_node_stack = stack;
10044 }
10045
10046 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10047 if !EditorSettings::get_global(cx).gutter.runnables {
10048 self.clear_tasks();
10049 return Task::ready(());
10050 }
10051 let project = self.project.as_ref().map(Entity::downgrade);
10052 cx.spawn_in(window, |this, mut cx| async move {
10053 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10054 let Some(project) = project.and_then(|p| p.upgrade()) else {
10055 return;
10056 };
10057 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10058 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10059 }) else {
10060 return;
10061 };
10062
10063 let hide_runnables = project
10064 .update(&mut cx, |project, cx| {
10065 // Do not display any test indicators in non-dev server remote projects.
10066 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10067 })
10068 .unwrap_or(true);
10069 if hide_runnables {
10070 return;
10071 }
10072 let new_rows =
10073 cx.background_executor()
10074 .spawn({
10075 let snapshot = display_snapshot.clone();
10076 async move {
10077 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10078 }
10079 })
10080 .await;
10081
10082 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10083 this.update(&mut cx, |this, _| {
10084 this.clear_tasks();
10085 for (key, value) in rows {
10086 this.insert_tasks(key, value);
10087 }
10088 })
10089 .ok();
10090 })
10091 }
10092 fn fetch_runnable_ranges(
10093 snapshot: &DisplaySnapshot,
10094 range: Range<Anchor>,
10095 ) -> Vec<language::RunnableRange> {
10096 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10097 }
10098
10099 fn runnable_rows(
10100 project: Entity<Project>,
10101 snapshot: DisplaySnapshot,
10102 runnable_ranges: Vec<RunnableRange>,
10103 mut cx: AsyncWindowContext,
10104 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10105 runnable_ranges
10106 .into_iter()
10107 .filter_map(|mut runnable| {
10108 let tasks = cx
10109 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10110 .ok()?;
10111 if tasks.is_empty() {
10112 return None;
10113 }
10114
10115 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10116
10117 let row = snapshot
10118 .buffer_snapshot
10119 .buffer_line_for_row(MultiBufferRow(point.row))?
10120 .1
10121 .start
10122 .row;
10123
10124 let context_range =
10125 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10126 Some((
10127 (runnable.buffer_id, row),
10128 RunnableTasks {
10129 templates: tasks,
10130 offset: MultiBufferOffset(runnable.run_range.start),
10131 context_range,
10132 column: point.column,
10133 extra_variables: runnable.extra_captures,
10134 },
10135 ))
10136 })
10137 .collect()
10138 }
10139
10140 fn templates_with_tags(
10141 project: &Entity<Project>,
10142 runnable: &mut Runnable,
10143 cx: &mut App,
10144 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10145 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10146 let (worktree_id, file) = project
10147 .buffer_for_id(runnable.buffer, cx)
10148 .and_then(|buffer| buffer.read(cx).file())
10149 .map(|file| (file.worktree_id(cx), file.clone()))
10150 .unzip();
10151
10152 (
10153 project.task_store().read(cx).task_inventory().cloned(),
10154 worktree_id,
10155 file,
10156 )
10157 });
10158
10159 let tags = mem::take(&mut runnable.tags);
10160 let mut tags: Vec<_> = tags
10161 .into_iter()
10162 .flat_map(|tag| {
10163 let tag = tag.0.clone();
10164 inventory
10165 .as_ref()
10166 .into_iter()
10167 .flat_map(|inventory| {
10168 inventory.read(cx).list_tasks(
10169 file.clone(),
10170 Some(runnable.language.clone()),
10171 worktree_id,
10172 cx,
10173 )
10174 })
10175 .filter(move |(_, template)| {
10176 template.tags.iter().any(|source_tag| source_tag == &tag)
10177 })
10178 })
10179 .sorted_by_key(|(kind, _)| kind.to_owned())
10180 .collect();
10181 if let Some((leading_tag_source, _)) = tags.first() {
10182 // Strongest source wins; if we have worktree tag binding, prefer that to
10183 // global and language bindings;
10184 // if we have a global binding, prefer that to language binding.
10185 let first_mismatch = tags
10186 .iter()
10187 .position(|(tag_source, _)| tag_source != leading_tag_source);
10188 if let Some(index) = first_mismatch {
10189 tags.truncate(index);
10190 }
10191 }
10192
10193 tags
10194 }
10195
10196 pub fn move_to_enclosing_bracket(
10197 &mut self,
10198 _: &MoveToEnclosingBracket,
10199 window: &mut Window,
10200 cx: &mut Context<Self>,
10201 ) {
10202 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10203 s.move_offsets_with(|snapshot, selection| {
10204 let Some(enclosing_bracket_ranges) =
10205 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10206 else {
10207 return;
10208 };
10209
10210 let mut best_length = usize::MAX;
10211 let mut best_inside = false;
10212 let mut best_in_bracket_range = false;
10213 let mut best_destination = None;
10214 for (open, close) in enclosing_bracket_ranges {
10215 let close = close.to_inclusive();
10216 let length = close.end() - open.start;
10217 let inside = selection.start >= open.end && selection.end <= *close.start();
10218 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10219 || close.contains(&selection.head());
10220
10221 // If best is next to a bracket and current isn't, skip
10222 if !in_bracket_range && best_in_bracket_range {
10223 continue;
10224 }
10225
10226 // Prefer smaller lengths unless best is inside and current isn't
10227 if length > best_length && (best_inside || !inside) {
10228 continue;
10229 }
10230
10231 best_length = length;
10232 best_inside = inside;
10233 best_in_bracket_range = in_bracket_range;
10234 best_destination = Some(
10235 if close.contains(&selection.start) && close.contains(&selection.end) {
10236 if inside {
10237 open.end
10238 } else {
10239 open.start
10240 }
10241 } else if inside {
10242 *close.start()
10243 } else {
10244 *close.end()
10245 },
10246 );
10247 }
10248
10249 if let Some(destination) = best_destination {
10250 selection.collapse_to(destination, SelectionGoal::None);
10251 }
10252 })
10253 });
10254 }
10255
10256 pub fn undo_selection(
10257 &mut self,
10258 _: &UndoSelection,
10259 window: &mut Window,
10260 cx: &mut Context<Self>,
10261 ) {
10262 self.end_selection(window, cx);
10263 self.selection_history.mode = SelectionHistoryMode::Undoing;
10264 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10265 self.change_selections(None, window, cx, |s| {
10266 s.select_anchors(entry.selections.to_vec())
10267 });
10268 self.select_next_state = entry.select_next_state;
10269 self.select_prev_state = entry.select_prev_state;
10270 self.add_selections_state = entry.add_selections_state;
10271 self.request_autoscroll(Autoscroll::newest(), cx);
10272 }
10273 self.selection_history.mode = SelectionHistoryMode::Normal;
10274 }
10275
10276 pub fn redo_selection(
10277 &mut self,
10278 _: &RedoSelection,
10279 window: &mut Window,
10280 cx: &mut Context<Self>,
10281 ) {
10282 self.end_selection(window, cx);
10283 self.selection_history.mode = SelectionHistoryMode::Redoing;
10284 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10285 self.change_selections(None, window, cx, |s| {
10286 s.select_anchors(entry.selections.to_vec())
10287 });
10288 self.select_next_state = entry.select_next_state;
10289 self.select_prev_state = entry.select_prev_state;
10290 self.add_selections_state = entry.add_selections_state;
10291 self.request_autoscroll(Autoscroll::newest(), cx);
10292 }
10293 self.selection_history.mode = SelectionHistoryMode::Normal;
10294 }
10295
10296 pub fn expand_excerpts(
10297 &mut self,
10298 action: &ExpandExcerpts,
10299 _: &mut Window,
10300 cx: &mut Context<Self>,
10301 ) {
10302 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10303 }
10304
10305 pub fn expand_excerpts_down(
10306 &mut self,
10307 action: &ExpandExcerptsDown,
10308 _: &mut Window,
10309 cx: &mut Context<Self>,
10310 ) {
10311 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10312 }
10313
10314 pub fn expand_excerpts_up(
10315 &mut self,
10316 action: &ExpandExcerptsUp,
10317 _: &mut Window,
10318 cx: &mut Context<Self>,
10319 ) {
10320 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10321 }
10322
10323 pub fn expand_excerpts_for_direction(
10324 &mut self,
10325 lines: u32,
10326 direction: ExpandExcerptDirection,
10327
10328 cx: &mut Context<Self>,
10329 ) {
10330 let selections = self.selections.disjoint_anchors();
10331
10332 let lines = if lines == 0 {
10333 EditorSettings::get_global(cx).expand_excerpt_lines
10334 } else {
10335 lines
10336 };
10337
10338 self.buffer.update(cx, |buffer, cx| {
10339 let snapshot = buffer.snapshot(cx);
10340 let mut excerpt_ids = selections
10341 .iter()
10342 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10343 .collect::<Vec<_>>();
10344 excerpt_ids.sort();
10345 excerpt_ids.dedup();
10346 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10347 })
10348 }
10349
10350 pub fn expand_excerpt(
10351 &mut self,
10352 excerpt: ExcerptId,
10353 direction: ExpandExcerptDirection,
10354 cx: &mut Context<Self>,
10355 ) {
10356 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10357 self.buffer.update(cx, |buffer, cx| {
10358 buffer.expand_excerpts([excerpt], lines, direction, cx)
10359 })
10360 }
10361
10362 pub fn go_to_singleton_buffer_point(
10363 &mut self,
10364 point: Point,
10365 window: &mut Window,
10366 cx: &mut Context<Self>,
10367 ) {
10368 self.go_to_singleton_buffer_range(point..point, window, cx);
10369 }
10370
10371 pub fn go_to_singleton_buffer_range(
10372 &mut self,
10373 range: Range<Point>,
10374 window: &mut Window,
10375 cx: &mut Context<Self>,
10376 ) {
10377 let multibuffer = self.buffer().read(cx);
10378 let Some(buffer) = multibuffer.as_singleton() else {
10379 return;
10380 };
10381 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10382 return;
10383 };
10384 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10385 return;
10386 };
10387 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10388 s.select_anchor_ranges([start..end])
10389 });
10390 }
10391
10392 fn go_to_diagnostic(
10393 &mut self,
10394 _: &GoToDiagnostic,
10395 window: &mut Window,
10396 cx: &mut Context<Self>,
10397 ) {
10398 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10399 }
10400
10401 fn go_to_prev_diagnostic(
10402 &mut self,
10403 _: &GoToPrevDiagnostic,
10404 window: &mut Window,
10405 cx: &mut Context<Self>,
10406 ) {
10407 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10408 }
10409
10410 pub fn go_to_diagnostic_impl(
10411 &mut self,
10412 direction: Direction,
10413 window: &mut Window,
10414 cx: &mut Context<Self>,
10415 ) {
10416 let buffer = self.buffer.read(cx).snapshot(cx);
10417 let selection = self.selections.newest::<usize>(cx);
10418
10419 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10420 if direction == Direction::Next {
10421 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10422 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10423 return;
10424 };
10425 self.activate_diagnostics(
10426 buffer_id,
10427 popover.local_diagnostic.diagnostic.group_id,
10428 window,
10429 cx,
10430 );
10431 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10432 let primary_range_start = active_diagnostics.primary_range.start;
10433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10434 let mut new_selection = s.newest_anchor().clone();
10435 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10436 s.select_anchors(vec![new_selection.clone()]);
10437 });
10438 self.refresh_inline_completion(false, true, window, cx);
10439 }
10440 return;
10441 }
10442 }
10443
10444 let active_group_id = self
10445 .active_diagnostics
10446 .as_ref()
10447 .map(|active_group| active_group.group_id);
10448 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10449 active_diagnostics
10450 .primary_range
10451 .to_offset(&buffer)
10452 .to_inclusive()
10453 });
10454 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10455 if active_primary_range.contains(&selection.head()) {
10456 *active_primary_range.start()
10457 } else {
10458 selection.head()
10459 }
10460 } else {
10461 selection.head()
10462 };
10463
10464 let snapshot = self.snapshot(window, cx);
10465 let primary_diagnostics_before = buffer
10466 .diagnostics_in_range::<usize>(0..search_start)
10467 .filter(|entry| entry.diagnostic.is_primary)
10468 .filter(|entry| entry.range.start != entry.range.end)
10469 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10470 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10471 .collect::<Vec<_>>();
10472 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10473 primary_diagnostics_before
10474 .iter()
10475 .position(|entry| entry.diagnostic.group_id == active_group_id)
10476 });
10477
10478 let primary_diagnostics_after = buffer
10479 .diagnostics_in_range::<usize>(search_start..buffer.len())
10480 .filter(|entry| entry.diagnostic.is_primary)
10481 .filter(|entry| entry.range.start != entry.range.end)
10482 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10483 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10484 .collect::<Vec<_>>();
10485 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10486 primary_diagnostics_after
10487 .iter()
10488 .enumerate()
10489 .rev()
10490 .find_map(|(i, entry)| {
10491 if entry.diagnostic.group_id == active_group_id {
10492 Some(i)
10493 } else {
10494 None
10495 }
10496 })
10497 });
10498
10499 let next_primary_diagnostic = match direction {
10500 Direction::Prev => primary_diagnostics_before
10501 .iter()
10502 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10503 .rev()
10504 .next(),
10505 Direction::Next => primary_diagnostics_after
10506 .iter()
10507 .skip(
10508 last_same_group_diagnostic_after
10509 .map(|index| index + 1)
10510 .unwrap_or(0),
10511 )
10512 .next(),
10513 };
10514
10515 // Cycle around to the start of the buffer, potentially moving back to the start of
10516 // the currently active diagnostic.
10517 let cycle_around = || match direction {
10518 Direction::Prev => primary_diagnostics_after
10519 .iter()
10520 .rev()
10521 .chain(primary_diagnostics_before.iter().rev())
10522 .next(),
10523 Direction::Next => primary_diagnostics_before
10524 .iter()
10525 .chain(primary_diagnostics_after.iter())
10526 .next(),
10527 };
10528
10529 if let Some((primary_range, group_id)) = next_primary_diagnostic
10530 .or_else(cycle_around)
10531 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10532 {
10533 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10534 return;
10535 };
10536 self.activate_diagnostics(buffer_id, group_id, window, cx);
10537 if self.active_diagnostics.is_some() {
10538 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10539 s.select(vec![Selection {
10540 id: selection.id,
10541 start: primary_range.start,
10542 end: primary_range.start,
10543 reversed: false,
10544 goal: SelectionGoal::None,
10545 }]);
10546 });
10547 self.refresh_inline_completion(false, true, window, cx);
10548 }
10549 }
10550 }
10551
10552 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10553 let snapshot = self.snapshot(window, cx);
10554 let selection = self.selections.newest::<Point>(cx);
10555 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10556 }
10557
10558 fn go_to_hunk_after_position(
10559 &mut self,
10560 snapshot: &EditorSnapshot,
10561 position: Point,
10562 window: &mut Window,
10563 cx: &mut Context<Editor>,
10564 ) -> Option<MultiBufferDiffHunk> {
10565 let mut hunk = snapshot
10566 .buffer_snapshot
10567 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10568 .find(|hunk| hunk.row_range.start.0 > position.row);
10569 if hunk.is_none() {
10570 hunk = snapshot
10571 .buffer_snapshot
10572 .diff_hunks_in_range(Point::zero()..position)
10573 .find(|hunk| hunk.row_range.end.0 < position.row)
10574 }
10575 if let Some(hunk) = &hunk {
10576 let destination = Point::new(hunk.row_range.start.0, 0);
10577 self.unfold_ranges(&[destination..destination], false, false, cx);
10578 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10579 s.select_ranges(vec![destination..destination]);
10580 });
10581 }
10582
10583 hunk
10584 }
10585
10586 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10587 let snapshot = self.snapshot(window, cx);
10588 let selection = self.selections.newest::<Point>(cx);
10589 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10590 }
10591
10592 fn go_to_hunk_before_position(
10593 &mut self,
10594 snapshot: &EditorSnapshot,
10595 position: Point,
10596 window: &mut Window,
10597 cx: &mut Context<Editor>,
10598 ) -> Option<MultiBufferDiffHunk> {
10599 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10600 if hunk.is_none() {
10601 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10602 }
10603 if let Some(hunk) = &hunk {
10604 let destination = Point::new(hunk.row_range.start.0, 0);
10605 self.unfold_ranges(&[destination..destination], false, false, cx);
10606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10607 s.select_ranges(vec![destination..destination]);
10608 });
10609 }
10610
10611 hunk
10612 }
10613
10614 pub fn go_to_definition(
10615 &mut self,
10616 _: &GoToDefinition,
10617 window: &mut Window,
10618 cx: &mut Context<Self>,
10619 ) -> Task<Result<Navigated>> {
10620 let definition =
10621 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10622 cx.spawn_in(window, |editor, mut cx| async move {
10623 if definition.await? == Navigated::Yes {
10624 return Ok(Navigated::Yes);
10625 }
10626 match editor.update_in(&mut cx, |editor, window, cx| {
10627 editor.find_all_references(&FindAllReferences, window, cx)
10628 })? {
10629 Some(references) => references.await,
10630 None => Ok(Navigated::No),
10631 }
10632 })
10633 }
10634
10635 pub fn go_to_declaration(
10636 &mut self,
10637 _: &GoToDeclaration,
10638 window: &mut Window,
10639 cx: &mut Context<Self>,
10640 ) -> Task<Result<Navigated>> {
10641 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10642 }
10643
10644 pub fn go_to_declaration_split(
10645 &mut self,
10646 _: &GoToDeclaration,
10647 window: &mut Window,
10648 cx: &mut Context<Self>,
10649 ) -> Task<Result<Navigated>> {
10650 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10651 }
10652
10653 pub fn go_to_implementation(
10654 &mut self,
10655 _: &GoToImplementation,
10656 window: &mut Window,
10657 cx: &mut Context<Self>,
10658 ) -> Task<Result<Navigated>> {
10659 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10660 }
10661
10662 pub fn go_to_implementation_split(
10663 &mut self,
10664 _: &GoToImplementationSplit,
10665 window: &mut Window,
10666 cx: &mut Context<Self>,
10667 ) -> Task<Result<Navigated>> {
10668 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10669 }
10670
10671 pub fn go_to_type_definition(
10672 &mut self,
10673 _: &GoToTypeDefinition,
10674 window: &mut Window,
10675 cx: &mut Context<Self>,
10676 ) -> Task<Result<Navigated>> {
10677 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10678 }
10679
10680 pub fn go_to_definition_split(
10681 &mut self,
10682 _: &GoToDefinitionSplit,
10683 window: &mut Window,
10684 cx: &mut Context<Self>,
10685 ) -> Task<Result<Navigated>> {
10686 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10687 }
10688
10689 pub fn go_to_type_definition_split(
10690 &mut self,
10691 _: &GoToTypeDefinitionSplit,
10692 window: &mut Window,
10693 cx: &mut Context<Self>,
10694 ) -> Task<Result<Navigated>> {
10695 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10696 }
10697
10698 fn go_to_definition_of_kind(
10699 &mut self,
10700 kind: GotoDefinitionKind,
10701 split: bool,
10702 window: &mut Window,
10703 cx: &mut Context<Self>,
10704 ) -> Task<Result<Navigated>> {
10705 let Some(provider) = self.semantics_provider.clone() else {
10706 return Task::ready(Ok(Navigated::No));
10707 };
10708 let head = self.selections.newest::<usize>(cx).head();
10709 let buffer = self.buffer.read(cx);
10710 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10711 text_anchor
10712 } else {
10713 return Task::ready(Ok(Navigated::No));
10714 };
10715
10716 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10717 return Task::ready(Ok(Navigated::No));
10718 };
10719
10720 cx.spawn_in(window, |editor, mut cx| async move {
10721 let definitions = definitions.await?;
10722 let navigated = editor
10723 .update_in(&mut cx, |editor, window, cx| {
10724 editor.navigate_to_hover_links(
10725 Some(kind),
10726 definitions
10727 .into_iter()
10728 .filter(|location| {
10729 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10730 })
10731 .map(HoverLink::Text)
10732 .collect::<Vec<_>>(),
10733 split,
10734 window,
10735 cx,
10736 )
10737 })?
10738 .await?;
10739 anyhow::Ok(navigated)
10740 })
10741 }
10742
10743 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10744 let selection = self.selections.newest_anchor();
10745 let head = selection.head();
10746 let tail = selection.tail();
10747
10748 let Some((buffer, start_position)) =
10749 self.buffer.read(cx).text_anchor_for_position(head, cx)
10750 else {
10751 return;
10752 };
10753
10754 let end_position = if head != tail {
10755 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10756 return;
10757 };
10758 Some(pos)
10759 } else {
10760 None
10761 };
10762
10763 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10764 let url = if let Some(end_pos) = end_position {
10765 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10766 } else {
10767 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10768 };
10769
10770 if let Some(url) = url {
10771 editor.update(&mut cx, |_, cx| {
10772 cx.open_url(&url);
10773 })
10774 } else {
10775 Ok(())
10776 }
10777 });
10778
10779 url_finder.detach();
10780 }
10781
10782 pub fn open_selected_filename(
10783 &mut self,
10784 _: &OpenSelectedFilename,
10785 window: &mut Window,
10786 cx: &mut Context<Self>,
10787 ) {
10788 let Some(workspace) = self.workspace() else {
10789 return;
10790 };
10791
10792 let position = self.selections.newest_anchor().head();
10793
10794 let Some((buffer, buffer_position)) =
10795 self.buffer.read(cx).text_anchor_for_position(position, cx)
10796 else {
10797 return;
10798 };
10799
10800 let project = self.project.clone();
10801
10802 cx.spawn_in(window, |_, mut cx| async move {
10803 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10804
10805 if let Some((_, path)) = result {
10806 workspace
10807 .update_in(&mut cx, |workspace, window, cx| {
10808 workspace.open_resolved_path(path, window, cx)
10809 })?
10810 .await?;
10811 }
10812 anyhow::Ok(())
10813 })
10814 .detach();
10815 }
10816
10817 pub(crate) fn navigate_to_hover_links(
10818 &mut self,
10819 kind: Option<GotoDefinitionKind>,
10820 mut definitions: Vec<HoverLink>,
10821 split: bool,
10822 window: &mut Window,
10823 cx: &mut Context<Editor>,
10824 ) -> Task<Result<Navigated>> {
10825 // If there is one definition, just open it directly
10826 if definitions.len() == 1 {
10827 let definition = definitions.pop().unwrap();
10828
10829 enum TargetTaskResult {
10830 Location(Option<Location>),
10831 AlreadyNavigated,
10832 }
10833
10834 let target_task = match definition {
10835 HoverLink::Text(link) => {
10836 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10837 }
10838 HoverLink::InlayHint(lsp_location, server_id) => {
10839 let computation =
10840 self.compute_target_location(lsp_location, server_id, window, cx);
10841 cx.background_executor().spawn(async move {
10842 let location = computation.await?;
10843 Ok(TargetTaskResult::Location(location))
10844 })
10845 }
10846 HoverLink::Url(url) => {
10847 cx.open_url(&url);
10848 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10849 }
10850 HoverLink::File(path) => {
10851 if let Some(workspace) = self.workspace() {
10852 cx.spawn_in(window, |_, mut cx| async move {
10853 workspace
10854 .update_in(&mut cx, |workspace, window, cx| {
10855 workspace.open_resolved_path(path, window, cx)
10856 })?
10857 .await
10858 .map(|_| TargetTaskResult::AlreadyNavigated)
10859 })
10860 } else {
10861 Task::ready(Ok(TargetTaskResult::Location(None)))
10862 }
10863 }
10864 };
10865 cx.spawn_in(window, |editor, mut cx| async move {
10866 let target = match target_task.await.context("target resolution task")? {
10867 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10868 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10869 TargetTaskResult::Location(Some(target)) => target,
10870 };
10871
10872 editor.update_in(&mut cx, |editor, window, cx| {
10873 let Some(workspace) = editor.workspace() else {
10874 return Navigated::No;
10875 };
10876 let pane = workspace.read(cx).active_pane().clone();
10877
10878 let range = target.range.to_point(target.buffer.read(cx));
10879 let range = editor.range_for_match(&range);
10880 let range = collapse_multiline_range(range);
10881
10882 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10883 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10884 } else {
10885 window.defer(cx, move |window, cx| {
10886 let target_editor: Entity<Self> =
10887 workspace.update(cx, |workspace, cx| {
10888 let pane = if split {
10889 workspace.adjacent_pane(window, cx)
10890 } else {
10891 workspace.active_pane().clone()
10892 };
10893
10894 workspace.open_project_item(
10895 pane,
10896 target.buffer.clone(),
10897 true,
10898 true,
10899 window,
10900 cx,
10901 )
10902 });
10903 target_editor.update(cx, |target_editor, cx| {
10904 // When selecting a definition in a different buffer, disable the nav history
10905 // to avoid creating a history entry at the previous cursor location.
10906 pane.update(cx, |pane, _| pane.disable_history());
10907 target_editor.go_to_singleton_buffer_range(range, window, cx);
10908 pane.update(cx, |pane, _| pane.enable_history());
10909 });
10910 });
10911 }
10912 Navigated::Yes
10913 })
10914 })
10915 } else if !definitions.is_empty() {
10916 cx.spawn_in(window, |editor, mut cx| async move {
10917 let (title, location_tasks, workspace) = editor
10918 .update_in(&mut cx, |editor, window, cx| {
10919 let tab_kind = match kind {
10920 Some(GotoDefinitionKind::Implementation) => "Implementations",
10921 _ => "Definitions",
10922 };
10923 let title = definitions
10924 .iter()
10925 .find_map(|definition| match definition {
10926 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10927 let buffer = origin.buffer.read(cx);
10928 format!(
10929 "{} for {}",
10930 tab_kind,
10931 buffer
10932 .text_for_range(origin.range.clone())
10933 .collect::<String>()
10934 )
10935 }),
10936 HoverLink::InlayHint(_, _) => None,
10937 HoverLink::Url(_) => None,
10938 HoverLink::File(_) => None,
10939 })
10940 .unwrap_or(tab_kind.to_string());
10941 let location_tasks = definitions
10942 .into_iter()
10943 .map(|definition| match definition {
10944 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10945 HoverLink::InlayHint(lsp_location, server_id) => editor
10946 .compute_target_location(lsp_location, server_id, window, cx),
10947 HoverLink::Url(_) => Task::ready(Ok(None)),
10948 HoverLink::File(_) => Task::ready(Ok(None)),
10949 })
10950 .collect::<Vec<_>>();
10951 (title, location_tasks, editor.workspace().clone())
10952 })
10953 .context("location tasks preparation")?;
10954
10955 let locations = future::join_all(location_tasks)
10956 .await
10957 .into_iter()
10958 .filter_map(|location| location.transpose())
10959 .collect::<Result<_>>()
10960 .context("location tasks")?;
10961
10962 let Some(workspace) = workspace else {
10963 return Ok(Navigated::No);
10964 };
10965 let opened = workspace
10966 .update_in(&mut cx, |workspace, window, cx| {
10967 Self::open_locations_in_multibuffer(
10968 workspace,
10969 locations,
10970 title,
10971 split,
10972 MultibufferSelectionMode::First,
10973 window,
10974 cx,
10975 )
10976 })
10977 .ok();
10978
10979 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10980 })
10981 } else {
10982 Task::ready(Ok(Navigated::No))
10983 }
10984 }
10985
10986 fn compute_target_location(
10987 &self,
10988 lsp_location: lsp::Location,
10989 server_id: LanguageServerId,
10990 window: &mut Window,
10991 cx: &mut Context<Self>,
10992 ) -> Task<anyhow::Result<Option<Location>>> {
10993 let Some(project) = self.project.clone() else {
10994 return Task::ready(Ok(None));
10995 };
10996
10997 cx.spawn_in(window, move |editor, mut cx| async move {
10998 let location_task = editor.update(&mut cx, |_, cx| {
10999 project.update(cx, |project, cx| {
11000 let language_server_name = project
11001 .language_server_statuses(cx)
11002 .find(|(id, _)| server_id == *id)
11003 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11004 language_server_name.map(|language_server_name| {
11005 project.open_local_buffer_via_lsp(
11006 lsp_location.uri.clone(),
11007 server_id,
11008 language_server_name,
11009 cx,
11010 )
11011 })
11012 })
11013 })?;
11014 let location = match location_task {
11015 Some(task) => Some({
11016 let target_buffer_handle = task.await.context("open local buffer")?;
11017 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11018 let target_start = target_buffer
11019 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11020 let target_end = target_buffer
11021 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11022 target_buffer.anchor_after(target_start)
11023 ..target_buffer.anchor_before(target_end)
11024 })?;
11025 Location {
11026 buffer: target_buffer_handle,
11027 range,
11028 }
11029 }),
11030 None => None,
11031 };
11032 Ok(location)
11033 })
11034 }
11035
11036 pub fn find_all_references(
11037 &mut self,
11038 _: &FindAllReferences,
11039 window: &mut Window,
11040 cx: &mut Context<Self>,
11041 ) -> Option<Task<Result<Navigated>>> {
11042 let selection = self.selections.newest::<usize>(cx);
11043 let multi_buffer = self.buffer.read(cx);
11044 let head = selection.head();
11045
11046 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11047 let head_anchor = multi_buffer_snapshot.anchor_at(
11048 head,
11049 if head < selection.tail() {
11050 Bias::Right
11051 } else {
11052 Bias::Left
11053 },
11054 );
11055
11056 match self
11057 .find_all_references_task_sources
11058 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11059 {
11060 Ok(_) => {
11061 log::info!(
11062 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11063 );
11064 return None;
11065 }
11066 Err(i) => {
11067 self.find_all_references_task_sources.insert(i, head_anchor);
11068 }
11069 }
11070
11071 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11072 let workspace = self.workspace()?;
11073 let project = workspace.read(cx).project().clone();
11074 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11075 Some(cx.spawn_in(window, |editor, mut cx| async move {
11076 let _cleanup = defer({
11077 let mut cx = cx.clone();
11078 move || {
11079 let _ = editor.update(&mut cx, |editor, _| {
11080 if let Ok(i) =
11081 editor
11082 .find_all_references_task_sources
11083 .binary_search_by(|anchor| {
11084 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11085 })
11086 {
11087 editor.find_all_references_task_sources.remove(i);
11088 }
11089 });
11090 }
11091 });
11092
11093 let locations = references.await?;
11094 if locations.is_empty() {
11095 return anyhow::Ok(Navigated::No);
11096 }
11097
11098 workspace.update_in(&mut cx, |workspace, window, cx| {
11099 let title = locations
11100 .first()
11101 .as_ref()
11102 .map(|location| {
11103 let buffer = location.buffer.read(cx);
11104 format!(
11105 "References to `{}`",
11106 buffer
11107 .text_for_range(location.range.clone())
11108 .collect::<String>()
11109 )
11110 })
11111 .unwrap();
11112 Self::open_locations_in_multibuffer(
11113 workspace,
11114 locations,
11115 title,
11116 false,
11117 MultibufferSelectionMode::First,
11118 window,
11119 cx,
11120 );
11121 Navigated::Yes
11122 })
11123 }))
11124 }
11125
11126 /// Opens a multibuffer with the given project locations in it
11127 pub fn open_locations_in_multibuffer(
11128 workspace: &mut Workspace,
11129 mut locations: Vec<Location>,
11130 title: String,
11131 split: bool,
11132 multibuffer_selection_mode: MultibufferSelectionMode,
11133 window: &mut Window,
11134 cx: &mut Context<Workspace>,
11135 ) {
11136 // If there are multiple definitions, open them in a multibuffer
11137 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11138 let mut locations = locations.into_iter().peekable();
11139 let mut ranges = Vec::new();
11140 let capability = workspace.project().read(cx).capability();
11141
11142 let excerpt_buffer = cx.new(|cx| {
11143 let mut multibuffer = MultiBuffer::new(capability);
11144 while let Some(location) = locations.next() {
11145 let buffer = location.buffer.read(cx);
11146 let mut ranges_for_buffer = Vec::new();
11147 let range = location.range.to_offset(buffer);
11148 ranges_for_buffer.push(range.clone());
11149
11150 while let Some(next_location) = locations.peek() {
11151 if next_location.buffer == location.buffer {
11152 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11153 locations.next();
11154 } else {
11155 break;
11156 }
11157 }
11158
11159 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11160 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11161 location.buffer.clone(),
11162 ranges_for_buffer,
11163 DEFAULT_MULTIBUFFER_CONTEXT,
11164 cx,
11165 ))
11166 }
11167
11168 multibuffer.with_title(title)
11169 });
11170
11171 let editor = cx.new(|cx| {
11172 Editor::for_multibuffer(
11173 excerpt_buffer,
11174 Some(workspace.project().clone()),
11175 true,
11176 window,
11177 cx,
11178 )
11179 });
11180 editor.update(cx, |editor, cx| {
11181 match multibuffer_selection_mode {
11182 MultibufferSelectionMode::First => {
11183 if let Some(first_range) = ranges.first() {
11184 editor.change_selections(None, window, cx, |selections| {
11185 selections.clear_disjoint();
11186 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11187 });
11188 }
11189 editor.highlight_background::<Self>(
11190 &ranges,
11191 |theme| theme.editor_highlighted_line_background,
11192 cx,
11193 );
11194 }
11195 MultibufferSelectionMode::All => {
11196 editor.change_selections(None, window, cx, |selections| {
11197 selections.clear_disjoint();
11198 selections.select_anchor_ranges(ranges);
11199 });
11200 }
11201 }
11202 editor.register_buffers_with_language_servers(cx);
11203 });
11204
11205 let item = Box::new(editor);
11206 let item_id = item.item_id();
11207
11208 if split {
11209 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11210 } else {
11211 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11212 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11213 pane.close_current_preview_item(window, cx)
11214 } else {
11215 None
11216 }
11217 });
11218 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11219 }
11220 workspace.active_pane().update(cx, |pane, cx| {
11221 pane.set_preview_item_id(Some(item_id), cx);
11222 });
11223 }
11224
11225 pub fn rename(
11226 &mut self,
11227 _: &Rename,
11228 window: &mut Window,
11229 cx: &mut Context<Self>,
11230 ) -> Option<Task<Result<()>>> {
11231 use language::ToOffset as _;
11232
11233 let provider = self.semantics_provider.clone()?;
11234 let selection = self.selections.newest_anchor().clone();
11235 let (cursor_buffer, cursor_buffer_position) = self
11236 .buffer
11237 .read(cx)
11238 .text_anchor_for_position(selection.head(), cx)?;
11239 let (tail_buffer, cursor_buffer_position_end) = self
11240 .buffer
11241 .read(cx)
11242 .text_anchor_for_position(selection.tail(), cx)?;
11243 if tail_buffer != cursor_buffer {
11244 return None;
11245 }
11246
11247 let snapshot = cursor_buffer.read(cx).snapshot();
11248 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11249 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11250 let prepare_rename = provider
11251 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11252 .unwrap_or_else(|| Task::ready(Ok(None)));
11253 drop(snapshot);
11254
11255 Some(cx.spawn_in(window, |this, mut cx| async move {
11256 let rename_range = if let Some(range) = prepare_rename.await? {
11257 Some(range)
11258 } else {
11259 this.update(&mut cx, |this, cx| {
11260 let buffer = this.buffer.read(cx).snapshot(cx);
11261 let mut buffer_highlights = this
11262 .document_highlights_for_position(selection.head(), &buffer)
11263 .filter(|highlight| {
11264 highlight.start.excerpt_id == selection.head().excerpt_id
11265 && highlight.end.excerpt_id == selection.head().excerpt_id
11266 });
11267 buffer_highlights
11268 .next()
11269 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11270 })?
11271 };
11272 if let Some(rename_range) = rename_range {
11273 this.update_in(&mut cx, |this, window, cx| {
11274 let snapshot = cursor_buffer.read(cx).snapshot();
11275 let rename_buffer_range = rename_range.to_offset(&snapshot);
11276 let cursor_offset_in_rename_range =
11277 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11278 let cursor_offset_in_rename_range_end =
11279 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11280
11281 this.take_rename(false, window, cx);
11282 let buffer = this.buffer.read(cx).read(cx);
11283 let cursor_offset = selection.head().to_offset(&buffer);
11284 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11285 let rename_end = rename_start + rename_buffer_range.len();
11286 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11287 let mut old_highlight_id = None;
11288 let old_name: Arc<str> = buffer
11289 .chunks(rename_start..rename_end, true)
11290 .map(|chunk| {
11291 if old_highlight_id.is_none() {
11292 old_highlight_id = chunk.syntax_highlight_id;
11293 }
11294 chunk.text
11295 })
11296 .collect::<String>()
11297 .into();
11298
11299 drop(buffer);
11300
11301 // Position the selection in the rename editor so that it matches the current selection.
11302 this.show_local_selections = false;
11303 let rename_editor = cx.new(|cx| {
11304 let mut editor = Editor::single_line(window, cx);
11305 editor.buffer.update(cx, |buffer, cx| {
11306 buffer.edit([(0..0, old_name.clone())], None, cx)
11307 });
11308 let rename_selection_range = match cursor_offset_in_rename_range
11309 .cmp(&cursor_offset_in_rename_range_end)
11310 {
11311 Ordering::Equal => {
11312 editor.select_all(&SelectAll, window, cx);
11313 return editor;
11314 }
11315 Ordering::Less => {
11316 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11317 }
11318 Ordering::Greater => {
11319 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11320 }
11321 };
11322 if rename_selection_range.end > old_name.len() {
11323 editor.select_all(&SelectAll, window, cx);
11324 } else {
11325 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326 s.select_ranges([rename_selection_range]);
11327 });
11328 }
11329 editor
11330 });
11331 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11332 if e == &EditorEvent::Focused {
11333 cx.emit(EditorEvent::FocusedIn)
11334 }
11335 })
11336 .detach();
11337
11338 let write_highlights =
11339 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11340 let read_highlights =
11341 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11342 let ranges = write_highlights
11343 .iter()
11344 .flat_map(|(_, ranges)| ranges.iter())
11345 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11346 .cloned()
11347 .collect();
11348
11349 this.highlight_text::<Rename>(
11350 ranges,
11351 HighlightStyle {
11352 fade_out: Some(0.6),
11353 ..Default::default()
11354 },
11355 cx,
11356 );
11357 let rename_focus_handle = rename_editor.focus_handle(cx);
11358 window.focus(&rename_focus_handle);
11359 let block_id = this.insert_blocks(
11360 [BlockProperties {
11361 style: BlockStyle::Flex,
11362 placement: BlockPlacement::Below(range.start),
11363 height: 1,
11364 render: Arc::new({
11365 let rename_editor = rename_editor.clone();
11366 move |cx: &mut BlockContext| {
11367 let mut text_style = cx.editor_style.text.clone();
11368 if let Some(highlight_style) = old_highlight_id
11369 .and_then(|h| h.style(&cx.editor_style.syntax))
11370 {
11371 text_style = text_style.highlight(highlight_style);
11372 }
11373 div()
11374 .block_mouse_down()
11375 .pl(cx.anchor_x)
11376 .child(EditorElement::new(
11377 &rename_editor,
11378 EditorStyle {
11379 background: cx.theme().system().transparent,
11380 local_player: cx.editor_style.local_player,
11381 text: text_style,
11382 scrollbar_width: cx.editor_style.scrollbar_width,
11383 syntax: cx.editor_style.syntax.clone(),
11384 status: cx.editor_style.status.clone(),
11385 inlay_hints_style: HighlightStyle {
11386 font_weight: Some(FontWeight::BOLD),
11387 ..make_inlay_hints_style(cx.app)
11388 },
11389 inline_completion_styles: make_suggestion_styles(
11390 cx.app,
11391 ),
11392 ..EditorStyle::default()
11393 },
11394 ))
11395 .into_any_element()
11396 }
11397 }),
11398 priority: 0,
11399 }],
11400 Some(Autoscroll::fit()),
11401 cx,
11402 )[0];
11403 this.pending_rename = Some(RenameState {
11404 range,
11405 old_name,
11406 editor: rename_editor,
11407 block_id,
11408 });
11409 })?;
11410 }
11411
11412 Ok(())
11413 }))
11414 }
11415
11416 pub fn confirm_rename(
11417 &mut self,
11418 _: &ConfirmRename,
11419 window: &mut Window,
11420 cx: &mut Context<Self>,
11421 ) -> Option<Task<Result<()>>> {
11422 let rename = self.take_rename(false, window, cx)?;
11423 let workspace = self.workspace()?.downgrade();
11424 let (buffer, start) = self
11425 .buffer
11426 .read(cx)
11427 .text_anchor_for_position(rename.range.start, cx)?;
11428 let (end_buffer, _) = self
11429 .buffer
11430 .read(cx)
11431 .text_anchor_for_position(rename.range.end, cx)?;
11432 if buffer != end_buffer {
11433 return None;
11434 }
11435
11436 let old_name = rename.old_name;
11437 let new_name = rename.editor.read(cx).text(cx);
11438
11439 let rename = self.semantics_provider.as_ref()?.perform_rename(
11440 &buffer,
11441 start,
11442 new_name.clone(),
11443 cx,
11444 )?;
11445
11446 Some(cx.spawn_in(window, |editor, mut cx| async move {
11447 let project_transaction = rename.await?;
11448 Self::open_project_transaction(
11449 &editor,
11450 workspace,
11451 project_transaction,
11452 format!("Rename: {} → {}", old_name, new_name),
11453 cx.clone(),
11454 )
11455 .await?;
11456
11457 editor.update(&mut cx, |editor, cx| {
11458 editor.refresh_document_highlights(cx);
11459 })?;
11460 Ok(())
11461 }))
11462 }
11463
11464 fn take_rename(
11465 &mut self,
11466 moving_cursor: bool,
11467 window: &mut Window,
11468 cx: &mut Context<Self>,
11469 ) -> Option<RenameState> {
11470 let rename = self.pending_rename.take()?;
11471 if rename.editor.focus_handle(cx).is_focused(window) {
11472 window.focus(&self.focus_handle);
11473 }
11474
11475 self.remove_blocks(
11476 [rename.block_id].into_iter().collect(),
11477 Some(Autoscroll::fit()),
11478 cx,
11479 );
11480 self.clear_highlights::<Rename>(cx);
11481 self.show_local_selections = true;
11482
11483 if moving_cursor {
11484 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11485 editor.selections.newest::<usize>(cx).head()
11486 });
11487
11488 // Update the selection to match the position of the selection inside
11489 // the rename editor.
11490 let snapshot = self.buffer.read(cx).read(cx);
11491 let rename_range = rename.range.to_offset(&snapshot);
11492 let cursor_in_editor = snapshot
11493 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11494 .min(rename_range.end);
11495 drop(snapshot);
11496
11497 self.change_selections(None, window, cx, |s| {
11498 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11499 });
11500 } else {
11501 self.refresh_document_highlights(cx);
11502 }
11503
11504 Some(rename)
11505 }
11506
11507 pub fn pending_rename(&self) -> Option<&RenameState> {
11508 self.pending_rename.as_ref()
11509 }
11510
11511 fn format(
11512 &mut self,
11513 _: &Format,
11514 window: &mut Window,
11515 cx: &mut Context<Self>,
11516 ) -> Option<Task<Result<()>>> {
11517 let project = match &self.project {
11518 Some(project) => project.clone(),
11519 None => return None,
11520 };
11521
11522 Some(self.perform_format(
11523 project,
11524 FormatTrigger::Manual,
11525 FormatTarget::Buffers,
11526 window,
11527 cx,
11528 ))
11529 }
11530
11531 fn format_selections(
11532 &mut self,
11533 _: &FormatSelections,
11534 window: &mut Window,
11535 cx: &mut Context<Self>,
11536 ) -> Option<Task<Result<()>>> {
11537 let project = match &self.project {
11538 Some(project) => project.clone(),
11539 None => return None,
11540 };
11541
11542 let ranges = self
11543 .selections
11544 .all_adjusted(cx)
11545 .into_iter()
11546 .map(|selection| selection.range())
11547 .collect_vec();
11548
11549 Some(self.perform_format(
11550 project,
11551 FormatTrigger::Manual,
11552 FormatTarget::Ranges(ranges),
11553 window,
11554 cx,
11555 ))
11556 }
11557
11558 fn perform_format(
11559 &mut self,
11560 project: Entity<Project>,
11561 trigger: FormatTrigger,
11562 target: FormatTarget,
11563 window: &mut Window,
11564 cx: &mut Context<Self>,
11565 ) -> Task<Result<()>> {
11566 let buffer = self.buffer.clone();
11567 let (buffers, target) = match target {
11568 FormatTarget::Buffers => {
11569 let mut buffers = buffer.read(cx).all_buffers();
11570 if trigger == FormatTrigger::Save {
11571 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11572 }
11573 (buffers, LspFormatTarget::Buffers)
11574 }
11575 FormatTarget::Ranges(selection_ranges) => {
11576 let multi_buffer = buffer.read(cx);
11577 let snapshot = multi_buffer.read(cx);
11578 let mut buffers = HashSet::default();
11579 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11580 BTreeMap::new();
11581 for selection_range in selection_ranges {
11582 for (buffer, buffer_range, _) in
11583 snapshot.range_to_buffer_ranges(selection_range)
11584 {
11585 let buffer_id = buffer.remote_id();
11586 let start = buffer.anchor_before(buffer_range.start);
11587 let end = buffer.anchor_after(buffer_range.end);
11588 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11589 buffer_id_to_ranges
11590 .entry(buffer_id)
11591 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11592 .or_insert_with(|| vec![start..end]);
11593 }
11594 }
11595 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11596 }
11597 };
11598
11599 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11600 let format = project.update(cx, |project, cx| {
11601 project.format(buffers, target, true, trigger, cx)
11602 });
11603
11604 cx.spawn_in(window, |_, mut cx| async move {
11605 let transaction = futures::select_biased! {
11606 () = timeout => {
11607 log::warn!("timed out waiting for formatting");
11608 None
11609 }
11610 transaction = format.log_err().fuse() => transaction,
11611 };
11612
11613 buffer
11614 .update(&mut cx, |buffer, cx| {
11615 if let Some(transaction) = transaction {
11616 if !buffer.is_singleton() {
11617 buffer.push_transaction(&transaction.0, cx);
11618 }
11619 }
11620
11621 cx.notify();
11622 })
11623 .ok();
11624
11625 Ok(())
11626 })
11627 }
11628
11629 fn restart_language_server(
11630 &mut self,
11631 _: &RestartLanguageServer,
11632 _: &mut Window,
11633 cx: &mut Context<Self>,
11634 ) {
11635 if let Some(project) = self.project.clone() {
11636 self.buffer.update(cx, |multi_buffer, cx| {
11637 project.update(cx, |project, cx| {
11638 project.restart_language_servers_for_buffers(
11639 multi_buffer.all_buffers().into_iter().collect(),
11640 cx,
11641 );
11642 });
11643 })
11644 }
11645 }
11646
11647 fn cancel_language_server_work(
11648 workspace: &mut Workspace,
11649 _: &actions::CancelLanguageServerWork,
11650 _: &mut Window,
11651 cx: &mut Context<Workspace>,
11652 ) {
11653 let project = workspace.project();
11654 let buffers = workspace
11655 .active_item(cx)
11656 .and_then(|item| item.act_as::<Editor>(cx))
11657 .map_or(HashSet::default(), |editor| {
11658 editor.read(cx).buffer.read(cx).all_buffers()
11659 });
11660 project.update(cx, |project, cx| {
11661 project.cancel_language_server_work_for_buffers(buffers, cx);
11662 });
11663 }
11664
11665 fn show_character_palette(
11666 &mut self,
11667 _: &ShowCharacterPalette,
11668 window: &mut Window,
11669 _: &mut Context<Self>,
11670 ) {
11671 window.show_character_palette();
11672 }
11673
11674 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11675 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11676 let buffer = self.buffer.read(cx).snapshot(cx);
11677 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11678 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11679 let is_valid = buffer
11680 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11681 .any(|entry| {
11682 entry.diagnostic.is_primary
11683 && !entry.range.is_empty()
11684 && entry.range.start == primary_range_start
11685 && entry.diagnostic.message == active_diagnostics.primary_message
11686 });
11687
11688 if is_valid != active_diagnostics.is_valid {
11689 active_diagnostics.is_valid = is_valid;
11690 let mut new_styles = HashMap::default();
11691 for (block_id, diagnostic) in &active_diagnostics.blocks {
11692 new_styles.insert(
11693 *block_id,
11694 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11695 );
11696 }
11697 self.display_map.update(cx, |display_map, _cx| {
11698 display_map.replace_blocks(new_styles)
11699 });
11700 }
11701 }
11702 }
11703
11704 fn activate_diagnostics(
11705 &mut self,
11706 buffer_id: BufferId,
11707 group_id: usize,
11708 window: &mut Window,
11709 cx: &mut Context<Self>,
11710 ) {
11711 self.dismiss_diagnostics(cx);
11712 let snapshot = self.snapshot(window, cx);
11713 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11714 let buffer = self.buffer.read(cx).snapshot(cx);
11715
11716 let mut primary_range = None;
11717 let mut primary_message = None;
11718 let diagnostic_group = buffer
11719 .diagnostic_group(buffer_id, group_id)
11720 .filter_map(|entry| {
11721 let start = entry.range.start;
11722 let end = entry.range.end;
11723 if snapshot.is_line_folded(MultiBufferRow(start.row))
11724 && (start.row == end.row
11725 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11726 {
11727 return None;
11728 }
11729 if entry.diagnostic.is_primary {
11730 primary_range = Some(entry.range.clone());
11731 primary_message = Some(entry.diagnostic.message.clone());
11732 }
11733 Some(entry)
11734 })
11735 .collect::<Vec<_>>();
11736 let primary_range = primary_range?;
11737 let primary_message = primary_message?;
11738
11739 let blocks = display_map
11740 .insert_blocks(
11741 diagnostic_group.iter().map(|entry| {
11742 let diagnostic = entry.diagnostic.clone();
11743 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11744 BlockProperties {
11745 style: BlockStyle::Fixed,
11746 placement: BlockPlacement::Below(
11747 buffer.anchor_after(entry.range.start),
11748 ),
11749 height: message_height,
11750 render: diagnostic_block_renderer(diagnostic, None, true, true),
11751 priority: 0,
11752 }
11753 }),
11754 cx,
11755 )
11756 .into_iter()
11757 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11758 .collect();
11759
11760 Some(ActiveDiagnosticGroup {
11761 primary_range: buffer.anchor_before(primary_range.start)
11762 ..buffer.anchor_after(primary_range.end),
11763 primary_message,
11764 group_id,
11765 blocks,
11766 is_valid: true,
11767 })
11768 });
11769 }
11770
11771 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11772 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11773 self.display_map.update(cx, |display_map, cx| {
11774 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11775 });
11776 cx.notify();
11777 }
11778 }
11779
11780 pub fn set_selections_from_remote(
11781 &mut self,
11782 selections: Vec<Selection<Anchor>>,
11783 pending_selection: Option<Selection<Anchor>>,
11784 window: &mut Window,
11785 cx: &mut Context<Self>,
11786 ) {
11787 let old_cursor_position = self.selections.newest_anchor().head();
11788 self.selections.change_with(cx, |s| {
11789 s.select_anchors(selections);
11790 if let Some(pending_selection) = pending_selection {
11791 s.set_pending(pending_selection, SelectMode::Character);
11792 } else {
11793 s.clear_pending();
11794 }
11795 });
11796 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11797 }
11798
11799 fn push_to_selection_history(&mut self) {
11800 self.selection_history.push(SelectionHistoryEntry {
11801 selections: self.selections.disjoint_anchors(),
11802 select_next_state: self.select_next_state.clone(),
11803 select_prev_state: self.select_prev_state.clone(),
11804 add_selections_state: self.add_selections_state.clone(),
11805 });
11806 }
11807
11808 pub fn transact(
11809 &mut self,
11810 window: &mut Window,
11811 cx: &mut Context<Self>,
11812 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11813 ) -> Option<TransactionId> {
11814 self.start_transaction_at(Instant::now(), window, cx);
11815 update(self, window, cx);
11816 self.end_transaction_at(Instant::now(), cx)
11817 }
11818
11819 pub fn start_transaction_at(
11820 &mut self,
11821 now: Instant,
11822 window: &mut Window,
11823 cx: &mut Context<Self>,
11824 ) {
11825 self.end_selection(window, cx);
11826 if let Some(tx_id) = self
11827 .buffer
11828 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11829 {
11830 self.selection_history
11831 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11832 cx.emit(EditorEvent::TransactionBegun {
11833 transaction_id: tx_id,
11834 })
11835 }
11836 }
11837
11838 pub fn end_transaction_at(
11839 &mut self,
11840 now: Instant,
11841 cx: &mut Context<Self>,
11842 ) -> Option<TransactionId> {
11843 if let Some(transaction_id) = self
11844 .buffer
11845 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11846 {
11847 if let Some((_, end_selections)) =
11848 self.selection_history.transaction_mut(transaction_id)
11849 {
11850 *end_selections = Some(self.selections.disjoint_anchors());
11851 } else {
11852 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11853 }
11854
11855 cx.emit(EditorEvent::Edited { transaction_id });
11856 Some(transaction_id)
11857 } else {
11858 None
11859 }
11860 }
11861
11862 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11863 if self.selection_mark_mode {
11864 self.change_selections(None, window, cx, |s| {
11865 s.move_with(|_, sel| {
11866 sel.collapse_to(sel.head(), SelectionGoal::None);
11867 });
11868 })
11869 }
11870 self.selection_mark_mode = true;
11871 cx.notify();
11872 }
11873
11874 pub fn swap_selection_ends(
11875 &mut self,
11876 _: &actions::SwapSelectionEnds,
11877 window: &mut Window,
11878 cx: &mut Context<Self>,
11879 ) {
11880 self.change_selections(None, window, cx, |s| {
11881 s.move_with(|_, sel| {
11882 if sel.start != sel.end {
11883 sel.reversed = !sel.reversed
11884 }
11885 });
11886 });
11887 self.request_autoscroll(Autoscroll::newest(), cx);
11888 cx.notify();
11889 }
11890
11891 pub fn toggle_fold(
11892 &mut self,
11893 _: &actions::ToggleFold,
11894 window: &mut Window,
11895 cx: &mut Context<Self>,
11896 ) {
11897 if self.is_singleton(cx) {
11898 let selection = self.selections.newest::<Point>(cx);
11899
11900 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11901 let range = if selection.is_empty() {
11902 let point = selection.head().to_display_point(&display_map);
11903 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11904 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11905 .to_point(&display_map);
11906 start..end
11907 } else {
11908 selection.range()
11909 };
11910 if display_map.folds_in_range(range).next().is_some() {
11911 self.unfold_lines(&Default::default(), window, cx)
11912 } else {
11913 self.fold(&Default::default(), window, cx)
11914 }
11915 } else {
11916 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11917 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11918 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11919 .map(|(snapshot, _, _)| snapshot.remote_id())
11920 .collect();
11921
11922 for buffer_id in buffer_ids {
11923 if self.is_buffer_folded(buffer_id, cx) {
11924 self.unfold_buffer(buffer_id, cx);
11925 } else {
11926 self.fold_buffer(buffer_id, cx);
11927 }
11928 }
11929 }
11930 }
11931
11932 pub fn toggle_fold_recursive(
11933 &mut self,
11934 _: &actions::ToggleFoldRecursive,
11935 window: &mut Window,
11936 cx: &mut Context<Self>,
11937 ) {
11938 let selection = self.selections.newest::<Point>(cx);
11939
11940 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11941 let range = if selection.is_empty() {
11942 let point = selection.head().to_display_point(&display_map);
11943 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11944 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11945 .to_point(&display_map);
11946 start..end
11947 } else {
11948 selection.range()
11949 };
11950 if display_map.folds_in_range(range).next().is_some() {
11951 self.unfold_recursive(&Default::default(), window, cx)
11952 } else {
11953 self.fold_recursive(&Default::default(), window, cx)
11954 }
11955 }
11956
11957 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11958 if self.is_singleton(cx) {
11959 let mut to_fold = Vec::new();
11960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11961 let selections = self.selections.all_adjusted(cx);
11962
11963 for selection in selections {
11964 let range = selection.range().sorted();
11965 let buffer_start_row = range.start.row;
11966
11967 if range.start.row != range.end.row {
11968 let mut found = false;
11969 let mut row = range.start.row;
11970 while row <= range.end.row {
11971 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11972 {
11973 found = true;
11974 row = crease.range().end.row + 1;
11975 to_fold.push(crease);
11976 } else {
11977 row += 1
11978 }
11979 }
11980 if found {
11981 continue;
11982 }
11983 }
11984
11985 for row in (0..=range.start.row).rev() {
11986 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11987 if crease.range().end.row >= buffer_start_row {
11988 to_fold.push(crease);
11989 if row <= range.start.row {
11990 break;
11991 }
11992 }
11993 }
11994 }
11995 }
11996
11997 self.fold_creases(to_fold, true, window, cx);
11998 } else {
11999 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12000
12001 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12002 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12003 .map(|(snapshot, _, _)| snapshot.remote_id())
12004 .collect();
12005 for buffer_id in buffer_ids {
12006 self.fold_buffer(buffer_id, cx);
12007 }
12008 }
12009 }
12010
12011 fn fold_at_level(
12012 &mut self,
12013 fold_at: &FoldAtLevel,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) {
12017 if !self.buffer.read(cx).is_singleton() {
12018 return;
12019 }
12020
12021 let fold_at_level = fold_at.0;
12022 let snapshot = self.buffer.read(cx).snapshot(cx);
12023 let mut to_fold = Vec::new();
12024 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12025
12026 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12027 while start_row < end_row {
12028 match self
12029 .snapshot(window, cx)
12030 .crease_for_buffer_row(MultiBufferRow(start_row))
12031 {
12032 Some(crease) => {
12033 let nested_start_row = crease.range().start.row + 1;
12034 let nested_end_row = crease.range().end.row;
12035
12036 if current_level < fold_at_level {
12037 stack.push((nested_start_row, nested_end_row, current_level + 1));
12038 } else if current_level == fold_at_level {
12039 to_fold.push(crease);
12040 }
12041
12042 start_row = nested_end_row + 1;
12043 }
12044 None => start_row += 1,
12045 }
12046 }
12047 }
12048
12049 self.fold_creases(to_fold, true, window, cx);
12050 }
12051
12052 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12053 if self.buffer.read(cx).is_singleton() {
12054 let mut fold_ranges = Vec::new();
12055 let snapshot = self.buffer.read(cx).snapshot(cx);
12056
12057 for row in 0..snapshot.max_row().0 {
12058 if let Some(foldable_range) = self
12059 .snapshot(window, cx)
12060 .crease_for_buffer_row(MultiBufferRow(row))
12061 {
12062 fold_ranges.push(foldable_range);
12063 }
12064 }
12065
12066 self.fold_creases(fold_ranges, true, window, cx);
12067 } else {
12068 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12069 editor
12070 .update_in(&mut cx, |editor, _, cx| {
12071 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12072 editor.fold_buffer(buffer_id, cx);
12073 }
12074 })
12075 .ok();
12076 });
12077 }
12078 }
12079
12080 pub fn fold_function_bodies(
12081 &mut self,
12082 _: &actions::FoldFunctionBodies,
12083 window: &mut Window,
12084 cx: &mut Context<Self>,
12085 ) {
12086 let snapshot = self.buffer.read(cx).snapshot(cx);
12087
12088 let ranges = snapshot
12089 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12090 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12091 .collect::<Vec<_>>();
12092
12093 let creases = ranges
12094 .into_iter()
12095 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12096 .collect();
12097
12098 self.fold_creases(creases, true, window, cx);
12099 }
12100
12101 pub fn fold_recursive(
12102 &mut self,
12103 _: &actions::FoldRecursive,
12104 window: &mut Window,
12105 cx: &mut Context<Self>,
12106 ) {
12107 let mut to_fold = Vec::new();
12108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12109 let selections = self.selections.all_adjusted(cx);
12110
12111 for selection in selections {
12112 let range = selection.range().sorted();
12113 let buffer_start_row = range.start.row;
12114
12115 if range.start.row != range.end.row {
12116 let mut found = false;
12117 for row in range.start.row..=range.end.row {
12118 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12119 found = true;
12120 to_fold.push(crease);
12121 }
12122 }
12123 if found {
12124 continue;
12125 }
12126 }
12127
12128 for row in (0..=range.start.row).rev() {
12129 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12130 if crease.range().end.row >= buffer_start_row {
12131 to_fold.push(crease);
12132 } else {
12133 break;
12134 }
12135 }
12136 }
12137 }
12138
12139 self.fold_creases(to_fold, true, window, cx);
12140 }
12141
12142 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12143 let buffer_row = fold_at.buffer_row;
12144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12145
12146 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12147 let autoscroll = self
12148 .selections
12149 .all::<Point>(cx)
12150 .iter()
12151 .any(|selection| crease.range().overlaps(&selection.range()));
12152
12153 self.fold_creases(vec![crease], autoscroll, window, cx);
12154 }
12155 }
12156
12157 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12158 if self.is_singleton(cx) {
12159 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12160 let buffer = &display_map.buffer_snapshot;
12161 let selections = self.selections.all::<Point>(cx);
12162 let ranges = selections
12163 .iter()
12164 .map(|s| {
12165 let range = s.display_range(&display_map).sorted();
12166 let mut start = range.start.to_point(&display_map);
12167 let mut end = range.end.to_point(&display_map);
12168 start.column = 0;
12169 end.column = buffer.line_len(MultiBufferRow(end.row));
12170 start..end
12171 })
12172 .collect::<Vec<_>>();
12173
12174 self.unfold_ranges(&ranges, true, true, cx);
12175 } else {
12176 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12177 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12178 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12179 .map(|(snapshot, _, _)| snapshot.remote_id())
12180 .collect();
12181 for buffer_id in buffer_ids {
12182 self.unfold_buffer(buffer_id, cx);
12183 }
12184 }
12185 }
12186
12187 pub fn unfold_recursive(
12188 &mut self,
12189 _: &UnfoldRecursive,
12190 _window: &mut Window,
12191 cx: &mut Context<Self>,
12192 ) {
12193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12194 let selections = self.selections.all::<Point>(cx);
12195 let ranges = selections
12196 .iter()
12197 .map(|s| {
12198 let mut range = s.display_range(&display_map).sorted();
12199 *range.start.column_mut() = 0;
12200 *range.end.column_mut() = display_map.line_len(range.end.row());
12201 let start = range.start.to_point(&display_map);
12202 let end = range.end.to_point(&display_map);
12203 start..end
12204 })
12205 .collect::<Vec<_>>();
12206
12207 self.unfold_ranges(&ranges, true, true, cx);
12208 }
12209
12210 pub fn unfold_at(
12211 &mut self,
12212 unfold_at: &UnfoldAt,
12213 _window: &mut Window,
12214 cx: &mut Context<Self>,
12215 ) {
12216 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12217
12218 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12219 ..Point::new(
12220 unfold_at.buffer_row.0,
12221 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12222 );
12223
12224 let autoscroll = self
12225 .selections
12226 .all::<Point>(cx)
12227 .iter()
12228 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12229
12230 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12231 }
12232
12233 pub fn unfold_all(
12234 &mut self,
12235 _: &actions::UnfoldAll,
12236 _window: &mut Window,
12237 cx: &mut Context<Self>,
12238 ) {
12239 if self.buffer.read(cx).is_singleton() {
12240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12241 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12242 } else {
12243 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12244 editor
12245 .update(&mut cx, |editor, cx| {
12246 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12247 editor.unfold_buffer(buffer_id, cx);
12248 }
12249 })
12250 .ok();
12251 });
12252 }
12253 }
12254
12255 pub fn fold_selected_ranges(
12256 &mut self,
12257 _: &FoldSelectedRanges,
12258 window: &mut Window,
12259 cx: &mut Context<Self>,
12260 ) {
12261 let selections = self.selections.all::<Point>(cx);
12262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12263 let line_mode = self.selections.line_mode;
12264 let ranges = selections
12265 .into_iter()
12266 .map(|s| {
12267 if line_mode {
12268 let start = Point::new(s.start.row, 0);
12269 let end = Point::new(
12270 s.end.row,
12271 display_map
12272 .buffer_snapshot
12273 .line_len(MultiBufferRow(s.end.row)),
12274 );
12275 Crease::simple(start..end, display_map.fold_placeholder.clone())
12276 } else {
12277 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12278 }
12279 })
12280 .collect::<Vec<_>>();
12281 self.fold_creases(ranges, true, window, cx);
12282 }
12283
12284 pub fn fold_ranges<T: ToOffset + Clone>(
12285 &mut self,
12286 ranges: Vec<Range<T>>,
12287 auto_scroll: bool,
12288 window: &mut Window,
12289 cx: &mut Context<Self>,
12290 ) {
12291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12292 let ranges = ranges
12293 .into_iter()
12294 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12295 .collect::<Vec<_>>();
12296 self.fold_creases(ranges, auto_scroll, window, cx);
12297 }
12298
12299 pub fn fold_creases<T: ToOffset + Clone>(
12300 &mut self,
12301 creases: Vec<Crease<T>>,
12302 auto_scroll: bool,
12303 window: &mut Window,
12304 cx: &mut Context<Self>,
12305 ) {
12306 if creases.is_empty() {
12307 return;
12308 }
12309
12310 let mut buffers_affected = HashSet::default();
12311 let multi_buffer = self.buffer().read(cx);
12312 for crease in &creases {
12313 if let Some((_, buffer, _)) =
12314 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12315 {
12316 buffers_affected.insert(buffer.read(cx).remote_id());
12317 };
12318 }
12319
12320 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12321
12322 if auto_scroll {
12323 self.request_autoscroll(Autoscroll::fit(), cx);
12324 }
12325
12326 cx.notify();
12327
12328 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12329 // Clear diagnostics block when folding a range that contains it.
12330 let snapshot = self.snapshot(window, cx);
12331 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12332 drop(snapshot);
12333 self.active_diagnostics = Some(active_diagnostics);
12334 self.dismiss_diagnostics(cx);
12335 } else {
12336 self.active_diagnostics = Some(active_diagnostics);
12337 }
12338 }
12339
12340 self.scrollbar_marker_state.dirty = true;
12341 }
12342
12343 /// Removes any folds whose ranges intersect any of the given ranges.
12344 pub fn unfold_ranges<T: ToOffset + Clone>(
12345 &mut self,
12346 ranges: &[Range<T>],
12347 inclusive: bool,
12348 auto_scroll: bool,
12349 cx: &mut Context<Self>,
12350 ) {
12351 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12352 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12353 });
12354 }
12355
12356 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12357 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12358 return;
12359 }
12360 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12361 self.display_map
12362 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12363 cx.emit(EditorEvent::BufferFoldToggled {
12364 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12365 folded: true,
12366 });
12367 cx.notify();
12368 }
12369
12370 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12371 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12372 return;
12373 }
12374 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12375 self.display_map.update(cx, |display_map, cx| {
12376 display_map.unfold_buffer(buffer_id, cx);
12377 });
12378 cx.emit(EditorEvent::BufferFoldToggled {
12379 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12380 folded: false,
12381 });
12382 cx.notify();
12383 }
12384
12385 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12386 self.display_map.read(cx).is_buffer_folded(buffer)
12387 }
12388
12389 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12390 self.display_map.read(cx).folded_buffers()
12391 }
12392
12393 /// Removes any folds with the given ranges.
12394 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12395 &mut self,
12396 ranges: &[Range<T>],
12397 type_id: TypeId,
12398 auto_scroll: bool,
12399 cx: &mut Context<Self>,
12400 ) {
12401 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12402 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12403 });
12404 }
12405
12406 fn remove_folds_with<T: ToOffset + Clone>(
12407 &mut self,
12408 ranges: &[Range<T>],
12409 auto_scroll: bool,
12410 cx: &mut Context<Self>,
12411 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12412 ) {
12413 if ranges.is_empty() {
12414 return;
12415 }
12416
12417 let mut buffers_affected = HashSet::default();
12418 let multi_buffer = self.buffer().read(cx);
12419 for range in ranges {
12420 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12421 buffers_affected.insert(buffer.read(cx).remote_id());
12422 };
12423 }
12424
12425 self.display_map.update(cx, update);
12426
12427 if auto_scroll {
12428 self.request_autoscroll(Autoscroll::fit(), cx);
12429 }
12430
12431 cx.notify();
12432 self.scrollbar_marker_state.dirty = true;
12433 self.active_indent_guides_state.dirty = true;
12434 }
12435
12436 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12437 self.display_map.read(cx).fold_placeholder.clone()
12438 }
12439
12440 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12441 self.buffer.update(cx, |buffer, cx| {
12442 buffer.set_all_diff_hunks_expanded(cx);
12443 });
12444 }
12445
12446 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12447 self.distinguish_unstaged_diff_hunks = true;
12448 }
12449
12450 pub fn expand_all_diff_hunks(
12451 &mut self,
12452 _: &ExpandAllHunkDiffs,
12453 _window: &mut Window,
12454 cx: &mut Context<Self>,
12455 ) {
12456 self.buffer.update(cx, |buffer, cx| {
12457 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12458 });
12459 }
12460
12461 pub fn toggle_selected_diff_hunks(
12462 &mut self,
12463 _: &ToggleSelectedDiffHunks,
12464 _window: &mut Window,
12465 cx: &mut Context<Self>,
12466 ) {
12467 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12468 self.toggle_diff_hunks_in_ranges(ranges, cx);
12469 }
12470
12471 fn diff_hunks_in_ranges<'a>(
12472 &'a self,
12473 ranges: &'a [Range<Anchor>],
12474 buffer: &'a MultiBufferSnapshot,
12475 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12476 ranges.iter().flat_map(move |range| {
12477 let end_excerpt_id = range.end.excerpt_id;
12478 let range = range.to_point(buffer);
12479 let mut peek_end = range.end;
12480 if range.end.row < buffer.max_row().0 {
12481 peek_end = Point::new(range.end.row + 1, 0);
12482 }
12483 buffer
12484 .diff_hunks_in_range(range.start..peek_end)
12485 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12486 })
12487 }
12488
12489 pub fn has_stageable_diff_hunks_in_ranges(
12490 &self,
12491 ranges: &[Range<Anchor>],
12492 snapshot: &MultiBufferSnapshot,
12493 ) -> bool {
12494 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12495 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12496 }
12497
12498 pub fn toggle_staged_selected_diff_hunks(
12499 &mut self,
12500 _: &ToggleStagedSelectedDiffHunks,
12501 _window: &mut Window,
12502 cx: &mut Context<Self>,
12503 ) {
12504 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12505 self.stage_or_unstage_diff_hunks(&ranges, cx);
12506 }
12507
12508 pub fn stage_or_unstage_diff_hunks(
12509 &mut self,
12510 ranges: &[Range<Anchor>],
12511 cx: &mut Context<Self>,
12512 ) {
12513 let Some(project) = &self.project else {
12514 return;
12515 };
12516 let snapshot = self.buffer.read(cx).snapshot(cx);
12517 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12518
12519 let chunk_by = self
12520 .diff_hunks_in_ranges(&ranges, &snapshot)
12521 .chunk_by(|hunk| hunk.buffer_id);
12522 for (buffer_id, hunks) in &chunk_by {
12523 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12524 log::debug!("no buffer for id");
12525 continue;
12526 };
12527 let buffer = buffer.read(cx).snapshot();
12528 let Some((repo, path)) = project
12529 .read(cx)
12530 .repository_and_path_for_buffer_id(buffer_id, cx)
12531 else {
12532 log::debug!("no git repo for buffer id");
12533 continue;
12534 };
12535 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12536 log::debug!("no diff for buffer id");
12537 continue;
12538 };
12539 let Some(secondary_diff) = diff.secondary_diff() else {
12540 log::debug!("no secondary diff for buffer id");
12541 continue;
12542 };
12543
12544 let edits = diff.secondary_edits_for_stage_or_unstage(
12545 stage,
12546 hunks.map(|hunk| {
12547 (
12548 hunk.diff_base_byte_range.clone(),
12549 hunk.secondary_diff_base_byte_range.clone(),
12550 hunk.buffer_range.clone(),
12551 )
12552 }),
12553 &buffer,
12554 );
12555
12556 let index_base = secondary_diff.base_text().map_or_else(
12557 || Rope::from(""),
12558 |snapshot| snapshot.text.as_rope().clone(),
12559 );
12560 let index_buffer = cx.new(|cx| {
12561 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12562 });
12563 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12564 index_buffer.edit(edits, None, cx);
12565 index_buffer.snapshot().as_rope().to_string()
12566 });
12567 let new_index_text = if new_index_text.is_empty()
12568 && (diff.is_single_insertion
12569 || buffer
12570 .file()
12571 .map_or(false, |file| file.disk_state() == DiskState::New))
12572 {
12573 log::debug!("removing from index");
12574 None
12575 } else {
12576 Some(new_index_text)
12577 };
12578
12579 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12580 }
12581 }
12582
12583 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12584 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12585 self.buffer
12586 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12587 }
12588
12589 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12590 self.buffer.update(cx, |buffer, cx| {
12591 let ranges = vec![Anchor::min()..Anchor::max()];
12592 if !buffer.all_diff_hunks_expanded()
12593 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12594 {
12595 buffer.collapse_diff_hunks(ranges, cx);
12596 true
12597 } else {
12598 false
12599 }
12600 })
12601 }
12602
12603 fn toggle_diff_hunks_in_ranges(
12604 &mut self,
12605 ranges: Vec<Range<Anchor>>,
12606 cx: &mut Context<'_, Editor>,
12607 ) {
12608 self.buffer.update(cx, |buffer, cx| {
12609 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12610 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12611 })
12612 }
12613
12614 fn toggle_diff_hunks_in_ranges_narrow(
12615 &mut self,
12616 ranges: Vec<Range<Anchor>>,
12617 cx: &mut Context<'_, Editor>,
12618 ) {
12619 self.buffer.update(cx, |buffer, cx| {
12620 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12621 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12622 })
12623 }
12624
12625 pub(crate) fn apply_all_diff_hunks(
12626 &mut self,
12627 _: &ApplyAllDiffHunks,
12628 window: &mut Window,
12629 cx: &mut Context<Self>,
12630 ) {
12631 let buffers = self.buffer.read(cx).all_buffers();
12632 for branch_buffer in buffers {
12633 branch_buffer.update(cx, |branch_buffer, cx| {
12634 branch_buffer.merge_into_base(Vec::new(), cx);
12635 });
12636 }
12637
12638 if let Some(project) = self.project.clone() {
12639 self.save(true, project, window, cx).detach_and_log_err(cx);
12640 }
12641 }
12642
12643 pub(crate) fn apply_selected_diff_hunks(
12644 &mut self,
12645 _: &ApplyDiffHunk,
12646 window: &mut Window,
12647 cx: &mut Context<Self>,
12648 ) {
12649 let snapshot = self.snapshot(window, cx);
12650 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12651 let mut ranges_by_buffer = HashMap::default();
12652 self.transact(window, cx, |editor, _window, cx| {
12653 for hunk in hunks {
12654 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12655 ranges_by_buffer
12656 .entry(buffer.clone())
12657 .or_insert_with(Vec::new)
12658 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12659 }
12660 }
12661
12662 for (buffer, ranges) in ranges_by_buffer {
12663 buffer.update(cx, |buffer, cx| {
12664 buffer.merge_into_base(ranges, cx);
12665 });
12666 }
12667 });
12668
12669 if let Some(project) = self.project.clone() {
12670 self.save(true, project, window, cx).detach_and_log_err(cx);
12671 }
12672 }
12673
12674 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12675 if hovered != self.gutter_hovered {
12676 self.gutter_hovered = hovered;
12677 cx.notify();
12678 }
12679 }
12680
12681 pub fn insert_blocks(
12682 &mut self,
12683 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12684 autoscroll: Option<Autoscroll>,
12685 cx: &mut Context<Self>,
12686 ) -> Vec<CustomBlockId> {
12687 let blocks = self
12688 .display_map
12689 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12690 if let Some(autoscroll) = autoscroll {
12691 self.request_autoscroll(autoscroll, cx);
12692 }
12693 cx.notify();
12694 blocks
12695 }
12696
12697 pub fn resize_blocks(
12698 &mut self,
12699 heights: HashMap<CustomBlockId, u32>,
12700 autoscroll: Option<Autoscroll>,
12701 cx: &mut Context<Self>,
12702 ) {
12703 self.display_map
12704 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12705 if let Some(autoscroll) = autoscroll {
12706 self.request_autoscroll(autoscroll, cx);
12707 }
12708 cx.notify();
12709 }
12710
12711 pub fn replace_blocks(
12712 &mut self,
12713 renderers: HashMap<CustomBlockId, RenderBlock>,
12714 autoscroll: Option<Autoscroll>,
12715 cx: &mut Context<Self>,
12716 ) {
12717 self.display_map
12718 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12719 if let Some(autoscroll) = autoscroll {
12720 self.request_autoscroll(autoscroll, cx);
12721 }
12722 cx.notify();
12723 }
12724
12725 pub fn remove_blocks(
12726 &mut self,
12727 block_ids: HashSet<CustomBlockId>,
12728 autoscroll: Option<Autoscroll>,
12729 cx: &mut Context<Self>,
12730 ) {
12731 self.display_map.update(cx, |display_map, cx| {
12732 display_map.remove_blocks(block_ids, cx)
12733 });
12734 if let Some(autoscroll) = autoscroll {
12735 self.request_autoscroll(autoscroll, cx);
12736 }
12737 cx.notify();
12738 }
12739
12740 pub fn row_for_block(
12741 &self,
12742 block_id: CustomBlockId,
12743 cx: &mut Context<Self>,
12744 ) -> Option<DisplayRow> {
12745 self.display_map
12746 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12747 }
12748
12749 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12750 self.focused_block = Some(focused_block);
12751 }
12752
12753 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12754 self.focused_block.take()
12755 }
12756
12757 pub fn insert_creases(
12758 &mut self,
12759 creases: impl IntoIterator<Item = Crease<Anchor>>,
12760 cx: &mut Context<Self>,
12761 ) -> Vec<CreaseId> {
12762 self.display_map
12763 .update(cx, |map, cx| map.insert_creases(creases, cx))
12764 }
12765
12766 pub fn remove_creases(
12767 &mut self,
12768 ids: impl IntoIterator<Item = CreaseId>,
12769 cx: &mut Context<Self>,
12770 ) {
12771 self.display_map
12772 .update(cx, |map, cx| map.remove_creases(ids, cx));
12773 }
12774
12775 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12776 self.display_map
12777 .update(cx, |map, cx| map.snapshot(cx))
12778 .longest_row()
12779 }
12780
12781 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12782 self.display_map
12783 .update(cx, |map, cx| map.snapshot(cx))
12784 .max_point()
12785 }
12786
12787 pub fn text(&self, cx: &App) -> String {
12788 self.buffer.read(cx).read(cx).text()
12789 }
12790
12791 pub fn is_empty(&self, cx: &App) -> bool {
12792 self.buffer.read(cx).read(cx).is_empty()
12793 }
12794
12795 pub fn text_option(&self, cx: &App) -> Option<String> {
12796 let text = self.text(cx);
12797 let text = text.trim();
12798
12799 if text.is_empty() {
12800 return None;
12801 }
12802
12803 Some(text.to_string())
12804 }
12805
12806 pub fn set_text(
12807 &mut self,
12808 text: impl Into<Arc<str>>,
12809 window: &mut Window,
12810 cx: &mut Context<Self>,
12811 ) {
12812 self.transact(window, cx, |this, _, cx| {
12813 this.buffer
12814 .read(cx)
12815 .as_singleton()
12816 .expect("you can only call set_text on editors for singleton buffers")
12817 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12818 });
12819 }
12820
12821 pub fn display_text(&self, cx: &mut App) -> String {
12822 self.display_map
12823 .update(cx, |map, cx| map.snapshot(cx))
12824 .text()
12825 }
12826
12827 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12828 let mut wrap_guides = smallvec::smallvec![];
12829
12830 if self.show_wrap_guides == Some(false) {
12831 return wrap_guides;
12832 }
12833
12834 let settings = self.buffer.read(cx).settings_at(0, cx);
12835 if settings.show_wrap_guides {
12836 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12837 wrap_guides.push((soft_wrap as usize, true));
12838 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12839 wrap_guides.push((soft_wrap as usize, true));
12840 }
12841 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12842 }
12843
12844 wrap_guides
12845 }
12846
12847 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12848 let settings = self.buffer.read(cx).settings_at(0, cx);
12849 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12850 match mode {
12851 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12852 SoftWrap::None
12853 }
12854 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12855 language_settings::SoftWrap::PreferredLineLength => {
12856 SoftWrap::Column(settings.preferred_line_length)
12857 }
12858 language_settings::SoftWrap::Bounded => {
12859 SoftWrap::Bounded(settings.preferred_line_length)
12860 }
12861 }
12862 }
12863
12864 pub fn set_soft_wrap_mode(
12865 &mut self,
12866 mode: language_settings::SoftWrap,
12867
12868 cx: &mut Context<Self>,
12869 ) {
12870 self.soft_wrap_mode_override = Some(mode);
12871 cx.notify();
12872 }
12873
12874 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12875 self.text_style_refinement = Some(style);
12876 }
12877
12878 /// called by the Element so we know what style we were most recently rendered with.
12879 pub(crate) fn set_style(
12880 &mut self,
12881 style: EditorStyle,
12882 window: &mut Window,
12883 cx: &mut Context<Self>,
12884 ) {
12885 let rem_size = window.rem_size();
12886 self.display_map.update(cx, |map, cx| {
12887 map.set_font(
12888 style.text.font(),
12889 style.text.font_size.to_pixels(rem_size),
12890 cx,
12891 )
12892 });
12893 self.style = Some(style);
12894 }
12895
12896 pub fn style(&self) -> Option<&EditorStyle> {
12897 self.style.as_ref()
12898 }
12899
12900 // Called by the element. This method is not designed to be called outside of the editor
12901 // element's layout code because it does not notify when rewrapping is computed synchronously.
12902 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12903 self.display_map
12904 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12905 }
12906
12907 pub fn set_soft_wrap(&mut self) {
12908 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12909 }
12910
12911 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12912 if self.soft_wrap_mode_override.is_some() {
12913 self.soft_wrap_mode_override.take();
12914 } else {
12915 let soft_wrap = match self.soft_wrap_mode(cx) {
12916 SoftWrap::GitDiff => return,
12917 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12918 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12919 language_settings::SoftWrap::None
12920 }
12921 };
12922 self.soft_wrap_mode_override = Some(soft_wrap);
12923 }
12924 cx.notify();
12925 }
12926
12927 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12928 let Some(workspace) = self.workspace() else {
12929 return;
12930 };
12931 let fs = workspace.read(cx).app_state().fs.clone();
12932 let current_show = TabBarSettings::get_global(cx).show;
12933 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12934 setting.show = Some(!current_show);
12935 });
12936 }
12937
12938 pub fn toggle_indent_guides(
12939 &mut self,
12940 _: &ToggleIndentGuides,
12941 _: &mut Window,
12942 cx: &mut Context<Self>,
12943 ) {
12944 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12945 self.buffer
12946 .read(cx)
12947 .settings_at(0, cx)
12948 .indent_guides
12949 .enabled
12950 });
12951 self.show_indent_guides = Some(!currently_enabled);
12952 cx.notify();
12953 }
12954
12955 fn should_show_indent_guides(&self) -> Option<bool> {
12956 self.show_indent_guides
12957 }
12958
12959 pub fn toggle_line_numbers(
12960 &mut self,
12961 _: &ToggleLineNumbers,
12962 _: &mut Window,
12963 cx: &mut Context<Self>,
12964 ) {
12965 let mut editor_settings = EditorSettings::get_global(cx).clone();
12966 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12967 EditorSettings::override_global(editor_settings, cx);
12968 }
12969
12970 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12971 self.use_relative_line_numbers
12972 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12973 }
12974
12975 pub fn toggle_relative_line_numbers(
12976 &mut self,
12977 _: &ToggleRelativeLineNumbers,
12978 _: &mut Window,
12979 cx: &mut Context<Self>,
12980 ) {
12981 let is_relative = self.should_use_relative_line_numbers(cx);
12982 self.set_relative_line_number(Some(!is_relative), cx)
12983 }
12984
12985 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12986 self.use_relative_line_numbers = is_relative;
12987 cx.notify();
12988 }
12989
12990 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12991 self.show_gutter = show_gutter;
12992 cx.notify();
12993 }
12994
12995 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12996 self.show_scrollbars = show_scrollbars;
12997 cx.notify();
12998 }
12999
13000 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13001 self.show_line_numbers = Some(show_line_numbers);
13002 cx.notify();
13003 }
13004
13005 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13006 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13007 cx.notify();
13008 }
13009
13010 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13011 self.show_code_actions = Some(show_code_actions);
13012 cx.notify();
13013 }
13014
13015 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13016 self.show_runnables = Some(show_runnables);
13017 cx.notify();
13018 }
13019
13020 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13021 if self.display_map.read(cx).masked != masked {
13022 self.display_map.update(cx, |map, _| map.masked = masked);
13023 }
13024 cx.notify()
13025 }
13026
13027 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13028 self.show_wrap_guides = Some(show_wrap_guides);
13029 cx.notify();
13030 }
13031
13032 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13033 self.show_indent_guides = Some(show_indent_guides);
13034 cx.notify();
13035 }
13036
13037 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13038 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13039 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13040 if let Some(dir) = file.abs_path(cx).parent() {
13041 return Some(dir.to_owned());
13042 }
13043 }
13044
13045 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13046 return Some(project_path.path.to_path_buf());
13047 }
13048 }
13049
13050 None
13051 }
13052
13053 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13054 self.active_excerpt(cx)?
13055 .1
13056 .read(cx)
13057 .file()
13058 .and_then(|f| f.as_local())
13059 }
13060
13061 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13062 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13063 let buffer = buffer.read(cx);
13064 if let Some(project_path) = buffer.project_path(cx) {
13065 let project = self.project.as_ref()?.read(cx);
13066 project.absolute_path(&project_path, cx)
13067 } else {
13068 buffer
13069 .file()
13070 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13071 }
13072 })
13073 }
13074
13075 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13076 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13077 let project_path = buffer.read(cx).project_path(cx)?;
13078 let project = self.project.as_ref()?.read(cx);
13079 let entry = project.entry_for_path(&project_path, cx)?;
13080 let path = entry.path.to_path_buf();
13081 Some(path)
13082 })
13083 }
13084
13085 pub fn reveal_in_finder(
13086 &mut self,
13087 _: &RevealInFileManager,
13088 _window: &mut Window,
13089 cx: &mut Context<Self>,
13090 ) {
13091 if let Some(target) = self.target_file(cx) {
13092 cx.reveal_path(&target.abs_path(cx));
13093 }
13094 }
13095
13096 pub fn copy_path(
13097 &mut self,
13098 _: &zed_actions::workspace::CopyPath,
13099 _window: &mut Window,
13100 cx: &mut Context<Self>,
13101 ) {
13102 if let Some(path) = self.target_file_abs_path(cx) {
13103 if let Some(path) = path.to_str() {
13104 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13105 }
13106 }
13107 }
13108
13109 pub fn copy_relative_path(
13110 &mut self,
13111 _: &zed_actions::workspace::CopyRelativePath,
13112 _window: &mut Window,
13113 cx: &mut Context<Self>,
13114 ) {
13115 if let Some(path) = self.target_file_path(cx) {
13116 if let Some(path) = path.to_str() {
13117 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13118 }
13119 }
13120 }
13121
13122 pub fn copy_file_name_without_extension(
13123 &mut self,
13124 _: &CopyFileNameWithoutExtension,
13125 _: &mut Window,
13126 cx: &mut Context<Self>,
13127 ) {
13128 if let Some(file) = self.target_file(cx) {
13129 if let Some(file_stem) = file.path().file_stem() {
13130 if let Some(name) = file_stem.to_str() {
13131 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13132 }
13133 }
13134 }
13135 }
13136
13137 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13138 if let Some(file) = self.target_file(cx) {
13139 if let Some(file_name) = file.path().file_name() {
13140 if let Some(name) = file_name.to_str() {
13141 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13142 }
13143 }
13144 }
13145 }
13146
13147 pub fn toggle_git_blame(
13148 &mut self,
13149 _: &ToggleGitBlame,
13150 window: &mut Window,
13151 cx: &mut Context<Self>,
13152 ) {
13153 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13154
13155 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13156 self.start_git_blame(true, window, cx);
13157 }
13158
13159 cx.notify();
13160 }
13161
13162 pub fn toggle_git_blame_inline(
13163 &mut self,
13164 _: &ToggleGitBlameInline,
13165 window: &mut Window,
13166 cx: &mut Context<Self>,
13167 ) {
13168 self.toggle_git_blame_inline_internal(true, window, cx);
13169 cx.notify();
13170 }
13171
13172 pub fn git_blame_inline_enabled(&self) -> bool {
13173 self.git_blame_inline_enabled
13174 }
13175
13176 pub fn toggle_selection_menu(
13177 &mut self,
13178 _: &ToggleSelectionMenu,
13179 _: &mut Window,
13180 cx: &mut Context<Self>,
13181 ) {
13182 self.show_selection_menu = self
13183 .show_selection_menu
13184 .map(|show_selections_menu| !show_selections_menu)
13185 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13186
13187 cx.notify();
13188 }
13189
13190 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13191 self.show_selection_menu
13192 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13193 }
13194
13195 fn start_git_blame(
13196 &mut self,
13197 user_triggered: bool,
13198 window: &mut Window,
13199 cx: &mut Context<Self>,
13200 ) {
13201 if let Some(project) = self.project.as_ref() {
13202 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13203 return;
13204 };
13205
13206 if buffer.read(cx).file().is_none() {
13207 return;
13208 }
13209
13210 let focused = self.focus_handle(cx).contains_focused(window, cx);
13211
13212 let project = project.clone();
13213 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13214 self.blame_subscription =
13215 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13216 self.blame = Some(blame);
13217 }
13218 }
13219
13220 fn toggle_git_blame_inline_internal(
13221 &mut self,
13222 user_triggered: bool,
13223 window: &mut Window,
13224 cx: &mut Context<Self>,
13225 ) {
13226 if self.git_blame_inline_enabled {
13227 self.git_blame_inline_enabled = false;
13228 self.show_git_blame_inline = false;
13229 self.show_git_blame_inline_delay_task.take();
13230 } else {
13231 self.git_blame_inline_enabled = true;
13232 self.start_git_blame_inline(user_triggered, window, cx);
13233 }
13234
13235 cx.notify();
13236 }
13237
13238 fn start_git_blame_inline(
13239 &mut self,
13240 user_triggered: bool,
13241 window: &mut Window,
13242 cx: &mut Context<Self>,
13243 ) {
13244 self.start_git_blame(user_triggered, window, cx);
13245
13246 if ProjectSettings::get_global(cx)
13247 .git
13248 .inline_blame_delay()
13249 .is_some()
13250 {
13251 self.start_inline_blame_timer(window, cx);
13252 } else {
13253 self.show_git_blame_inline = true
13254 }
13255 }
13256
13257 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13258 self.blame.as_ref()
13259 }
13260
13261 pub fn show_git_blame_gutter(&self) -> bool {
13262 self.show_git_blame_gutter
13263 }
13264
13265 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13266 self.show_git_blame_gutter && self.has_blame_entries(cx)
13267 }
13268
13269 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13270 self.show_git_blame_inline
13271 && self.focus_handle.is_focused(window)
13272 && !self.newest_selection_head_on_empty_line(cx)
13273 && self.has_blame_entries(cx)
13274 }
13275
13276 fn has_blame_entries(&self, cx: &App) -> bool {
13277 self.blame()
13278 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13279 }
13280
13281 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13282 let cursor_anchor = self.selections.newest_anchor().head();
13283
13284 let snapshot = self.buffer.read(cx).snapshot(cx);
13285 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13286
13287 snapshot.line_len(buffer_row) == 0
13288 }
13289
13290 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13291 let buffer_and_selection = maybe!({
13292 let selection = self.selections.newest::<Point>(cx);
13293 let selection_range = selection.range();
13294
13295 let multi_buffer = self.buffer().read(cx);
13296 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13297 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13298
13299 let (buffer, range, _) = if selection.reversed {
13300 buffer_ranges.first()
13301 } else {
13302 buffer_ranges.last()
13303 }?;
13304
13305 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13306 ..text::ToPoint::to_point(&range.end, &buffer).row;
13307 Some((
13308 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13309 selection,
13310 ))
13311 });
13312
13313 let Some((buffer, selection)) = buffer_and_selection else {
13314 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13315 };
13316
13317 let Some(project) = self.project.as_ref() else {
13318 return Task::ready(Err(anyhow!("editor does not have project")));
13319 };
13320
13321 project.update(cx, |project, cx| {
13322 project.get_permalink_to_line(&buffer, selection, cx)
13323 })
13324 }
13325
13326 pub fn copy_permalink_to_line(
13327 &mut self,
13328 _: &CopyPermalinkToLine,
13329 window: &mut Window,
13330 cx: &mut Context<Self>,
13331 ) {
13332 let permalink_task = self.get_permalink_to_line(cx);
13333 let workspace = self.workspace();
13334
13335 cx.spawn_in(window, |_, mut cx| async move {
13336 match permalink_task.await {
13337 Ok(permalink) => {
13338 cx.update(|_, cx| {
13339 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13340 })
13341 .ok();
13342 }
13343 Err(err) => {
13344 let message = format!("Failed to copy permalink: {err}");
13345
13346 Err::<(), anyhow::Error>(err).log_err();
13347
13348 if let Some(workspace) = workspace {
13349 workspace
13350 .update_in(&mut cx, |workspace, _, cx| {
13351 struct CopyPermalinkToLine;
13352
13353 workspace.show_toast(
13354 Toast::new(
13355 NotificationId::unique::<CopyPermalinkToLine>(),
13356 message,
13357 ),
13358 cx,
13359 )
13360 })
13361 .ok();
13362 }
13363 }
13364 }
13365 })
13366 .detach();
13367 }
13368
13369 pub fn copy_file_location(
13370 &mut self,
13371 _: &CopyFileLocation,
13372 _: &mut Window,
13373 cx: &mut Context<Self>,
13374 ) {
13375 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13376 if let Some(file) = self.target_file(cx) {
13377 if let Some(path) = file.path().to_str() {
13378 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13379 }
13380 }
13381 }
13382
13383 pub fn open_permalink_to_line(
13384 &mut self,
13385 _: &OpenPermalinkToLine,
13386 window: &mut Window,
13387 cx: &mut Context<Self>,
13388 ) {
13389 let permalink_task = self.get_permalink_to_line(cx);
13390 let workspace = self.workspace();
13391
13392 cx.spawn_in(window, |_, mut cx| async move {
13393 match permalink_task.await {
13394 Ok(permalink) => {
13395 cx.update(|_, cx| {
13396 cx.open_url(permalink.as_ref());
13397 })
13398 .ok();
13399 }
13400 Err(err) => {
13401 let message = format!("Failed to open permalink: {err}");
13402
13403 Err::<(), anyhow::Error>(err).log_err();
13404
13405 if let Some(workspace) = workspace {
13406 workspace
13407 .update(&mut cx, |workspace, cx| {
13408 struct OpenPermalinkToLine;
13409
13410 workspace.show_toast(
13411 Toast::new(
13412 NotificationId::unique::<OpenPermalinkToLine>(),
13413 message,
13414 ),
13415 cx,
13416 )
13417 })
13418 .ok();
13419 }
13420 }
13421 }
13422 })
13423 .detach();
13424 }
13425
13426 pub fn insert_uuid_v4(
13427 &mut self,
13428 _: &InsertUuidV4,
13429 window: &mut Window,
13430 cx: &mut Context<Self>,
13431 ) {
13432 self.insert_uuid(UuidVersion::V4, window, cx);
13433 }
13434
13435 pub fn insert_uuid_v7(
13436 &mut self,
13437 _: &InsertUuidV7,
13438 window: &mut Window,
13439 cx: &mut Context<Self>,
13440 ) {
13441 self.insert_uuid(UuidVersion::V7, window, cx);
13442 }
13443
13444 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13445 self.transact(window, cx, |this, window, cx| {
13446 let edits = this
13447 .selections
13448 .all::<Point>(cx)
13449 .into_iter()
13450 .map(|selection| {
13451 let uuid = match version {
13452 UuidVersion::V4 => uuid::Uuid::new_v4(),
13453 UuidVersion::V7 => uuid::Uuid::now_v7(),
13454 };
13455
13456 (selection.range(), uuid.to_string())
13457 });
13458 this.edit(edits, cx);
13459 this.refresh_inline_completion(true, false, window, cx);
13460 });
13461 }
13462
13463 pub fn open_selections_in_multibuffer(
13464 &mut self,
13465 _: &OpenSelectionsInMultibuffer,
13466 window: &mut Window,
13467 cx: &mut Context<Self>,
13468 ) {
13469 let multibuffer = self.buffer.read(cx);
13470
13471 let Some(buffer) = multibuffer.as_singleton() else {
13472 return;
13473 };
13474
13475 let Some(workspace) = self.workspace() else {
13476 return;
13477 };
13478
13479 let locations = self
13480 .selections
13481 .disjoint_anchors()
13482 .iter()
13483 .map(|range| Location {
13484 buffer: buffer.clone(),
13485 range: range.start.text_anchor..range.end.text_anchor,
13486 })
13487 .collect::<Vec<_>>();
13488
13489 let title = multibuffer.title(cx).to_string();
13490
13491 cx.spawn_in(window, |_, mut cx| async move {
13492 workspace.update_in(&mut cx, |workspace, window, cx| {
13493 Self::open_locations_in_multibuffer(
13494 workspace,
13495 locations,
13496 format!("Selections for '{title}'"),
13497 false,
13498 MultibufferSelectionMode::All,
13499 window,
13500 cx,
13501 );
13502 })
13503 })
13504 .detach();
13505 }
13506
13507 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13508 /// last highlight added will be used.
13509 ///
13510 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13511 pub fn highlight_rows<T: 'static>(
13512 &mut self,
13513 range: Range<Anchor>,
13514 color: Hsla,
13515 should_autoscroll: bool,
13516 cx: &mut Context<Self>,
13517 ) {
13518 let snapshot = self.buffer().read(cx).snapshot(cx);
13519 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13520 let ix = row_highlights.binary_search_by(|highlight| {
13521 Ordering::Equal
13522 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13523 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13524 });
13525
13526 if let Err(mut ix) = ix {
13527 let index = post_inc(&mut self.highlight_order);
13528
13529 // If this range intersects with the preceding highlight, then merge it with
13530 // the preceding highlight. Otherwise insert a new highlight.
13531 let mut merged = false;
13532 if ix > 0 {
13533 let prev_highlight = &mut row_highlights[ix - 1];
13534 if prev_highlight
13535 .range
13536 .end
13537 .cmp(&range.start, &snapshot)
13538 .is_ge()
13539 {
13540 ix -= 1;
13541 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13542 prev_highlight.range.end = range.end;
13543 }
13544 merged = true;
13545 prev_highlight.index = index;
13546 prev_highlight.color = color;
13547 prev_highlight.should_autoscroll = should_autoscroll;
13548 }
13549 }
13550
13551 if !merged {
13552 row_highlights.insert(
13553 ix,
13554 RowHighlight {
13555 range: range.clone(),
13556 index,
13557 color,
13558 should_autoscroll,
13559 },
13560 );
13561 }
13562
13563 // If any of the following highlights intersect with this one, merge them.
13564 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13565 let highlight = &row_highlights[ix];
13566 if next_highlight
13567 .range
13568 .start
13569 .cmp(&highlight.range.end, &snapshot)
13570 .is_le()
13571 {
13572 if next_highlight
13573 .range
13574 .end
13575 .cmp(&highlight.range.end, &snapshot)
13576 .is_gt()
13577 {
13578 row_highlights[ix].range.end = next_highlight.range.end;
13579 }
13580 row_highlights.remove(ix + 1);
13581 } else {
13582 break;
13583 }
13584 }
13585 }
13586 }
13587
13588 /// Remove any highlighted row ranges of the given type that intersect the
13589 /// given ranges.
13590 pub fn remove_highlighted_rows<T: 'static>(
13591 &mut self,
13592 ranges_to_remove: Vec<Range<Anchor>>,
13593 cx: &mut Context<Self>,
13594 ) {
13595 let snapshot = self.buffer().read(cx).snapshot(cx);
13596 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13597 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13598 row_highlights.retain(|highlight| {
13599 while let Some(range_to_remove) = ranges_to_remove.peek() {
13600 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13601 Ordering::Less | Ordering::Equal => {
13602 ranges_to_remove.next();
13603 }
13604 Ordering::Greater => {
13605 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13606 Ordering::Less | Ordering::Equal => {
13607 return false;
13608 }
13609 Ordering::Greater => break,
13610 }
13611 }
13612 }
13613 }
13614
13615 true
13616 })
13617 }
13618
13619 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13620 pub fn clear_row_highlights<T: 'static>(&mut self) {
13621 self.highlighted_rows.remove(&TypeId::of::<T>());
13622 }
13623
13624 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13625 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13626 self.highlighted_rows
13627 .get(&TypeId::of::<T>())
13628 .map_or(&[] as &[_], |vec| vec.as_slice())
13629 .iter()
13630 .map(|highlight| (highlight.range.clone(), highlight.color))
13631 }
13632
13633 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13634 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13635 /// Allows to ignore certain kinds of highlights.
13636 pub fn highlighted_display_rows(
13637 &self,
13638 window: &mut Window,
13639 cx: &mut App,
13640 ) -> BTreeMap<DisplayRow, Hsla> {
13641 let snapshot = self.snapshot(window, cx);
13642 let mut used_highlight_orders = HashMap::default();
13643 self.highlighted_rows
13644 .iter()
13645 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13646 .fold(
13647 BTreeMap::<DisplayRow, Hsla>::new(),
13648 |mut unique_rows, highlight| {
13649 let start = highlight.range.start.to_display_point(&snapshot);
13650 let end = highlight.range.end.to_display_point(&snapshot);
13651 let start_row = start.row().0;
13652 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13653 && end.column() == 0
13654 {
13655 end.row().0.saturating_sub(1)
13656 } else {
13657 end.row().0
13658 };
13659 for row in start_row..=end_row {
13660 let used_index =
13661 used_highlight_orders.entry(row).or_insert(highlight.index);
13662 if highlight.index >= *used_index {
13663 *used_index = highlight.index;
13664 unique_rows.insert(DisplayRow(row), highlight.color);
13665 }
13666 }
13667 unique_rows
13668 },
13669 )
13670 }
13671
13672 pub fn highlighted_display_row_for_autoscroll(
13673 &self,
13674 snapshot: &DisplaySnapshot,
13675 ) -> Option<DisplayRow> {
13676 self.highlighted_rows
13677 .values()
13678 .flat_map(|highlighted_rows| highlighted_rows.iter())
13679 .filter_map(|highlight| {
13680 if highlight.should_autoscroll {
13681 Some(highlight.range.start.to_display_point(snapshot).row())
13682 } else {
13683 None
13684 }
13685 })
13686 .min()
13687 }
13688
13689 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13690 self.highlight_background::<SearchWithinRange>(
13691 ranges,
13692 |colors| colors.editor_document_highlight_read_background,
13693 cx,
13694 )
13695 }
13696
13697 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13698 self.breadcrumb_header = Some(new_header);
13699 }
13700
13701 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13702 self.clear_background_highlights::<SearchWithinRange>(cx);
13703 }
13704
13705 pub fn highlight_background<T: 'static>(
13706 &mut self,
13707 ranges: &[Range<Anchor>],
13708 color_fetcher: fn(&ThemeColors) -> Hsla,
13709 cx: &mut Context<Self>,
13710 ) {
13711 self.background_highlights
13712 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13713 self.scrollbar_marker_state.dirty = true;
13714 cx.notify();
13715 }
13716
13717 pub fn clear_background_highlights<T: 'static>(
13718 &mut self,
13719 cx: &mut Context<Self>,
13720 ) -> Option<BackgroundHighlight> {
13721 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13722 if !text_highlights.1.is_empty() {
13723 self.scrollbar_marker_state.dirty = true;
13724 cx.notify();
13725 }
13726 Some(text_highlights)
13727 }
13728
13729 pub fn highlight_gutter<T: 'static>(
13730 &mut self,
13731 ranges: &[Range<Anchor>],
13732 color_fetcher: fn(&App) -> Hsla,
13733 cx: &mut Context<Self>,
13734 ) {
13735 self.gutter_highlights
13736 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13737 cx.notify();
13738 }
13739
13740 pub fn clear_gutter_highlights<T: 'static>(
13741 &mut self,
13742 cx: &mut Context<Self>,
13743 ) -> Option<GutterHighlight> {
13744 cx.notify();
13745 self.gutter_highlights.remove(&TypeId::of::<T>())
13746 }
13747
13748 #[cfg(feature = "test-support")]
13749 pub fn all_text_background_highlights(
13750 &self,
13751 window: &mut Window,
13752 cx: &mut Context<Self>,
13753 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13754 let snapshot = self.snapshot(window, cx);
13755 let buffer = &snapshot.buffer_snapshot;
13756 let start = buffer.anchor_before(0);
13757 let end = buffer.anchor_after(buffer.len());
13758 let theme = cx.theme().colors();
13759 self.background_highlights_in_range(start..end, &snapshot, theme)
13760 }
13761
13762 #[cfg(feature = "test-support")]
13763 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13764 let snapshot = self.buffer().read(cx).snapshot(cx);
13765
13766 let highlights = self
13767 .background_highlights
13768 .get(&TypeId::of::<items::BufferSearchHighlights>());
13769
13770 if let Some((_color, ranges)) = highlights {
13771 ranges
13772 .iter()
13773 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13774 .collect_vec()
13775 } else {
13776 vec![]
13777 }
13778 }
13779
13780 fn document_highlights_for_position<'a>(
13781 &'a self,
13782 position: Anchor,
13783 buffer: &'a MultiBufferSnapshot,
13784 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13785 let read_highlights = self
13786 .background_highlights
13787 .get(&TypeId::of::<DocumentHighlightRead>())
13788 .map(|h| &h.1);
13789 let write_highlights = self
13790 .background_highlights
13791 .get(&TypeId::of::<DocumentHighlightWrite>())
13792 .map(|h| &h.1);
13793 let left_position = position.bias_left(buffer);
13794 let right_position = position.bias_right(buffer);
13795 read_highlights
13796 .into_iter()
13797 .chain(write_highlights)
13798 .flat_map(move |ranges| {
13799 let start_ix = match ranges.binary_search_by(|probe| {
13800 let cmp = probe.end.cmp(&left_position, buffer);
13801 if cmp.is_ge() {
13802 Ordering::Greater
13803 } else {
13804 Ordering::Less
13805 }
13806 }) {
13807 Ok(i) | Err(i) => i,
13808 };
13809
13810 ranges[start_ix..]
13811 .iter()
13812 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13813 })
13814 }
13815
13816 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13817 self.background_highlights
13818 .get(&TypeId::of::<T>())
13819 .map_or(false, |(_, highlights)| !highlights.is_empty())
13820 }
13821
13822 pub fn background_highlights_in_range(
13823 &self,
13824 search_range: Range<Anchor>,
13825 display_snapshot: &DisplaySnapshot,
13826 theme: &ThemeColors,
13827 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13828 let mut results = Vec::new();
13829 for (color_fetcher, ranges) in self.background_highlights.values() {
13830 let color = color_fetcher(theme);
13831 let start_ix = match ranges.binary_search_by(|probe| {
13832 let cmp = probe
13833 .end
13834 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13835 if cmp.is_gt() {
13836 Ordering::Greater
13837 } else {
13838 Ordering::Less
13839 }
13840 }) {
13841 Ok(i) | Err(i) => i,
13842 };
13843 for range in &ranges[start_ix..] {
13844 if range
13845 .start
13846 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13847 .is_ge()
13848 {
13849 break;
13850 }
13851
13852 let start = range.start.to_display_point(display_snapshot);
13853 let end = range.end.to_display_point(display_snapshot);
13854 results.push((start..end, color))
13855 }
13856 }
13857 results
13858 }
13859
13860 pub fn background_highlight_row_ranges<T: 'static>(
13861 &self,
13862 search_range: Range<Anchor>,
13863 display_snapshot: &DisplaySnapshot,
13864 count: usize,
13865 ) -> Vec<RangeInclusive<DisplayPoint>> {
13866 let mut results = Vec::new();
13867 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13868 return vec![];
13869 };
13870
13871 let start_ix = match ranges.binary_search_by(|probe| {
13872 let cmp = probe
13873 .end
13874 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13875 if cmp.is_gt() {
13876 Ordering::Greater
13877 } else {
13878 Ordering::Less
13879 }
13880 }) {
13881 Ok(i) | Err(i) => i,
13882 };
13883 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13884 if let (Some(start_display), Some(end_display)) = (start, end) {
13885 results.push(
13886 start_display.to_display_point(display_snapshot)
13887 ..=end_display.to_display_point(display_snapshot),
13888 );
13889 }
13890 };
13891 let mut start_row: Option<Point> = None;
13892 let mut end_row: Option<Point> = None;
13893 if ranges.len() > count {
13894 return Vec::new();
13895 }
13896 for range in &ranges[start_ix..] {
13897 if range
13898 .start
13899 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13900 .is_ge()
13901 {
13902 break;
13903 }
13904 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13905 if let Some(current_row) = &end_row {
13906 if end.row == current_row.row {
13907 continue;
13908 }
13909 }
13910 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13911 if start_row.is_none() {
13912 assert_eq!(end_row, None);
13913 start_row = Some(start);
13914 end_row = Some(end);
13915 continue;
13916 }
13917 if let Some(current_end) = end_row.as_mut() {
13918 if start.row > current_end.row + 1 {
13919 push_region(start_row, end_row);
13920 start_row = Some(start);
13921 end_row = Some(end);
13922 } else {
13923 // Merge two hunks.
13924 *current_end = end;
13925 }
13926 } else {
13927 unreachable!();
13928 }
13929 }
13930 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13931 push_region(start_row, end_row);
13932 results
13933 }
13934
13935 pub fn gutter_highlights_in_range(
13936 &self,
13937 search_range: Range<Anchor>,
13938 display_snapshot: &DisplaySnapshot,
13939 cx: &App,
13940 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13941 let mut results = Vec::new();
13942 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13943 let color = color_fetcher(cx);
13944 let start_ix = match ranges.binary_search_by(|probe| {
13945 let cmp = probe
13946 .end
13947 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13948 if cmp.is_gt() {
13949 Ordering::Greater
13950 } else {
13951 Ordering::Less
13952 }
13953 }) {
13954 Ok(i) | Err(i) => i,
13955 };
13956 for range in &ranges[start_ix..] {
13957 if range
13958 .start
13959 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13960 .is_ge()
13961 {
13962 break;
13963 }
13964
13965 let start = range.start.to_display_point(display_snapshot);
13966 let end = range.end.to_display_point(display_snapshot);
13967 results.push((start..end, color))
13968 }
13969 }
13970 results
13971 }
13972
13973 /// Get the text ranges corresponding to the redaction query
13974 pub fn redacted_ranges(
13975 &self,
13976 search_range: Range<Anchor>,
13977 display_snapshot: &DisplaySnapshot,
13978 cx: &App,
13979 ) -> Vec<Range<DisplayPoint>> {
13980 display_snapshot
13981 .buffer_snapshot
13982 .redacted_ranges(search_range, |file| {
13983 if let Some(file) = file {
13984 file.is_private()
13985 && EditorSettings::get(
13986 Some(SettingsLocation {
13987 worktree_id: file.worktree_id(cx),
13988 path: file.path().as_ref(),
13989 }),
13990 cx,
13991 )
13992 .redact_private_values
13993 } else {
13994 false
13995 }
13996 })
13997 .map(|range| {
13998 range.start.to_display_point(display_snapshot)
13999 ..range.end.to_display_point(display_snapshot)
14000 })
14001 .collect()
14002 }
14003
14004 pub fn highlight_text<T: 'static>(
14005 &mut self,
14006 ranges: Vec<Range<Anchor>>,
14007 style: HighlightStyle,
14008 cx: &mut Context<Self>,
14009 ) {
14010 self.display_map.update(cx, |map, _| {
14011 map.highlight_text(TypeId::of::<T>(), ranges, style)
14012 });
14013 cx.notify();
14014 }
14015
14016 pub(crate) fn highlight_inlays<T: 'static>(
14017 &mut self,
14018 highlights: Vec<InlayHighlight>,
14019 style: HighlightStyle,
14020 cx: &mut Context<Self>,
14021 ) {
14022 self.display_map.update(cx, |map, _| {
14023 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14024 });
14025 cx.notify();
14026 }
14027
14028 pub fn text_highlights<'a, T: 'static>(
14029 &'a self,
14030 cx: &'a App,
14031 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14032 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14033 }
14034
14035 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14036 let cleared = self
14037 .display_map
14038 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14039 if cleared {
14040 cx.notify();
14041 }
14042 }
14043
14044 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14045 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14046 && self.focus_handle.is_focused(window)
14047 }
14048
14049 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14050 self.show_cursor_when_unfocused = is_enabled;
14051 cx.notify();
14052 }
14053
14054 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14055 cx.notify();
14056 }
14057
14058 fn on_buffer_event(
14059 &mut self,
14060 multibuffer: &Entity<MultiBuffer>,
14061 event: &multi_buffer::Event,
14062 window: &mut Window,
14063 cx: &mut Context<Self>,
14064 ) {
14065 match event {
14066 multi_buffer::Event::Edited {
14067 singleton_buffer_edited,
14068 edited_buffer: buffer_edited,
14069 } => {
14070 self.scrollbar_marker_state.dirty = true;
14071 self.active_indent_guides_state.dirty = true;
14072 self.refresh_active_diagnostics(cx);
14073 self.refresh_code_actions(window, cx);
14074 if self.has_active_inline_completion() {
14075 self.update_visible_inline_completion(window, cx);
14076 }
14077 if let Some(buffer) = buffer_edited {
14078 let buffer_id = buffer.read(cx).remote_id();
14079 if !self.registered_buffers.contains_key(&buffer_id) {
14080 if let Some(project) = self.project.as_ref() {
14081 project.update(cx, |project, cx| {
14082 self.registered_buffers.insert(
14083 buffer_id,
14084 project.register_buffer_with_language_servers(&buffer, cx),
14085 );
14086 })
14087 }
14088 }
14089 }
14090 cx.emit(EditorEvent::BufferEdited);
14091 cx.emit(SearchEvent::MatchesInvalidated);
14092 if *singleton_buffer_edited {
14093 if let Some(project) = &self.project {
14094 #[allow(clippy::mutable_key_type)]
14095 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14096 multibuffer
14097 .all_buffers()
14098 .into_iter()
14099 .filter_map(|buffer| {
14100 buffer.update(cx, |buffer, cx| {
14101 let language = buffer.language()?;
14102 let should_discard = project.update(cx, |project, cx| {
14103 project.is_local()
14104 && !project.has_language_servers_for(buffer, cx)
14105 });
14106 should_discard.not().then_some(language.clone())
14107 })
14108 })
14109 .collect::<HashSet<_>>()
14110 });
14111 if !languages_affected.is_empty() {
14112 self.refresh_inlay_hints(
14113 InlayHintRefreshReason::BufferEdited(languages_affected),
14114 cx,
14115 );
14116 }
14117 }
14118 }
14119
14120 let Some(project) = &self.project else { return };
14121 let (telemetry, is_via_ssh) = {
14122 let project = project.read(cx);
14123 let telemetry = project.client().telemetry().clone();
14124 let is_via_ssh = project.is_via_ssh();
14125 (telemetry, is_via_ssh)
14126 };
14127 refresh_linked_ranges(self, window, cx);
14128 telemetry.log_edit_event("editor", is_via_ssh);
14129 }
14130 multi_buffer::Event::ExcerptsAdded {
14131 buffer,
14132 predecessor,
14133 excerpts,
14134 } => {
14135 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14136 let buffer_id = buffer.read(cx).remote_id();
14137 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14138 if let Some(project) = &self.project {
14139 get_uncommitted_diff_for_buffer(
14140 project,
14141 [buffer.clone()],
14142 self.buffer.clone(),
14143 cx,
14144 )
14145 .detach();
14146 }
14147 }
14148 cx.emit(EditorEvent::ExcerptsAdded {
14149 buffer: buffer.clone(),
14150 predecessor: *predecessor,
14151 excerpts: excerpts.clone(),
14152 });
14153 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14154 }
14155 multi_buffer::Event::ExcerptsRemoved { ids } => {
14156 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14157 let buffer = self.buffer.read(cx);
14158 self.registered_buffers
14159 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14160 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14161 }
14162 multi_buffer::Event::ExcerptsEdited { ids } => {
14163 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14164 }
14165 multi_buffer::Event::ExcerptsExpanded { ids } => {
14166 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14167 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14168 }
14169 multi_buffer::Event::Reparsed(buffer_id) => {
14170 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14171
14172 cx.emit(EditorEvent::Reparsed(*buffer_id));
14173 }
14174 multi_buffer::Event::DiffHunksToggled => {
14175 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14176 }
14177 multi_buffer::Event::LanguageChanged(buffer_id) => {
14178 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14179 cx.emit(EditorEvent::Reparsed(*buffer_id));
14180 cx.notify();
14181 }
14182 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14183 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14184 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14185 cx.emit(EditorEvent::TitleChanged)
14186 }
14187 // multi_buffer::Event::DiffBaseChanged => {
14188 // self.scrollbar_marker_state.dirty = true;
14189 // cx.emit(EditorEvent::DiffBaseChanged);
14190 // cx.notify();
14191 // }
14192 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14193 multi_buffer::Event::DiagnosticsUpdated => {
14194 self.refresh_active_diagnostics(cx);
14195 self.scrollbar_marker_state.dirty = true;
14196 cx.notify();
14197 }
14198 _ => {}
14199 };
14200 }
14201
14202 fn on_display_map_changed(
14203 &mut self,
14204 _: Entity<DisplayMap>,
14205 _: &mut Window,
14206 cx: &mut Context<Self>,
14207 ) {
14208 cx.notify();
14209 }
14210
14211 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14212 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14213 self.refresh_inline_completion(true, false, window, cx);
14214 self.refresh_inlay_hints(
14215 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14216 self.selections.newest_anchor().head(),
14217 &self.buffer.read(cx).snapshot(cx),
14218 cx,
14219 )),
14220 cx,
14221 );
14222
14223 let old_cursor_shape = self.cursor_shape;
14224
14225 {
14226 let editor_settings = EditorSettings::get_global(cx);
14227 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14228 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14229 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14230 }
14231
14232 if old_cursor_shape != self.cursor_shape {
14233 cx.emit(EditorEvent::CursorShapeChanged);
14234 }
14235
14236 let project_settings = ProjectSettings::get_global(cx);
14237 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14238
14239 if self.mode == EditorMode::Full {
14240 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14241 if self.git_blame_inline_enabled != inline_blame_enabled {
14242 self.toggle_git_blame_inline_internal(false, window, cx);
14243 }
14244 }
14245
14246 cx.notify();
14247 }
14248
14249 pub fn set_searchable(&mut self, searchable: bool) {
14250 self.searchable = searchable;
14251 }
14252
14253 pub fn searchable(&self) -> bool {
14254 self.searchable
14255 }
14256
14257 fn open_proposed_changes_editor(
14258 &mut self,
14259 _: &OpenProposedChangesEditor,
14260 window: &mut Window,
14261 cx: &mut Context<Self>,
14262 ) {
14263 let Some(workspace) = self.workspace() else {
14264 cx.propagate();
14265 return;
14266 };
14267
14268 let selections = self.selections.all::<usize>(cx);
14269 let multi_buffer = self.buffer.read(cx);
14270 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14271 let mut new_selections_by_buffer = HashMap::default();
14272 for selection in selections {
14273 for (buffer, range, _) in
14274 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14275 {
14276 let mut range = range.to_point(buffer);
14277 range.start.column = 0;
14278 range.end.column = buffer.line_len(range.end.row);
14279 new_selections_by_buffer
14280 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14281 .or_insert(Vec::new())
14282 .push(range)
14283 }
14284 }
14285
14286 let proposed_changes_buffers = new_selections_by_buffer
14287 .into_iter()
14288 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14289 .collect::<Vec<_>>();
14290 let proposed_changes_editor = cx.new(|cx| {
14291 ProposedChangesEditor::new(
14292 "Proposed changes",
14293 proposed_changes_buffers,
14294 self.project.clone(),
14295 window,
14296 cx,
14297 )
14298 });
14299
14300 window.defer(cx, move |window, cx| {
14301 workspace.update(cx, |workspace, cx| {
14302 workspace.active_pane().update(cx, |pane, cx| {
14303 pane.add_item(
14304 Box::new(proposed_changes_editor),
14305 true,
14306 true,
14307 None,
14308 window,
14309 cx,
14310 );
14311 });
14312 });
14313 });
14314 }
14315
14316 pub fn open_excerpts_in_split(
14317 &mut self,
14318 _: &OpenExcerptsSplit,
14319 window: &mut Window,
14320 cx: &mut Context<Self>,
14321 ) {
14322 self.open_excerpts_common(None, true, window, cx)
14323 }
14324
14325 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14326 self.open_excerpts_common(None, false, window, cx)
14327 }
14328
14329 fn open_excerpts_common(
14330 &mut self,
14331 jump_data: Option<JumpData>,
14332 split: bool,
14333 window: &mut Window,
14334 cx: &mut Context<Self>,
14335 ) {
14336 let Some(workspace) = self.workspace() else {
14337 cx.propagate();
14338 return;
14339 };
14340
14341 if self.buffer.read(cx).is_singleton() {
14342 cx.propagate();
14343 return;
14344 }
14345
14346 let mut new_selections_by_buffer = HashMap::default();
14347 match &jump_data {
14348 Some(JumpData::MultiBufferPoint {
14349 excerpt_id,
14350 position,
14351 anchor,
14352 line_offset_from_top,
14353 }) => {
14354 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14355 if let Some(buffer) = multi_buffer_snapshot
14356 .buffer_id_for_excerpt(*excerpt_id)
14357 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14358 {
14359 let buffer_snapshot = buffer.read(cx).snapshot();
14360 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14361 language::ToPoint::to_point(anchor, &buffer_snapshot)
14362 } else {
14363 buffer_snapshot.clip_point(*position, Bias::Left)
14364 };
14365 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14366 new_selections_by_buffer.insert(
14367 buffer,
14368 (
14369 vec![jump_to_offset..jump_to_offset],
14370 Some(*line_offset_from_top),
14371 ),
14372 );
14373 }
14374 }
14375 Some(JumpData::MultiBufferRow {
14376 row,
14377 line_offset_from_top,
14378 }) => {
14379 let point = MultiBufferPoint::new(row.0, 0);
14380 if let Some((buffer, buffer_point, _)) =
14381 self.buffer.read(cx).point_to_buffer_point(point, cx)
14382 {
14383 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14384 new_selections_by_buffer
14385 .entry(buffer)
14386 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14387 .0
14388 .push(buffer_offset..buffer_offset)
14389 }
14390 }
14391 None => {
14392 let selections = self.selections.all::<usize>(cx);
14393 let multi_buffer = self.buffer.read(cx);
14394 for selection in selections {
14395 for (buffer, mut range, _) in multi_buffer
14396 .snapshot(cx)
14397 .range_to_buffer_ranges(selection.range())
14398 {
14399 // When editing branch buffers, jump to the corresponding location
14400 // in their base buffer.
14401 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14402 let buffer = buffer_handle.read(cx);
14403 if let Some(base_buffer) = buffer.base_buffer() {
14404 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14405 buffer_handle = base_buffer;
14406 }
14407
14408 if selection.reversed {
14409 mem::swap(&mut range.start, &mut range.end);
14410 }
14411 new_selections_by_buffer
14412 .entry(buffer_handle)
14413 .or_insert((Vec::new(), None))
14414 .0
14415 .push(range)
14416 }
14417 }
14418 }
14419 }
14420
14421 if new_selections_by_buffer.is_empty() {
14422 return;
14423 }
14424
14425 // We defer the pane interaction because we ourselves are a workspace item
14426 // and activating a new item causes the pane to call a method on us reentrantly,
14427 // which panics if we're on the stack.
14428 window.defer(cx, move |window, cx| {
14429 workspace.update(cx, |workspace, cx| {
14430 let pane = if split {
14431 workspace.adjacent_pane(window, cx)
14432 } else {
14433 workspace.active_pane().clone()
14434 };
14435
14436 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14437 let editor = buffer
14438 .read(cx)
14439 .file()
14440 .is_none()
14441 .then(|| {
14442 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14443 // so `workspace.open_project_item` will never find them, always opening a new editor.
14444 // Instead, we try to activate the existing editor in the pane first.
14445 let (editor, pane_item_index) =
14446 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14447 let editor = item.downcast::<Editor>()?;
14448 let singleton_buffer =
14449 editor.read(cx).buffer().read(cx).as_singleton()?;
14450 if singleton_buffer == buffer {
14451 Some((editor, i))
14452 } else {
14453 None
14454 }
14455 })?;
14456 pane.update(cx, |pane, cx| {
14457 pane.activate_item(pane_item_index, true, true, window, cx)
14458 });
14459 Some(editor)
14460 })
14461 .flatten()
14462 .unwrap_or_else(|| {
14463 workspace.open_project_item::<Self>(
14464 pane.clone(),
14465 buffer,
14466 true,
14467 true,
14468 window,
14469 cx,
14470 )
14471 });
14472
14473 editor.update(cx, |editor, cx| {
14474 let autoscroll = match scroll_offset {
14475 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14476 None => Autoscroll::newest(),
14477 };
14478 let nav_history = editor.nav_history.take();
14479 editor.change_selections(Some(autoscroll), window, cx, |s| {
14480 s.select_ranges(ranges);
14481 });
14482 editor.nav_history = nav_history;
14483 });
14484 }
14485 })
14486 });
14487 }
14488
14489 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14490 let snapshot = self.buffer.read(cx).read(cx);
14491 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14492 Some(
14493 ranges
14494 .iter()
14495 .map(move |range| {
14496 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14497 })
14498 .collect(),
14499 )
14500 }
14501
14502 fn selection_replacement_ranges(
14503 &self,
14504 range: Range<OffsetUtf16>,
14505 cx: &mut App,
14506 ) -> Vec<Range<OffsetUtf16>> {
14507 let selections = self.selections.all::<OffsetUtf16>(cx);
14508 let newest_selection = selections
14509 .iter()
14510 .max_by_key(|selection| selection.id)
14511 .unwrap();
14512 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14513 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14514 let snapshot = self.buffer.read(cx).read(cx);
14515 selections
14516 .into_iter()
14517 .map(|mut selection| {
14518 selection.start.0 =
14519 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14520 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14521 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14522 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14523 })
14524 .collect()
14525 }
14526
14527 fn report_editor_event(
14528 &self,
14529 event_type: &'static str,
14530 file_extension: Option<String>,
14531 cx: &App,
14532 ) {
14533 if cfg!(any(test, feature = "test-support")) {
14534 return;
14535 }
14536
14537 let Some(project) = &self.project else { return };
14538
14539 // If None, we are in a file without an extension
14540 let file = self
14541 .buffer
14542 .read(cx)
14543 .as_singleton()
14544 .and_then(|b| b.read(cx).file());
14545 let file_extension = file_extension.or(file
14546 .as_ref()
14547 .and_then(|file| Path::new(file.file_name(cx)).extension())
14548 .and_then(|e| e.to_str())
14549 .map(|a| a.to_string()));
14550
14551 let vim_mode = cx
14552 .global::<SettingsStore>()
14553 .raw_user_settings()
14554 .get("vim_mode")
14555 == Some(&serde_json::Value::Bool(true));
14556
14557 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14558 let copilot_enabled = edit_predictions_provider
14559 == language::language_settings::EditPredictionProvider::Copilot;
14560 let copilot_enabled_for_language = self
14561 .buffer
14562 .read(cx)
14563 .settings_at(0, cx)
14564 .show_edit_predictions;
14565
14566 let project = project.read(cx);
14567 telemetry::event!(
14568 event_type,
14569 file_extension,
14570 vim_mode,
14571 copilot_enabled,
14572 copilot_enabled_for_language,
14573 edit_predictions_provider,
14574 is_via_ssh = project.is_via_ssh(),
14575 );
14576 }
14577
14578 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14579 /// with each line being an array of {text, highlight} objects.
14580 fn copy_highlight_json(
14581 &mut self,
14582 _: &CopyHighlightJson,
14583 window: &mut Window,
14584 cx: &mut Context<Self>,
14585 ) {
14586 #[derive(Serialize)]
14587 struct Chunk<'a> {
14588 text: String,
14589 highlight: Option<&'a str>,
14590 }
14591
14592 let snapshot = self.buffer.read(cx).snapshot(cx);
14593 let range = self
14594 .selected_text_range(false, window, cx)
14595 .and_then(|selection| {
14596 if selection.range.is_empty() {
14597 None
14598 } else {
14599 Some(selection.range)
14600 }
14601 })
14602 .unwrap_or_else(|| 0..snapshot.len());
14603
14604 let chunks = snapshot.chunks(range, true);
14605 let mut lines = Vec::new();
14606 let mut line: VecDeque<Chunk> = VecDeque::new();
14607
14608 let Some(style) = self.style.as_ref() else {
14609 return;
14610 };
14611
14612 for chunk in chunks {
14613 let highlight = chunk
14614 .syntax_highlight_id
14615 .and_then(|id| id.name(&style.syntax));
14616 let mut chunk_lines = chunk.text.split('\n').peekable();
14617 while let Some(text) = chunk_lines.next() {
14618 let mut merged_with_last_token = false;
14619 if let Some(last_token) = line.back_mut() {
14620 if last_token.highlight == highlight {
14621 last_token.text.push_str(text);
14622 merged_with_last_token = true;
14623 }
14624 }
14625
14626 if !merged_with_last_token {
14627 line.push_back(Chunk {
14628 text: text.into(),
14629 highlight,
14630 });
14631 }
14632
14633 if chunk_lines.peek().is_some() {
14634 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14635 line.pop_front();
14636 }
14637 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14638 line.pop_back();
14639 }
14640
14641 lines.push(mem::take(&mut line));
14642 }
14643 }
14644 }
14645
14646 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14647 return;
14648 };
14649 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14650 }
14651
14652 pub fn open_context_menu(
14653 &mut self,
14654 _: &OpenContextMenu,
14655 window: &mut Window,
14656 cx: &mut Context<Self>,
14657 ) {
14658 self.request_autoscroll(Autoscroll::newest(), cx);
14659 let position = self.selections.newest_display(cx).start;
14660 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14661 }
14662
14663 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14664 &self.inlay_hint_cache
14665 }
14666
14667 pub fn replay_insert_event(
14668 &mut self,
14669 text: &str,
14670 relative_utf16_range: Option<Range<isize>>,
14671 window: &mut Window,
14672 cx: &mut Context<Self>,
14673 ) {
14674 if !self.input_enabled {
14675 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14676 return;
14677 }
14678 if let Some(relative_utf16_range) = relative_utf16_range {
14679 let selections = self.selections.all::<OffsetUtf16>(cx);
14680 self.change_selections(None, window, cx, |s| {
14681 let new_ranges = selections.into_iter().map(|range| {
14682 let start = OffsetUtf16(
14683 range
14684 .head()
14685 .0
14686 .saturating_add_signed(relative_utf16_range.start),
14687 );
14688 let end = OffsetUtf16(
14689 range
14690 .head()
14691 .0
14692 .saturating_add_signed(relative_utf16_range.end),
14693 );
14694 start..end
14695 });
14696 s.select_ranges(new_ranges);
14697 });
14698 }
14699
14700 self.handle_input(text, window, cx);
14701 }
14702
14703 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14704 let Some(provider) = self.semantics_provider.as_ref() else {
14705 return false;
14706 };
14707
14708 let mut supports = false;
14709 self.buffer().update(cx, |this, cx| {
14710 this.for_each_buffer(|buffer| {
14711 supports |= provider.supports_inlay_hints(buffer, cx);
14712 });
14713 });
14714
14715 supports
14716 }
14717
14718 pub fn is_focused(&self, window: &Window) -> bool {
14719 self.focus_handle.is_focused(window)
14720 }
14721
14722 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14723 cx.emit(EditorEvent::Focused);
14724
14725 if let Some(descendant) = self
14726 .last_focused_descendant
14727 .take()
14728 .and_then(|descendant| descendant.upgrade())
14729 {
14730 window.focus(&descendant);
14731 } else {
14732 if let Some(blame) = self.blame.as_ref() {
14733 blame.update(cx, GitBlame::focus)
14734 }
14735
14736 self.blink_manager.update(cx, BlinkManager::enable);
14737 self.show_cursor_names(window, cx);
14738 self.buffer.update(cx, |buffer, cx| {
14739 buffer.finalize_last_transaction(cx);
14740 if self.leader_peer_id.is_none() {
14741 buffer.set_active_selections(
14742 &self.selections.disjoint_anchors(),
14743 self.selections.line_mode,
14744 self.cursor_shape,
14745 cx,
14746 );
14747 }
14748 });
14749 }
14750 }
14751
14752 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14753 cx.emit(EditorEvent::FocusedIn)
14754 }
14755
14756 fn handle_focus_out(
14757 &mut self,
14758 event: FocusOutEvent,
14759 _window: &mut Window,
14760 _cx: &mut Context<Self>,
14761 ) {
14762 if event.blurred != self.focus_handle {
14763 self.last_focused_descendant = Some(event.blurred);
14764 }
14765 }
14766
14767 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14768 self.blink_manager.update(cx, BlinkManager::disable);
14769 self.buffer
14770 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14771
14772 if let Some(blame) = self.blame.as_ref() {
14773 blame.update(cx, GitBlame::blur)
14774 }
14775 if !self.hover_state.focused(window, cx) {
14776 hide_hover(self, cx);
14777 }
14778
14779 self.hide_context_menu(window, cx);
14780 self.discard_inline_completion(false, cx);
14781 cx.emit(EditorEvent::Blurred);
14782 cx.notify();
14783 }
14784
14785 pub fn register_action<A: Action>(
14786 &mut self,
14787 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14788 ) -> Subscription {
14789 let id = self.next_editor_action_id.post_inc();
14790 let listener = Arc::new(listener);
14791 self.editor_actions.borrow_mut().insert(
14792 id,
14793 Box::new(move |window, _| {
14794 let listener = listener.clone();
14795 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14796 let action = action.downcast_ref().unwrap();
14797 if phase == DispatchPhase::Bubble {
14798 listener(action, window, cx)
14799 }
14800 })
14801 }),
14802 );
14803
14804 let editor_actions = self.editor_actions.clone();
14805 Subscription::new(move || {
14806 editor_actions.borrow_mut().remove(&id);
14807 })
14808 }
14809
14810 pub fn file_header_size(&self) -> u32 {
14811 FILE_HEADER_HEIGHT
14812 }
14813
14814 pub fn revert(
14815 &mut self,
14816 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14817 window: &mut Window,
14818 cx: &mut Context<Self>,
14819 ) {
14820 self.buffer().update(cx, |multi_buffer, cx| {
14821 for (buffer_id, changes) in revert_changes {
14822 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14823 buffer.update(cx, |buffer, cx| {
14824 buffer.edit(
14825 changes.into_iter().map(|(range, text)| {
14826 (range, text.to_string().map(Arc::<str>::from))
14827 }),
14828 None,
14829 cx,
14830 );
14831 });
14832 }
14833 }
14834 });
14835 self.change_selections(None, window, cx, |selections| selections.refresh());
14836 }
14837
14838 pub fn to_pixel_point(
14839 &self,
14840 source: multi_buffer::Anchor,
14841 editor_snapshot: &EditorSnapshot,
14842 window: &mut Window,
14843 ) -> Option<gpui::Point<Pixels>> {
14844 let source_point = source.to_display_point(editor_snapshot);
14845 self.display_to_pixel_point(source_point, editor_snapshot, window)
14846 }
14847
14848 pub fn display_to_pixel_point(
14849 &self,
14850 source: DisplayPoint,
14851 editor_snapshot: &EditorSnapshot,
14852 window: &mut Window,
14853 ) -> Option<gpui::Point<Pixels>> {
14854 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14855 let text_layout_details = self.text_layout_details(window);
14856 let scroll_top = text_layout_details
14857 .scroll_anchor
14858 .scroll_position(editor_snapshot)
14859 .y;
14860
14861 if source.row().as_f32() < scroll_top.floor() {
14862 return None;
14863 }
14864 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14865 let source_y = line_height * (source.row().as_f32() - scroll_top);
14866 Some(gpui::Point::new(source_x, source_y))
14867 }
14868
14869 pub fn has_visible_completions_menu(&self) -> bool {
14870 !self.edit_prediction_preview_is_active()
14871 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14872 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14873 })
14874 }
14875
14876 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14877 self.addons
14878 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14879 }
14880
14881 pub fn unregister_addon<T: Addon>(&mut self) {
14882 self.addons.remove(&std::any::TypeId::of::<T>());
14883 }
14884
14885 pub fn addon<T: Addon>(&self) -> Option<&T> {
14886 let type_id = std::any::TypeId::of::<T>();
14887 self.addons
14888 .get(&type_id)
14889 .and_then(|item| item.to_any().downcast_ref::<T>())
14890 }
14891
14892 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14893 let text_layout_details = self.text_layout_details(window);
14894 let style = &text_layout_details.editor_style;
14895 let font_id = window.text_system().resolve_font(&style.text.font());
14896 let font_size = style.text.font_size.to_pixels(window.rem_size());
14897 let line_height = style.text.line_height_in_pixels(window.rem_size());
14898 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14899
14900 gpui::Size::new(em_width, line_height)
14901 }
14902
14903 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14904 self.load_diff_task.clone()
14905 }
14906}
14907
14908fn get_uncommitted_diff_for_buffer(
14909 project: &Entity<Project>,
14910 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14911 buffer: Entity<MultiBuffer>,
14912 cx: &mut App,
14913) -> Task<()> {
14914 let mut tasks = Vec::new();
14915 project.update(cx, |project, cx| {
14916 for buffer in buffers {
14917 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14918 }
14919 });
14920 cx.spawn(|mut cx| async move {
14921 let diffs = futures::future::join_all(tasks).await;
14922 buffer
14923 .update(&mut cx, |buffer, cx| {
14924 for diff in diffs.into_iter().flatten() {
14925 buffer.add_diff(diff, cx);
14926 }
14927 })
14928 .ok();
14929 })
14930}
14931
14932fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14933 let tab_size = tab_size.get() as usize;
14934 let mut width = offset;
14935
14936 for ch in text.chars() {
14937 width += if ch == '\t' {
14938 tab_size - (width % tab_size)
14939 } else {
14940 1
14941 };
14942 }
14943
14944 width - offset
14945}
14946
14947#[cfg(test)]
14948mod tests {
14949 use super::*;
14950
14951 #[test]
14952 fn test_string_size_with_expanded_tabs() {
14953 let nz = |val| NonZeroU32::new(val).unwrap();
14954 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14955 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14956 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14957 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14958 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14959 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14960 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14961 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14962 }
14963}
14964
14965/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14966struct WordBreakingTokenizer<'a> {
14967 input: &'a str,
14968}
14969
14970impl<'a> WordBreakingTokenizer<'a> {
14971 fn new(input: &'a str) -> Self {
14972 Self { input }
14973 }
14974}
14975
14976fn is_char_ideographic(ch: char) -> bool {
14977 use unicode_script::Script::*;
14978 use unicode_script::UnicodeScript;
14979 matches!(ch.script(), Han | Tangut | Yi)
14980}
14981
14982fn is_grapheme_ideographic(text: &str) -> bool {
14983 text.chars().any(is_char_ideographic)
14984}
14985
14986fn is_grapheme_whitespace(text: &str) -> bool {
14987 text.chars().any(|x| x.is_whitespace())
14988}
14989
14990fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14991 text.chars().next().map_or(false, |ch| {
14992 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14993 })
14994}
14995
14996#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14997struct WordBreakToken<'a> {
14998 token: &'a str,
14999 grapheme_len: usize,
15000 is_whitespace: bool,
15001}
15002
15003impl<'a> Iterator for WordBreakingTokenizer<'a> {
15004 /// Yields a span, the count of graphemes in the token, and whether it was
15005 /// whitespace. Note that it also breaks at word boundaries.
15006 type Item = WordBreakToken<'a>;
15007
15008 fn next(&mut self) -> Option<Self::Item> {
15009 use unicode_segmentation::UnicodeSegmentation;
15010 if self.input.is_empty() {
15011 return None;
15012 }
15013
15014 let mut iter = self.input.graphemes(true).peekable();
15015 let mut offset = 0;
15016 let mut graphemes = 0;
15017 if let Some(first_grapheme) = iter.next() {
15018 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15019 offset += first_grapheme.len();
15020 graphemes += 1;
15021 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15022 if let Some(grapheme) = iter.peek().copied() {
15023 if should_stay_with_preceding_ideograph(grapheme) {
15024 offset += grapheme.len();
15025 graphemes += 1;
15026 }
15027 }
15028 } else {
15029 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15030 let mut next_word_bound = words.peek().copied();
15031 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15032 next_word_bound = words.next();
15033 }
15034 while let Some(grapheme) = iter.peek().copied() {
15035 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15036 break;
15037 };
15038 if is_grapheme_whitespace(grapheme) != is_whitespace {
15039 break;
15040 };
15041 offset += grapheme.len();
15042 graphemes += 1;
15043 iter.next();
15044 }
15045 }
15046 let token = &self.input[..offset];
15047 self.input = &self.input[offset..];
15048 if is_whitespace {
15049 Some(WordBreakToken {
15050 token: " ",
15051 grapheme_len: 1,
15052 is_whitespace: true,
15053 })
15054 } else {
15055 Some(WordBreakToken {
15056 token,
15057 grapheme_len: graphemes,
15058 is_whitespace: false,
15059 })
15060 }
15061 } else {
15062 None
15063 }
15064 }
15065}
15066
15067#[test]
15068fn test_word_breaking_tokenizer() {
15069 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15070 ("", &[]),
15071 (" ", &[(" ", 1, true)]),
15072 ("Ʒ", &[("Ʒ", 1, false)]),
15073 ("Ǽ", &[("Ǽ", 1, false)]),
15074 ("⋑", &[("⋑", 1, false)]),
15075 ("⋑⋑", &[("⋑⋑", 2, false)]),
15076 (
15077 "原理,进而",
15078 &[
15079 ("原", 1, false),
15080 ("理,", 2, false),
15081 ("进", 1, false),
15082 ("而", 1, false),
15083 ],
15084 ),
15085 (
15086 "hello world",
15087 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15088 ),
15089 (
15090 "hello, world",
15091 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15092 ),
15093 (
15094 " hello world",
15095 &[
15096 (" ", 1, true),
15097 ("hello", 5, false),
15098 (" ", 1, true),
15099 ("world", 5, false),
15100 ],
15101 ),
15102 (
15103 "这是什么 \n 钢笔",
15104 &[
15105 ("这", 1, false),
15106 ("是", 1, false),
15107 ("什", 1, false),
15108 ("么", 1, false),
15109 (" ", 1, true),
15110 ("钢", 1, false),
15111 ("笔", 1, false),
15112 ],
15113 ),
15114 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15115 ];
15116
15117 for (input, result) in tests {
15118 assert_eq!(
15119 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15120 result
15121 .iter()
15122 .copied()
15123 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15124 token,
15125 grapheme_len,
15126 is_whitespace,
15127 })
15128 .collect::<Vec<_>>()
15129 );
15130 }
15131}
15132
15133fn wrap_with_prefix(
15134 line_prefix: String,
15135 unwrapped_text: String,
15136 wrap_column: usize,
15137 tab_size: NonZeroU32,
15138) -> String {
15139 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15140 let mut wrapped_text = String::new();
15141 let mut current_line = line_prefix.clone();
15142
15143 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15144 let mut current_line_len = line_prefix_len;
15145 for WordBreakToken {
15146 token,
15147 grapheme_len,
15148 is_whitespace,
15149 } in tokenizer
15150 {
15151 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15152 wrapped_text.push_str(current_line.trim_end());
15153 wrapped_text.push('\n');
15154 current_line.truncate(line_prefix.len());
15155 current_line_len = line_prefix_len;
15156 if !is_whitespace {
15157 current_line.push_str(token);
15158 current_line_len += grapheme_len;
15159 }
15160 } else if !is_whitespace {
15161 current_line.push_str(token);
15162 current_line_len += grapheme_len;
15163 } else if current_line_len != line_prefix_len {
15164 current_line.push(' ');
15165 current_line_len += 1;
15166 }
15167 }
15168
15169 if !current_line.is_empty() {
15170 wrapped_text.push_str(¤t_line);
15171 }
15172 wrapped_text
15173}
15174
15175#[test]
15176fn test_wrap_with_prefix() {
15177 assert_eq!(
15178 wrap_with_prefix(
15179 "# ".to_string(),
15180 "abcdefg".to_string(),
15181 4,
15182 NonZeroU32::new(4).unwrap()
15183 ),
15184 "# abcdefg"
15185 );
15186 assert_eq!(
15187 wrap_with_prefix(
15188 "".to_string(),
15189 "\thello world".to_string(),
15190 8,
15191 NonZeroU32::new(4).unwrap()
15192 ),
15193 "hello\nworld"
15194 );
15195 assert_eq!(
15196 wrap_with_prefix(
15197 "// ".to_string(),
15198 "xx \nyy zz aa bb cc".to_string(),
15199 12,
15200 NonZeroU32::new(4).unwrap()
15201 ),
15202 "// xx yy zz\n// aa bb cc"
15203 );
15204 assert_eq!(
15205 wrap_with_prefix(
15206 String::new(),
15207 "这是什么 \n 钢笔".to_string(),
15208 3,
15209 NonZeroU32::new(4).unwrap()
15210 ),
15211 "这是什\n么 钢\n笔"
15212 );
15213}
15214
15215pub trait CollaborationHub {
15216 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15217 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15218 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15219}
15220
15221impl CollaborationHub for Entity<Project> {
15222 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15223 self.read(cx).collaborators()
15224 }
15225
15226 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15227 self.read(cx).user_store().read(cx).participant_indices()
15228 }
15229
15230 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15231 let this = self.read(cx);
15232 let user_ids = this.collaborators().values().map(|c| c.user_id);
15233 this.user_store().read_with(cx, |user_store, cx| {
15234 user_store.participant_names(user_ids, cx)
15235 })
15236 }
15237}
15238
15239pub trait SemanticsProvider {
15240 fn hover(
15241 &self,
15242 buffer: &Entity<Buffer>,
15243 position: text::Anchor,
15244 cx: &mut App,
15245 ) -> Option<Task<Vec<project::Hover>>>;
15246
15247 fn inlay_hints(
15248 &self,
15249 buffer_handle: Entity<Buffer>,
15250 range: Range<text::Anchor>,
15251 cx: &mut App,
15252 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15253
15254 fn resolve_inlay_hint(
15255 &self,
15256 hint: InlayHint,
15257 buffer_handle: Entity<Buffer>,
15258 server_id: LanguageServerId,
15259 cx: &mut App,
15260 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15261
15262 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15263
15264 fn document_highlights(
15265 &self,
15266 buffer: &Entity<Buffer>,
15267 position: text::Anchor,
15268 cx: &mut App,
15269 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15270
15271 fn definitions(
15272 &self,
15273 buffer: &Entity<Buffer>,
15274 position: text::Anchor,
15275 kind: GotoDefinitionKind,
15276 cx: &mut App,
15277 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15278
15279 fn range_for_rename(
15280 &self,
15281 buffer: &Entity<Buffer>,
15282 position: text::Anchor,
15283 cx: &mut App,
15284 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15285
15286 fn perform_rename(
15287 &self,
15288 buffer: &Entity<Buffer>,
15289 position: text::Anchor,
15290 new_name: String,
15291 cx: &mut App,
15292 ) -> Option<Task<Result<ProjectTransaction>>>;
15293}
15294
15295pub trait CompletionProvider {
15296 fn completions(
15297 &self,
15298 buffer: &Entity<Buffer>,
15299 buffer_position: text::Anchor,
15300 trigger: CompletionContext,
15301 window: &mut Window,
15302 cx: &mut Context<Editor>,
15303 ) -> Task<Result<Vec<Completion>>>;
15304
15305 fn resolve_completions(
15306 &self,
15307 buffer: Entity<Buffer>,
15308 completion_indices: Vec<usize>,
15309 completions: Rc<RefCell<Box<[Completion]>>>,
15310 cx: &mut Context<Editor>,
15311 ) -> Task<Result<bool>>;
15312
15313 fn apply_additional_edits_for_completion(
15314 &self,
15315 _buffer: Entity<Buffer>,
15316 _completions: Rc<RefCell<Box<[Completion]>>>,
15317 _completion_index: usize,
15318 _push_to_history: bool,
15319 _cx: &mut Context<Editor>,
15320 ) -> Task<Result<Option<language::Transaction>>> {
15321 Task::ready(Ok(None))
15322 }
15323
15324 fn is_completion_trigger(
15325 &self,
15326 buffer: &Entity<Buffer>,
15327 position: language::Anchor,
15328 text: &str,
15329 trigger_in_words: bool,
15330 cx: &mut Context<Editor>,
15331 ) -> bool;
15332
15333 fn sort_completions(&self) -> bool {
15334 true
15335 }
15336}
15337
15338pub trait CodeActionProvider {
15339 fn id(&self) -> Arc<str>;
15340
15341 fn code_actions(
15342 &self,
15343 buffer: &Entity<Buffer>,
15344 range: Range<text::Anchor>,
15345 window: &mut Window,
15346 cx: &mut App,
15347 ) -> Task<Result<Vec<CodeAction>>>;
15348
15349 fn apply_code_action(
15350 &self,
15351 buffer_handle: Entity<Buffer>,
15352 action: CodeAction,
15353 excerpt_id: ExcerptId,
15354 push_to_history: bool,
15355 window: &mut Window,
15356 cx: &mut App,
15357 ) -> Task<Result<ProjectTransaction>>;
15358}
15359
15360impl CodeActionProvider for Entity<Project> {
15361 fn id(&self) -> Arc<str> {
15362 "project".into()
15363 }
15364
15365 fn code_actions(
15366 &self,
15367 buffer: &Entity<Buffer>,
15368 range: Range<text::Anchor>,
15369 _window: &mut Window,
15370 cx: &mut App,
15371 ) -> Task<Result<Vec<CodeAction>>> {
15372 self.update(cx, |project, cx| {
15373 project.code_actions(buffer, range, None, cx)
15374 })
15375 }
15376
15377 fn apply_code_action(
15378 &self,
15379 buffer_handle: Entity<Buffer>,
15380 action: CodeAction,
15381 _excerpt_id: ExcerptId,
15382 push_to_history: bool,
15383 _window: &mut Window,
15384 cx: &mut App,
15385 ) -> Task<Result<ProjectTransaction>> {
15386 self.update(cx, |project, cx| {
15387 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15388 })
15389 }
15390}
15391
15392fn snippet_completions(
15393 project: &Project,
15394 buffer: &Entity<Buffer>,
15395 buffer_position: text::Anchor,
15396 cx: &mut App,
15397) -> Task<Result<Vec<Completion>>> {
15398 let language = buffer.read(cx).language_at(buffer_position);
15399 let language_name = language.as_ref().map(|language| language.lsp_id());
15400 let snippet_store = project.snippets().read(cx);
15401 let snippets = snippet_store.snippets_for(language_name, cx);
15402
15403 if snippets.is_empty() {
15404 return Task::ready(Ok(vec![]));
15405 }
15406 let snapshot = buffer.read(cx).text_snapshot();
15407 let chars: String = snapshot
15408 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15409 .collect();
15410
15411 let scope = language.map(|language| language.default_scope());
15412 let executor = cx.background_executor().clone();
15413
15414 cx.background_executor().spawn(async move {
15415 let classifier = CharClassifier::new(scope).for_completion(true);
15416 let mut last_word = chars
15417 .chars()
15418 .take_while(|c| classifier.is_word(*c))
15419 .collect::<String>();
15420 last_word = last_word.chars().rev().collect();
15421
15422 if last_word.is_empty() {
15423 return Ok(vec![]);
15424 }
15425
15426 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15427 let to_lsp = |point: &text::Anchor| {
15428 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15429 point_to_lsp(end)
15430 };
15431 let lsp_end = to_lsp(&buffer_position);
15432
15433 let candidates = snippets
15434 .iter()
15435 .enumerate()
15436 .flat_map(|(ix, snippet)| {
15437 snippet
15438 .prefix
15439 .iter()
15440 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15441 })
15442 .collect::<Vec<StringMatchCandidate>>();
15443
15444 let mut matches = fuzzy::match_strings(
15445 &candidates,
15446 &last_word,
15447 last_word.chars().any(|c| c.is_uppercase()),
15448 100,
15449 &Default::default(),
15450 executor,
15451 )
15452 .await;
15453
15454 // Remove all candidates where the query's start does not match the start of any word in the candidate
15455 if let Some(query_start) = last_word.chars().next() {
15456 matches.retain(|string_match| {
15457 split_words(&string_match.string).any(|word| {
15458 // Check that the first codepoint of the word as lowercase matches the first
15459 // codepoint of the query as lowercase
15460 word.chars()
15461 .flat_map(|codepoint| codepoint.to_lowercase())
15462 .zip(query_start.to_lowercase())
15463 .all(|(word_cp, query_cp)| word_cp == query_cp)
15464 })
15465 });
15466 }
15467
15468 let matched_strings = matches
15469 .into_iter()
15470 .map(|m| m.string)
15471 .collect::<HashSet<_>>();
15472
15473 let result: Vec<Completion> = snippets
15474 .into_iter()
15475 .filter_map(|snippet| {
15476 let matching_prefix = snippet
15477 .prefix
15478 .iter()
15479 .find(|prefix| matched_strings.contains(*prefix))?;
15480 let start = as_offset - last_word.len();
15481 let start = snapshot.anchor_before(start);
15482 let range = start..buffer_position;
15483 let lsp_start = to_lsp(&start);
15484 let lsp_range = lsp::Range {
15485 start: lsp_start,
15486 end: lsp_end,
15487 };
15488 Some(Completion {
15489 old_range: range,
15490 new_text: snippet.body.clone(),
15491 resolved: false,
15492 label: CodeLabel {
15493 text: matching_prefix.clone(),
15494 runs: vec![],
15495 filter_range: 0..matching_prefix.len(),
15496 },
15497 server_id: LanguageServerId(usize::MAX),
15498 documentation: snippet
15499 .description
15500 .clone()
15501 .map(CompletionDocumentation::SingleLine),
15502 lsp_completion: lsp::CompletionItem {
15503 label: snippet.prefix.first().unwrap().clone(),
15504 kind: Some(CompletionItemKind::SNIPPET),
15505 label_details: snippet.description.as_ref().map(|description| {
15506 lsp::CompletionItemLabelDetails {
15507 detail: Some(description.clone()),
15508 description: None,
15509 }
15510 }),
15511 insert_text_format: Some(InsertTextFormat::SNIPPET),
15512 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15513 lsp::InsertReplaceEdit {
15514 new_text: snippet.body.clone(),
15515 insert: lsp_range,
15516 replace: lsp_range,
15517 },
15518 )),
15519 filter_text: Some(snippet.body.clone()),
15520 sort_text: Some(char::MAX.to_string()),
15521 ..Default::default()
15522 },
15523 confirm: None,
15524 })
15525 })
15526 .collect();
15527
15528 Ok(result)
15529 })
15530}
15531
15532impl CompletionProvider for Entity<Project> {
15533 fn completions(
15534 &self,
15535 buffer: &Entity<Buffer>,
15536 buffer_position: text::Anchor,
15537 options: CompletionContext,
15538 _window: &mut Window,
15539 cx: &mut Context<Editor>,
15540 ) -> Task<Result<Vec<Completion>>> {
15541 self.update(cx, |project, cx| {
15542 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15543 let project_completions = project.completions(buffer, buffer_position, options, cx);
15544 cx.background_executor().spawn(async move {
15545 let mut completions = project_completions.await?;
15546 let snippets_completions = snippets.await?;
15547 completions.extend(snippets_completions);
15548 Ok(completions)
15549 })
15550 })
15551 }
15552
15553 fn resolve_completions(
15554 &self,
15555 buffer: Entity<Buffer>,
15556 completion_indices: Vec<usize>,
15557 completions: Rc<RefCell<Box<[Completion]>>>,
15558 cx: &mut Context<Editor>,
15559 ) -> Task<Result<bool>> {
15560 self.update(cx, |project, cx| {
15561 project.lsp_store().update(cx, |lsp_store, cx| {
15562 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15563 })
15564 })
15565 }
15566
15567 fn apply_additional_edits_for_completion(
15568 &self,
15569 buffer: Entity<Buffer>,
15570 completions: Rc<RefCell<Box<[Completion]>>>,
15571 completion_index: usize,
15572 push_to_history: bool,
15573 cx: &mut Context<Editor>,
15574 ) -> Task<Result<Option<language::Transaction>>> {
15575 self.update(cx, |project, cx| {
15576 project.lsp_store().update(cx, |lsp_store, cx| {
15577 lsp_store.apply_additional_edits_for_completion(
15578 buffer,
15579 completions,
15580 completion_index,
15581 push_to_history,
15582 cx,
15583 )
15584 })
15585 })
15586 }
15587
15588 fn is_completion_trigger(
15589 &self,
15590 buffer: &Entity<Buffer>,
15591 position: language::Anchor,
15592 text: &str,
15593 trigger_in_words: bool,
15594 cx: &mut Context<Editor>,
15595 ) -> bool {
15596 let mut chars = text.chars();
15597 let char = if let Some(char) = chars.next() {
15598 char
15599 } else {
15600 return false;
15601 };
15602 if chars.next().is_some() {
15603 return false;
15604 }
15605
15606 let buffer = buffer.read(cx);
15607 let snapshot = buffer.snapshot();
15608 if !snapshot.settings_at(position, cx).show_completions_on_input {
15609 return false;
15610 }
15611 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15612 if trigger_in_words && classifier.is_word(char) {
15613 return true;
15614 }
15615
15616 buffer.completion_triggers().contains(text)
15617 }
15618}
15619
15620impl SemanticsProvider for Entity<Project> {
15621 fn hover(
15622 &self,
15623 buffer: &Entity<Buffer>,
15624 position: text::Anchor,
15625 cx: &mut App,
15626 ) -> Option<Task<Vec<project::Hover>>> {
15627 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15628 }
15629
15630 fn document_highlights(
15631 &self,
15632 buffer: &Entity<Buffer>,
15633 position: text::Anchor,
15634 cx: &mut App,
15635 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15636 Some(self.update(cx, |project, cx| {
15637 project.document_highlights(buffer, position, cx)
15638 }))
15639 }
15640
15641 fn definitions(
15642 &self,
15643 buffer: &Entity<Buffer>,
15644 position: text::Anchor,
15645 kind: GotoDefinitionKind,
15646 cx: &mut App,
15647 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15648 Some(self.update(cx, |project, cx| match kind {
15649 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15650 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15651 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15652 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15653 }))
15654 }
15655
15656 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15657 // TODO: make this work for remote projects
15658 self.update(cx, |this, cx| {
15659 buffer.update(cx, |buffer, cx| {
15660 this.any_language_server_supports_inlay_hints(buffer, cx)
15661 })
15662 })
15663 }
15664
15665 fn inlay_hints(
15666 &self,
15667 buffer_handle: Entity<Buffer>,
15668 range: Range<text::Anchor>,
15669 cx: &mut App,
15670 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15671 Some(self.update(cx, |project, cx| {
15672 project.inlay_hints(buffer_handle, range, cx)
15673 }))
15674 }
15675
15676 fn resolve_inlay_hint(
15677 &self,
15678 hint: InlayHint,
15679 buffer_handle: Entity<Buffer>,
15680 server_id: LanguageServerId,
15681 cx: &mut App,
15682 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15683 Some(self.update(cx, |project, cx| {
15684 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15685 }))
15686 }
15687
15688 fn range_for_rename(
15689 &self,
15690 buffer: &Entity<Buffer>,
15691 position: text::Anchor,
15692 cx: &mut App,
15693 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15694 Some(self.update(cx, |project, cx| {
15695 let buffer = buffer.clone();
15696 let task = project.prepare_rename(buffer.clone(), position, cx);
15697 cx.spawn(|_, mut cx| async move {
15698 Ok(match task.await? {
15699 PrepareRenameResponse::Success(range) => Some(range),
15700 PrepareRenameResponse::InvalidPosition => None,
15701 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15702 // Fallback on using TreeSitter info to determine identifier range
15703 buffer.update(&mut cx, |buffer, _| {
15704 let snapshot = buffer.snapshot();
15705 let (range, kind) = snapshot.surrounding_word(position);
15706 if kind != Some(CharKind::Word) {
15707 return None;
15708 }
15709 Some(
15710 snapshot.anchor_before(range.start)
15711 ..snapshot.anchor_after(range.end),
15712 )
15713 })?
15714 }
15715 })
15716 })
15717 }))
15718 }
15719
15720 fn perform_rename(
15721 &self,
15722 buffer: &Entity<Buffer>,
15723 position: text::Anchor,
15724 new_name: String,
15725 cx: &mut App,
15726 ) -> Option<Task<Result<ProjectTransaction>>> {
15727 Some(self.update(cx, |project, cx| {
15728 project.perform_rename(buffer.clone(), position, new_name, cx)
15729 }))
15730 }
15731}
15732
15733fn inlay_hint_settings(
15734 location: Anchor,
15735 snapshot: &MultiBufferSnapshot,
15736 cx: &mut Context<Editor>,
15737) -> InlayHintSettings {
15738 let file = snapshot.file_at(location);
15739 let language = snapshot.language_at(location).map(|l| l.name());
15740 language_settings(language, file, cx).inlay_hints
15741}
15742
15743fn consume_contiguous_rows(
15744 contiguous_row_selections: &mut Vec<Selection<Point>>,
15745 selection: &Selection<Point>,
15746 display_map: &DisplaySnapshot,
15747 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15748) -> (MultiBufferRow, MultiBufferRow) {
15749 contiguous_row_selections.push(selection.clone());
15750 let start_row = MultiBufferRow(selection.start.row);
15751 let mut end_row = ending_row(selection, display_map);
15752
15753 while let Some(next_selection) = selections.peek() {
15754 if next_selection.start.row <= end_row.0 {
15755 end_row = ending_row(next_selection, display_map);
15756 contiguous_row_selections.push(selections.next().unwrap().clone());
15757 } else {
15758 break;
15759 }
15760 }
15761 (start_row, end_row)
15762}
15763
15764fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15765 if next_selection.end.column > 0 || next_selection.is_empty() {
15766 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15767 } else {
15768 MultiBufferRow(next_selection.end.row)
15769 }
15770}
15771
15772impl EditorSnapshot {
15773 pub fn remote_selections_in_range<'a>(
15774 &'a self,
15775 range: &'a Range<Anchor>,
15776 collaboration_hub: &dyn CollaborationHub,
15777 cx: &'a App,
15778 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15779 let participant_names = collaboration_hub.user_names(cx);
15780 let participant_indices = collaboration_hub.user_participant_indices(cx);
15781 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15782 let collaborators_by_replica_id = collaborators_by_peer_id
15783 .iter()
15784 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15785 .collect::<HashMap<_, _>>();
15786 self.buffer_snapshot
15787 .selections_in_range(range, false)
15788 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15789 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15790 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15791 let user_name = participant_names.get(&collaborator.user_id).cloned();
15792 Some(RemoteSelection {
15793 replica_id,
15794 selection,
15795 cursor_shape,
15796 line_mode,
15797 participant_index,
15798 peer_id: collaborator.peer_id,
15799 user_name,
15800 })
15801 })
15802 }
15803
15804 pub fn hunks_for_ranges(
15805 &self,
15806 ranges: impl Iterator<Item = Range<Point>>,
15807 ) -> Vec<MultiBufferDiffHunk> {
15808 let mut hunks = Vec::new();
15809 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15810 HashMap::default();
15811 for query_range in ranges {
15812 let query_rows =
15813 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15814 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15815 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15816 ) {
15817 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15818 // when the caret is just above or just below the deleted hunk.
15819 let allow_adjacent = hunk.status().is_removed();
15820 let related_to_selection = if allow_adjacent {
15821 hunk.row_range.overlaps(&query_rows)
15822 || hunk.row_range.start == query_rows.end
15823 || hunk.row_range.end == query_rows.start
15824 } else {
15825 hunk.row_range.overlaps(&query_rows)
15826 };
15827 if related_to_selection {
15828 if !processed_buffer_rows
15829 .entry(hunk.buffer_id)
15830 .or_default()
15831 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15832 {
15833 continue;
15834 }
15835 hunks.push(hunk);
15836 }
15837 }
15838 }
15839
15840 hunks
15841 }
15842
15843 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15844 self.display_snapshot.buffer_snapshot.language_at(position)
15845 }
15846
15847 pub fn is_focused(&self) -> bool {
15848 self.is_focused
15849 }
15850
15851 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15852 self.placeholder_text.as_ref()
15853 }
15854
15855 pub fn scroll_position(&self) -> gpui::Point<f32> {
15856 self.scroll_anchor.scroll_position(&self.display_snapshot)
15857 }
15858
15859 fn gutter_dimensions(
15860 &self,
15861 font_id: FontId,
15862 font_size: Pixels,
15863 max_line_number_width: Pixels,
15864 cx: &App,
15865 ) -> Option<GutterDimensions> {
15866 if !self.show_gutter {
15867 return None;
15868 }
15869
15870 let descent = cx.text_system().descent(font_id, font_size);
15871 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15872 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15873
15874 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15875 matches!(
15876 ProjectSettings::get_global(cx).git.git_gutter,
15877 Some(GitGutterSetting::TrackedFiles)
15878 )
15879 });
15880 let gutter_settings = EditorSettings::get_global(cx).gutter;
15881 let show_line_numbers = self
15882 .show_line_numbers
15883 .unwrap_or(gutter_settings.line_numbers);
15884 let line_gutter_width = if show_line_numbers {
15885 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15886 let min_width_for_number_on_gutter = em_advance * 4.0;
15887 max_line_number_width.max(min_width_for_number_on_gutter)
15888 } else {
15889 0.0.into()
15890 };
15891
15892 let show_code_actions = self
15893 .show_code_actions
15894 .unwrap_or(gutter_settings.code_actions);
15895
15896 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15897
15898 let git_blame_entries_width =
15899 self.git_blame_gutter_max_author_length
15900 .map(|max_author_length| {
15901 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15902
15903 /// The number of characters to dedicate to gaps and margins.
15904 const SPACING_WIDTH: usize = 4;
15905
15906 let max_char_count = max_author_length
15907 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15908 + ::git::SHORT_SHA_LENGTH
15909 + MAX_RELATIVE_TIMESTAMP.len()
15910 + SPACING_WIDTH;
15911
15912 em_advance * max_char_count
15913 });
15914
15915 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15916 left_padding += if show_code_actions || show_runnables {
15917 em_width * 3.0
15918 } else if show_git_gutter && show_line_numbers {
15919 em_width * 2.0
15920 } else if show_git_gutter || show_line_numbers {
15921 em_width
15922 } else {
15923 px(0.)
15924 };
15925
15926 let right_padding = if gutter_settings.folds && show_line_numbers {
15927 em_width * 4.0
15928 } else if gutter_settings.folds {
15929 em_width * 3.0
15930 } else if show_line_numbers {
15931 em_width
15932 } else {
15933 px(0.)
15934 };
15935
15936 Some(GutterDimensions {
15937 left_padding,
15938 right_padding,
15939 width: line_gutter_width + left_padding + right_padding,
15940 margin: -descent,
15941 git_blame_entries_width,
15942 })
15943 }
15944
15945 pub fn render_crease_toggle(
15946 &self,
15947 buffer_row: MultiBufferRow,
15948 row_contains_cursor: bool,
15949 editor: Entity<Editor>,
15950 window: &mut Window,
15951 cx: &mut App,
15952 ) -> Option<AnyElement> {
15953 let folded = self.is_line_folded(buffer_row);
15954 let mut is_foldable = false;
15955
15956 if let Some(crease) = self
15957 .crease_snapshot
15958 .query_row(buffer_row, &self.buffer_snapshot)
15959 {
15960 is_foldable = true;
15961 match crease {
15962 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15963 if let Some(render_toggle) = render_toggle {
15964 let toggle_callback =
15965 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15966 if folded {
15967 editor.update(cx, |editor, cx| {
15968 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15969 });
15970 } else {
15971 editor.update(cx, |editor, cx| {
15972 editor.unfold_at(
15973 &crate::UnfoldAt { buffer_row },
15974 window,
15975 cx,
15976 )
15977 });
15978 }
15979 });
15980 return Some((render_toggle)(
15981 buffer_row,
15982 folded,
15983 toggle_callback,
15984 window,
15985 cx,
15986 ));
15987 }
15988 }
15989 }
15990 }
15991
15992 is_foldable |= self.starts_indent(buffer_row);
15993
15994 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15995 Some(
15996 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15997 .toggle_state(folded)
15998 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15999 if folded {
16000 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16001 } else {
16002 this.fold_at(&FoldAt { buffer_row }, window, cx);
16003 }
16004 }))
16005 .into_any_element(),
16006 )
16007 } else {
16008 None
16009 }
16010 }
16011
16012 pub fn render_crease_trailer(
16013 &self,
16014 buffer_row: MultiBufferRow,
16015 window: &mut Window,
16016 cx: &mut App,
16017 ) -> Option<AnyElement> {
16018 let folded = self.is_line_folded(buffer_row);
16019 if let Crease::Inline { render_trailer, .. } = self
16020 .crease_snapshot
16021 .query_row(buffer_row, &self.buffer_snapshot)?
16022 {
16023 let render_trailer = render_trailer.as_ref()?;
16024 Some(render_trailer(buffer_row, folded, window, cx))
16025 } else {
16026 None
16027 }
16028 }
16029}
16030
16031impl Deref for EditorSnapshot {
16032 type Target = DisplaySnapshot;
16033
16034 fn deref(&self) -> &Self::Target {
16035 &self.display_snapshot
16036 }
16037}
16038
16039#[derive(Clone, Debug, PartialEq, Eq)]
16040pub enum EditorEvent {
16041 InputIgnored {
16042 text: Arc<str>,
16043 },
16044 InputHandled {
16045 utf16_range_to_replace: Option<Range<isize>>,
16046 text: Arc<str>,
16047 },
16048 ExcerptsAdded {
16049 buffer: Entity<Buffer>,
16050 predecessor: ExcerptId,
16051 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16052 },
16053 ExcerptsRemoved {
16054 ids: Vec<ExcerptId>,
16055 },
16056 BufferFoldToggled {
16057 ids: Vec<ExcerptId>,
16058 folded: bool,
16059 },
16060 ExcerptsEdited {
16061 ids: Vec<ExcerptId>,
16062 },
16063 ExcerptsExpanded {
16064 ids: Vec<ExcerptId>,
16065 },
16066 BufferEdited,
16067 Edited {
16068 transaction_id: clock::Lamport,
16069 },
16070 Reparsed(BufferId),
16071 Focused,
16072 FocusedIn,
16073 Blurred,
16074 DirtyChanged,
16075 Saved,
16076 TitleChanged,
16077 DiffBaseChanged,
16078 SelectionsChanged {
16079 local: bool,
16080 },
16081 ScrollPositionChanged {
16082 local: bool,
16083 autoscroll: bool,
16084 },
16085 Closed,
16086 TransactionUndone {
16087 transaction_id: clock::Lamport,
16088 },
16089 TransactionBegun {
16090 transaction_id: clock::Lamport,
16091 },
16092 Reloaded,
16093 CursorShapeChanged,
16094}
16095
16096impl EventEmitter<EditorEvent> for Editor {}
16097
16098impl Focusable for Editor {
16099 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16100 self.focus_handle.clone()
16101 }
16102}
16103
16104impl Render for Editor {
16105 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16106 let settings = ThemeSettings::get_global(cx);
16107
16108 let mut text_style = match self.mode {
16109 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16110 color: cx.theme().colors().editor_foreground,
16111 font_family: settings.ui_font.family.clone(),
16112 font_features: settings.ui_font.features.clone(),
16113 font_fallbacks: settings.ui_font.fallbacks.clone(),
16114 font_size: rems(0.875).into(),
16115 font_weight: settings.ui_font.weight,
16116 line_height: relative(settings.buffer_line_height.value()),
16117 ..Default::default()
16118 },
16119 EditorMode::Full => TextStyle {
16120 color: cx.theme().colors().editor_foreground,
16121 font_family: settings.buffer_font.family.clone(),
16122 font_features: settings.buffer_font.features.clone(),
16123 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16124 font_size: settings.buffer_font_size(cx).into(),
16125 font_weight: settings.buffer_font.weight,
16126 line_height: relative(settings.buffer_line_height.value()),
16127 ..Default::default()
16128 },
16129 };
16130 if let Some(text_style_refinement) = &self.text_style_refinement {
16131 text_style.refine(text_style_refinement)
16132 }
16133
16134 let background = match self.mode {
16135 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16136 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16137 EditorMode::Full => cx.theme().colors().editor_background,
16138 };
16139
16140 EditorElement::new(
16141 &cx.entity(),
16142 EditorStyle {
16143 background,
16144 local_player: cx.theme().players().local(),
16145 text: text_style,
16146 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16147 syntax: cx.theme().syntax().clone(),
16148 status: cx.theme().status().clone(),
16149 inlay_hints_style: make_inlay_hints_style(cx),
16150 inline_completion_styles: make_suggestion_styles(cx),
16151 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16152 },
16153 )
16154 }
16155}
16156
16157impl EntityInputHandler for Editor {
16158 fn text_for_range(
16159 &mut self,
16160 range_utf16: Range<usize>,
16161 adjusted_range: &mut Option<Range<usize>>,
16162 _: &mut Window,
16163 cx: &mut Context<Self>,
16164 ) -> Option<String> {
16165 let snapshot = self.buffer.read(cx).read(cx);
16166 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16167 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16168 if (start.0..end.0) != range_utf16 {
16169 adjusted_range.replace(start.0..end.0);
16170 }
16171 Some(snapshot.text_for_range(start..end).collect())
16172 }
16173
16174 fn selected_text_range(
16175 &mut self,
16176 ignore_disabled_input: bool,
16177 _: &mut Window,
16178 cx: &mut Context<Self>,
16179 ) -> Option<UTF16Selection> {
16180 // Prevent the IME menu from appearing when holding down an alphabetic key
16181 // while input is disabled.
16182 if !ignore_disabled_input && !self.input_enabled {
16183 return None;
16184 }
16185
16186 let selection = self.selections.newest::<OffsetUtf16>(cx);
16187 let range = selection.range();
16188
16189 Some(UTF16Selection {
16190 range: range.start.0..range.end.0,
16191 reversed: selection.reversed,
16192 })
16193 }
16194
16195 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16196 let snapshot = self.buffer.read(cx).read(cx);
16197 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16198 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16199 }
16200
16201 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16202 self.clear_highlights::<InputComposition>(cx);
16203 self.ime_transaction.take();
16204 }
16205
16206 fn replace_text_in_range(
16207 &mut self,
16208 range_utf16: Option<Range<usize>>,
16209 text: &str,
16210 window: &mut Window,
16211 cx: &mut Context<Self>,
16212 ) {
16213 if !self.input_enabled {
16214 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16215 return;
16216 }
16217
16218 self.transact(window, cx, |this, window, cx| {
16219 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16220 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16221 Some(this.selection_replacement_ranges(range_utf16, cx))
16222 } else {
16223 this.marked_text_ranges(cx)
16224 };
16225
16226 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16227 let newest_selection_id = this.selections.newest_anchor().id;
16228 this.selections
16229 .all::<OffsetUtf16>(cx)
16230 .iter()
16231 .zip(ranges_to_replace.iter())
16232 .find_map(|(selection, range)| {
16233 if selection.id == newest_selection_id {
16234 Some(
16235 (range.start.0 as isize - selection.head().0 as isize)
16236 ..(range.end.0 as isize - selection.head().0 as isize),
16237 )
16238 } else {
16239 None
16240 }
16241 })
16242 });
16243
16244 cx.emit(EditorEvent::InputHandled {
16245 utf16_range_to_replace: range_to_replace,
16246 text: text.into(),
16247 });
16248
16249 if let Some(new_selected_ranges) = new_selected_ranges {
16250 this.change_selections(None, window, cx, |selections| {
16251 selections.select_ranges(new_selected_ranges)
16252 });
16253 this.backspace(&Default::default(), window, cx);
16254 }
16255
16256 this.handle_input(text, window, cx);
16257 });
16258
16259 if let Some(transaction) = self.ime_transaction {
16260 self.buffer.update(cx, |buffer, cx| {
16261 buffer.group_until_transaction(transaction, cx);
16262 });
16263 }
16264
16265 self.unmark_text(window, cx);
16266 }
16267
16268 fn replace_and_mark_text_in_range(
16269 &mut self,
16270 range_utf16: Option<Range<usize>>,
16271 text: &str,
16272 new_selected_range_utf16: Option<Range<usize>>,
16273 window: &mut Window,
16274 cx: &mut Context<Self>,
16275 ) {
16276 if !self.input_enabled {
16277 return;
16278 }
16279
16280 let transaction = self.transact(window, cx, |this, window, cx| {
16281 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16282 let snapshot = this.buffer.read(cx).read(cx);
16283 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16284 for marked_range in &mut marked_ranges {
16285 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16286 marked_range.start.0 += relative_range_utf16.start;
16287 marked_range.start =
16288 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16289 marked_range.end =
16290 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16291 }
16292 }
16293 Some(marked_ranges)
16294 } else if let Some(range_utf16) = range_utf16 {
16295 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16296 Some(this.selection_replacement_ranges(range_utf16, cx))
16297 } else {
16298 None
16299 };
16300
16301 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16302 let newest_selection_id = this.selections.newest_anchor().id;
16303 this.selections
16304 .all::<OffsetUtf16>(cx)
16305 .iter()
16306 .zip(ranges_to_replace.iter())
16307 .find_map(|(selection, range)| {
16308 if selection.id == newest_selection_id {
16309 Some(
16310 (range.start.0 as isize - selection.head().0 as isize)
16311 ..(range.end.0 as isize - selection.head().0 as isize),
16312 )
16313 } else {
16314 None
16315 }
16316 })
16317 });
16318
16319 cx.emit(EditorEvent::InputHandled {
16320 utf16_range_to_replace: range_to_replace,
16321 text: text.into(),
16322 });
16323
16324 if let Some(ranges) = ranges_to_replace {
16325 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16326 }
16327
16328 let marked_ranges = {
16329 let snapshot = this.buffer.read(cx).read(cx);
16330 this.selections
16331 .disjoint_anchors()
16332 .iter()
16333 .map(|selection| {
16334 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16335 })
16336 .collect::<Vec<_>>()
16337 };
16338
16339 if text.is_empty() {
16340 this.unmark_text(window, cx);
16341 } else {
16342 this.highlight_text::<InputComposition>(
16343 marked_ranges.clone(),
16344 HighlightStyle {
16345 underline: Some(UnderlineStyle {
16346 thickness: px(1.),
16347 color: None,
16348 wavy: false,
16349 }),
16350 ..Default::default()
16351 },
16352 cx,
16353 );
16354 }
16355
16356 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16357 let use_autoclose = this.use_autoclose;
16358 let use_auto_surround = this.use_auto_surround;
16359 this.set_use_autoclose(false);
16360 this.set_use_auto_surround(false);
16361 this.handle_input(text, window, cx);
16362 this.set_use_autoclose(use_autoclose);
16363 this.set_use_auto_surround(use_auto_surround);
16364
16365 if let Some(new_selected_range) = new_selected_range_utf16 {
16366 let snapshot = this.buffer.read(cx).read(cx);
16367 let new_selected_ranges = marked_ranges
16368 .into_iter()
16369 .map(|marked_range| {
16370 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16371 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16372 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16373 snapshot.clip_offset_utf16(new_start, Bias::Left)
16374 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16375 })
16376 .collect::<Vec<_>>();
16377
16378 drop(snapshot);
16379 this.change_selections(None, window, cx, |selections| {
16380 selections.select_ranges(new_selected_ranges)
16381 });
16382 }
16383 });
16384
16385 self.ime_transaction = self.ime_transaction.or(transaction);
16386 if let Some(transaction) = self.ime_transaction {
16387 self.buffer.update(cx, |buffer, cx| {
16388 buffer.group_until_transaction(transaction, cx);
16389 });
16390 }
16391
16392 if self.text_highlights::<InputComposition>(cx).is_none() {
16393 self.ime_transaction.take();
16394 }
16395 }
16396
16397 fn bounds_for_range(
16398 &mut self,
16399 range_utf16: Range<usize>,
16400 element_bounds: gpui::Bounds<Pixels>,
16401 window: &mut Window,
16402 cx: &mut Context<Self>,
16403 ) -> Option<gpui::Bounds<Pixels>> {
16404 let text_layout_details = self.text_layout_details(window);
16405 let gpui::Size {
16406 width: em_width,
16407 height: line_height,
16408 } = self.character_size(window);
16409
16410 let snapshot = self.snapshot(window, cx);
16411 let scroll_position = snapshot.scroll_position();
16412 let scroll_left = scroll_position.x * em_width;
16413
16414 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16415 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16416 + self.gutter_dimensions.width
16417 + self.gutter_dimensions.margin;
16418 let y = line_height * (start.row().as_f32() - scroll_position.y);
16419
16420 Some(Bounds {
16421 origin: element_bounds.origin + point(x, y),
16422 size: size(em_width, line_height),
16423 })
16424 }
16425
16426 fn character_index_for_point(
16427 &mut self,
16428 point: gpui::Point<Pixels>,
16429 _window: &mut Window,
16430 _cx: &mut Context<Self>,
16431 ) -> Option<usize> {
16432 let position_map = self.last_position_map.as_ref()?;
16433 if !position_map.text_hitbox.contains(&point) {
16434 return None;
16435 }
16436 let display_point = position_map.point_for_position(point).previous_valid;
16437 let anchor = position_map
16438 .snapshot
16439 .display_point_to_anchor(display_point, Bias::Left);
16440 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16441 Some(utf16_offset.0)
16442 }
16443}
16444
16445trait SelectionExt {
16446 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16447 fn spanned_rows(
16448 &self,
16449 include_end_if_at_line_start: bool,
16450 map: &DisplaySnapshot,
16451 ) -> Range<MultiBufferRow>;
16452}
16453
16454impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16455 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16456 let start = self
16457 .start
16458 .to_point(&map.buffer_snapshot)
16459 .to_display_point(map);
16460 let end = self
16461 .end
16462 .to_point(&map.buffer_snapshot)
16463 .to_display_point(map);
16464 if self.reversed {
16465 end..start
16466 } else {
16467 start..end
16468 }
16469 }
16470
16471 fn spanned_rows(
16472 &self,
16473 include_end_if_at_line_start: bool,
16474 map: &DisplaySnapshot,
16475 ) -> Range<MultiBufferRow> {
16476 let start = self.start.to_point(&map.buffer_snapshot);
16477 let mut end = self.end.to_point(&map.buffer_snapshot);
16478 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16479 end.row -= 1;
16480 }
16481
16482 let buffer_start = map.prev_line_boundary(start).0;
16483 let buffer_end = map.next_line_boundary(end).0;
16484 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16485 }
16486}
16487
16488impl<T: InvalidationRegion> InvalidationStack<T> {
16489 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16490 where
16491 S: Clone + ToOffset,
16492 {
16493 while let Some(region) = self.last() {
16494 let all_selections_inside_invalidation_ranges =
16495 if selections.len() == region.ranges().len() {
16496 selections
16497 .iter()
16498 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16499 .all(|(selection, invalidation_range)| {
16500 let head = selection.head().to_offset(buffer);
16501 invalidation_range.start <= head && invalidation_range.end >= head
16502 })
16503 } else {
16504 false
16505 };
16506
16507 if all_selections_inside_invalidation_ranges {
16508 break;
16509 } else {
16510 self.pop();
16511 }
16512 }
16513 }
16514}
16515
16516impl<T> Default for InvalidationStack<T> {
16517 fn default() -> Self {
16518 Self(Default::default())
16519 }
16520}
16521
16522impl<T> Deref for InvalidationStack<T> {
16523 type Target = Vec<T>;
16524
16525 fn deref(&self) -> &Self::Target {
16526 &self.0
16527 }
16528}
16529
16530impl<T> DerefMut for InvalidationStack<T> {
16531 fn deref_mut(&mut self) -> &mut Self::Target {
16532 &mut self.0
16533 }
16534}
16535
16536impl InvalidationRegion for SnippetState {
16537 fn ranges(&self) -> &[Range<Anchor>] {
16538 &self.ranges[self.active_index]
16539 }
16540}
16541
16542pub fn diagnostic_block_renderer(
16543 diagnostic: Diagnostic,
16544 max_message_rows: Option<u8>,
16545 allow_closing: bool,
16546 _is_valid: bool,
16547) -> RenderBlock {
16548 let (text_without_backticks, code_ranges) =
16549 highlight_diagnostic_message(&diagnostic, max_message_rows);
16550
16551 Arc::new(move |cx: &mut BlockContext| {
16552 let group_id: SharedString = cx.block_id.to_string().into();
16553
16554 let mut text_style = cx.window.text_style().clone();
16555 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16556 let theme_settings = ThemeSettings::get_global(cx);
16557 text_style.font_family = theme_settings.buffer_font.family.clone();
16558 text_style.font_style = theme_settings.buffer_font.style;
16559 text_style.font_features = theme_settings.buffer_font.features.clone();
16560 text_style.font_weight = theme_settings.buffer_font.weight;
16561
16562 let multi_line_diagnostic = diagnostic.message.contains('\n');
16563
16564 let buttons = |diagnostic: &Diagnostic| {
16565 if multi_line_diagnostic {
16566 v_flex()
16567 } else {
16568 h_flex()
16569 }
16570 .when(allow_closing, |div| {
16571 div.children(diagnostic.is_primary.then(|| {
16572 IconButton::new("close-block", IconName::XCircle)
16573 .icon_color(Color::Muted)
16574 .size(ButtonSize::Compact)
16575 .style(ButtonStyle::Transparent)
16576 .visible_on_hover(group_id.clone())
16577 .on_click(move |_click, window, cx| {
16578 window.dispatch_action(Box::new(Cancel), cx)
16579 })
16580 .tooltip(|window, cx| {
16581 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16582 })
16583 }))
16584 })
16585 .child(
16586 IconButton::new("copy-block", IconName::Copy)
16587 .icon_color(Color::Muted)
16588 .size(ButtonSize::Compact)
16589 .style(ButtonStyle::Transparent)
16590 .visible_on_hover(group_id.clone())
16591 .on_click({
16592 let message = diagnostic.message.clone();
16593 move |_click, _, cx| {
16594 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16595 }
16596 })
16597 .tooltip(Tooltip::text("Copy diagnostic message")),
16598 )
16599 };
16600
16601 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16602 AvailableSpace::min_size(),
16603 cx.window,
16604 cx.app,
16605 );
16606
16607 h_flex()
16608 .id(cx.block_id)
16609 .group(group_id.clone())
16610 .relative()
16611 .size_full()
16612 .block_mouse_down()
16613 .pl(cx.gutter_dimensions.width)
16614 .w(cx.max_width - cx.gutter_dimensions.full_width())
16615 .child(
16616 div()
16617 .flex()
16618 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16619 .flex_shrink(),
16620 )
16621 .child(buttons(&diagnostic))
16622 .child(div().flex().flex_shrink_0().child(
16623 StyledText::new(text_without_backticks.clone()).with_highlights(
16624 &text_style,
16625 code_ranges.iter().map(|range| {
16626 (
16627 range.clone(),
16628 HighlightStyle {
16629 font_weight: Some(FontWeight::BOLD),
16630 ..Default::default()
16631 },
16632 )
16633 }),
16634 ),
16635 ))
16636 .into_any_element()
16637 })
16638}
16639
16640fn inline_completion_edit_text(
16641 current_snapshot: &BufferSnapshot,
16642 edits: &[(Range<Anchor>, String)],
16643 edit_preview: &EditPreview,
16644 include_deletions: bool,
16645 cx: &App,
16646) -> HighlightedText {
16647 let edits = edits
16648 .iter()
16649 .map(|(anchor, text)| {
16650 (
16651 anchor.start.text_anchor..anchor.end.text_anchor,
16652 text.clone(),
16653 )
16654 })
16655 .collect::<Vec<_>>();
16656
16657 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16658}
16659
16660pub fn highlight_diagnostic_message(
16661 diagnostic: &Diagnostic,
16662 mut max_message_rows: Option<u8>,
16663) -> (SharedString, Vec<Range<usize>>) {
16664 let mut text_without_backticks = String::new();
16665 let mut code_ranges = Vec::new();
16666
16667 if let Some(source) = &diagnostic.source {
16668 text_without_backticks.push_str(source);
16669 code_ranges.push(0..source.len());
16670 text_without_backticks.push_str(": ");
16671 }
16672
16673 let mut prev_offset = 0;
16674 let mut in_code_block = false;
16675 let has_row_limit = max_message_rows.is_some();
16676 let mut newline_indices = diagnostic
16677 .message
16678 .match_indices('\n')
16679 .filter(|_| has_row_limit)
16680 .map(|(ix, _)| ix)
16681 .fuse()
16682 .peekable();
16683
16684 for (quote_ix, _) in diagnostic
16685 .message
16686 .match_indices('`')
16687 .chain([(diagnostic.message.len(), "")])
16688 {
16689 let mut first_newline_ix = None;
16690 let mut last_newline_ix = None;
16691 while let Some(newline_ix) = newline_indices.peek() {
16692 if *newline_ix < quote_ix {
16693 if first_newline_ix.is_none() {
16694 first_newline_ix = Some(*newline_ix);
16695 }
16696 last_newline_ix = Some(*newline_ix);
16697
16698 if let Some(rows_left) = &mut max_message_rows {
16699 if *rows_left == 0 {
16700 break;
16701 } else {
16702 *rows_left -= 1;
16703 }
16704 }
16705 let _ = newline_indices.next();
16706 } else {
16707 break;
16708 }
16709 }
16710 let prev_len = text_without_backticks.len();
16711 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16712 text_without_backticks.push_str(new_text);
16713 if in_code_block {
16714 code_ranges.push(prev_len..text_without_backticks.len());
16715 }
16716 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16717 in_code_block = !in_code_block;
16718 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16719 text_without_backticks.push_str("...");
16720 break;
16721 }
16722 }
16723
16724 (text_without_backticks.into(), code_ranges)
16725}
16726
16727fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16728 match severity {
16729 DiagnosticSeverity::ERROR => colors.error,
16730 DiagnosticSeverity::WARNING => colors.warning,
16731 DiagnosticSeverity::INFORMATION => colors.info,
16732 DiagnosticSeverity::HINT => colors.info,
16733 _ => colors.ignored,
16734 }
16735}
16736
16737pub fn styled_runs_for_code_label<'a>(
16738 label: &'a CodeLabel,
16739 syntax_theme: &'a theme::SyntaxTheme,
16740) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16741 let fade_out = HighlightStyle {
16742 fade_out: Some(0.35),
16743 ..Default::default()
16744 };
16745
16746 let mut prev_end = label.filter_range.end;
16747 label
16748 .runs
16749 .iter()
16750 .enumerate()
16751 .flat_map(move |(ix, (range, highlight_id))| {
16752 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16753 style
16754 } else {
16755 return Default::default();
16756 };
16757 let mut muted_style = style;
16758 muted_style.highlight(fade_out);
16759
16760 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16761 if range.start >= label.filter_range.end {
16762 if range.start > prev_end {
16763 runs.push((prev_end..range.start, fade_out));
16764 }
16765 runs.push((range.clone(), muted_style));
16766 } else if range.end <= label.filter_range.end {
16767 runs.push((range.clone(), style));
16768 } else {
16769 runs.push((range.start..label.filter_range.end, style));
16770 runs.push((label.filter_range.end..range.end, muted_style));
16771 }
16772 prev_end = cmp::max(prev_end, range.end);
16773
16774 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16775 runs.push((prev_end..label.text.len(), fade_out));
16776 }
16777
16778 runs
16779 })
16780}
16781
16782pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16783 let mut prev_index = 0;
16784 let mut prev_codepoint: Option<char> = None;
16785 text.char_indices()
16786 .chain([(text.len(), '\0')])
16787 .filter_map(move |(index, codepoint)| {
16788 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16789 let is_boundary = index == text.len()
16790 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16791 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16792 if is_boundary {
16793 let chunk = &text[prev_index..index];
16794 prev_index = index;
16795 Some(chunk)
16796 } else {
16797 None
16798 }
16799 })
16800}
16801
16802pub trait RangeToAnchorExt: Sized {
16803 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16804
16805 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16806 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16807 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16808 }
16809}
16810
16811impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16812 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16813 let start_offset = self.start.to_offset(snapshot);
16814 let end_offset = self.end.to_offset(snapshot);
16815 if start_offset == end_offset {
16816 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16817 } else {
16818 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16819 }
16820 }
16821}
16822
16823pub trait RowExt {
16824 fn as_f32(&self) -> f32;
16825
16826 fn next_row(&self) -> Self;
16827
16828 fn previous_row(&self) -> Self;
16829
16830 fn minus(&self, other: Self) -> u32;
16831}
16832
16833impl RowExt for DisplayRow {
16834 fn as_f32(&self) -> f32 {
16835 self.0 as f32
16836 }
16837
16838 fn next_row(&self) -> Self {
16839 Self(self.0 + 1)
16840 }
16841
16842 fn previous_row(&self) -> Self {
16843 Self(self.0.saturating_sub(1))
16844 }
16845
16846 fn minus(&self, other: Self) -> u32 {
16847 self.0 - other.0
16848 }
16849}
16850
16851impl RowExt for MultiBufferRow {
16852 fn as_f32(&self) -> f32 {
16853 self.0 as f32
16854 }
16855
16856 fn next_row(&self) -> Self {
16857 Self(self.0 + 1)
16858 }
16859
16860 fn previous_row(&self) -> Self {
16861 Self(self.0.saturating_sub(1))
16862 }
16863
16864 fn minus(&self, other: Self) -> u32 {
16865 self.0 - other.0
16866 }
16867}
16868
16869trait RowRangeExt {
16870 type Row;
16871
16872 fn len(&self) -> usize;
16873
16874 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16875}
16876
16877impl RowRangeExt for Range<MultiBufferRow> {
16878 type Row = MultiBufferRow;
16879
16880 fn len(&self) -> usize {
16881 (self.end.0 - self.start.0) as usize
16882 }
16883
16884 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16885 (self.start.0..self.end.0).map(MultiBufferRow)
16886 }
16887}
16888
16889impl RowRangeExt for Range<DisplayRow> {
16890 type Row = DisplayRow;
16891
16892 fn len(&self) -> usize {
16893 (self.end.0 - self.start.0) as usize
16894 }
16895
16896 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16897 (self.start.0..self.end.0).map(DisplayRow)
16898 }
16899}
16900
16901/// If select range has more than one line, we
16902/// just point the cursor to range.start.
16903fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16904 if range.start.row == range.end.row {
16905 range
16906 } else {
16907 range.start..range.start
16908 }
16909}
16910pub struct KillRing(ClipboardItem);
16911impl Global for KillRing {}
16912
16913const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16914
16915fn all_edits_insertions_or_deletions(
16916 edits: &Vec<(Range<Anchor>, String)>,
16917 snapshot: &MultiBufferSnapshot,
16918) -> bool {
16919 let mut all_insertions = true;
16920 let mut all_deletions = true;
16921
16922 for (range, new_text) in edits.iter() {
16923 let range_is_empty = range.to_offset(&snapshot).is_empty();
16924 let text_is_empty = new_text.is_empty();
16925
16926 if range_is_empty != text_is_empty {
16927 if range_is_empty {
16928 all_deletions = false;
16929 } else {
16930 all_insertions = false;
16931 }
16932 } else {
16933 return false;
16934 }
16935
16936 if !all_insertions && !all_deletions {
16937 return false;
16938 }
16939 }
16940 all_insertions || all_deletions
16941}